Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Pasquale Andriani 2012-10-24 22:58:25 +02:00
commit dfbdc02ea4
1803 changed files with 84089 additions and 40609 deletions

View File

@ -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

View File

@ -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

View File

@ -24,7 +24,7 @@
<parent>
<groupId>org.jclouds</groupId>
<artifactId>jclouds-project</artifactId>
<version>1.5.0-SNAPSHOT</version>
<version>1.6.0-SNAPSHOT</version>
<relativePath>../project/pom.xml</relativePath>
</parent>
<artifactId>jclouds-all</artifactId>
@ -40,6 +40,11 @@
<artifactId>aws-cloudwatch</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.jclouds.provider</groupId>
<artifactId>aws-sqs</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>jclouds-allloadbalancer</artifactId>

View File

@ -24,7 +24,7 @@
<parent>
<groupId>org.jclouds</groupId>
<artifactId>jclouds-project</artifactId>
<version>1.5.0-SNAPSHOT</version>
<version>1.6.0-SNAPSHOT</version>
<relativePath>../project/pom.xml</relativePath>
</parent>
<artifactId>jclouds-allblobstore</artifactId>

View File

@ -24,7 +24,7 @@
<parent>
<groupId>org.jclouds</groupId>
<artifactId>jclouds-project</artifactId>
<version>1.5.0-SNAPSHOT</version>
<version>1.6.0-SNAPSHOT</version>
<relativePath>../project/pom.xml</relativePath>
</parent>
<artifactId>jclouds-allcompute</artifactId>

View File

@ -24,7 +24,7 @@
<parent>
<groupId>org.jclouds</groupId>
<artifactId>jclouds-project</artifactId>
<version>1.5.0-SNAPSHOT</version>
<version>1.6.0-SNAPSHOT</version>
<relativePath>../project/pom.xml</relativePath>
</parent>
<artifactId>jclouds-allloadbalancer</artifactId>

View File

@ -1,91 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to jclouds, Inc. (jclouds) under one or more
contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. jclouds licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.jclouds</groupId>
<artifactId>jclouds-project</artifactId>
<version>1.5.0-SNAPSHOT</version>
<relativePath>../project/pom.xml</relativePath>
</parent>
<artifactId>jclouds-antcontrib</artifactId>
<name>Ant-Contrib extensions</name>
<properties>
<jclouds.test.listener />
</properties>
<dependencies>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>jclouds-scriptbuilder</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>jclouds-compute</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
<version>1.7.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant-jsch</artifactId>
<version>1.7.1</version>
</dependency>
<dependency>
<groupId>org.jclouds.driver</groupId>
<artifactId>jclouds-jsch</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,183 +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.
-->
<project name="compute" default="dump" basedir="." xmlns:artifact="urn:maven-artifact-ant">
<property file="build.properties" />
<property name="jclouds.version" value="1.0-beta-9a" />
<property name="privatekeyfile" value="${user.home}/.ssh/id_rsa" />
<property name="publickeyfile" value="${user.home}/.ssh/id_rsa.pub" />
<mkdir dir="build" />
<get src="http://opensource.become.com/apache//maven/binaries/maven-ant-tasks-2.1.1.jar" dest="build/maven-ant-tasks.jar"/>
<input
message="Which provider would you like to use (aws-ec2, bluelock-vcdirector, cloudservers-uk, cloudservers-us, cloudsigma-zrh, eucalyptus-partnercloud-ec2, elastichosts-lon-b, elastichosts-lon-p, elastichosts-sat-p, gogrid, openhosting-east1, serverlove-z1-man, skalicloud-sdg-my, slicehost, trmk-ecloud, trmk-vcloudexpress)?"
validargs="aws-ec2,bluelock-vcdirector,cloudservers-uk,cloudservers-us,cloudsigma-zrh,eucalyptus-partnercloud-ec2,elastichosts-lon-b,elastichosts-lon-p,elastichosts-sat-p,gogrid,openhosting-east1,serverlove-z1-man,skalicloud-sdg-my,slicehost,trmk-ecloud,trmk-vcloudexpress"
addproperty="provider"
/>
<path id="maven-ant-tasks.classpath" path="build/maven-ant-tasks.jar" />
<typedef resource="org/apache/maven/artifact/ant/antlib.xml" uri="urn:maven-artifact-ant" classpathref="maven-ant-tasks.classpath" />
<artifact:localRepository id="local.repository" path="${user.home}/.m2/repository" />
<artifact:remoteRepository id="jclouds-snapshot.repository" url="https://oss.sonatype.org/content/repositories/snapshots" />
<artifact:dependencies pathId="jclouds.classpath">
<dependency groupId="org.jclouds" artifactId="jclouds-antcontrib" version="${jclouds.version}" />
<dependency groupId="org.jclouds.provider" artifactId="${provider}" version="${jclouds.version}" />
<localRepository refid="local.repository" />
<remoteRepository refid="jclouds-snapshot.repository" />
</artifact:dependencies>
<typedef name="compute" classname="org.jclouds.tools.ant.taskdefs.compute.ComputeTask" classpathref="jclouds.classpath" />
<input
message="What is your identity on ${provider}?"
addproperty="identity"
/>
<input
message="What is the credential for ${identity}?"
addproperty="credential"
/>
<property name="jclouds.compute.url" value="compute://${identity}:${credential}@${provider}" />
<target name="list" description="list the identity of all nodes">
<compute actions="list" provider="${jclouds.compute.url}" />
</target>
<target name="list-details" description="list the details of all nodes">
<compute actions="list-details" provider="${jclouds.compute.url}" />
</target>
<target name="list-images" description="list the images supported">
<compute actions="list-images" provider="${jclouds.compute.url}" />
</target>
<target name="list-hardwares" description="list the hardwares supported">
<compute actions="list-sizes" provider="${jclouds.compute.url}" />
</target>
<target name="list-locations" description="list the locations supported">
<compute actions="list-locations" provider="${jclouds.compute.url}" />
</target>
<target name="dump" description="list all information we can obtain about the cloud">
<compute actions="list-locations,list-sizes,list-images,list-details" provider="${jclouds.compute.url}" />
</target>
<target name="reboot" depends="reboot-id,reboot-group" />
<target name="reboot-id" description="reboot the node ${id}" unless="group">
<input
message="Which node do you wish to reboot"
addproperty="id"
/>
<compute actions="reboot" provider="${jclouds.compute.url}">
<nodes id="${id}" />
</compute>
</target>
<target name="reboot-group" description="reboot the nodes with group ${group}" unless="id" >
<input
message="Which group do you wish to reboot"
addproperty="group"
/>
<compute actions="reboot" provider="${jclouds.compute.url}">
<nodes group="${group}" />
</compute>
</target>
<target name="destroy" depends="destroy-id,destroy-group" />
<target name="destroy-id" description="destroy the node ${id}" unless="group">
<input
message="Which node do you wish to destroy"
addproperty="id"
/>
<compute actions="destroy" provider="${jclouds.compute.url}">
<nodes id="${id}" />
</compute>
</target>
<target name="destroy-group" description="destroy the nodes with group ${group}" unless="id" >
<input
message="Which group do you wish to destroy"
addproperty="group"
/>
<compute actions="destroy" provider="${jclouds.compute.url}">
<nodes group="${group}" />
</compute>
</target>
<target name="get" depends="get-group,get-id" />
<target name="get-id" description="get the node ${id}" unless="group">
<input
message="Which node do you wish to get"
addproperty="id"
/>
<compute actions="get" provider="${jclouds.compute.url}">
<nodes id="${id}" />
</compute>
</target>
<target name="get-group" description="get the nodes with group ${group}" unless="id" >
<input
message="Which group do you wish to get"
addproperty="group"
/>
<compute actions="get" provider="${jclouds.compute.url}">
<nodes group="${group}" />
</compute>
</target>
<property name="location" value="" />
<target name="create" description="create the node ${group}">
<property name="privatekeyfile" value="${user.home}/.ssh/id_rsa" />
<property name="publickeyfile" value="${user.home}/.ssh/id_rsa.pub" />
<property name="os" value="UBUNTU" />
<property name="count" value="1" />
<input
message="What do you want to group your nodes with?"
addproperty="group"
/>
<compute actions="create" provider="${jclouds.compute.url}">
<nodes privatekeyfile="${privatekeyfile}" publickeyfile="${publickeyfile}" group="${group}" count="${count}" os="${os}" hardware="SMALLEST" hostproperty="host" usernameproperty="username" passwordproperty="password" />
</compute>
</target>
</project>

View File

@ -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

View File

@ -1,83 +0,0 @@
<?xml version="1.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.
-->
<project name="sshjava" default="sshjava" basedir=".">
<description>
simple example build file
</description>
<!-- set global properties for this build -->
<property name="src" location="src"/>
<property name="build" location="build"/>
<property name="dist" location="dist"/>
<input
message="Please enter the ip or hostname of the ssh machine"
addproperty="host"
/>
<input
message="Please enter the user you will connect as"
addproperty="username"
/>
<input
message="Please enter the path to the dsa key"
addproperty="keyfile"
/>
<input
message="Please enter the strings you'd like to test"
addproperty="line"
/>
<target name="init">
<!-- Create the time stamp -->
<tstamp/>
<!-- Create the build directory structure used by compile -->
<mkdir dir="${build}"/>
</target>
<target name="compile" depends="init" description="compile the source ">
<!-- Compile the java code from ${src} into ${build} -->
<javac srcdir="${src}" destdir="${build}"/>
</target>
<target name="clean" description="clean up">
<!-- Delete the ${build} and ${dist} directory trees -->
<delete dir="${build}"/>
<delete dir="${dist}"/>
</target>
<taskdef name="sshjava" classname="org.jclouds.tools.ant.taskdefs.sshjava.SSHJava" />
<target name="sshjava" depends="compile" description="remote execute the java command">
<echo message="normal java task"/>
<java classname="TestClass" classpath="${build}" dir="${user.dir}" >
<arg line="${line}"/>
</java>
<echo message="java task over ssh"/>
<sshjava classname="TestClass" classpath="${build}" dir="${user.dir}" host="${host}" username="${username}" keyfile="${keyfile}" trust="true" remotebase="/tmp/test" >
<arg line="${line}"/>
</sshjava>
</target>
</project>

View File

@ -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<String> 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;
}
}

View File

@ -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<URI, ComputeServiceContext> 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<Project> projectProvider = new Provider<Project>() {
@Override
public Project get() {
return getProject();
}
};
public ComputeTask(@Nullable LoadingCache<URI, ComputeServiceContext> 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;
}
}

View File

@ -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<URI, ComputeServiceContext> buildComputeMap(final Provider<Project> projectProvider) {
return CacheBuilder.newBuilder().build(new CacheLoader<URI, ComputeServiceContext>() {
@SuppressWarnings("unchecked")
@Override
public ComputeServiceContext load(URI from) {
Properties props = new Properties();
props.putAll(projectProvider.get().getProperties());
Set<Module> modules = ImmutableSet.<Module> 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<String> set) {
if (set.size() > 0) {
return Iterables.get(set, 0);
} else {
return "";
}
}
static int[] getPortsToOpenFromElement(NodeElement nodeElement) {
Iterable<String> 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;
}
}

View File

@ -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;
}
}

View File

@ -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<String, String> shiftMap = Maps.newLinkedHashMap();
@VisibleForTesting
final LinkedHashMap<String, String> 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<String, String> 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<String, String> map = Maps.newLinkedHashMap();
// this has to go first
map.put(directory.getAbsolutePath(), remotedir.getAbsolutePath());
map.putAll(Maps.transformValues(shiftMap, new Function<String, String>() {
@Override
public String apply(String in) {
return remotebase + ShellToken.FS.to(osFamily) + in;
}
}));
map.putAll(replace);
for (Entry<String, String> 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<FileSet> 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<FileSet> 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<String, String> 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<String, String> 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<String, String> 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
* <i>${user.home}/.ssh/known_hosts</i>.
*
* @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 &quot;wait forever&quot;.
*
* @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);
}
}
}

View File

@ -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.
*
* <p/>
* 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 <code>PumpStreamHandler</code> 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 &quot;wait forever&quot;.
*
* @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
* <i>${user.home}/.ssh/known_hosts</i>.
*
* @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 <code>Process</code>.
* @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");
}
}
}

View File

@ -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<String, String> 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.<String, String> of(System.getProperty("user.home")
+ "/apache-maven-2.2.1", "maven"));
assertEquals(task.replace, ImmutableMap.<String, String> 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 extends Java> 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;
}
}

View File

@ -24,7 +24,7 @@
<parent>
<groupId>org.jclouds</groupId>
<artifactId>jclouds-project</artifactId>
<version>1.5.0-SNAPSHOT</version>
<version>1.6.0-SNAPSHOT</version>
<relativePath>../../project/pom.xml</relativePath>
</parent>

View File

@ -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;

View File

@ -37,6 +37,7 @@ import com.google.inject.Inject;
/**
* Handles Retryable responses with error codes in the 4xx range
*
* @see Error codes section at <a href="https://www.synaptic.att.com/assets/us/en/home/Atmos_Programmers_Guide_1.3.4A.pdf" />
* @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

View File

@ -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();
final AtmosObject object = blob2Object.apply(blob);
try {
sync.createFile(container, object, options);
} catch(KeyAlreadyExistsException e) {
deleteAndEnsureGone(sync, path);
sync.createFile(container, blob2Object.apply(blob), options);
sync.createFile(container, object, options);
}
return path;
}

View File

@ -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);

View File

@ -24,7 +24,7 @@
<parent>
<groupId>org.jclouds</groupId>
<artifactId>jclouds-project</artifactId>
<version>1.5.0-SNAPSHOT</version>
<version>1.6.0-SNAPSHOT</version>
<relativePath>../../project/pom.xml</relativePath>
</parent>

View File

@ -24,7 +24,7 @@
<parent>
<groupId>org.jclouds</groupId>
<artifactId>jclouds-project</artifactId>
<version>1.5.0-SNAPSHOT</version>
<version>1.6.0-SNAPSHOT</version>
<relativePath>../../project/pom.xml</relativePath>
</parent>
<groupId>org.jclouds.api</groupId>
@ -34,6 +34,7 @@
<packaging>bundle</packaging>
<properties>
<test.blobstore.container-count>15</test.blobstore.container-count>
<test.cloudfiles.endpoint>https://auth.api.rackspacecloud.com</test.cloudfiles.endpoint>
<test.cloudfiles.api-version>1.0</test.cloudfiles.api-version>
<test.cloudfiles.build-version></test.cloudfiles.build-version>
@ -112,6 +113,7 @@
</goals>
<configuration>
<systemPropertyVariables>
<test.blobstore.container-count>${test.blobstore.container-count}</test.blobstore.container-count>
<jclouds.blobstore.httpstream.url>${jclouds.blobstore.httpstream.url}</jclouds.blobstore.httpstream.url>
<jclouds.blobstore.httpstream.md5>${jclouds.blobstore.httpstream.md5}</jclouds.blobstore.httpstream.md5>
<test.cloudfiles.endpoint>${test.cloudfiles.endpoint}</test.cloudfiles.endpoint>

View File

@ -22,15 +22,19 @@ 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
@ -78,7 +82,11 @@ 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.<Class<? extends Module>>of(StorageAndCDNManagementEndpointModule.class, CloudFilesRestClientModule.class, CloudFilesBlobStoreContextModule.class));
.defaultModules(ImmutableSet.<Class<? extends Module>>builder()
.add(StorageAndCDNManagementEndpointModule.class)
.add(CloudFilesRestClientModule.class)
.add(CloudFilesBlobStoreContextModule.class)
.add(CloudFilesTemporaryUrlExtensionModule.class).build());
}
@Override
@ -93,4 +101,13 @@ public class CloudFilesApiMetadata extends SwiftApiMetadata {
}
}
public static class CloudFilesTemporaryUrlExtensionModule extends TemporaryUrlExtensionModule<CloudFilesAsyncClient> {
@Override
protected void bindRequestSigner() {
bind(BlobRequestSigner.class).to(new TypeLiteral<SwiftBlobSigner<CloudFilesAsyncClient>>() {
});
}
}
}

View File

@ -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<Boolean> setCDNStaticWebsiteError(@PathParam("container") String container,
@PathParam("error") String error);
/**
* @see CloudFilesClient#getTemporaryUrlKey
*/
@HEAD
@Path("/")
@ResponseParser(ParseTemporaryUrlKeyFromHeaders.class)
ListenableFuture<String> getTemporaryUrlKey();
/**
* @see CloudFilesClient#setTemporaryUrlKey
*/
@POST
@Path("/")
ListenableFuture<Void> setTemporaryUrlKey(@HeaderParam(CloudFilesHeaders.ACCOUNT_TEMPORARY_URL_KEY) String key);
}

View File

@ -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 <a href="http://docs.rackspace.com/files/api/v1/cf-devguide/content/Set_Account_Metadata-d1a4460.html" />
* @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 <a href="http://docs.rackspace.com/files/api/v1/cf-devguide/content/Set_Account_Metadata-d1a4460.html" />
* @param temporaryUrlKey
*/
void setTemporaryUrlKey(String temporaryUrlKey);
}

View File

@ -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);
}
}

View File

@ -53,6 +53,7 @@ public class CloudFilesRestClientModule extends SwiftRestClientModule<CloudFiles
.<Class<?>, Class<?>> of());
}
@Override
protected void bindResolvedClientsToCommonSwift() {
bind(CommonSwiftClient.class).to(CloudFilesClient.class).in(Scopes.SINGLETON);
bind(CommonSwiftAsyncClient.class).to(CloudFilesAsyncClient.class).in(Scopes.SINGLETON);

View File

@ -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";

View File

@ -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.<Class<? extends Module>>of(StorageEndpointModule.class,
CloudFilesRestClientModule.class, FixedCloudFilesBlobStoreContextModule.class)).build();
}
}

View File

@ -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<HttpRequest, HttpResponse> 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.<HttpRequest, HttpResponse> 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.<Class<? extends Module>> builder()
.add(StorageAndCDNManagementEndpointModule.class)
.add(CloudFilesRestClientModule.class)
.add(CloudFilesBlobStoreContextModule.class)
.add(StaticTimeAndTemporaryUrlKeyModule.class).build()).build();
}
}

View File

@ -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);
}
}

View File

@ -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);

View File

@ -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);
}
}
}

View File

@ -24,7 +24,7 @@
<parent>
<groupId>org.jclouds</groupId>
<artifactId>jclouds-project</artifactId>
<version>1.5.0-SNAPSHOT</version>
<version>1.6.0-SNAPSHOT</version>
<relativePath>../../project/pom.xml</relativePath>
</parent>
<groupId>org.jclouds.api</groupId>

View File

@ -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 BaseCloudLoadBalancersAsyncClientTest<N
public void createNodesInLoadBalancerWithType() throws SecurityException, NoSuchMethodException, IOException {
Method method = NodeAsyncClient.class.getMethod("createNodesInLoadBalancer", Set.class, int.class);
HttpRequest httpRequest = processor.createRequest(method, Collections.<NodeRequest>singleton(NodeRequest.builder().
HttpRequest httpRequest = processor.createRequest(method, ImmutableList.<NodeRequest>of(NodeRequest.builder().
address("192.168.1.1").port(8080).build()), 3);
assertRequestLineEquals(httpRequest,

View File

@ -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<Node> newNodes = client.getNodeClient(region).createNodesInLoadBalancer(
Collections.<NodeRequest> singleton(NodeRequest.builder().address("192.168.1.2").port(8080).build()),
ImmutableSet.<NodeRequest> of(NodeRequest.builder().address("192.168.1.2").port(8080).build()),
lb.getId());
for (Node n : newNodes) {

View File

@ -24,7 +24,7 @@
<parent>
<groupId>org.jclouds</groupId>
<artifactId>jclouds-project</artifactId>
<version>1.5.0-SNAPSHOT</version>
<version>1.6.0-SNAPSHOT</version>
<relativePath>../../project/pom.xml</relativePath>
</parent>

View File

@ -24,7 +24,7 @@
<parent>
<groupId>org.jclouds</groupId>
<artifactId>jclouds-project</artifactId>
<version>1.5.0-SNAPSHOT</version>
<version>1.6.0-SNAPSHOT</version>
<relativePath>../../project/pom.xml</relativePath>
</parent>
<groupId>org.jclouds.api</groupId>

View File

@ -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() {
@ -49,6 +50,13 @@ public class CloudSigmaComputeServiceLiveTest extends BaseComputeServiceLiveTest
"node userMetadata did not match %s %s", userMetadata, node);
}
// cloudsigma does not support tags
@Override
protected void checkTagsInNodeEquals(final NodeMetadata node, final ImmutableSet<String> tags) {
assert node.getTags().equals(ImmutableSet.<String> 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");

View File

@ -24,7 +24,7 @@
<parent>
<groupId>org.jclouds</groupId>
<artifactId>jclouds-project</artifactId>
<version>1.5.0-SNAPSHOT</version>
<version>1.6.0-SNAPSHOT</version>
<relativePath>../../project/pom.xml</relativePath>
</parent>
<groupId>org.jclouds.api</groupId>

View File

@ -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.<Class<? extends Module>>of(CloudStackRestClientModule.class, CloudStackComputeServiceContextModule.class));
.defaultModules(ImmutableSet.<Class<? extends Module>> builder()
.add(CloudStackParserModule.class)
.add(CloudStackRestClientModule.class)
.add(CloudStackComputeServiceContextModule.class).build());
}
@Override

View File

@ -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"));
}
}

View File

@ -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 <E> TypeAdapter<Iterable<E>> newIterableAdapter(final TypeAdapter<E> elementAdapter) {
return new TypeAdapter<Iterable<E>>() {
public void write(JsonWriter out, Iterable<E> value) throws IOException {
out.beginArray();
for (E element : value) {
elementAdapter.write(out, element);
}
out.endArray();
}
@SuppressWarnings("unchecked")
public Iterable<E> 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<E>) (val != null ? Splitter.on(',').split(val) : ImmutableSet.of());
} else {
Builder<E> builder = ImmutableList.<E> builder();
in.beginArray();
while (in.hasNext()) {
E element = elementAdapter.read(in);
if (element != null)
builder.add(element);
}
in.endArray();
return builder.build();
}
}
}.nullSafe();
}
}
}

View File

@ -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<CloudStackClien
@Override
protected void configure() {
bind(DateAdapter.class).to(CloudStackDateAdapter.class);
bind(new TypeLiteral<RestContext<CloudStackDomainClient, CloudStackDomainAsyncClient>>() {
}).to(new TypeLiteral<RestContextImpl<CloudStackDomainClient, CloudStackDomainAsyncClient>>() {
});

View File

@ -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<DiskOffering> {
protected String domainId;
protected int diskSize;
protected boolean customized;
protected String tags;
protected ImmutableSet.Builder<String> tags = ImmutableSet.<String>builder();
/**
* @see DiskOffering#getId()
@ -123,13 +125,21 @@ public class DiskOffering implements Comparable<DiskOffering> {
/**
* @see DiskOffering#getTags()
*/
public T tags(String tags) {
this.tags = tags;
public T tags(Iterable<String> tags) {
this.tags = ImmutableSet.<String>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<DiskOffering> {
private final String domainId;
private final int diskSize;
private final boolean customized;
private final String tags;
private final Set<String> 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<String> tags) {
this.id = checkNotNull(id, "id");
this.name = name;
this.displayText = displayText;
@ -177,7 +187,7 @@ public class DiskOffering implements Comparable<DiskOffering> {
this.domainId = domainId;
this.diskSize = diskSize;
this.customized = customized;
this.tags = tags;
this.tags = tags != null ? ImmutableSet.copyOf(tags) : ImmutableSet.<String> of();
}
/**
@ -244,8 +254,7 @@ public class DiskOffering implements Comparable<DiskOffering> {
/**
* @return the tags for the disk offering
*/
@Nullable
public String getTags() {
public Set<String> getTags() {
return this.tags;
}

View File

@ -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<Host> {
protected long diskSizeTotal;
protected String events;
protected boolean hasEnoughCapacity;
protected String hostTags;
protected ImmutableSet.Builder<String> tags = ImmutableSet.<String>builder();
protected String hypervisor;
protected String ipAddress;
protected boolean localStorageActive;
@ -319,10 +321,18 @@ public class Host implements Comparable<Host> {
}
/**
* @see Host#getHostTags()
* @see Host#getTags()
*/
public T hostTags(String hostTags) {
this.hostTags = hostTags;
public T tags(Iterable<String> tags) {
this.tags = ImmutableSet.<String>builder().addAll(tags);
return self();
}
/**
* @see Host#getTags()
*/
public T tag(String tag) {
this.tags.add(tag);
return self();
}
@ -512,7 +522,7 @@ public class Host implements Comparable<Host> {
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<Host> {
.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<Host> {
private final long diskSizeTotal;
private final String events;
private final boolean hasEnoughCapacity;
private final String hostTags;
private final Set<String> tags;
private final String hypervisor;
private final String ipAddress;
private final boolean localStorageActive;
@ -619,7 +629,7 @@ public class Host implements Comparable<Host> {
@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<String> 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<Host> {
this.diskSizeTotal = diskSizeTotal;
this.events = events;
this.hasEnoughCapacity = hasEnoughCapacity;
this.hostTags = hostTags;
this.tags = tags != null ? ImmutableSet.copyOf(tags) : ImmutableSet.<String> of();
this.hypervisor = hypervisor;
this.ipAddress = ipAddress;
this.localStorageActive = localStorageActive;
@ -752,11 +762,14 @@ public class Host implements Comparable<Host> {
return this.hasEnoughCapacity;
}
@Nullable
public String getHostTags() {
return this.hostTags;
/**
* @return the tags for the host
*/
public Set<String> getTags() {
return this.tags;
}
@Nullable
public String getHypervisor() {
return this.hypervisor;
@ -868,7 +881,7 @@ public class Host implements Comparable<Host> {
@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<Host> {
&& 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<Host> {
.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)

View File

@ -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<String> tags = ImmutableSet.<String>builder();
protected boolean securityGroupEnabled;
protected Set<? extends NetworkService> services = ImmutableSortedSet.of();
@ -302,11 +303,20 @@ public class Network {
/**
* @see Network#getTags()
*/
public T tags(String tags) {
this.tags = tags;
public T tags(Iterable<String> tags) {
this.tags = ImmutableSet.<String>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<String> tags;
private final boolean securityGroupEnabled;
private final Set<? extends NetworkService> 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<? extends NetworkService> services) {
@Nullable String zoneId, @Nullable Iterable<String> tags, boolean securityGroupEnabled, Set<? extends NetworkService> 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.<String> 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<String> getTags() {
return this.tags;
}

View File

@ -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<NetworkOffering> {
protected TrafficType trafficType;
protected GuestIPType guestIPType;
protected int networkRate;
protected String tags;
protected ImmutableSet.Builder<String> tags = ImmutableSet.<String>builder();
/**
* @see NetworkOffering#getId()
@ -150,13 +152,22 @@ public class NetworkOffering implements Comparable<NetworkOffering> {
/**
* @see NetworkOffering#getTags()
*/
public T tags(String tags) {
this.tags = tags;
public T tags(Iterable<String> tags) {
this.tags = ImmutableSet.<String>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<NetworkOffering> {
private final TrafficType trafficType;
private final GuestIPType guestIPType;
private final int networkRate;
private final String tags;
private final Set<String> 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<String> tags) {
this.id = checkNotNull(id, "id");
this.name = name;
this.displayText = displayText;
@ -211,7 +222,7 @@ public class NetworkOffering implements Comparable<NetworkOffering> {
this.trafficType = trafficType;
this.guestIPType = guestIPType;
this.networkRate = networkRate;
this.tags = tags;
this.tags = tags != null ? ImmutableSet.copyOf(tags) : ImmutableSet.<String> of();
}
/**
@ -302,8 +313,7 @@ public class NetworkOffering implements Comparable<NetworkOffering> {
/**
* @return the tags for the network offering
*/
@Nullable
public String getTags() {
public Set<String> getTags() {
return this.tags;
}

View File

@ -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<ServiceOffering> {
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<String> tags = ImmutableSet.of();
protected ImmutableSet.Builder<String> tags = ImmutableSet.<String>builder();
/**
* @see ServiceOffering#getId()
@ -161,8 +157,16 @@ public class ServiceOffering implements Comparable<ServiceOffering> {
/**
* @see ServiceOffering#getTags()
*/
public T tags(Set<String> tags) {
this.tags = ImmutableSet.copyOf(checkNotNull(tags, "tags"));
public T tags(Iterable<String> tags) {
this.tags = ImmutableSet.<String>builder().addAll(tags);
return self();
}
/**
* @see ServiceOffering#getTags()
*/
public T tag(String tag) {
this.tags.add(tag);
return self();
}
@ -174,14 +178,6 @@ public class ServiceOffering implements Comparable<ServiceOffering> {
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<ServiceOffering> {
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<ServiceOffering> {
.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<ServiceOffering> {
private final StorageType storageType;
private final Set<String> 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<String> 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<ServiceOffering> {
this.memory = memory;
this.haSupport = haSupport;
this.storageType = storageType;
this.tags = !(Strings.emptyToNull(tags) == null) ? ImmutableSet.copyOf(Splitter.on(',').split(tags))
: ImmutableSet.<String> of();
this.tags = tags != null ? ImmutableSet.copyOf(tags) : ImmutableSet.<String> 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<ServiceOffering> {
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<ServiceOffering> {
@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<ServiceOffering> {
&& 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<ServiceOffering> {
.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);
}

View File

@ -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<StoragePool> {
protected String id;
protected String name;
protected String path;
protected String tags;
protected ImmutableSet.Builder<String> tags = ImmutableSet.<String>builder();
protected StoragePool.State state;
protected StoragePool.Type type;
protected String zoneId;
@ -143,10 +145,18 @@ public class StoragePool implements Comparable<StoragePool> {
}
/**
* @see StoragePool#getTags()
* @see DiskOffering#getTags()
*/
public T tags(String tags) {
this.tags = tags;
public T tags(Iterable<String> tags) {
this.tags = ImmutableSet.<String>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<StoragePool> {
}
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<StoragePool> {
private final String id;
private final String name;
private final String path;
private final String tags;
private final Set<String> tags;
private final StoragePool.State state;
private final StoragePool.Type type;
private final String zoneId;
@ -318,11 +328,15 @@ public class StoragePool implements Comparable<StoragePool> {
@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<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) {
this.id = checkNotNull(id, "id");
this.name = name;
this.path = path;
this.tags = tags;
this.tags = tags != null ? ImmutableSet.copyOf(tags) : ImmutableSet.<String> of();
this.state = state;
this.type = type;
this.zoneId = zoneId;
@ -353,8 +367,7 @@ public class StoragePool implements Comparable<StoragePool> {
return this.path;
}
@Nullable
public String getTags() {
public Set<String> getTags() {
return this.tags;
}

View File

@ -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() {

View File

@ -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<Encryp
cipher.init(Cipher.DECRYPT_MODE, privKey);
byte[] cipherText = Base64.decode(dataAndKey.getEncryptedPassword());
byte[] plainText = cipher.doFinal(cipherText);
String password = new String(plainText, Charset.forName("ASCII"));
String password = new String(plainText, Charsets.US_ASCII);
return LoginCredentials.builder()
.user("Administrator")

View File

@ -21,7 +21,6 @@ package org.jclouds.cloudstack.compute.strategy;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import java.util.Collections;
import java.util.Map;
import org.jclouds.cloudstack.compute.options.CloudStackTemplateOptions;
@ -36,7 +35,7 @@ import com.google.common.collect.ImmutableSet;
@Test(singleThreaded = true, testName="OptionsConverterTest")
public class OptionsConverterTest {
private static final Map<String,Network> EMPTY_NETWORKS_MAP = Collections.<String, Network>emptyMap();
private static final Map<String,Network> EMPTY_NETWORKS_MAP = ImmutableMap.<String, Network>of();
private static final String ZONE_ID = "2";
private final NetworkService firewallServiceWithStaticNat
= NetworkService.builder().name("Firewall").capabilities(ImmutableMap.of("StaticNat", "true")).build();

View File

@ -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.<String>emptySet()).allocationState(AllocationState.ENABLED).clusterId("1").clusterName("Xen Clust 1").podId("1"));
AddHostOptions.Builder.hostTags(ImmutableSet.<String>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.<String>emptySet()).osCategoryId("5"));
Host actual = requestSendsResponse(request, response).updateHost("1", UpdateHostOptions.Builder.allocationState(AllocationState.ENABLED).hostTags(ImmutableSet.<String>of()).osCategoryId("5"));
assertEquals(actual, expected);
}

View File

@ -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<Host>, Set<Host>>
@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<Host>, Set<Host>>
.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(),

View File

@ -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<Set<StoragePool>> {
@Override
@ -54,7 +58,16 @@ public class ListStoragePoolsResponseTest extends BaseItemParserTest<Set<Storage
c.set(Calendar.SECOND, 6);
Date created = c.getTime();
StoragePool storagePool = StoragePool.builder().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(created).type(StoragePool.Type.NETWORK_FILESYSTEM).clusterId("1").clusterName("Xen Clust 1").diskSizeTotal(898356445184L).diskSizeAllocated(18276679680L).tags("").state(StoragePool.State.UP).build();
StoragePool storagePool = StoragePool.builder().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(created).type(StoragePool.Type.NETWORK_FILESYSTEM).clusterId("1").clusterName("Xen Clust 1")
.diskSizeTotal(898356445184L).diskSizeAllocated(18276679680L).tag("tag1").state(StoragePool.State.UP)
.build();
return ImmutableSet.of(storagePool);
}
@Override
protected Injector injector() {
return Guice.createInjector(new GsonModule(), new CloudStackParserModule());
}
}

View File

@ -23,7 +23,7 @@ import java.util.Date;
import java.util.Set;
import java.util.TimeZone;
import org.jclouds.cloudstack.config.CloudStackDateAdapter;
import org.jclouds.cloudstack.config.CloudStackParserModule;
import org.jclouds.cloudstack.domain.UsageRecord;
import org.jclouds.json.BaseSetParserTest;
import org.jclouds.json.config.GsonModule;
@ -72,14 +72,7 @@ public class ListUsageRecordsResponseTest extends BaseSetParserTest<UsageRecord>
@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());
}
});
}
}

View File

@ -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"} ] } }
{ "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"} ] } }

View File

@ -24,7 +24,7 @@
<parent>
<groupId>org.jclouds</groupId>
<artifactId>jclouds-project</artifactId>
<version>1.5.0-SNAPSHOT</version>
<version>1.6.0-SNAPSHOT</version>
<relativePath>../../project/pom.xml</relativePath>
</parent>
<groupId>org.jclouds.api</groupId>

View File

@ -93,8 +93,10 @@ public class MetricDataBinder implements org.jclouds.rest.Binder {
formParameters.put("MetricData.member." + metricDatumIndex + ".Unit",
String.valueOf(metricDatum.getUnit()));
if (metricDatum.getValue().isPresent()) {
formParameters.put("MetricData.member." + metricDatumIndex + ".Value",
String.valueOf(metricDatum.getValue()));
String.valueOf(metricDatum.getValue().get()));
}
metricDatumIndex++;
}

View File

@ -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<Datapoint> {
public class GetMetricStatisticsResponse extends FluentIterable<Datapoint> {
private final Set<Datapoint> datapoints;
private final Iterable<Datapoint> datapoints;
private final String label;
public GetMetricStatisticsResponse(@Nullable Set<Datapoint> datapoints, String label) {
public GetMetricStatisticsResponse(@Nullable Iterable<Datapoint> datapoints, String label) {
// Default to an empty set
if (datapoints == null) {
this.datapoints = ImmutableSet.<Datapoint>of();
@ -90,8 +90,8 @@ public class GetMetricStatisticsResponse extends ForwardingSet<Datapoint> {
}
@Override
protected Set<Datapoint> delegate() {
return datapoints;
public Iterator<Datapoint> iterator() {
return datapoints.iterator();
}
}

View File

@ -25,13 +25,15 @@ 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 <a href="http://docs.amazonwebservices.com/AmazonCloudWatch/latest/APIReference/API_MetricDatum.html" />
* @see <a href=
* "http://docs.amazonwebservices.com/AmazonCloudWatch/latest/APIReference/API_MetricDatum.html"
* />
*
* @author Jeremy Whitlock
*/
@ -42,17 +44,17 @@ public class MetricDatum {
private final Optional<StatisticValues> statisticValues;
private final Optional<Date> timestamp;
private final Unit unit;
private final double value;
private final Optional<Double> value;
/**
* Private constructor to enforce using {@link Builder}.
*/
protected MetricDatum(Set<Dimension> dimensions, String metricName, StatisticValues statisticValues, Date timestamp,
Unit unit, double value) {
this.dimensions = ImmutableSet.<Dimension>copyOf(checkNotNull(dimensions, "dimensions"));
protected MetricDatum(Iterable<Dimension> dimensions, String metricName, Optional<StatisticValues> statisticValues,
Optional<Date> timestamp, Unit unit, Optional<Double> value) {
this.dimensions = ImmutableSet.<Dimension> 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<Double> 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,27 +112,29 @@ public class MetricDatum {
public static class Builder {
// this builder is set to be additive on dimension calls, so make this mutable
private Set<Dimension> dimensions = Sets.newLinkedHashSet();
private ImmutableList.Builder<Dimension> dimensions = ImmutableList.<Dimension> builder();
private String metricName;
private StatisticValues statisticValues;
private Date timestamp;
private Optional<StatisticValues> statisticValues = Optional.absent();
private Optional<Date> timestamp = Optional.absent();
private Unit unit = Unit.NONE;
private double value;
private Optional<Double> 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<Dimension> dimensions) {
public Builder dimensions(Iterable<Dimension> dimensions) {
this.dimensions.addAll(checkNotNull(dimensions, "dimensions"));
return this;
}
@ -138,7 +142,8 @@ public class MetricDatum {
/**
* 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
*/
@ -150,7 +155,8 @@ public class MetricDatum {
/**
* The name of the metric.
*
* @param metricName the metric name
* @param metricName
* the metric name
*
* @return this {@code Builder} object
*/
@ -162,32 +168,35 @@ 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.
* 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
* @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
*/
@ -199,12 +208,13 @@ 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());
}
}

View File

@ -34,6 +34,7 @@ import org.jclouds.concurrent.Timeout;
* Provides access to Amazon CloudWatch via the Query API
* <p/>
*
* @see MetricAsyncApi
* @see <a href="http://docs.amazonwebservices.com/AmazonCloudWatch/latest/APIReference" />
* @author Jeremy Whitlock
*/

View File

@ -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<? extends PagedIterable<Metric>> list();
/**
@ -73,6 +77,7 @@ public interface MetricAsyncApi {
@Path("/")
@XMLResponseParser(ListMetricsResponseHandler.class)
@FormParams(keys = "Action", values = "ListMetrics")
@ExceptionParser(ReturnEmptyIterableWithMarkerOnNotFoundOr404.class)
ListenableFuture<? extends IterableWithMarker<Metric>> list(ListMetricsOptions options);
/**

View File

@ -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 {

View File

@ -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 {

View File

@ -24,7 +24,7 @@
<parent>
<groupId>org.jclouds</groupId>
<artifactId>jclouds-project</artifactId>
<version>1.5.0-SNAPSHOT</version>
<version>1.6.0-SNAPSHOT</version>
<relativePath>../../project/pom.xml</relativePath>
</parent>
<groupId>org.jclouds.api</groupId>

View File

@ -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)

View File

@ -24,7 +24,7 @@
<parent>
<groupId>org.jclouds</groupId>
<artifactId>jclouds-project</artifactId>
<version>1.5.0-SNAPSHOT</version>
<version>1.6.0-SNAPSHOT</version>
<relativePath>../../project/pom.xml</relativePath>
</parent>
<groupId>org.jclouds.api</groupId>

View File

@ -196,7 +196,7 @@ public class RunningInstanceToNodeMetadata implements Function<RunningInstance,
@VisibleForTesting
String getGroupForInstance(final RunningInstance instance) {
String group = parseGroupFrom(instance, instance.getGroupIds());
String group = parseGroupFrom(instance, instance.getGroupNames());
if(group == null && instance.getKeyName() != null) {
// when not using a generated security group, e.g. in VPC, try from key:
group = parseGroupFrom(instance, Sets.newHashSet(instance.getKeyName()));

View File

@ -18,7 +18,6 @@
*/
package org.jclouds.ec2.compute.functions;
import java.nio.charset.Charset;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.KeySpec;
@ -33,6 +32,7 @@ import org.jclouds.ec2.compute.domain.PasswordDataAndPrivateKey;
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.Singleton;
@ -66,7 +66,7 @@ public class WindowsLoginCredentialsFromEncryptedData implements Function<Passwo
cipher.init(Cipher.DECRYPT_MODE, privKey);
byte[] cipherText = Base64.decode(dataAndKey.getPasswordData().getPasswordData());
byte[] plainText = cipher.doFinal(cipherText);
String password = new String(plainText, Charset.forName("ASCII"));
String password = new String(plainText, Charsets.US_ASCII);
return LoginCredentials.builder()
.user("Administrator")

View File

@ -23,7 +23,6 @@ import static com.google.common.collect.Iterables.transform;
import static org.jclouds.ec2.options.DescribeImagesOptions.Builder.ownedBy;
import static org.jclouds.ec2.reference.EC2Constants.PROPERTY_EC2_AMI_OWNERS;
import java.util.Collections;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
@ -83,7 +82,7 @@ public class EC2ImageSupplier implements Supplier<Set<? extends Image>> {
public Set<? extends Image> get() {
if (amiOwners.length == 0) {
logger.debug(">> no owners specified, skipping image parsing");
return Collections.emptySet();
return ImmutableSet.of();
} else {
logger.debug(">> providing images");

View File

@ -114,8 +114,12 @@ public class Attachment implements Comparable<Attachment> {
}
/**
* Snapshots are tied to Regions and can only be used for volumes within the same Region.
* To be removed in jclouds 1.6 <h4>Warning</h4>
*
* 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;
}

View File

@ -209,9 +209,12 @@ public class BundleTask implements Comparable<BundleTask> {
}
/**
* To be removed in jclouds 1.6 <h4>Warning</h4>
*
* @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;
}

View File

@ -219,9 +219,12 @@ public class Image implements Comparable<Image> {
}
/**
* AMIs are tied to the Region where its files are located within Amazon S3.
* To be removed in jclouds 1.6 <h4>Warning</h4>
*
* 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;
}

View File

@ -47,8 +47,12 @@ public class InstanceStateChange implements Comparable<InstanceStateChange> {
}
/**
* Instances are tied to Availability Zones. However, the instance ID is tied to the Region.
* To be removed in jclouds 1.6 <h4>Warning</h4>
*
* 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;
}

View File

@ -18,9 +18,17 @@
*/
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;
/**
*
@ -29,38 +37,155 @@ import com.google.common.collect.Multimap;
* />
* @author Adrian Cole
*/
public interface IpPermission extends Comparable<IpPermission> {
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<String, String> userIdGroupPairs = LinkedHashMultimap.create();
private Set<String> groupIds = Sets.newLinkedHashSet();
private Set<String> 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<String, String> userIdGroupPairs) {
this.userIdGroupPairs.putAll(checkNotNull(userIdGroupPairs, "userIdGroupPairs"));
return this;
}
public Builder ipRange(String ipRange) {
this.ipRanges.add(ipRange);
return this;
}
public Builder ipRanges(Iterable<String> 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<String> 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<String, String> userIdGroupPairs;
private final Set<String> groupIds;
private final IpProtocol ipProtocol;
private final Set<String> ipRanges;
public IpPermission(IpProtocol ipProtocol, int fromPort, int toPort, Multimap<String, String> userIdGroupPairs,
Iterable<String> groupIds, Iterable<String> 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<String, String> getUserIdGroupPairs();
public Multimap<String, String> getUserIdGroupPairs() {
return userIdGroupPairs;
}
/**
* List of security group Ids
*/
Set<String> getGroupIds();
public Set<String> getGroupIds() {
return groupIds;
}
/**
* IP protocol
*/
IpProtocol getIpProtocol();
public IpProtocol getIpProtocol() {
return ipProtocol;
}
/**
* IP ranges.
*/
Set<String> getIpRanges();
public Set<String> 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();
}
}

View File

@ -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 <a href=
* "http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-ItemType-IpPermissionType.html"
* />
* @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<String, String> userIdGroupPairs = LinkedHashMultimap.create();
private Set<String> groupIds = Sets.newLinkedHashSet();
private Set<String> 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<String, String> userIdGroupPairs) {
this.userIdGroupPairs.putAll(userIdGroupPairs);
return this;
}
public Builder ipRange(String ipRange) {
this.ipRanges.add(ipRange);
return this;
}
public Builder ipRanges(Iterable<String> ipRanges) {
Iterables.addAll(this.ipRanges, ipRanges);
return this;
}
public Builder groupId(String groupId) {
this.groupIds.add(groupId);
return this;
}
public Builder groupIds(Iterable<String> 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<String, String> userIdGroupPairs;
private final Set<String> groupIds;
private final IpProtocol ipProtocol;
private final Set<String> ipRanges;
public IpPermissionImpl(IpProtocol ipProtocol, int fromPort, int toPort,
Multimap<String, String> userIdGroupPairs, Iterable<String> groupIds, Iterable<String> 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<String, String> getUserIdGroupPairs() {
return userIdGroupPairs;
}
/**
* {@inheritDoc}
*/
@Override
public Set<String> getGroupIds() {
return groupIds;
}
/**
* {@inheritDoc}
*/
@Override
public IpProtocol getIpProtocol() {
return ipProtocol;
}
/**
* {@inheritDoc}
*/
@Override
public Set<String> 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 + "]";
}
}

View File

@ -103,8 +103,12 @@ public class KeyPair implements Comparable<KeyPair> {
}
/**
* Key pairs (to connect to instances) are Region-specific.
* To be removed in jclouds 1.6 <h4>Warning</h4>
*
* 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;
}

View File

@ -42,8 +42,12 @@ public class PublicIpInstanceIdPair implements Comparable<PublicIpInstanceIdPair
}
/**
* Elastic IP addresses are tied to a Region and cannot be mapped across Regions.
* To be removed in jclouds 1.6 <h4>Warning</h4>
*
* 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;
}

View File

@ -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 <a href="http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-ItemType-ReservationInfoType.html"
* @see <a href=
* "http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-ItemType-ReservationInfoType.html"
* />
* @author Adrian Cole
*/
public class Reservation<T extends RunningInstance> extends LinkedHashSet<T> implements Comparable<Reservation<T>>,
Set<T> {
public class Reservation<T extends RunningInstance> extends ForwardingSet<T> implements Comparable<Reservation<T>>{
public static <T extends RunningInstance> Builder<T> builder() {
return new Builder<T>();
}
public Builder<T> toBuilder() {
return Reservation.<T> builder().fromReservation(this);
}
public static class Builder<T extends RunningInstance> {
private String region;
private String ownerId;
private String requesterId;
private String reservationId;
private ImmutableSet.Builder<T> instances = ImmutableSet.<T> builder();
private ImmutableSet.Builder<String> groupNames = ImmutableSet.<String> builder();
/**
* @see Reservation#getRegion()
*/
public Builder<T> region(String region) {
this.region = region;
return this;
}
/**
* @see Reservation#getOwnerId()
*/
public Builder<T> ownerId(String ownerId) {
this.ownerId = ownerId;
return this;
}
/**
* @see Reservation#getRequesterId()
*/
public Builder<T> requesterId(String requesterId) {
this.requesterId = requesterId;
return this;
}
/**
* @see Reservation#getReservationId()
*/
public Builder<T> reservationId(String reservationId) {
this.reservationId = reservationId;
return this;
}
/**
* @see Reservation#iterator
*/
public Builder<T> instance(T instance) {
this.instances.add(checkNotNull(instance, "instance"));
return this;
}
/**
* @see Reservation#iterator
*/
public Builder<T> instances(Set<T> instances) {
this.instances.addAll(checkNotNull(instances, "instances"));
return this;
}
/**
* @see Reservation#getGroupNames()
*/
public Builder<T> groupName(String groupName) {
this.groupNames.add(checkNotNull(groupName, "groupName"));
return this;
}
/**
* @see Reservation#getGroupNames()
*/
public Builder<T> groupNames(Iterable<String> groupNames) {
this.groupNames = ImmutableSet.<String> builder().addAll(checkNotNull(groupNames, "groupNames"));
return this;
}
public Reservation<T> build() {
return new Reservation<T>(region, groupNames.build(), instances.build(), ownerId, requesterId, reservationId);
}
public Builder<T> fromReservation(Reservation<T> 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<String> groupIds = Sets.newLinkedHashSet();
private final ImmutableSet<String> groupNames;
private final ImmutableSet<T> instances;
@Nullable
private final String ownerId;
@Nullable
@ -48,32 +140,45 @@ public class Reservation<T extends RunningInstance> extends LinkedHashSet<T> imp
@Nullable
private final String reservationId;
public Reservation(String region, Iterable<String> groupIds, Iterable<T> instances, @Nullable String ownerId,
public Reservation(String region, Iterable<String> groupNames, Iterable<T> 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<T> 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 <h4>Warning</h4>
*
* 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<T> o) {
return (this == o) ? 0 : getReservationId().compareTo(o.getReservationId());
/**
* @see #getGroupNames()
*/
@Deprecated
public Set<String> getGroupIds() {
return groupNames;
}
/**
* Names of the security groups.
*/
public Set<String> getGroupIds() {
return groupIds;
public Set<String> getGroupNames() {
return groupNames;
}
/**
@ -84,7 +189,8 @@ public class Reservation<T extends RunningInstance> extends LinkedHashSet<T> 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<T extends RunningInstance> extends LinkedHashSet<T> 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<T> 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<T> other) {
return ComparisonChain.start().compare(region, other.region)
.compare(reservationId, other.reservationId, Ordering.natural().nullsLast()).result();
}
}

View File

@ -46,6 +46,13 @@ public class ReservedInstancesOffering implements Comparable<ReservedInstancesOf
this.usagePrice = usagePrice;
}
/**
* To be removed in jclouds 1.6 <h4>Warning</h4>
*
* 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;
}

View File

@ -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<RunningInstance> {
public static class Builder {
protected String region;
protected Set<String> groupIds = Sets.newLinkedHashSet();
protected Set<String> groupNames = Sets.newLinkedHashSet();
protected String amiLaunchIndex;
protected String dnsName;
protected String imageId;
@ -72,14 +76,14 @@ public class RunningInstance implements Comparable<RunningInstance> {
return this;
}
public Builder groupIds(Iterable<String> groupIds) {
this.groupIds = ImmutableSet.copyOf(checkNotNull(groupIds, "groupIds"));
public Builder groupNames(Iterable<String> 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<RunningInstance> {
}
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<RunningInstance> {
}
protected final String region;
protected final Set<String> groupIds;
protected final Set<String> groupNames;
protected final String amiLaunchIndex;
@Nullable
protected final String dnsName;
@ -253,11 +257,7 @@ public class RunningInstance implements Comparable<RunningInstance> {
protected final String rootDeviceName;
protected final Map<String, BlockDevice> ebsBlockDevices;
public int compareTo(RunningInstance o) {
return (this == o) ? 0 : getId().compareTo(o.getId());
}
protected RunningInstance(String region, Iterable<String> groupIds, @Nullable String amiLaunchIndex,
protected RunningInstance(String region, Iterable<String> 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<RunningInstance> {
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 <h4>Warning</h4>
*
* 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<RunningInstance> {
return ebsBlockDevices;
}
/**
* @see #getGroupNames()
*/
@Deprecated
public Set<String> getGroupIds() {
return getGroupNames();
}
/**
* Names of the security groups.
*/
public Set<String> getGroupIds() {
return groupIds;
public Set<String> 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();
}
}

View File

@ -24,6 +24,11 @@ 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 <a href=
@ -31,42 +36,135 @@ import org.jclouds.javax.annotation.Nullable;
* />
* @author Adrian Cole
*/
public class SecurityGroup implements Comparable<SecurityGroup> {
public class SecurityGroup extends ForwardingSet<IpPermission> {
public static Builder<?> builder() {
return new ConcreteBuilder();
}
public Builder<?> toBuilder() {
return new ConcreteBuilder().fromSecurityGroup(this);
}
public static abstract class Builder<T extends Builder<T>> {
protected abstract T self();
protected String region;
protected String id;
protected String name;
protected String ownerId;
protected String description;
protected ImmutableSet.Builder<IpPermission> ipPermissions = ImmutableSet.<IpPermission> 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<IpPermission> 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<ConcreteBuilder> {
@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<IpPermissionImpl> ipPermissions;
private final Set<IpPermission> ipPermissions;
public SecurityGroup(String region, String id, String name, String ownerId, String description,
Set<IpPermissionImpl> ipPermissions) {
Iterable<IpPermission> 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 <h4>Warning</h4>
*
* 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<SecurityGroup> {
}
/**
* Set of IP permissions associated with the security group.
* Please use this class as a collection
*/
public Set<IpPermissionImpl> getIpPermissions() {
@Deprecated
public Set<IpPermission> 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<IpPermission> delegate() {
return ipPermissions;
}
}

View File

@ -75,8 +75,12 @@ public class Snapshot implements Comparable<Snapshot> {
}
/**
* Snapshots are tied to Regions and can only be used for volumes within the same Region.
* To be removed in jclouds 1.6 <h4>Warning</h4>
*
* 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;
}

View File

@ -38,6 +38,10 @@ import com.google.common.collect.ImmutableSet;
*/
public class Volume implements Comparable<Volume> {
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.
@ -147,6 +151,12 @@ public class Volume implements Comparable<Volume> {
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<Volume> {
}
/**
* 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 <h4>Warning</h4>
*
* 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;
}

View File

@ -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;
@ -42,7 +41,7 @@ import com.google.common.collect.Multimaps;
*
* @author Adrian Cole
*/
public class IpPermissions extends IpPermissionImpl {
public class IpPermissions extends IpPermission {
protected IpPermissions(IpProtocol ipProtocol, int fromPort, int toPort,
Multimap<String, String> userIdGroupPairs, Iterable<String> groupIds, Iterable<String> ipRanges) {

View File

@ -80,7 +80,7 @@ public abstract class BaseReservationHandler<T> extends HandlerForGeneratedReque
private String deviceName;
// reservation stuff
private Set<String> groupIds = Sets.newLinkedHashSet();
private Set<String> groupNames = Sets.newLinkedHashSet();
private String ownerId;
private String requesterId;
private String reservationId;
@ -111,7 +111,7 @@ public abstract class BaseReservationHandler<T> 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<T> 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<T> extends HandlerForGeneratedReque
String region = getRequest() != null ? AWSUtils.findRegionInArgsOrNull(getRequest()) : null;
if (region == null)
region = defaultRegion.get();
Reservation<? extends RunningInstance> info = new Reservation<RunningInstance>(region, groupIds, instances,
Reservation<? extends RunningInstance> info = new Reservation<RunningInstance>(region, groupNames, instances,
ownerId, requesterId, reservationId);
this.groupIds = Sets.newLinkedHashSet();
this.groupNames = Sets.newLinkedHashSet();
this.instances = Sets.newLinkedHashSet();
this.ownerId = null;
this.requesterId = null;

View File

@ -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 <a href=
* "http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/index.html?ApiReference-query-DescribeSecurityGroups.html"
* "http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/index.html?ApiReference-query-DescribesecurityGroupInfo.html"
* />
* @author Adrian Cole
*/
public class DescribeSecurityGroupsResponseHandler extends
ParseSax.HandlerForGeneratedRequestWithResult<Set<SecurityGroup>> {
@Inject
@Region
Supplier<String> defaultRegion;
private final SecurityGroupHandler securityGroupHandler;
private StringBuilder currentText = new StringBuilder();
private Set<SecurityGroup> securtyGroups = Sets.newLinkedHashSet();
private String groupId;
private String groupName;
private String ownerId;
private String groupDescription;
private Set<IpPermissionImpl> ipPermissions = Sets.newLinkedHashSet();
private int fromPort;
private int toPort;
private Multimap<String, String> groups = LinkedHashMultimap.create();
private String userId;
private String userIdGroupName;
private IpProtocol ipProtocol;
private Set<String> ipRanges = Sets.newLinkedHashSet();
private Builder<SecurityGroup> securityGroups = ImmutableSet.<SecurityGroup> 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<Set<SecurityGroup>> setContext(HttpRequest request) {
securityGroupHandler.setContext(request);
return super.setContext(request);
}
/**
* {@inheritDoc}
*/
@Override
public Set<SecurityGroup> 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.<String> 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();
}
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);
}
}
}

View File

@ -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<IpPermission> {
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);
}
}

View File

@ -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<SecurityGroup> {
protected final IpPermissionHandler ipPermissionHandler;
protected final Supplier<String> 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<String> defaultRegion) {
this.ipPermissionHandler = ipPermissionHandler;
this.defaultRegion = defaultRegion;
}
protected SecurityGroup.Builder<?> builder() {
return SecurityGroup.builder().region(region);
}
@Override
public HandlerForGeneratedRequestWithResult<SecurityGroup> 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);
}
}
}

View File

@ -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.<String> of("jclouds#" + group + "#"
assertEquals(Sets.newTreeSet(instance.getGroupNames()), ImmutableSortedSet.<String> of("jclouds#" + group + "#"
+ instance.getRegion(), group));
// make sure our dummy group has no rules

View File

@ -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());
}

View File

@ -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)

View File

@ -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"));
}
}

View File

@ -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)

View File

@ -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() {

View File

@ -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() {

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