diff --git a/all/pom.xml b/all/pom.xml index 8235fbb327..2e6577c690 100644 --- a/all/pom.xml +++ b/all/pom.xml @@ -44,15 +44,5 @@ jclouds-twitter ${project.version} - - ${project.groupId} - jclouds-chef - ${project.version} - - - ${project.groupId} - jclouds-opscodeplatform - ${project.version} - diff --git a/chef/compute/pom.xml b/chef/compute/pom.xml deleted file mode 100644 index f2a00803d4..0000000000 --- a/chef/compute/pom.xml +++ /dev/null @@ -1,185 +0,0 @@ - - - - 4.0.0 - - org.jclouds - jclouds-chef-project - 1.0-SNAPSHOT - ../pom.xml - - org.jclouds - jclouds-chef-compute - jclouds chef compute integration - provisions nodes with jclouds and kick's off chef to configure and integrate - - - YOUR_PREFERRED_PROVIDER - - - YOUR_ACCOUNT - YOUR_CREDENTIAL - - jcloudschef - YOUR_USER - ${user.home}/.chef/${jclouds.chef.identity}.pem - YOUR_ORG - https://api.opscode.com/organizations/${jclouds.opscodeplatform.org} - - - - - - jclouds-googlecode-deploy - http://jclouds.googlecode.com/svn/repo - - - jclouds-rimu-snapshots-nexus - https://oss.sonatype.org/content/repositories/snapshots - - true - - - - - - - ${project.groupId} - jclouds-chef - ${project.version} - - - ${project.groupId} - jclouds-compute - ${project.version} - - - ${project.groupId} - jclouds-jsch - ${project.version} - test - - - ${project.groupId} - jclouds-log4j - ${project.version} - test - - - log4j - log4j - 1.2.14 - test - - - ${project.groupId} - jclouds-core - ${project.version} - test-jar - test - - - ${project.groupId} - jclouds-compute - ${project.version} - test-jar - test - - - ${project.groupId} - jclouds-allcompute - ${project.version} - test - true - - - - - live - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration - integration-test - - test - - - - none - - - **/*LiveTest.java - - - - jclouds.compute.provider - ${jclouds.compute.provider} - - - jclouds.compute.endpoint - ${jclouds.compute.endpoint} - - - jclouds.compute.identity - ${jclouds.compute.identity} - - - jclouds.compute.credential - ${jclouds.compute.credential} - - - jclouds.compute.tag - ${jclouds.compute.tag} - - - jclouds.compute.credential - ${jclouds.compute.credential} - - - jclouds.chef.credential.pem - ${jclouds.chef.credential.pem} - - - jclouds.chef.endpoint - ${jclouds.chef.endpoint} - - - - - - - - - - - - diff --git a/chef/compute/src/test/java/org/jclouds/chef/compute/ChefComputeServiceLiveTest.java b/chef/compute/src/test/java/org/jclouds/chef/compute/ChefComputeServiceLiveTest.java deleted file mode 100644 index bbeaf583e0..0000000000 --- a/chef/compute/src/test/java/org/jclouds/chef/compute/ChefComputeServiceLiveTest.java +++ /dev/null @@ -1,165 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.compute; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.collect.Iterables.any; -import static com.google.common.collect.Iterables.concat; -import static com.google.common.collect.Iterables.getLast; -import static org.jclouds.chef.predicates.CookbookVersionPredicates.containsRecipe; -import static org.jclouds.chef.predicates.CookbookVersionPredicates.containsRecipes; -import static org.jclouds.compute.options.TemplateOptions.Builder.runScript; -import static org.testng.Assert.assertEquals; - -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.util.List; -import java.util.Properties; - -import org.jclouds.chef.ChefContext; -import org.jclouds.chef.ChefContextFactory; -import org.jclouds.chef.domain.CookbookVersion; -import org.jclouds.chef.util.RunListBuilder; -import org.jclouds.compute.ComputeServiceContext; -import org.jclouds.compute.ComputeServiceContextFactory; -import org.jclouds.compute.RunNodesException; -import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.predicates.NodePredicates; -import org.jclouds.io.Payload; -import org.jclouds.logging.log4j.config.Log4JLoggingModule; -import org.jclouds.ssh.jsch.config.JschSshClientModule; -import org.jclouds.util.Utils; -import org.testng.annotations.AfterGroups; -import org.testng.annotations.BeforeGroups; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableSet; -import com.google.inject.Module; - -/** - * - * @author Adrian Cole - */ -@Test(groups = "live", testName = "chef.ChefComputeServiceLiveTest") -public class ChefComputeServiceLiveTest { - - private ComputeServiceContext computeContext; - private ChefContext chefContext; - private String tag; - private String clientName; - private String chefEndpoint; - private Iterable nodes; - - @BeforeGroups(groups = { "live" }) - public void setupAll() throws FileNotFoundException, IOException { - tag = System.getProperty("jclouds.compute.tag") != null ? System.getProperty("jclouds.compute.tag") - : "jcloudschef"; - String computeProvider = checkNotNull(System.getProperty("jclouds.compute.provider"), "jclouds.compute.provider"); - String computeEndpoint = System.getProperty("jclouds.compute.endpoint"); - String computeIdentity = checkNotNull(System.getProperty("jclouds.compute.identity"), "jclouds.compute.identity"); - String computeCredential = checkNotNull(System.getProperty("jclouds.compute.credential"), - "jclouds.compute.credential"); - chefEndpoint = checkNotNull(System.getProperty("jclouds.chef.endpoint"), "jclouds.chef.endpoint"); - String chefIdentity = checkNotNull(System.getProperty("jclouds.chef.identity"), "jclouds.chef.identity"); - String chefCredentialFile = System.getProperty("jclouds.chef.credential.pem"); - if (chefCredentialFile == null || chefCredentialFile.equals("")) - chefCredentialFile = System.getProperty("user.home") + "/.chef/" + chefIdentity + ".pem"; - - Properties props = new Properties(); - props.setProperty(computeProvider + ".identity", computeIdentity); - props.setProperty(computeProvider + ".credential", computeCredential); - props.setProperty("chef.endpoint", chefEndpoint); - props.setProperty("chef.identity", chefIdentity); - props.setProperty("chef.credential.file", chefCredentialFile); - - if (computeEndpoint != null && !computeEndpoint.trim().equals("")) - props.setProperty(computeProvider + ".endpoint", computeEndpoint); - - computeContext = new ComputeServiceContextFactory().createContext(computeProvider, ImmutableSet.of( - new Log4JLoggingModule(), getSshModule()), props); - - chefContext = new ChefContextFactory().createContext(ImmutableSet. of(new Log4JLoggingModule()), props); - } - - protected Module getSshModule() { - return new JschSshClientModule(); - } - - @Test - public void testCanUpdateRunList() throws IOException { - String recipe = "apache2"; - - Iterable cookbookVersions = chefContext.getChefService().listCookbookVersions(); - - if (any(cookbookVersions, containsRecipe(recipe))) { - List runList = new RunListBuilder().addRecipe(recipe).build(); - chefContext.getChefService().updateRunListForTag(runList, tag); - assertEquals(chefContext.getChefService().getRunListForTag(tag), runList); - } else { - assert false : String.format("recipe %s not in %s", recipe, cookbookVersions); - } - - // TODO move this to a unit test - assert any(cookbookVersions, containsRecipe("apache2::mod_proxy")); - assert any(cookbookVersions, containsRecipes("apache2", "apache2::mod_proxy", "apache2::mod_proxy_http")); - assert !any(cookbookVersions, containsRecipe("apache2::bar")); - assert !any(cookbookVersions, containsRecipe("foo::bar")); - } - - @Test(dependsOnMethods = "testCanUpdateRunList") - public void testRunNodesWithBootstrap() throws IOException { - - Payload bootstrap = chefContext.getChefService().createClientAndBootstrapScriptForTag(tag); - - try { - nodes = computeContext.getComputeService().runNodesWithTag(tag, 1, runScript(bootstrap)); - } catch (RunNodesException e) { - nodes = concat(e.getSuccessfulNodes(), e.getNodeErrors().keySet()); - } - - for (NodeMetadata node : nodes) { - URI uri = URI.create("http://" + getLast(node.getPublicAddresses())); - InputStream content = computeContext.utils().http().get(uri); - String string = Utils.toStringAndClose(content); - assert string.indexOf("It works!") >= 0 : string; - } - - } - - @AfterGroups(groups = { "live" }) - public void teardownCompute() { - if (computeContext != null) { - computeContext.getComputeService().destroyNodesMatching(NodePredicates.withTag(tag)); - computeContext.close(); - } - } - - @AfterGroups(groups = { "live" }) - public void teardownChef() { - if (chefContext != null) { - chefContext.getChefService().cleanupStaleNodesAndClients(tag + "-", 1); - if (clientName != null && chefContext.getApi().clientExists(clientName)) - chefContext.getApi().deleteClient(clientName); - chefContext.close(); - } - } -} diff --git a/chef/compute/src/test/resources/log4j.xml b/chef/compute/src/test/resources/log4j.xml deleted file mode 100755 index 66bf053d21..0000000000 --- a/chef/compute/src/test/resources/log4j.xml +++ /dev/null @@ -1,203 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/chef/core/pom.xml b/chef/core/pom.xml deleted file mode 100644 index a30bf22b18..0000000000 --- a/chef/core/pom.xml +++ /dev/null @@ -1,120 +0,0 @@ - - - - 4.0.0 - - org.jclouds - jclouds-chef-project - 1.0-SNAPSHOT - ../pom.xml - - org.jclouds - jclouds-chef - jclouds Chef core - jclouds components to access Chef - - - scm:svn:http://jclouds.googlecode.com/svn/trunk/chef - scm:svn:https://jclouds.googlecode.com/svn/trunk/chef - http://jclouds.googlecode.com/svn/trunk/chef - - - - - - jclouds-googlecode-deploy - http://jclouds.googlecode.com/svn/repo - - false - - - - jclouds-rimu-snapshots-nexus - https://oss.sonatype.org/content/repositories/snapshots - - true - - - - - - chef-validator - /etc/chef/validation.pem - http://localhost:4000 - ${jclouds.chef.identity} - ${jclouds.chef.rsa-key} - ${jclouds.chef.endpoint} - - - - - ${project.groupId} - jclouds-core - ${project.version} - - - - org.bouncycastle - bcprov-jdk15 - 1.44 - - - ${project.groupId} - jclouds-scriptbuilder - ${project.version} - - - ${project.groupId} - jclouds-core - ${project.version} - test-jar - test - - - log4j - log4j - 1.2.14 - test - - - ${project.groupId} - jclouds-log4j - ${project.version} - test - - - org.danlarkin - clojure-json - 1.1 - true - - - - ${project.groupId} - jclouds-blobstore - ${project.version} - true - - - diff --git a/chef/core/src/main/clojure/org/jclouds/chef.clj b/chef/core/src/main/clojure/org/jclouds/chef.clj deleted file mode 100644 index 6503e6d59c..0000000000 --- a/chef/core/src/main/clojure/org/jclouds/chef.clj +++ /dev/null @@ -1,261 +0,0 @@ -; -; -; Copyright (C) 2010 Cloud Conscious, LLC. -; -; ==================================================================== -; Licensed under the Apache License, Version 2.0 (the "License"); -; you may not use this file except in compliance with the License. -; You may obtain a copy of the License at -; -; http://www.apache.org/licenses/LICENSE-2.0 -; -; Unless required by applicable law or agreed to in writing, software -; distributed under the License is distributed on an "AS IS" BASIS, -; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -; See the License for the specific language governing permissions and -; limitations under the License. -; ==================================================================== -; - -(ns - #^{:author "Adrian Cole" - :doc "A clojure binding to the jclouds chef interface. - -Here's a quick example of how to manipulate a databag on the Opscode Platform, -which is basically Chef Server as a Service. - -(use 'org.jclouds.chef) - -(def client \"YOUR_CLIENT\") -;; load the rsa key from ~/.chef/CLIENT_NAME.pem -(def credential (load-pem client)) - -;; create a connection to the opscode platform -(def chef (chef-service \"chef\" client credential :chef.endpoint \"https://api.opscode.com/organizations/YOUR_ORG\")) - -(with-chef-service [chef] - (create-databag \"cluster-config\") - (update-databag-item \"cluster-config\" {:id \"master\" :name \"myhost.com\"})) - -;; note that you can create your chef connection like this to do in-memory testing -(def chef (chef-service \"transientchef\" \"\" \"\")) - -See http://code.google.com/p/jclouds for details."} - org.jclouds.chef - (:use [org.jclouds.core]) - (:require (org.danlarkin [json :as json])) - (:import - java.util.Properties - [org.jclouds.chef ChefClient - ChefService ChefContext ChefContextFactory] - [org.jclouds.chef.domain DatabagItem])) -(try - (use '[clojure.contrib.reflect :only [get-field]]) - (catch Exception e - (use '[clojure.contrib.java-utils - :only [wall-hack-field] - :rename {wall-hack-field get-field}]))) - -(defn load-pem - "get the pem associated with the supplied identity" - ([#^String identity] - (slurp (str (. System getProperty "user.home") "/.chef/" identity ".pem")))) - -;; TODO find a way to pass the chef provider by default - -(defn chef-service - "Create a logged in context to a chef server. - -provider \"chef\" is a remote connection, and you can pass the option - :chef.endpoint \"https://url\" to override the endpoint - -provider \"transientchef\" is for in-memory when you are looking to do -unit testing" - ([#^String provider #^String identity #^String credential & options] - (let [module-keys (set (keys module-lookup)) - ext-modules (filter #(module-keys %) options) - opts (apply hash-map (filter #(not (module-keys %)) options))] - (.. (ChefContextFactory.) - (createContext provider identity credential - (apply modules (concat ext-modules (opts :extensions))) - (reduce #(do (.put %1 (name (first %2)) (second %2)) %1) - (Properties.) (dissoc opts :extensions))) - (getChefService))))) - -(defn chef-context - "Returns a chef context from a chef service." - [#^ChefService chef] - (.getContext chef)) - -(defn chef-service? - [object] - (instance? ChefService object)) - -(defn chef-context? - [object] - (instance? ChefContext object)) - -(defn as-chef-service - "Tries hard to produce a chef service from its input arguments" - [& args] - (cond - (chef-service? (first args)) (first args) - (chef-context? (first args)) (.getChefService (first args)) - :else (apply chef-service args))) - -(defn as-chef-api - "Tries hard to produce a chef client from its input arguments" - [& args] - (cond - (chef-service? (first args)) (.getApi (.getContext (first args))) - (chef-context? (first args)) (.getApi (first args)) - :else (.getApi (.getContext (apply chef-service args))))) - -(def *chef*) - -(defmacro with-chef-service - "Specify the default chef service" - [[& chef-or-args] & body] - `(binding [*chef* (as-chef-service ~@chef-or-args)] - ~@body)) - -(defn nodes - "Retrieve the names of the existing nodes in your chef server." - ([] (nodes *chef*)) - ([#^ChefService chef] - (seq (.listNodes (as-chef-api chef))))) - -(defn nodes-with-details - "Retrieve the existing nodes in your chef server including all details." - ([] (nodes *chef*)) - ([#^ChefService chef] - (seq (.listNodes chef)))) - -(defn clients - "Retrieve the names of the existing clients in your chef server." - ([] (clients *chef*)) - ([#^ChefService chef] - (seq (.listClients (as-chef-api chef))))) - -(defn clients-with-details - "Retrieve the existing clients in your chef server including all details." - ([] (clients *chef*)) - ([#^ChefService chef] - (seq (.listClients chef)))) - -(defn cookbooks - "Retrieve the names of the existing cookbooks in your chef server." - ([] (cookbooks *chef*)) - ([#^ChefService chef] - (seq (.listCookbooks (as-chef-api chef))))) - -(defn cookbook-versions - "Retrieve the versions of an existing cookbook in your chef server." - ([name] (cookbook-versions *chef*)) - ([#^ChefService name chef] - (seq (.getVersionsOfCookbook (as-chef-api chef) name)))) - -(defn cookbook-versions-with-details - "Retrieve the existing cookbook versions in your chef server including all details." - ([] (cookbook-versions *chef*)) - ([#^ChefService chef] - (seq (.listCookbookVersions chef)))) - -(defn update-run-list - "Updates the run-list associated with a tag" - ([run-list tag] (update-run-list run-list tag *chef*)) - ([run-list tag #^ChefService chef] - (.updateRunListForTag chef run-list tag))) - -(defn run-list - "Retrieves the run-list associated with a tag" - ([tag] (run-list tag *chef*)) - ([tag #^ChefService chef] - (seq (.getRunListForTag chef tag)))) - -(defn create-bootstrap - "creates a client and bootstrap script associated with a tag" - ([tag] (create-bootstrap tag *chef*)) - ([tag #^ChefService chef] - (.createClientAndBootstrapScriptForTag chef tag))) - -(defn databags - "Retrieve the names of the existing data bags in your chef server." - ([] (databags *chef*)) - ([#^ChefService chef] - (seq (.listDatabags (as-chef-api chef))))) - -(defn databag-exists? - "Predicate to check presence of a databag" - ([databag-name] - (databag-exists? databag-name *chef*)) - ([databag-name #^ChefService chef] - (.databagExists (as-chef-api chef) databag-name))) - -(defn delete-databag - "Delete a data bag, including its items" - ([databag] - (delete-databag databag *chef*)) - ([databag chef] - (.deleteDatabag (as-chef-api chef) databag))) - -(defn create-databag - "create a data bag" - ([databag] - (create-databag databag *chef*)) - ([databag chef] - (.createDatabag (as-chef-api chef) databag))) - -(defn databag-items - "Retrieve the names of the existing items in a data bag in your chef server." - ([databag] - (databag-items databag *chef*)) - ([databag chef] - (seq (.listDatabagItems (as-chef-api chef) databag)))) - -(defn databag-item-exists? - "Predicate to check presence of a databag item" - ([databag-name item-id] - (databag-item-exists? databag-name item-id *chef*)) - ([databag-name item-id #^ChefService chef] - (.databagExists (as-chef-api chef) databag-name item-id))) - -(defn databag-item - "Get an item from the data bag" - ([databag item-id] - (databag-item databag item-id *chef*)) - ([databag item-id chef] - (json/decode-from-str (str (.getDatabagItem (as-chef-api chef) databag item-id))))) - -(defn delete-databag-item - "delete an item from the data bag" - ([databag item-id] - (delete-databag-item databag item-id *chef*)) - ([databag item-id chef] - (.deleteDatabagItem (as-chef-api chef) databag item-id))) - -(defn create-databag-item - "put a new item in the data bag. Note the Map you pass must have an :id key: - -ex. - (create-databag-item \"cluster-config\" {:id \"master\" :name \"myhost.com\"}))" - ([databag value] - (create-databag-item databag value *chef*)) - ([databag value chef] - (let [value-str (json/encode-to-str value)] - (let [value-json (json/decode-from-str value-str)] - (.createDatabagItem (as-chef-api chef) databag - (DatabagItem. (get value-json :id) value-str)))))) - -(defn update-databag-item - "updates an existing item in the data bag. Note the Map you pass must have an :id key: - -ex. - (update-databag-item \"cluster-config\" {:id \"master\" :name \"myhost.com\"}))" - ([databag value] - (update-databag-item databag value *chef*)) - ([databag value chef] - (let [value-str (json/encode-to-str value)] - (let [value-json (json/decode-from-str value-str)] - (.updateDatabagItem (as-chef-api chef) databag - (DatabagItem. (get value-json :id) value-str)))))) diff --git a/chef/core/src/main/java/org/jclouds/chef/ChefAsyncClient.java b/chef/core/src/main/java/org/jclouds/chef/ChefAsyncClient.java deleted file mode 100644 index 25749777d3..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/ChefAsyncClient.java +++ /dev/null @@ -1,420 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef; - -import java.util.List; -import java.util.Set; - -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.HEAD; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.core.MediaType; - -import org.jclouds.chef.binders.BindChecksumsToJsonPayload; -import org.jclouds.chef.binders.BindClientnameToJsonPayload; -import org.jclouds.chef.binders.BindGenerateKeyForClientToJsonPayload; -import org.jclouds.chef.binders.BindIsCompletedToJsonPayload; -import org.jclouds.chef.binders.BindNameToJsonPayload; -import org.jclouds.chef.binders.DatabagItemId; -import org.jclouds.chef.binders.NodeName; -import org.jclouds.chef.binders.RoleName; -import org.jclouds.chef.domain.Client; -import org.jclouds.chef.domain.CookbookVersion; -import org.jclouds.chef.domain.DatabagItem; -import org.jclouds.chef.domain.Node; -import org.jclouds.chef.domain.Role; -import org.jclouds.chef.domain.Sandbox; -import org.jclouds.chef.domain.SearchResult; -import org.jclouds.chef.domain.UploadSandbox; -import org.jclouds.chef.filters.SignedHeaderAuth; -import org.jclouds.chef.functions.ParseKeySetFromJson; -import org.jclouds.chef.functions.ParseSearchClientsFromJson; -import org.jclouds.chef.functions.ParseSearchDatabagFromJson; -import org.jclouds.chef.functions.ParseSearchNodesFromJson; -import org.jclouds.chef.functions.ParseSearchRolesFromJson; -import org.jclouds.rest.annotations.BinderParam; -import org.jclouds.rest.annotations.ExceptionParser; -import org.jclouds.rest.annotations.Headers; -import org.jclouds.rest.annotations.ParamParser; -import org.jclouds.rest.annotations.RequestFilters; -import org.jclouds.rest.annotations.ResponseParser; -import org.jclouds.rest.annotations.Unwrap; -import org.jclouds.rest.binders.BindToJsonPayload; -import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404; -import org.jclouds.rest.functions.ReturnFalseOnNotFoundOr404; -import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; -import org.jclouds.rest.functions.ReturnVoidOnNotFoundOr404; - -import com.google.common.util.concurrent.ListenableFuture; - -/** - * Provides asynchronous access to Chef via their REST API. - *

- * - * @see ChefClient - * @see - * @author Adrian Cole - */ -@RequestFilters(SignedHeaderAuth.class) -@Headers(keys = "X-Chef-Version", values = ChefAsyncClient.VERSION) -@Consumes(MediaType.APPLICATION_JSON) -public interface ChefAsyncClient { - public static final String VERSION = "0.9.8"; - - /** - * @see ChefClient#getUploadSandboxForChecksums - */ - @POST - @Path("/sandboxes") - ListenableFuture getUploadSandboxForChecksums( - @BinderParam(BindChecksumsToJsonPayload.class) Set> md5s); - - @PUT - @Path("") - ListenableFuture uploadContent(@BinderParam(BindChecksumsToJsonPayload.class) Set> md5s); - - /** - * @see ChefClient#commitSandbox - */ - @PUT - @Path("/sandboxes/{id}") - ListenableFuture commitSandbox(@PathParam("id") String id, - @BinderParam(BindIsCompletedToJsonPayload.class) boolean isCompleted); - - /** - * @see ChefCookbooks#listCookbooks - */ - @GET - @Path("/cookbooks") - @ResponseParser(ParseKeySetFromJson.class) - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listCookbooks(); - - /** - * @see ChefClient#updateCookbook - */ - @PUT - @Path("/cookbooks/{cookbookname}/{version}") - ListenableFuture updateCookbook(@PathParam("cookbookname") String cookbookName, - @PathParam("version") String version, @BinderParam(BindToJsonPayload.class) CookbookVersion cookbook); - - /** - * @see ChefCookbook#deleteCookbook(String) - */ - @DELETE - @Path("/cookbooks/{cookbookname}/{version}") - @ExceptionParser(ReturnNullOnNotFoundOr404.class) - ListenableFuture deleteCookbook(@PathParam("cookbookname") String cookbookName, - @PathParam("version") String version); - - /** - * @see ChefCookbook#getVersionsOfCookbook - */ - @GET - @Path("/cookbooks/{cookbookname}") - @Unwrap - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> getVersionsOfCookbook(@PathParam("cookbookname") String cookbookName); - - /** - * @see ChefCookbook#getCookbook - */ - @GET - @Path("/cookbooks/{cookbookname}/{version}") - @ExceptionParser(ReturnNullOnNotFoundOr404.class) - ListenableFuture getCookbook(@PathParam("cookbookname") String cookbookName, - @PathParam("version") String version); - - /** - * @see ChefClient#createClient - */ - @POST - @Path("/clients") - ListenableFuture createClient(@BinderParam(BindClientnameToJsonPayload.class) String clientname); - - /** - * @see ChefClient#generateKeyForClient - */ - @PUT - @Path("/clients/{clientname}") - ListenableFuture generateKeyForClient( - @PathParam("clientname") @BinderParam(BindGenerateKeyForClientToJsonPayload.class) String clientname); - - /** - * @see ChefClient#clientExists - */ - @HEAD - @Path("/clients/{clientname}") - @ExceptionParser(ReturnFalseOnNotFoundOr404.class) - ListenableFuture clientExists(@PathParam("clientname") String clientname); - - /** - * @see ChefClient#getClient - */ - @GET - @Path("/clients/{clientname}") - @ExceptionParser(ReturnNullOnNotFoundOr404.class) - ListenableFuture getClient(@PathParam("clientname") String clientname); - - /** - * @see ChefClient#deleteClient - */ - @DELETE - @Path("/clients/{clientname}") - @ExceptionParser(ReturnNullOnNotFoundOr404.class) - ListenableFuture deleteClient(@PathParam("clientname") String clientname); - - /** - * @see ChefClient#listClients - */ - @GET - @Path("/clients") - @ResponseParser(ParseKeySetFromJson.class) - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listClients(); - - /** - * @see ChefClient#createNode - */ - @POST - @Path("/nodes") - ListenableFuture createNode(@BinderParam(BindToJsonPayload.class) Node node); - - /** - * @see ChefClient#updateNode - */ - @PUT - @Path("/nodes/{nodename}") - ListenableFuture updateNode( - @PathParam("nodename") @ParamParser(NodeName.class) @BinderParam(BindToJsonPayload.class) Node node); - - /** - * @see ChefNode#nodeExists - */ - @HEAD - @Path("/nodes/{nodename}") - @ExceptionParser(ReturnFalseOnNotFoundOr404.class) - ListenableFuture nodeExists(@PathParam("nodename") String nodename); - - /** - * @see ChefNode#getNode - */ - @GET - @Path("/nodes/{nodename}") - @ExceptionParser(ReturnNullOnNotFoundOr404.class) - ListenableFuture getNode(@PathParam("nodename") String nodename); - - /** - * @see ChefNode#deleteNode - */ - @DELETE - @Path("/nodes/{nodename}") - @ExceptionParser(ReturnNullOnNotFoundOr404.class) - ListenableFuture deleteNode(@PathParam("nodename") String nodename); - - /** - * @see ChefNode#listNodes - */ - @GET - @Path("/nodes") - @ResponseParser(ParseKeySetFromJson.class) - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listNodes(); - - /** - * @see ChefClient#createRole - */ - @POST - @Path("/roles") - ListenableFuture createRole(@BinderParam(BindToJsonPayload.class) Role role); - - /** - * @see ChefClient#updateRole - */ - @PUT - @Path("/roles/{rolename}") - ListenableFuture updateRole( - @PathParam("rolename") @ParamParser(RoleName.class) @BinderParam(BindToJsonPayload.class) Role role); - - /** - * @see ChefRole#roleExists - */ - @HEAD - @Path("/roles/{rolename}") - @ExceptionParser(ReturnFalseOnNotFoundOr404.class) - ListenableFuture roleExists(@PathParam("rolename") String rolename); - - /** - * @see ChefRole#getRole - */ - @GET - @Path("/roles/{rolename}") - @ExceptionParser(ReturnNullOnNotFoundOr404.class) - ListenableFuture getRole(@PathParam("rolename") String rolename); - - /** - * @see ChefRole#deleteRole - */ - @DELETE - @Path("/roles/{rolename}") - @ExceptionParser(ReturnNullOnNotFoundOr404.class) - ListenableFuture deleteRole(@PathParam("rolename") String rolename); - - /** - * @see ChefRole#listRoles - */ - @GET - @Path("/roles") - @ResponseParser(ParseKeySetFromJson.class) - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listRoles(); - - /** - * @see ChefClient#listDatabags - */ - @GET - @Path("/data") - @ResponseParser(ParseKeySetFromJson.class) - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listDatabags(); - - /** - * @see ChefClient#createDatabag - */ - @POST - @Path("/data") - ListenableFuture createDatabag(@BinderParam(BindNameToJsonPayload.class) String databagName); - - /** - * @see ChefClient#databagExists - */ - @HEAD - @Path("/data/{name}") - @ExceptionParser(ReturnFalseOnNotFoundOr404.class) - ListenableFuture databagExists(@PathParam("name") String databagName); - - /** - * @see ChefClient#deleteDatabag - */ - @DELETE - @Path("/data/{name}") - @ExceptionParser(ReturnVoidOnNotFoundOr404.class) - ListenableFuture deleteDatabag(@PathParam("name") String databagName); - - /** - * @see ChefClient#listDatabagItems - */ - @GET - @Path("/data/{name}") - @ResponseParser(ParseKeySetFromJson.class) - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listDatabagItems(@PathParam("name") String databagName); - - /** - * @see ChefClient#createDatabagItem - */ - @POST - @Path("/data/{databagName}") - ListenableFuture createDatabagItem(@PathParam("databagName") String databagName, - @BinderParam(BindToJsonPayload.class) DatabagItem databagItem); - - /** - * @see ChefClient#updateDatabagItem - */ - @PUT - @Path("/data/{databagName}/{databagItemId}") - ListenableFuture updateDatabagItem( - @PathParam("databagName") String databagName, - @PathParam("databagItemId") @ParamParser(DatabagItemId.class) @BinderParam(BindToJsonPayload.class) DatabagItem item); - - /** - * @see ChefClient#databagItemExists - */ - @HEAD - @Path("/data/{databagName}/{databagItemId}") - @ExceptionParser(ReturnFalseOnNotFoundOr404.class) - ListenableFuture databagItemExists(@PathParam("databagName") String databagName, - @PathParam("databagItemId") String databagItemId); - - /** - * @see ChefClient#getDatabagItem - */ - @GET - @Path("/data/{databagName}/{databagItemId}") - @ExceptionParser(ReturnNullOnNotFoundOr404.class) - ListenableFuture getDatabagItem(@PathParam("databagName") String databagName, - @PathParam("databagItemId") String databagItemId); - - /** - * @see ChefClient#deleteDatabagItem - */ - @DELETE - @Path("/data/{databagName}/{databagItemId}") - @ExceptionParser(ReturnNullOnNotFoundOr404.class) - ListenableFuture deleteDatabagItem(@PathParam("databagName") String databagName, - @PathParam("databagItemId") String databagItemId); - - /** - * @see ChefClient#listSearchIndexes - */ - @GET - @Path("/search") - @ResponseParser(ParseKeySetFromJson.class) - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listSearchIndexes(); - - /** - * @see ChefClient#searchRoles - */ - @GET - @Path("/search/role") - @ResponseParser(ParseSearchRolesFromJson.class) - ListenableFuture> searchRoles(); - - /** - * @see ChefClient#searchClients - */ - @GET - @Path("/search/client") - @ResponseParser(ParseSearchClientsFromJson.class) - ListenableFuture> searchClients(); - - /** - * @see ChefClient#searchNodes - */ - @GET - @Path("/search/node") - @ResponseParser(ParseSearchNodesFromJson.class) - ListenableFuture> searchNodes(); - - /** - * @see ChefClient#searchDatabag - */ - @GET - @Path("/search/{databagName}") - @ResponseParser(ParseSearchDatabagFromJson.class) - ListenableFuture> searchDatabag( - @PathParam("databagName") String databagName); -} diff --git a/chef/core/src/main/java/org/jclouds/chef/ChefClient.java b/chef/core/src/main/java/org/jclouds/chef/ChefClient.java deleted file mode 100644 index 6ffd44128a..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/ChefClient.java +++ /dev/null @@ -1,533 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef; - -import java.util.List; -import java.util.Set; -import java.util.concurrent.TimeUnit; - -import org.jclouds.chef.domain.Client; -import org.jclouds.chef.domain.CookbookVersion; -import org.jclouds.chef.domain.DatabagItem; -import org.jclouds.chef.domain.Node; -import org.jclouds.chef.domain.Role; -import org.jclouds.chef.domain.Sandbox; -import org.jclouds.chef.domain.SearchResult; -import org.jclouds.chef.domain.UploadSandbox; -import org.jclouds.concurrent.Timeout; -import org.jclouds.http.HttpResponseException; -import org.jclouds.rest.AuthorizationException; -import org.jclouds.rest.annotations.BinderParam; -import org.jclouds.rest.binders.BindToJsonPayload; - -/** - * Provides synchronous access to Chef. - *

- * - * @see ChefAsyncClient - * @see - * @author Adrian Cole - */ -@Timeout(duration = 30, timeUnit = TimeUnit.SECONDS) -public interface ChefClient { - /** - * - * FIXME Comment this - * - * @param md5s - * raw md5s; uses {@code Bytes.asList()} and {@code - * Bytes.toByteArray()} as necessary - * @return - */ - UploadSandbox getUploadSandboxForChecksums(Set> md5s); - - Sandbox commitSandbox(String id, boolean isCompleted); - - /** - * - * @return a list of all the cookbook names - * @throws AuthorizationException - *

- * "401 Unauthorized" if the caller is not a recognized user. - *

- * "403 Forbidden" if you do not have permission to see the - * cookbook list. - */ - Set listCookbooks(); - - /** - * Creates or updates (uploads) a cookbook //TODO document - * - * @param cookbookName - * @throws HttpResponseException - * "409 Conflict" if the cookbook already exists - */ - @Timeout(duration = 10, timeUnit = TimeUnit.MINUTES) - CookbookVersion updateCookbook(String cookbookName, String version, CookbookVersion cookbook); - - /** - * deletes an existing cookbook. - * - * @return last state of the client you deleted or null, if not found - * @throws AuthorizationException - *

- * "401 Unauthorized" if you are not a recognized user. - *

- * "403 Forbidden" if you do not have Delete rights on the - * cookbook. - */ - CookbookVersion deleteCookbook(String cookbookName, String version); - - /** - * - * @return the versions of a cookbook or null, if not found - * - * @throws AuthorizationException - *

- * "401 Unauthorized" if the caller is not a recognized user. - *

- * "403 Forbidden" if the caller is not authorized to view the - * cookbook. - */ - Set getVersionsOfCookbook(String cookbookName); - - /** - * Returns a description of the cookbook, with links to all of its component - * parts, and the metadata. - * - * @return the cookbook or null, if not found - * - * @throws AuthorizationException - *

- * "401 Unauthorized" if the caller is not a recognized user. - *

- * "403 Forbidden" if the caller is not authorized to view the - * cookbook. - */ - CookbookVersion getCookbook(String cookbookName, String version); - - /** - * creates a new client - * - * @return the private key of the client. You can then use this client name - * and private key to access the Opscode API. - * @throws AuthorizationException - *

- * "401 Unauthorized" if the caller is not a recognized user. - *

- * "403 Forbidden" if the caller is not authorized to create a - * client. - * @throws HttpResponseException - * "409 Conflict" if the client already exists - */ - @Timeout(duration = 120, timeUnit = TimeUnit.SECONDS) - Client createClient(String name); - - /** - * generate a new key-pair for this client, and return the new private key in - * the response body. - * - * @return the new private key - * - * @throws AuthorizationException - *

- * "401 Unauthorized" if the caller is not a recognized user. - *

- * "403 Forbidden" if the caller is not authorized to modify the - * client. - */ - @Timeout(duration = 120, timeUnit = TimeUnit.SECONDS) - Client generateKeyForClient(String name); - - /** - * @return list of client names. - * - * @throws AuthorizationException - *

- * "401 Unauthorized" if you are not a recognized user. - *

- * "403 Forbidden" if you do not have rights to list clients. - */ - Set listClients(); - - /** - * - * @return true if the specified client name exists. - * - * @throws AuthorizationException - *

- * "401 Unauthorized" if you are not a recognized user. - *

- * "403 Forbidden" if you do not have rights to view the client. - */ - boolean clientExists(String name); - - /** - * deletes an existing client. - * - * @return last state of the client you deleted or null, if not found - * - * @throws AuthorizationException - *

- * "401 Unauthorized" if you are not a recognized user. - *

- * "403 Forbidden" if you do not have Delete rights on the client. - */ - Client deleteClient(String name); - - /** - * gets an existing client. - * - * @throws AuthorizationException - *

- * "401 Unauthorized" if you are not a recognized user. - *

- * "403 Forbidden" if you do not have view rights on the client. - */ - Client getClient(String name); - - /** - * creates a new node - * - * @return //TODO - * @throws AuthorizationException - *

- * "401 Unauthorized" if the caller is not a recognized user. - *

- * "403 Forbidden" if the caller is not authorized to create a - * node. - * @throws HttpResponseException - * "409 Conflict" if the node already exists - */ - @Timeout(duration = 120, timeUnit = TimeUnit.SECONDS) - void createNode(Node node); - - /** - * Creates or updates (uploads) a node //TODO document - * - * @param nodeName - * @throws HttpResponseException - * "409 Conflict" if the node already exists - */ - @Timeout(duration = 10, timeUnit = TimeUnit.MINUTES) - Node updateNode(Node node); - - /** - * @return list of node names. - * - * @throws AuthorizationException - *

- * "401 Unauthorized" if you are not a recognized user. - *

- * "403 Forbidden" if you do not have rights to list nodes. - */ - Set listNodes(); - - /** - * - * @return true if the specified node name exists. - * - * @throws AuthorizationException - *

- * "401 Unauthorized" if you are not a recognized user. - *

- * "403 Forbidden" if you do not have rights to view the node. - */ - boolean nodeExists(String name); - - /** - * deletes an existing node. - * - * @return last state of the node you deleted or null, if not found - * - * @throws AuthorizationException - *

- * "401 Unauthorized" if you are not a recognized user. - *

- * "403 Forbidden" if you do not have Delete rights on the node. - */ - Node deleteNode(String name); - - /** - * gets an existing node. - * - * @throws AuthorizationException - *

- * "401 Unauthorized" if you are not a recognized user. - *

- * "403 Forbidden" if you do not have view rights on the node. - */ - Node getNode(String name); - - /** - * creates a new role - * - * @return //TODO - * @throws AuthorizationException - *

- * "401 Unauthorized" if the caller is not a recognized user. - *

- * "403 Forbidden" if the caller is not authorized to create a - * role. - * @throws HttpResponseException - * "409 Conflict" if the role already exists - */ - @Timeout(duration = 120, timeUnit = TimeUnit.SECONDS) - void createRole(Role role); - - /** - * Creates or updates (uploads) a role //TODO document - * - * @param roleName - * @throws HttpResponseException - * "409 Conflict" if the role already exists - */ - @Timeout(duration = 10, timeUnit = TimeUnit.MINUTES) - Role updateRole(Role role); - - /** - * @return list of role names. - * - * @throws AuthorizationException - *

- * "401 Unauthorized" if you are not a recognized user. - *

- * "403 Forbidden" if you do not have rights to list roles. - */ - Set listRoles(); - - /** - * - * @return true if the specified role name exists. - * - * @throws AuthorizationException - *

- * "401 Unauthorized" if you are not a recognized user. - *

- * "403 Forbidden" if you do not have rights to view the role. - */ - boolean roleExists(String name); - - /** - * deletes an existing role. - * - * @return last state of the role you deleted or null, if not found - * - * @throws AuthorizationException - *

- * "401 Unauthorized" if you are not a recognized user. - *

- * "403 Forbidden" if you do not have Delete rights on the role. - */ - Role deleteRole(String name); - - /** - * gets an existing role. - * - * @throws AuthorizationException - *

- * "401 Unauthorized" if you are not a recognized user. - *

- * "403 Forbidden" if you do not have view rights on the role. - */ - Role getRole(String name); - - /** - * lists databags available to the client - * - * @throws AuthorizationException - *

- * "401 Unauthorized" if you are not a recognized user. - *

- * "403 Forbidden" if you do not have view rights on the databag. - */ - Set listDatabags(); - - /** - * creates a databag. - * - * @throws AuthorizationException - *

- * "401 Unauthorized" if you are not a recognized user. - *

- * "403 Forbidden" if you do not have view rights on the databag. - */ - void createDatabag(String databagName); - - /** - * true is a databag exists - * - * @throws AuthorizationException - *

- * "401 Unauthorized" if you are not a recognized user. - *

- * "403 Forbidden" if you do not have view rights on the databag. - */ - boolean databagExists(String databagName); - - /** - * Delete a data bag, including its items - * - * @throws AuthorizationException - *

- * "401 Unauthorized" if you are not a recognized user. - *

- * "403 Forbidden" if you do not have view rights on the databag. - */ - void deleteDatabag(String databagName); - - /** - * Show the items in a data bag. - * - * @throws AuthorizationException - *

- * "401 Unauthorized" if you are not a recognized user. - *

- * "403 Forbidden" if you do not have view rights on the databag. - */ - Set listDatabagItems(String databagName); - - /** - * Create a data bag item in the data bag - * - * @throws AuthorizationException - *

- * "401 Unauthorized" if you are not a recognized user. - *

- * "403 Forbidden" if you do not have view rights on the databag. - *

- * @throws IllegalStateException - * if the item already exists - * - */ - DatabagItem createDatabagItem(String databagName, @BinderParam(BindToJsonPayload.class) DatabagItem node); - - /** - * Update (or create if not exists) a data bag item - * - * @throws AuthorizationException - *

- * "401 Unauthorized" if you are not a recognized user. - *

- * "403 Forbidden" if you do not have view rights on the databag. - */ - DatabagItem updateDatabagItem(String databagName, DatabagItem item); - - /** - * determines if a databag item exists - * - * @throws AuthorizationException - *

- * "401 Unauthorized" if you are not a recognized user. - *

- * "403 Forbidden" if you do not have view rights on the databag. - */ - boolean databagItemExists(String databagName, String databagItemId); - - /** - * gets an existing databag item. - * - * @throws AuthorizationException - *

- * "401 Unauthorized" if you are not a recognized user. - *

- * "403 Forbidden" if you do not have view rights on the databag. - */ - DatabagItem getDatabagItem(String databagName, String databagItemId); - - /** - * Delete a data bag item - * - * @throws AuthorizationException - *

- * "401 Unauthorized" if you are not a recognized user. - *

- * "403 Forbidden" if you do not have view rights on the databag. - */ - DatabagItem deleteDatabagItem(String databagName, String databagItemId); - - /** - * Show indexes you can search on - *

- * By default, the "role", "node" and "client" indexes will always be - * available. - *

- * Note that the search indexes may lag behind the most current data by at - * least 10 seconds at any given time - so if you need to write data and - * immediately query it, you likely need to produce an artificial delay (or - * simply retry until the data is available.) - * - * @throws AuthorizationException - *

- * "401 Unauthorized" if you are not a recognized user. - *

- * "403 Forbidden" if you do not have view rights on the databag. - */ - Set listSearchIndexes(); - - /** - * search all roles. - *

- * Note that without any request parameters this will return all of the data - * within the index. - * - * @return The response contains the total number of rows that matched your - * request, the position this result set returns (useful for paging) - * and the rows themselves. - */ - SearchResult searchRoles(); - - /** - * search all clients. - *

- * Note that without any request parameters this will return all of the data - * within the index. - * - * @return The response contains the total number of rows that matched your - * request, the position this result set returns (useful for paging) - * and the rows themselves. - */ - SearchResult searchClients(); - - /** - * search all nodes. - *

- * Note that without any request parameters this will return all of the data - * within the index. - * - * @return The response contains the total number of rows that matched your - * request, the position this result set returns (useful for paging) - * and the rows themselves. - */ - SearchResult searchNodes(); - - /** - * search all items in a databag. - *

- * Note that without any request parameters this will return all of the data - * within the index. - * - * @return The response contains the total number of rows that matched your - * request, the position this result set returns (useful for paging) - * and the rows themselves. - */ - SearchResult searchDatabag(String databagName); - -} diff --git a/chef/core/src/main/java/org/jclouds/chef/ChefContext.java b/chef/core/src/main/java/org/jclouds/chef/ChefContext.java deleted file mode 100644 index 5954a25f82..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/ChefContext.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef; - -import org.jclouds.chef.internal.ChefContextImpl; -import org.jclouds.rest.RestContext; - -import com.google.inject.ImplementedBy; - -/** - * - * - * @author Adrian Cole - * - */ -@ImplementedBy(ChefContextImpl.class) -public interface ChefContext extends RestContext{ - - ChefService getChefService(); - -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/ChefContextBuilder.java b/chef/core/src/main/java/org/jclouds/chef/ChefContextBuilder.java deleted file mode 100644 index 00963a25fb..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/ChefContextBuilder.java +++ /dev/null @@ -1,65 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef; - -import java.util.List; -import java.util.Properties; - -import org.jclouds.chef.config.ChefRestClientModule; -import org.jclouds.ohai.OhaiContextBuilder; - -import com.google.inject.Injector; -import com.google.inject.Module; - -/** - * @author Adrian Cole - */ -public class ChefContextBuilder extends OhaiContextBuilder { - - public ChefContextBuilder(Properties props) { - super(ChefClient.class, ChefAsyncClient.class, props); - } - - @Override - protected void addClientModule(List modules) { - modules.add(new ChefRestClientModule()); - } - - @Override - public Injector buildInjector() { - addOhaiModuleIfNotPresent(); - return super.buildInjector(); - } - - /** - * {@inheritDoc} - */ - @Override - public ChefContextBuilder withModules(Iterable modules) { - return (ChefContextBuilder) super.withModules(modules); - } - - @SuppressWarnings("unchecked") - @Override - public ChefContext buildContext() { - Injector injector = buildInjector(); - return injector.getInstance(ChefContext.class); - } -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/ChefContextFactory.java b/chef/core/src/main/java/org/jclouds/chef/ChefContextFactory.java deleted file mode 100644 index 919437c1bc..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/ChefContextFactory.java +++ /dev/null @@ -1,180 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef; - -import static org.jclouds.rest.RestContextFactory.createContextBuilder; -import static org.jclouds.util.Utils.propagateAuthorizationOrOriginalException; - -import java.util.Properties; - -import javax.annotation.Nullable; - -import org.jclouds.rest.RestContextBuilder; -import org.jclouds.rest.RestContextFactory; -import org.jclouds.rest.RestContextFactory.ContextSpec; - -import com.google.inject.Module; - -/** - * Helper class to instantiate {@code ChefContext} instances. - * - * @author Adrian Cole - */ -public class ChefContextFactory { - - private final RestContextFactory contextFactory; - - /** - * Initializes with the default properties built-in to jclouds. This is - * typically stored in the classpath resource {@code rest.properties} - * - * @see RestContextFactory#getPropertiesFromResource - */ - public ChefContextFactory() { - this(new RestContextFactory()); - } - - /** - * Finds definitions in the specified properties. - */ - public ChefContextFactory(Properties properties) { - this(new RestContextFactory(properties)); - } - - /** - * - * Uses the supplied RestContextFactory to create {@link ChefContext}s - */ - public ChefContextFactory(RestContextFactory restContextFactory) { - this.contextFactory = restContextFactory; - } - - public static ChefContext buildContextUnwrappingExceptions(RestContextBuilder builder) { - try { - return (ChefContext) builder.buildContext(); - } catch (Exception e) { - return propagateAuthorizationOrOriginalException(e); - } - } - - /** - * @see #createContext(String, String, String) - */ - public ChefContext createContext(String identity, String credential) { - return createContext("chef", identity, credential); - } - - /** - * @see RestContextFactory#createContextBuilder(String, String, String) - */ - public ChefContext createContext(String provider, String identity, String credential) { - RestContextBuilder builder = RestContextBuilder.class.cast(contextFactory.createContextBuilder(provider, - identity, credential)); - return buildContextUnwrappingExceptions(builder); - } - - /** - * @see #createContext(String, Properties) - */ - public ChefContext createContext(Properties overrides) { - return createContext("chef", overrides); - } - - /** - * @see RestContextFactory#createContextBuilder(String, Properties) - */ - public ChefContext createContext(String provider, Properties overrides) { - RestContextBuilder builder = RestContextBuilder.class.cast(contextFactory.createContextBuilder(provider, - overrides)); - return buildContextUnwrappingExceptions(builder); - } - - /** - * @see #createContext(String, Iterable, Properties) - */ - public ChefContext createContext(Iterable modules, Properties overrides) { - return createContext("chef", modules, overrides); - } - - /** - * @see RestContextFactory#createContextBuilder(String, Iterable, Properties) - */ - public ChefContext createContext(String provider, Iterable modules, Properties overrides) { - RestContextBuilder builder = RestContextBuilder.class.cast(contextFactory.createContextBuilder(provider, - modules, overrides)); - return buildContextUnwrappingExceptions(builder); - } - - /** - * @see #createContext(String,String,String,Iterable) - */ - public ChefContext createContext(@Nullable String identity, @Nullable String credential, - Iterable modules) { - return createContext("chef", identity, credential, modules); - } - - /** - * @see RestContextFactory#createContextBuilder(String,String String, - * Iterable) - */ - public ChefContext createContext(String provider, @Nullable String identity, @Nullable String credential, - Iterable modules) { - RestContextBuilder builder = RestContextBuilder.class.cast(contextFactory.createContextBuilder(provider, - identity, credential, modules)); - return buildContextUnwrappingExceptions(builder); - } - - /** - * @see #createContext(String,String, String, Iterable, Properties) - */ - public ChefContext createContext(@Nullable String identity, @Nullable String credential, - Iterable modules, Properties overrides) { - return createContext("chef", identity, credential, modules, overrides); - } - - /** - * @see RestContextFactory#createContextBuilder(String,String,String, - * Iterable, Properties) - */ - public ChefContext createContext(String provider, @Nullable String identity, @Nullable String credential, - Iterable modules, Properties overrides) { - RestContextBuilder builder = RestContextBuilder.class.cast(contextFactory.createContextBuilder(provider, - identity, credential, modules, overrides)); - return buildContextUnwrappingExceptions(builder); - } - - /** - * @see RestContextFactory#createContextBuilder(ContextSpec) - */ - public ChefContext createContext(ContextSpec contextSpec) { - RestContextBuilder builder = RestContextBuilder.class.cast(createContextBuilder(contextSpec)); - return buildContextUnwrappingExceptions(builder); - - } - - /** - * @see RestContextFactory#createContextBuilder(ContextSpec, Properties) - */ - public ChefContext createContext(ContextSpec contextSpec, Properties overrides) { - RestContextBuilder builder = RestContextBuilder.class.cast(createContextBuilder(contextSpec, overrides)); - return buildContextUnwrappingExceptions(builder); - } - -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/ChefPropertiesBuilder.java b/chef/core/src/main/java/org/jclouds/chef/ChefPropertiesBuilder.java deleted file mode 100644 index 644842704a..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/ChefPropertiesBuilder.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef; - -import static org.jclouds.Constants.PROPERTY_ENDPOINT; - -import java.util.Properties; - -import org.jclouds.chef.internal.BaseChefPropertiesBuilder; - -/** - * Builds properties used in Chef Clients - * - * @author Adrian Cole - */ -public class ChefPropertiesBuilder extends BaseChefPropertiesBuilder { - @Override - protected Properties defaultProperties() { - Properties properties = super.defaultProperties(); - properties.setProperty(PROPERTY_ENDPOINT, "http://localhost:4000"); - return properties; - } - - public ChefPropertiesBuilder(Properties properties) { - super(properties); - } - -} diff --git a/chef/core/src/main/java/org/jclouds/chef/ChefService.java b/chef/core/src/main/java/org/jclouds/chef/ChefService.java deleted file mode 100644 index 12c968daec..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/ChefService.java +++ /dev/null @@ -1,122 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef; - -import java.io.IOException; -import java.io.InputStream; -import java.util.List; - -import org.jclouds.chef.domain.Client; -import org.jclouds.chef.domain.CookbookVersion; -import org.jclouds.chef.domain.Node; -import org.jclouds.chef.internal.BaseChefService; -import org.jclouds.io.Payload; - -import com.google.common.base.Predicate; -import com.google.common.io.InputSupplier; -import com.google.inject.ImplementedBy; - -/** - * Provides high level chef operations - * - * @author Adrian Cole - */ -@ImplementedBy(BaseChefService.class) -public interface ChefService { - /** - * @return a reference to the context that created this. - */ - ChefContext getContext(); - - byte[] encrypt(InputSupplier supplier) throws IOException; - - byte[] decrypt(InputSupplier supplier) throws IOException; - - void cleanupStaleNodesAndClients(String prefix, int secondsStale); - - /** - * - * @param nodeName - * @param runList - * @return node sent to the server containing the automatic attributes - */ - Node createNodeAndPopulateAutomaticAttributes(String nodeName, Iterable runList); - - /** - * Creates all steps necessary to bootstrap and run the chef client. - * - * @param tag - * corresponds to a configured - * {@link org.jclouds.chef.reference.ChefConstants#CHEF_BOOTSTRAP_DATABAG databag} - * where run_list and other information are stored - * @return boot script - * @see #updateRunListForTag - */ - Payload createClientAndBootstrapScriptForTag(String tag); - - /** - * assigns a run list to all nodes bootstrapped with a certain tag - * - * @param runList - * list of recipes or roles to assign. syntax is {@code recipe[name]} and {@code - * role[name]} - * - * @param tag - * corresponds to a configured - * {@link org.jclouds.chef.reference.ChefConstants#CHEF_BOOTSTRAP_DATABAG databag} - * where run_list and other information are stored - * @see #makeChefClientBootstrapScriptForTag - */ - void updateRunListForTag(Iterable runList, String tag); - - /** - * @param tag - * corresponds to a configured - * {@link org.jclouds.chef.reference.ChefConstants#CHEF_BOOTSTRAP_DATABAG databag} - * where run_list and other information are stored - * @return run list for all nodes bootstrapped with a certain tag - * @see #updateRunListForTag - */ - List getRunListForTag(String tag); - - void deleteAllNodesInList(Iterable names); - - Iterable listNodes(); - - Iterable listNodesMatching(Predicate nodeNameSelector); - - Iterable listNodesNamed(Iterable names); - - void deleteAllClientsInList(Iterable names); - - Iterable listClientsDetails(); - - Iterable listClientsDetailsMatching(Predicate clientNameSelector); - - Iterable listClientsNamed(Iterable names); - - Iterable listCookbookVersions(); - - Iterable listCookbookVersionsMatching(Predicate cookbookNameSelector); - - Iterable listCookbookVersionsNamed(Iterable cookbookNames); - - void updateAutomaticAttributesOnNode(String nodeName); -} diff --git a/chef/core/src/main/java/org/jclouds/chef/binders/BindChecksumsToJsonPayload.java b/chef/core/src/main/java/org/jclouds/chef/binders/BindChecksumsToJsonPayload.java deleted file mode 100644 index 6952bb2e1b..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/binders/BindChecksumsToJsonPayload.java +++ /dev/null @@ -1,62 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.binders; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; - -import java.util.List; -import java.util.Set; - -import javax.inject.Singleton; -import javax.ws.rs.core.MediaType; - -import org.jclouds.crypto.CryptoStreams; -import org.jclouds.http.HttpRequest; -import org.jclouds.rest.binders.BindToStringPayload; - -import com.google.common.primitives.Bytes; - -/** - * - * - * @author Adrian Cole - */ -@Singleton -public class BindChecksumsToJsonPayload extends BindToStringPayload { - - @SuppressWarnings("unchecked") - public void bindToRequest(HttpRequest request, Object input) { - checkArgument(checkNotNull(input, "input") instanceof Set, "this binder is only valid for Set!"); - - Set> md5s = (Set>) input; - - StringBuilder builder = new StringBuilder(); - builder.append("{\"checksums\":{"); - - for (List md5 : md5s) - builder.append(String.format("\"%s\":null,", CryptoStreams.hex(Bytes.toArray(md5)))); - builder.deleteCharAt(builder.length() - 1); - builder.append("}}"); - super.bindToRequest(request, builder.toString()); - request.getPayload().setContentType(MediaType.APPLICATION_JSON); - } - -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/binders/BindClientnameToJsonPayload.java b/chef/core/src/main/java/org/jclouds/chef/binders/BindClientnameToJsonPayload.java deleted file mode 100644 index 9588585117..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/binders/BindClientnameToJsonPayload.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.binders; - -import javax.inject.Singleton; -import javax.ws.rs.core.MediaType; - -import org.jclouds.http.HttpRequest; -import org.jclouds.rest.binders.BindToStringPayload; - -/** - * - * @author Adrian Cole - * - */ -@Singleton -public class BindClientnameToJsonPayload extends BindToStringPayload { - - @Override - public void bindToRequest(HttpRequest request, Object payload) { - super.bindToRequest(request, String.format("{\"clientname\":\"%s\"}", payload)); - request.getPayload().setContentType(MediaType.APPLICATION_JSON); - } - -} diff --git a/chef/core/src/main/java/org/jclouds/chef/binders/BindGenerateKeyForClientToJsonPayload.java b/chef/core/src/main/java/org/jclouds/chef/binders/BindGenerateKeyForClientToJsonPayload.java deleted file mode 100644 index 349813051a..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/binders/BindGenerateKeyForClientToJsonPayload.java +++ /dev/null @@ -1,43 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.binders; - -import javax.inject.Singleton; -import javax.ws.rs.core.MediaType; - -import org.jclouds.http.HttpRequest; -import org.jclouds.rest.binders.BindToStringPayload; - -/** - * - * @author Adrian Cole - * - */ -@Singleton -public class BindGenerateKeyForClientToJsonPayload extends BindToStringPayload { - - @Override - public void bindToRequest(HttpRequest request, Object payload) { - super.bindToRequest(request, String.format("{\"clientname\":\"%s\", \"private_key\": true}", - payload)); - request.getPayload().setContentType(MediaType.APPLICATION_JSON); - } - -} diff --git a/chef/core/src/main/java/org/jclouds/chef/binders/BindIsCompletedToJsonPayload.java b/chef/core/src/main/java/org/jclouds/chef/binders/BindIsCompletedToJsonPayload.java deleted file mode 100644 index 7a15928040..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/binders/BindIsCompletedToJsonPayload.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.binders; - -import javax.inject.Singleton; -import javax.ws.rs.core.MediaType; - -import org.jclouds.http.HttpRequest; -import org.jclouds.rest.binders.BindToStringPayload; - -/** - * - * @author Adrian Cole - * - */ -@Singleton -public class BindIsCompletedToJsonPayload extends BindToStringPayload { - - @Override - public void bindToRequest(HttpRequest request, Object value) { - super.bindToRequest(request, String.format("{\"is_completed\":\"%s\"}", value)); - request.getPayload().setContentType(MediaType.APPLICATION_JSON); - } - -} diff --git a/chef/core/src/main/java/org/jclouds/chef/binders/BindNameToJsonPayload.java b/chef/core/src/main/java/org/jclouds/chef/binders/BindNameToJsonPayload.java deleted file mode 100644 index 6d05e520dc..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/binders/BindNameToJsonPayload.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.binders; - -import javax.inject.Singleton; -import javax.ws.rs.core.MediaType; - -import org.jclouds.http.HttpRequest; -import org.jclouds.rest.binders.BindToStringPayload; - -/** - * - * @author Adrian Cole - * - */ -@Singleton -public class BindNameToJsonPayload extends BindToStringPayload { - - @Override - public void bindToRequest(HttpRequest request, Object payload) { - super.bindToRequest(request, String.format("{\"name\":\"%s\"}", payload)); - request.getPayload().setContentType(MediaType.APPLICATION_JSON); - } - -} diff --git a/chef/core/src/main/java/org/jclouds/chef/binders/DatabagItemId.java b/chef/core/src/main/java/org/jclouds/chef/binders/DatabagItemId.java deleted file mode 100644 index 3f4383a530..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/binders/DatabagItemId.java +++ /dev/null @@ -1,39 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.binders; - -import javax.inject.Singleton; - -import org.jclouds.chef.domain.DatabagItem; - -import com.google.common.base.Function; - -/** - * - * @author Adrian Cole - */ -@Singleton -public class DatabagItemId implements Function { - - public String apply(Object from) { - return ((DatabagItem) from).getId(); - } - -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/binders/NodeName.java b/chef/core/src/main/java/org/jclouds/chef/binders/NodeName.java deleted file mode 100644 index 92ee1e3147..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/binders/NodeName.java +++ /dev/null @@ -1,39 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.binders; - -import javax.inject.Singleton; - -import org.jclouds.chef.domain.Node; - -import com.google.common.base.Function; - -/** - * - * @author Adrian Cole - */ -@Singleton -public class NodeName implements Function { - - public String apply(Object from) { - return ((Node) from).getName(); - } - -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/binders/RoleName.java b/chef/core/src/main/java/org/jclouds/chef/binders/RoleName.java deleted file mode 100644 index 1d2f29a18b..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/binders/RoleName.java +++ /dev/null @@ -1,39 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.binders; - -import javax.inject.Singleton; - -import org.jclouds.chef.domain.Role; - -import com.google.common.base.Function; - -/** - * - * @author Adrian Cole - */ -@Singleton -public class RoleName implements Function { - - public String apply(Object from) { - return ((Role) from).getName(); - } - -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/config/BaseChefRestClientModule.java b/chef/core/src/main/java/org/jclouds/chef/config/BaseChefRestClientModule.java deleted file mode 100644 index 8e8b48d760..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/config/BaseChefRestClientModule.java +++ /dev/null @@ -1,116 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.config; - -import static org.jclouds.Constants.PROPERTY_CREDENTIAL; -import static org.jclouds.Constants.PROPERTY_SESSION_INTERVAL; - -import java.io.IOException; -import java.security.PrivateKey; -import java.security.spec.InvalidKeySpecException; -import java.util.Map; -import java.util.concurrent.TimeUnit; - -import javax.inject.Named; -import javax.inject.Singleton; - -import org.jclouds.chef.handlers.ChefClientErrorRetryHandler; -import org.jclouds.chef.handlers.ChefErrorHandler; -import org.jclouds.crypto.Crypto; -import org.jclouds.crypto.Pems; -import org.jclouds.date.DateService; -import org.jclouds.date.TimeStamp; -import org.jclouds.http.HttpErrorHandler; -import org.jclouds.http.HttpRetryHandler; -import org.jclouds.http.RequiresHttp; -import org.jclouds.http.annotation.ClientError; -import org.jclouds.http.annotation.Redirection; -import org.jclouds.http.annotation.ServerError; -import org.jclouds.io.InputSuppliers; -import org.jclouds.rest.ConfiguresRestClient; -import org.jclouds.rest.config.RestClientModule; - -import com.google.common.base.Supplier; -import com.google.common.base.Suppliers; -import com.google.inject.Provides; - -/** - * Configures the Chef connection. - * - * @author Adrian Cole - */ -@RequiresHttp -@ConfiguresRestClient -public class BaseChefRestClientModule extends RestClientModule { - - protected BaseChefRestClientModule(Class syncClientType, Class asyncClientType) { - super(syncClientType, asyncClientType); - } - - protected BaseChefRestClientModule(Class syncClientType, Class asyncClientType, - Map, Class> delegates) { - super(syncClientType, asyncClientType, delegates); - } - - @Provides - @TimeStamp - protected String provideTimeStamp(@TimeStamp Supplier cache) { - return cache.get(); - } - - /** - * borrowing concurrency code to ensure that caching takes place properly - */ - @Provides - @TimeStamp - Supplier provideTimeStampCache(@Named(PROPERTY_SESSION_INTERVAL) long seconds, final DateService dateService) { - return Suppliers.memoizeWithExpiration(new Supplier() { - public String get() { - return dateService.iso8601SecondsDateFormat(); - } - }, seconds, TimeUnit.SECONDS); - } - - @Provides - @Singleton - public PrivateKey provideKey(Crypto crypto, @Named(PROPERTY_CREDENTIAL) String pem) throws InvalidKeySpecException, - IOException { - return crypto.rsaKeyFactory().generatePrivate(Pems.privateKeySpec(InputSuppliers.of(pem))); - } - - @Override - protected void bindErrorHandlers() { - bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to(ChefErrorHandler.class); - bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to(ChefErrorHandler.class); - bind(HttpErrorHandler.class).annotatedWith(ServerError.class).to(ChefErrorHandler.class); - } - - @Override - protected void bindRetryHandlers() { - bind(HttpRetryHandler.class).annotatedWith(ClientError.class).to(ChefClientErrorRetryHandler.class); - } - - @Override - protected void configure() { - install(new ChefParserModule()); - super.configure(); - } - -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/config/ChefParserModule.java b/chef/core/src/main/java/org/jclouds/chef/config/ChefParserModule.java deleted file mode 100644 index 75d558b1bc..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/config/ChefParserModule.java +++ /dev/null @@ -1,226 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.config; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkState; - -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.lang.reflect.Type; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.security.spec.InvalidKeySpecException; -import java.util.Map; - -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - -import org.jclouds.Constants; -import org.jclouds.chef.domain.DatabagItem; -import org.jclouds.crypto.Crypto; -import org.jclouds.crypto.Pems; -import org.jclouds.io.InputSuppliers; -import org.jclouds.json.Json; -import org.jclouds.json.config.GsonModule.DateAdapter; -import org.jclouds.json.config.GsonModule.Iso8601DateAdapter; - -import com.google.common.base.Throwables; -import com.google.common.collect.ImmutableMap; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonLiteral; -import com.google.gson.JsonParseException; -import com.google.gson.JsonSerializationContext; -import com.google.gson.JsonSerializer; -import com.google.inject.AbstractModule; -import com.google.inject.ImplementedBy; -import com.google.inject.Provides; - -/** - * - * - * @author Adrian Cole - */ -public class ChefParserModule extends AbstractModule { - @ImplementedBy(PrivateKeyAdapterImpl.class) - public static interface PrivateKeyAdapter extends JsonDeserializer { - - } - - @Singleton - public static class PrivateKeyAdapterImpl implements PrivateKeyAdapter { - private final Crypto crypto; - - @Inject - PrivateKeyAdapterImpl(Crypto crypto) { - this.crypto = crypto; - } - - @Override - public PrivateKey deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) - throws JsonParseException { - String keyText = json.getAsString().replaceAll("\\n", "\n"); - try { - return crypto.rsaKeyFactory().generatePrivate(Pems.privateKeySpec(InputSuppliers.of(keyText))); - } catch (UnsupportedEncodingException e) { - Throwables.propagate(e); - return null; - } catch (InvalidKeySpecException e) { - Throwables.propagate(e); - return null; - } catch (IOException e) { - Throwables.propagate(e); - return null; - } - } - } - - @ImplementedBy(PublicKeyAdapterImpl.class) - public static interface PublicKeyAdapter extends JsonDeserializer { - - } - - @Singleton - public static class PublicKeyAdapterImpl implements PublicKeyAdapter { - private final Crypto crypto; - - @Inject - PublicKeyAdapterImpl(Crypto crypto) { - this.crypto = crypto; - } - - @Override - public PublicKey deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) - throws JsonParseException { - String keyText = json.getAsString().replaceAll("\\n", "\n"); - try { - return crypto.rsaKeyFactory().generatePublic(Pems.publicKeySpec(InputSuppliers.of(keyText))); - } catch (UnsupportedEncodingException e) { - Throwables.propagate(e); - return null; - } catch (InvalidKeySpecException e) { - Throwables.propagate(e); - return null; - } catch (IOException e) { - Throwables.propagate(e); - return null; - } - } - } - - @ImplementedBy(X509CertificateAdapterImpl.class) - public static interface X509CertificateAdapter extends JsonDeserializer { - - } - - @Singleton - public static class X509CertificateAdapterImpl implements X509CertificateAdapter { - private final Crypto crypto; - - @Inject - X509CertificateAdapterImpl(Crypto crypto) { - this.crypto = crypto; - } - - @Override - public X509Certificate deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) - throws JsonParseException { - String keyText = json.getAsString().replaceAll("\\n", "\n"); - try { - return Pems.x509Certificate(InputSuppliers.of(keyText), crypto.certFactory()); - } catch (UnsupportedEncodingException e) { - Throwables.propagate(e); - return null; - } catch (IOException e) { - Throwables.propagate(e); - return null; - } catch (CertificateException e) { - Throwables.propagate(e); - return null; - } - } - } - - @ImplementedBy(DataBagItemAdapterImpl.class) - public static interface DataBagItemAdapter extends JsonSerializer, JsonDeserializer { - - } - - @Singleton - public static class DataBagItemAdapterImpl implements DataBagItemAdapter { - private final Json json; - - @Inject - DataBagItemAdapterImpl(Json json) { - this.json = json; - } - - @Override - public JsonElement serialize(DatabagItem src, Type typeOfSrc, JsonSerializationContext context) { - String text = src.toString(); - try { - IdHolder idHolder = json.fromJson(text, IdHolder.class); - if (idHolder.id == null) - text = text.replaceFirst("\\{", String.format("{\"id\":\"%s\",", src.getId())); - else - checkArgument(src.getId().equals(idHolder.id), "incorrect id in databagItem text, should be %s: was %s", - src.getId(), idHolder.id); - return new JsonLiteral(text); - } catch (JsonParseException e) { - throw new IllegalArgumentException(String.format( - "databag item must be a json hash ex. {\"id\":\"item1\",\"my_key\":\"my_data\"}; was %s", text), e); - } - } - - @Override - public DatabagItem deserialize(JsonElement jsonElement, Type typeOfT, JsonDeserializationContext context) - throws JsonParseException { - String text = jsonElement.toString(); - IdHolder idHolder = json.fromJson(text, IdHolder.class); - checkState(idHolder.id != null, - "databag item must be a json hash ex. {\"id\":\"item1\",\"my_key\":\"my_data\"}; was %s", text); - text = text.replaceFirst(String.format("\\{\"id\"[ ]?:\"%s\",", idHolder.id), "{"); - return new DatabagItem(idHolder.id, text); - } - } - - private static class IdHolder { - private String id; - } - - @Provides - @Singleton - @Named(Constants.PROPERTY_GSON_ADAPTERS) - public Map provideCustomAdapterBindings(DataBagItemAdapter adapter, PrivateKeyAdapter privateAdapter, - PublicKeyAdapter publicAdapter, X509CertificateAdapter certAdapter) { - return ImmutableMap. of(DatabagItem.class, adapter, PrivateKey.class, privateAdapter, - PublicKey.class, publicAdapter, X509Certificate.class, certAdapter); - } - - @Override - protected void configure() { - bind(DateAdapter.class).to(Iso8601DateAdapter.class); - } -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/config/ChefRestClientModule.java b/chef/core/src/main/java/org/jclouds/chef/config/ChefRestClientModule.java deleted file mode 100644 index c845cb1487..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/config/ChefRestClientModule.java +++ /dev/null @@ -1,72 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.config; - -import java.util.List; -import java.util.Map; - -import javax.inject.Singleton; - -import org.jclouds.chef.ChefAsyncClient; -import org.jclouds.chef.ChefClient; -import org.jclouds.chef.domain.Client; -import org.jclouds.chef.functions.ClientForTag; -import org.jclouds.chef.functions.RunListForTag; -import org.jclouds.chef.statements.InstallChefGems; -import org.jclouds.http.RequiresHttp; -import org.jclouds.rest.ConfiguresRestClient; -import org.jclouds.scriptbuilder.domain.Statement; - -import com.google.common.collect.MapMaker; -import com.google.inject.Provides; -import com.google.inject.name.Names; - -/** - * Configures the Chef connection. - * - * @author Adrian Cole - */ -@RequiresHttp -@ConfiguresRestClient -public class ChefRestClientModule extends BaseChefRestClientModule { - - public ChefRestClientModule() { - super(ChefClient.class, ChefAsyncClient.class); - } - - @Provides - @Singleton - Map> runListForTag(RunListForTag runListForTag) { - return new MapMaker().makeComputingMap(runListForTag); - } - - @Provides - @Singleton - Map tagToClient(ClientForTag tagToClient) { - return new MapMaker().makeComputingMap(tagToClient); - } - - @Override - protected void configure() { - bind(Statement.class).annotatedWith(Names.named("installChefGems")).to(InstallChefGems.class); - super.configure(); - } - -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/domain/Attribute.java b/chef/core/src/main/java/org/jclouds/chef/domain/Attribute.java deleted file mode 100644 index 9a2fe6e584..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/domain/Attribute.java +++ /dev/null @@ -1,167 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.domain; - -import java.util.List; -import java.util.Set; - -import org.jclouds.domain.JsonBall; - -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; -import com.google.gson.annotations.SerializedName; - -/** - * Cookbook object. - * - * @author Adrian Cole - */ -public class Attribute { - - private String required; - private boolean calculated; - private List choice = Lists.newArrayList(); - @SerializedName("default") - private JsonBall defaultValue; - private String type; - private List recipes = Lists.newArrayList(); - @SerializedName("display_name") - private String displayName; - private String description; - - public Attribute(String required, boolean calculated, Set choice, JsonBall defaultValue, String type, - List recipes, String displayName, String description) { - this.required = required; - this.calculated = calculated; - Iterables.addAll(this.choice, choice); - this.defaultValue = defaultValue; - this.type = type; - Iterables.addAll(this.recipes, recipes); - this.displayName = displayName; - this.description = description; - } - - public Attribute() { - } - - public String getRequired() { - return required; - } - - public boolean isCalculated() { - return calculated; - } - - public List getChoice() { - return choice; - } - - public JsonBall getDefaultValue() { - return defaultValue; - } - - public String getType() { - return type; - } - - public List getRecipes() { - return recipes; - } - - public String getDisplayName() { - return displayName; - } - - public String getDescription() { - return description; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + (calculated ? 1231 : 1237); - result = prime * result + ((choice == null) ? 0 : choice.hashCode()); - result = prime * result + ((defaultValue == null) ? 0 : defaultValue.hashCode()); - result = prime * result + ((description == null) ? 0 : description.hashCode()); - result = prime * result + ((displayName == null) ? 0 : displayName.hashCode()); - result = prime * result + ((recipes == null) ? 0 : recipes.hashCode()); - result = prime * result + ((required == null) ? 0 : required.hashCode()); - result = prime * result + ((type == null) ? 0 : type.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; - Attribute other = (Attribute) obj; - if (calculated != other.calculated) - return false; - if (choice == null) { - if (other.choice != null) - return false; - } else if (!choice.equals(other.choice)) - return false; - if (defaultValue == null) { - if (other.defaultValue != null) - return false; - } else if (!defaultValue.equals(other.defaultValue)) - return false; - if (description == null) { - if (other.description != null) - return false; - } else if (!description.equals(other.description)) - return false; - if (displayName == null) { - if (other.displayName != null) - return false; - } else if (!displayName.equals(other.displayName)) - return false; - if (recipes == null) { - if (other.recipes != null) - return false; - } else if (!recipes.equals(other.recipes)) - return false; - if (required == null) { - if (other.required != null) - return false; - } else if (!required.equals(other.required)) - return false; - if (type == null) { - if (other.type != null) - return false; - } else if (!type.equals(other.type)) - return false; - return true; - } - - @Override - public String toString() { - return "Attribute [calculated=" + calculated + ", choice=" + choice + ", defaultValue=" + defaultValue - + ", description=" + description + ", displayName=" + displayName + ", recipes=" + recipes + ", required=" - + required + ", type=" + type + "]"; - } - -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/domain/ChecksumStatus.java b/chef/core/src/main/java/org/jclouds/chef/domain/ChecksumStatus.java deleted file mode 100644 index 620a9e3127..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/domain/ChecksumStatus.java +++ /dev/null @@ -1,84 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.domain; - -import java.net.URI; - -import com.google.gson.annotations.SerializedName; - -/** - * - * @author Adrian Cole - */ -public class ChecksumStatus { - private URI url; - @SerializedName("needs_upload") - private boolean needsUpload; - - public ChecksumStatus(URI url, boolean needsUpload) { - this.url = url; - this.needsUpload = needsUpload; - } - - public ChecksumStatus() { - - } - - public URI getUrl() { - return url; - } - - public boolean needsUpload() { - return needsUpload; - } - - @Override - public String toString() { - return "ChecksumStatus [needsUpload=" + needsUpload + ", url=" + url + "]"; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + (needsUpload ? 1231 : 1237); - result = prime * result + ((url == null) ? 0 : url.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; - ChecksumStatus other = (ChecksumStatus) obj; - if (needsUpload != other.needsUpload) - return false; - if (url == null) { - if (other.url != null) - return false; - } else if (!url.equals(other.url)) - return false; - return true; - } -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/domain/Client.java b/chef/core/src/main/java/org/jclouds/chef/domain/Client.java deleted file mode 100644 index b106d49f78..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/domain/Client.java +++ /dev/null @@ -1,140 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.domain; - -import java.security.PrivateKey; -import java.security.cert.X509Certificate; - -import javax.annotation.Nullable; - -import com.google.gson.annotations.SerializedName; - -/** - * Client object. - * - * @author Adrian Cole - */ -public class Client { - private X509Certificate certificate; - @SerializedName("private_key") - private PrivateKey privateKey; - private String orgname; - private String clientname; - private String name; - private boolean validator; - - // only for deserialization - Client() { - - } - - public PrivateKey getPrivateKey() { - return privateKey; - } - - public X509Certificate getCertificate() { - return certificate; - } - - public String getOrgname() { - return orgname; - } - - public String getClientname() { - return clientname; - } - - public String getName() { - return name; - } - - public boolean isValidator() { - return validator; - } - - @Override - public String toString() { - return "[name=" + name + ", clientname=" + clientname + ", orgname=" + orgname + ", isValidator=" + validator - + ", certificate=" + certificate + ", privateKey=" + (privateKey != null) + "]"; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((certificate == null) ? 0 : certificate.hashCode()); - result = prime * result + ((clientname == null) ? 0 : clientname.hashCode()); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((orgname == null) ? 0 : orgname.hashCode()); - result = prime * result + ((privateKey == null) ? 0 : privateKey.hashCode()); - result = prime * result + (validator ? 1231 : 1237); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Client other = (Client) obj; - if (certificate == null) { - if (other.certificate != null) - return false; - } else if (!certificate.equals(other.certificate)) - return false; - if (clientname == null) { - if (other.clientname != null) - return false; - } else if (!clientname.equals(other.clientname)) - return false; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - if (orgname == null) { - if (other.orgname != null) - return false; - } else if (!orgname.equals(other.orgname)) - return false; - if (privateKey == null) { - if (other.privateKey != null) - return false; - } else if (!privateKey.equals(other.privateKey)) - return false; - if (validator != other.validator) - return false; - return true; - } - - public Client(X509Certificate certificate, String orgname, String clientname, String name, boolean isValidator, - @Nullable PrivateKey privateKey) { - this.certificate = certificate; - this.orgname = orgname; - this.clientname = clientname; - this.name = name; - this.validator = isValidator; - this.privateKey = privateKey; - } - -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/domain/CookbookVersion.java b/chef/core/src/main/java/org/jclouds/chef/domain/CookbookVersion.java deleted file mode 100644 index 470c7b29d6..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/domain/CookbookVersion.java +++ /dev/null @@ -1,246 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.domain; - -import java.util.Set; - -import com.google.common.collect.Iterables; -import com.google.common.collect.Sets; -import com.google.gson.annotations.SerializedName; - -/** - * Cookbook object. - * - * @author Adrian Cole - */ -public class CookbookVersion { - - private String name; - private Set definitions = Sets.newLinkedHashSet(); - private Set attributes = Sets.newLinkedHashSet(); - private Set files = Sets.newLinkedHashSet(); - private Metadata metadata = new Metadata(); - private Set providers = Sets.newLinkedHashSet(); - @SerializedName("cookbook_name") - private String cookbookName; - private Set resources = Sets.newLinkedHashSet(); - private Set templates = Sets.newLinkedHashSet(); - private Set libraries = Sets.newLinkedHashSet(); - private String version; - private Set recipes = Sets.newLinkedHashSet(); - @SerializedName("root_files") - private Set rootFiles = Sets.newLinkedHashSet(); - - // internal - @SuppressWarnings("unused") - @SerializedName("json_class") - private String _jsonClass = "Chef::CookbookVersion"; - @SerializedName("chef_type") - @SuppressWarnings("unused") - private String _chefType = "cookbook_version"; - - public CookbookVersion(String cookbookName, String version) { - this.cookbookName = cookbookName; - this.version = version; - this.name = cookbookName + "-" + version; - } - - public CookbookVersion(String name, Set definitions, Set attributes, Set files, - Metadata metadata, Set providers, String cookbookName, Set resources, - Set templates, Set libraries, String version, Set recipes, - Set rootFiles) { - this.name = name; - Iterables.addAll(this.definitions, definitions); - Iterables.addAll(this.attributes, attributes); - Iterables.addAll(this.files, files); - this.metadata = metadata; - Iterables.addAll(this.providers, providers); - this.cookbookName = cookbookName; - Iterables.addAll(this.resources, resources); - Iterables.addAll(this.templates, templates); - Iterables.addAll(this.libraries, libraries); - this.version = version; - Iterables.addAll(this.recipes, recipes); - Iterables.addAll(this.rootFiles, rootFiles); - } - - // hidden but needs to be here for json deserialization to work - CookbookVersion() { - - } - - public String getName() { - return name; - } - - public Set getDefinitions() { - return definitions; - } - - public Set getAttributes() { - return attributes; - } - - public Set getFiles() { - return files; - } - - public Metadata getMetadata() { - return metadata; - } - - public Set getSuppliers() { - return providers; - } - - public String getCookbookName() { - return cookbookName; - } - - public Set getResources() { - return resources; - } - - public Set getTemplates() { - return templates; - } - - public Set getLibraries() { - return libraries; - } - - public String getVersion() { - return version; - } - - public Set getRecipes() { - return recipes; - } - - public Set getRootFiles() { - return rootFiles; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((attributes == null) ? 0 : attributes.hashCode()); - result = prime * result + ((cookbookName == null) ? 0 : cookbookName.hashCode()); - result = prime * result + ((definitions == null) ? 0 : definitions.hashCode()); - result = prime * result + ((files == null) ? 0 : files.hashCode()); - result = prime * result + ((libraries == null) ? 0 : libraries.hashCode()); - result = prime * result + ((metadata == null) ? 0 : metadata.hashCode()); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((providers == null) ? 0 : providers.hashCode()); - result = prime * result + ((recipes == null) ? 0 : recipes.hashCode()); - result = prime * result + ((resources == null) ? 0 : resources.hashCode()); - result = prime * result + ((rootFiles == null) ? 0 : rootFiles.hashCode()); - result = prime * result + ((templates == null) ? 0 : templates.hashCode()); - result = prime * result + ((version == null) ? 0 : version.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; - CookbookVersion other = (CookbookVersion) obj; - if (attributes == null) { - if (other.attributes != null) - return false; - } else if (!attributes.equals(other.attributes)) - return false; - if (cookbookName == null) { - if (other.cookbookName != null) - return false; - } else if (!cookbookName.equals(other.cookbookName)) - return false; - if (definitions == null) { - if (other.definitions != null) - return false; - } else if (!definitions.equals(other.definitions)) - return false; - if (files == null) { - if (other.files != null) - return false; - } else if (!files.equals(other.files)) - return false; - if (libraries == null) { - if (other.libraries != null) - return false; - } else if (!libraries.equals(other.libraries)) - return false; - if (metadata == null) { - if (other.metadata != null) - return false; - } else if (!metadata.equals(other.metadata)) - return false; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - if (providers == null) { - if (other.providers != null) - return false; - } else if (!providers.equals(other.providers)) - return false; - if (recipes == null) { - if (other.recipes != null) - return false; - } else if (!recipes.equals(other.recipes)) - return false; - if (resources == null) { - if (other.resources != null) - return false; - } else if (!resources.equals(other.resources)) - return false; - if (rootFiles == null) { - if (other.rootFiles != null) - return false; - } else if (!rootFiles.equals(other.rootFiles)) - return false; - if (templates == null) { - if (other.templates != null) - return false; - } else if (!templates.equals(other.templates)) - return false; - if (version == null) { - if (other.version != null) - return false; - } else if (!version.equals(other.version)) - return false; - return true; - } - - @Override - public String toString() { - return "Cookbook [attributes=" + attributes + ", cookbookName=" + cookbookName + ", definitions=" + definitions - + ", files=" + files + ", libraries=" + libraries + ", metadata=" + metadata + ", name=" + name - + ", providers=" + providers + ", recipes=" + recipes + ", resources=" + resources + ", rootFiles=" - + rootFiles + ", templates=" + templates + ", version=" + version + "]"; - } - -} diff --git a/chef/core/src/main/java/org/jclouds/chef/domain/DatabagItem.java b/chef/core/src/main/java/org/jclouds/chef/domain/DatabagItem.java deleted file mode 100644 index fd524660f7..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/domain/DatabagItem.java +++ /dev/null @@ -1,68 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.domain; - -import static com.google.common.base.Preconditions.checkNotNull; - -import org.jclouds.domain.JsonBall; - -/** - * - * @author Adrian Cole - */ -public class DatabagItem extends JsonBall { - - private static final long serialVersionUID = 7905637919304343493L; - private final String id; - - public DatabagItem(String id, String value) { - super(value); - this.id = checkNotNull(id, "id"); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + ((id == null) ? 0 : id.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - DatabagItem other = (DatabagItem) obj; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - return true; - } - - public String getId() { - return id; - } -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/domain/Metadata.java b/chef/core/src/main/java/org/jclouds/chef/domain/Metadata.java deleted file mode 100644 index bc1fa6f215..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/domain/Metadata.java +++ /dev/null @@ -1,281 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.domain; - -import java.util.Map; -import java.util.Set; - -import com.google.common.collect.Maps; -import com.google.gson.annotations.SerializedName; - -/** - * Cookbook object. - * - * @author Adrian Cole - */ -public class Metadata { - - private String license; - private String maintainer; - private Map suggestions = Maps.newLinkedHashMap(); - private Map> dependencies = Maps.newLinkedHashMap(); - @SerializedName("maintainer_email") - private String maintainerEmail; - private Map> conflicting = Maps.newLinkedHashMap(); - private String description; - private Map> providing = Maps.newLinkedHashMap(); - private Map> platforms = Maps.newLinkedHashMap(); - private String version; - private Map recipes = Maps.newLinkedHashMap(); - private Map> replacing = Maps.newLinkedHashMap(); - private String name; - private Map groupings = Maps.newLinkedHashMap(); - @SerializedName("long_description") - private String longDescription; - private Map attributes = Maps.newLinkedHashMap(); - private Map recommendations = Maps.newLinkedHashMap(); - - public Metadata(String license, String maintainer, Map suggestions, - Map> dependencies, String maintainerEmail, Map> conflicting, - String description, Map> providing, Map> platforms, String version, - Map recipes, Map> replacing, String name, Map groupings, - String longDescription, Map attributes, Map recommendations) { - this.license = license; - this.maintainer = maintainer; - this.suggestions.putAll(suggestions); - this.dependencies.putAll(dependencies); - this.maintainerEmail = maintainerEmail; - this.conflicting.putAll(conflicting); - this.description = description; - this.providing.putAll(providing); - this.platforms.putAll(platforms); - this.version = version; - this.recipes.putAll(recipes); - this.replacing.putAll(replacing); - this.name = name; - this.groupings.putAll(groupings); - this.longDescription = longDescription; - this.attributes.putAll(attributes); - this.recommendations.putAll(recommendations); - } - - public Metadata() { - } - - public String getLicense() { - return license; - } - - public String getMaintainer() { - return maintainer; - } - - public Map getSuggestions() { - return suggestions; - } - - public Map> getDependencies() { - return dependencies; - } - - public String getMaintainerEmail() { - return maintainerEmail; - } - - public Map> getConflicting() { - return conflicting; - } - - public String getDescription() { - return description; - } - - public Map> getProviding() { - return providing; - } - - public Map> getPlatforms() { - return platforms; - } - - public String getVersion() { - return version; - } - - public Map getRecipes() { - return recipes; - } - - public Map> getReplacing() { - return replacing; - } - - public String getName() { - return name; - } - - public Map getGroupings() { - return groupings; - } - - public String getLongDescription() { - return longDescription; - } - - public Map getAttributes() { - return attributes; - } - - public Map getRecommendations() { - return recommendations; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((attributes == null) ? 0 : attributes.hashCode()); - result = prime * result + ((conflicting == null) ? 0 : conflicting.hashCode()); - result = prime * result + ((dependencies == null) ? 0 : dependencies.hashCode()); - result = prime * result + ((description == null) ? 0 : description.hashCode()); - result = prime * result + ((groupings == null) ? 0 : groupings.hashCode()); - result = prime * result + ((license == null) ? 0 : license.hashCode()); - result = prime * result + ((longDescription == null) ? 0 : longDescription.hashCode()); - result = prime * result + ((maintainer == null) ? 0 : maintainer.hashCode()); - result = prime * result + ((maintainerEmail == null) ? 0 : maintainerEmail.hashCode()); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((platforms == null) ? 0 : platforms.hashCode()); - result = prime * result + ((providing == null) ? 0 : providing.hashCode()); - result = prime * result + ((recipes == null) ? 0 : recipes.hashCode()); - result = prime * result + ((recommendations == null) ? 0 : recommendations.hashCode()); - result = prime * result + ((replacing == null) ? 0 : replacing.hashCode()); - result = prime * result + ((suggestions == null) ? 0 : suggestions.hashCode()); - result = prime * result + ((version == null) ? 0 : version.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; - Metadata other = (Metadata) obj; - if (attributes == null) { - if (other.attributes != null) - return false; - } else if (!attributes.equals(other.attributes)) - return false; - if (conflicting == null) { - if (other.conflicting != null) - return false; - } else if (!conflicting.equals(other.conflicting)) - return false; - if (dependencies == null) { - if (other.dependencies != null) - return false; - } else if (!dependencies.equals(other.dependencies)) - return false; - if (description == null) { - if (other.description != null) - return false; - } else if (!description.equals(other.description)) - return false; - if (groupings == null) { - if (other.groupings != null) - return false; - } else if (!groupings.equals(other.groupings)) - return false; - if (license == null) { - if (other.license != null) - return false; - } else if (!license.equals(other.license)) - return false; - if (longDescription == null) { - if (other.longDescription != null) - return false; - } else if (!longDescription.equals(other.longDescription)) - return false; - if (maintainer == null) { - if (other.maintainer != null) - return false; - } else if (!maintainer.equals(other.maintainer)) - return false; - if (maintainerEmail == null) { - if (other.maintainerEmail != null) - return false; - } else if (!maintainerEmail.equals(other.maintainerEmail)) - return false; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - if (platforms == null) { - if (other.platforms != null) - return false; - } else if (!platforms.equals(other.platforms)) - return false; - if (providing == null) { - if (other.providing != null) - return false; - } else if (!providing.equals(other.providing)) - return false; - if (recipes == null) { - if (other.recipes != null) - return false; - } else if (!recipes.equals(other.recipes)) - return false; - if (recommendations == null) { - if (other.recommendations != null) - return false; - } else if (!recommendations.equals(other.recommendations)) - return false; - if (replacing == null) { - if (other.replacing != null) - return false; - } else if (!replacing.equals(other.replacing)) - return false; - if (suggestions == null) { - if (other.suggestions != null) - return false; - } else if (!suggestions.equals(other.suggestions)) - return false; - if (version == null) { - if (other.version != null) - return false; - } else if (!version.equals(other.version)) - return false; - return true; - } - - @Override - public String toString() { - return "Metadata [attributes=" + attributes + ", conflicting=" + conflicting + ", dependencies=" + dependencies - + ", description=" + description + ", groupings=" + groupings + ", license=" + license - + ", longDescription=" + longDescription + ", maintainer=" + maintainer + ", maintainerEmail=" - + maintainerEmail + ", name=" + name + ", platforms=" + platforms + ", providing=" + providing - + ", recipes=" + recipes + ", recommendations=" + recommendations + ", replacing=" + replacing - + ", suggestions=" + suggestions + ", version=" + version + "]"; - } - -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/domain/Node.java b/chef/core/src/main/java/org/jclouds/chef/domain/Node.java deleted file mode 100644 index fd570de4a3..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/domain/Node.java +++ /dev/null @@ -1,172 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.domain; - -import java.util.List; -import java.util.Map; - -import org.jclouds.domain.JsonBall; - -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.google.gson.annotations.SerializedName; - -/** - * Sandbox object. - * - * @author Adrian Cole - */ -public class Node { - - private String name; - private Map normal = Maps.newLinkedHashMap(); - private Map override = Maps.newLinkedHashMap(); - @SerializedName("default") - private Map defaultA = Maps.newLinkedHashMap(); - private Map automatic = Maps.newLinkedHashMap(); - @SerializedName("run_list") - private List runList = Lists.newArrayList(); - - // internal - @SerializedName("json_class") - private String _jsonClass = "Chef::Node"; - - public Node(String name, Map normal, Map override, - Map defaultA, Map automatic, Iterable runList) { - this.name = name; - this.normal.putAll(normal); - this.override.putAll(override); - this.defaultA.putAll(defaultA); - this.automatic.putAll(automatic); - Iterables.addAll(this.runList, runList); - } - - @Override - public String toString() { - return "Node [name=" + name + ", runList=" + runList + ", normal=" + normal + ", default=" + defaultA - + ", override=" + override + ", automatic=" + automatic + "]"; - } - - public Node(String name, Iterable runList) { - this.name = name; - Iterables.addAll(this.runList, runList); - } - - // hidden but needs to be here for json deserialization to work - Node() { - - } - - public String getName() { - return name; - } - - public Map getNormal() { - return normal; - } - - public Map getOverride() { - return override; - } - - public Map getDefault() { - return defaultA; - } - - public Map getAutomatic() { - return automatic; - } - - public List getRunList() { - return runList; - } - - @SerializedName("chef_type") - private String _chefType = "node"; - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((_chefType == null) ? 0 : _chefType.hashCode()); - result = prime * result + ((_jsonClass == null) ? 0 : _jsonClass.hashCode()); - result = prime * result + ((automatic == null) ? 0 : automatic.hashCode()); - result = prime * result + ((defaultA == null) ? 0 : defaultA.hashCode()); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((normal == null) ? 0 : normal.hashCode()); - result = prime * result + ((override == null) ? 0 : override.hashCode()); - result = prime * result + ((runList == null) ? 0 : runList.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; - Node other = (Node) obj; - if (_chefType == null) { - if (other._chefType != null) - return false; - } else if (!_chefType.equals(other._chefType)) - return false; - if (_jsonClass == null) { - if (other._jsonClass != null) - return false; - } else if (!_jsonClass.equals(other._jsonClass)) - return false; - if (automatic == null) { - if (other.automatic != null) - return false; - } else if (!automatic.equals(other.automatic)) - return false; - if (defaultA == null) { - if (other.defaultA != null) - return false; - } else if (!defaultA.equals(other.defaultA)) - return false; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - if (normal == null) { - if (other.normal != null) - return false; - } else if (!normal.equals(other.normal)) - return false; - if (override == null) { - if (other.override != null) - return false; - } else if (!override.equals(other.override)) - return false; - if (runList == null) { - if (other.runList != null) - return false; - } else if (!runList.equals(other.runList)) - return false; - return true; - } - -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/domain/Resource.java b/chef/core/src/main/java/org/jclouds/chef/domain/Resource.java deleted file mode 100644 index 62bce310e0..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/domain/Resource.java +++ /dev/null @@ -1,135 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.domain; - -import java.net.URI; -import java.util.Arrays; - -import org.jclouds.io.payloads.FilePayload; - -import com.google.common.primitives.Bytes; - -/** - * Cookbook object. - * - * @author Adrian Cole - */ -public class Resource { - - private String name; - private URI url; - private byte[] checksum; - private String path; - private String specificity; - - public Resource(FilePayload payload) { - this(payload.getRawContent().getName(), null, payload.getContentMD5(), payload - .getRawContent().getPath(), "default"); - } - - public Resource(String name, byte[] checksum, String path) { - this(name, null, checksum, path, "default"); - } - - public Resource(String name, URI url, byte[] checksum, String path, String specificity) { - this.name = name; - this.url = url; - this.checksum = checksum; - this.path = path; - this.specificity = specificity; - } - - // hidden but needs to be here for json deserialization to work - Resource() { - } - - public String getName() { - return name; - } - - public URI getUrl() { - return url; - } - - public byte[] getChecksum() { - return checksum; - } - - public String getPath() { - return path; - } - - public String getSpecificity() { - return specificity; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + Arrays.hashCode(checksum); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((path == null) ? 0 : path.hashCode()); - result = prime * result + ((specificity == null) ? 0 : specificity.hashCode()); - result = prime * result + ((url == null) ? 0 : url.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; - Resource other = (Resource) obj; - if (!Arrays.equals(checksum, other.checksum)) - return false; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - if (path == null) { - if (other.path != null) - return false; - } else if (!path.equals(other.path)) - return false; - if (specificity == null) { - if (other.specificity != null) - return false; - } else if (!specificity.equals(other.specificity)) - return false; - if (url == null) { - if (other.url != null) - return false; - } else if (!url.equals(other.url)) - return false; - return true; - } - - @Override - public String toString() { - return "Resource [checksum=" + Bytes.asList(checksum) + ", name=" + name + ", path=" + path - + ", specificity=" + specificity + ", url=" + url + "]"; - } - -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/domain/Role.java b/chef/core/src/main/java/org/jclouds/chef/domain/Role.java deleted file mode 100644 index 6925ae6844..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/domain/Role.java +++ /dev/null @@ -1,160 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.domain; - -import java.util.List; -import java.util.Map; - -import org.jclouds.domain.JsonBall; - -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.google.gson.annotations.SerializedName; - -/** - * Sandbox object. - * - * @author Adrian Cole - */ -public class Role { - - private String name; - private String description; - @SerializedName("override_attributes") - private Map override = Maps.newLinkedHashMap(); - @SerializedName("default_attributes") - private Map defaultA = Maps.newLinkedHashMap(); - @SerializedName("run_list") - private List runList = Lists.newArrayList(); - - // internal - @SerializedName("json_class") - private String _jsonClass = "Chef::Role"; - @SerializedName("chef_type") - private String _chefType = "role"; - - public Role(String name, String description, Map defaultA, List runList, - Map override) { - this.name = name; - this.description = description; - this.defaultA = defaultA; - this.runList = runList; - this.override = override; - } - - public Role(String name, Iterable runList) { - this.name = name; - Iterables.addAll(this.runList, runList); - } - - // hidden but needs to be here for json deserialization to work - Role() { - - } - - public String getName() { - return name; - } - - public String getDescription() { - return description; - } - - public Map getOverride() { - return override; - } - - public Map getDefault() { - return defaultA; - } - - public List getRunList() { - return runList; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((_chefType == null) ? 0 : _chefType.hashCode()); - result = prime * result + ((_jsonClass == null) ? 0 : _jsonClass.hashCode()); - result = prime * result + ((defaultA == null) ? 0 : defaultA.hashCode()); - result = prime * result + ((description == null) ? 0 : description.hashCode()); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((override == null) ? 0 : override.hashCode()); - result = prime * result + ((runList == null) ? 0 : runList.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; - Role other = (Role) obj; - if (_chefType == null) { - if (other._chefType != null) - return false; - } else if (!_chefType.equals(other._chefType)) - return false; - if (_jsonClass == null) { - if (other._jsonClass != null) - return false; - } else if (!_jsonClass.equals(other._jsonClass)) - return false; - if (defaultA == null) { - if (other.defaultA != null) - return false; - } else if (!defaultA.equals(other.defaultA)) - return false; - if (description == null) { - if (other.description != null) - return false; - } else if (!description.equals(other.description)) - return false; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - if (override == null) { - if (other.override != null) - return false; - } else if (!override.equals(other.override)) - return false; - if (runList == null) { - if (other.runList != null) - return false; - } else if (!runList.equals(other.runList)) - return false; - return true; - } - - @Override - public String toString() { - return "[name=" + name + ", description=" + description + ", defaultA=" + defaultA + ", override=" + override - + ", runList=" + runList + "]"; - } - -} diff --git a/chef/core/src/main/java/org/jclouds/chef/domain/Sandbox.java b/chef/core/src/main/java/org/jclouds/chef/domain/Sandbox.java deleted file mode 100644 index 1f04f06ff1..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/domain/Sandbox.java +++ /dev/null @@ -1,148 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.domain; - -import java.util.Date; -import java.util.Set; - -import com.google.common.collect.Iterables; -import com.google.common.collect.Sets; -import com.google.gson.annotations.SerializedName; - -/** - * Sandbox object. - * - * @author Adrian Cole - */ -public class Sandbox { - - @SerializedName("_rev") - private String rev; - @SerializedName("is_completed") - private boolean isCompleted; - @SerializedName("create_time") - private Date createTime; - private Set checksums = Sets.newLinkedHashSet(); - private String name; - private String guid; - - // internal - @SuppressWarnings("unused") - @SerializedName("json_class") - private String _jsonClass = "Chef::Sandbox"; - @SerializedName("chef_type") - @SuppressWarnings("unused") - private String _chefType = "sandbox"; - - public Sandbox(String rev, boolean isCompleted, Date createTime, Iterable checksums, String name, String guid) { - this.rev = rev; - this.isCompleted = isCompleted; - this.createTime = createTime; - Iterables.addAll(this.checksums, checksums); - this.name = name; - this.guid = guid; - } - - public Sandbox() { - - } - - public String getRev() { - return rev; - } - - public boolean isCompleted() { - return isCompleted; - } - - public Date getCreateTime() { - return createTime; - } - - public Set getChecksums() { - return checksums; - } - - public String getName() { - return name; - } - - public String getGuid() { - return guid; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((checksums == null) ? 0 : checksums.hashCode()); - result = prime * result + ((createTime == null) ? 0 : createTime.hashCode()); - result = prime * result + ((guid == null) ? 0 : guid.hashCode()); - result = prime * result + (isCompleted ? 1231 : 1237); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((rev == null) ? 0 : rev.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; - Sandbox other = (Sandbox) obj; - if (checksums == null) { - if (other.checksums != null) - return false; - } else if (!checksums.equals(other.checksums)) - return false; - if (createTime == null) { - if (other.createTime != null) - return false; - } else if (!createTime.equals(other.createTime)) - return false; - if (guid == null) { - if (other.guid != null) - return false; - } else if (!guid.equals(other.guid)) - return false; - if (isCompleted != other.isCompleted) - return false; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - if (rev == null) { - if (other.rev != null) - return false; - } else if (!rev.equals(other.rev)) - return false; - return true; - } - - @Override - public String toString() { - return "Sandbox [checksums=" + checksums + ", createTime=" + createTime + ", guid=" + guid + ", isCompleted=" - + isCompleted + ", name=" + name + ", rev=" + rev + "]"; - } -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/domain/SearchResult.java b/chef/core/src/main/java/org/jclouds/chef/domain/SearchResult.java deleted file mode 100644 index b94169f210..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/domain/SearchResult.java +++ /dev/null @@ -1,52 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.domain; - -import java.util.LinkedHashSet; - -import com.google.common.collect.Iterables; - -/** - * - * @author Adrian Cole - * - */ -public class SearchResult extends LinkedHashSet { - private long start; - - SearchResult() { - } - - public SearchResult(long start, Iterable results) { - this.start = start; - Iterables.addAll(this, results); - } - - private static final long serialVersionUID = 4000610660948065287L; - - /** - * - * @return the result position this started from from - */ - long getStart() { - return start; - } - -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/domain/UploadSandbox.java b/chef/core/src/main/java/org/jclouds/chef/domain/UploadSandbox.java deleted file mode 100644 index 914aa4c7d9..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/domain/UploadSandbox.java +++ /dev/null @@ -1,103 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.domain; - -import java.net.URI; -import java.util.List; -import java.util.Map; - -import com.google.common.collect.Maps; -import com.google.gson.annotations.SerializedName; - -/** - * - * @author Adrian Cole - */ -public class UploadSandbox { - private URI uri; - private Map, ChecksumStatus> checksums = Maps.newLinkedHashMap(); - @SerializedName("sandbox_id") - private String sandboxId; - - public UploadSandbox(URI uri, Map, ChecksumStatus> checksums, String sandboxId) { - this.uri = uri; - this.checksums.putAll(checksums); - this.sandboxId = sandboxId; - } - - public UploadSandbox() { - - } - - public URI getUri() { - return uri; - } - - public Map, ChecksumStatus> getChecksums() { - return checksums; - } - - public String getSandboxId() { - return sandboxId; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((checksums == null) ? 0 : checksums.hashCode()); - result = prime * result + ((sandboxId == null) ? 0 : sandboxId.hashCode()); - result = prime * result + ((uri == null) ? 0 : uri.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; - UploadSandbox other = (UploadSandbox) obj; - if (checksums == null) { - if (other.checksums != null) - return false; - } else if (!checksums.equals(other.checksums)) - return false; - if (sandboxId == null) { - if (other.sandboxId != null) - return false; - } else if (!sandboxId.equals(other.sandboxId)) - return false; - if (uri == null) { - if (other.uri != null) - return false; - } else if (!uri.equals(other.uri)) - return false; - return true; - } - - @Override - public String toString() { - return "UploadSite [checksums=" + checksums + ", id=" + sandboxId + ", uri=" + uri + "]"; - } - -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/filters/SignedHeaderAuth.java b/chef/core/src/main/java/org/jclouds/chef/filters/SignedHeaderAuth.java deleted file mode 100644 index 50180f3153..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/filters/SignedHeaderAuth.java +++ /dev/null @@ -1,193 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.filters; - -import static com.google.common.base.Preconditions.checkArgument; -import static org.jclouds.Constants.PROPERTY_IDENTITY; - -import java.security.PrivateKey; -import java.util.Collections; -import java.util.NoSuchElementException; - -import javax.annotation.Resource; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Provider; -import javax.inject.Singleton; - -import org.jclouds.Constants; -import org.jclouds.crypto.Crypto; -import org.jclouds.crypto.CryptoStreams; -import org.jclouds.date.TimeStamp; -import org.jclouds.http.HttpException; -import org.jclouds.http.HttpRequest; -import org.jclouds.http.HttpRequestFilter; -import org.jclouds.http.HttpUtils; -import org.jclouds.http.internal.SignatureWire; -import org.jclouds.io.InputSuppliers; -import org.jclouds.io.Payload; -import org.jclouds.io.Payloads; -import org.jclouds.io.payloads.MultipartForm; -import org.jclouds.io.payloads.Part; -import org.jclouds.io.payloads.RSAEncryptingPayload; -import org.jclouds.logging.Logger; -import org.jclouds.util.Utils; - -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Predicate; -import com.google.common.base.Splitter; -import com.google.common.base.Throwables; -import com.google.common.collect.Iterables; -import com.google.common.io.ByteStreams; - -/** - * Ported from mixlib-authentication in order to sign Chef requests. - * - * @see - * @author Adrian Cole - * - */ -@Singleton -public class SignedHeaderAuth implements HttpRequestFilter { - public static final String SIGNING_DESCRIPTION = "version=1.0"; - - private final SignatureWire signatureWire; - private final String userId; - private final PrivateKey privateKey; - private final Provider timeStampProvider; - private final Crypto crypto; - private final String emptyStringHash; - private final HttpUtils utils; - - @Resource - @Named(Constants.LOGGER_SIGNATURE) - Logger signatureLog = Logger.NULL; - - @Inject - public SignedHeaderAuth(SignatureWire signatureWire, @Named(PROPERTY_IDENTITY) String userId, PrivateKey privateKey, - @TimeStamp Provider timeStampProvider, Crypto crypto, HttpUtils utils) { - this.signatureWire = signatureWire; - this.userId = userId; - this.privateKey = privateKey; - this.timeStampProvider = timeStampProvider; - this.crypto = crypto; - this.emptyStringHash = hashBody(Payloads.newStringPayload("")); - this.utils = utils; - } - - public void filter(HttpRequest request) throws HttpException { - - String contentHash = hashBody(request.getPayload()); - request.getHeaders().replaceValues("X-Ops-Content-Hash", Collections.singletonList(contentHash)); - String timestamp = timeStampProvider.get(); - String toSign = createStringToSign(request.getMethod(), hashPath(request.getEndpoint().getPath()), contentHash, - timestamp); - request.getHeaders().replaceValues("X-Ops-Userid", Collections.singletonList(userId)); - request.getHeaders().replaceValues("X-Ops-Sign", Collections.singletonList(SIGNING_DESCRIPTION)); - calculateAndReplaceAuthorizationHeaders(request, toSign); - request.getHeaders().replaceValues("X-Ops-Timestamp", Collections.singletonList(timestamp)); - utils.logRequest(signatureLog, request, "<<"); - } - - @VisibleForTesting - void calculateAndReplaceAuthorizationHeaders(HttpRequest request, String toSign) throws HttpException { - String signature = sign(toSign); - if (signatureWire.enabled()) - signatureWire.input(Utils.toInputStream(signature)); - String[] signatureLines = Iterables.toArray(Splitter.fixedLength(60).split(signature), String.class); - for (int i = 0; i < signatureLines.length; i++) { - request.getHeaders().replaceValues("X-Ops-Authorization-" + (i + 1), - Collections.singletonList(signatureLines[i])); - } - } - - public String createStringToSign(String request, String hashedPath, String contentHash, String timestamp) { - - return new StringBuilder().append("Method:").append(request).append("\n").append("Hashed Path:").append( - hashedPath).append("\n").append("X-Ops-Content-Hash:").append(contentHash).append("\n").append( - "X-Ops-Timestamp:").append(timestamp).append("\n").append("X-Ops-UserId:").append(userId).toString(); - - } - - @VisibleForTesting - String hashPath(String path) { - try { - return CryptoStreams.base64(CryptoStreams.digest(InputSuppliers.of(canonicalPath(path)), crypto.sha1())); - } catch (Exception e) { - Throwables.propagateIfPossible(e); - throw new HttpException("error creating sigature for path: " + path, e); - } - } - - /** - * Build the canonicalized path, which collapses multiple slashes (/) and removes a trailing - * slash unless the path is only "/" - */ - @VisibleForTesting - String canonicalPath(String path) { - path = path.replaceAll("\\/+", "/"); - return path.endsWith("/") && path.length() > 1 ? path.substring(0, path.length() - 1) : path; - } - - @VisibleForTesting - String hashBody(Payload payload) { - if (payload == null) - return emptyStringHash; - payload = useTheFilePartIfForm(payload); - checkArgument(payload != null, "payload was null"); - checkArgument(payload.isRepeatable(), "payload must be repeatable: " + payload); - try { - return CryptoStreams.base64(CryptoStreams.digest(payload, crypto.sha1())); - } catch (Exception e) { - Throwables.propagateIfPossible(e); - throw new HttpException("error creating sigature for payload: " + payload, e); - } - } - - private Payload useTheFilePartIfForm(Payload payload) { - if (payload instanceof MultipartForm) { - Iterable parts = MultipartForm.class.cast(payload).getRawContent(); - try { - payload = Iterables.find(parts, new Predicate() { - - @Override - public boolean apply(Part input) { - return "file".equals(input.getName()); - } - - }); - } catch (NoSuchElementException e) { - - } - } - return payload; - } - - public String sign(String toSign) { - try { - byte[] encrypted = ByteStreams.toByteArray(new RSAEncryptingPayload(Payloads.newStringPayload(toSign), - privateKey)); - return CryptoStreams.base64(encrypted); - } catch (Exception e) { - throw new HttpException("error signing request", e); - } - } - -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/functions/ClientForTag.java b/chef/core/src/main/java/org/jclouds/chef/functions/ClientForTag.java deleted file mode 100644 index 6ff71ab03e..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/functions/ClientForTag.java +++ /dev/null @@ -1,69 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.functions; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.collect.Sets.newHashSet; - -import java.util.Set; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import org.jclouds.chef.ChefClient; -import org.jclouds.chef.domain.Client; - -import com.google.common.base.Function; - -/** - * - * Generates a client relevant for a particular tag - * - * @author Adrian Cole - */ -@Singleton -public class ClientForTag implements Function { - private final ChefClient chefClient; - - @Inject - public ClientForTag(ChefClient chefClient) { - this.chefClient = checkNotNull(chefClient, "chefClient"); - } - - @Override - public Client apply(String from) { - String clientName = findNextClientName(chefClient.listClients(), from + "-validator-%02d"); - Client client = chefClient.createClient(clientName); - // response from create only includes the key - return new Client(null, null, clientName, clientName, false, client.getPrivateKey()); - } - - private static String findNextClientName(Set clients, String pattern) { - String clientName; - Set names = newHashSet(clients); - int index = 0; - while (true) { - clientName = String.format(pattern,index++); - if (!names.contains(clientName)) - break; - } - return clientName; - } -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/functions/ParseErrorFromJsonOrReturnBody.java b/chef/core/src/main/java/org/jclouds/chef/functions/ParseErrorFromJsonOrReturnBody.java deleted file mode 100644 index 9cc8f15b23..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/functions/ParseErrorFromJsonOrReturnBody.java +++ /dev/null @@ -1,63 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.functions; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import org.jclouds.http.HttpResponse; -import org.jclouds.http.functions.ReturnStringIf2xx; - -import com.google.common.base.Function; - -/** - * - * - * @author Adrian Cole - */ -@Singleton -public class ParseErrorFromJsonOrReturnBody implements Function { - Pattern pattern = Pattern.compile(".*\\[\"([^\"]+)\"\\].*"); - private final ReturnStringIf2xx returnStringIf200; - - @Inject - ParseErrorFromJsonOrReturnBody(ReturnStringIf2xx returnStringIf200) { - this.returnStringIf200 = returnStringIf200; - } - - @Override - public String apply(HttpResponse response) { - String content = returnStringIf200.apply(response); - if (content == null) - return null; - return parse(content); - } - - public String parse(String in) { - Matcher matcher = pattern.matcher(in); - if (matcher.find()) { - return matcher.group(1); - } - return in; - } -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/functions/ParseKeySetFromJson.java b/chef/core/src/main/java/org/jclouds/chef/functions/ParseKeySetFromJson.java deleted file mode 100644 index fb1c41e048..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/functions/ParseKeySetFromJson.java +++ /dev/null @@ -1,51 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.functions; - -import java.util.Map; -import java.util.Set; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import org.jclouds.http.HttpResponse; -import org.jclouds.http.functions.ParseJson; - -import com.google.common.base.Function; - -/** - * @author Adrian Cole - */ -@Singleton -public class ParseKeySetFromJson implements Function> { - - private final ParseJson> json; - - @Inject - ParseKeySetFromJson(ParseJson> json) { - this.json = json; - } - - @Override - public Set apply(HttpResponse arg0) { - return json.apply(arg0).keySet(); - - } -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/functions/ParseSearchClientsFromJson.java b/chef/core/src/main/java/org/jclouds/chef/functions/ParseSearchClientsFromJson.java deleted file mode 100644 index 46076054e3..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/functions/ParseSearchClientsFromJson.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.functions; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import org.jclouds.chef.domain.Client; -import org.jclouds.http.functions.ParseJson; - -/** - * - * @author Adrian Cole - */ -@Singleton -public class ParseSearchClientsFromJson extends ParseSearchResultFromJson { - - // TODO add generic json parser detector - - @Inject - ParseSearchClientsFromJson(ParseJson> json) { - super(json); - } - -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/functions/ParseSearchDatabagFromJson.java b/chef/core/src/main/java/org/jclouds/chef/functions/ParseSearchDatabagFromJson.java deleted file mode 100644 index 6d2b3010bc..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/functions/ParseSearchDatabagFromJson.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.functions; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import org.jclouds.chef.domain.DatabagItem; -import org.jclouds.http.functions.ParseJson; - -/** - * - * @author Adrian Cole - */ -@Singleton -public class ParseSearchDatabagFromJson extends ParseSearchResultFromJson { - - // TODO add generic json parser detector - - @Inject - ParseSearchDatabagFromJson(ParseJson> json) { - super(json); - } - -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/functions/ParseSearchNodesFromJson.java b/chef/core/src/main/java/org/jclouds/chef/functions/ParseSearchNodesFromJson.java deleted file mode 100644 index 6c132dd708..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/functions/ParseSearchNodesFromJson.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.functions; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import org.jclouds.chef.domain.Node; -import org.jclouds.http.functions.ParseJson; - -/** - * - * @author Adrian Cole - */ -@Singleton -public class ParseSearchNodesFromJson extends ParseSearchResultFromJson { - - // TODO add generic json parser detector - - @Inject - ParseSearchNodesFromJson(ParseJson> json) { - super(json); - } - -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/functions/ParseSearchResultFromJson.java b/chef/core/src/main/java/org/jclouds/chef/functions/ParseSearchResultFromJson.java deleted file mode 100644 index d22905e0d0..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/functions/ParseSearchResultFromJson.java +++ /dev/null @@ -1,56 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.functions; - -import java.util.List; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import org.jclouds.chef.domain.SearchResult; -import org.jclouds.http.HttpResponse; -import org.jclouds.http.functions.ParseJson; - -import com.google.common.base.Function; - -/** - * @author Adrian Cole - */ -@Singleton -public class ParseSearchResultFromJson implements Function> { - - private final ParseJson> json; - - static class Response { - long start; - List rows; - } - - @Inject - ParseSearchResultFromJson(ParseJson> json) { - this.json = json; - } - - @Override - public SearchResult apply(HttpResponse arg0) { - Response returnVal = json.apply(arg0); - return new SearchResult(returnVal.start, returnVal.rows); - } -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/functions/ParseSearchRolesFromJson.java b/chef/core/src/main/java/org/jclouds/chef/functions/ParseSearchRolesFromJson.java deleted file mode 100644 index c739e64df5..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/functions/ParseSearchRolesFromJson.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.functions; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import org.jclouds.chef.domain.Role; -import org.jclouds.http.functions.ParseJson; - -/** - * - * @author Adrian Cole - */ -@Singleton -public class ParseSearchRolesFromJson extends ParseSearchResultFromJson { - - // TODO add generic json parser detector - - @Inject - ParseSearchRolesFromJson(ParseJson> json) { - super(json); - } - -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/functions/RunListForTag.java b/chef/core/src/main/java/org/jclouds/chef/functions/RunListForTag.java deleted file mode 100644 index d847ff4d16..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/functions/RunListForTag.java +++ /dev/null @@ -1,71 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.functions; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Preconditions.checkState; -import static org.jclouds.chef.reference.ChefConstants.CHEF_BOOTSTRAP_DATABAG; - -import java.lang.reflect.Type; -import java.util.List; -import java.util.Map; - -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - -import org.jclouds.chef.ChefClient; -import org.jclouds.chef.domain.DatabagItem; -import org.jclouds.json.Json; - -import com.google.common.base.Function; -import com.google.inject.TypeLiteral; - -/** - * - * Retrieves the run-list for a specific tag - * - * - * @author Adrian Cole - */ -@Singleton -public class RunListForTag implements Function> { - public static final Type RUN_LIST_TYPE = new TypeLiteral>>() { - }.getType(); - private final ChefClient client; - private final Json json; - private final String databag; - - @Inject - public RunListForTag(@Named(CHEF_BOOTSTRAP_DATABAG) String databag, ChefClient client, Json json) { - this.databag = checkNotNull(databag, "databag"); - this.client = checkNotNull(client, "client"); - this.json = checkNotNull(json, "json"); - } - - @SuppressWarnings("unchecked") - @Override - public List apply(String from) { - DatabagItem list = client.getDatabagItem(databag, from); - checkState(list != null, "databag item %s/%s not found", databag, from); - return ((Map>) json.fromJson(list.toString(), RUN_LIST_TYPE)).get("run_list"); - } - -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/functions/TagToBootScript.java b/chef/core/src/main/java/org/jclouds/chef/functions/TagToBootScript.java deleted file mode 100644 index b4b2e3f574..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/functions/TagToBootScript.java +++ /dev/null @@ -1,118 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.functions; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Preconditions.checkState; -import static org.jclouds.io.Payloads.newStringPayload; -import static org.jclouds.scriptbuilder.domain.Statements.createFile; -import static org.jclouds.scriptbuilder.domain.Statements.exec; -import static org.jclouds.scriptbuilder.domain.Statements.newStatementList; - -import java.lang.reflect.Type; -import java.net.URI; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - -import org.jclouds.chef.domain.Client; -import org.jclouds.crypto.Pems; -import org.jclouds.io.Payload; -import org.jclouds.json.Json; -import org.jclouds.rest.annotations.Provider; -import org.jclouds.scriptbuilder.domain.OsFamily; -import org.jclouds.scriptbuilder.domain.Statement; - -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Function; -import com.google.common.base.Splitter; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.inject.TypeLiteral; - -/** - * - * Generates a bootstrap script relevant for a particular tag - * - * @author Adrian Cole - */ -@Singleton -public class TagToBootScript implements Function { - @VisibleForTesting - static final Type RUN_LIST_TYPE = new TypeLiteral>>() { - }.getType(); - private final URI endpoint; - private final Json json; - private final Map tagToClient; - private final Map> runListForTag; - private final Statement installChefGems; - - @Inject - public TagToBootScript(@Provider URI endpoint, Json json, Map tagToClient, - Map> runListForTag, @Named("installChefGems") Statement installChefGems) { - this.endpoint = checkNotNull(endpoint, "endpoint"); - this.json = checkNotNull(json, "json"); - this.tagToClient = checkNotNull(tagToClient, "tagToClient"); - this.runListForTag = checkNotNull(runListForTag, "runListForTag"); - this.installChefGems = checkNotNull(installChefGems, "installChefGems"); - } - - public Payload apply(String tag) { - checkNotNull(tag, "tag"); - - Client client = tagToClient.get(tag); - checkState(client != null, "could not get a client for tag %s", tag); - checkState(client.getClientname() != null, "clientname null for %s", client); - checkState(client.getPrivateKey() != null, "privatekey null for %s", client); - - List runList = runListForTag.get(tag); - checkState(runList != null, "runList for %s was not found", tag); - checkState(runList.size() > 0, "runList for %s was empty", tag); - - String chefConfigDir = "{root}etc{fs}chef"; - Statement createChefConfigDir = exec("{md} " + chefConfigDir); - Statement createClientRb = createFile(chefConfigDir + "{fs}client.rb", ImmutableList.of("require 'rubygems'", - "require 'ohai'", "o = Ohai::System.new", "o.all_plugins", String.format( - "node_name \"%s-\" + o[:ipaddress]", tag), "log_level :info", "log_location STDOUT", String - .format("validation_client_name \"%s\"", client.getClientname()), String.format( - "chef_server_url \"%s\"", endpoint))); - - Statement createValidationPem = createFile(chefConfigDir + "{fs}validation.pem", Splitter.on('\n').split( - Pems.pem(client.getPrivateKey()))); - - String chefBootFile = chefConfigDir + "{fs}first-boot.json"; - - Statement createFirstBoot = createFile(chefBootFile, Collections.singleton(json.toJson(ImmutableMap - .> of("run_list", runList), RUN_LIST_TYPE))); - - Statement runChef = exec("chef-client -j " + chefBootFile); - - Statement bootstrapAndRunChef = newStatementList(installChefGems, createChefConfigDir, createClientRb, - createValidationPem, createFirstBoot, runChef); - - String runScript = bootstrapAndRunChef.render(OsFamily.UNIX); - return newStringPayload(runScript); - } - -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/handlers/ChefClientErrorRetryHandler.java b/chef/core/src/main/java/org/jclouds/chef/handlers/ChefClientErrorRetryHandler.java deleted file mode 100644 index b4b6967fc0..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/handlers/ChefClientErrorRetryHandler.java +++ /dev/null @@ -1,72 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.handlers; - -import static org.jclouds.http.HttpUtils.closeClientButKeepContentStream; - -import javax.annotation.Resource; -import javax.inject.Named; - -import org.jclouds.Constants; -import org.jclouds.http.HttpCommand; -import org.jclouds.http.HttpResponse; -import org.jclouds.http.HttpRetryHandler; -import org.jclouds.http.handlers.BackoffLimitedRetryHandler; -import org.jclouds.logging.Logger; - -import com.google.inject.Inject; - -/** - * Allow for eventual consistency on sandbox requests. - * - * @author Adrian Cole - */ -public class ChefClientErrorRetryHandler implements HttpRetryHandler { - - @Inject(optional = true) - @Named(Constants.PROPERTY_MAX_RETRIES) - private int retryCountLimit = 5; - - @Resource - protected Logger logger = Logger.NULL; - - private final BackoffLimitedRetryHandler backoffLimitedRetryHandler; - - @Inject - ChefClientErrorRetryHandler(BackoffLimitedRetryHandler backoffLimitedRetryHandler) { - this.backoffLimitedRetryHandler = backoffLimitedRetryHandler; - } - - public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) { - if (command.getFailureCount() > retryCountLimit) - return false; - if (response.getStatusCode() == 400 && command.getRequest().getMethod().equals("PUT") - && command.getRequest().getEndpoint().getPath().indexOf("sandboxes") != -1) { - if (response.getPayload() != null) { - String error = new String(closeClientButKeepContentStream(response)); - if (error != null && error.indexOf("was not uploaded") != -1) { - return backoffLimitedRetryHandler.shouldRetryRequest(command, response); - } - } - } - return false; - } - -} diff --git a/chef/core/src/main/java/org/jclouds/chef/handlers/ChefErrorHandler.java b/chef/core/src/main/java/org/jclouds/chef/handlers/ChefErrorHandler.java deleted file mode 100644 index b2f06b53ed..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/handlers/ChefErrorHandler.java +++ /dev/null @@ -1,78 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.handlers; - -import javax.annotation.Resource; -import javax.inject.Inject; -import javax.inject.Singleton; - -import org.jclouds.chef.functions.ParseErrorFromJsonOrReturnBody; -import org.jclouds.http.HttpCommand; -import org.jclouds.http.HttpErrorHandler; -import org.jclouds.http.HttpResponse; -import org.jclouds.http.HttpResponseException; -import org.jclouds.logging.Logger; -import org.jclouds.rest.AuthorizationException; -import org.jclouds.rest.ResourceNotFoundException; - -import com.google.common.io.Closeables; - -/** - * This will parse and set an appropriate exception on the command object. - * - * @author Adrian Cole - * - */ -@Singleton -public class ChefErrorHandler implements HttpErrorHandler { - @Resource - protected Logger logger = Logger.NULL; - private final ParseErrorFromJsonOrReturnBody errorParser; - - @Inject - ChefErrorHandler(ParseErrorFromJsonOrReturnBody errorParser) { - this.errorParser = errorParser; - } - - public void handleError(HttpCommand command, HttpResponse response) { - String message = errorParser.apply(response); - Exception exception = new HttpResponseException(command, response, message); - try { - message = message != null ? message : String.format("%s -> %s", command.getRequest() - .getRequestLine(), response.getStatusLine()); - switch (response.getStatusCode()) { - case 401: - case 403: - exception = new AuthorizationException(message, exception); - break; - case 404: - if (!command.getRequest().getMethod().equals("DELETE")) { - exception = new ResourceNotFoundException(message, exception); - } - break; - } - } finally { - if (response.getPayload() != null) - Closeables.closeQuietly(response.getPayload().getInput()); - command.setException(exception); - } - } - -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/internal/BaseChefPropertiesBuilder.java b/chef/core/src/main/java/org/jclouds/chef/internal/BaseChefPropertiesBuilder.java deleted file mode 100644 index 6d4339502b..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/internal/BaseChefPropertiesBuilder.java +++ /dev/null @@ -1,49 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.internal; - -import static org.jclouds.Constants.PROPERTY_API_VERSION; -import static org.jclouds.Constants.PROPERTY_SESSION_INTERVAL; -import static org.jclouds.chef.reference.ChefConstants.CHEF_BOOTSTRAP_DATABAG; - -import java.util.Properties; - -import org.jclouds.PropertiesBuilder; -import org.jclouds.chef.ChefAsyncClient; - -/** - * Builds properties used in Chef Clients - * - * @author Adrian Cole - */ -public abstract class BaseChefPropertiesBuilder extends PropertiesBuilder { - @Override - protected Properties defaultProperties() { - Properties properties = super.defaultProperties(); - properties.setProperty(PROPERTY_SESSION_INTERVAL, "1"); - properties.setProperty(PROPERTY_API_VERSION, ChefAsyncClient.VERSION); - properties.setProperty(CHEF_BOOTSTRAP_DATABAG, "bootstrap"); - return properties; - } - - public BaseChefPropertiesBuilder(Properties properties) { - super(properties); - } -} diff --git a/chef/core/src/main/java/org/jclouds/chef/internal/BaseChefService.java b/chef/core/src/main/java/org/jclouds/chef/internal/BaseChefService.java deleted file mode 100644 index c87ae96190..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/internal/BaseChefService.java +++ /dev/null @@ -1,227 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.internal; - -import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.chef.reference.ChefConstants.CHEF_BOOTSTRAP_DATABAG; - -import java.io.IOException; -import java.io.InputStream; -import java.security.PrivateKey; -import java.util.List; - -import javax.annotation.Resource; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Provider; -import javax.inject.Singleton; - -import org.jclouds.chef.ChefContext; -import org.jclouds.chef.ChefService; -import org.jclouds.chef.domain.Client; -import org.jclouds.chef.domain.CookbookVersion; -import org.jclouds.chef.domain.DatabagItem; -import org.jclouds.chef.domain.Node; -import org.jclouds.chef.functions.RunListForTag; -import org.jclouds.chef.functions.TagToBootScript; -import org.jclouds.chef.reference.ChefConstants; -import org.jclouds.chef.strategy.CleanupStaleNodesAndClients; -import org.jclouds.chef.strategy.CreateNodeAndPopulateAutomaticAttributes; -import org.jclouds.chef.strategy.DeleteAllClientsInList; -import org.jclouds.chef.strategy.DeleteAllNodesInList; -import org.jclouds.chef.strategy.ListClients; -import org.jclouds.chef.strategy.ListCookbookVersions; -import org.jclouds.chef.strategy.ListNodes; -import org.jclouds.chef.strategy.UpdateAutomaticAttributesOnNode; -import org.jclouds.io.Payload; -import org.jclouds.io.Payloads; -import org.jclouds.io.payloads.RSADecryptingPayload; -import org.jclouds.io.payloads.RSAEncryptingPayload; -import org.jclouds.logging.Logger; - -import com.google.common.base.Predicate; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Lists; -import com.google.common.io.ByteStreams; -import com.google.common.io.InputSupplier; - -/** - * - * @author Adrian Cole - */ -@Singleton -public class BaseChefService implements ChefService { - - @Resource - @Named(ChefConstants.CHEF_LOGGER) - protected Logger logger = Logger.NULL; - - private final ChefContext chefContext; - private final CleanupStaleNodesAndClients cleanupStaleNodesAndClients; - private final CreateNodeAndPopulateAutomaticAttributes createNodeAndPopulateAutomaticAttributes; - private final DeleteAllNodesInList deleteAllNodesInList; - private final ListNodes listNodes; - private final DeleteAllClientsInList deleteAllClientsInList; - private final ListClients listClients; - private final UpdateAutomaticAttributesOnNode updateAutomaticAttributesOnNode; - private final Provider privateKey; - private final TagToBootScript tagToBootScript; - private final String databag; - private final RunListForTag runListForTag; - private final ListCookbookVersions listCookbookVersions; - - @Inject - protected BaseChefService(ChefContext chefContext, CleanupStaleNodesAndClients cleanupStaleNodesAndClients, - CreateNodeAndPopulateAutomaticAttributes createNodeAndPopulateAutomaticAttributes, - DeleteAllNodesInList deleteAllNodesInList, ListNodes listNodes, - DeleteAllClientsInList deleteAllClientsInList, ListClients listClients, - ListCookbookVersions listCookbookVersions, UpdateAutomaticAttributesOnNode updateAutomaticAttributesOnNode, - Provider privateKey, @Named(CHEF_BOOTSTRAP_DATABAG) String databag, - TagToBootScript tagToBootScript, RunListForTag runListForTag) { - this.chefContext = checkNotNull(chefContext, "chefContext"); - this.cleanupStaleNodesAndClients = checkNotNull(cleanupStaleNodesAndClients, "cleanupStaleNodesAndClients"); - this.createNodeAndPopulateAutomaticAttributes = checkNotNull(createNodeAndPopulateAutomaticAttributes, - "createNodeAndPopulateAutomaticAttributes"); - this.deleteAllNodesInList = checkNotNull(deleteAllNodesInList, "deleteAllNodesInList"); - this.listNodes = checkNotNull(listNodes, "listNodes"); - this.deleteAllClientsInList = checkNotNull(deleteAllClientsInList, "deleteAllClientsInList"); - this.listClients = checkNotNull(listClients, "listClients"); - this.listCookbookVersions = checkNotNull(listCookbookVersions, "listCookbookVersions"); - this.updateAutomaticAttributesOnNode = checkNotNull(updateAutomaticAttributesOnNode, - "updateAutomaticAttributesOnNode"); - this.privateKey = checkNotNull(privateKey, "privateKey"); - this.tagToBootScript = checkNotNull(tagToBootScript, "tagToBootScript"); - this.databag = checkNotNull(databag, "databag"); - this.runListForTag = checkNotNull(runListForTag, "runListForTag"); - } - - @Override - public void cleanupStaleNodesAndClients(String prefix, int secondsStale) { - cleanupStaleNodesAndClients.execute(prefix, secondsStale); - } - - @Override - public Node createNodeAndPopulateAutomaticAttributes(String nodeName, Iterable runList) { - return createNodeAndPopulateAutomaticAttributes.execute(nodeName, runList); - } - - @Override - public void deleteAllNodesInList(Iterable names) { - deleteAllNodesInList.execute(names); - } - - @Override - public Iterable listNodes() { - return listNodes.execute(); - } - - @Override - public Iterable listNodesMatching(Predicate nodeNameSelector) { - return listNodes.execute(nodeNameSelector); - } - - @Override - public Iterable listNodesNamed(Iterable names) { - return listNodes.execute(names); - } - - @Override - public void deleteAllClientsInList(Iterable names) { - deleteAllClientsInList.execute(names); - } - - @Override - public Iterable listClientsDetails() { - return listClients.execute(); - } - - @Override - public Iterable listClientsDetailsMatching(Predicate clientNameSelector) { - return listClients.execute(clientNameSelector); - } - - @Override - public Iterable listClientsNamed(Iterable names) { - return listClients.execute(names); - } - - @Override - public Iterable listCookbookVersions() { - return listCookbookVersions.execute(); - } - - @Override - public Iterable listCookbookVersionsMatching(Predicate cookbookNameSelector) { - return listCookbookVersions.execute(cookbookNameSelector); - } - - @Override - public Iterable listCookbookVersionsNamed(Iterable names) { - return listCookbookVersions.execute(names); - } - - - @Override - public void updateAutomaticAttributesOnNode(String nodeName) { - updateAutomaticAttributesOnNode.execute(nodeName); - } - - @Override - public ChefContext getContext() { - return chefContext; - } - - @Override - public Payload createClientAndBootstrapScriptForTag(String tag) { - return tagToBootScript.apply(tag); - } - - @Override - public void updateRunListForTag(Iterable runList, String tag) { - try { - chefContext.getApi().createDatabag(databag); - } catch (IllegalStateException e) { - - } - chefContext.getApi().updateDatabagItem( - databag, - new DatabagItem(tag, chefContext.utils().json().toJson( - ImmutableMap.> of("run_list", Lists.newArrayList(runList)), - RunListForTag.RUN_LIST_TYPE))); - } - - @Override - public List getRunListForTag(String tag) { - return runListForTag.apply(tag); - } - - @Override - public byte[] decrypt(InputSupplier supplier) throws IOException { - return ByteStreams.toByteArray(new RSADecryptingPayload(Payloads.newPayload(supplier.getInput()), privateKey - .get())); - } - - @Override - public byte[] encrypt(InputSupplier supplier) throws IOException { - return ByteStreams.toByteArray(new RSAEncryptingPayload(Payloads.newPayload(supplier.getInput()), privateKey - .get())); - } - -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/internal/ChefContextImpl.java b/chef/core/src/main/java/org/jclouds/chef/internal/ChefContextImpl.java deleted file mode 100644 index 89457fba24..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/internal/ChefContextImpl.java +++ /dev/null @@ -1,61 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.internal; - -import java.net.URI; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import org.jclouds.chef.ChefAsyncClient; -import org.jclouds.chef.ChefClient; -import org.jclouds.chef.ChefContext; -import org.jclouds.chef.ChefService; -import org.jclouds.lifecycle.Closer; -import org.jclouds.rest.Utils; -import org.jclouds.rest.annotations.ApiVersion; -import org.jclouds.rest.annotations.Identity; -import org.jclouds.rest.annotations.Provider; -import org.jclouds.rest.internal.RestContextImpl; - -import com.google.inject.Injector; -import com.google.inject.TypeLiteral; - -/** - * @author Adrian Cole - */ -@Singleton -public class ChefContextImpl extends RestContextImpl implements ChefContext { - private final ChefService chefService; - - @Inject - protected ChefContextImpl(Closer closer, Utils utils, Injector injector, TypeLiteral syncApi, - TypeLiteral asyncApi, @Provider URI endpoint, @Provider String provider, - @Identity String identity, @ApiVersion String apiVersion, ChefService chefService) { - super(closer, utils, injector, syncApi, asyncApi, endpoint, provider, identity, apiVersion); - this.chefService = chefService; - } - - @Override - public ChefService getChefService() { - return chefService; - } - -} diff --git a/chef/core/src/main/java/org/jclouds/chef/predicates/CookbookVersionPredicates.java b/chef/core/src/main/java/org/jclouds/chef/predicates/CookbookVersionPredicates.java deleted file mode 100644 index e0d298caf7..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/predicates/CookbookVersionPredicates.java +++ /dev/null @@ -1,97 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.predicates; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.collect.Iterables.any; -import static com.google.common.collect.Iterables.get; - -import org.jclouds.chef.domain.CookbookVersion; -import org.jclouds.chef.domain.Resource; - -import com.google.common.base.Predicate; -import com.google.common.base.Splitter; -import com.google.common.collect.LinkedListMultimap; -import com.google.common.collect.Multimap; - -/** - * Container for cookbook filters (predicates). - * - * This class has static methods that create customized predicates to use with - * {@link org.jclouds.chef.ChefService}. - * - * @author Adrian Cole - */ -public class CookbookVersionPredicates { - /** - * @see #containsRecipes - */ - public static Predicate containsRecipe(String recipe) { - return containsRecipes(checkNotNull(recipe, "recipe must be defined")); - } - - /** - * Note that the default recipe of a cookbook is its name. Otherwise, you prefix the recipe with - * the name of the cookbook. ex. {@code apache2} will be the default recipe where {@code - * apache2::mod_proxy} is a specific one in the cookbook. - * - * @param recipes - * names of the recipes. - * @return true if the cookbook version contains a recipe in the list. - */ - public static Predicate containsRecipes(String... recipes) { - checkNotNull(recipes, "recipes must be defined"); - final Multimap search = LinkedListMultimap.create(); - for (String recipe : recipes) { - if (recipe.indexOf("::") != -1) { - Iterable nameRecipe = Splitter.on("::").split(recipe); - search.put(get(nameRecipe, 0), get(nameRecipe, 1) + ".rb"); - } else { - search.put(recipe, "default.rb"); - } - } - return new Predicate() { - @Override - public boolean apply(final CookbookVersion cookbookVersion) { - return search.containsKey(cookbookVersion.getCookbookName()) - && any(search.get(cookbookVersion.getCookbookName()), new Predicate() { - - @Override - public boolean apply(final String recipeName) { - return any(cookbookVersion.getRecipes(), new Predicate() { - - @Override - public boolean apply(Resource resource) { - return resource.getName().equals(recipeName); - } - - }); - } - - }); - } - - @Override - public String toString() { - return "containsRecipes(" + search + ")"; - } - }; - } -} diff --git a/chef/core/src/main/java/org/jclouds/chef/reference/ChefConstants.java b/chef/core/src/main/java/org/jclouds/chef/reference/ChefConstants.java deleted file mode 100644 index 1286124a36..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/reference/ChefConstants.java +++ /dev/null @@ -1,58 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.reference; - -/** - * Configuration properties and constants used in Chef connections. - * - * @author Adrian Cole - */ -public interface ChefConstants { - /** - * There are generally 3 types of identities - *

- * - */ - - /** - * The PEM-encoded key - */ - - /** - * how often to refresh timestamps in seconds. - */ - - public static final String CHEF_LOGGER = "jclouds.chef"; - public static final String CHEF_SERVICE_CLIENT = "chef.service-client"; - public static final String CHEF_NODE = "chef.node"; - public static final String CHEF_NODE_PATTERN = "chef.node-pattern"; - public static final String CHEF_RUN_LIST = "chef.run-list"; - /** - * databag that holds chef bootstrap hints, should be a json ball in the following format: - *

- * {"tag":{"run_list":["recipe[apache2]"]}} - */ - public static final String CHEF_BOOTSTRAP_DATABAG = "chef.bootstrap-databag"; - -} diff --git a/chef/core/src/main/java/org/jclouds/chef/statements/InstallChefGems.java b/chef/core/src/main/java/org/jclouds/chef/statements/InstallChefGems.java deleted file mode 100644 index 6681f743c0..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/statements/InstallChefGems.java +++ /dev/null @@ -1,54 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.statements; - -import java.io.IOException; -import java.util.Collections; - -import javax.inject.Singleton; - -import org.jclouds.scriptbuilder.domain.OsFamily; -import org.jclouds.scriptbuilder.domain.Statement; -import org.jclouds.util.Utils; - -import com.google.common.base.Throwables; - -/** - * @author Adrian Cole - */ -@Singleton -public class InstallChefGems implements Statement { - @Override - public String render(OsFamily family) { - try { - return Utils.toStringAndClose(InstallChefGems.class.getClassLoader().getResourceAsStream( - "install-chef-gems.sh")); - } catch (IOException e) { - Throwables.propagate(e); - return null; - } - } - - @Override - public Iterable functionDependecies(OsFamily family) { - return Collections.emptyList(); - } - -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/strategy/CleanupStaleNodesAndClients.java b/chef/core/src/main/java/org/jclouds/chef/strategy/CleanupStaleNodesAndClients.java deleted file mode 100644 index be4a3dc328..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/strategy/CleanupStaleNodesAndClients.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.strategy; - -import org.jclouds.chef.strategy.internal.CleanupStaleNodesAndClientsImpl; - -import com.google.inject.ImplementedBy; - -/** - * - * Cleans up nodes and clients who have been hanging around too long. - * - * @author Adrian Cole - */ -@ImplementedBy(CleanupStaleNodesAndClientsImpl.class) -public interface CleanupStaleNodesAndClients { - - void execute(String prefix, int secondsStale); - -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/strategy/CreateNodeAndPopulateAutomaticAttributes.java b/chef/core/src/main/java/org/jclouds/chef/strategy/CreateNodeAndPopulateAutomaticAttributes.java deleted file mode 100644 index 2edd7c540a..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/strategy/CreateNodeAndPopulateAutomaticAttributes.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.strategy; - -import org.jclouds.chef.domain.Node; -import org.jclouds.chef.strategy.internal.CreateNodeAndPopulateAutomaticAttributesImpl; - -import com.google.inject.ImplementedBy; - -/** - * - * Creates a new node with automatic attributes. - * - * @author Adrian Cole - */ -@ImplementedBy(CreateNodeAndPopulateAutomaticAttributesImpl.class) -public interface CreateNodeAndPopulateAutomaticAttributes { - Node execute(Node node); - - Node execute(String nodeName, Iterable runList); -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/strategy/DeleteAllClientsInList.java b/chef/core/src/main/java/org/jclouds/chef/strategy/DeleteAllClientsInList.java deleted file mode 100644 index 68a1ad21d1..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/strategy/DeleteAllClientsInList.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.strategy; - -import org.jclouds.chef.strategy.internal.DeleteAllClientsInListImpl; - -import com.google.inject.ImplementedBy; - -/** - * - * - * @author Adrian Cole - */ -@ImplementedBy(DeleteAllClientsInListImpl.class) -public interface DeleteAllClientsInList { - - public void execute(Iterable names); - -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/strategy/DeleteAllNodesInList.java b/chef/core/src/main/java/org/jclouds/chef/strategy/DeleteAllNodesInList.java deleted file mode 100644 index b7deb1f525..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/strategy/DeleteAllNodesInList.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.strategy; - -import org.jclouds.chef.strategy.internal.DeleteAllNodesInListImpl; - -import com.google.inject.ImplementedBy; - -/** - * - * - * @author Adrian Cole - */ -@ImplementedBy(DeleteAllNodesInListImpl.class) -public interface DeleteAllNodesInList { - - public void execute(Iterable names); - -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/strategy/ListClients.java b/chef/core/src/main/java/org/jclouds/chef/strategy/ListClients.java deleted file mode 100644 index eef05e2636..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/strategy/ListClients.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.strategy; - -import org.jclouds.chef.domain.Client; -import org.jclouds.chef.strategy.internal.ListClientsImpl; - -import com.google.common.base.Predicate; -import com.google.inject.ImplementedBy; - -/** - * - * - * @author Adrian Cole - */ -@ImplementedBy(ListClientsImpl.class) -public interface ListClients { - - Iterable execute(); - - Iterable execute(Predicate clientNameSelector); - - Iterable execute(Iterable toGet); -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/strategy/ListCookbookVersions.java b/chef/core/src/main/java/org/jclouds/chef/strategy/ListCookbookVersions.java deleted file mode 100644 index 4ef353cf16..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/strategy/ListCookbookVersions.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.strategy; - -import org.jclouds.chef.domain.CookbookVersion; -import org.jclouds.chef.strategy.internal.ListCookbookVersionsImpl; - -import com.google.common.base.Predicate; -import com.google.inject.ImplementedBy; - -/** - * - * - * @author Adrian Cole - */ -@ImplementedBy(ListCookbookVersionsImpl.class) -public interface ListCookbookVersions { - - Iterable execute(); - - Iterable execute(Predicate cookbookNameSelector); - - Iterable execute(Iterable cookbookNames); -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/strategy/ListNodes.java b/chef/core/src/main/java/org/jclouds/chef/strategy/ListNodes.java deleted file mode 100644 index d807783173..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/strategy/ListNodes.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.strategy; - -import org.jclouds.chef.domain.Node; -import org.jclouds.chef.strategy.internal.ListNodesImpl; - -import com.google.common.base.Predicate; -import com.google.inject.ImplementedBy; - -/** - * - * - * @author Adrian Cole - */ -@ImplementedBy(ListNodesImpl.class) -public interface ListNodes { - - Iterable execute(); - - Iterable execute(Predicate nodeNameSelector); - - Iterable execute(Iterable toGet); -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/strategy/UpdateAutomaticAttributesOnNode.java b/chef/core/src/main/java/org/jclouds/chef/strategy/UpdateAutomaticAttributesOnNode.java deleted file mode 100644 index 2832f8c734..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/strategy/UpdateAutomaticAttributesOnNode.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.strategy; - -import org.jclouds.chef.strategy.internal.UpdateAutomaticAttributesOnNodeImpl; - -import com.google.inject.ImplementedBy; - -/** - * - * Updates node with new automatic attributes. - * - * @author Adrian Cole - */ -@ImplementedBy(UpdateAutomaticAttributesOnNodeImpl.class) -public interface UpdateAutomaticAttributesOnNode { - - public void execute(String nodeName); -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/strategy/internal/CleanupStaleNodesAndClientsImpl.java b/chef/core/src/main/java/org/jclouds/chef/strategy/internal/CleanupStaleNodesAndClientsImpl.java deleted file mode 100644 index b5f19a91ab..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/strategy/internal/CleanupStaleNodesAndClientsImpl.java +++ /dev/null @@ -1,108 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.strategy.internal; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Predicates.and; -import static com.google.common.base.Predicates.notNull; -import static com.google.common.collect.Iterables.filter; -import static com.google.common.collect.Iterables.transform; -import static org.jclouds.chef.util.ChefUtils.fromOhaiTime; - -import java.util.Calendar; -import java.util.Date; - -import javax.annotation.Resource; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - -import org.jclouds.chef.domain.Node; -import org.jclouds.chef.reference.ChefConstants; -import org.jclouds.chef.strategy.CleanupStaleNodesAndClients; -import org.jclouds.chef.strategy.DeleteAllClientsInList; -import org.jclouds.chef.strategy.DeleteAllNodesInList; -import org.jclouds.chef.strategy.ListNodes; -import org.jclouds.domain.JsonBall; -import org.jclouds.logging.Logger; - -import com.google.common.base.Function; -import com.google.common.base.Predicate; - -/** - * - * Cleans up nodes and clients who have been hanging around too long. - * - * @author Adrian Cole - */ -@Singleton -public class CleanupStaleNodesAndClientsImpl implements CleanupStaleNodesAndClients { - @Resource - @Named(ChefConstants.CHEF_LOGGER) - protected Logger logger = Logger.NULL; - - private final ListNodes nodeLister; - private final DeleteAllNodesInList nodeDeleter; - private final DeleteAllClientsInList clientDeleter; - - @Inject - public CleanupStaleNodesAndClientsImpl(DeleteAllNodesInList nodeDeleter, DeleteAllClientsInList clientDeleter, - ListNodes nodeLister) { - this.nodeLister = checkNotNull(nodeLister, "nodeLister"); - this.nodeDeleter = checkNotNull(nodeDeleter, "nodeDeleter"); - this.clientDeleter = checkNotNull(clientDeleter, "clientDeleter"); - } - - @Override - public void execute(final String prefix, int secondsStale) { - final Calendar expired = Calendar.getInstance(); - expired.setTime(new Date()); - expired.add(Calendar.SECOND, -secondsStale); - Iterable staleNodes = filter(nodeLister.execute(new Predicate() { - - @Override - public boolean apply(String input) { - return input.startsWith(prefix); - } - - }), and(notNull(), new Predicate() { - @Override - public boolean apply(Node input) { - JsonBall dateLong = input.getAutomatic().get("ohai_time"); - if (dateLong == null) - return true; - Calendar nodeUpdate = Calendar.getInstance(); - nodeUpdate.setTime(fromOhaiTime(dateLong)); - return expired.after(nodeUpdate); - } - - })); - Iterable nodeNames = transform(staleNodes, new Function() { - - @Override - public String apply(Node from) { - return from.getName(); - } - - }); - nodeDeleter.execute(nodeNames); - clientDeleter.execute(nodeNames); - } -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/strategy/internal/CreateNodeAndPopulateAutomaticAttributesImpl.java b/chef/core/src/main/java/org/jclouds/chef/strategy/internal/CreateNodeAndPopulateAutomaticAttributesImpl.java deleted file mode 100644 index deae6156a8..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/strategy/internal/CreateNodeAndPopulateAutomaticAttributesImpl.java +++ /dev/null @@ -1,77 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.strategy.internal; - -import static com.google.common.base.Preconditions.checkNotNull; - -import java.util.Map; - -import javax.annotation.Resource; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - -import org.jclouds.chef.ChefClient; -import org.jclouds.chef.domain.Node; -import org.jclouds.chef.reference.ChefConstants; -import org.jclouds.chef.strategy.CreateNodeAndPopulateAutomaticAttributes; -import org.jclouds.domain.JsonBall; -import org.jclouds.logging.Logger; -import org.jclouds.ohai.Automatic; - -import com.google.common.base.Supplier; - -/** - * - * Updates node with new automatic attributes. - * - * @author Adrian Cole - */ -@Singleton -public class CreateNodeAndPopulateAutomaticAttributesImpl implements CreateNodeAndPopulateAutomaticAttributes { - - @Resource - @Named(ChefConstants.CHEF_LOGGER) - protected Logger logger = Logger.NULL; - - private final ChefClient chef; - private final Supplier> automaticSupplier; - - @Inject - public CreateNodeAndPopulateAutomaticAttributesImpl(ChefClient chef, - @Automatic Supplier> automaticSupplier) { - this.chef = checkNotNull(chef, "chef"); - this.automaticSupplier = checkNotNull(automaticSupplier, "automaticSupplier"); - } - - @Override - public Node execute(Node node) { - logger.trace("creating node %s", node.getName()); - node.getAutomatic().putAll(automaticSupplier.get()); - chef.createNode(node); - logger.debug("created node %s", node.getName()); - return node; - } - - @Override - public Node execute(String nodeName, Iterable runList) { - return execute(new Node(nodeName, runList)); - } -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/strategy/internal/DeleteAllClientsInListImpl.java b/chef/core/src/main/java/org/jclouds/chef/strategy/internal/DeleteAllClientsInListImpl.java deleted file mode 100644 index de771383dc..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/strategy/internal/DeleteAllClientsInListImpl.java +++ /dev/null @@ -1,81 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.strategy.internal; - -import static com.google.common.collect.Maps.newHashMap; -import static org.jclouds.concurrent.FutureIterables.awaitCompletion; - -import java.util.Map; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Future; - -import javax.annotation.Resource; -import javax.inject.Named; -import javax.inject.Singleton; - -import org.jclouds.Constants; -import org.jclouds.chef.ChefAsyncClient; -import org.jclouds.chef.ChefClient; -import org.jclouds.chef.reference.ChefConstants; -import org.jclouds.chef.strategy.DeleteAllClientsInList; -import org.jclouds.logging.Logger; - -import com.google.inject.Inject; - -/** - * - * - * @author Adrian Cole - */ -@Singleton -public class DeleteAllClientsInListImpl implements DeleteAllClientsInList { - - protected final ChefClient chefClient; - protected final ChefAsyncClient chefAsyncClient; - protected final ExecutorService userExecutor; - @Resource - @Named(ChefConstants.CHEF_LOGGER) - protected Logger logger = Logger.NULL; - - @Inject(optional = true) - @Named(Constants.PROPERTY_REQUEST_TIMEOUT) - protected Long maxTime; - - @Inject - DeleteAllClientsInListImpl(@Named(Constants.PROPERTY_USER_THREADS) ExecutorService userExecutor, - ChefClient getAllClient, ChefAsyncClient ablobstore) { - this.userExecutor = userExecutor; - this.chefAsyncClient = ablobstore; - this.chefClient = getAllClient; - } - - @Override - public void execute(Iterable names) { - Map exceptions = newHashMap(); - Map> responses = newHashMap(); - for (String name : names) { - responses.put(name, chefAsyncClient.deleteClient(name)); - } - exceptions = awaitCompletion(responses, userExecutor, maxTime, logger, String.format( - "deleting clients: %s", names)); - if (exceptions.size() > 0) - throw new RuntimeException(String.format("errors deleting clients: %s: %s", names, exceptions)); - } -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/strategy/internal/DeleteAllNodesInListImpl.java b/chef/core/src/main/java/org/jclouds/chef/strategy/internal/DeleteAllNodesInListImpl.java deleted file mode 100644 index 1de4f361f1..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/strategy/internal/DeleteAllNodesInListImpl.java +++ /dev/null @@ -1,81 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.strategy.internal; - -import static com.google.common.collect.Maps.newHashMap; -import static org.jclouds.concurrent.FutureIterables.awaitCompletion; - -import java.util.Map; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Future; - -import javax.annotation.Resource; -import javax.inject.Named; -import javax.inject.Singleton; - -import org.jclouds.Constants; -import org.jclouds.chef.ChefAsyncClient; -import org.jclouds.chef.ChefClient; -import org.jclouds.chef.reference.ChefConstants; -import org.jclouds.chef.strategy.DeleteAllNodesInList; -import org.jclouds.logging.Logger; - -import com.google.inject.Inject; - -/** - * - * - * @author Adrian Cole - */ -@Singleton -public class DeleteAllNodesInListImpl implements DeleteAllNodesInList { - - protected final ChefClient chefClient; - protected final ChefAsyncClient chefAsyncClient; - protected final ExecutorService userExecutor; - @Resource - @Named(ChefConstants.CHEF_LOGGER) - protected Logger logger = Logger.NULL; - - @Inject(optional = true) - @Named(Constants.PROPERTY_REQUEST_TIMEOUT) - protected Long maxTime; - - @Inject - DeleteAllNodesInListImpl(@Named(Constants.PROPERTY_USER_THREADS) ExecutorService userExecutor, - ChefClient getAllNode, ChefAsyncClient ablobstore) { - this.userExecutor = userExecutor; - this.chefAsyncClient = ablobstore; - this.chefClient = getAllNode; - } - - @Override - public void execute(Iterable names) { - Map exceptions = newHashMap(); - Map> responses = newHashMap(); - for (String name : names) { - responses.put(name, chefAsyncClient.deleteNode(name)); - } - exceptions = awaitCompletion(responses, userExecutor, maxTime, logger, String.format( - "deleting nodes: %s", names)); - if (exceptions.size() > 0) - throw new RuntimeException(String.format("errors deleting nodes: %s: %s", names, exceptions)); - } -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/strategy/internal/ListClientsImpl.java b/chef/core/src/main/java/org/jclouds/chef/strategy/internal/ListClientsImpl.java deleted file mode 100644 index 80bf87fe56..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/strategy/internal/ListClientsImpl.java +++ /dev/null @@ -1,94 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.strategy.internal; - -import static com.google.common.collect.Iterables.filter; -import static org.jclouds.concurrent.FutureIterables.transformParallel; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Future; - -import javax.annotation.Resource; -import javax.inject.Named; -import javax.inject.Singleton; - -import org.jclouds.Constants; -import org.jclouds.chef.ChefAsyncClient; -import org.jclouds.chef.ChefClient; -import org.jclouds.chef.domain.Client; -import org.jclouds.chef.reference.ChefConstants; -import org.jclouds.chef.strategy.ListClients; -import org.jclouds.logging.Logger; - -import com.google.common.base.Function; -import com.google.common.base.Predicate; -import com.google.inject.Inject; - -/** - * - * - * @author Adrian Cole - */ -@Singleton -public class ListClientsImpl implements ListClients { - - protected final ChefClient chefClient; - protected final ChefAsyncClient chefAsyncClient; - protected final ExecutorService userExecutor; - @Resource - @Named(ChefConstants.CHEF_LOGGER) - protected Logger logger = Logger.NULL; - - @Inject(optional = true) - @Named(Constants.PROPERTY_REQUEST_TIMEOUT) - protected Long maxTime; - - @Inject - ListClientsImpl(@Named(Constants.PROPERTY_USER_THREADS) ExecutorService userExecutor, ChefClient getAllClient, - ChefAsyncClient ablobstore) { - this.userExecutor = userExecutor; - this.chefAsyncClient = ablobstore; - this.chefClient = getAllClient; - } - - @Override - public Iterable execute() { - return execute(chefClient.listClients()); - } - - @Override - public Iterable execute(Predicate clientNameSelector) { - return execute(filter(chefClient.listClients(), clientNameSelector)); - } - - @Override - public Iterable execute(Iterable toGet) { - return transformParallel(toGet, new Function>() { - - @Override - public Future apply(String from) { - return chefAsyncClient.getClient(from); - } - - }, userExecutor, maxTime, logger, "getting clients"); - - } - -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/strategy/internal/ListCookbookVersionsImpl.java b/chef/core/src/main/java/org/jclouds/chef/strategy/internal/ListCookbookVersionsImpl.java deleted file mode 100644 index dff73418fd..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/strategy/internal/ListCookbookVersionsImpl.java +++ /dev/null @@ -1,104 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.strategy.internal; - -import static com.google.common.collect.Iterables.concat; -import static com.google.common.collect.Iterables.filter; -import static com.google.common.collect.Iterables.transform; -import static org.jclouds.concurrent.FutureIterables.transformParallel; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Future; - -import javax.annotation.Resource; -import javax.inject.Named; -import javax.inject.Singleton; - -import org.jclouds.Constants; -import org.jclouds.chef.ChefAsyncClient; -import org.jclouds.chef.ChefClient; -import org.jclouds.chef.domain.CookbookVersion; -import org.jclouds.chef.reference.ChefConstants; -import org.jclouds.chef.strategy.ListCookbookVersions; -import org.jclouds.logging.Logger; - -import com.google.common.base.Function; -import com.google.common.base.Predicate; -import com.google.inject.Inject; - -/** - * - * - * @author Adrian Cole - */ -@Singleton -public class ListCookbookVersionsImpl implements ListCookbookVersions { - - protected final ChefClient chefClient; - protected final ChefAsyncClient chefAsyncClient; - protected final ExecutorService userExecutor; - @Resource - @Named(ChefConstants.CHEF_LOGGER) - protected Logger logger = Logger.NULL; - - @Inject(optional = true) - @Named(Constants.PROPERTY_REQUEST_TIMEOUT) - protected Long maxTime; - - @Inject - ListCookbookVersionsImpl(@Named(Constants.PROPERTY_USER_THREADS) ExecutorService userExecutor, - ChefClient getAllCookbookVersion, ChefAsyncClient ablobstore) { - this.userExecutor = userExecutor; - this.chefAsyncClient = ablobstore; - this.chefClient = getAllCookbookVersion; - } - - @Override - public Iterable execute() { - return execute(chefClient.listCookbooks()); - } - - @Override - public Iterable execute(Predicate cookbookNameSelector) { - return execute(filter(chefClient.listCookbooks(), cookbookNameSelector)); - } - - @Override - public Iterable execute(Iterable toGet) { - return concat(transform(toGet, new Function>() { - - @Override - public Iterable apply(final String cookbook) { - // TODO getting each version could also go parallel - return transformParallel(chefClient.getVersionsOfCookbook(cookbook), - new Function>() { - - @Override - public Future apply(String version) { - return chefAsyncClient.getCookbook(cookbook, version); - } - - }, userExecutor, maxTime, logger, "getting versions of cookbook " + cookbook); - } - - })); - } - -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/strategy/internal/ListNodesImpl.java b/chef/core/src/main/java/org/jclouds/chef/strategy/internal/ListNodesImpl.java deleted file mode 100644 index be3399e7ed..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/strategy/internal/ListNodesImpl.java +++ /dev/null @@ -1,94 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.strategy.internal; - -import static com.google.common.collect.Iterables.filter; -import static org.jclouds.concurrent.FutureIterables.transformParallel; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Future; - -import javax.annotation.Resource; -import javax.inject.Named; -import javax.inject.Singleton; - -import org.jclouds.Constants; -import org.jclouds.chef.ChefAsyncClient; -import org.jclouds.chef.ChefClient; -import org.jclouds.chef.domain.Node; -import org.jclouds.chef.reference.ChefConstants; -import org.jclouds.chef.strategy.ListNodes; -import org.jclouds.logging.Logger; - -import com.google.common.base.Function; -import com.google.common.base.Predicate; -import com.google.inject.Inject; - -/** - * - * - * @author Adrian Cole - */ -@Singleton -public class ListNodesImpl implements ListNodes { - - protected final ChefClient chefClient; - protected final ChefAsyncClient chefAsyncClient; - protected final ExecutorService userExecutor; - @Resource - @Named(ChefConstants.CHEF_LOGGER) - protected Logger logger = Logger.NULL; - - @Inject(optional = true) - @Named(Constants.PROPERTY_REQUEST_TIMEOUT) - protected Long maxTime; - - @Inject - ListNodesImpl(@Named(Constants.PROPERTY_USER_THREADS) ExecutorService userExecutor, ChefClient getAllNode, - ChefAsyncClient ablobstore) { - this.userExecutor = userExecutor; - this.chefAsyncClient = ablobstore; - this.chefClient = getAllNode; - } - - @Override - public Iterable execute() { - return execute(chefClient.listNodes()); - } - - @Override - public Iterable execute(Predicate nodeNameSelector) { - return execute(filter(chefClient.listNodes(), nodeNameSelector)); - } - - @Override - public Iterable execute(Iterable toGet) { - return transformParallel(toGet, new Function>() { - - @Override - public Future apply(String from) { - return chefAsyncClient.getNode(from); - } - - }, userExecutor, maxTime, logger, "getting nodes"); - - } - -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/strategy/internal/UpdateAutomaticAttributesOnNodeImpl.java b/chef/core/src/main/java/org/jclouds/chef/strategy/internal/UpdateAutomaticAttributesOnNodeImpl.java deleted file mode 100644 index dc9b8a2cf1..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/strategy/internal/UpdateAutomaticAttributesOnNodeImpl.java +++ /dev/null @@ -1,72 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.strategy.internal; - -import static com.google.common.base.Preconditions.checkNotNull; - -import java.util.Map; - -import javax.annotation.Resource; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - -import org.jclouds.chef.ChefClient; -import org.jclouds.chef.domain.Node; -import org.jclouds.chef.reference.ChefConstants; -import org.jclouds.chef.strategy.UpdateAutomaticAttributesOnNode; -import org.jclouds.domain.JsonBall; -import org.jclouds.logging.Logger; -import org.jclouds.ohai.Automatic; - -import com.google.common.base.Supplier; - -/** - * - * Updates node with new automatic attributes. - * - * @author Adrian Cole - */ -@Singleton -public class UpdateAutomaticAttributesOnNodeImpl implements UpdateAutomaticAttributesOnNode { - - @Resource - @Named(ChefConstants.CHEF_LOGGER) - protected Logger logger = Logger.NULL; - - private final ChefClient chef; - private final Supplier> automaticSupplier; - - @Inject - public UpdateAutomaticAttributesOnNodeImpl(ChefClient chef, - @Automatic Supplier> automaticSupplier) { - this.chef = checkNotNull(chef, "chef"); - this.automaticSupplier = checkNotNull(automaticSupplier, "automaticSupplier"); - } - - @Override - public void execute(String nodeName) { - logger.trace("updating node %s", nodeName); - Node node = chef.getNode(nodeName); - node.getAutomatic().putAll(automaticSupplier.get()); - chef.updateNode(node); - logger.debug("updated node %s", nodeName); - } -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/test/TransientChefAsyncClient.java b/chef/core/src/main/java/org/jclouds/chef/test/TransientChefAsyncClient.java deleted file mode 100644 index e1cde03148..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/test/TransientChefAsyncClient.java +++ /dev/null @@ -1,346 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.test; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Throwables.propagate; -import static com.google.common.collect.Iterables.transform; -import static com.google.common.collect.Sets.newLinkedHashSet; -import static org.jclouds.concurrent.Futures.compose; - -import java.io.IOException; -import java.util.List; -import java.util.Set; -import java.util.concurrent.ExecutorService; - -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - -import org.jclouds.Constants; -import org.jclouds.blobstore.TransientAsyncBlobStore; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.blobstore.domain.PageSet; -import org.jclouds.blobstore.domain.StorageMetadata; -import org.jclouds.chef.ChefAsyncClient; -import org.jclouds.chef.domain.Client; -import org.jclouds.chef.domain.CookbookVersion; -import org.jclouds.chef.domain.DatabagItem; -import org.jclouds.chef.domain.Node; -import org.jclouds.chef.domain.Role; -import org.jclouds.chef.domain.Sandbox; -import org.jclouds.chef.domain.SearchResult; -import org.jclouds.chef.domain.UploadSandbox; -import org.jclouds.util.Utils; - -import com.google.common.base.Function; -import com.google.common.util.concurrent.Futures; -import com.google.common.util.concurrent.ListenableFuture; - -/** - * In-memory chef simulator. - * - * @author Adrian Cole - */ - -public class TransientChefAsyncClient implements ChefAsyncClient { - @Singleton - private static class StorageMetadataToName implements Function, Set> { - @Override - public Set apply(PageSet from) { - return newLinkedHashSet(transform(from, new Function() { - - @Override - public String apply(StorageMetadata from) { - return from.getName(); - } - })); - } - } - - @Singleton - private static class BlobToDatabagItem implements Function { - @Override - public DatabagItem apply(Blob from) { - try { - return from == null ? null : new DatabagItem(from.getMetadata().getName(), Utils.toStringAndClose(from - .getPayload().getInput())); - } catch (IOException e) { - propagate(e); - return null; - } - } - } - - private final TransientAsyncBlobStore databags; - private final ExecutorService executor; - private final BlobToDatabagItem blobToDatabagItem; - private final StorageMetadataToName storageMetadataToName; - - @Inject - TransientChefAsyncClient(@Named("databags") TransientAsyncBlobStore databags, - StorageMetadataToName storageMetadataToName, BlobToDatabagItem blobToDatabagItem, - @Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor) { - this.databags = checkNotNull(databags, "databags"); - this.storageMetadataToName = checkNotNull(storageMetadataToName, "storageMetadataToName"); - this.blobToDatabagItem = checkNotNull(blobToDatabagItem, "blobToDatabagItem"); - this.executor = checkNotNull(executor, "executor"); - } - - @Override - public ListenableFuture clientExists(String clientname) { - // TODO Auto-generated method stub - return null; - } - - @Override - public ListenableFuture commitSandbox(String id, boolean isCompleted) { - // TODO Auto-generated method stub - return null; - } - - @Override - public ListenableFuture createClient(String clientname) { - // TODO Auto-generated method stub - return null; - } - - @Override - public ListenableFuture createDatabag(String databagName) { - return databags.createContainerInLocationIfAbsent(null, databagName); - } - - @Override - public ListenableFuture createDatabagItem(String databagName, DatabagItem databagItem) { - Blob blob = databags.newBlob(databagItem.getId()); - blob.setPayload(databagItem.toString()); - databags.putBlobAndReturnOld(databagName, blob); - return Futures.immediateFuture(databagItem); - } - - @Override - public ListenableFuture createNode(Node node) { - // TODO Auto-generated method stub - return null; - } - - @Override - public ListenableFuture createRole(Role role) { - // TODO Auto-generated method stub - return null; - } - - @Override - public ListenableFuture databagExists(String databagName) { - return databags.containerExists(databagName); - } - - @Override - public ListenableFuture databagItemExists(String databagName, String databagItemId) { - return databags.blobExists(databagName, databagItemId); - } - - @Override - public ListenableFuture deleteClient(String clientname) { - // TODO Auto-generated method stub - return null; - } - - @Override - public ListenableFuture deleteCookbook(String cookbookName, String version) { - // TODO Auto-generated method stub - return null; - } - - @Override - public ListenableFuture deleteDatabag(String databagName) { - return databags.deleteContainer(databagName); - } - - @Override - public ListenableFuture deleteDatabagItem(String databagName, String databagItemId) { - return compose(databags.removeBlobAndReturnOld(databagName, databagItemId), blobToDatabagItem, executor); - } - - @Override - public ListenableFuture deleteNode(String nodename) { - // TODO Auto-generated method stub - return null; - } - - @Override - public ListenableFuture deleteRole(String rolename) { - // TODO Auto-generated method stub - return null; - } - - @Override - public ListenableFuture generateKeyForClient(String clientname) { - // TODO Auto-generated method stub - return null; - } - - @Override - public ListenableFuture getClient(String clientname) { - // TODO Auto-generated method stub - return null; - } - - @Override - public ListenableFuture getCookbook(String cookbookName, String version) { - // TODO Auto-generated method stub - return null; - } - - @Override - public ListenableFuture getDatabagItem(String databagName, String databagItemId) { - return compose(databags.getBlob(databagName, databagItemId), blobToDatabagItem, executor); - } - - @Override - public ListenableFuture getNode(String nodename) { - // TODO Auto-generated method stub - return null; - } - - @Override - public ListenableFuture getRole(String rolename) { - // TODO Auto-generated method stub - return null; - } - - @Override - public ListenableFuture getUploadSandboxForChecksums(Set> md5s) { - // TODO Auto-generated method stub - return null; - } - - @Override - public ListenableFuture> getVersionsOfCookbook(String cookbookName) { - // TODO Auto-generated method stub - return null; - } - - @Override - public ListenableFuture> listClients() { - // TODO Auto-generated method stub - return null; - } - - @Override - public ListenableFuture> listCookbooks() { - // TODO Auto-generated method stub - return null; - } - - @Override - public ListenableFuture> listDatabagItems(String databagName) { - return compose(databags.list(databagName), storageMetadataToName, executor); - } - - @Override - public ListenableFuture> listDatabags() { - return compose(databags.list(), storageMetadataToName, executor); - } - - @Override - public ListenableFuture> listNodes() { - // TODO Auto-generated method stub - return null; - } - - @Override - public ListenableFuture> listRoles() { - // TODO Auto-generated method stub - return null; - } - - @Override - public ListenableFuture> listSearchIndexes() { - // TODO Auto-generated method stub - return null; - } - - @Override - public ListenableFuture nodeExists(String nodename) { - // TODO Auto-generated method stub - return null; - } - - @Override - public ListenableFuture roleExists(String rolename) { - // TODO Auto-generated method stub - return null; - } - - @Override - public ListenableFuture> searchClients() { - // TODO Auto-generated method stub - return null; - } - - @Override - public ListenableFuture> searchDatabag(String databagName) { - // TODO Auto-generated method stub - return null; - } - - @Override - public ListenableFuture> searchNodes() { - // TODO Auto-generated method stub - return null; - } - - @Override - public ListenableFuture> searchRoles() { - // TODO Auto-generated method stub - return null; - } - - @Override - public ListenableFuture updateCookbook(String cookbookName, String version, CookbookVersion cookbook) { - // TODO Auto-generated method stub - return null; - } - - @Override - public ListenableFuture updateDatabagItem(String databagName, DatabagItem item) { - return createDatabagItem(databagName, item); - } - - @Override - public ListenableFuture updateNode(Node node) { - // TODO Auto-generated method stub - return null; - } - - @Override - public ListenableFuture updateRole(Role role) { - // TODO Auto-generated method stub - return null; - } - - @Override - public ListenableFuture uploadContent(Set> md5s) { - // TODO Auto-generated method stub - return null; - } - -} diff --git a/chef/core/src/main/java/org/jclouds/chef/test/TransientChefClient.java b/chef/core/src/main/java/org/jclouds/chef/test/TransientChefClient.java deleted file mode 100644 index 7aa44781b7..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/test/TransientChefClient.java +++ /dev/null @@ -1,39 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.test; - -import java.util.concurrent.TimeUnit; - -import org.jclouds.chef.ChefAsyncClient; -import org.jclouds.chef.ChefClient; -import org.jclouds.concurrent.Timeout; - -/** - * In-memory chef simulator. - *

- * - * @see ChefAsyncClient - * @see - * @author Adrian Cole - */ -@Timeout(duration = 30, timeUnit = TimeUnit.MILLISECONDS) -public interface TransientChefClient extends ChefClient { - -} diff --git a/chef/core/src/main/java/org/jclouds/chef/test/TransientChefContextBuilder.java b/chef/core/src/main/java/org/jclouds/chef/test/TransientChefContextBuilder.java deleted file mode 100644 index 8a98f87f22..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/test/TransientChefContextBuilder.java +++ /dev/null @@ -1,43 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.test; - -import java.util.List; -import java.util.Properties; - -import org.jclouds.chef.ChefContextBuilder; -import org.jclouds.chef.test.config.TransientChefClientModule; - -import com.google.inject.Module; - -/** - * @author Adrian Cole - */ -public class TransientChefContextBuilder extends ChefContextBuilder { - - public TransientChefContextBuilder(Properties props) { - super(props); - } - - @Override - protected void addClientModule(List modules) { - modules.add(new TransientChefClientModule()); - } -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/test/config/TransientChefClientModule.java b/chef/core/src/main/java/org/jclouds/chef/test/config/TransientChefClientModule.java deleted file mode 100644 index 2b6587a671..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/test/config/TransientChefClientModule.java +++ /dev/null @@ -1,85 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.jclouds.chef.test.config; - -import java.util.List; -import java.util.Map; - -import javax.inject.Singleton; - -import org.jclouds.blobstore.TransientAsyncBlobStore; -import org.jclouds.chef.ChefAsyncClient; -import org.jclouds.chef.ChefClient; -import org.jclouds.chef.config.BaseChefRestClientModule; -import org.jclouds.chef.domain.Client; -import org.jclouds.chef.functions.ClientForTag; -import org.jclouds.chef.functions.RunListForTag; -import org.jclouds.chef.statements.InstallChefGems; -import org.jclouds.chef.test.TransientChefAsyncClient; -import org.jclouds.chef.test.TransientChefClient; -import org.jclouds.rest.RestContextFactory; -import org.jclouds.scriptbuilder.domain.Statement; - -import com.google.common.collect.MapMaker; -import com.google.inject.Provides; -import com.google.inject.name.Names; - -/** - * - * @author Adrian Cole - */ -public class TransientChefClientModule extends BaseChefRestClientModule { - - public TransientChefClientModule() { - super(TransientChefClient.class, ChefAsyncClient.class); - } - - @Override - protected void configure() { - bind(TransientAsyncBlobStore.class).annotatedWith(Names.named("databags")).toInstance( - new RestContextFactory().createContextBuilder("transient", "foo", "bar").buildInjector().getInstance( - TransientAsyncBlobStore.class)); - bind(Statement.class).annotatedWith(Names.named("installChefGems")).to(InstallChefGems.class); - super.configure(); - } - - @Override - protected void bindAsyncClient() { - bind(ChefAsyncClient.class).to(TransientChefAsyncClient.class).asEagerSingleton(); - } - - @Provides - @Singleton - ChefClient provideClient(TransientChefClient in) { - return in; - } - - @Provides - @Singleton - Map> runListForTag(RunListForTag runListForTag) { - return new MapMaker().makeComputingMap(runListForTag); - } - - @Provides - @Singleton - Map tagToClient(ClientForTag tagToClient) { - return new MapMaker().makeComputingMap(tagToClient); - } - -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/util/ChefUtils.java b/chef/core/src/main/java/org/jclouds/chef/util/ChefUtils.java deleted file mode 100644 index e611cb88b0..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/util/ChefUtils.java +++ /dev/null @@ -1,79 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.util; - -import static com.google.common.base.Preconditions.checkNotNull; - -import java.util.Date; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.jclouds.domain.JsonBall; -import org.jclouds.ohai.Automatic; -import org.jclouds.ohai.config.multibindings.MapBinder; - -import com.google.common.base.Predicate; -import com.google.common.base.Supplier; -import com.google.common.collect.Iterables; -import com.google.inject.Binder; -import com.google.inject.TypeLiteral; - -/** - * - * - * @author Adrian Cole - */ -public class ChefUtils { - - public static Date fromOhaiTime(JsonBall ohaiDate) { - return new Date(Long.parseLong(checkNotNull(ohaiDate, "ohaiDate").toString().replaceAll("\\.[0-9]*$", ""))); - } - - public static JsonBall toOhaiTime(long millis) { - return new JsonBall(millis + ""); - } - - public static MapBinder> ohaiAutomaticAttributeBinder(Binder binder) { - MapBinder> mapbinder = MapBinder.newMapBinder(binder, new TypeLiteral() { - }, new TypeLiteral>() { - }, Automatic.class); - return mapbinder; - } - - /** - * - * @return NoSuchElementException if no element in the runList is a role. - */ - public static String findRoleInRunList(List runList) { - final Pattern pattern = Pattern.compile("^role\\[(.*)\\]$"); - String roleToParse = Iterables.find(runList, new Predicate() { - - @Override - public boolean apply(String input) { - return pattern.matcher(input).matches(); - } - - }); - Matcher matcher = pattern.matcher(roleToParse); - matcher.find(); - return matcher.group(1); - } -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/chef/util/RunListBuilder.java b/chef/core/src/main/java/org/jclouds/chef/util/RunListBuilder.java deleted file mode 100644 index 96f1910119..0000000000 --- a/chef/core/src/main/java/org/jclouds/chef/util/RunListBuilder.java +++ /dev/null @@ -1,88 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.util; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.collect.Iterables.addAll; -import static com.google.common.collect.Lists.newArrayList; -import static com.google.common.collect.Lists.transform; - -import java.util.Arrays; -import java.util.List; - -import com.google.common.base.Function; -import com.google.common.collect.ImmutableList; - -/** - * builds a run list in the correct syntax for chef. - * - * @author Adrian Cole - */ -public class RunListBuilder { - private List list = newArrayList(); - - /** - * Add the following recipe to the run list - */ - public RunListBuilder addRecipe(String recipe) { - return addRecipes(checkNotNull(recipe, "recipe")); - } - - /** - * Add the following recipes to the run list - */ - public RunListBuilder addRecipes(String... recipes) { - addAll(list, transform(Arrays.asList(checkNotNull(recipes, "recipes")), new Function() { - - @Override - public String apply(String from) { - return "recipe[" + from + "]"; - } - - })); - return this; - } - - /** - * Add the following role to the run list - */ - public RunListBuilder addRole(String role) { - return addRoles(checkNotNull(role, "role")); - } - - /** - * Add the following roles to the run list - */ - public RunListBuilder addRoles(String... roles) { - addAll(list, transform(Arrays.asList(checkNotNull(roles, "roles")), new Function() { - - @Override - public String apply(String from) { - return "role[" + from + "]"; - } - - })); - return this; - } - - public List build() { - return ImmutableList.copyOf(list); - } -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/ohai/Automatic.java b/chef/core/src/main/java/org/jclouds/ohai/Automatic.java deleted file mode 100644 index 6984f367c7..0000000000 --- a/chef/core/src/main/java/org/jclouds/ohai/Automatic.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.ohai; - -import static java.lang.annotation.ElementType.METHOD; -import static java.lang.annotation.ElementType.PARAMETER; -import static java.lang.annotation.ElementType.TYPE; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import javax.inject.Qualifier; - -/** - * - * @author Adrian Cole - */ -@Retention(RUNTIME) -@Target( { TYPE, METHOD, PARAMETER }) -@Qualifier -public @interface Automatic { -} diff --git a/chef/core/src/main/java/org/jclouds/ohai/AutomaticSupplier.java b/chef/core/src/main/java/org/jclouds/ohai/AutomaticSupplier.java deleted file mode 100644 index 6c20cda31c..0000000000 --- a/chef/core/src/main/java/org/jclouds/ohai/AutomaticSupplier.java +++ /dev/null @@ -1,56 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.ohai; - -import static com.google.common.base.Preconditions.checkNotNull; - -import java.util.Map; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import org.jclouds.domain.JsonBall; -import org.jclouds.ohai.functions.NestSlashKeys; - -import com.google.common.base.Supplier; -import com.google.common.collect.Multimap; - -/** - * - * @author Adrian Cole - * - */ -@Singleton -public class AutomaticSupplier implements Supplier> { - private final Multimap> autoAttrs; - private final NestSlashKeys nester; - - @Inject - AutomaticSupplier(@Automatic Multimap> autoAttrs, NestSlashKeys nester) { - this.autoAttrs = checkNotNull(autoAttrs, "autoAttrs"); - this.nester = checkNotNull(nester, "nester"); - } - - @Override - public Map get() { - return nester.apply(autoAttrs); - } - -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/ohai/OhaiContextBuilder.java b/chef/core/src/main/java/org/jclouds/ohai/OhaiContextBuilder.java deleted file mode 100644 index 147a21dc2a..0000000000 --- a/chef/core/src/main/java/org/jclouds/ohai/OhaiContextBuilder.java +++ /dev/null @@ -1,61 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.ohai; - -import java.util.Properties; - -import javax.inject.Inject; - -import org.jclouds.ohai.config.ConfiguresOhai; -import org.jclouds.ohai.config.JMXOhaiModule; -import org.jclouds.rest.RestContext; -import org.jclouds.rest.RestContextBuilder; - -import com.google.common.base.Predicate; -import com.google.common.collect.Iterables; -import com.google.inject.Module; - -/** - * - * @see RestContext - */ -public class OhaiContextBuilder extends RestContextBuilder { - - @Inject - public OhaiContextBuilder(Class syncClientClass, Class asyncClientClass, Properties properties) { - super(syncClientClass, asyncClientClass, properties); - } - - protected void addOhaiModuleIfNotPresent() { - if (!Iterables.any(modules, new Predicate() { - public boolean apply(Module input) { - return input.getClass().isAnnotationPresent(ConfiguresOhai.class); - } - - })) { - addOhaiModule(); - } - } - - protected void addOhaiModule() { - modules.add(new JMXOhaiModule()); - } - -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/ohai/config/ConfiguresOhai.java b/chef/core/src/main/java/org/jclouds/ohai/config/ConfiguresOhai.java deleted file mode 100644 index bf105cacca..0000000000 --- a/chef/core/src/main/java/org/jclouds/ohai/config/ConfiguresOhai.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.ohai.config; - -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.TYPE; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -/** - * - * @author Adrian Cole - */ -@Retention(RUNTIME) -@Target(TYPE) -public @interface ConfiguresOhai { -} diff --git a/chef/core/src/main/java/org/jclouds/ohai/config/JMXOhaiModule.java b/chef/core/src/main/java/org/jclouds/ohai/config/JMXOhaiModule.java deleted file mode 100644 index 5ca0e9b909..0000000000 --- a/chef/core/src/main/java/org/jclouds/ohai/config/JMXOhaiModule.java +++ /dev/null @@ -1,53 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.ohai.config; - -import java.lang.management.ManagementFactory; -import java.lang.management.RuntimeMXBean; - -import javax.inject.Singleton; - -import org.jclouds.domain.JsonBall; -import org.jclouds.ohai.config.multibindings.MapBinder; -import org.jclouds.ohai.suppliers.UptimeSecondsSupplier; - -import com.google.common.base.Supplier; -import com.google.inject.Provides; - -/** - * Wires the components needed to parse ohai data from a JVM - * - * @author Adrian Cole - */ -@ConfiguresOhai -public class JMXOhaiModule extends OhaiModule { - - @Provides - @Singleton - protected RuntimeMXBean provideRuntimeMXBean() { - return ManagementFactory.getRuntimeMXBean(); - } - - public MapBinder> bindOhai() { - MapBinder> mapBinder = super.bindOhai(); - mapBinder.addBinding("uptime_seconds").to(UptimeSecondsSupplier.class); - return mapBinder; - } -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/ohai/config/OhaiModule.java b/chef/core/src/main/java/org/jclouds/ohai/config/OhaiModule.java deleted file mode 100644 index ec3b3f3893..0000000000 --- a/chef/core/src/main/java/org/jclouds/ohai/config/OhaiModule.java +++ /dev/null @@ -1,188 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.ohai.config; - -import static org.jclouds.chef.util.ChefUtils.ohaiAutomaticAttributeBinder; -import static org.jclouds.chef.util.ChefUtils.toOhaiTime; - -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Provider; -import javax.inject.Singleton; - -import org.jclouds.domain.JsonBall; -import org.jclouds.json.Json; -import org.jclouds.ohai.Automatic; -import org.jclouds.ohai.AutomaticSupplier; -import org.jclouds.ohai.config.multibindings.MapBinder; -import org.jclouds.ohai.functions.ByteArrayToMacAddress; -import org.jclouds.ohai.functions.MapSetToMultimap; - -import com.google.common.base.Function; -import com.google.common.base.Supplier; -import com.google.common.collect.Multimap; -import com.google.inject.AbstractModule; -import com.google.inject.Provides; -import com.google.inject.TypeLiteral; - -/** - * Wires the components needed to parse ohai data - * - * @author Adrian Cole - */ -@ConfiguresOhai -public class OhaiModule extends AbstractModule { - - @Override - protected void configure() { - bind(new TypeLiteral>() { - }).to(new TypeLiteral() { - }); - bindOhai(); - } - - @Provides - @Automatic - protected Supplier> provideAutomatic(AutomaticSupplier in) { - return in; - } - - @Provides - @Automatic - Multimap> provideAutomatic(MapSetToMultimap> converter, - @Automatic Map>> input) { - return converter.apply(input); - - } - - @Named("systemProperties") - @Provides - protected Properties systemProperties() { - return System.getProperties(); - } - - public MapBinder> bindOhai() { - MapBinder> mapbinder = ohaiAutomaticAttributeBinder(binder()).permitDuplicates(); - mapbinder.addBinding("ohai_time").to(OhaiTimeProvider.class); - mapbinder.addBinding("jvm/system").to(SystemPropertiesProvider.class); - mapbinder.addBinding("platform").to(PlatformProvider.class); - mapbinder.addBinding("platform_version").to(PlatformVersionProvider.class); - mapbinder.addBinding("current_user").to(CurrentUserProvider.class); - return mapbinder; - } - - @Singleton - public static class OhaiTimeProvider implements Supplier { - private final Provider timeProvider; - - @Inject - OhaiTimeProvider(Provider timeProvider) { - this.timeProvider = timeProvider; - } - - @Override - public JsonBall get() { - return toOhaiTime(timeProvider.get()); - } - - } - - @Provides - protected Long millis() { - return System.currentTimeMillis(); - } - - @Singleton - public static class SystemPropertiesProvider implements Supplier { - - private final Json json; - private final Properties systemProperties; - - @Inject - SystemPropertiesProvider(Json json, @Named("systemProperties") Properties systemProperties) { - this.json = json; - this.systemProperties = systemProperties; - } - - @Override - public JsonBall get() { - return new JsonBall(json.toJson(systemProperties)); - } - - } - - @Singleton - public static class PlatformProvider extends SystemPropertyProvider { - - @Inject - PlatformProvider(@Named("systemProperties") Properties systemProperties) { - super("os.name", systemProperties); - } - - @Override - public JsonBall get() { - JsonBall returnValue = super.get(); - return returnValue != null ? new JsonBall(returnValue.toString().replaceAll("[ -]", "").toLowerCase()) : null; - } - - } - - @Singleton - public static class PlatformVersionProvider extends SystemPropertyProvider { - - @Inject - PlatformVersionProvider(@Named("systemProperties") Properties systemProperties) { - super("os.version", systemProperties); - } - - } - - @Singleton - public static class CurrentUserProvider extends SystemPropertyProvider { - - @Inject - CurrentUserProvider(@Named("systemProperties") Properties systemProperties) { - super("user.name", systemProperties); - } - - } - - public static class SystemPropertyProvider implements Supplier { - private final Properties systemProperties; - private final String property; - - @Inject - SystemPropertyProvider(String property, @Named("systemProperties") Properties systemProperties) { - this.property = property; - this.systemProperties = systemProperties; - } - - @Override - public JsonBall get() { - return systemProperties.containsKey(property) ? new JsonBall(systemProperties.getProperty(property)) : null; - } - - } - -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/ohai/config/multibindings/Element.java b/chef/core/src/main/java/org/jclouds/ohai/config/multibindings/Element.java deleted file mode 100644 index 86d2078353..0000000000 --- a/chef/core/src/main/java/org/jclouds/ohai/config/multibindings/Element.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.ohai.config.multibindings; - -import com.google.inject.BindingAnnotation; - -import java.lang.annotation.Retention; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -/** - * An internal binding annotation applied to each element in a multibinding. - * All elements are assigned a globally-unique id to allow different modules - * to contribute multibindings independently. - * - * @author jessewilson@google.com (Jesse Wilson) - */ -@Retention(RUNTIME) @BindingAnnotation -@interface Element { - String setName(); - int uniqueId(); -} diff --git a/chef/core/src/main/java/org/jclouds/ohai/config/multibindings/MapBinder.java b/chef/core/src/main/java/org/jclouds/ohai/config/multibindings/MapBinder.java deleted file mode 100644 index b5118ca067..0000000000 --- a/chef/core/src/main/java/org/jclouds/ohai/config/multibindings/MapBinder.java +++ /dev/null @@ -1,537 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.ohai.config.multibindings; - -import static com.google.inject.util.Types.newParameterizedTypeWithOwner; -import static org.jclouds.ohai.config.multibindings.Multibinder.checkConfiguration; -import static org.jclouds.ohai.config.multibindings.Multibinder.checkNotNull; -import static org.jclouds.ohai.config.multibindings.Multibinder.setOf; - -import java.lang.annotation.Annotation; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Set; -import java.util.Map.Entry; - -import org.jclouds.ohai.config.multibindings.Multibinder.RealMultibinder; - -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; -import com.google.inject.Binder; -import com.google.inject.Inject; -import com.google.inject.Injector; -import com.google.inject.Key; -import com.google.inject.Module; -import com.google.inject.Provider; -import com.google.inject.TypeLiteral; -import com.google.inject.binder.LinkedBindingBuilder; -import com.google.inject.spi.Dependency; -import com.google.inject.spi.ProviderWithDependencies; -import com.google.inject.util.Types; - -/** - * An API to bind multiple map entries separately, only to later inject them as - * a complete map. MapBinder is intended for use in your application's module: - * - *

- * 
- * public class SnacksModule extends AbstractModule {
- *   protected void configure() {
- *     MapBinder<String, Snack> mapbinder
- *         = MapBinder.newMapBinder(binder(), String.class, Snack.class);
- *     mapbinder.addBinding("twix").toInstance(new Twix());
- *     mapbinder.addBinding("snickers").toProvider(SnickersProvider.class);
- *     mapbinder.addBinding("skittles").to(Skittles.class);
- *   }
- * }
- * 
- * - *

- * With this binding, a {@link Map}{@code } can now be injected: - * - *

- * 
- * class SnackMachine {
- *   {@literal @}Inject
- *   public SnackMachine(Map<String, Snack> snacks) { ... }
- * }
- * 
- * - *

- * In addition to binding {@code Map}, a mapbinder will also bind {@code - * Map>} for lazy value provision: - * - *

- * 
- * class SnackMachine {
- *   {@literal @}Inject
- *   public SnackMachine(Map<String, Provider<Snack>> snackSuppliers) { ... }
- * }
- * 
- * - *

- * Contributing mapbindings from different modules is supported. For example, it - * is okay to have both {@code CandyModule} and {@code ChipsModule} both create - * their own {@code MapBinder}, and to each contribute bindings - * to the snacks map. When that map is injected, it will contain entries from - * both modules. - * - *

- * The map's iteration order is consistent with the binding order. This is - * convenient when multiple elements are contributed by the same module because - * that module can order its bindings appropriately. Avoid relying on the - * iteration order of elements contributed by different modules, since there is - * no equivalent mechanism to order modules. - * - *

- * Values are resolved at map injection time. If a value is bound to a provider, - * that provider's get method will be called each time the map is injected - * (unless the binding is also scoped, or a map of providers is injected). - * - *

- * Annotations are used to create different maps of the same key/value type. - * Each distinct annotation gets its own independent map. - * - *

- * Keys must be distinct. If the same key is bound more than - * once, map injection will fail. However, use {@link #permitDuplicates()} in - * order to allow duplicate keys; extra bindings to {@code Map>} and - * {@code Map>} will be added. - * - *

- * Keys must be non-null. {@code addBinding(null)} will throw - * an unchecked exception. - * - *

- * Values must be non-null to use map injection. If any value - * is null, map injection will fail (although injecting a map of providers will - * not). - * - * @author dpb@google.com (David P. Baker) - */ -public abstract class MapBinder { - private MapBinder() { - } - - /** - * Returns a new mapbinder that collects entries of {@code keyType}/{@code - * valueType} in a {@link Map} that is itself bound with no binding - * annotation. - */ - public static MapBinder newMapBinder(Binder binder, TypeLiteral keyType, TypeLiteral valueType) { - binder = binder.skipSources(MapBinder.class, RealMapBinder.class); - return newMapBinder(binder, valueType, Key.get(mapOf(keyType, valueType)), Key.get(mapOfProviderOf(keyType, - valueType)), Key.get(mapOf(keyType, setOf(valueType))), Key.get(mapOfSetOfProviderOf(keyType, valueType)), - Multibinder.newSetBinder(binder, entryOfProviderOf(keyType, valueType))); - } - - /** - * Returns a new mapbinder that collects entries of {@code keyType}/{@code - * valueType} in a {@link Map} that is itself bound with no binding - * annotation. - */ - public static MapBinder newMapBinder(Binder binder, Class keyType, Class valueType) { - return newMapBinder(binder, TypeLiteral.get(keyType), TypeLiteral.get(valueType)); - } - - /** - * Returns a new mapbinder that collects entries of {@code keyType}/{@code - * valueType} in a {@link Map} that is itself bound with {@code annotation}. - */ - public static MapBinder newMapBinder(Binder binder, TypeLiteral keyType, TypeLiteral valueType, - Annotation annotation) { - binder = binder.skipSources(MapBinder.class, RealMapBinder.class); - return newMapBinder(binder, valueType, Key.get(mapOf(keyType, valueType), annotation), Key.get(mapOfProviderOf( - keyType, valueType), annotation), Key.get(mapOf(keyType, setOf(valueType)), annotation), Key.get( - mapOfSetOfProviderOf(keyType, valueType), annotation), Multibinder.newSetBinder(binder, entryOfProviderOf( - keyType, valueType), annotation)); - } - - /** - * Returns a new mapbinder that collects entries of {@code keyType}/{@code - * valueType} in a {@link Map} that is itself bound with {@code annotation}. - */ - public static MapBinder newMapBinder(Binder binder, Class keyType, Class valueType, - Annotation annotation) { - return newMapBinder(binder, TypeLiteral.get(keyType), TypeLiteral.get(valueType), annotation); - } - - /** - * Returns a new mapbinder that collects entries of {@code keyType}/{@code - * valueType} in a {@link Map} that is itself bound with {@code - * annotationType}. - */ - public static MapBinder newMapBinder(Binder binder, TypeLiteral keyType, TypeLiteral valueType, - Class annotationType) { - binder = binder.skipSources(MapBinder.class, RealMapBinder.class); - return newMapBinder(binder, valueType, Key.get(mapOf(keyType, valueType), annotationType), Key.get( - mapOfProviderOf(keyType, valueType), annotationType), Key.get(mapOf(keyType, setOf(valueType)), - annotationType), Key.get(mapOfSetOfProviderOf(keyType, valueType), annotationType), Multibinder - .newSetBinder(binder, entryOfProviderOf(keyType, valueType), annotationType)); - } - - /** - * Returns a new mapbinder that collects entries of {@code keyType}/{@code - * valueType} in a {@link Map} that is itself bound with {@code - * annotationType}. - */ - public static MapBinder newMapBinder(Binder binder, Class keyType, Class valueType, - Class annotationType) { - return newMapBinder(binder, TypeLiteral.get(keyType), TypeLiteral.get(valueType), annotationType); - } - - @SuppressWarnings("unchecked") - // a map of is safely a Map - private static TypeLiteral> mapOf(TypeLiteral keyType, TypeLiteral valueType) { - return (TypeLiteral>) TypeLiteral.get(Types.mapOf(keyType.getType(), valueType.getType())); - } - - @SuppressWarnings("unchecked") - // a provider map is safely a Map> - private static TypeLiteral>> mapOfProviderOf(TypeLiteral keyType, - TypeLiteral valueType) { - return (TypeLiteral>>) TypeLiteral.get(Types.mapOf(keyType.getType(), Types - .providerOf(valueType.getType()))); - } - - @SuppressWarnings("unchecked") - // a provider map > is safely a Map>> - private static TypeLiteral>>> mapOfSetOfProviderOf(TypeLiteral keyType, - TypeLiteral valueType) { - return (TypeLiteral>>>) TypeLiteral.get(Types.mapOf(keyType.getType(), Types.setOf(Types - .providerOf(valueType.getType())))); - } - - @SuppressWarnings("unchecked") - // a provider entry is safely a Map.Entry> - private static TypeLiteral>> entryOfProviderOf(TypeLiteral keyType, - TypeLiteral valueType) { - return (TypeLiteral>>) TypeLiteral.get(newParameterizedTypeWithOwner(Map.class, Entry.class, - keyType.getType(), Types.providerOf(valueType.getType()))); - } - - private static MapBinder newMapBinder(Binder binder, TypeLiteral valueType, Key> mapKey, - Key>> providerMapKey, Key>> multimapKey, - Key>>> providerMultimapKey, Multibinder>> entrySetBinder) { - RealMapBinder mapBinder = new RealMapBinder(binder, valueType, mapKey, providerMapKey, multimapKey, - providerMultimapKey, entrySetBinder); - binder.install(mapBinder); - return mapBinder; - } - - /** - * Configures the {@code MapBinder} to handle duplicate entries. - *

- * When multiple equal keys are bound, the value that gets included in the - * map is arbitrary. - *

- * In addition to the {@code Map} and {@code Map>} maps - * that are normally bound, a {@code Map>} and {@code Map>>} are also bound, which contain all values bound - * to each key. - *

- * When multiple modules contribute elements to the map, this configuration - * option impacts all of them. - * - * @return this map binder - */ - public abstract MapBinder permitDuplicates(); - - /** - * Returns a binding builder used to add a new entry in the map. Each key - * must be distinct (and non-null). Bound providers will be evaluated each - * time the map is injected. - * - *

- * It is an error to call this method without also calling one of the {@code - * to} methods on the returned binding builder. - * - *

- * Scoping elements independently is supported. Use the {@code in} method to - * specify a binding scope. - */ - public abstract LinkedBindingBuilder addBinding(K key); - - /** - * The actual mapbinder plays several roles: - * - *

- * As a MapBinder, it acts as a factory for LinkedBindingBuilders for each of - * the map's values. It delegates to a {@link Multibinder} of entries (keys - * to value providers). - * - *

- * As a Module, it installs the binding to the map itself, as well as to a - * corresponding map whose values are providers. It uses the entry set - * multibinder to construct the map and the provider map. - * - *

- * As a module, this implements equals() and hashcode() in order to trick - * Guice into executing its configure() method only once. That makes it so - * that multiple mapbinders can be created for the same target map, but only - * one is bound. Since the list of bindings is retrieved from the injector - * itself (and not the mapbinder), each mapbinder has access to all - * contributions from all equivalent mapbinders. - * - *

- * Rather than binding a single Map.Entry<K, V>, the map binder binds - * keys and values independently. This allows the values to be properly - * scoped. - * - *

- * We use a subclass to hide 'implements Module' from the public API. - */ - private static final class RealMapBinder extends MapBinder implements Module { - private final TypeLiteral valueType; - private final Key> mapKey; - private final Key>> providerMapKey; - private final Key>> multimapKey; - private final Key>>> providerMultimapKey; - private final RealMultibinder>> entrySetBinder; - - /* - * the target injector's binder. non-null until initialization, null - * afterwards - */ - private Binder binder; - - private RealMapBinder(Binder binder, TypeLiteral valueType, Key> mapKey, - Key>> providerMapKey, Key>> multimapKey, - Key>>> providerMultimapKey, Multibinder>> entrySetBinder) { - this.valueType = valueType; - this.mapKey = mapKey; - this.providerMapKey = providerMapKey; - this.multimapKey = multimapKey; - this.providerMultimapKey = providerMultimapKey; - this.entrySetBinder = (RealMultibinder>>) entrySetBinder; - this.binder = binder; - } - - @Override - public MapBinder permitDuplicates() { - entrySetBinder.permitDuplicates(); - binder.install(new MultimapBinder(multimapKey, providerMultimapKey, entrySetBinder.getSetKey())); - return this; - } - - /** - * This creates two bindings. One for the {@code Map.Entry>} and another for {@code V}. - */ - @Override - public LinkedBindingBuilder addBinding(K key) { - checkNotNull(key, "key"); - checkConfiguration(!isInitialized(), "MapBinder was already initialized"); - - Key valueKey = Key.get(valueType, new RealElement(entrySetBinder.getSetName())); - entrySetBinder.addBinding().toInstance(new MapEntry>(key, binder.getProvider(valueKey))); - return binder.bind(valueKey); - } - - public void configure(Binder binder) { - checkConfiguration(!isInitialized(), "MapBinder was already initialized"); - - final ImmutableSet> dependencies = ImmutableSet.> of(Dependency.get(entrySetBinder - .getSetKey())); - - // Binds a Map> from a collection of Map>. - final Provider>>> entrySetProvider = binder.getProvider(entrySetBinder.getSetKey()); - binder.bind(providerMapKey).toProvider(new ProviderWithDependencies>>() { - private Map> providerMap; - - @SuppressWarnings("unused") - @Inject - void initialize(Injector injector) { - RealMapBinder.this.binder = null; - boolean permitDuplicates = entrySetBinder.permitsDuplicates(injector); - - Map> providerMapMutable = new LinkedHashMap>(); - for (Entry> entry : entrySetProvider.get()) { - Provider previous = providerMapMutable.put(entry.getKey(), entry.getValue()); - checkConfiguration(previous == null || permitDuplicates, - "Map injection failed due to duplicated key \"%s\"", entry.getKey()); - } - - providerMap = ImmutableMap.copyOf(providerMapMutable); - } - - public Map> get() { - return providerMap; - } - - public Set> getDependencies() { - return dependencies; - } - }); - - final Provider>> mapProvider = binder.getProvider(providerMapKey); - binder.bind(mapKey).toProvider(new ProviderWithDependencies>() { - public Map get() { - Map map = new LinkedHashMap(); - for (Entry> entry : mapProvider.get().entrySet()) { - V value = entry.getValue().get(); - K key = entry.getKey(); - checkConfiguration(value != null, "Map injection failed due to null value for key \"%s\"", key); - map.put(key, value); - } - return Collections.unmodifiableMap(map); - } - - public Set> getDependencies() { - return dependencies; - } - }); - } - - private boolean isInitialized() { - return binder == null; - } - - @Override - public boolean equals(Object o) { - return o instanceof RealMapBinder && ((RealMapBinder) o).mapKey.equals(mapKey); - } - - @Override - public int hashCode() { - return mapKey.hashCode(); - } - - /** - * Binds {@code Map>} and {{@code Map>>}. - */ - private static final class MultimapBinder implements Module { - - private final Key>> multimapKey; - private final Key>>> providerMultimapKey; - private final Key>>> entrySetKey; - - public MultimapBinder(Key>> multimapKey, Key>>> providerMultimapKey, - Key>>> entrySetKey) { - this.multimapKey = multimapKey; - this.providerMultimapKey = providerMultimapKey; - this.entrySetKey = entrySetKey; - } - - public void configure(Binder binder) { - final ImmutableSet> dependencies = ImmutableSet.> of(Dependency - .get(entrySetKey)); - - final Provider>>> entrySetProvider = binder.getProvider(entrySetKey); - // Binds a Map>> from a collection of - // Map> if - // permitDuplicates was called. - binder.bind(providerMultimapKey).toProvider(new ProviderWithDependencies>>>() { - private Map>> providerMultimap; - - @SuppressWarnings("unused") - @Inject - void initialize(Injector injector) { - Map>> providerMultimapMutable = new LinkedHashMap>>(); - for (Entry> entry : entrySetProvider.get()) { - if (!providerMultimapMutable.containsKey(entry.getKey())) { - providerMultimapMutable.put(entry.getKey(), ImmutableSet.> builder()); - } - providerMultimapMutable.get(entry.getKey()).add(entry.getValue()); - } - - ImmutableMap.Builder>> providerMultimapBuilder = ImmutableMap.builder(); - for (Entry>> entry : providerMultimapMutable.entrySet()) { - providerMultimapBuilder.put(entry.getKey(), entry.getValue().build()); - } - providerMultimap = providerMultimapBuilder.build(); - } - - public Map>> get() { - return providerMultimap; - } - - public Set> getDependencies() { - return dependencies; - } - }); - - final Provider>>> multimapProvider = binder.getProvider(providerMultimapKey); - binder.bind(multimapKey).toProvider(new ProviderWithDependencies>>() { - - public Map> get() { - ImmutableMap.Builder> multimapBuilder = ImmutableMap.builder(); - for (Entry>> entry : multimapProvider.get().entrySet()) { - K key = entry.getKey(); - ImmutableSet.Builder valuesBuilder = ImmutableSet.builder(); - for (Provider valueProvider : entry.getValue()) { - V value = valueProvider.get(); - checkConfiguration(value != null, "Multimap injection failed due to null value for key \"%s\"", - key); - valuesBuilder.add(value); - } - multimapBuilder.put(key, valuesBuilder.build()); - } - return multimapBuilder.build(); - } - - public Set> getDependencies() { - return dependencies; - } - }); - } - } - - private static final class MapEntry implements Map.Entry { - private final K key; - private final V value; - - private MapEntry(K key, V value) { - this.key = key; - this.value = value; - } - - public K getKey() { - return key; - } - - public V getValue() { - return value; - } - - public V setValue(V value) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean equals(Object obj) { - return obj instanceof Map.Entry && key.equals(((Map.Entry) obj).getKey()) - && value.equals(((Map.Entry) obj).getValue()); - } - - @Override - public int hashCode() { - return 127 * ("key".hashCode() ^ key.hashCode()) + 127 * ("value".hashCode() ^ value.hashCode()); - } - - @Override - public String toString() { - return "MapEntry(" + key + ", " + value + ")"; - } - } - } -} diff --git a/chef/core/src/main/java/org/jclouds/ohai/config/multibindings/Multibinder.java b/chef/core/src/main/java/org/jclouds/ohai/config/multibindings/Multibinder.java deleted file mode 100644 index b8bc241e03..0000000000 --- a/chef/core/src/main/java/org/jclouds/ohai/config/multibindings/Multibinder.java +++ /dev/null @@ -1,413 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.ohai.config.multibindings; - -import static com.google.inject.name.Names.named; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Type; -import java.util.Collections; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Set; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Lists; -import com.google.inject.AbstractModule; -import com.google.inject.Binder; -import com.google.inject.Binding; -import com.google.inject.ConfigurationException; -import com.google.inject.Inject; -import com.google.inject.Injector; -import com.google.inject.Key; -import com.google.inject.Module; -import com.google.inject.Provider; -import com.google.inject.TypeLiteral; -import com.google.inject.binder.LinkedBindingBuilder; -import com.google.inject.internal.Errors; -import com.google.inject.spi.Dependency; -import com.google.inject.spi.HasDependencies; -import com.google.inject.spi.Message; -import com.google.inject.spi.Toolable; -import com.google.inject.util.Types; - -/** - * - * An API to bind multiple values separately, only to later inject them as a - * complete collection. Multibinder is intended for use in your application's - * module: - * - *

- * 
- * public class SnacksModule extends AbstractModule {
- *   protected void configure() {
- *     Multibinder<Snack> multibinder
- *         = Multibinder.newSetBinder(binder(), Snack.class);
- *     multibinder.addBinding().toInstance(new Twix());
- *     multibinder.addBinding().toProvider(SnickersProvider.class);
- *     multibinder.addBinding().to(Skittles.class);
- *   }
- * }
- * 
- * - *

- * With this binding, a {@link Set}{@code } can now be injected: - * - *

- * 
- * class SnackMachine {
- *   {@literal @}Inject
- *   public SnackMachine(Set<Snack> snacks) { ... }
- * }
- * 
- * - *

- * Contributing multibindings from different modules is supported. For example, - * it is okay to have both {@code CandyModule} and {@code ChipsModule} to both - * create their own {@code Multibinder}, and to each contribute bindings - * to the set of snacks. When that set is injected, it will contain elements - * from both modules. - * - *

- * The set's iteration order is consistent with the binding order. This is - * convenient when multiple elements are contributed by the same module because - * that module can order its bindings appropriately. Avoid relying on the - * iteration order of elements contributed by different modules, since there is - * no equivalent mechanism to order modules. - * - *

- * Elements are resolved at set injection time. If an element is bound to a - * provider, that provider's get method will be called each time the set is - * injected (unless the binding is also scoped). - * - *

- * Annotations are be used to create different sets of the same element type. - * Each distinct annotation gets its own independent collection of elements. - * - *

- * Elements must be distinct. If multiple bound elements have - * the same value, set injection will fail. - * - *

- * Elements must be non-null. If any set element is null, set - * injection will fail. - * - * @author jessewilson@google.com (Jesse Wilson) - */ -public abstract class Multibinder { - private Multibinder() { - } - - /** - * Returns a new multibinder that collects instances of {@code type} in a - * {@link Set} that is itself bound with no binding annotation. - */ - public static Multibinder newSetBinder(Binder binder, TypeLiteral type) { - binder = binder.skipSources(RealMultibinder.class, Multibinder.class); - RealMultibinder result = new RealMultibinder(binder, type, "", Key.get(Multibinder. setOf(type))); - binder.install(result); - return result; - } - - /** - * Returns a new multibinder that collects instances of {@code type} in a - * {@link Set} that is itself bound with no binding annotation. - */ - public static Multibinder newSetBinder(Binder binder, Class type) { - return newSetBinder(binder, TypeLiteral.get(type)); - } - - /** - * Returns a new multibinder that collects instances of {@code type} in a - * {@link Set} that is itself bound with {@code annotation}. - */ - public static Multibinder newSetBinder(Binder binder, TypeLiteral type, Annotation annotation) { - binder = binder.skipSources(RealMultibinder.class, Multibinder.class); - RealMultibinder result = new RealMultibinder(binder, type, annotation.toString(), Key.get(Multibinder - . setOf(type), annotation)); - binder.install(result); - return result; - } - - /** - * Returns a new multibinder that collects instances of {@code type} in a - * {@link Set} that is itself bound with {@code annotation}. - */ - public static Multibinder newSetBinder(Binder binder, Class type, Annotation annotation) { - return newSetBinder(binder, TypeLiteral.get(type), annotation); - } - - /** - * Returns a new multibinder that collects instances of {@code type} in a - * {@link Set} that is itself bound with {@code annotationType}. - */ - public static Multibinder newSetBinder(Binder binder, TypeLiteral type, - Class annotationType) { - binder = binder.skipSources(RealMultibinder.class, Multibinder.class); - RealMultibinder result = new RealMultibinder(binder, type, "@" + annotationType.getName(), Key.get( - Multibinder. setOf(type), annotationType)); - binder.install(result); - return result; - } - - /** - * Returns a new multibinder that collects instances of {@code type} in a - * {@link Set} that is itself bound with {@code annotationType}. - */ - public static Multibinder newSetBinder(Binder binder, Class type, - Class annotationType) { - return newSetBinder(binder, TypeLiteral.get(type), annotationType); - } - - @SuppressWarnings("unchecked") - // wrapping a T in a Set safely returns a Set - static TypeLiteral> setOf(TypeLiteral elementType) { - Type type = Types.setOf(elementType.getType()); - return (TypeLiteral>) TypeLiteral.get(type); - } - - /** - * Configures the bound set to silently discard duplicate elements. When - * multiple equal values are bound, the one that gets included is arbitrary. - * When multiple modules contribute elements to the set, this configuration - * option impacts all of them. - * - * @return this multibinder - */ - public abstract Multibinder permitDuplicates(); - - /** - * Returns a binding builder used to add a new element in the set. Each bound - * element must have a distinct value. Bound providers will be evaluated each - * time the set is injected. - * - *

- * It is an error to call this method without also calling one of the {@code - * to} methods on the returned binding builder. - * - *

- * Scoping elements independently is supported. Use the {@code in} method to - * specify a binding scope. - */ - public abstract LinkedBindingBuilder addBinding(); - - /** - * The actual multibinder plays several roles: - * - *

- * As a Multibinder, it acts as a factory for LinkedBindingBuilders for each - * of the set's elements. Each binding is given an annotation that identifies - * it as a part of this set. - * - *

- * As a Module, it installs the binding to the set itself. As a module, this - * implements equals() and hashcode() in order to trick Guice into executing - * its configure() method only once. That makes it so that multiple - * multibinders can be created for the same target collection, but only one - * is bound. Since the list of bindings is retrieved from the injector itself - * (and not the multibinder), each multibinder has access to all - * contributions from all multibinders. - * - *

- * As a Provider, this constructs the set instances. - * - *

- * We use a subclass to hide 'implements Module, Provider' from the public - * API. - */ - static final class RealMultibinder extends Multibinder implements Module, Provider>, HasDependencies { - - private final TypeLiteral elementType; - private final String setName; - private final Key> setKey; - private final Key permitDuplicatesKey; - - /* - * the target injector's binder. non-null until initialization, null - * afterwards - */ - private Binder binder; - - /* - * a provider for each element in the set. null until initialization, - * non-null afterwards - */ - private List> providers; - private Set> dependencies; - - /** - * whether duplicates are allowed. Possibly configured by a different - * instance - */ - private boolean permitDuplicates; - - private RealMultibinder(Binder binder, TypeLiteral elementType, String setName, Key> setKey) { - this.binder = checkNotNull(binder, "binder"); - this.elementType = checkNotNull(elementType, "elementType"); - this.setName = checkNotNull(setName, "setName"); - this.setKey = checkNotNull(setKey, "setKey"); - this.permitDuplicatesKey = Key.get(Boolean.class, named(toString() + " permits duplicates")); - } - - public void configure(Binder binder) { - checkConfiguration(!isInitialized(), "Multibinder was already initialized"); - binder.bind(setKey).toProvider(this); - } - - @Override - public Multibinder permitDuplicates() { - binder.install(new PermitDuplicatesModule(permitDuplicatesKey)); - return this; - } - - @Override - public LinkedBindingBuilder addBinding() { - checkConfiguration(!isInitialized(), "Multibinder was already initialized"); - - return binder.bind(Key.get(elementType, new RealElement(setName))); - } - - /** - * Invoked by Guice at Injector-creation time to prepare providers for - * each element in this set. At this time the set's size is known, but its - * contents are only evaluated when get() is invoked. - */ - @Toolable - @Inject - void initialize(Injector injector) { - providers = Lists.newArrayList(); - List> dependencies = Lists.newArrayList(); - for (Binding entry : injector.findBindingsByType(elementType)) { - - if (keyMatches(entry.getKey())) { - @SuppressWarnings("unchecked") - // protected by findBindingsByType() - Binding binding = (Binding) entry; - providers.add(binding.getProvider()); - dependencies.add(Dependency.get(binding.getKey())); - } - } - - this.dependencies = ImmutableSet.copyOf(dependencies); - this.permitDuplicates = permitsDuplicates(injector); - this.binder = null; - } - - boolean permitsDuplicates(Injector injector) { - return injector.getBindings().containsKey(permitDuplicatesKey); - } - - private boolean keyMatches(Key key) { - return key.getTypeLiteral().equals(elementType) && key.getAnnotation() instanceof Element - && ((Element) key.getAnnotation()).setName().equals(setName); - } - - private boolean isInitialized() { - return binder == null; - } - - public Set get() { - checkConfiguration(isInitialized(), "Multibinder is not initialized"); - - Set result = new LinkedHashSet(); - for (Provider provider : providers) { - final T newValue = provider.get(); - checkConfiguration(newValue != null, "Set injection failed due to null element"); - checkConfiguration(result.add(newValue) || permitDuplicates, - "Set injection failed due to duplicated element \"%s\"", newValue); - } - return Collections.unmodifiableSet(result); - } - - String getSetName() { - return setName; - } - - Key> getSetKey() { - return setKey; - } - - public Set> getDependencies() { - return dependencies; - } - - @Override - public boolean equals(Object o) { - return o instanceof RealMultibinder && ((RealMultibinder) o).setKey.equals(setKey); - } - - @Override - public int hashCode() { - return setKey.hashCode(); - } - - @Override - public String toString() { - return new StringBuilder().append(setName).append(setName.length() > 0 ? " " : "").append("Multibinder<") - .append(elementType).append(">").toString(); - } - } - - /** - * We install the permit duplicates configuration as its own binding, all by - * itself. This way, if only one of a multibinder's users remember to call - * permitDuplicates(), they're still permitted. - */ - private static class PermitDuplicatesModule extends AbstractModule { - private final Key key; - - PermitDuplicatesModule(Key key) { - this.key = key; - } - - @Override - protected void configure() { - bind(key).toInstance(true); - } - - @Override - public boolean equals(Object o) { - return o instanceof PermitDuplicatesModule && ((PermitDuplicatesModule) o).key.equals(key); - } - - @Override - public int hashCode() { - return getClass().hashCode() ^ key.hashCode(); - } - } - - static void checkConfiguration(boolean condition, String format, Object... args) { - if (condition) { - return; - } - - throw new ConfigurationException(ImmutableSet.of(new Message(Errors.format(format, args)))); - } - - static T checkNotNull(T reference, String name) { - if (reference != null) { - return reference; - } - - NullPointerException npe = new NullPointerException(name); - throw new ConfigurationException(ImmutableSet.of(new Message(ImmutableList.of(), npe.toString(), npe))); - } -} diff --git a/chef/core/src/main/java/org/jclouds/ohai/config/multibindings/RealElement.java b/chef/core/src/main/java/org/jclouds/ohai/config/multibindings/RealElement.java deleted file mode 100644 index 4cf22ac80c..0000000000 --- a/chef/core/src/main/java/org/jclouds/ohai/config/multibindings/RealElement.java +++ /dev/null @@ -1,69 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - - - -package org.jclouds.ohai.config.multibindings; - -import java.lang.annotation.Annotation; -import java.util.concurrent.atomic.AtomicInteger; - - -/** - * @author jessewilson@google.com (Jesse Wilson) - */ -class RealElement implements Element { - private static final AtomicInteger nextUniqueId = new AtomicInteger(1); - - private final int uniqueId; - private final String setName; - - RealElement(String setName) { - uniqueId = nextUniqueId.getAndIncrement(); - this.setName = setName; - } - - public String setName() { - return setName; - } - - public int uniqueId() { - return uniqueId; - } - - public Class annotationType() { - return Element.class; - } - - @Override public String toString() { - return "@" + Element.class.getName() + "(setName=" + setName - + ",uniqueId=" + uniqueId + ")"; - } - - @Override public boolean equals(Object o) { - return o instanceof Element - && ((Element) o).setName().equals(setName()) - && ((Element) o).uniqueId() == uniqueId(); - } - - @Override public int hashCode() { - return 127 * ("setName".hashCode() ^ setName.hashCode()) - + 127 * ("uniqueId".hashCode() ^ uniqueId); - } -} diff --git a/chef/core/src/main/java/org/jclouds/ohai/config/multibindings/package-info.java b/chef/core/src/main/java/org/jclouds/ohai/config/multibindings/package-info.java deleted file mode 100644 index 9ae91d5485..0000000000 --- a/chef/core/src/main/java/org/jclouds/ohai/config/multibindings/package-info.java +++ /dev/null @@ -1,24 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -/** - * Taken from r1154 of Guice, as they decided to stop supporting multiple bindings and instead silently throw them away. - */ -package org.jclouds.ohai.config.multibindings; - diff --git a/chef/core/src/main/java/org/jclouds/ohai/functions/ByteArrayToMacAddress.java b/chef/core/src/main/java/org/jclouds/ohai/functions/ByteArrayToMacAddress.java deleted file mode 100644 index b0aac212d8..0000000000 --- a/chef/core/src/main/java/org/jclouds/ohai/functions/ByteArrayToMacAddress.java +++ /dev/null @@ -1,57 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.ohai.functions; - -import static com.google.common.collect.Iterables.transform; -import static com.google.common.collect.Lists.partition; -import static com.google.common.primitives.Bytes.asList; -import static com.google.common.primitives.Bytes.toArray; - -import java.util.List; - -import javax.inject.Singleton; - -import org.jclouds.crypto.CryptoStreams; - -import com.google.common.base.Function; -import com.google.common.base.Joiner; - -/** - * - * Creates a string in the form: {@code 00:26:bb:09:e6:c4 } - * - * @author Adrian Cole - */ -@Singleton -public class ByteArrayToMacAddress implements Function { - - @Override - public String apply(byte[] from) { - return Joiner.on(':').join(transform(partition(asList(from), 1), new Function, String>() { - - @Override - public String apply(List from) { - return CryptoStreams.hex(toArray(from)); - } - - })); - } - -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/ohai/functions/MapSetToMultimap.java b/chef/core/src/main/java/org/jclouds/ohai/functions/MapSetToMultimap.java deleted file mode 100644 index dbcebc0f54..0000000000 --- a/chef/core/src/main/java/org/jclouds/ohai/functions/MapSetToMultimap.java +++ /dev/null @@ -1,49 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.ohai.functions; - -import java.util.Map; -import java.util.Set; -import java.util.Map.Entry; - -import javax.inject.Singleton; - -import com.google.common.base.Function; -import com.google.common.collect.LinkedHashMultimap; -import com.google.common.collect.Multimap; - -/** - * - * @author Adrian Cole - */ -@Singleton -public class MapSetToMultimap implements Function>, Multimap> { - - @Override - public Multimap apply(Map> from) { - Multimap returnV = LinkedHashMultimap.create(); - for (Entry> entry : from.entrySet()) { - for (V value : entry.getValue()) - returnV.put(entry.getKey(), value); - } - return returnV; - } - -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/ohai/functions/NestSlashKeys.java b/chef/core/src/main/java/org/jclouds/ohai/functions/NestSlashKeys.java deleted file mode 100644 index fce2ae06f7..0000000000 --- a/chef/core/src/main/java/org/jclouds/ohai/functions/NestSlashKeys.java +++ /dev/null @@ -1,161 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.ohai.functions; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; - -import java.lang.reflect.Type; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Map.Entry; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import org.jclouds.domain.JsonBall; -import org.jclouds.json.Json; - -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Function; -import com.google.common.base.Predicate; -import com.google.common.base.Splitter; -import com.google.common.base.Supplier; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.google.common.collect.Multimap; -import com.google.common.collect.Sets; -import com.google.inject.TypeLiteral; - -/** - * - * - * @author Adrian Cole - */ -@Singleton -public class NestSlashKeys implements Function>, Map> { - - private final Json json; - - @Inject - NestSlashKeys(Json json) { - this.json = checkNotNull(json, "json"); - } - - @Override - public Map apply(Multimap> from) { - - Map autoAttrs = mergeSameKeys(from); - - Map modifiableFlatMap = Maps.newLinkedHashMap(Maps.filterKeys(autoAttrs, - new Predicate() { - - @Override - public boolean apply(String input) { - return input.indexOf('/') == -1; - } - - })); - Map withSlashesMap = Maps.difference(autoAttrs, modifiableFlatMap).entriesOnlyOnLeft(); - for (Entry entry : withSlashesMap.entrySet()) { - List keyParts = Lists.newArrayList(Splitter.on('/').split(entry.getKey())); - JsonBall toInsert = entry.getValue(); - try { - putUnderContext(keyParts, toInsert, modifiableFlatMap); - } catch (IllegalArgumentException e) { - throw new IllegalArgumentException("error inserting value in entry: " + entry.getKey(), e); - } - } - return modifiableFlatMap; - } - - private Map mergeSameKeys(Multimap> from) { - Map merged = Maps.newLinkedHashMap(); - for (Entry> entry : from.entries()) { - if (merged.containsKey(entry.getKey())) { - mergeAsPeer(entry.getKey(), entry.getValue().get(), merged); - } else { - merged.put(entry.getKey(), entry.getValue().get()); - } - } - return merged; - } - - @VisibleForTesting - void mergeAsPeer(String key, JsonBall value, Map insertionContext) { - Map valueContext = json.fromJson(insertionContext.get(key).toString(), mapLiteral); - Map toPut = json.> fromJson(value.toString(), mapLiteral); - Set uniques = Sets.difference(toPut.keySet(), valueContext.keySet()); - for (String k : uniques) - valueContext.put(k, toPut.get(k)); - Set conflicts = Sets.difference(toPut.keySet(), uniques); - for (String k : conflicts) { - JsonBall v = toPut.get(k); - if (v.toString().matches("^\\{.*\\}$")) { - mergeAsPeer(k, v, valueContext); - } else { - // replace - valueContext.put(k, v); - } - } - insertionContext.put(key, new JsonBall(json.toJson(valueContext, mapLiteral))); - } - - /** - * @param keyParts - * @param toInsert - * @param destination - * @throws IllegalArgumentException - *

- * if destination.get(keyParts(0)) is not a map * - *

- * keyParts is zero length - */ - void putUnderContext(List keyParts, JsonBall toInsert, Map destination) { - checkNotNull(keyParts, "keyParts"); - checkArgument(keyParts.size() >= 1, "keyParts must contain at least one element"); - - checkNotNull(toInsert, "toInsert"); - checkNotNull(destination, "destination"); - - String rootKey = keyParts.remove(0); - String rootValue = destination.containsKey(rootKey) ? destination.get(rootKey).toString() : "{}"; - - checkArgument(rootValue.matches("^\\{.*\\}$"), "value must be a hash: %s", rootValue); - Map insertionContext = json.fromJson(rootValue, mapLiteral); - if (keyParts.size() == 1) { - if (!insertionContext.containsKey(keyParts.get(0))) { - insertionContext.put(keyParts.get(0), toInsert); - } else { - String key = keyParts.get(0); - mergeAsPeer(key, toInsert, insertionContext); - } - } else { - putUnderContext(keyParts, toInsert, insertionContext); - } - destination.put(rootKey, new JsonBall(json.toJson(insertionContext, mapLiteral))); - } - - final Type mapLiteral = new TypeLiteral>() { - }.getType(); - final Type listLiteral = new TypeLiteral>() { - }.getType(); -} \ No newline at end of file diff --git a/chef/core/src/main/java/org/jclouds/ohai/suppliers/UptimeSecondsSupplier.java b/chef/core/src/main/java/org/jclouds/ohai/suppliers/UptimeSecondsSupplier.java deleted file mode 100644 index 05d5c4d424..0000000000 --- a/chef/core/src/main/java/org/jclouds/ohai/suppliers/UptimeSecondsSupplier.java +++ /dev/null @@ -1,51 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.ohai.suppliers; - -import java.lang.management.RuntimeMXBean; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import org.jclouds.domain.JsonBall; - -import com.google.common.base.Supplier; - -/** - * - * @author Adrian Cole - */ -@Singleton -public class UptimeSecondsSupplier implements Supplier { - - @Inject - UptimeSecondsSupplier(RuntimeMXBean runtime) { - this.runtime = runtime; - } - - private final RuntimeMXBean runtime; - - @Override - public JsonBall get() { - long uptimeInSeconds = runtime.getUptime() / 1000; - return new JsonBall(uptimeInSeconds); - } - -} \ No newline at end of file diff --git a/chef/core/src/main/resources/install-chef-gems.sh b/chef/core/src/main/resources/install-chef-gems.sh deleted file mode 100755 index e68baaa3cd..0000000000 --- a/chef/core/src/main/resources/install-chef-gems.sh +++ /dev/null @@ -1,15 +0,0 @@ -if [ ! -f /usr/bin/chef-client ]; then - apt-get update - apt-get install -y ruby ruby1.8-dev build-essential wget libruby-extras libruby1.8-extras - mkdir -p /tmp/bootchef - ( - cd /tmp/bootchef - wget http://rubyforge.org/frs/download.php/69365/rubygems-1.3.6.tgz - tar xvf rubygems-1.3.6.tgz - cd rubygems-1.3.6 - ruby setup.rb - cp /usr/bin/gem1.8 /usr/bin/gem - ) - rm -rf /tmp/bootchef - gem install chef ohai --no-rdoc --no-ri --verbose -fi diff --git a/chef/core/src/test/clojure/org/jclouds/chef_test.clj b/chef/core/src/test/clojure/org/jclouds/chef_test.clj deleted file mode 100644 index fb26934fad..0000000000 --- a/chef/core/src/test/clojure/org/jclouds/chef_test.clj +++ /dev/null @@ -1,72 +0,0 @@ -; -; -; Copyright (C) 2010 Cloud Conscious, LLC. -; -; ==================================================================== -; Licensed under the Apache License, Version 2.0 (the "License"); -; you may not use this file except in compliance with the License. -; You may obtain a copy of the License at -; -; http://www.apache.org/licenses/LICENSE-2.0 -; -; Unless required by applicable law or agreed to in writing, software -; distributed under the License is distributed on an "AS IS" BASIS, -; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -; See the License for the specific language governing permissions and -; limitations under the License. -; ==================================================================== -; - -(ns org.jclouds.chef-test - (:use [org.jclouds.chef] :reload-all) - (:use [clojure.test])) - -(defn clean-stub-fixture - "This should allow basic tests to easily be run with another service." - [service account key & options] - (fn [f] - (with-chef-service [(apply chef-service service account key options)] -(doseq [databag (databags)] - (delete-databag databag)) -(f)))) - -(use-fixtures :each (clean-stub-fixture "transientchef" "" "")) - -(deftest chef-service?-test - (is (chef-service? *chef*))) - -(deftest as-chef-service-test - (is (chef-service? (chef-service "transientchef" "" ""))) - (is (chef-service? (as-chef-service *chef*))) - (is (chef-service? (as-chef-service (chef-context *chef*))))) - -(deftest create-existing-databag-test - (is (not (databag-exists? ""))) - (create-databag "fred") - (is (databag-exists? "fred"))) - -(deftest create-databag-test - (create-databag "fred") - (is (databag-exists? "fred"))) - -(deftest databags-test - (is (empty? (databags))) - (create-databag "fred") - (is (= 1 (count (databags))))) - -(deftest databag-items-test - (create-databag "databag") - (is (empty? (databag-items "databag"))) - (is (create-databag-item "databag" {:id "databag-item1" :value "databag-value1"})) - (is (create-databag-item "databag" {:id "databag-item2" :value "databag-value2"})) - (is (= 2 (count (databag-items "databag"))))) - -(deftest databag-item-test - (create-databag "databag") - (is (create-databag-item "databag" {:id "databag-item1" :value "databag-value1"})) - (is (create-databag-item "databag" {:id "databag-item2" :value "databag-value2"})) - (is (= {:id "databag-item2" :value "databag-value2"} (databag-item "databag" "databag-item2")))) - -(deftest run-list-test - (update-run-list #{"recipe[foo]"} "tag") - (is (= ["recipe[foo]"] (run-list "tag")))) diff --git a/chef/core/src/test/java/org/jclouds/chef/BaseChefClientLiveTest.java b/chef/core/src/test/java/org/jclouds/chef/BaseChefClientLiveTest.java deleted file mode 100644 index e97da0ec2f..0000000000 --- a/chef/core/src/test/java/org/jclouds/chef/BaseChefClientLiveTest.java +++ /dev/null @@ -1,378 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.util.Collections; -import java.util.List; -import java.util.Properties; -import java.util.Set; - -import org.jclouds.chef.domain.ChecksumStatus; -import org.jclouds.chef.domain.Client; -import org.jclouds.chef.domain.CookbookVersion; -import org.jclouds.chef.domain.DatabagItem; -import org.jclouds.chef.domain.Node; -import org.jclouds.chef.domain.Resource; -import org.jclouds.chef.domain.Role; -import org.jclouds.chef.domain.SearchResult; -import org.jclouds.chef.domain.UploadSandbox; -import org.jclouds.crypto.CryptoStreams; -import org.jclouds.crypto.Pems; -import org.jclouds.io.InputSuppliers; -import org.jclouds.io.Payloads; -import org.jclouds.io.payloads.FilePayload; -import org.jclouds.json.Json; -import org.jclouds.rest.AuthorizationException; -import org.jclouds.rest.HttpClient; -import org.jclouds.rest.ResourceNotFoundException; -import org.testng.annotations.AfterClass; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableSet; -import com.google.common.primitives.Bytes; - -/** - * Tests behavior of {@code ChefClient} - * - * @author Adrian Cole - */ -@Test(groups = "live", testName = "chef.ChefClientLiveTest") -public abstract class BaseChefClientLiveTest { - - protected String clientKey; - - protected abstract void closeContexts(); - - protected abstract void recreateClientConnection() throws IOException; - - protected abstract ChefClient getClientConnection(); - - protected abstract ChefClient getValidatorConnection(); - - protected abstract ChefClient getAdminConnection(); - - protected abstract HttpClient getHttp(); - - public abstract void setupClient() throws IOException; - - protected String endpoint; - protected String user; - private Node node; - private Role role; - protected Json json; - protected DatabagItem databagItem; - public static final String PREFIX = System.getProperty("user.name") + "-jcloudstest"; - - public BaseChefClientLiveTest() { - super(); - } - - public void testCreateNewCookbook() throws Exception { - - // define the file you want in the cookbook - FilePayload content = Payloads.newFilePayload(new File(System.getProperty("user.dir"), "pom.xml")); - content.setContentType("application/x-binary"); - - // get an md5 so that you can see if the server already has it or not - Payloads.calculateMD5(content); - - // Note that java collections cannot effectively do equals or hashcodes on - // byte arrays, - // so let's convert to a list of bytes. - List md5 = Bytes.asList(content.getContentMD5()); - - // request an upload site for this file - UploadSandbox site = getAdminConnection().getUploadSandboxForChecksums(ImmutableSet.of(md5)); - - try { - assert site.getChecksums().containsKey(md5) : md5 + " not in " + site.getChecksums(); - - ChecksumStatus status = site.getChecksums().get(md5); - if (status.needsUpload()) { - getHttp().put(status.getUrl(), content); - } - - getAdminConnection().commitSandbox(site.getSandboxId(), true); - - } catch (RuntimeException e) { - getAdminConnection().commitSandbox(site.getSandboxId(), false); - } - - // create a new cookbook - CookbookVersion cookbook = new CookbookVersion("test3", "0.0.0"); - cookbook.getRootFiles().add(new Resource(content)); - - // upload the cookbook to the remote server - getAdminConnection().updateCookbook("test3", "0.0.0", cookbook); - } - - @Test(dependsOnMethods = "testCreateClient") - public void testGenerateKeyForClient() throws Exception { - clientKey = Pems.pem(getClientConnection().generateKeyForClient(PREFIX).getPrivateKey()); - - assertNotNull(clientKey); - recreateClientConnection(); - getClientConnection().clientExists(PREFIX); - } - - @Test(dependsOnMethods = "testCreateNewCookbook") - public void testListCookbooks() throws Exception { - for (String cookbook : getAdminConnection().listCookbooks()) - for (String version : getAdminConnection().getVersionsOfCookbook(cookbook)) { - System.err.printf("%s/%s:%n", cookbook, version); - CookbookVersion cookbookO = getAdminConnection().getCookbook(cookbook, version); - for (Resource resource : ImmutableList. builder().addAll(cookbookO.getDefinitions()).addAll( - cookbookO.getFiles()).addAll(cookbookO.getLibraries()).addAll(cookbookO.getSuppliers()).addAll( - cookbookO.getRecipes()).addAll(cookbookO.getResources()).addAll(cookbookO.getRootFiles()).addAll( - cookbookO.getTemplates()).build()) { - try { - InputStream stream = getHttp().get(resource.getUrl()); - byte[] md5 = CryptoStreams.md5(InputSuppliers.of(stream)); - assertEquals(md5, resource.getChecksum()); - } catch (NullPointerException e) { - assert false : "resource not found: " + resource; - } - System.err.printf("resource %s ok%n", resource.getName()); - } - } - } - - @Test(dependsOnMethods = "testListCookbooks") - public void testUpdateCookbook() throws Exception { - for (String cookbook : getAdminConnection().listCookbooks()) - for (String version : getAdminConnection().getVersionsOfCookbook(cookbook)) { - System.err.printf("%s/%s:%n", cookbook, version); - CookbookVersion cook = getAdminConnection().getCookbook(cookbook, version); - getAdminConnection().updateCookbook(cookbook, version, cook); - } - } - - @Test(dependsOnMethods = "testUpdateCookbook") - public void testCreateCookbook() throws Exception { - for (String cookbook : getAdminConnection().listCookbooks()) - for (String version : getAdminConnection().getVersionsOfCookbook(cookbook)) { - System.err.printf("%s/%s:%n", cookbook, version); - CookbookVersion cook = getAdminConnection().getCookbook(cookbook, version); - getAdminConnection().deleteCookbook(cookbook, version); - assert getAdminConnection().getCookbook(cookbook, version) == null : cookbook + version; - getAdminConnection().updateCookbook(cookbook, version, cook); - } - } - - @Test(expectedExceptions = AuthorizationException.class) - public void testValidatorCannotListClients() throws Exception { - for (String client : getValidatorConnection().listClients()) - assertNotNull(getValidatorConnection().getClient(client)); - } - - @Test(expectedExceptions = AuthorizationException.class) - public void testValidatorCannotDeleteClient() throws Exception { - getValidatorConnection().deleteClient(PREFIX); - } - - @Test(expectedExceptions = AuthorizationException.class) - public void testValidatorCannotCreateClient() throws Exception { - getValidatorConnection().createClient(PREFIX); - } - - @Test - public void testCreateClient() throws Exception { - getAdminConnection().deleteClient(PREFIX); - - clientKey = Pems.pem(getAdminConnection().createClient(PREFIX).getPrivateKey()); - - recreateClientConnection(); - getClientConnection().clientExists(PREFIX); - Set clients = getAdminConnection().listClients(); - assert clients.contains(PREFIX) : String.format("client %s not in %s", PREFIX, clients); - assertNotNull(getClientConnection().getClient(PREFIX)); - } - - @Test(dependsOnMethods = "testCreateClient") - public void testClientExists() throws Exception { - assertNotNull(getValidatorConnection().clientExists(PREFIX)); - } - - @Test - public void testListNodes() throws Exception { - Set nodes = getAdminConnection().listNodes(); - assertNotNull(nodes); - } - - @Test(dependsOnMethods = "testCreateRole") - public void testCreateNode() throws Exception { - getAdminConnection().deleteNode(PREFIX); - getClientConnection().createNode(new Node(PREFIX, Collections.singleton("role[" + PREFIX + "]"))); - node = getAdminConnection().getNode(PREFIX); - // TODO check recipes - assertNotNull(node); - Set nodes = getAdminConnection().listNodes(); - assert nodes.contains(PREFIX) : String.format("node %s not in %s", PREFIX, nodes); - } - - @Test(dependsOnMethods = "testCreateNode") - public void testNodeExists() throws Exception { - assertNotNull(getClientConnection().nodeExists(PREFIX)); - } - - @Test(dependsOnMethods = "testNodeExists") - public void testUpdateNode() throws Exception { - for (String nodename : getClientConnection().listNodes()) { - Node node = getAdminConnection().getNode(nodename); - getAdminConnection().updateNode(node); - } - } - - @Test - public void testListRoles() throws Exception { - Set roles = getAdminConnection().listRoles(); - assertNotNull(roles); - } - - @Test(dependsOnMethods = "testCreateClient") - public void testCreateRole() throws Exception { - getAdminConnection().deleteRole(PREFIX); - getAdminConnection().createRole(new Role(PREFIX, Collections.singleton("recipe[java]"))); - role = getAdminConnection().getRole(PREFIX); - assertNotNull(role); - assertEquals(role.getName(), PREFIX); - assertEquals(role.getRunList(), Collections.singleton("recipe[java]")); - } - - @Test(dependsOnMethods = "testCreateRole") - public void testRoleExists() throws Exception { - assertNotNull(getClientConnection().roleExists(PREFIX)); - } - - @Test(dependsOnMethods = "testRoleExists") - public void testUpdateRole() throws Exception { - for (String rolename : getClientConnection().listRoles()) { - Role role = getAdminConnection().getRole(rolename); - getAdminConnection().updateRole(role); - } - } - - @Test - public void testListDatabags() throws Exception { - Set databags = getAdminConnection().listDatabags(); - assertNotNull(databags); - } - - @Test(dependsOnMethods = "testCreateClient") - public void testCreateDatabag() throws Exception { - getAdminConnection().deleteDatabag(PREFIX); - getAdminConnection().createDatabag(PREFIX); - } - - @Test(dependsOnMethods = "testCreateDatabag") - public void testDatabagExists() throws Exception { - assertNotNull(getClientConnection().databagExists(PREFIX)); - } - - @Test(dependsOnMethods = "testCreateDatabagItem") - public void testListDatabagItems() throws Exception { - Set databagItems = getAdminConnection().listDatabagItems(PREFIX); - assertNotNull(databagItems); - } - - @Test(dependsOnMethods = { "testCreateDatabag", "testCreateRole" }) - public void testCreateDatabagItem() throws Exception { - Properties config = new Properties(); - config.setProperty("foo", "bar"); - getAdminConnection().deleteDatabagItem(PREFIX, PREFIX); - databagItem = getAdminConnection().createDatabagItem(PREFIX, new DatabagItem("config", json.toJson(config))); - assertNotNull(databagItem); - assertEquals(databagItem.getId(), "config"); - assertEquals(config, json.fromJson(databagItem.toString(), Properties.class)); - } - - @Test(dependsOnMethods = "testCreateDatabagItem") - public void testDatabagItemExists() throws Exception { - assertNotNull(getClientConnection().databagItemExists(PREFIX, PREFIX)); - } - - @Test(dependsOnMethods = "testDatabagItemExists") - public void testUpdateDatabagItem() throws Exception { - for (String databagItemId : getClientConnection().listDatabagItems(PREFIX)) { - DatabagItem databagItem = getAdminConnection().getDatabagItem(PREFIX, databagItemId); - getAdminConnection().updateDatabagItem(PREFIX, databagItem); - } - } - - @Test - public void testListSearchIndexes() throws Exception { - Set indexes = getAdminConnection().listSearchIndexes(); - assertNotNull(indexes); - assert indexes.contains("node") : indexes; - assert indexes.contains("client") : indexes; - assert indexes.contains("role") : indexes; - } - - @Test - public void testSearchNodes() throws Exception { - SearchResult results = getAdminConnection().searchNodes(); - assertNotNull(results); - } - - @Test - public void testSearchClients() throws Exception { - SearchResult results = getAdminConnection().searchClients(); - assertNotNull(results); - } - - @Test - public void testSearchRoles() throws Exception { - SearchResult results = getAdminConnection().searchRoles(); - assertNotNull(results); - } - - @Test(dependsOnMethods = "testDatabagItemExists") - public void testSearchDatabag() throws Exception { - SearchResult results = getAdminConnection().searchDatabag(PREFIX); - assertNotNull(results); - } - - @Test(expectedExceptions = ResourceNotFoundException.class) - public void testSearchDatabagNotFound() throws Exception { - SearchResult results = getAdminConnection().searchDatabag("whoopie"); - assertNotNull(results); - } - - @AfterClass(groups = { "live" }) - public void teardownClient() throws IOException { - if (getValidatorConnection().clientExists(PREFIX)) - getValidatorConnection().deleteClient(PREFIX); - if (getAdminConnection().nodeExists(PREFIX)) - getAdminConnection().deleteNode(PREFIX); - if (getAdminConnection().roleExists(PREFIX)) - getAdminConnection().deleteRole(PREFIX); - if (getAdminConnection().databagExists(PREFIX)) - getAdminConnection().deleteDatabag(PREFIX); - closeContexts(); - } - -} \ No newline at end of file diff --git a/chef/core/src/test/java/org/jclouds/chef/ChefAsyncClientTest.java b/chef/core/src/test/java/org/jclouds/chef/ChefAsyncClientTest.java deleted file mode 100644 index 9c32215796..0000000000 --- a/chef/core/src/test/java/org/jclouds/chef/ChefAsyncClientTest.java +++ /dev/null @@ -1,745 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef; - -import static org.testng.Assert.assertEquals; - -import java.io.IOException; -import java.lang.reflect.Method; -import java.util.Properties; -import java.util.Set; - -import org.jclouds.chef.config.ChefRestClientModule; -import org.jclouds.chef.domain.CookbookVersion; -import org.jclouds.chef.domain.DatabagItem; -import org.jclouds.chef.domain.Node; -import org.jclouds.chef.domain.Role; -import org.jclouds.chef.filters.SignedHeaderAuth; -import org.jclouds.chef.filters.SignedHeaderAuthTest; -import org.jclouds.chef.functions.ParseKeySetFromJson; -import org.jclouds.chef.functions.ParseSearchClientsFromJson; -import org.jclouds.chef.functions.ParseSearchDatabagFromJson; -import org.jclouds.chef.functions.ParseSearchNodesFromJson; -import org.jclouds.chef.functions.ParseSearchRolesFromJson; -import org.jclouds.crypto.CryptoStreams; -import org.jclouds.date.TimeStamp; -import org.jclouds.http.HttpRequest; -import org.jclouds.http.RequiresHttp; -import org.jclouds.http.functions.ParseJson; -import org.jclouds.http.functions.ReleasePayloadAndReturn; -import org.jclouds.http.functions.ReturnTrueIf2xx; -import org.jclouds.rest.ConfiguresRestClient; -import org.jclouds.rest.RestClientTest; -import org.jclouds.rest.RestContextFactory; -import org.jclouds.rest.RestContextFactory.ContextSpec; -import org.jclouds.rest.functions.MapHttp4xxCodesToExceptions; -import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404; -import org.jclouds.rest.functions.ReturnFalseOnNotFoundOr404; -import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; -import org.jclouds.rest.functions.ReturnVoidOnNotFoundOr404; -import org.jclouds.rest.internal.GeneratedHttpRequest; -import org.jclouds.rest.internal.RestAnnotationProcessor; -import org.testng.annotations.Test; - -import com.google.common.base.Supplier; -import com.google.common.collect.ImmutableSet; -import com.google.common.primitives.Bytes; -import com.google.inject.Module; -import com.google.inject.TypeLiteral; - -/** - * Tests annotation parsing of {@code ChefAsyncClient} - * - * @author Adrian Cole - */ -@Test(groups = "unit", testName = "chef.ChefAsyncClientTest") -public class ChefAsyncClientTest extends RestClientTest { - - public void testCommitSandbox() throws SecurityException, NoSuchMethodException, IOException { - - Method method = ChefAsyncClient.class.getMethod("commitSandbox", String.class, boolean.class); - GeneratedHttpRequest httpRequest = processor.createRequest(method, - "0189e76ccc476701d6b374e5a1a27347", true); - assertRequestLineEquals(httpRequest, - "PUT http://localhost:4000/sandboxes/0189e76ccc476701d6b374e5a1a27347 HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - assertPayloadEquals(httpRequest, "{\"is_completed\":\"true\"}", "application/json", false); - - assertResponseParserClassEquals(method, httpRequest, ParseJson.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); - - checkFilters(httpRequest); - - } - - public void testGetUploadSandboxForChecksums() throws SecurityException, NoSuchMethodException, IOException { - Method method = ChefAsyncClient.class.getMethod("getUploadSandboxForChecksums", Set.class); - GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableSet.of(Bytes - .asList(CryptoStreams.hex("0189e76ccc476701d6b374e5a1a27347")), Bytes.asList(CryptoStreams - .hex("0c5ecd7788cf4f6c7de2a57193897a6c")), Bytes.asList(CryptoStreams - .hex("1dda05ed139664f1f89b9dec482b77c0")))); - assertRequestLineEquals(httpRequest, "POST http://localhost:4000/sandboxes HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - assertPayloadEquals( - httpRequest, - "{\"checksums\":{\"0189e76ccc476701d6b374e5a1a27347\":null,\"0c5ecd7788cf4f6c7de2a57193897a6c\":null,\"1dda05ed139664f1f89b9dec482b77c0\":null}}", - "application/json", false); - - assertResponseParserClassEquals(method, httpRequest, ParseJson.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); - - checkFilters(httpRequest); - - } - - public void testGetCookbook() throws SecurityException, NoSuchMethodException, IOException { - Method method = ChefAsyncClient.class.getMethod("getCookbook", String.class, String.class); - GeneratedHttpRequest httpRequest = processor.createRequest(method, "cookbook", "1.0.0"); - assertRequestLineEquals(httpRequest, "GET http://localhost:4000/cookbooks/cookbook/1.0.0 HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - assertPayloadEquals(httpRequest, null, null, false); - - assertResponseParserClassEquals(method, httpRequest, ParseJson.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); - - checkFilters(httpRequest); - - } - - public void testDeleteCookbook() throws SecurityException, NoSuchMethodException, IOException { - Method method = ChefAsyncClient.class.getMethod("deleteCookbook", String.class, String.class); - GeneratedHttpRequest httpRequest = processor.createRequest(method, "cookbook", "1.0.0"); - assertRequestLineEquals(httpRequest, "DELETE http://localhost:4000/cookbooks/cookbook/1.0.0 HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - assertPayloadEquals(httpRequest, null, null, false); - - assertResponseParserClassEquals(method, httpRequest, ParseJson.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); - - checkFilters(httpRequest); - - } - - public void testUpdateCookbook() throws SecurityException, NoSuchMethodException, IOException { - Method method = ChefAsyncClient.class.getMethod("updateCookbook", String.class, String.class, - CookbookVersion.class); - GeneratedHttpRequest httpRequest = processor.createRequest(method, "cookbook", "1.0.1", - new CookbookVersion("cookbook", "1.0.1")); - - assertRequestLineEquals(httpRequest, "PUT http://localhost:4000/cookbooks/cookbook/1.0.1 HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - assertPayloadEquals( - httpRequest, - "{\"name\":\"cookbook-1.0.1\",\"definitions\":[],\"attributes\":[],\"files\":[],\"metadata\":{\"suggestions\":{},\"dependencies\":{},\"conflicting\":{},\"providing\":{},\"platforms\":{},\"recipes\":{},\"replacing\":{},\"groupings\":{},\"attributes\":{},\"recommendations\":{}},\"providers\":[],\"cookbook_name\":\"cookbook\",\"resources\":[],\"templates\":[],\"libraries\":[],\"version\":\"1.0.1\",\"recipes\":[],\"root_files\":[],\"json_class\":\"Chef::CookbookVersion\",\"chef_type\":\"cookbook_version\"}", - "application/json", false); - assertResponseParserClassEquals(method, httpRequest, ParseJson.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); - - checkFilters(httpRequest); - - } - - public void testListCookbooks() throws SecurityException, NoSuchMethodException, IOException { - Method method = ChefAsyncClient.class.getMethod("listCookbooks"); - GeneratedHttpRequest httpRequest = processor.createRequest(method); - - assertRequestLineEquals(httpRequest, "GET http://localhost:4000/cookbooks HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - assertPayloadEquals(httpRequest, null, null, false); - - assertResponseParserClassEquals(method, httpRequest, ParseKeySetFromJson.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); - - checkFilters(httpRequest); - - } - - public void testClientExists() throws SecurityException, NoSuchMethodException, IOException { - Method method = ChefAsyncClient.class.getMethod("clientExists", String.class); - GeneratedHttpRequest httpRequest = processor.createRequest(method, "client"); - assertRequestLineEquals(httpRequest, "HEAD http://localhost:4000/clients/client HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - assertPayloadEquals(httpRequest, null, null, false); - - assertResponseParserClassEquals(method, httpRequest, ReturnTrueIf2xx.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnFalseOnNotFoundOr404.class); - - checkFilters(httpRequest); - - } - - public void testDeleteClient() throws SecurityException, NoSuchMethodException, IOException { - Method method = ChefAsyncClient.class.getMethod("deleteClient", String.class); - GeneratedHttpRequest httpRequest = processor.createRequest(method, "client"); - assertRequestLineEquals(httpRequest, "DELETE http://localhost:4000/clients/client HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - assertPayloadEquals(httpRequest, null, null, false); - - assertResponseParserClassEquals(method, httpRequest, ParseJson.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); - - checkFilters(httpRequest); - - } - - public void testCreateClient() throws SecurityException, NoSuchMethodException, IOException { - Method method = ChefAsyncClient.class.getMethod("createClient", String.class); - GeneratedHttpRequest httpRequest = processor.createRequest(method, "client"); - - assertRequestLineEquals(httpRequest, "POST http://localhost:4000/clients HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - assertPayloadEquals(httpRequest, "{\"clientname\":\"client\"}", "application/json", false); - - assertResponseParserClassEquals(method, httpRequest, ParseJson.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); - - checkFilters(httpRequest); - - } - - public void testListClients() throws SecurityException, NoSuchMethodException, IOException { - Method method = ChefAsyncClient.class.getMethod("listClients"); - GeneratedHttpRequest httpRequest = processor.createRequest(method); - - assertRequestLineEquals(httpRequest, "GET http://localhost:4000/clients HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - assertPayloadEquals(httpRequest, null, null, false); - - assertResponseParserClassEquals(method, httpRequest, ParseKeySetFromJson.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); - - checkFilters(httpRequest); - - } - - public void testGenerateKeyForClient() throws SecurityException, NoSuchMethodException, IOException { - Method method = ChefAsyncClient.class.getMethod("generateKeyForClient", String.class); - GeneratedHttpRequest httpRequest = processor.createRequest(method, "client"); - assertRequestLineEquals(httpRequest, "PUT http://localhost:4000/clients/client HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - assertPayloadEquals(httpRequest, "{\"clientname\":\"client\", \"private_key\": true}", "application/json", false); - - assertResponseParserClassEquals(method, httpRequest, ParseJson.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); - - checkFilters(httpRequest); - - } - - public void testNodeExists() throws SecurityException, NoSuchMethodException, IOException { - Method method = ChefAsyncClient.class.getMethod("nodeExists", String.class); - GeneratedHttpRequest httpRequest = processor.createRequest(method, "node"); - assertRequestLineEquals(httpRequest, "HEAD http://localhost:4000/nodes/node HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - assertPayloadEquals(httpRequest, null, null, false); - - assertResponseParserClassEquals(method, httpRequest, ReturnTrueIf2xx.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnFalseOnNotFoundOr404.class); - - checkFilters(httpRequest); - - } - - public void testDeleteNode() throws SecurityException, NoSuchMethodException, IOException { - Method method = ChefAsyncClient.class.getMethod("deleteNode", String.class); - GeneratedHttpRequest httpRequest = processor.createRequest(method, "node"); - assertRequestLineEquals(httpRequest, "DELETE http://localhost:4000/nodes/node HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - assertPayloadEquals(httpRequest, null, null, false); - - assertResponseParserClassEquals(method, httpRequest, ParseJson.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); - - checkFilters(httpRequest); - - } - - public void testCreateNode() throws SecurityException, NoSuchMethodException, IOException { - Method method = ChefAsyncClient.class.getMethod("createNode", Node.class); - GeneratedHttpRequest httpRequest = processor.createRequest(method, new Node("testnode", - ImmutableSet.of("recipe[java]"))); - - assertRequestLineEquals(httpRequest, "POST http://localhost:4000/nodes HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - assertPayloadEquals( - httpRequest, - "{\"name\":\"testnode\",\"normal\":{},\"override\":{},\"default\":{},\"automatic\":{},\"run_list\":[\"recipe[java]\"],\"json_class\":\"Chef::Node\",\"chef_type\":\"node\"}", - "application/json", false); - - assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); - - checkFilters(httpRequest); - - } - - public void testUpdateNode() throws SecurityException, NoSuchMethodException, IOException { - Method method = ChefAsyncClient.class.getMethod("updateNode", Node.class); - GeneratedHttpRequest httpRequest = processor.createRequest(method, new Node("testnode", - ImmutableSet.of("recipe[java]"))); - - assertRequestLineEquals(httpRequest, "PUT http://localhost:4000/nodes/testnode HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - assertPayloadEquals( - httpRequest, - "{\"name\":\"testnode\",\"normal\":{},\"override\":{},\"default\":{},\"automatic\":{},\"run_list\":[\"recipe[java]\"],\"json_class\":\"Chef::Node\",\"chef_type\":\"node\"}", - "application/json", false); - - assertResponseParserClassEquals(method, httpRequest, ParseJson.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); - - checkFilters(httpRequest); - - } - - public void testListNodes() throws SecurityException, NoSuchMethodException, IOException { - Method method = ChefAsyncClient.class.getMethod("listNodes"); - GeneratedHttpRequest httpRequest = processor.createRequest(method); - - assertRequestLineEquals(httpRequest, "GET http://localhost:4000/nodes HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - assertPayloadEquals(httpRequest, null, null, false); - - assertResponseParserClassEquals(method, httpRequest, ParseKeySetFromJson.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); - - checkFilters(httpRequest); - - } - - public void testRoleExists() throws SecurityException, NoSuchMethodException, IOException { - Method method = ChefAsyncClient.class.getMethod("roleExists", String.class); - GeneratedHttpRequest httpRequest = processor.createRequest(method, "role"); - assertRequestLineEquals(httpRequest, "HEAD http://localhost:4000/roles/role HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - assertPayloadEquals(httpRequest, null, null, false); - - assertResponseParserClassEquals(method, httpRequest, ReturnTrueIf2xx.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnFalseOnNotFoundOr404.class); - - checkFilters(httpRequest); - - } - - public void testDeleteRole() throws SecurityException, NoSuchMethodException, IOException { - Method method = ChefAsyncClient.class.getMethod("deleteRole", String.class); - GeneratedHttpRequest httpRequest = processor.createRequest(method, "role"); - assertRequestLineEquals(httpRequest, "DELETE http://localhost:4000/roles/role HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - assertPayloadEquals(httpRequest, null, null, false); - - assertResponseParserClassEquals(method, httpRequest, ParseJson.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); - - checkFilters(httpRequest); - - } - - public void testCreateRole() throws SecurityException, NoSuchMethodException, IOException { - Method method = ChefAsyncClient.class.getMethod("createRole", Role.class); - GeneratedHttpRequest httpRequest = processor.createRequest(method, new Role("testrole", - ImmutableSet.of("recipe[java]"))); - - assertRequestLineEquals(httpRequest, "POST http://localhost:4000/roles HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - assertPayloadEquals( - httpRequest, - "{\"name\":\"testrole\",\"override_attributes\":{},\"default_attributes\":{},\"run_list\":[\"recipe[java]\"],\"json_class\":\"Chef::Role\",\"chef_type\":\"role\"}", - "application/json", false); - - assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); - - checkFilters(httpRequest); - - } - - public void testUpdateRole() throws SecurityException, NoSuchMethodException, IOException { - Method method = ChefAsyncClient.class.getMethod("updateRole", Role.class); - GeneratedHttpRequest httpRequest = processor.createRequest(method, new Role("testrole", - ImmutableSet.of("recipe[java]"))); - - assertRequestLineEquals(httpRequest, "PUT http://localhost:4000/roles/testrole HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - assertPayloadEquals( - httpRequest, - "{\"name\":\"testrole\",\"override_attributes\":{},\"default_attributes\":{},\"run_list\":[\"recipe[java]\"],\"json_class\":\"Chef::Role\",\"chef_type\":\"role\"}", - "application/json", false); - - assertResponseParserClassEquals(method, httpRequest, ParseJson.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); - - checkFilters(httpRequest); - - } - - public void testListRoles() throws SecurityException, NoSuchMethodException, IOException { - Method method = ChefAsyncClient.class.getMethod("listRoles"); - GeneratedHttpRequest httpRequest = processor.createRequest(method); - - assertRequestLineEquals(httpRequest, "GET http://localhost:4000/roles HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - assertPayloadEquals(httpRequest, null, null, false); - - assertResponseParserClassEquals(method, httpRequest, ParseKeySetFromJson.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); - - checkFilters(httpRequest); - - } - - public void testDatabagExists() throws SecurityException, NoSuchMethodException, IOException { - Method method = ChefAsyncClient.class.getMethod("databagExists", String.class); - GeneratedHttpRequest httpRequest = processor.createRequest(method, "databag"); - assertRequestLineEquals(httpRequest, "HEAD http://localhost:4000/data/databag HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - assertPayloadEquals(httpRequest, null, null, false); - - assertResponseParserClassEquals(method, httpRequest, ReturnTrueIf2xx.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnFalseOnNotFoundOr404.class); - - checkFilters(httpRequest); - - } - - public void testDeleteDatabag() throws SecurityException, NoSuchMethodException, IOException { - Method method = ChefAsyncClient.class.getMethod("deleteDatabag", String.class); - GeneratedHttpRequest httpRequest = processor.createRequest(method, "databag"); - assertRequestLineEquals(httpRequest, "DELETE http://localhost:4000/data/databag HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - assertPayloadEquals(httpRequest, null, null, false); - - assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnVoidOnNotFoundOr404.class); - - checkFilters(httpRequest); - - } - - public void testCreateDatabag() throws SecurityException, NoSuchMethodException, IOException { - Method method = ChefAsyncClient.class.getMethod("createDatabag", String.class); - GeneratedHttpRequest httpRequest = processor.createRequest(method, "name"); - - assertRequestLineEquals(httpRequest, "POST http://localhost:4000/data HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - assertPayloadEquals(httpRequest, "{\"name\":\"name\"}", "application/json", false); - - assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); - - checkFilters(httpRequest); - - } - - public void testListDatabags() throws SecurityException, NoSuchMethodException, IOException { - Method method = ChefAsyncClient.class.getMethod("listDatabags"); - GeneratedHttpRequest httpRequest = processor.createRequest(method); - - assertRequestLineEquals(httpRequest, "GET http://localhost:4000/data HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - assertPayloadEquals(httpRequest, null, null, false); - - assertResponseParserClassEquals(method, httpRequest, ParseKeySetFromJson.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); - - checkFilters(httpRequest); - - } - - public void testDatabagItemExists() throws SecurityException, NoSuchMethodException, IOException { - Method method = ChefAsyncClient.class.getMethod("databagItemExists", String.class, String.class); - GeneratedHttpRequest httpRequest = processor.createRequest(method, "name", "databagItem"); - assertRequestLineEquals(httpRequest, "HEAD http://localhost:4000/data/name/databagItem HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - assertPayloadEquals(httpRequest, null, null, false); - - assertResponseParserClassEquals(method, httpRequest, ReturnTrueIf2xx.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnFalseOnNotFoundOr404.class); - - checkFilters(httpRequest); - - } - - public void testDeleteDatabagItem() throws SecurityException, NoSuchMethodException, IOException { - Method method = ChefAsyncClient.class.getMethod("deleteDatabagItem", String.class, String.class); - GeneratedHttpRequest httpRequest = processor.createRequest(method, "name", "databagItem"); - assertRequestLineEquals(httpRequest, "DELETE http://localhost:4000/data/name/databagItem HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - assertPayloadEquals(httpRequest, null, null, false); - - assertResponseParserClassEquals(method, httpRequest, ParseJson.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); - - checkFilters(httpRequest); - - } - - @Test(expectedExceptions = IllegalArgumentException.class) - public void testCreateDatabagItemThrowsIllegalArgumentOnPrimitive() throws SecurityException, NoSuchMethodException, - IOException { - Method method = ChefAsyncClient.class.getMethod("createDatabagItem", String.class, DatabagItem.class); - GeneratedHttpRequest httpRequest = processor.createRequest(method, "name", new DatabagItem("id", - "100")); - - assertRequestLineEquals(httpRequest, "POST http://localhost:4000/data/name HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - assertPayloadEquals( - httpRequest, - "{\"name\":\"testdatabagItem\",\"override_attributes\":{},\"default_attributes\":{},\"run_list\":[\"recipe[java]\"],\"json_class\":\"Chef::DatabagItem\",\"chef_type\":\"databagItem\"}", - "application/json", false); - - assertResponseParserClassEquals(method, httpRequest, ParseJson.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); - - checkFilters(httpRequest); - - } - - @Test(expectedExceptions = IllegalArgumentException.class) - public void testCreateDatabagItemThrowsIllegalArgumentOnWrongId() throws SecurityException, NoSuchMethodException, - IOException { - Method method = ChefAsyncClient.class.getMethod("createDatabagItem", String.class, DatabagItem.class); - GeneratedHttpRequest httpRequest = processor.createRequest(method, "name", new DatabagItem("id", - "{\"id\": \"item1\",\"my_key\": \"my_data\"}")); - - assertRequestLineEquals(httpRequest, "POST http://localhost:4000/data/name HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - assertPayloadEquals( - httpRequest, - "{\"name\":\"testdatabagItem\",\"override_attributes\":{},\"default_attributes\":{},\"run_list\":[\"recipe[java]\"],\"json_class\":\"Chef::DatabagItem\",\"chef_type\":\"databagItem\"}", - "application/json", false); - - assertResponseParserClassEquals(method, httpRequest, ParseJson.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); - - checkFilters(httpRequest); - - } - - public void testCreateDatabagItem() throws SecurityException, NoSuchMethodException, IOException { - Method method = ChefAsyncClient.class.getMethod("createDatabagItem", String.class, DatabagItem.class); - GeneratedHttpRequest httpRequest = processor.createRequest(method, "name", new DatabagItem("id", - "{\"id\": \"id\",\"my_key\": \"my_data\"}")); - - assertRequestLineEquals(httpRequest, "POST http://localhost:4000/data/name HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - assertPayloadEquals(httpRequest, "{\"id\": \"id\",\"my_key\": \"my_data\"}", "application/json", false); - - assertResponseParserClassEquals(method, httpRequest, ParseJson.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); - - checkFilters(httpRequest); - - } - - public void testCreateDatabagItemEvenWhenUserForgotId() throws SecurityException, NoSuchMethodException, IOException { - Method method = ChefAsyncClient.class.getMethod("createDatabagItem", String.class, DatabagItem.class); - GeneratedHttpRequest httpRequest = processor.createRequest(method, "name", new DatabagItem("id", - "{\"my_key\": \"my_data\"}")); - - assertRequestLineEquals(httpRequest, "POST http://localhost:4000/data/name HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - assertPayloadEquals(httpRequest, "{\"id\":\"id\",\"my_key\": \"my_data\"}", "application/json", false); - - assertResponseParserClassEquals(method, httpRequest, ParseJson.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); - - checkFilters(httpRequest); - - } - - public void testUpdateDatabagItem() throws SecurityException, NoSuchMethodException, IOException { - Method method = ChefAsyncClient.class.getMethod("updateDatabagItem", String.class, DatabagItem.class); - GeneratedHttpRequest httpRequest = processor.createRequest(method, "name", new DatabagItem("id", - "{\"my_key\": \"my_data\"}")); - - assertRequestLineEquals(httpRequest, "PUT http://localhost:4000/data/name/id HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - - assertPayloadEquals(httpRequest, "{\"id\":\"id\",\"my_key\": \"my_data\"}", "application/json", false); - - assertResponseParserClassEquals(method, httpRequest, ParseJson.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); - - checkFilters(httpRequest); - - } - - public void testListDatabagItems() throws SecurityException, NoSuchMethodException, IOException { - Method method = ChefAsyncClient.class.getMethod("listDatabagItems", String.class); - GeneratedHttpRequest httpRequest = processor.createRequest(method, "name"); - - assertRequestLineEquals(httpRequest, "GET http://localhost:4000/data/name HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - assertPayloadEquals(httpRequest, null, null, false); - - assertResponseParserClassEquals(method, httpRequest, ParseKeySetFromJson.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); - - checkFilters(httpRequest); - - } - - public void testListSearchIndexes() throws SecurityException, NoSuchMethodException, IOException { - Method method = ChefAsyncClient.class.getMethod("listSearchIndexes"); - GeneratedHttpRequest httpRequest = processor.createRequest(method); - - assertRequestLineEquals(httpRequest, "GET http://localhost:4000/search HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - assertPayloadEquals(httpRequest, null, null, false); - - assertResponseParserClassEquals(method, httpRequest, ParseKeySetFromJson.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); - - checkFilters(httpRequest); - - } - - public void testSearchRoles() throws SecurityException, NoSuchMethodException, IOException { - Method method = ChefAsyncClient.class.getMethod("searchRoles"); - GeneratedHttpRequest httpRequest = processor.createRequest(method); - - assertRequestLineEquals(httpRequest, "GET http://localhost:4000/search/role HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - assertPayloadEquals(httpRequest, null, null, false); - - assertResponseParserClassEquals(method, httpRequest, ParseSearchRolesFromJson.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, MapHttp4xxCodesToExceptions.class); - - checkFilters(httpRequest); - - } - - public void testSearchClients() throws SecurityException, NoSuchMethodException, IOException { - Method method = ChefAsyncClient.class.getMethod("searchClients"); - GeneratedHttpRequest httpRequest = processor.createRequest(method); - - assertRequestLineEquals(httpRequest, "GET http://localhost:4000/search/client HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - assertPayloadEquals(httpRequest, null, null, false); - - assertResponseParserClassEquals(method, httpRequest, ParseSearchClientsFromJson.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, MapHttp4xxCodesToExceptions.class); - - checkFilters(httpRequest); - - } - - public void testSearchNodes() throws SecurityException, NoSuchMethodException, IOException { - Method method = ChefAsyncClient.class.getMethod("searchNodes"); - GeneratedHttpRequest httpRequest = processor.createRequest(method); - - assertRequestLineEquals(httpRequest, "GET http://localhost:4000/search/node HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - assertPayloadEquals(httpRequest, null, null, false); - - assertResponseParserClassEquals(method, httpRequest, ParseSearchNodesFromJson.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, MapHttp4xxCodesToExceptions.class); - - checkFilters(httpRequest); - - } - - public void testSearchDatabag() throws SecurityException, NoSuchMethodException, IOException { - Method method = ChefAsyncClient.class.getMethod("searchDatabag", String.class); - GeneratedHttpRequest httpRequest = processor.createRequest(method, "foo"); - - assertRequestLineEquals(httpRequest, "GET http://localhost:4000/search/foo HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - assertPayloadEquals(httpRequest, null, null, false); - - assertResponseParserClassEquals(method, httpRequest, ParseSearchDatabagFromJson.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, MapHttp4xxCodesToExceptions.class); - - checkFilters(httpRequest); - - } - - @Override - protected void checkFilters(HttpRequest request) { - assertEquals(request.getFilters().size(), 1); - assertEquals(request.getFilters().get(0).getClass(), SignedHeaderAuth.class); - } - - @Override - protected TypeLiteral> createTypeLiteral() { - return new TypeLiteral>() { - }; - } - - @Override - protected Module createModule() { - return new TestChefRestClientModule(); - } - - @RequiresHttp - @ConfiguresRestClient - static class TestChefRestClientModule extends ChefRestClientModule { - @Override - protected String provideTimeStamp(@TimeStamp Supplier cache) { - return "timestamp"; - } - - } - - @Override - public ContextSpec createContextSpec() { - return new RestContextFactory().createContextSpec("chef", "user", SignedHeaderAuthTest.PRIVATE_KEY, - new Properties()); - } -} diff --git a/chef/core/src/test/java/org/jclouds/chef/ChefClientLiveTest.java b/chef/core/src/test/java/org/jclouds/chef/ChefClientLiveTest.java deleted file mode 100644 index 416277b112..0000000000 --- a/chef/core/src/test/java/org/jclouds/chef/ChefClientLiveTest.java +++ /dev/null @@ -1,126 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef; - -import static com.google.common.base.Preconditions.checkNotNull; -import static org.testng.Assert.assertNotNull; - -import java.io.File; -import java.io.IOException; -import java.util.Properties; - -import org.jclouds.chef.config.ChefParserModule; -import org.jclouds.chef.domain.CookbookVersion; -import org.jclouds.json.Json; -import org.jclouds.json.config.GsonModule; -import org.jclouds.logging.log4j.config.Log4JLoggingModule; -import org.jclouds.rest.HttpClient; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import com.google.common.base.Charsets; -import com.google.common.collect.ImmutableSet; -import com.google.common.io.Files; -import com.google.inject.Guice; -import com.google.inject.Module; - -/** - * Tests behavior of {@code ChefClient} - * - * @author Adrian Cole - */ -@Test(groups = "live", testName = "chef.ChefClientLiveTest") -public class ChefClientLiveTest extends BaseChefClientLiveTest { - - private ChefContext validatorConnection; - private ChefContext clientConnection; - private ChefContext adminConnection; - - private String validator; - - @Override - @BeforeClass(groups = { "live" }) - public void setupClient() throws IOException { - endpoint = checkNotNull(System.getProperty("jclouds.test.endpoint"), "jclouds.test.endpoint"); - validator = System.getProperty("jclouds.test.validator"); - if (validator == null || validator.equals("")) - validator = "chef-validator"; - String validatorKey = System.getProperty("jclouds.test.validator.key"); - if (validatorKey == null || validatorKey.equals("")) - validatorKey = System.getProperty("user.home") + "/.chef/validation.pem"; - user = checkNotNull(System.getProperty("jclouds.test.identity"), "jclouds.test.identity"); - String keyfile = System.getProperty("jclouds.test.credential"); - if (keyfile == null || keyfile.equals("")) - keyfile = System.getProperty("user.home") + "/.chef/" + user + ".pem"; - validatorConnection = createConnection(validator, Files.toString(new File(validatorKey), Charsets.UTF_8)); - adminConnection = createConnection(user, Files.toString(new File(keyfile), Charsets.UTF_8)); - json = Guice.createInjector(new GsonModule(), new ChefParserModule()).getInstance(Json.class); - } - - private ChefContext createConnection(String identity, String key) throws IOException { - Properties props = new Properties(); - props.setProperty("chef.endpoint", endpoint); - return new ChefContextFactory().createContext(identity, key, ImmutableSet. of(new Log4JLoggingModule()), - props); - } - - @Override - protected HttpClient getHttp() { - return adminConnection.utils().http(); - } - - @Override - protected ChefClient getAdminConnection() { - return adminConnection.getApi(); - } - - @Override - protected ChefClient getValidatorConnection() { - return validatorConnection.getApi(); - } - - @Override - protected ChefClient getClientConnection() { - return clientConnection.getApi(); - } - - @Override - protected void recreateClientConnection() throws IOException { - if (clientConnection != null) - clientConnection.close(); - clientConnection = createConnection(PREFIX, clientKey); - } - - @Test - public void testListCookbookVersionsWithChefService() throws Exception { - Iterable cookbooks = adminConnection.getChefService().listCookbookVersions(); - assertNotNull(cookbooks); - } - - @Override - protected void closeContexts() { - if (clientConnection != null) - clientConnection.close(); - if (validatorConnection != null) - validatorConnection.close(); - if (adminConnection != null) - adminConnection.close(); - } -} diff --git a/chef/core/src/test/java/org/jclouds/chef/ProvidersInPropertiesTest.java b/chef/core/src/test/java/org/jclouds/chef/ProvidersInPropertiesTest.java deleted file mode 100644 index 6fec644db0..0000000000 --- a/chef/core/src/test/java/org/jclouds/chef/ProvidersInPropertiesTest.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef; - -import org.jclouds.util.Utils; -import org.testng.annotations.Test; - -import com.google.common.collect.Iterables; - -/** - * - * @author Adrian Cole - * - */ -@Test(groups = "unit") -public class ProvidersInPropertiesTest { - - @Test - public void testSupportedProviders() { - Iterable providers = Utils.getSupportedProviders(); - assert Iterables.contains(providers, "chef") : providers; - } - -} diff --git a/chef/core/src/test/java/org/jclouds/chef/binders/BindHexEncodedMD5sToJsonPayloadTest.java b/chef/core/src/test/java/org/jclouds/chef/binders/BindHexEncodedMD5sToJsonPayloadTest.java deleted file mode 100644 index f698e0b163..0000000000 --- a/chef/core/src/test/java/org/jclouds/chef/binders/BindHexEncodedMD5sToJsonPayloadTest.java +++ /dev/null @@ -1,67 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.binders; - -import static org.testng.Assert.assertEquals; - -import java.io.File; -import java.net.URI; - -import javax.ws.rs.HttpMethod; - -import org.jclouds.chef.config.ChefParserModule; -import org.jclouds.crypto.CryptoStreams; -import org.jclouds.http.HttpRequest; -import org.jclouds.json.config.GsonModule; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableSet; -import com.google.inject.Guice; -import com.google.inject.Injector; - -/** - * @author Adrian Cole - */ -@Test(groups = "unit", testName = "chef.BootstrapChefClientTest") -public class BindHexEncodedMD5sToJsonPayloadTest { - - Injector injector = Guice.createInjector(new ChefParserModule(), new GsonModule()); - BindChecksumsToJsonPayload binder = injector.getInstance(BindChecksumsToJsonPayload.class); - - @Test(expectedExceptions = IllegalArgumentException.class) - public void testMustBeIterable() { - HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost")); - binder.bindToRequest(request, new File("foo")); - } - - @Test(enabled = false) - public void testCorrect() { - HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost")); - binder.bindToRequest(request, ImmutableSet.of(CryptoStreams.hex("abddef"), CryptoStreams.hex("1234"))); - assertEquals(request.getPayload().getRawContent(), "{\"checksums\":{\"abddef\":null,\"1234\":null}}"); - } - - @Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class }) - public void testNullIsBad() { - HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost")); - binder.bindToRequest(request, null); - } - -} diff --git a/chef/core/src/test/java/org/jclouds/chef/filters/SignedHeaderAuthTest.java b/chef/core/src/test/java/org/jclouds/chef/filters/SignedHeaderAuthTest.java deleted file mode 100644 index 9f5fb6c8d5..0000000000 --- a/chef/core/src/test/java/org/jclouds/chef/filters/SignedHeaderAuthTest.java +++ /dev/null @@ -1,201 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.filters; - -import static org.testng.Assert.assertEquals; - -import java.io.IOException; -import java.net.URI; -import java.security.PrivateKey; -import java.util.Properties; - -import javax.inject.Provider; -import javax.ws.rs.HttpMethod; -import javax.ws.rs.core.HttpHeaders; - -import org.jclouds.crypto.Crypto; -import org.jclouds.http.HttpRequest; -import org.jclouds.http.HttpUtils; -import org.jclouds.http.internal.SignatureWire; -import org.jclouds.logging.config.NullLoggingModule; -import org.jclouds.rest.RestContextFactory; -import org.jclouds.rest.BaseRestClientTest.MockModule; -import org.jclouds.util.Utils; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import com.google.common.base.Joiner; -import com.google.common.base.Throwables; -import com.google.common.collect.ImmutableMultimap; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.LinkedHashMultimap; -import com.google.common.collect.Multimap; -import com.google.inject.Injector; -import com.google.inject.Module; - -/** - * - * @author Adrian Cole - */ -@Test(groups = "unit", testName = "chef.SignedHeaderAuthTest") -public class SignedHeaderAuthTest { - - public static final String USER_ID = "spec-user"; - public static final String BODY = "Spec Body"; - // Base64.encode64(Digest::SHA1.digest("Spec Body")).chomp - public static final String HASHED_BODY = "DFteJZPVv6WKdQmMqZUQUumUyRs="; - public static final String TIMESTAMP_ISO8601 = "2009-01-01T12:00:00Z"; - - public static final String PATH = "/organizations/clownco"; - // Base64.encode64(Digest::SHA1.digest("/organizations/clownco")).chomp - - public static final String HASHED_CANONICAL_PATH = "YtBWDn1blGGuFIuKksdwXzHU9oE="; - public static final String REQUESTING_ACTOR_ID = "c0f8a68c52bffa1020222a56b23cccfa"; - - // Content hash is ???TODO - public static final String X_OPS_CONTENT_HASH = "DFteJZPVv6WKdQmMqZUQUumUyRs="; - - public static final String[] X_OPS_AUTHORIZATION_LINES = new String[] { - "jVHrNniWzpbez/eGWjFnO6lINRIuKOg40ZTIQudcFe47Z9e/HvrszfVXlKG4", - "NMzYZgyooSvU85qkIUmKuCqgG2AIlvYa2Q/2ctrMhoaHhLOCWWoqYNMaEqPc", - "3tKHE+CfvP+WuPdWk4jv4wpIkAz6ZLxToxcGhXmZbXpk56YTmqgBW2cbbw4O", - "IWPZDHSiPcw//AYNgW1CCDptt+UFuaFYbtqZegcBd2n/jzcWODA7zL4KWEUy", - "9q4rlh/+1tBReg60QdsmDRsw/cdO1GZrKtuCwbuD4+nbRdVBKv72rqHX9cu0", "utju9jzczCyB+sSAQWrxSsXB/b8vV2qs0l4VD2ML+w==" }; - - // We expect Mixlib::Authentication::SignedHeaderAuth//sign to return this - // if passed the BODY above. - public static final Multimap EXPECTED_SIGN_RESULT = ImmutableMultimap. builder() - .put("X-Ops-Content-Hash", X_OPS_CONTENT_HASH).put("X-Ops-Userid", USER_ID).put("X-Ops-Sign", "version=1.0") - .put("X-Ops-Authorization-1", X_OPS_AUTHORIZATION_LINES[0]).put("X-Ops-Authorization-2", - X_OPS_AUTHORIZATION_LINES[1]).put("X-Ops-Authorization-3", X_OPS_AUTHORIZATION_LINES[2]).put( - "X-Ops-Authorization-4", X_OPS_AUTHORIZATION_LINES[3]).put("X-Ops-Authorization-5", - X_OPS_AUTHORIZATION_LINES[4]).put("X-Ops-Authorization-6", X_OPS_AUTHORIZATION_LINES[5]).put( - "X-Ops-Timestamp", TIMESTAMP_ISO8601).build(); - - // Content hash for empty string - public static final String X_OPS_CONTENT_HASH_EMPTY = "2jmj7l5rSw0yVb/vlWAYkK/YBwk="; - public static final Multimap EXPECTED_SIGN_RESULT_EMPTY = ImmutableMultimap - . builder().put("X-Ops-Content-Hash", X_OPS_CONTENT_HASH_EMPTY).put("X-Ops-Userid", USER_ID) - .put("X-Ops-Sign", "version=1.0").put("X-Ops-Authorization-1", - "N6U75kopDK64cEFqrB6vw+PnubnXr0w5LQeXnIGNGLRP2LvifwIeisk7QxEx").put("X-Ops-Authorization-2", - "mtpQOWAw8HvnWErjzuk9AvUsqVmWpv14ficvkaD79qsPMvbje+aLcIrCGT1P").put("X-Ops-Authorization-3", - "3d2uvf4w7iqwzrIscPnkxLR6o6pymR90gvJXDPzV7Le0jbfD8kmZ8AAK0sGG").put("X-Ops-Authorization-4", - "09F1ftW80bLatJTA66Cw2wBz261r6x/abZhIKFJFDWLzyQGJ8ZNOkUrDDtgI").put("X-Ops-Authorization-5", - "svLVXpOJKZZfKunsElpWjjsyNt3k8vpI1Y4ANO8Eg2bmeCPeEK+YriGm5fbC").put("X-Ops-Authorization-6", - "DzWNPylHJqMeGKVYwGQKpg62QDfe5yXh3wZLiQcXow==").put("X-Ops-Timestamp", TIMESTAMP_ISO8601).build(); - - public static String PUBLIC_KEY; - public static String PRIVATE_KEY; - - static { - try { - PUBLIC_KEY = Utils.toStringAndClose(SignedHeaderAuthTest.class.getResourceAsStream("/pubkey.txt")); - - PRIVATE_KEY = Utils.toStringAndClose(SignedHeaderAuthTest.class.getResourceAsStream("/privkey.txt")); - } catch (IOException e) { - Throwables.propagate(e); - } - } - - @Test - void canonicalizedPathRemovesMultipleSlashes() { - assertEquals(signing_obj.canonicalPath("///"), "/"); - } - - @Test - void canonicalizedPathRemovesTrailingSlash() { - assertEquals(signing_obj.canonicalPath("/path/"), "/path"); - } - - @Test - void shouldGenerateTheCorrectStringToSignAndSignature() { - - URI host = URI.create("http://localhost/" + PATH); - HttpRequest request = new HttpRequest(HttpMethod.POST, host); - request.setPayload(BODY); - - String expected_string_to_sign = new StringBuilder().append("Method:POST").append("\n").append("Hashed Path:") - .append(HASHED_CANONICAL_PATH).append("\n").append("X-Ops-Content-Hash:").append(HASHED_BODY).append("\n") - .append("X-Ops-Timestamp:").append(TIMESTAMP_ISO8601).append("\n").append("X-Ops-UserId:").append(USER_ID) - .toString(); - - assertEquals(signing_obj.createStringToSign("POST", HASHED_CANONICAL_PATH, HASHED_BODY, TIMESTAMP_ISO8601), - expected_string_to_sign); - assertEquals(signing_obj.sign(expected_string_to_sign), Joiner.on("").join(X_OPS_AUTHORIZATION_LINES)); - - signing_obj.filter(request); - Multimap headersWithoutContentLength = LinkedHashMultimap.create(request.getHeaders()); - headersWithoutContentLength.removeAll(HttpHeaders.CONTENT_LENGTH); - assertEquals(headersWithoutContentLength.values(), EXPECTED_SIGN_RESULT.values()); - } - - @Test - void shouldGenerateTheCorrectStringToSignAndSignatureWithNoBody() { - - URI host = URI.create("http://localhost/" + PATH); - HttpRequest request = new HttpRequest(HttpMethod.DELETE, host); - - signing_obj.filter(request); - Multimap headersWithoutContentLength = LinkedHashMultimap.create(request.getHeaders()); - assertEquals(headersWithoutContentLength.entries(), EXPECTED_SIGN_RESULT_EMPTY.entries()); - } - - @Test - void shouldNotChokeWhenSigningARequestForAResourceWithALongName() { - StringBuilder path = new StringBuilder("nodes/"); - for (int i = 0; i < 100; i++) - path.append('A'); - URI host = URI.create("http://localhost/" + path.toString()); - HttpRequest request = new HttpRequest(HttpMethod.PUT, host); - request.setPayload(BODY); - signing_obj.filter(request); - } - - private SignedHeaderAuth signing_obj; - private Crypto crypto; - - /** - * before class, as we need to ensure that the filter is threadsafe. - * - * @throws IOException - * - */ - @BeforeClass - protected void createFilter() throws IOException { - - Injector injector = new RestContextFactory().createContextBuilder("chef", USER_ID, PRIVATE_KEY, - ImmutableSet. of(new MockModule(), new NullLoggingModule()), new Properties()).buildInjector(); - - crypto = injector.getInstance(Crypto.class); - HttpUtils utils = injector.getInstance(HttpUtils.class); - - PrivateKey privateKey = injector.getInstance(PrivateKey.class); - - signing_obj = new SignedHeaderAuth(new SignatureWire(), USER_ID, privateKey, new Provider() { - - @Override - public String get() { - return TIMESTAMP_ISO8601; - } - - }, crypto, utils); - } - -} \ No newline at end of file diff --git a/chef/core/src/test/java/org/jclouds/chef/functions/ClientForTagTest.java b/chef/core/src/test/java/org/jclouds/chef/functions/ClientForTagTest.java deleted file mode 100644 index 8157ecc612..0000000000 --- a/chef/core/src/test/java/org/jclouds/chef/functions/ClientForTagTest.java +++ /dev/null @@ -1,112 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.functions; - -import static org.easymock.EasyMock.expect; -import static org.easymock.classextension.EasyMock.createMock; -import static org.easymock.classextension.EasyMock.replay; -import static org.easymock.classextension.EasyMock.verify; -import static org.testng.Assert.assertEquals; - -import java.io.IOException; -import java.security.PrivateKey; - -import org.jclouds.chef.ChefClient; -import org.jclouds.chef.domain.Client; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableSet; - -/** - * @author Adrian Cole - */ -@Test(groups = "unit", testName = "chef.ClientForTagTest") -public class ClientForTagTest { - - public void testWhenNoClientsInList() throws IOException { - ChefClient chefClient = createMock(ChefClient.class); - Client client = createMock(Client.class); - PrivateKey privateKey = createMock(PrivateKey.class); - - ClientForTag fn = new ClientForTag(chefClient); - - expect(chefClient.listClients()).andReturn(ImmutableSet. of()); - expect(chefClient.createClient("foo-validator-00")).andReturn(client); - expect(client.getPrivateKey()).andReturn(privateKey); - - replay(client); - replay(chefClient); - - Client compare = fn.apply("foo"); - assertEquals(compare.getClientname(), "foo-validator-00"); - assertEquals(compare.getName(), "foo-validator-00"); - assertEquals(compare.getPrivateKey(), privateKey); - - verify(client); - verify(chefClient); - } - - public void testWhenClientsInListAddsToEnd() throws IOException { - ChefClient chefClient = createMock(ChefClient.class); - Client client = createMock(Client.class); - PrivateKey privateKey = createMock(PrivateKey.class); - - ClientForTag fn = new ClientForTag(chefClient); - - expect(chefClient.listClients()).andReturn( - ImmutableSet. of("foo-validator-00", "foo-validator-01", "foo-validator-02")); - expect(chefClient.createClient("foo-validator-03")).andReturn(client); - expect(client.getPrivateKey()).andReturn(privateKey); - - replay(client); - replay(chefClient); - - Client compare = fn.apply("foo"); - assertEquals(compare.getClientname(), "foo-validator-03"); - assertEquals(compare.getName(), "foo-validator-03"); - assertEquals(compare.getPrivateKey(), privateKey); - - verify(client); - verify(chefClient); - } - - public void testWhenClientsInListReplacesMissing() throws IOException { - ChefClient chefClient = createMock(ChefClient.class); - Client client = createMock(Client.class); - PrivateKey privateKey = createMock(PrivateKey.class); - - ClientForTag fn = new ClientForTag(chefClient); - - expect(chefClient.listClients()).andReturn(ImmutableSet. of("foo-validator-00", "foo-validator-02")); - expect(chefClient.createClient("foo-validator-01")).andReturn(client); - expect(client.getPrivateKey()).andReturn(privateKey); - - replay(client); - replay(chefClient); - - Client compare = fn.apply("foo"); - assertEquals(compare.getClientname(), "foo-validator-01"); - assertEquals(compare.getName(), "foo-validator-01"); - assertEquals(compare.getPrivateKey(), privateKey); - - verify(client); - verify(chefClient); - } -} diff --git a/chef/core/src/test/java/org/jclouds/chef/functions/ParseClientFromJsonTest.java b/chef/core/src/test/java/org/jclouds/chef/functions/ParseClientFromJsonTest.java deleted file mode 100644 index bd210a809c..0000000000 --- a/chef/core/src/test/java/org/jclouds/chef/functions/ParseClientFromJsonTest.java +++ /dev/null @@ -1,89 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.functions; - -import static org.jclouds.io.Payloads.newInputStreamPayload; -import static org.testng.Assert.assertEquals; - -import java.io.IOException; -import java.security.PrivateKey; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.security.spec.InvalidKeySpecException; - -import org.jclouds.chef.config.ChefParserModule; -import org.jclouds.chef.domain.Client; -import org.jclouds.crypto.Crypto; -import org.jclouds.crypto.Pems; -import org.jclouds.http.HttpResponse; -import org.jclouds.http.functions.ParseJson; -import org.jclouds.io.Payloads; -import org.jclouds.io.payloads.RSADecryptingPayload; -import org.jclouds.io.payloads.RSAEncryptingPayload; -import org.jclouds.json.config.GsonModule; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.Test; - -import com.google.common.io.ByteStreams; -import com.google.inject.Guice; -import com.google.inject.Injector; -import com.google.inject.Key; -import com.google.inject.TypeLiteral; - -/** - * Tests behavior of {@code ParseClientFromJson} - * - * @author Adrian Cole - */ -@Test(groups = "unit", sequential = true, testName = "chef.ParseClientFromJsonTest") -public class ParseClientFromJsonTest { - - private static final String PRIVATE_KEY = "-----BEGIN RSA PRIVATE KEY-----\nMIIEpQIBAAKCAQEAyb2ZJJqGm0KKR+8nfQJNsSd+F9tXNMV7CfOcW6jsqs8EZgiV\nR09hD1IYOj4YqM0qJONlgyg4xRWewdSG7QTPj1lJpVAida9sXy2+kzyagZA1Am0O\nZcbqb5hoeIDgcX+eDa79s0u0DomjcfO9EKhvHLBz+zM+3QqPRkPV8nYTbfs+HjVz\nzOU6D1B0XR3+IPZZl2AnWs2d0qhnStHcDUvnRVQ0P482YwN9VgceOZtpPz0DCKEJ\n5Tx5STub8k0/zt/VAMHQafLSuQMLd2s4ZLuOZptN//uAsTmxireqd37z+8ZTdBbJ\n8LEpJ+iCXuSfm5aUh7iw6oxvToY2AL53+jK2UQIDAQABAoIBAQDA88B3i/xWn0vX\nBVxFamCYoecuNjGwXXkSyZew616A+EOCu47bh4aTurdFbYL0YFaAtaWvzlaN2eHg\nDb+HDuTefE29+WkcGk6SshPmiz5T0XOCAICWw6wSVDkHmGwS4jZvbAFm7W8nwGk9\nYhxgxFiRngswJZFopOLoF5WXs2td8guIYNslMpo7tu50iFnBHwKO2ZsPAk8t9nnS\nxlDavKruymEmqHCr3+dtio5eaenJcp3fjoXBQOKUk3ipII29XRB8NqeCVV/7Kxwq\nckqOBEbRwBclckyIbD+RiAgKvOelORjEiE9R42vuqvxRA6k9kd9o7utlX0AUtpEn\n3gZc6LepAoGBAP9ael5Y75+sK2JJUNOOhO8ae45cdsilp2yI0X+UBaSuQs2+dyPp\nkpEHAxd4pmmSvn/8c9TlEZhr+qYbABXVPlDncxpIuw2Ajbk7s/S4XaSKsRqpXL57\nzj/QOqLkRk8+OVV9q6lMeQNqLtEj1u6JPviX70Ro+FQtRttNOYbfdP/fAoGBAMpA\nXjR5woV5sUb+REg9vEuYo8RSyOarxqKFCIXVUNsLOx+22+AK4+CQpbueWN7jotrl\nYD6uT6svWi3AAC7kiY0UI/fjVPRCUi8tVoQUE0TaU5VLITaYOB+W/bBaDE4M9560\n1NuDWO90baA5dfU44iuzva02rGJXK9+nS3o8nk/PAoGBALOL6djnDe4mwAaG6Jco\ncd4xr8jkyPzCRZuyBCSBbwphIUXLc7hDprPky064ncJD1UDmwIdkXd/fpMkg2QmA\n/CUk6LEFjMisqHojOaCL9gQZJPhLN5QUN2x1PJWGjs1vQh8Tkx0iUUCOa8bQPXNR\n+34OTsW6TUna4CSZAycLfhffAoGBAIggVsefBCvuQkF0NeUhmDCRZfhnd8y55RHR\n1HCvqKIlpv+rhcX/zmyBLuteopYyRJRsOiE2FW00i8+rIPRu4Z3Q5nybx7w3PzV9\noHN5R5baE9OyI4KpZWztpYYitZF67NcnAvVULHHOvVJQGnKYfLHJYmrJF7GA1ojM\nAuMdFbjFAoGAPxUhxwFy8gaqBahKUEZn4F81HFP5ihGhkT4QL6AFPO2e+JhIGjuR\n27+85hcFqQ+HHVtFsm81b/a+R7P4UuCRgc8eCjxQMoJ1Xl4n7VbjPbHMnIN0Ryvd\nO4ZpWDWYnCO021JTOUUOJ4J/y0416Bvkw0z59y7sNX7wDBBHHbK/XCc=\n-----END RSA PRIVATE KEY-----\n"; - private static final String CERTIFICATE = "-----BEGIN CERTIFICATE-----\nMIIClzCCAgCgAwIBAgIBATANBgkqhkiG9w0BAQUFADCBnjELMAkGA1UEBhMCVVMx\nEzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxFjAUBgNVBAoM\nDU9wc2NvZGUsIEluYy4xHDAaBgNVBAsME0NlcnRpZmljYXRlIFNlcnZpY2UxMjAw\nBgNVBAMMKW9wc2NvZGUuY29tL2VtYWlsQWRkcmVzcz1hdXRoQG9wc2NvZGUuY29t\nMB4XDTEwMDczMDIwNDEzMFoXDTIwMDcyNzIwNDEzMFowADCCASIwDQYJKoZIhvcN\nAQEBBQADggEPADCCAQoCggEBAMm9mSSahptCikfvJ30CTbEnfhfbVzTFewnznFuo\n7KrPBGYIlUdPYQ9SGDo+GKjNKiTjZYMoOMUVnsHUhu0Ez49ZSaVQInWvbF8tvpM8\nmoGQNQJtDmXG6m+YaHiA4HF/ng2u/bNLtA6Jo3HzvRCobxywc/szPt0Kj0ZD1fJ2\nE237Ph41c8zlOg9QdF0d/iD2WZdgJ1rNndKoZ0rR3A1L50VUND+PNmMDfVYHHjmb\naT89AwihCeU8eUk7m/JNP87f1QDB0Gny0rkDC3drOGS7jmabTf/7gLE5sYq3qnd+\n8/vGU3QWyfCxKSfogl7kn5uWlIe4sOqMb06GNgC+d/oytlECAwEAATANBgkqhkiG\n9w0BAQUFAAOBgQBftzSZxstWw60GqRTDNN/F2GnrdtnKBoXzHww3r6jtGEylYq20\n5KfKpEx+sPX0gyZuYJiXC2CkEjImAluWKcdN9ZF6VD541sheAjbiaU7q7ZsztTxF\nWUH2tCvHeDXYKPKek3QzL7bYpUhLnCN/XxEv6ibeMDwtI7f5qpk2Aspzcw==\n-----END CERTIFICATE-----\n"; - private ParseJson handler; - private Crypto crypto; - private PrivateKey privateKey; - private X509Certificate certificate; - - @BeforeTest - protected void setUpInjector() throws IOException, CertificateException, InvalidKeySpecException { - Injector injector = Guice.createInjector(new ChefParserModule(), new GsonModule()); - handler = injector.getInstance(Key.get(new TypeLiteral>() { - })); - crypto = injector.getInstance(Crypto.class); - certificate = Pems.x509Certificate(Payloads.newStringPayload(CERTIFICATE), null); - privateKey = crypto.rsaKeyFactory().generatePrivate(Pems.privateKeySpec(Payloads.newStringPayload(PRIVATE_KEY))); - } - - public void test() throws IOException { - - Client user = new Client(certificate, "jclouds", "adriancole-jcloudstest", "adriancole-jcloudstest", false, - privateKey); - - byte[] encrypted = ByteStreams.toByteArray(new RSAEncryptingPayload(Payloads.newPayload("fooya"), user - .getCertificate().getPublicKey())); - - assertEquals(ByteStreams.toByteArray(new RSADecryptingPayload(Payloads.newPayload(encrypted), user - .getPrivateKey())), "fooya".getBytes()); - - assertEquals(handler.apply(new HttpResponse(200, "ok", newInputStreamPayload(ParseClientFromJsonTest.class - .getResourceAsStream("/client.json")))), user); - } -} diff --git a/chef/core/src/test/java/org/jclouds/chef/functions/ParseCookbookVersionFromJsonTest.java b/chef/core/src/test/java/org/jclouds/chef/functions/ParseCookbookVersionFromJsonTest.java deleted file mode 100644 index 4a2be9e550..0000000000 --- a/chef/core/src/test/java/org/jclouds/chef/functions/ParseCookbookVersionFromJsonTest.java +++ /dev/null @@ -1,138 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.functions; - -import static org.testng.Assert.assertEquals; - -import java.io.IOException; -import java.net.URI; -import java.util.Set; - -import org.jclouds.chef.config.ChefParserModule; -import org.jclouds.chef.domain.Attribute; -import org.jclouds.chef.domain.CookbookVersion; -import org.jclouds.chef.domain.Metadata; -import org.jclouds.chef.domain.Resource; -import org.jclouds.crypto.CryptoStreams; -import org.jclouds.http.HttpResponse; -import org.jclouds.http.functions.ParseJson; -import org.jclouds.io.Payloads; -import org.jclouds.json.Json; -import org.jclouds.json.config.GsonModule; -import org.jclouds.util.Utils; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; -import com.google.inject.Guice; -import com.google.inject.Injector; -import com.google.inject.Key; -import com.google.inject.TypeLiteral; - -/** - * Tests behavior of {@code ParseCookbookVersionFromJson} - * - * @author Adrian Cole - */ -@Test(groups = "unit", sequential = true, testName = "chef.ParseCookbookVersionFromJsonTest") -public class ParseCookbookVersionFromJsonTest { - - private ParseJson handler; - private Injector injector; - private Json json; - - @BeforeTest - protected void setUpInjector() throws IOException { - injector = Guice.createInjector(new ChefParserModule(), new GsonModule()); - json = injector.getInstance(Json.class); - handler = injector.getInstance(Key.get(new TypeLiteral>() { - })); - } - - @Test(enabled = false) - public void testBrew() throws IOException { - CookbookVersion cookbook = handler.apply(new HttpResponse(200, "ok", Payloads - .newPayload(ParseCookbookVersionFromJsonTest.class.getResourceAsStream("/brew-cookbook.json")))); - - assertEquals(cookbook, handler.apply(new HttpResponse(200, "ok", Payloads.newPayload(Utils.toInputStream(json - .toJson(cookbook)))))); - } - - @Test(enabled = false) - public void testTomcat() { - CookbookVersion cookbook = handler.apply(new HttpResponse(200, "ok", Payloads - .newPayload(ParseCookbookVersionFromJsonTest.class.getResourceAsStream("/tomcat-cookbook.json")))); - - assertEquals(cookbook, handler.apply(new HttpResponse(200, "ok", Payloads.newPayload(Utils.toInputStream(json - .toJson(cookbook)))))); - } - - @Test(enabled = false) - public void testMysql() throws IOException { - CookbookVersion cookbook = handler.apply(new HttpResponse(200, "ok", Payloads - .newPayload(ParseCookbookVersionFromJsonTest.class.getResourceAsStream("/mysql-cookbook.json")))); - - assertEquals(cookbook, handler.apply(new HttpResponse(200, "ok", Payloads.newPayload(Utils.toInputStream(json - .toJson(cookbook)))))); - } - - @Test(enabled = false) - public void testApache() { - - assertEquals( - handler.apply(new HttpResponse(200, "ok", Payloads.newPayload(ParseCookbookVersionFromJsonTest.class - .getResourceAsStream("/apache-chef-demo-cookbook.json")))), - new CookbookVersion( - "apache-chef-demo-0.0.0", - ImmutableSet. of(), - ImmutableSet. of(), - ImmutableSet. of(), - new Metadata("Apache v2.0", "Your Name", ImmutableMap. of(), ImmutableMap - .> of(), "youremail@example.com", ImmutableMap - .> of(), "A fabulous new cookbook", ImmutableMap - .> of(), ImmutableMap.> of(), "0.0.0", - ImmutableMap. of(), ImmutableMap.> of(), - "apache-chef-demo", ImmutableMap. of(), "", ImmutableMap - . of(), ImmutableMap. of()), - ImmutableSet. of(), - "apache-chef-demo", - ImmutableSet. of(), - ImmutableSet. of(), - ImmutableSet. of(), - "0.0.0", - ImmutableSet. of(), - ImmutableSet - . of( - new Resource( - "README", - URI - .create("https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-11637f98942eafbf49c71b7f2f048b78?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277766181&Signature=zgpNl6wSxjTNovqZu2nJq0JztU8%3D"), - CryptoStreams.hex("11637f98942eafbf49c71b7f2f048b78"), "README", - "default"), - new Resource( - "Rakefile", - URI - .create("https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-ebcf925a1651b4e04b9cd8aac2bc54eb?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277766181&Signature=EFzzDSKKytTl7b%2FxrCeNLh05zj4%3D"), - CryptoStreams.hex("ebcf925a1651b4e04b9cd8aac2bc54eb"), "Rakefile", - "default")))); - - } -} diff --git a/chef/core/src/test/java/org/jclouds/chef/functions/ParseDataBagItemFromJsonTest.java b/chef/core/src/test/java/org/jclouds/chef/functions/ParseDataBagItemFromJsonTest.java deleted file mode 100644 index 1cc6437c0f..0000000000 --- a/chef/core/src/test/java/org/jclouds/chef/functions/ParseDataBagItemFromJsonTest.java +++ /dev/null @@ -1,63 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.functions; - -import static org.testng.Assert.assertEquals; - -import java.io.IOException; - -import org.jclouds.chef.config.ChefParserModule; -import org.jclouds.chef.domain.DatabagItem; -import org.jclouds.http.HttpResponse; -import org.jclouds.http.functions.ParseJson; -import org.jclouds.io.Payloads; -import org.jclouds.json.Json; -import org.jclouds.json.config.GsonModule; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.Test; - -import com.google.inject.Guice; -import com.google.inject.Injector; -import com.google.inject.Key; -import com.google.inject.TypeLiteral; - -/** - * @author AdrianCole - */ -@Test(groups = "unit", testName = "chef.ParseDataBagItemFromJsonTest") -public class ParseDataBagItemFromJsonTest { - private ParseJson handler; - private Json mapper; - - @BeforeTest - protected void setUpInjector() throws IOException { - Injector injector = Guice.createInjector(new ChefParserModule(), new GsonModule()); - handler = injector.getInstance(Key.get(new TypeLiteral>() { - })); - mapper = injector.getInstance(Json.class); - } - - public void test1() { - String json = "{\"my_key\":\"my_data\",\"id\":\"item1\"}"; - DatabagItem item = new DatabagItem("item1", json); - assertEquals(handler.apply(new HttpResponse(200, "ok", Payloads.newStringPayload(json))), item); - assertEquals(mapper.toJson(item), json); - } -} diff --git a/chef/core/src/test/java/org/jclouds/chef/functions/ParseErrorFromJsonOrReturnBodyTest.java b/chef/core/src/test/java/org/jclouds/chef/functions/ParseErrorFromJsonOrReturnBodyTest.java deleted file mode 100644 index 690675a84f..0000000000 --- a/chef/core/src/test/java/org/jclouds/chef/functions/ParseErrorFromJsonOrReturnBodyTest.java +++ /dev/null @@ -1,50 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.functions; - -import static org.testng.Assert.assertEquals; - -import java.io.InputStream; -import java.net.UnknownHostException; - -import org.jclouds.http.HttpResponse; -import org.jclouds.http.functions.ReturnStringIf2xx; -import org.jclouds.io.Payloads; -import org.jclouds.util.Utils; -import org.testng.annotations.Test; - -/** - * @author Adrian Cole - */ -@Test(groups = "unit", testName = "chef.ParseErrorFromJsonOrReturnBodyTest") -public class ParseErrorFromJsonOrReturnBodyTest { - - @Test - public void testApplyInputStreamDetails() throws UnknownHostException { - InputStream is = Utils - .toInputStream("{\"error\":[\"invalid tarball: tarball root must contain java-bytearray\"]}"); - - ParseErrorFromJsonOrReturnBody parser = new ParseErrorFromJsonOrReturnBody( - new ReturnStringIf2xx()); - String response = parser.apply(new HttpResponse(200, "ok", Payloads.newPayload(is))); - assertEquals(response, "invalid tarball: tarball root must contain java-bytearray"); - } - -} diff --git a/chef/core/src/test/java/org/jclouds/chef/functions/ParseKeySetFromJsonTest.java b/chef/core/src/test/java/org/jclouds/chef/functions/ParseKeySetFromJsonTest.java deleted file mode 100644 index 0468e95575..0000000000 --- a/chef/core/src/test/java/org/jclouds/chef/functions/ParseKeySetFromJsonTest.java +++ /dev/null @@ -1,63 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.functions; - -import static org.testng.Assert.assertEquals; - -import java.io.IOException; - -import org.jclouds.chef.config.ChefParserModule; -import org.jclouds.http.HttpResponse; -import org.jclouds.io.Payloads; -import org.jclouds.json.config.GsonModule; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableSet; -import com.google.inject.Guice; -import com.google.inject.Injector; - -/** - * Tests behavior of {@code ParseKeySetFromJson} - * - * @author Adrian Cole - */ -@Test(groups = "unit", sequential = true, testName = "chef.ParseKeySetFromJsonTest") -public class ParseKeySetFromJsonTest { - - private ParseKeySetFromJson handler; - - @BeforeTest - protected void setUpInjector() throws IOException { - Injector injector = Guice.createInjector(new ChefParserModule(), new GsonModule()); - handler = injector.getInstance(ParseKeySetFromJson.class); - } - - public void testRegex() { - assertEquals( - handler - .apply(new HttpResponse( - 200, - "ok", - Payloads - .newStringPayload("{\n\"opscode-validator\": \"https://api.opscode.com/...\", \"pimp-validator\": \"https://api.opscode.com/...\"}"))), - ImmutableSet.of("opscode-validator", "pimp-validator")); - } -} diff --git a/chef/core/src/test/java/org/jclouds/chef/functions/ParseNodeFromJsonTest.java b/chef/core/src/test/java/org/jclouds/chef/functions/ParseNodeFromJsonTest.java deleted file mode 100644 index 74dac62de3..0000000000 --- a/chef/core/src/test/java/org/jclouds/chef/functions/ParseNodeFromJsonTest.java +++ /dev/null @@ -1,69 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.functions; - -import static org.testng.Assert.assertEquals; - -import java.io.IOException; -import java.util.Collections; - -import org.jclouds.chef.config.ChefParserModule; -import org.jclouds.chef.domain.Node; -import org.jclouds.domain.JsonBall; -import org.jclouds.http.HttpResponse; -import org.jclouds.http.functions.ParseJson; -import org.jclouds.io.Payloads; -import org.jclouds.json.config.GsonModule; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableMap; -import com.google.inject.Guice; -import com.google.inject.Injector; -import com.google.inject.Key; -import com.google.inject.TypeLiteral; - -/** - * Tests behavior of {@code ParseNodeFromJson} - * - * @author Adrian Cole - */ -@Test(groups = "unit", sequential = true, testName = "chef.ParseNodeFromJsonTest") -public class ParseNodeFromJsonTest { - - private ParseJson handler; - - @BeforeTest - protected void setUpInjector() throws IOException { - Injector injector = Guice.createInjector(new ChefParserModule(), new GsonModule()); - handler = injector.getInstance(Key.get(new TypeLiteral>() { - })); - } - - public void test() { - - Node node = new Node("adrian-jcloudstest", ImmutableMap. of("tomcat6", new JsonBall( - "{\"ssl_port\":8433}")), ImmutableMap. of(), ImmutableMap. of(), - ImmutableMap. of(), Collections.singleton("recipe[java]")); - - assertEquals(handler.apply(new HttpResponse(200, "ok", Payloads.newPayload(ParseCookbookVersionFromJsonTest.class - .getResourceAsStream("/node.json")))), node); - } -} diff --git a/chef/core/src/test/java/org/jclouds/chef/functions/ParseSandboxFromJsonTest.java b/chef/core/src/test/java/org/jclouds/chef/functions/ParseSandboxFromJsonTest.java deleted file mode 100644 index de0957e9d6..0000000000 --- a/chef/core/src/test/java/org/jclouds/chef/functions/ParseSandboxFromJsonTest.java +++ /dev/null @@ -1,67 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.functions; - -import static org.testng.Assert.assertEquals; - -import java.io.IOException; - -import org.jclouds.chef.config.ChefParserModule; -import org.jclouds.chef.domain.Sandbox; -import org.jclouds.date.DateService; -import org.jclouds.http.HttpResponse; -import org.jclouds.http.functions.ParseJson; -import org.jclouds.io.Payloads; -import org.jclouds.json.config.GsonModule; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableSet; -import com.google.inject.Guice; -import com.google.inject.Injector; -import com.google.inject.Key; -import com.google.inject.TypeLiteral; - -/** - * Tests behavior of {@code ParseSandboxFromJson} - * - * @author Adrian Cole - */ -@Test(groups = "unit", sequential = true, testName = "chef.ParseSandboxFromJsonTest") -public class ParseSandboxFromJsonTest { - - private ParseJson handler; - private DateService dateService; - - @BeforeTest - protected void setUpInjector() throws IOException { - Injector injector = Guice.createInjector(new ChefParserModule(), new GsonModule()); - handler = injector.getInstance(Key.get(new TypeLiteral>() { - })); - dateService = injector.getInstance(DateService.class); - } - - public void test() { - assertEquals(handler.apply(new HttpResponse(200, "ok", Payloads.newPayload(ParseSandboxFromJsonTest.class - .getResourceAsStream("/sandbox.json")))), new Sandbox("1-8c27b0ea4c2b7aaedbb44cfbdfcc11b2", false, - dateService.iso8601SecondsDateParse("2010-07-07T03:36:00+00:00"), ImmutableSet. of(), - "f9d6d9b72bae465890aae87969f98a9c", "f9d6d9b72bae465890aae87969f98a9c")); - } -} diff --git a/chef/core/src/test/java/org/jclouds/chef/functions/ParseUploadSandboxFromJsonTest.java b/chef/core/src/test/java/org/jclouds/chef/functions/ParseUploadSandboxFromJsonTest.java deleted file mode 100644 index 9d5312b10f..0000000000 --- a/chef/core/src/test/java/org/jclouds/chef/functions/ParseUploadSandboxFromJsonTest.java +++ /dev/null @@ -1,82 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.functions; - -import static org.testng.Assert.assertEquals; - -import java.io.IOException; -import java.net.URI; -import java.util.List; - -import org.jclouds.chef.config.ChefParserModule; -import org.jclouds.chef.domain.ChecksumStatus; -import org.jclouds.chef.domain.UploadSandbox; -import org.jclouds.crypto.CryptoStreams; -import org.jclouds.http.HttpResponse; -import org.jclouds.http.functions.ParseJson; -import org.jclouds.io.Payloads; -import org.jclouds.json.config.GsonModule; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableMap; -import com.google.common.primitives.Bytes; -import com.google.inject.Guice; -import com.google.inject.Injector; -import com.google.inject.Key; -import com.google.inject.TypeLiteral; - -/** - * Tests behavior of {@code ParseUploadSiteFromJson} - * - * @author Adrian Cole - */ -@Test(groups = "unit", sequential = true, testName = "chef.ParseUploadSiteFromJsonTest") -public class ParseUploadSandboxFromJsonTest { - - private ParseJson handler; - private Injector injector; - - @BeforeTest - protected void setUpInjector() throws IOException { - injector = Guice.createInjector(new ChefParserModule(), new GsonModule()); - handler = injector.getInstance(Key.get(new TypeLiteral>() { - })); - } - - public void test() { - assertEquals( - handler.apply(new HttpResponse(200, "ok", Payloads.newPayload(ParseUploadSandboxFromJsonTest.class - .getResourceAsStream("/upload-site.json")))), - new UploadSandbox( - URI - .create("https://api.opscode.com/organizations/jclouds/sandboxes/d454f71e2a5f400c808d0c5d04c2c88c"), - ImmutableMap - ., ChecksumStatus> of( - Bytes.asList(CryptoStreams.hex("0c5ecd7788cf4f6c7de2a57193897a6c")), - new ChecksumStatus( - URI - .create("https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/sandbox-d454f71e2a5f400c808d0c5d04c2c88c/checksum-0c5ecd7788cf4f6c7de2a57193897a6c?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277344702&Signature=FtKyqvYEjhhEKmRY%2B0M8aGPMM7g%3D"), - true), Bytes.asList(CryptoStreams - .hex("0189e76ccc476701d6b374e5a1a27347")), new ChecksumStatus(), - Bytes.asList(CryptoStreams.hex("1dda05ed139664f1f89b9dec482b77c0")), - new ChecksumStatus()), "d454f71e2a5f400c808d0c5d04c2c88c")); - } -} diff --git a/chef/core/src/test/java/org/jclouds/chef/functions/RunListForTagTest.java b/chef/core/src/test/java/org/jclouds/chef/functions/RunListForTagTest.java deleted file mode 100644 index b5a5e34ad5..0000000000 --- a/chef/core/src/test/java/org/jclouds/chef/functions/RunListForTagTest.java +++ /dev/null @@ -1,106 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.functions; - -import static org.easymock.EasyMock.expect; -import static org.easymock.classextension.EasyMock.createMock; -import static org.easymock.classextension.EasyMock.replay; -import static org.easymock.classextension.EasyMock.verify; -import static org.testng.Assert.assertEquals; - -import java.io.IOException; - -import org.jclouds.chef.ChefClient; -import org.jclouds.chef.config.ChefParserModule; -import org.jclouds.chef.domain.Client; -import org.jclouds.chef.domain.DatabagItem; -import org.jclouds.json.Json; -import org.jclouds.json.config.GsonModule; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableList; -import com.google.inject.Guice; -import com.google.inject.Injector; - -/** - * @author Adrian Cole - */ -@Test(groups = "unit", testName = "chef.RunListForTagTest") -public class RunListForTagTest { - Injector injector = Guice.createInjector(new ChefParserModule(), new GsonModule()); - Json json = injector.getInstance(Json.class); - - @Test(expectedExceptions = IllegalStateException.class) - public void testWhenNoDatabagItem() throws IOException { - ChefClient chefClient = createMock(ChefClient.class); - Client client = createMock(Client.class); - - RunListForTag fn = new RunListForTag("jclouds", chefClient, json); - - expect(chefClient.getDatabagItem("jclouds", "foo")).andReturn(null); - - replay(client); - replay(chefClient); - - fn.apply("foo"); - - verify(client); - verify(chefClient); - } - - @Test - public void testOneRecipe() throws IOException { - ChefClient chefClient = createMock(ChefClient.class); - Client client = createMock(Client.class); - - RunListForTag fn = new RunListForTag("jclouds", chefClient, json); - - expect(chefClient.getDatabagItem("jclouds", "foo")).andReturn( - new DatabagItem("foo", "{\"run_list\":[\"recipe[apache2]\"]}")); - - replay(client); - replay(chefClient); - - assertEquals(fn.apply("foo"), ImmutableList.of("recipe[apache2]")); - - verify(client); - verify(chefClient); - } - - @Test - public void testTwoRecipes() throws IOException { - ChefClient chefClient = createMock(ChefClient.class); - Client client = createMock(Client.class); - - RunListForTag fn = new RunListForTag("jclouds", chefClient, json); - - expect(chefClient.getDatabagItem("jclouds", "foo")).andReturn( - new DatabagItem("foo", "{\"run_list\":[\"recipe[apache2]\",\"recipe[mysql]\"]}")); - - replay(client); - replay(chefClient); - - assertEquals(fn.apply("foo"), ImmutableList.of("recipe[apache2]", "recipe[mysql]")); - - verify(client); - verify(chefClient); - } - -} diff --git a/chef/core/src/test/java/org/jclouds/chef/functions/TagToBootScriptTest.java b/chef/core/src/test/java/org/jclouds/chef/functions/TagToBootScriptTest.java deleted file mode 100644 index 238943089f..0000000000 --- a/chef/core/src/test/java/org/jclouds/chef/functions/TagToBootScriptTest.java +++ /dev/null @@ -1,104 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.functions; - -import static org.easymock.EasyMock.expect; -import static org.easymock.classextension.EasyMock.createMock; -import static org.easymock.classextension.EasyMock.replay; -import static org.easymock.classextension.EasyMock.verify; -import static org.testng.Assert.assertEquals; - -import java.io.IOException; -import java.net.URI; -import java.security.PrivateKey; -import java.util.List; - -import org.jclouds.chef.config.ChefParserModule; -import org.jclouds.chef.domain.Client; -import org.jclouds.chef.statements.InstallChefGems; -import org.jclouds.crypto.PemsTest; -import org.jclouds.json.Json; -import org.jclouds.json.config.GsonModule; -import org.jclouds.scriptbuilder.domain.Statement; -import org.testng.annotations.Test; - -import com.google.common.base.Charsets; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.io.CharStreams; -import com.google.common.io.Resources; -import com.google.inject.Guice; -import com.google.inject.Injector; - -/** - * @author Adrian Cole - */ -@Test(groups = "unit", testName = "chef.TagToBootScriptTest") -public class TagToBootScriptTest { - - Injector injector = Guice.createInjector(new ChefParserModule(), new GsonModule()); - Json json = injector.getInstance(Json.class); - Statement installChefGems = new InstallChefGems(); - - @Test(expectedExceptions = IllegalStateException.class) - public void testMustHaveClients() { - TagToBootScript fn = new TagToBootScript(URI.create("http://localhost:4000"), json, ImmutableMap - . of(), ImmutableMap.> of("foo", ImmutableList - .of("recipe[apache2]")), installChefGems); - fn.apply("foo"); - } - - @Test(expectedExceptions = IllegalStateException.class) - public void testMustHaveRunScripts() { - TagToBootScript fn = new TagToBootScript(URI.create("http://localhost:4000"), json, ImmutableMap - . of("foo", createMock(Client.class)), ImmutableMap.> of(), installChefGems); - fn.apply("foo"); - } - - @Test(expectedExceptions = IllegalStateException.class) - public void testMustHaveRunScriptsValue() { - TagToBootScript fn = new TagToBootScript(URI.create("http://localhost:4000"), json, ImmutableMap - . of("foo", createMock(Client.class)), ImmutableMap.> of("foo", - ImmutableList. of()), installChefGems); - fn.apply("foo"); - } - - public void testOneRecipe() throws IOException { - Client client = createMock(Client.class); - PrivateKey privateKey = createMock(PrivateKey.class); - - TagToBootScript fn = new TagToBootScript(URI.create("http://localhost:4000"), json, ImmutableMap - . of("foo", client), ImmutableMap.> of("foo", ImmutableList - . of("recipe[apache2]")), installChefGems); - - expect(client.getClientname()).andReturn("fooclient").atLeastOnce(); - expect(client.getPrivateKey()).andReturn(privateKey).atLeastOnce(); - expect(privateKey.getEncoded()).andReturn(PemsTest.PRIVATE_KEY.getBytes()); - - replay(client); - replay(privateKey); - - assertEquals(fn.apply("foo").getRawContent(), CharStreams.toString(Resources.newReaderSupplier(Resources - .getResource("one-recipe.sh"), Charsets.UTF_8))); - - verify(client); - verify(privateKey); - } -} diff --git a/chef/core/src/test/java/org/jclouds/chef/handlers/ChefClientErrorRetryHandlerTest.java b/chef/core/src/test/java/org/jclouds/chef/handlers/ChefClientErrorRetryHandlerTest.java deleted file mode 100644 index 1d448240a5..0000000000 --- a/chef/core/src/test/java/org/jclouds/chef/handlers/ChefClientErrorRetryHandlerTest.java +++ /dev/null @@ -1,120 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.handlers; - -import static org.easymock.EasyMock.expect; -import static org.easymock.classextension.EasyMock.createMock; -import static org.easymock.classextension.EasyMock.replay; -import static org.easymock.classextension.EasyMock.verify; - -import java.net.URI; - -import org.jclouds.http.HttpCommand; -import org.jclouds.http.HttpRequest; -import org.jclouds.http.HttpResponse; -import org.jclouds.http.handlers.BackoffLimitedRetryHandler; -import org.jclouds.io.Payloads; -import org.testng.annotations.Test; - -/** - * Tests behavior of {@code ChefClientErrorRetryHandler} - * - * @author Adrian Cole - */ -@Test(groups = "unit", testName = "chef.ChefClientErrorRetryHandlerTest") -public class ChefClientErrorRetryHandlerTest { - @Test - public void test401DoesNotRetry() { - - HttpCommand command = createMock(HttpCommand.class); - HttpResponse response = createMock(HttpResponse.class); - BackoffLimitedRetryHandler retry = createMock(BackoffLimitedRetryHandler.class); - - expect(command.getFailureCount()).andReturn(0); - expect(response.getStatusCode()).andReturn(401).atLeastOnce(); - - replay(response); - replay(retry); - replay(command); - - ChefClientErrorRetryHandler handler = new ChefClientErrorRetryHandler(retry); - - assert !handler.shouldRetryRequest(command, response); - - verify(retry); - verify(command); - verify(response); - - } - - @Test - public void test400DoesNotRetry() { - - HttpCommand command = createMock(HttpCommand.class); - HttpResponse response = createMock(HttpResponse.class); - BackoffLimitedRetryHandler retry = createMock(BackoffLimitedRetryHandler.class); - - expect(command.getFailureCount()).andReturn(0); - expect(response.getStatusCode()).andReturn(401).atLeastOnce(); - - replay(response); - replay(retry); - replay(command); - - ChefClientErrorRetryHandler handler = new ChefClientErrorRetryHandler(retry); - - assert !handler.shouldRetryRequest(command, response); - - verify(retry); - verify(command); - verify(response); - - } - - @Test - public void testRetryOn400PutSandbox() { - - HttpCommand command = createMock(HttpCommand.class); - BackoffLimitedRetryHandler retry = createMock(BackoffLimitedRetryHandler.class); - - HttpRequest request = new HttpRequest("PUT", URI - .create("https://api.opscode.com/organizations/jclouds/sandboxes/bfd68d4052f44053b2e593a33b5e1cd5")); - HttpResponse response = new HttpResponse( - 400, - "400 Bad Request", - Payloads - .newStringPayload("{\"error\":[\"Cannot update sandbox bfd68d4052f44053b2e593a33b5e1cd5: checksum 9b7c23369f4b576451216c39f214af6c was not uploaded\"]}")); - - expect(command.getFailureCount()).andReturn(0); - expect(command.getRequest()).andReturn(request).atLeastOnce(); - expect(retry.shouldRetryRequest(command, response)).andReturn(true); - - replay(retry); - replay(command); - - ChefClientErrorRetryHandler handler = new ChefClientErrorRetryHandler(retry); - - assert handler.shouldRetryRequest(command, response); - - verify(retry); - verify(command); - - } -} diff --git a/chef/core/src/test/java/org/jclouds/chef/strategy/internal/BaseChefStrategyLiveTest.java b/chef/core/src/test/java/org/jclouds/chef/strategy/internal/BaseChefStrategyLiveTest.java deleted file mode 100644 index b6260c2cb0..0000000000 --- a/chef/core/src/test/java/org/jclouds/chef/strategy/internal/BaseChefStrategyLiveTest.java +++ /dev/null @@ -1,81 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.strategy.internal; - -import static com.google.common.base.Preconditions.checkNotNull; - -import java.io.File; -import java.io.IOException; -import java.util.Properties; -import java.util.Set; - -import org.jclouds.chef.ChefAsyncClient; -import org.jclouds.chef.ChefClient; -import org.jclouds.lifecycle.Closer; -import org.jclouds.logging.log4j.config.Log4JLoggingModule; -import org.jclouds.rest.RestContextFactory; -import org.testng.annotations.AfterTest; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.Test; - -import com.google.common.base.Charsets; -import com.google.common.collect.Sets; -import com.google.common.io.Files; -import com.google.inject.Injector; -import com.google.inject.Module; - -/** - * Tests behavior of {@code ChefService} strategies - * - * @author Adrian Cole - */ -@Test(groups = "live", testName = "chef.BaseChefStrategyLiveTest") -public abstract class BaseChefStrategyLiveTest { - - protected Injector injector; - - protected String prefix = System.getProperty("user.name") + getClass().getSimpleName(); - - @BeforeTest(groups = { "live" }) - public void setupClient() throws IOException { - String endpoint = checkNotNull(System.getProperty("jclouds.test.endpoint"), "jclouds.test.endpoint"); - String user = checkNotNull(System.getProperty("jclouds.test.identity"), "jclouds.test.identity"); - String keyfile = System.getProperty("jclouds.test.credential"); - if (keyfile == null || keyfile.equals("")) - keyfile = System.getProperty("user.home") + "/.chef/" + user + ".pem"; - Properties props = new Properties(); - props.setProperty("chef.endpoint", endpoint); - Set modules = Sets.newHashSet(); - modules.add(new Log4JLoggingModule()); - addTestModulesTo(modules); - injector = new RestContextFactory(). createContextBuilder("chef", user, - Files.toString(new File(keyfile), Charsets.UTF_8), modules, props).buildInjector(); - } - - protected void addTestModulesTo(Set modules) { - - } - - @AfterTest(groups = { "live" }) - public void teardownClient() throws IOException { - if (injector != null) - injector.getInstance(Closer.class).close(); - } -} diff --git a/chef/core/src/test/java/org/jclouds/chef/strategy/internal/CleanupStaleNodesAndClientsImplLiveTest.java b/chef/core/src/test/java/org/jclouds/chef/strategy/internal/CleanupStaleNodesAndClientsImplLiveTest.java deleted file mode 100644 index 6b0186d94b..0000000000 --- a/chef/core/src/test/java/org/jclouds/chef/strategy/internal/CleanupStaleNodesAndClientsImplLiveTest.java +++ /dev/null @@ -1,63 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.strategy.internal; - -import org.jclouds.chef.ChefClient; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableSet; - -/** - * Tests behavior of {@code CleanupStaleNodesAndClientsImpl} strategies - * - * @author Adrian Cole - */ -@Test(groups = "live", testName = "chef.CleanupStaleNodesAndClientsImplLiveTest") -public class CleanupStaleNodesAndClientsImplLiveTest extends BaseChefStrategyLiveTest { - private CreateNodeAndPopulateAutomaticAttributesImpl creater; - private CleanupStaleNodesAndClientsImpl strategy; - private ChefClient chef; - - @BeforeTest(groups = "live", dependsOnMethods = "setupClient") - void setupStrategy() { - this.creater = injector.getInstance(CreateNodeAndPopulateAutomaticAttributesImpl.class); - this.strategy = injector.getInstance(CleanupStaleNodesAndClientsImpl.class); - this.chef = injector.getInstance(ChefClient.class); - } - - @Test - public void testExecute() throws InterruptedException { - try { - creater.execute(prefix, ImmutableSet. of()); - // http://tickets.corp.opscode.com/browse/PL-522 - // assert chef.nodeExists(prefix); - assert chef.getNode(prefix) != null; - strategy.execute(prefix, 10); - assert chef.getNode(prefix) != null; - Thread.sleep(1000); - strategy.execute(prefix, 1); - assert chef.getNode(prefix) == null; - } finally { - chef.deleteNode(prefix); - } - } - -} diff --git a/chef/core/src/test/java/org/jclouds/chef/strategy/internal/CreateNodeAndPopulateAutomaticAttributesImplLiveTest.java b/chef/core/src/test/java/org/jclouds/chef/strategy/internal/CreateNodeAndPopulateAutomaticAttributesImplLiveTest.java deleted file mode 100644 index 6e06ba9426..0000000000 --- a/chef/core/src/test/java/org/jclouds/chef/strategy/internal/CreateNodeAndPopulateAutomaticAttributesImplLiveTest.java +++ /dev/null @@ -1,86 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.strategy.internal; - -import static org.testng.Assert.assertEquals; - -import java.util.Map; -import java.util.Set; - -import org.jclouds.chef.ChefClient; -import org.jclouds.chef.domain.Node; -import org.jclouds.domain.JsonBall; -import org.jclouds.ohai.AutomaticSupplier; -import org.jclouds.ohai.config.ConfiguresOhai; -import org.jclouds.ohai.config.OhaiModule; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.Test; - -import com.google.common.base.Supplier; -import com.google.common.base.Suppliers; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; -import com.google.inject.Module; - -/** - * Tests behavior of {@code CreateNodeAndPopulateAutomaticAttributesImpl} - * strategies - * - * @author Adrian Cole - */ -@Test(groups = "live", testName = "chef.CreateNodeAndPopulateAutomaticAttributesImplLiveTest") -public class CreateNodeAndPopulateAutomaticAttributesImplLiveTest extends BaseChefStrategyLiveTest { - - private CreateNodeAndPopulateAutomaticAttributesImpl strategy; - private ChefClient chef; - - @ConfiguresOhai - static class TestOhaiModule extends OhaiModule { - - @Override - protected Supplier> provideAutomatic(AutomaticSupplier in) { - return Suppliers.> ofInstance(ImmutableMap.of("foo", new JsonBall("bar"))); - } - } - - protected void addTestModulesTo(Set modules) { - modules.add(new TestOhaiModule()); - } - - @BeforeTest(groups = "live", dependsOnMethods = "setupClient") - void setupStrategy() { - this.strategy = injector.getInstance(CreateNodeAndPopulateAutomaticAttributesImpl.class); - this.chef = injector.getInstance(ChefClient.class); - } - - @Test - public void testExecute() { - Set runList = ImmutableSet.of("role[" + prefix + "]"); - try { - strategy.execute(prefix, runList); - Node node = chef.getNode(prefix); - assertEquals(node.getName(), prefix); - assertEquals(node.getRunList(), runList); - assertEquals(node.getAutomatic().get("foo").toString(), "\"bar\""); - } finally { - injector.getInstance(ChefClient.class).deleteNode(prefix); - } - } -} diff --git a/chef/core/src/test/java/org/jclouds/chef/strategy/internal/CreateNodeAndPopulateAutomaticAttributesImplTest.java b/chef/core/src/test/java/org/jclouds/chef/strategy/internal/CreateNodeAndPopulateAutomaticAttributesImplTest.java deleted file mode 100644 index 8289b88613..0000000000 --- a/chef/core/src/test/java/org/jclouds/chef/strategy/internal/CreateNodeAndPopulateAutomaticAttributesImplTest.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.strategy.internal; - -import static org.easymock.classextension.EasyMock.createMock; -import static org.easymock.classextension.EasyMock.replay; -import static org.easymock.classextension.EasyMock.verify; - -import java.util.Map; - -import org.jclouds.chef.ChefClient; -import org.jclouds.chef.domain.Node; -import org.jclouds.domain.JsonBall; -import org.testng.annotations.Test; - -import com.google.common.base.Supplier; -import com.google.common.base.Suppliers; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; - -/** - * Tests behavior of {@code CreateNodeAndPopulateAutomaticAttributesImpl} - * - * @author Adrian Cole - */ -@Test(groups = "unit", testName = "ohai.CreateNodeAndPopulateAutomaticAttributesImplTest") -public class CreateNodeAndPopulateAutomaticAttributesImplTest { - - @Test - public void testWithNoRunlist() { - ChefClient chef = createMock(ChefClient.class); - - Map automatic = ImmutableMap. of(); - - Node node = new Node("name", ImmutableSet. of()); - - Supplier> automaticSupplier = Suppliers.> ofInstance(automatic); - - Node nodeWithAutomatic = new Node("name", ImmutableMap. of(), ImmutableMap - . of(), ImmutableMap. of(), automatic, ImmutableSet. of()); - - node.getAutomatic().putAll(automaticSupplier.get()); - chef.createNode(nodeWithAutomatic); - - replay(chef); - - CreateNodeAndPopulateAutomaticAttributesImpl updater = new CreateNodeAndPopulateAutomaticAttributesImpl(chef, automaticSupplier); - - updater.execute("name", ImmutableSet. of()); - verify(chef); - - } -} diff --git a/chef/core/src/test/java/org/jclouds/chef/strategy/internal/DeleteAllClientsAndNodesInListImplLiveTest.java b/chef/core/src/test/java/org/jclouds/chef/strategy/internal/DeleteAllClientsAndNodesInListImplLiveTest.java deleted file mode 100644 index dbf64e0c1f..0000000000 --- a/chef/core/src/test/java/org/jclouds/chef/strategy/internal/DeleteAllClientsAndNodesInListImplLiveTest.java +++ /dev/null @@ -1,65 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.strategy.internal; - -import org.jclouds.chef.ChefClient; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableSet; - -/** - * Tests behavior of {@code DeleteAllClientsAndNodesInListImpl} strategies - * - * @author Adrian Cole - */ -@Test(groups = "live", testName = "chef.DeleteAllClientsAndNodesInListImplTest") -public class DeleteAllClientsAndNodesInListImplLiveTest extends BaseChefStrategyLiveTest { - private DeleteAllNodesInListImpl strategy; - private CreateNodeAndPopulateAutomaticAttributesImpl creater; - private ChefClient chef; - - @BeforeTest(groups = "live", dependsOnMethods = "setupClient") - void setupStrategy() { - this.creater = injector.getInstance(CreateNodeAndPopulateAutomaticAttributesImpl.class); - this.strategy = injector.getInstance(DeleteAllNodesInListImpl.class); - this.chef = injector.getInstance(ChefClient.class); - } - - @Test - public void testExecute() throws InterruptedException { - try { - creater.execute(prefix, ImmutableSet. of()); - creater.execute(prefix + 1, ImmutableSet. of()); - - // http://tickets.corp.opscode.com/browse/PL-522 - // assert chef.nodeExists(prefix); - assert chef.getNode(prefix) != null; - assert chef.getNode(prefix + 1) != null; - - strategy.execute(ImmutableSet.of(prefix, prefix + 1)); - assert chef.getNode(prefix) == null; - assert chef.getNode(prefix + 1) == null; - } finally { - chef.deleteNode(prefix); - chef.deleteNode(prefix + 1); - } - } -} diff --git a/chef/core/src/test/java/org/jclouds/chef/strategy/internal/GetNodesImplLiveTest.java b/chef/core/src/test/java/org/jclouds/chef/strategy/internal/GetNodesImplLiveTest.java deleted file mode 100644 index 22ea900a1f..0000000000 --- a/chef/core/src/test/java/org/jclouds/chef/strategy/internal/GetNodesImplLiveTest.java +++ /dev/null @@ -1,89 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.strategy.internal; - -import static com.google.common.collect.Iterables.size; -import static org.testng.Assert.assertEquals; - -import java.io.IOException; - -import org.jclouds.chef.ChefClient; -import org.testng.annotations.AfterTest; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.Test; - -import com.google.common.base.Predicate; -import com.google.common.collect.ImmutableSet; - -/** - * Tests behavior of {@code GetNodesImpl} strategies - * - * @author Adrian Cole - */ -@Test(groups = "live", testName = "chef.GetNodesImplLiveTest") -public class GetNodesImplLiveTest extends BaseChefStrategyLiveTest { - private ListNodesImpl strategy; - private CreateNodeAndPopulateAutomaticAttributesImpl creater; - private ChefClient chef; - - @BeforeTest(groups = "live", dependsOnMethods = "setupClient") - void setupStrategy() { - this.creater = injector.getInstance(CreateNodeAndPopulateAutomaticAttributesImpl.class); - this.strategy = injector.getInstance(ListNodesImpl.class); - this.chef = injector.getInstance(ChefClient.class); - } - - @BeforeTest(groups = "live", dependsOnMethods = "setupStrategy") - void setupNodes() { - creater.execute(prefix, ImmutableSet. of()); - creater.execute(prefix + 1, ImmutableSet. of()); - } - - @AfterTest(groups = { "live" }) - @Override - public void teardownClient() throws IOException { - chef.deleteNode(prefix); - chef.deleteNode(prefix + 1); - super.teardownClient(); - } - - @Test - public void testExecute() { - assert size(strategy.execute()) > 0; - } - - @Test - public void testExecutePredicateOfString() { - assertEquals(size(strategy.execute(new Predicate() { - - @Override - public boolean apply(String input) { - return input.startsWith(prefix); - } - - })), 2); - } - - @Test - public void testExecuteIterableOfString() { - assertEquals(size(strategy.execute(ImmutableSet.of(prefix, prefix + 1))), 2); - } - -} diff --git a/chef/core/src/test/java/org/jclouds/chef/strategy/internal/UpdateAutomaticAttributesOnNodeImplLiveTest.java b/chef/core/src/test/java/org/jclouds/chef/strategy/internal/UpdateAutomaticAttributesOnNodeImplLiveTest.java deleted file mode 100644 index bd3290ea4c..0000000000 --- a/chef/core/src/test/java/org/jclouds/chef/strategy/internal/UpdateAutomaticAttributesOnNodeImplLiveTest.java +++ /dev/null @@ -1,84 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.strategy.internal; - -import static org.testng.Assert.assertEquals; - -import java.util.Map; -import java.util.Set; - -import org.jclouds.chef.ChefClient; -import org.jclouds.chef.domain.Node; -import org.jclouds.domain.JsonBall; -import org.jclouds.ohai.AutomaticSupplier; -import org.jclouds.ohai.config.ConfiguresOhai; -import org.jclouds.ohai.config.OhaiModule; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.Test; - -import com.google.common.base.Supplier; -import com.google.common.base.Suppliers; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; -import com.google.inject.Module; - -/** - * Tests behavior of {@code UpdateAutomaticAttributesOnNodeImpl} strategies - * - * @author Adrian Cole - */ -@Test(groups = "live", testName = "chef.UpdateAutomaticAttributesOnNodeImplLiveTest") -public class UpdateAutomaticAttributesOnNodeImplLiveTest extends BaseChefStrategyLiveTest { - private UpdateAutomaticAttributesOnNodeImpl strategy; - private ChefClient chef; - - @ConfiguresOhai - static class TestOhaiModule extends OhaiModule { - @Override - protected Supplier> provideAutomatic(AutomaticSupplier in) { - return Suppliers.> ofInstance(ImmutableMap.of("foo", new JsonBall("bar"))); - } - } - - protected void addTestModulesTo(Set modules) { - modules.add(new TestOhaiModule()); - } - - @BeforeTest(groups = "live", dependsOnMethods = "setupClient") - void setupStrategy() { - this.strategy = injector.getInstance(UpdateAutomaticAttributesOnNodeImpl.class); - this.chef = injector.getInstance(ChefClient.class); - } - - @Test - public void testExecute() { - Set runList = ImmutableSet.of("role[" + prefix + "]"); - try { - chef.createNode(new Node(prefix, runList)); - strategy.execute(prefix); - Node node = chef.getNode(prefix); - assertEquals(node.getName(), prefix); - assertEquals(node.getRunList(), runList); - assertEquals(node.getAutomatic().get("foo").toString(), "\"bar\""); - } finally { - injector.getInstance(ChefClient.class).deleteNode(prefix); - } - } -} diff --git a/chef/core/src/test/java/org/jclouds/chef/strategy/internal/UpdateAutomaticAttributesOnNodeImplTest.java b/chef/core/src/test/java/org/jclouds/chef/strategy/internal/UpdateAutomaticAttributesOnNodeImplTest.java deleted file mode 100644 index 3f052ac58f..0000000000 --- a/chef/core/src/test/java/org/jclouds/chef/strategy/internal/UpdateAutomaticAttributesOnNodeImplTest.java +++ /dev/null @@ -1,72 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.strategy.internal; - -import static org.easymock.EasyMock.expect; -import static org.easymock.classextension.EasyMock.createMock; -import static org.easymock.classextension.EasyMock.replay; -import static org.easymock.classextension.EasyMock.verify; - -import java.util.Map; - -import org.jclouds.chef.ChefClient; -import org.jclouds.chef.domain.Node; -import org.jclouds.domain.JsonBall; -import org.testng.annotations.Test; - -import com.google.common.base.Supplier; -import com.google.common.base.Suppliers; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; - -/** - * Tests behavior of {@code UpdateAutomaticAttributesOnNodeImpl} - * - * @author Adrian Cole - */ -@Test(groups = "unit", testName = "ohai.UpdateAutomaticAttributesOnNodeImplTest") -public class UpdateAutomaticAttributesOnNodeImplTest { - - @Test - public void test() { - ChefClient chef = createMock(ChefClient.class); - - Map automatic = ImmutableMap. of(); - - Node node = new Node("name", ImmutableSet. of()); - - Supplier> automaticSupplier = Suppliers.> ofInstance(automatic); - - Node nodeWithAutomatic = new Node("name", ImmutableMap. of(), ImmutableMap - . of(), ImmutableMap. of(), automatic, ImmutableSet. of()); - - expect(chef.getNode("name")).andReturn(node); - node.getAutomatic().putAll(automaticSupplier.get()); - expect(chef.updateNode(nodeWithAutomatic)).andReturn(null); - - replay(chef); - - UpdateAutomaticAttributesOnNodeImpl updater = new UpdateAutomaticAttributesOnNodeImpl(chef, automaticSupplier); - - updater.execute("name"); - verify(chef); - - } -} diff --git a/chef/core/src/test/java/org/jclouds/chef/test/TransientChefClientIntegrationTest.java b/chef/core/src/test/java/org/jclouds/chef/test/TransientChefClientIntegrationTest.java deleted file mode 100644 index 897e78dd17..0000000000 --- a/chef/core/src/test/java/org/jclouds/chef/test/TransientChefClientIntegrationTest.java +++ /dev/null @@ -1,327 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.test; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; - -import java.io.IOException; -import java.util.Properties; - -import org.jclouds.chef.BaseChefClientLiveTest; -import org.jclouds.chef.ChefClient; -import org.jclouds.chef.ChefContext; -import org.jclouds.chef.ChefContextFactory; -import org.jclouds.chef.config.ChefParserModule; -import org.jclouds.chef.domain.DatabagItem; -import org.jclouds.json.Json; -import org.jclouds.json.config.GsonModule; -import org.jclouds.rest.HttpClient; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import com.google.inject.Guice; - -/** - * Tests behavior of {@code TransientChefClient} - * - * @author Adrian Cole - */ -@Test(groups = "integration", testName = "chef.TransientChefClientIntegrationTest") -public class TransientChefClientIntegrationTest extends BaseChefClientLiveTest { - public void testCreateDatabag1() throws Exception { - getAdminConnection().deleteDatabag(PREFIX); - getAdminConnection().createDatabag(PREFIX); - } - - @Test(dependsOnMethods = "testCreateDatabag1") - public void testDatabagExists1() throws Exception { - assertNotNull(getClientConnection().databagExists(PREFIX)); - } - - @Test(dependsOnMethods = { "testCreateDatabag1"}) - public void testCreateDatabagItem1() throws Exception { - Properties config = new Properties(); - config.setProperty("foo", "bar"); - getAdminConnection().deleteDatabagItem(PREFIX, PREFIX); - databagItem = getAdminConnection().createDatabagItem(PREFIX, new DatabagItem("config", json.toJson(config))); - assertNotNull(databagItem); - assertEquals(databagItem.getId(), "config"); - assertEquals(config, json.fromJson(databagItem.toString(), Properties.class)); - } - - @Test(dependsOnMethods = "testCreateDatabagItem1") - public void testDatabagItemExists1() throws Exception { - assertNotNull(getClientConnection().databagItemExists(PREFIX, PREFIX)); - } - - @Test(dependsOnMethods = "testDatabagItemExists1") - public void testUpdateDatabagItem1() throws Exception { - for (String databagItemId : getClientConnection().listDatabagItems(PREFIX)) { - DatabagItem databagItem = getAdminConnection().getDatabagItem(PREFIX, databagItemId); - getAdminConnection().updateDatabagItem(PREFIX, databagItem); - } - } - @Override - @Test(enabled = false) - public void testClientExists() throws Exception { - super.testClientExists(); - } - - @Override - public void testCreateClient() throws Exception { - } - - @Override - public void testCreateDatabag() throws Exception { - super.testCreateDatabag(); - } - - @Override - public void testCreateDatabagItem() throws Exception { - super.testCreateDatabagItem(); - } - - @Override - public void testDatabagExists() throws Exception { - super.testDatabagExists(); - } - - @Override - public void testDatabagItemExists() throws Exception { - super.testDatabagItemExists(); - } - - @Override - public void testListDatabagItems() throws Exception { - super.testListDatabagItems(); - } - - @Override - public void testListDatabags() throws Exception { - super.testListDatabags(); - } - - @Override - @Test(enabled = false) - public void testCreateCookbook() throws Exception { - super.testCreateCookbook(); - } - - @Override - @Test(enabled = false) - public void testCreateNewCookbook() throws Exception { - super.testCreateNewCookbook(); - } - - @Override - @Test(enabled = false) - public void testCreateNode() throws Exception { - super.testCreateNode(); - } - - @Override - @Test(enabled = false) - public void testCreateRole() throws Exception { - super.testCreateRole(); - } - - @Override - @Test(enabled = false) - public void testGenerateKeyForClient() throws Exception { - super.testGenerateKeyForClient(); - } - - @Override - @Test(enabled = false) - public void testListCookbooks() throws Exception { - super.testListCookbooks(); - } - - @Override - @Test(enabled = false) - public void testListNodes() throws Exception { - super.testListNodes(); - } - - @Override - @Test(enabled = false) - public void testListRoles() throws Exception { - super.testListRoles(); - } - - @Override - @Test(enabled = false) - public void testListSearchIndexes() throws Exception { - super.testListSearchIndexes(); - } - - @Override - @Test(enabled = false) - public void testNodeExists() throws Exception { - super.testNodeExists(); - } - - @Override - @Test(enabled = false) - public void testRoleExists() throws Exception { - super.testRoleExists(); - } - - @Override - @Test(enabled = false) - public void testSearchClients() throws Exception { - super.testSearchClients(); - } - - @Override - @Test(enabled = false) - public void testSearchDatabag() throws Exception { - super.testSearchDatabag(); - } - - @Override - @Test(enabled = false) - public void testSearchDatabagNotFound() throws Exception { - super.testSearchDatabagNotFound(); - } - - @Override - @Test(enabled = false) - public void testSearchNodes() throws Exception { - super.testSearchNodes(); - } - - @Override - @Test(enabled = false) - public void testSearchRoles() throws Exception { - super.testSearchRoles(); - } - - @Override - @Test(enabled = false) - public void testUpdateCookbook() throws Exception { - super.testUpdateCookbook(); - } - - @Override - @Test(enabled = false) - public void testUpdateDatabagItem() throws Exception { - super.testUpdateDatabagItem(); - } - - @Override - @Test(enabled = false) - public void testUpdateNode() throws Exception { - super.testUpdateNode(); - } - - @Override - @Test(enabled = false) - public void testUpdateRole() throws Exception { - super.testUpdateRole(); - } - - @Override - @Test(enabled = false) - public void testValidatorCannotCreateClient() throws Exception { - super.testValidatorCannotCreateClient(); - } - - @Override - @Test(enabled = false) - public void testValidatorCannotDeleteClient() throws Exception { - super.testValidatorCannotDeleteClient(); - } - - @Override - @Test(enabled = false) - public void testValidatorCannotListClients() throws Exception { - super.testValidatorCannotListClients(); - } - - private ChefContext validatorConnection; - private ChefContext clientConnection; - private ChefContext adminConnection; - - @Override - @BeforeClass(groups = { "integration" }) - public void setupClient() throws IOException { - // TODO make this nicer - validatorConnection = adminConnection = clientConnection = createConnection("user", "userkey"); - json = Guice.createInjector(new GsonModule(), new ChefParserModule()).getInstance(Json.class); - } - - @Override - @AfterClass(groups = { "live" }) - public void teardownClient() throws IOException { - // if (getValidatorConnection().clientExists(PREFIX)) - // getValidatorConnection().deleteClient(PREFIX); - // if (getAdminConnection().nodeExists(PREFIX)) - // getAdminConnection().deleteNode(PREFIX); - // if (getAdminConnection().roleExists(PREFIX)) - // getAdminConnection().deleteRole(PREFIX); - if (getAdminConnection().databagExists(PREFIX)) - getAdminConnection().deleteDatabag(PREFIX); - closeContexts(); - } - - private ChefContext createConnection(String identity, String key) throws IOException { - return new ChefContextFactory().createContext("transientchef", identity, key); - } - - @Override - protected HttpClient getHttp() { - return adminConnection.utils().http(); - } - - @Override - protected ChefClient getAdminConnection() { - return adminConnection.getApi(); - } - - @Override - protected ChefClient getValidatorConnection() { - return validatorConnection.getApi(); - } - - @Override - protected ChefClient getClientConnection() { - return clientConnection.getApi(); - } - - @Override - protected void recreateClientConnection() throws IOException { - if (clientConnection != null) - clientConnection.close(); - clientConnection = createConnection(PREFIX, clientKey); - } - - @Override - protected void closeContexts() { - if (clientConnection != null) - clientConnection.close(); - if (validatorConnection != null) - validatorConnection.close(); - if (adminConnection != null) - adminConnection.close(); - } -} diff --git a/chef/core/src/test/java/org/jclouds/chef/util/ChefUtilsTest.java b/chef/core/src/test/java/org/jclouds/chef/util/ChefUtilsTest.java deleted file mode 100644 index 2c5c4f3aac..0000000000 --- a/chef/core/src/test/java/org/jclouds/chef/util/ChefUtilsTest.java +++ /dev/null @@ -1,62 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.util; - -import static org.testng.Assert.assertEquals; - -import java.util.Date; -import java.util.NoSuchElementException; - -import org.jclouds.domain.JsonBall; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableList; - -/** - * Tests behavior of {@code ChefUtils} - * - * @author Adrian Cole - */ -@Test(groups = "unit", sequential = true, testName = "ohai.ChefUtilsTest") -public class ChefUtilsTest { - public static long millis = 1280251180727l; - public static String millisString = "1280251180727"; - public static Date now = new Date(1280251180727l); - - public void testToOhaiTime() { - assertEquals(ChefUtils.toOhaiTime(millis).toString(), millisString); - } - - public void testFromOhaiTime() { - assertEquals(ChefUtils.fromOhaiTime(new JsonBall(millisString)), now); - - } - - @Test(expectedExceptions = NoSuchElementException.class) - public void testFindRoleInRunListThrowsNoSuchElementOnRecipe() { - ChefUtils.findRoleInRunList(ImmutableList.of("recipe[java]")); - } - - public void testFindRoleInRunList() { - assertEquals(ChefUtils.findRoleInRunList(ImmutableList.of("role[prod]")), "prod"); - - } - -} diff --git a/chef/core/src/test/java/org/jclouds/chef/util/RunListBuilderTest.java b/chef/core/src/test/java/org/jclouds/chef/util/RunListBuilderTest.java deleted file mode 100644 index 864dd90cfa..0000000000 --- a/chef/core/src/test/java/org/jclouds/chef/util/RunListBuilderTest.java +++ /dev/null @@ -1,74 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.util; - -import static org.testng.Assert.assertEquals; - -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableList; - -/** - * Tests possible uses of RunListBuilder - * - * @author Adrian Cole - */ -public class RunListBuilderTest { - - @Test - public void testRecipeAndRole() { - RunListBuilder options = new RunListBuilder(); - options.addRecipe("recipe").addRole("role"); - assertEquals(options.build(),ImmutableList.of("recipe[recipe]","role[role]")); - } - - @Test - public void testRecipe() { - RunListBuilder options = new RunListBuilder(); - options.addRecipe("test"); - assertEquals(options.build(),ImmutableList.of("recipe[test]")); - } - @Test - public void testRecipes() { - RunListBuilder options = new RunListBuilder(); - options.addRecipes("test", "test2"); - assertEquals(options.build(),ImmutableList.of("recipe[test]","recipe[test2]")); - } - - @Test - public void testRole() { - RunListBuilder options = new RunListBuilder(); - options.addRole("test"); - assertEquals(options.build(),ImmutableList.of("role[test]")); - } - @Test - public void testRoles() { - RunListBuilder options = new RunListBuilder(); - options.addRoles("test", "test2"); - assertEquals(options.build(),ImmutableList.of("role[test]","role[test2]")); - } - - @Test - public void testNoneRecipe() { - RunListBuilder options = new RunListBuilder(); - assertEquals(options.build(), ImmutableList.of()); - } - -} diff --git a/chef/core/src/test/java/org/jclouds/ohai/config/JMXTest.java b/chef/core/src/test/java/org/jclouds/ohai/config/JMXTest.java deleted file mode 100644 index b1b4f38cc5..0000000000 --- a/chef/core/src/test/java/org/jclouds/ohai/config/JMXTest.java +++ /dev/null @@ -1,80 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.ohai.config; - -import static org.easymock.EasyMock.expect; -import static org.easymock.classextension.EasyMock.createMock; -import static org.easymock.classextension.EasyMock.replay; -import static org.testng.Assert.assertEquals; - -import java.lang.management.RuntimeMXBean; -import java.util.Map; - -import javax.inject.Inject; - -import org.jclouds.chef.config.ChefParserModule; -import org.jclouds.domain.JsonBall; -import org.jclouds.json.Json; -import org.jclouds.json.config.GsonModule; -import org.jclouds.ohai.Automatic; -import org.jclouds.ohai.config.JMXOhaiModule; -import org.testng.annotations.Test; - -import com.google.common.base.Supplier; -import com.google.inject.Guice; -import com.google.inject.Injector; - -/** - * Tests behavior of {@code JMX} - * - * @author Adrian Cole - */ -@Test(groups = "unit", testName = "ohai.JMXTest") -public class JMXTest { - - @Test - public void test() { - - final RuntimeMXBean runtime = createMock(RuntimeMXBean.class); - - expect(runtime.getUptime()).andReturn(69876000l); - - replay(runtime); - - Injector injector = Guice.createInjector(new ChefParserModule(), new GsonModule(), new JMXOhaiModule() { - @Override - protected RuntimeMXBean provideRuntimeMXBean() { - return runtime; - } - }); - Json json = injector.getInstance(Json.class); - Ohai ohai = injector.getInstance(Ohai.class); - assertEquals(json.toJson(ohai.ohai.get().get("uptime_seconds")), "69876"); - } - - static class Ohai { - private Supplier> ohai; - - @Inject - public Ohai(@Automatic Supplier> ohai) { - this.ohai = ohai; - } - } -} diff --git a/chef/core/src/test/java/org/jclouds/ohai/config/OhaiModuleTest.java b/chef/core/src/test/java/org/jclouds/ohai/config/OhaiModuleTest.java deleted file mode 100644 index fc36a7fb2e..0000000000 --- a/chef/core/src/test/java/org/jclouds/ohai/config/OhaiModuleTest.java +++ /dev/null @@ -1,140 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.ohai.config; - -import static org.jclouds.chef.util.ChefUtils.ohaiAutomaticAttributeBinder; -import static org.testng.Assert.assertEquals; - -import java.net.SocketException; -import java.util.Map; -import java.util.Properties; - -import javax.inject.Inject; - -import org.jclouds.chef.config.ChefParserModule; -import org.jclouds.domain.JsonBall; -import org.jclouds.json.Json; -import org.jclouds.json.config.GsonModule; -import org.jclouds.ohai.Automatic; -import org.jclouds.ohai.config.multibindings.MapBinder; -import org.testng.annotations.Test; - -import com.google.common.base.Supplier; -import com.google.common.base.Suppliers; -import com.google.inject.AbstractModule; -import com.google.inject.Guice; -import com.google.inject.Injector; -import com.google.inject.TypeLiteral; -import com.google.inject.util.Providers; - -/** - * Tests behavior of {@code OhaiModule} - * - * @author Adrian Cole - */ -@Test(groups = "unit", testName = "ohai.OhaiModuleTest") -public class OhaiModuleTest { - - @Test - public void test() throws SocketException { - - final Properties sysProperties = new Properties(); - - sysProperties.setProperty("os.name", "Mac OS X"); - sysProperties.setProperty("os.version", "10.3.0"); - sysProperties.setProperty("user.name", "user"); - - Injector injector = Guice.createInjector(new ChefParserModule(), new GsonModule(), new OhaiModule() { - @Override - protected Long millis() { - return 127999291932529l; - } - - @Override - protected Properties systemProperties() { - return sysProperties; - } - - }); - Ohai ohai = injector.getInstance(Ohai.class); - Json json = injector.getInstance(Json.class); - - assertEquals( - json.toJson(ohai.ohai.get(), new TypeLiteral>() { - }.getType()), - "{\"ohai_time\":127999291932529,\"platform\":\"macosx\",\"platform_version\":\"10.3.0\",\"current_user\":\"user\",\"jvm\":{\"system\":{\"user.name\":\"user\",\"os.version\":\"10.3.0\",\"os.name\":\"Mac OS X\"}}}"); - } - - public void test2modules() throws SocketException { - - final Properties sysProperties = new Properties(); - - sysProperties.setProperty("os.name", "Mac OS X"); - sysProperties.setProperty("os.version", "10.3.0"); - sysProperties.setProperty("user.name", "user"); - - Injector injector = Guice.createInjector(new ChefParserModule(), new GsonModule(), new OhaiModule() { - @Override - protected Long millis() { - return 1279992919l; - } - - @Override - protected Properties systemProperties() { - return sysProperties; - } - - }, new AbstractModule() { - - @Override - protected void configure() { - MapBinder> mapbinder = ohaiAutomaticAttributeBinder(binder()); - mapbinder.addBinding("test").toProvider( - Providers.of(Suppliers.ofInstance(new JsonBall("{\"prop1\":\"test1\"}")))); - } - - }, new AbstractModule() { - - @Override - protected void configure() { - MapBinder> mapbinder = ohaiAutomaticAttributeBinder(binder()); - mapbinder.addBinding("test").toProvider( - Providers.of(Suppliers.ofInstance(new JsonBall("{\"prop2\":\"test2\"}")))); - } - - }); - Ohai ohai = injector.getInstance(Ohai.class); - Json json = injector.getInstance(Json.class); - - assertEquals( - json.toJson(ohai.ohai.get(), new TypeLiteral>() { - }.getType()), - "{\"ohai_time\":1279992919,\"platform\":\"macosx\",\"platform_version\":\"10.3.0\",\"current_user\":\"user\",\"test\":{\"prop1\":\"test1\",\"prop2\":\"test2\"},\"jvm\":{\"system\":{\"user.name\":\"user\",\"os.version\":\"10.3.0\",\"os.name\":\"Mac OS X\"}}}"); - } - - static class Ohai { - private Supplier> ohai; - - @Inject - public Ohai(@Automatic Supplier> ohai) { - this.ohai = ohai; - } - } -} diff --git a/chef/core/src/test/java/org/jclouds/ohai/functions/ByteArrayToMacAddressTest.java b/chef/core/src/test/java/org/jclouds/ohai/functions/ByteArrayToMacAddressTest.java deleted file mode 100644 index 39b2ee2cf5..0000000000 --- a/chef/core/src/test/java/org/jclouds/ohai/functions/ByteArrayToMacAddressTest.java +++ /dev/null @@ -1,52 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.ohai.functions; - -import static org.testng.Assert.assertEquals; - -import java.io.IOException; - -import org.jclouds.crypto.CryptoStreams; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.Test; - -import com.google.inject.Guice; -import com.google.inject.Injector; - -/** - * Tests behavior of {@code ByteArrayToMacAddress} - * - * @author Adrian Cole - */ -@Test(groups = "unit", sequential = true, testName = "ohai.ByteArrayToMacAddressTest") -public class ByteArrayToMacAddressTest { - - private ByteArrayToMacAddress converter; - - @BeforeTest - protected void setUpInjector() throws IOException { - Injector injector = Guice.createInjector(); - converter = injector.getInstance(ByteArrayToMacAddress.class); - } - - public void test() { - assertEquals(converter.apply(CryptoStreams.hex("0026bb09e6c4")), "00:26:bb:09:e6:c4"); - } -} diff --git a/chef/core/src/test/java/org/jclouds/ohai/functions/NestSlashKeysTest.java b/chef/core/src/test/java/org/jclouds/ohai/functions/NestSlashKeysTest.java deleted file mode 100644 index a6658e5d29..0000000000 --- a/chef/core/src/test/java/org/jclouds/ohai/functions/NestSlashKeysTest.java +++ /dev/null @@ -1,102 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.ohai.functions; - -import static org.testng.Assert.assertEquals; - -import java.io.IOException; - -import org.jclouds.chef.config.ChefParserModule; -import org.jclouds.domain.JsonBall; -import org.jclouds.json.Json; -import org.jclouds.json.config.GsonModule; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.Test; - -import com.google.common.base.Supplier; -import com.google.common.base.Suppliers; -import com.google.common.collect.ImmutableMultimap; -import com.google.inject.Guice; -import com.google.inject.Injector; - -/** - * Tests behavior of {@code NestSlashKeys} - * - * @author Adrian Cole - */ -@Test(groups = "unit", sequential = true, testName = "ohai.NestSlashKeysTest") -public class NestSlashKeysTest { - - private NestSlashKeys converter; - private Json json; - - @BeforeTest - protected void setUpInjector() throws IOException { - Injector injector = Guice.createInjector(new ChefParserModule(), new GsonModule()); - converter = injector.getInstance(NestSlashKeys.class); - json = injector.getInstance(Json.class); - } - - @Test - public void testBase() { - assertEquals(json.toJson(converter.apply(ImmutableMultimap.> of("java", Suppliers - .ofInstance(new JsonBall("java"))))), "{\"java\":\"java\"}"); - } - - @Test(expectedExceptions = IllegalArgumentException.class) - public void testIllegal() { - json.toJson(converter.apply(ImmutableMultimap.> of("java", Suppliers - .ofInstance(new JsonBall("java")), "java/system", Suppliers.ofInstance(new JsonBall("system"))))); - } - - @Test - public void testOne() { - assertEquals(json.toJson(converter.apply(ImmutableMultimap.> of("java", Suppliers - .ofInstance(new JsonBall("{\"time\":\"time\"}")), "java/system", Suppliers - .ofInstance(new JsonBall("system"))))), "{\"java\":{\"time\":\"time\",\"system\":\"system\"}}"); - } - - @Test - public void testOneDuplicate() { - assertEquals(json.toJson(converter.apply(ImmutableMultimap.> of("java", Suppliers - .ofInstance(new JsonBall("{\"time\":\"time\"}")), "java", Suppliers.ofInstance(new JsonBall( - "{\"system\":\"system\"}"))))), "{\"java\":{\"time\":\"time\",\"system\":\"system\"}}"); - } - - @Test - public void testMerge() { - assertEquals(json.toJson(converter.apply(ImmutableMultimap.> of("java", Suppliers - .ofInstance(new JsonBall("{\"time\":{\"1\":\"hello\"}}")), "java/time", Suppliers.ofInstance(new JsonBall( - "{\"2\":\"goodbye\"}"))))), "{\"java\":{\"time\":{\"1\":\"hello\",\"2\":\"goodbye\"}}}"); - } - @Test - public void testMergeNestedTwice() { - assertEquals(json.toJson(converter.apply(ImmutableMultimap.> of("java", Suppliers - .ofInstance(new JsonBall("{\"time\":{\"1\":\"hello\"}}")), "java", Suppliers.ofInstance(new JsonBall( - "{\"time\":{\"2\":\"goodbye\"}}"))))), "{\"java\":{\"time\":{\"1\":\"hello\",\"2\":\"goodbye\"}}}"); - } - - @Test - public void testReplaceList() { - assertEquals(json.toJson(converter.apply(ImmutableMultimap.> of("java", Suppliers - .ofInstance(new JsonBall("{\"time\":{\"1\":[\"hello\"]}}")), "java/time", Suppliers.ofInstance(new JsonBall( - "{\"1\":[\"goodbye\"]}"))))), "{\"java\":{\"time\":{\"1\":[\"goodbye\"]}}}"); - } -} diff --git a/chef/core/src/test/resources/apache-chef-demo-cookbook.json b/chef/core/src/test/resources/apache-chef-demo-cookbook.json deleted file mode 100644 index 0a3e384039..0000000000 --- a/chef/core/src/test/resources/apache-chef-demo-cookbook.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "definitions": [], - "name": "apache-chef-demo-0.0.0", - "attributes": [], - "files": [], - "json_class": "Chef::CookbookVersion", - "providers": [], - "metadata": { - "dependencies": {}, "name": "apache-chef-demo", - "maintainer_email": "youremail@example.com", - "attributes": {}, "license": "Apache v2.0", - "maintainer": "Your Name", - "suggestions": {}, "platforms": {}, "long_description": "", - "recommendations": {}, "version": "0.0.0", - "groupings": {}, "recipes": {}, "conflicting": {}, "description": "A fabulous new cookbook", - "replacing": {}, "providing": {} - }, "libraries": [], - "resources": [], - "templates": [], - "cookbook_name": "apache-chef-demo", - "version": "0.0.0", - "recipes": [], - "root_files": [{ - "name": "README", - "url": "https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-11637f98942eafbf49c71b7f2f048b78?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277766181&Signature=zgpNl6wSxjTNovqZu2nJq0JztU8%3D", - "checksum": "11637f98942eafbf49c71b7f2f048b78", - "path": "README", - "specificity": "default" - }, { - "name": "Rakefile", - "url": "https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-ebcf925a1651b4e04b9cd8aac2bc54eb?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277766181&Signature=EFzzDSKKytTl7b%2FxrCeNLh05zj4%3D", - "checksum": "ebcf925a1651b4e04b9cd8aac2bc54eb", - "path": "Rakefile", - "specificity": "default" - }], - "chef_type": "cookbook_version" -} \ No newline at end of file diff --git a/chef/core/src/test/resources/brew-cookbook.json b/chef/core/src/test/resources/brew-cookbook.json deleted file mode 100644 index f0b09ede2a..0000000000 --- a/chef/core/src/test/resources/brew-cookbook.json +++ /dev/null @@ -1 +0,0 @@ -{"name":"brew-0.0.0","definitions":[],"json_class":"Chef::CookbookVersion","attributes":[],"files":[],"metadata":{"dependencies":{},"name":"brew","maintainer_email":"youremail@example.com","license":"Apache v2.0","attributes":{},"maintainer":"Your Name","suggestions":{},"platforms":{},"long_description":"","version":"0.0.0","recommendations":{},"conflicting":{},"recipes":{"brew":""},"groupings":{},"description":"A fabulous new cookbook","replacing":{},"providing":{"brew":[]}},"providers":[{"name":"brew.rb","url":"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-0c5ecd7788cf4f6c7de2a57193897a6c?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277774465&Signature=brTA3YkBF7iDnjPGCCHxgm7AHko%3D","checksum":"0c5ecd7788cf4f6c7de2a57193897a6c","path":"providers/brew.rb","specificity":"default"}],"cookbook_name":"brew","resources":[{"name":"brew.rb","url":"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-0189e76ccc476701d6b374e5a1a27347?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277774465&Signature=ufrI1k6pKJ1%2FBRMAaIGr6icJlpc%3D","checksum":"0189e76ccc476701d6b374e5a1a27347","path":"resources/brew.rb","specificity":"default"}],"templates":[],"libraries":[],"version":"0.0.0","recipes":[{"name":"default.rb","url":"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-1dda05ed139664f1f89b9dec482b77c0?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277774465&Signature=dOzPk64at92zOfZlxt1suDpGuPs%3D","checksum":"1dda05ed139664f1f89b9dec482b77c0","path":"recipes/default.rb","specificity":"default"}],"root_files":[],"chef_type":"cookbook_version"} \ No newline at end of file diff --git a/chef/core/src/test/resources/client.json b/chef/core/src/test/resources/client.json deleted file mode 100644 index 15ff8d06a7..0000000000 --- a/chef/core/src/test/resources/client.json +++ /dev/null @@ -1 +0,0 @@ -{"orgname":"jclouds","certificate":"-----BEGIN CERTIFICATE-----\nMIIClzCCAgCgAwIBAgIBATANBgkqhkiG9w0BAQUFADCBnjELMAkGA1UEBhMCVVMx\nEzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxFjAUBgNVBAoM\nDU9wc2NvZGUsIEluYy4xHDAaBgNVBAsME0NlcnRpZmljYXRlIFNlcnZpY2UxMjAw\nBgNVBAMMKW9wc2NvZGUuY29tL2VtYWlsQWRkcmVzcz1hdXRoQG9wc2NvZGUuY29t\nMB4XDTEwMDczMDIwNDEzMFoXDTIwMDcyNzIwNDEzMFowADCCASIwDQYJKoZIhvcN\nAQEBBQADggEPADCCAQoCggEBAMm9mSSahptCikfvJ30CTbEnfhfbVzTFewnznFuo\n7KrPBGYIlUdPYQ9SGDo+GKjNKiTjZYMoOMUVnsHUhu0Ez49ZSaVQInWvbF8tvpM8\nmoGQNQJtDmXG6m+YaHiA4HF/ng2u/bNLtA6Jo3HzvRCobxywc/szPt0Kj0ZD1fJ2\nE237Ph41c8zlOg9QdF0d/iD2WZdgJ1rNndKoZ0rR3A1L50VUND+PNmMDfVYHHjmb\naT89AwihCeU8eUk7m/JNP87f1QDB0Gny0rkDC3drOGS7jmabTf/7gLE5sYq3qnd+\n8/vGU3QWyfCxKSfogl7kn5uWlIe4sOqMb06GNgC+d/oytlECAwEAATANBgkqhkiG\n9w0BAQUFAAOBgQBftzSZxstWw60GqRTDNN/F2GnrdtnKBoXzHww3r6jtGEylYq20\n5KfKpEx+sPX0gyZuYJiXC2CkEjImAluWKcdN9ZF6VD541sheAjbiaU7q7ZsztTxF\nWUH2tCvHeDXYKPKek3QzL7bYpUhLnCN/XxEv6ibeMDwtI7f5qpk2Aspzcw==\n-----END CERTIFICATE-----\n","uri":"https://api.opscode.com/organizations/jclouds/clients/adriancole-jcloudstest","private_key":"-----BEGIN RSA PRIVATE KEY-----\nMIIEpQIBAAKCAQEAyb2ZJJqGm0KKR+8nfQJNsSd+F9tXNMV7CfOcW6jsqs8EZgiV\nR09hD1IYOj4YqM0qJONlgyg4xRWewdSG7QTPj1lJpVAida9sXy2+kzyagZA1Am0O\nZcbqb5hoeIDgcX+eDa79s0u0DomjcfO9EKhvHLBz+zM+3QqPRkPV8nYTbfs+HjVz\nzOU6D1B0XR3+IPZZl2AnWs2d0qhnStHcDUvnRVQ0P482YwN9VgceOZtpPz0DCKEJ\n5Tx5STub8k0/zt/VAMHQafLSuQMLd2s4ZLuOZptN//uAsTmxireqd37z+8ZTdBbJ\n8LEpJ+iCXuSfm5aUh7iw6oxvToY2AL53+jK2UQIDAQABAoIBAQDA88B3i/xWn0vX\nBVxFamCYoecuNjGwXXkSyZew616A+EOCu47bh4aTurdFbYL0YFaAtaWvzlaN2eHg\nDb+HDuTefE29+WkcGk6SshPmiz5T0XOCAICWw6wSVDkHmGwS4jZvbAFm7W8nwGk9\nYhxgxFiRngswJZFopOLoF5WXs2td8guIYNslMpo7tu50iFnBHwKO2ZsPAk8t9nnS\nxlDavKruymEmqHCr3+dtio5eaenJcp3fjoXBQOKUk3ipII29XRB8NqeCVV/7Kxwq\nckqOBEbRwBclckyIbD+RiAgKvOelORjEiE9R42vuqvxRA6k9kd9o7utlX0AUtpEn\n3gZc6LepAoGBAP9ael5Y75+sK2JJUNOOhO8ae45cdsilp2yI0X+UBaSuQs2+dyPp\nkpEHAxd4pmmSvn/8c9TlEZhr+qYbABXVPlDncxpIuw2Ajbk7s/S4XaSKsRqpXL57\nzj/QOqLkRk8+OVV9q6lMeQNqLtEj1u6JPviX70Ro+FQtRttNOYbfdP/fAoGBAMpA\nXjR5woV5sUb+REg9vEuYo8RSyOarxqKFCIXVUNsLOx+22+AK4+CQpbueWN7jotrl\nYD6uT6svWi3AAC7kiY0UI/fjVPRCUi8tVoQUE0TaU5VLITaYOB+W/bBaDE4M9560\n1NuDWO90baA5dfU44iuzva02rGJXK9+nS3o8nk/PAoGBALOL6djnDe4mwAaG6Jco\ncd4xr8jkyPzCRZuyBCSBbwphIUXLc7hDprPky064ncJD1UDmwIdkXd/fpMkg2QmA\n/CUk6LEFjMisqHojOaCL9gQZJPhLN5QUN2x1PJWGjs1vQh8Tkx0iUUCOa8bQPXNR\n+34OTsW6TUna4CSZAycLfhffAoGBAIggVsefBCvuQkF0NeUhmDCRZfhnd8y55RHR\n1HCvqKIlpv+rhcX/zmyBLuteopYyRJRsOiE2FW00i8+rIPRu4Z3Q5nybx7w3PzV9\noHN5R5baE9OyI4KpZWztpYYitZF67NcnAvVULHHOvVJQGnKYfLHJYmrJF7GA1ojM\nAuMdFbjFAoGAPxUhxwFy8gaqBahKUEZn4F81HFP5ihGhkT4QL6AFPO2e+JhIGjuR\n27+85hcFqQ+HHVtFsm81b/a+R7P4UuCRgc8eCjxQMoJ1Xl4n7VbjPbHMnIN0Ryvd\nO4ZpWDWYnCO021JTOUUOJ4J/y0416Bvkw0z59y7sNX7wDBBHHbK/XCc=\n-----END RSA PRIVATE KEY-----\n","clientname":"adriancole-jcloudstest","name":"adriancole-jcloudstest","validator":false} \ No newline at end of file diff --git a/chef/core/src/test/resources/client.txt b/chef/core/src/test/resources/client.txt deleted file mode 100644 index 5023370477..0000000000 --- a/chef/core/src/test/resources/client.txt +++ /dev/null @@ -1,7 +0,0 @@ -{ - "certificate": "-----BEGIN CERTIFICATE-----\ndXQ==\n-----END CERTIFICATE-----\n", - "orgname": "jclouds", - "clientname": "adrian-jcloudstest", - "name": "adrian-jcloudstest", - "validator": false -} \ No newline at end of file diff --git a/chef/core/src/test/resources/log4j.xml b/chef/core/src/test/resources/log4j.xml deleted file mode 100644 index 4cf98d7922..0000000000 --- a/chef/core/src/test/resources/log4j.xml +++ /dev/null @@ -1,142 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/chef/core/src/test/resources/mysql-cookbook.json b/chef/core/src/test/resources/mysql-cookbook.json deleted file mode 100644 index b0f8bc4ee6..0000000000 --- a/chef/core/src/test/resources/mysql-cookbook.json +++ /dev/null @@ -1 +0,0 @@ -{"definitions":[],"name":"mysql-0.21.2","attributes":[{"name":"server.rb","url":"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-548fa4bc548b8b59ac98fffee8e81f4a?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277774082&Signature=MsgggSKS0T1q1Lc72nJpHORBQX0%3D","checksum":"548fa4bc548b8b59ac98fffee8e81f4a","path":"attributes/server.rb","specificity":"default"}],"files":[],"json_class":"Chef::CookbookVersion","providers":[{"name":"database.rb","url":"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-b994881a2aba60e32c4b6408ffba993d?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277774082&Signature=2XMRbryCmEqirCWLCvrXoenYubw%3D","checksum":"b994881a2aba60e32c4b6408ffba993d","path":"providers/database.rb","specificity":"default"}],"metadata":{"dependencies":{"openssl":[]},"name":"mysql","maintainer_email":"cookbooks@opscode.com","attributes":{"mysql/server_root_password":{"required":"optional","calculated":false,"default":"randomly generated","choice":[],"type":"string","recipes":[],"display_name":"MySQL Server Root Password","description":"Randomly generated password for the mysqld root user"},"mysql/tunable/max_heap_table_size":{"required":"optional","calculated":false,"default":"32M","choice":[],"type":"string","recipes":[],"display_name":"MySQL Tunable Max Heap Table Size"},"mysql/bind_address":{"required":"optional","calculated":false,"default":"ipaddress","choice":[],"type":"string","recipes":[],"display_name":"MySQL Bind Address","description":"Address that mysqld should listen on"},"mysql/datadir":{"required":"optional","calculated":false,"default":"/var/lib/mysql","choice":[],"type":"string","recipes":[],"display_name":"MySQL Data Directory","description":"Location of mysql databases"},"mysql/tunable/wait_timeout":{"required":"optional","calculated":false,"default":"180","choice":[],"type":"string","recipes":[],"display_name":"MySQL Tunable Wait Timeout"},"mysql/tunable/back_log":{"required":"optional","calculated":false,"default":"128","choice":[],"type":"string","recipes":[],"display_name":"MySQL Tunable Back Log"},"mysql/tunable/net_read_timeout":{"required":"optional","calculated":false,"default":"30","choice":[],"type":"string","recipes":[],"display_name":"MySQL Tunable Net Read Timeout"},"mysql/tunable/max_connections":{"required":"optional","calculated":false,"default":"800","choice":[],"type":"string","recipes":[],"display_name":"MySQL Tunable Max Connections"},"mysql/tunable":{"required":"optional","calculated":false,"choice":[],"type":"hash","recipes":[],"display_name":"MySQL Tunables","description":"Hash of MySQL tunable attributes"},"mysql/tunable/table_cache":{"required":"optional","calculated":false,"default":"128","choice":[],"type":"string","recipes":[],"display_name":"MySQL Tunable Table Cache"},"mysql/ec2_path":{"required":"optional","calculated":false,"default":"/mnt/mysql","choice":[],"type":"string","recipes":[],"display_name":"MySQL EC2 Path","description":"Location of mysql directory on EC2 instance EBS volumes"},"mysql/tunable/key_buffer":{"required":"optional","calculated":false,"default":"250M","choice":[],"type":"string","recipes":[],"display_name":"MySQL Tuntable Key Buffer"},"mysql/tunable/net_write_timeout":{"required":"optional","calculated":false,"default":"30","choice":[],"type":"string","recipes":[],"display_name":"MySQL Tunable Net Write Timeout"}},"license":"Apache 2.0","maintainer":"Opscode, Inc.","suggestions":{},"platforms":{"debian":[],"ubuntu":[]},"long_description":"= DESCRIPTION:\n\nInstalls and configures MySQL client or server.\n\n= REQUIREMENTS:\n\n== Platform:\n\nBest tested on Ubuntu 9.04,9.10. On EC2, requires platform that supports -o bind option for the 'mount' command.\n\n== Cookbooks:\n\nRequires Opscode's openssl cookbook for secure password generation.\n\n= ATTRIBUTES: \n\n* mysql[:server_root_password] - Set the server's root password with this, default is a randomly generated password with OpenSSL::Random.random_bytes.\n* mysql[:server_repl_password] - Set the replication user 'repl' password with this, default is a randomly generated password with OpenSSL::Random.random_bytes.\n* mysql[:server_debian_password] - Set the debian-sys-maint user password with this, default is a randomly generated password with OpenSSL::Random.random_bytes.\n* mysql[:bind_address] - Listen address for MySQLd, default is node's ipaddress.\n* mysql[:datadir] - Location for mysql data directory, default is \"/var/lib/mysql\" \n* mysql[:ec2_path] - location of mysql datadir on EC2 nodes, default \"/mnt/mysql\" \n\nPerformance tuning attributes, each corresponds to the same-named parameter in my.cnf; default values listed\n\n* mysql[:tunable][:key_buffer] = \"250M\"\n* mysql[:tunable][:max_connections] = \"800\" \n* mysql[:tunable][:wait_timeout] = \"180\" \n* mysql[:tunable][:net_write_timeout] = \"30\" \n* mysql[:tunable][:net_write_timeout] = \"30\" \n* mysql[:tunable][:back_log] = \"128\" \n* mysql[:tunable][:table_cache] = \"128\" \n* mysql[:tunable][:max_heap_table_size] = \"32M\" \n\n= USAGE:\n\nOn client nodes,\n\n include_recipe \"mysql::client\"\n \nAs the common use case is on systems with Ruby, we also install the MySQL RubyGem. Because we may want to be able to use the gem within another Chef recipe, we make sure the mysql development package and gem are installed first. The key is this:\n\n r = package ... do\n action :nothing\n end\n \n r.run_action(:install)\n \nThis creates a resource object for the package and does the installation before other recipes are parsed. You'll need to have the C compiler and such (ie, build-essential on Ubuntu) before running the recipes, but we already do that when installing Chef :-). If you want to be able to access a MySQL database via Ruby within another recipe, you could do so, like so:\n\n Gem.clear_paths # needed for Chef to find the gem...\n require 'mysql' # requires the mysql gem\n\n execute \"create #{node[:railsapp][:db][:database]} database\" do\n command \"/usr/bin/mysqladmin -u root -p#{node[:mysql][:server_root_password]} create #{node[:railsapp][:db][:database]}\"\n not_if do\n m = Mysql.new(\"localhost\", \"root\", @node[:mysql][:server_root_password])\n m.list_dbs.include?(@node[:railsapp][:db][:database])\n end\n end\n\nOn server nodes, \n\n include_recipe \"mysql::server\"\n \nOn Debian/Ubuntu this will preseed the MySQL package with the randomly generated root password. You can of course change the password afterward, but this makes sure that there's a good password set. You can view it in the node data in the Chef Server webui. Sets a new password for debian-sys-maint user as well.\n\nAlso sets up 'repl' user grants for replication slaves.\n\nOn EC2 nodes,\n\n include_recipe \"mysql::server_ec2\"\n \nWhen the ec2_path doesn't exist we look for a mounted filesystem (eg, EBS) and move the datadir there.\n\nThe client recipe is already included by server and 'default' recipes.\n\n= LICENSE and AUTHOR:\n \nAuthor:: Joshua Timberman ()\nAuthor:: AJ Christensen ()\n\nCopyright:: 2009, Opscode, Inc\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n","recommendations":{},"version":"0.21.2","groupings":{},"recipes":{"mysql::client":"Installs packages required for mysql clients using run_action magic","mysql::server_ec2":"Performs EC2-specific mountpoint manipulation","mysql::server":"Installs packages required for mysql servers w/o manual intervention"},"conflicting":{},"description":"Installs and configures mysql for client or server","replacing":{},"providing":{}},"libraries":[{"name":"database.rb","url":"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-b2eb0760c07734be9c637dcffc86175a?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277774082&Signature=CvVbxzrA%2Fuxc59ZjLR5BsMozfxk%3D","checksum":"b2eb0760c07734be9c637dcffc86175a","path":"libraries/database.rb","specificity":"default"}],"resources":[{"name":"database.rb","url":"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-8aa8e2cafe54c2932c7aa65d62ec2695?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277774082&Signature=6URS94f1HpRibHC%2FhBkr7Eg3dVA%3D","checksum":"8aa8e2cafe54c2932c7aa65d62ec2695","path":"resources/database.rb","specificity":"default"}],"templates":[{"name":"my.cnf.erb","url":"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-689c1b6fbb242b6c508384e56646341d?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277774082&Signature=2ugp0XVvvUktYdBxfC9bCZBjOs4%3D","checksum":"689c1b6fbb242b6c508384e56646341d","path":"templates/ubuntu-9.10/my.cnf.erb","specificity":"ubuntu-9.10"},{"name":"mysql-server.seed.erb","url":"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-16b036a0bb31957a77e9b825cf616cc5?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277774082&Signature=50bRvt6GQqFEcfYtaIsq1d4a4c8%3D","checksum":"16b036a0bb31957a77e9b825cf616cc5","path":"templates/default/mysql-server.seed.erb","specificity":"default"},{"name":"grants.sql.erb","url":"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-932b51ddddcbd24ee10a76ecae33b8ba?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277774082&Signature=RHR0obLFcsN1M9tL28IH4Tcur5g%3D","checksum":"932b51ddddcbd24ee10a76ecae33b8ba","path":"templates/default/grants.sql.erb","specificity":"default"},{"name":"my.cnf.erb","url":"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-7746560b37ac8d4a0cf68befbecbd8a3?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277774082&Signature=W7Nqkvhw2TBrlDvcM2rlA4Oj5%2Bk%3D","checksum":"7746560b37ac8d4a0cf68befbecbd8a3","path":"templates/default/my.cnf.erb","specificity":"default"},{"name":"my.cnf.erb","url":"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-63bd67fae6d297e8f658e9c0ad01a411?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277774082&Signature=oFcRya56f%2F4oJBGrIvk4XcWQFm4%3D","checksum":"63bd67fae6d297e8f658e9c0ad01a411","path":"templates/centos/my.cnf.erb","specificity":"centos"},{"name":"my.cnf.erb","url":"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-689c1b6fbb242b6c508384e56646341d?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277774082&Signature=2ugp0XVvvUktYdBxfC9bCZBjOs4%3D","checksum":"689c1b6fbb242b6c508384e56646341d","path":"templates/ubuntu-10.04/my.cnf.erb","specificity":"ubuntu-10.04"},{"name":"my.cnf.erb","url":"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-63bd67fae6d297e8f658e9c0ad01a411?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277774082&Signature=oFcRya56f%2F4oJBGrIvk4XcWQFm4%3D","checksum":"63bd67fae6d297e8f658e9c0ad01a411","path":"templates/redhat/my.cnf.erb","specificity":"redhat"},{"name":"port_mysql.erb","url":"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-d2244150a145b3f658cd37c13269fafc?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277774082&Signature=23iHcjwpNOvlNf%2BlrKcV2pkU7uo%3D","checksum":"d2244150a145b3f658cd37c13269fafc","path":"templates/default/port_mysql.erb","specificity":"default"},{"name":"debian.cnf.erb","url":"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-2e08553db526f5f80c28b343f6a616cb?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277774082&Signature=VdcFYxnLUkj1tS3k8DovrzZEA7E%3D","checksum":"2e08553db526f5f80c28b343f6a616cb","path":"templates/default/debian.cnf.erb","specificity":"default"},{"name":"my.cnf.erb","url":"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-1e5068eec65b51f5a327580fb0af4677?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277774082&Signature=D5lPeu1UQvA9pEXZm5nVOwj3WIo%3D","checksum":"1e5068eec65b51f5a327580fb0af4677","path":"templates/ubuntu-8.04/my.cnf.erb","specificity":"ubuntu-8.04"}],"cookbook_name":"mysql","version":"0.21.2","recipes":[{"name":"server_ec2.rb","url":"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-f51bd8122b7dccc9f4656319fef3252a?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277774082&Signature=BUR2mosCvmoOKq4Mkh3JUG0MY38%3D","checksum":"f51bd8122b7dccc9f4656319fef3252a","path":"recipes/server_ec2.rb","specificity":"default"},{"name":"server.rb","url":"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-80daa897597560372d017c58c4df0e3c?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277774082&Signature=bU3j9Nw%2BnuIroXKrlJZe7tjaugA%3D","checksum":"80daa897597560372d017c58c4df0e3c","path":"recipes/server.rb","specificity":"default"},{"name":"default.rb","url":"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-bd3ba2d05dea6a8cf0dc2a45f540cc32?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277774082&Signature=7haumT5EtEM2h8l32efqV%2Fik%2BdY%3D","checksum":"bd3ba2d05dea6a8cf0dc2a45f540cc32","path":"recipes/default.rb","specificity":"default"},{"name":"client.rb","url":"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-a1d679c7480267cd9b69e3194c7e45ab?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277774082&Signature=ZhfTiwv1aXC7HZMnW8A7i4vkMCM%3D","checksum":"a1d679c7480267cd9b69e3194c7e45ab","path":"recipes/client.rb","specificity":"default"}],"root_files":[{"name":"README.rdoc","url":"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-e9278fc99fd668bdce33d72dc71fade9?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277774082&Signature=KPgAGqShEO5SGzz8oRdwIInPUOc%3D","checksum":"e9278fc99fd668bdce33d72dc71fade9","path":"README.rdoc","specificity":"default"},{"name":"metadata.rb","url":"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-8d2f9635f4817ff905a4124e09ec6c59?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277774082&Signature=fPF2iY7tNrq%2FuNrCjRLImP9vRbA%3D","checksum":"8d2f9635f4817ff905a4124e09ec6c59","path":"metadata.rb","specificity":"default"},{"name":"metadata.json","url":"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-e6804b8f3e6dfdbbece9d319537ffea1?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277774082&Signature=EVsALLreeAA41%2BiPAfPt%2FxFEIYI%3D","checksum":"e6804b8f3e6dfdbbece9d319537ffea1","path":"metadata.json","specificity":"default"}],"chef_type":"cookbook_version"} \ No newline at end of file diff --git a/chef/core/src/test/resources/newclient.txt b/chef/core/src/test/resources/newclient.txt deleted file mode 100644 index c1e93687b7..0000000000 --- a/chef/core/src/test/resources/newclient.txt +++ /dev/null @@ -1 +0,0 @@ -{"clientname":"adriancole-jcloudstest","private_key":"-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEAuzaE6azgUxwESX1rCGdJ5xpdrc1XC311bOGZBCE8NA+CpFh2\npopCBQwjpOnlgpdd/+C+TESl30ojauvVej9AbgJb30Jl7e7dEX4Brncnj03G+mo+\nG4osf7I2PA/6+9Ol7xamK9GL/cs8nOb17cRTWmhTRW7+3Rrli/s6wzqQXjGjWzgz\nthXv7FOPHA87UjJzrePBFta7+S8BxKCG2QaTxzNGytSAy8KBX8BUrSt5+X22QjEM\nQF3zA4TPtoWp/lcDRzCMdffMYoVPZzKqIeEFSexwvNlJ/qU6hbcyAxab1lYawjKU\nRgvPCflVYTIw6teHNqkyvTPX+lpIAVXigSVQXwIDAQABAoIBAHz81xvTSSjzaYFO\n9Gh13QcnuSdSEi0fo4f/zdLOBY2UVVo3nW9umskX46w0ZAAd4qn0d9gfdMZwjtjR\nfoLRO8i2VnPltnt1n64P/DtoXcb03EVPLQvh4feXGVJcMOpz0TKgYmyax+W3DE6M\ne+Az1JplUELo6crgLCSapA63SK85PEuWAcMUQg9s6MnzB/qXz95yJlzgjVMIJUyb\n9jFdq2s0gefTpK2cKeSYWQAFPd41Ea5v/3j0LN8qs/dImNnzxDXu+hi8+16/4PTK\npl+1bJXwE9YkWPdd39EfjVkk6q/HyFijK3VpHnOy7n3iaJTUKwBJLRsFrQ5Eor3U\nvNKyGXECgYEA3RZdFC6MRBAo76GKd9axbA0G9Bmct9pQT4B+od2AGGOdiYzYRWfF\nlyTgctY9dcfsX5DBQFUHNnYXMHHI0wHQk1m20UpFLa7IV3RWkW5JwYkbQHmeP4pn\np8GtJEXC+4PrT0Pc32acfWozArokUju7nLLazCPCDdfc8t9MPX1W230CgYEA2MbB\ndwdwLZx9zEqZ0MciRxjsOA30b6OYPOqMP1ADVeExPN8fHLCAQjwUExQa86+FMV4H\nOtu+DXlisp+TSTRQzpXMfGppupbK1j5cqz2sU37upKuz/uf0XyeyBLOi0y9/DMl5\njG2StLLIMawRqJRUuq/fyA/6oTzADNwoW6LjCgsCgYBGvCj7lAj8nc77HEwZG2+Y\ninJ3Ftq1V/vp88qQLzYUl4qHv7BSRGlLelj1ZOY1EMnnqYCq/IlaO14f+ceu+x2o\nh0OeooyPmSQwFuC7lvWyHhPCBSdEXRvc6HJk8Iz5u7NFoQjB0SqwVZIMhVGpncLg\n17h5J9emZjIi4p6Z7cgkYQKBgHt+/8in3Cif9qrj9S0TxVtrv2dPy+mt8ZUCqlOH\nad8LI9nh4v+dLfSN9YHI+nHJlL/DKatGdMeIV8obTvVtcHvAq3ZVyVYbggL8FB8a\nS4plzd7SUwDtdDKhkrFLBX/6lw7Z2P0/j0ySbaqetJCtsHeKqpp3P/mLen3ZDsTl\nzyJxAoGBAIxl1SGzu3lO3BQ5+EPaprNw3eN3nzG4WLQvnzZwpeAFS+E5pllMkIfs\nu01Vfv68NC4u6LFgdXSY1vQt6hiA5TNqQk0TyVfFAunbXgTekF6XqDPQUf1nq9aZ\nlMvo4vlaLDKBkhG5HJE/pIa0iB+RMZLS0GhxsIWerEDmYdHKM25o\n-----END RSA PRIVATE KEY-----\n","uri":"https://api.opscode.com/organizations/jclouds/clients/adriancole-jcloudstest","certificate":"-----BEGIN CERTIFICATE-----\nMIIClzCCAgCgAwIBAgIBATANBgkqhkiG9w0BAQUFADCBnjELMAkGA1UEBhMCVVMx\nEzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxFjAUBgNVBAoM\nDU9wc2NvZGUsIEluYy4xHDAaBgNVBAsME0NlcnRpZmljYXRlIFNlcnZpY2UxMjAw\nBgNVBAMMKW9wc2NvZGUuY29tL2VtYWlsQWRkcmVzcz1hdXRoQG9wc2NvZGUuY29t\nMB4XDTEwMDYwNDIzMzM0NloXDTIwMDYwMTIzMzM0NlowADCCASIwDQYJKoZIhvcN\nAQEBBQADggEPADCCAQoCggEBALs2hOms4FMcBEl9awhnSecaXa3NVwt9dWzhmQQh\nPDQPgqRYdqaKQgUMI6Tp5YKXXf/gvkxEpd9KI2rr1Xo/QG4CW99CZe3u3RF+Aa53\nJ49NxvpqPhuKLH+yNjwP+vvTpe8WpivRi/3LPJzm9e3EU1poU0Vu/t0a5Yv7OsM6\nkF4xo1s4M7YV7+xTjxwPO1Iyc63jwRbWu/kvAcSghtkGk8czRsrUgMvCgV/AVK0r\nefl9tkIxDEBd8wOEz7aFqf5XA0cwjHX3zGKFT2cyqiHhBUnscLzZSf6lOoW3MgMW\nm9ZWGsIylEYLzwn5VWEyMOrXhzapMr0z1/paSAFV4oElUF8CAwEAATANBgkqhkiG\n9w0BAQUFAAOBgQCTllbpWNagYjCiaU5UnjIFXn0YyNfZzqCh8SQ0Asj8MtksVbFG\nAErp03+Cb9a7GTdNE7fIyPsLTnGzFhqTwKN+3jIj4wgxhrbYXF73x1+rDRyHjJu7\na7gdTEYZqWiAHdW47vXj69W1dB5e4vNm1F29gOSL/x7BMAyjLFWbdbKw0w==\n-----END CERTIFICATE-----\n","orgname":"jclouds} \ No newline at end of file diff --git a/chef/core/src/test/resources/node.json b/chef/core/src/test/resources/node.json deleted file mode 100644 index a367c3d4c1..0000000000 --- a/chef/core/src/test/resources/node.json +++ /dev/null @@ -1 +0,0 @@ -{"normal":{"tomcat6":{"ssl_port":8433}},"name":"adrian-jcloudstest","override":{},"default":{},"json_class":"Chef::Node","automatic":{},"run_list":["recipe[java]"],"chef_type":"node"} \ No newline at end of file diff --git a/chef/core/src/test/resources/one-recipe.sh b/chef/core/src/test/resources/one-recipe.sh deleted file mode 100755 index 5209003828..0000000000 --- a/chef/core/src/test/resources/one-recipe.sh +++ /dev/null @@ -1,70 +0,0 @@ -if [ ! -f /usr/bin/chef-client ]; then - apt-get update - apt-get install -y ruby ruby1.8-dev build-essential wget libruby-extras libruby1.8-extras - mkdir -p /tmp/bootchef - ( - cd /tmp/bootchef - wget http://rubyforge.org/frs/download.php/69365/rubygems-1.3.6.tgz - tar xvf rubygems-1.3.6.tgz - cd rubygems-1.3.6 - ruby setup.rb - cp /usr/bin/gem1.8 /usr/bin/gem - ) - rm -rf /tmp/bootchef - gem install chef ohai --no-rdoc --no-ri --verbose -fi -mkdir -p /etc/chef -cat > /etc/chef/client.rb <<'END_OF_FILE' -require 'rubygems' -require 'ohai' -o = Ohai::System.new -o.all_plugins -node_name "foo-" + o[:ipaddress] -log_level :info -log_location STDOUT -validation_client_name "fooclient" -chef_server_url "http://localhost:4000" -END_OF_FILE -cat > /etc/chef/validation.pem <<'END_OF_FILE' ------BEGIN PRIVATE KEY----- -LS0tLS1CRUdJTiBSU0EgUFJJVkFURSBLRVktLS0tLQpNSUlFcFFJQkFBS0NBUUVB -eWIyWkpKcUdtMEtLUis4bmZRSk5zU2QrRjl0WE5NVjdDZk9jVzZqc3FzOEVaZ2lW -ClIwOWhEMUlZT2o0WXFNMHFKT05sZ3lnNHhSV2V3ZFNHN1FUUGoxbEpwVkFpZGE5 -c1h5MitrenlhZ1pBMUFtME8KWmNicWI1aG9lSURnY1grZURhNzlzMHUwRG9tamNm -TzlFS2h2SExCeit6TSszUXFQUmtQVjhuWVRiZnMrSGpWegp6T1U2RDFCMFhSMytJ -UFpabDJBbldzMmQwcWhuU3RIY0RVdm5SVlEwUDQ4Mll3TjlWZ2NlT1p0cFB6MERD -S0VKCjVUeDVTVHViOGswL3p0L1ZBTUhRYWZMU3VRTUxkMnM0Wkx1T1pwdE4vL3VB -c1RteGlyZXFkMzd6KzhaVGRCYkoKOExFcEoraUNYdVNmbTVhVWg3aXc2b3h2VG9Z -MkFMNTMraksyVVFJREFRQUJBb0lCQVFEQTg4QjNpL3hXbjB2WApCVnhGYW1DWW9l -Y3VOakd3WFhrU3laZXc2MTZBK0VPQ3U0N2JoNGFUdXJkRmJZTDBZRmFBdGFXdnps -YU4yZUhnCkRiK0hEdVRlZkUyOStXa2NHazZTc2hQbWl6NVQwWE9DQUlDV3c2d1NW -RGtIbUd3UzRqWnZiQUZtN1c4bndHazkKWWh4Z3hGaVJuZ3N3SlpGb3BPTG9GNVdY -czJ0ZDhndUlZTnNsTXBvN3R1NTBpRm5CSHdLTzJac1BBazh0OW5uUwp4bERhdkty -dXltRW1xSENyMytkdGlvNWVhZW5KY3AzZmpvWEJRT0tVazNpcElJMjlYUkI4TnFl -Q1ZWLzdLeHdxCmNrcU9CRWJSd0JjbGNreUliRCtSaUFnS3ZPZWxPUmpFaUU5UjQy -dnVxdnhSQTZrOWtkOW83dXRsWDBBVXRwRW4KM2daYzZMZXBBb0dCQVA5YWVsNVk3 -NStzSzJKSlVOT09oTzhhZTQ1Y2RzaWxwMnlJMFgrVUJhU3VRczIrZHlQcAprcEVI -QXhkNHBtbVN2bi84YzlUbEVaaHIrcVliQUJYVlBsRG5jeHBJdXcyQWpiazdzL1M0 -WGFTS3NScXBYTDU3CnpqL1FPcUxrUms4K09WVjlxNmxNZVFOcUx0RWoxdTZKUHZp -WDcwUm8rRlF0UnR0Tk9ZYmZkUC9mQW9HQkFNcEEKWGpSNXdvVjVzVWIrUkVnOXZF -dVlvOFJTeU9hcnhxS0ZDSVhWVU5zTE94KzIyK0FLNCtDUXBidWVXTjdqb3RybApZ -RDZ1VDZzdldpM0FBQzdraVkwVUkvZmpWUFJDVWk4dFZvUVVFMFRhVTVWTElUYVlP -QitXL2JCYURFNE05NTYwCjFOdURXTzkwYmFBNWRmVTQ0aXV6dmEwMnJHSlhLOStu -UzNvOG5rL1BBb0dCQUxPTDZkam5EZTRtd0FhRzZKY28KY2Q0eHI4amt5UHpDUlp1 -eUJDU0Jid3BoSVVYTGM3aERwclBreTA2NG5jSkQxVURtd0lka1hkL2ZwTWtnMlFt -QQovQ1VrNkxFRmpNaXNxSG9qT2FDTDlnUVpKUGhMTjVRVU4yeDFQSldHanMxdlFo -OFRreDBpVVVDT2E4YlFQWE5SCiszNE9Uc1c2VFVuYTRDU1pBeWNMZmhmZkFvR0JB -SWdnVnNlZkJDdnVRa0YwTmVVaG1EQ1JaZmhuZDh5NTVSSFIKMUhDdnFLSWxwdity -aGNYL3pteUJMdXRlb3BZeVJKUnNPaUUyRlcwMGk4K3JJUFJ1NFozUTVueWJ4N3cz -UHpWOQpvSE41UjViYUU5T3lJNEtwWld6dHBZWWl0WkY2N05jbkF2VlVMSEhPdlZK -UUduS1lmTEhKWW1ySkY3R0Exb2pNCkF1TWRGYmpGQW9HQVB4VWh4d0Z5OGdhcUJh -aEtVRVpuNEY4MUhGUDVpaEdoa1Q0UUw2QUZQTzJlK0poSUdqdVIKMjcrODVoY0Zx -UStISFZ0RnNtODFiL2ErUjdQNFV1Q1JnYzhlQ2p4UU1vSjFYbDRuN1ZialBiSE1u -SU4wUnl2ZApPNFpwV0RXWW5DTzAyMUpUT1VVT0o0Si95MDQxNkJ2a3cwejU5eTdz -Tlg3d0RCQkhIYksvWENjPQotLS0tLUVORCBSU0EgUFJJVkFURSBLRVktLS0tLQo= ------END PRIVATE KEY----- -END_OF_FILE -cat > /etc/chef/first-boot.json <<'END_OF_FILE' -{"run_list":["recipe[apache2]"]} -END_OF_FILE -chef-client -j /etc/chef/first-boot.json diff --git a/chef/core/src/test/resources/privkey.txt b/chef/core/src/test/resources/privkey.txt deleted file mode 100644 index 43be3f786a..0000000000 --- a/chef/core/src/test/resources/privkey.txt +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIEpAIBAAKCAQEA0ueqo76MXuP6XqZBILFziH/9AI7C6PaN5W0dSvkr9yInyGHS -z/IR1+4tqvP2qlfKVKI4CP6BFH251Ft9qMUBuAsnlAVQ1z0exDtIFFOyQCdR7iXm -jBIWMSS4buBwRQXwDK7id1OxtU23qVJv+xwEV0IzaaSJmaGLIbvRBD+qatfUuQJB -MU/04DdJIwvLtZBYdC2219m5dUBQaa4bimL+YN9EcsDzD9h9UxQo5ReK7b3cNMzJ -BKJWLzFBcJuePMzAnLFktr/RufX4wpXe6XJxoVPaHo72GorLkwnQ0HYMTY8rehT4 -mDi1FI969LHCFFaFHSAaRnwdXaQkJmSfcxzCYQIDAQABAoIBAQCW3I4sKN5B9jOe -xq/pkeWBq4OvhW8Ys1yW0zFT8t6nHbB1XrwscQygd8gE9BPqj3e0iIEqtdphbPmj -VHqTYbC0FI6QDClifV7noTwTBjeIOlgZ0NSUN0/WgVzIOxUz2mZ2vBZUovKILPqG -TOi7J7RXMoySMdcXpP1f+PgvYNcnKsT72UcWaSXEV8/zo+Zm/qdGPVWwJonri5Mp -DVm5EQSENBiRyt028rU6ElXORNmoQpVjDVqZ1gipzXkifdjGyENw2rt4V/iKYD7V -5iqXOsvP6Cemf4gbrjunAgDG08S00kiUgvVWcdXW+dlsR2nCvH4DOEe3AYYh/aH8 -DxEE7FbtAoGBAPcNO8fJ56mNw0ow4Qg38C+Zss/afhBOCfX4O/SZKv/roRn5+gRM -KRJYSVXNnsjPI1plzqR4OCyOrjAhtuvL4a0DinDzf1+fiztyNohwYsW1vYmqn3ti -EN0GhSgE7ppZjqvLQ3f3LUTxynhA0U+k9wflb4irIlViTUlCsOPkrNJDAoGBANqL -Q+vvuGSsmRLU/Cenjy+Mjj6+QENg51dz34o8JKuVKIPKU8pNnyeLa5fat0qD2MHm -OB9opeQOcw0dStodxr6DB3wi83bpjeU6BWUGITNiWEaZEBrQ0aiqNJJKrrHm8fAZ -9o4l4oHc4hI0kYVYYDuxtKuVJrzZiEapTwoOcYiLAoGBAI/EWbeIHZIj9zOjgjEA -LHvm25HtulLOtyk2jd1njQhlHNk7CW2azIPqcLLH99EwCYi/miNH+pijZ2aHGCXb -/bZrSxM0ADmrZKDxdB6uGCyp+GS2sBxjEyEsfCyvwhJ8b3Q100tqwiNO+d5FCglp -HICx2dgUjuRVUliBwOK93nx1AoGAUI8RhIEjOYkeDAESyhNMBr0LGjnLOosX+/as -qiotYkpjWuFULbibOFp+WMW41vDvD9qrSXir3fstkeIAW5KqVkO6mJnRoT3Knnra -zjiKOITCAZQeiaP8BO5o3pxE9TMqb9VCO3ffnPstIoTaN4syPg7tiGo8k1SklVeH -2S8lzq0CgYAKG2fljIYWQvGH628rp4ZcXS4hWmYohOxsnl1YrszbJ+hzR+IQOhGl -YlkUQYXhy9JixmUUKtH+NXkKX7Lyc8XYw5ETr7JBT3ifs+G7HruDjVG78EJVojbd -8uLA+DdQm5mg4vd1GTiSK65q/3EeoBlUaVor3HhLFki+i9qpT8CBsg== ------END RSA PRIVATE KEY----- \ No newline at end of file diff --git a/chef/core/src/test/resources/pubkey.txt b/chef/core/src/test/resources/pubkey.txt deleted file mode 100644 index 886a471d15..0000000000 --- a/chef/core/src/test/resources/pubkey.txt +++ /dev/null @@ -1,9 +0,0 @@ ------BEGIN PUBLIC KEY----- -MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0ueqo76MXuP6XqZBILFz -iH/9AI7C6PaN5W0dSvkr9yInyGHSz/IR1+4tqvP2qlfKVKI4CP6BFH251Ft9qMUB -uAsnlAVQ1z0exDtIFFOyQCdR7iXmjBIWMSS4buBwRQXwDK7id1OxtU23qVJv+xwE -V0IzaaSJmaGLIbvRBD+qatfUuQJBMU/04DdJIwvLtZBYdC2219m5dUBQaa4bimL+ -YN9EcsDzD9h9UxQo5ReK7b3cNMzJBKJWLzFBcJuePMzAnLFktr/RufX4wpXe6XJx -oVPaHo72GorLkwnQ0HYMTY8rehT4mDi1FI969LHCFFaFHSAaRnwdXaQkJmSfcxzC -YQIDAQAB ------END PUBLIC KEY----- \ No newline at end of file diff --git a/chef/core/src/test/resources/sandbox.json b/chef/core/src/test/resources/sandbox.json deleted file mode 100644 index 640f2a1fea..0000000000 --- a/chef/core/src/test/resources/sandbox.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "_rev": "1-8c27b0ea4c2b7aaedbb44cfbdfcc11b2", - "json_class": "Chef::Sandbox", - "is_completed": false, - "create_time": "2010-07-07T03:36:00+00:00", - "chef_type": "sandbox", - "checksums": [], - "name": "f9d6d9b72bae465890aae87969f98a9c", - "guid": "f9d6d9b72bae465890aae87969f98a9c" - } - - diff --git a/chef/core/src/test/resources/tomcat-cookbook.json b/chef/core/src/test/resources/tomcat-cookbook.json deleted file mode 100644 index 6331b514ac..0000000000 --- a/chef/core/src/test/resources/tomcat-cookbook.json +++ /dev/null @@ -1 +0,0 @@ -{"definitions":[],"name":"tomcat6-0.1.0","files":[{"name":"org.apache.tomcat.tomcat6.plist","url":"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-18e534a72652f3d53b197ca4e5027009?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277771874&Signature=M3fBL4t7uuYVXVah2PyZ8eL1QCc%3D","checksum":"18e534a72652f3d53b197ca4e5027009","path":"files/default/org.apache.tomcat.tomcat6.plist","specificity":"default"},{"name":"logging.properties","url":"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-6a35ce92050296862ea63b784529d2e0?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277771874&Signature=vRlKoye2%2Fwz8mdQI%2F3Ht916sllE%3D","checksum":"6a35ce92050296862ea63b784529d2e0","path":"files/default/logging.properties","specificity":"default"}],"attributes":[{"name":"tomcat6.rb","url":"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-6e3fd0d16a87a55c569da108194ecb29?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277771874&Signature=zvYjsgUXIC7Xj3MT8Wd93esDGJM%3D","checksum":"6e3fd0d16a87a55c569da108194ecb29","path":"attributes/tomcat6.rb","specificity":"default"}],"json_class":"Chef::CookbookVersion","providers":[],"metadata":{"dependencies":{},"name":"tomcat6","maintainer_email":"cookbooks@opscode.com","license":"Apache 2.0","attributes":{"tomcat6/with_native":{"required":"optional","calculated":false,"default":"false","choice":[],"type":"string","recipes":[],"display_name":"Tomcat native support","description":"works for centos, install tomcat-native libraries"}},"maintainer":"Opscode, Inc.","suggestions":{},"platforms":{"debian":[],"centos":[],"ubuntu":[],"redhat":[]},"long_description":"= DESCRIPTION:\n\nInstalls Tomcat6\n\n= REQUIREMENTS:\n\n== Platform and Application Environment:\n\nTested on Centos 5.2 8.10. May work on other platforms, esp Redhat.\nNeeds Java at least Java 5\n\n== Cookbooks:\n\nOpscode cookbooks, http://github.com/opscode/cookbooks/tree/master:\n\n* java\n\n= ATTRIBUTES: \n\n= USAGE:\n\n\n= LICENSE and AUTHOR:\n \nAuthor:: Edmund Haselwanter ()\nCopyright:: 2009, Edmund Haselwanter\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n","version":"0.1.0","recommendations":{},"conflicting":{},"recipes":{"tomcat6":"Main Tomcat 6 configuration"},"groupings":{},"description":"Installs and configures all aspects of tomcat6 using custom local installation","replacing":{},"providing":{}},"libraries":[{"name":"tomcat_manager.rb","url":"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-2b6f7847142bb36823c570899669c54b?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277771874&Signature=zxIoUKcGYWo9ir6qf1tTy3wvKZ4%3D","checksum":"2b6f7847142bb36823c570899669c54b","path":"libraries/tomcat_manager.rb","specificity":"default"},{"name":"tomcat.rb","url":"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-24db7b7dd6f04f8da5fa2b282910ac08?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277771874&Signature=c4Gbn5kX0ZaPbWvk5LAcR77sITg%3D","checksum":"24db7b7dd6f04f8da5fa2b282910ac08","path":"libraries/tomcat.rb","specificity":"default"}],"templates":[{"name":"tomcat-users.xml.erb","url":"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-107263b81e4700cf0adad7af2a133bbd?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277771874&Signature=QC7MNIauR2ox5MVlohf2i73uM1s%3D","checksum":"107263b81e4700cf0adad7af2a133bbd","path":"templates/default/tomcat-users.xml.erb","specificity":"default"},{"name":"sv-tomcat6-run.erb","url":"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-fa4432b353fa57b9da26a4bff44285f2?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277771874&Signature=q2rDeJFeh4oyhfv9ExMifGB0wxo%3D","checksum":"fa4432b353fa57b9da26a4bff44285f2","path":"templates/default/sv-tomcat6-run.erb","specificity":"default"},{"name":"manager.xml.erb","url":"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-33fd6f63133e7ebe28bc62e58773c408?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277771874&Signature=rIijEhwLPf5PWTJOg%2BElbOquPBM%3D","checksum":"33fd6f63133e7ebe28bc62e58773c408","path":"templates/default/manager.xml.erb","specificity":"default"},{"name":"sv-tomcat6-log-run.erb","url":"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-09f2bf988663175cd1b7973198dfb5eb?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277771874&Signature=UnfNDP4pDzPM3PoLcLWyTnTa%2FKI%3D","checksum":"09f2bf988663175cd1b7973198dfb5eb","path":"templates/default/sv-tomcat6-log-run.erb","specificity":"default"}],"resources":[],"cookbook_name":"tomcat6","version":"0.1.0","recipes":[{"name":"default.rb","url":"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-d45661e4b50f9677de7b8684af26ff9d?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277771874&Signature=r3CvyVe7dcOzB%2F0fNAun5ldGwr8%3D","checksum":"d45661e4b50f9677de7b8684af26ff9d","path":"recipes/default.rb","specificity":"default"}],"root_files":[{"name":"README.rdoc","url":"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-14f6977f68c3674484e8289e361fb5a4?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277771874&Signature=VNZxN%2B7CxO7ZbDHJOS%2FaTtpkPaE%3D","checksum":"14f6977f68c3674484e8289e361fb5a4","path":"README.rdoc","specificity":"default"},{"name":"metadata.rb","url":"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-abc416ffba9ea64ca71635191cb87af6?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277771874&Signature=pemynt9Q1F%2BxlS26kLaz%2F4NDGO4%3D","checksum":"abc416ffba9ea64ca71635191cb87af6","path":"metadata.rb","specificity":"default"},{"name":"metadata.json","url":"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-dd8473a8a7f2b446250ecdefb1882a5e?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277771874&Signature=sHpayqP%2Fe4Luv20EMa3q%2FaMN4ms%3D","checksum":"dd8473a8a7f2b446250ecdefb1882a5e","path":"metadata.json","specificity":"default"}],"chef_type":"cookbook_version"} \ No newline at end of file diff --git a/chef/core/src/test/resources/upload-site.json b/chef/core/src/test/resources/upload-site.json deleted file mode 100644 index 58bf1656a6..0000000000 --- a/chef/core/src/test/resources/upload-site.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "uri": "https://api.opscode.com/organizations/jclouds/sandboxes/d454f71e2a5f400c808d0c5d04c2c88c", - "checksums": { - "0c5ecd7788cf4f6c7de2a57193897a6c": { - "url": "https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/sandbox-d454f71e2a5f400c808d0c5d04c2c88c/checksum-0c5ecd7788cf4f6c7de2a57193897a6c?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277344702&Signature=FtKyqvYEjhhEKmRY%2B0M8aGPMM7g%3D", - "needs_upload": true - }, "0189e76ccc476701d6b374e5a1a27347": { - "needs_upload": false - }, "1dda05ed139664f1f89b9dec482b77c0": { - "needs_upload": false - } - }, "sandbox_id": "d454f71e2a5f400c808d0c5d04c2c88c" -} \ No newline at end of file diff --git a/chef/pom.xml b/chef/pom.xml deleted file mode 100644 index 05b43def2d..0000000000 --- a/chef/pom.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - jclouds-project - org.jclouds - 1.0-SNAPSHOT - ../project/pom.xml - - 4.0.0 - jclouds-chef-project - pom - jclouds chef project - - core - servlet - compute - - diff --git a/chef/servlet/pom.xml b/chef/servlet/pom.xml deleted file mode 100644 index 886c50736d..0000000000 --- a/chef/servlet/pom.xml +++ /dev/null @@ -1,71 +0,0 @@ - - - - 4.0.0 - - org.jclouds - jclouds-chef-project - 1.0-SNAPSHOT - ../pom.xml - - org.jclouds - jclouds-chef-servlet - jclouds chef servlet components - jclouds components to access chef from a servlet container - - - - - jclouds-googlecode-deploy - http://jclouds.googlecode.com/svn/repo - - - jclouds-rimu-snapshots-nexus - https://oss.sonatype.org/content/repositories/snapshots - - true - - - - - - - ${project.groupId} - jclouds-chef - ${project.version} - - - ${project.groupId} - jclouds-core - ${project.version} - test-jar - test - - - org.apache.geronimo.specs - geronimo-servlet_2.5_spec - 1.2 - provided - - - diff --git a/chef/servlet/src/main/java/org/jclouds/chef/servlet/ChefRegistrationListener.java b/chef/servlet/src/main/java/org/jclouds/chef/servlet/ChefRegistrationListener.java deleted file mode 100644 index a3f8b3bf41..0000000000 --- a/chef/servlet/src/main/java/org/jclouds/chef/servlet/ChefRegistrationListener.java +++ /dev/null @@ -1,142 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.servlet; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.collect.Sets.newHashSet; -import static java.util.Collections.singleton; -import static org.jclouds.chef.reference.ChefConstants.CHEF_NODE; -import static org.jclouds.chef.reference.ChefConstants.CHEF_NODE_PATTERN; -import static org.jclouds.chef.reference.ChefConstants.CHEF_RUN_LIST; -import static org.jclouds.chef.reference.ChefConstants.CHEF_SERVICE_CLIENT; - -import java.util.Properties; -import java.util.Set; - -import javax.servlet.ServletContext; -import javax.servlet.ServletContextEvent; -import javax.servlet.ServletContextListener; - -import org.jclouds.chef.ChefContextFactory; -import org.jclouds.chef.ChefService; -import org.jclouds.chef.domain.Node; -import org.jclouds.chef.reference.ChefConstants; -import org.jclouds.chef.servlet.functions.InitParamsToProperties; -import org.jclouds.logging.Logger; -import org.jclouds.logging.jdk.JDKLogger; - -import com.google.common.base.Splitter; -import com.google.common.collect.ImmutableSet; -import com.google.inject.AbstractModule; - -/** - * Registers a new node in Chef and binds its name to - * {@link ChefConstants.CHEF_NODE}, its role to {@link ChefConstants.CHEF_ROLE} - * and the {@link ChefService} for the client to - * {@link ChefConstants.CHEF_SERVICE_CLIENT} upon initialized. Deletes the node - * and client when the context is destroyed. - * - * @author Adrian Cole - */ -public class ChefRegistrationListener implements ServletContextListener { - - private Logger logger = new JDKLogger.JDKLoggerFactory().getLogger(ChefRegistrationListener.class.getName()); - - @Override - public void contextInitialized(ServletContextEvent servletContextEvent) { - try { - logger.debug("starting initialization"); - Properties overrides = InitParamsToProperties.INSTANCE.apply(servletContextEvent.getServletContext()); - - logger.trace("creating client connection"); - - ChefService client = createService(overrides, servletContextEvent); - logger.debug("created client connection"); - - Node node; - String nodeName; - while (true) { - nodeName = findNextNodeName(client, getInitParam(servletContextEvent, CHEF_NODE_PATTERN)); - try { - node = client.createNodeAndPopulateAutomaticAttributes(nodeName, Splitter.on(',').split( - getInitParam(servletContextEvent, CHEF_RUN_LIST))); - break; - } catch (IllegalStateException ex) { - logger.debug("client already exists %s: %s", nodeName, ex.getMessage()); - } - } - - servletContextEvent.getServletContext().setAttribute(CHEF_NODE, node); - servletContextEvent.getServletContext().setAttribute(CHEF_SERVICE_CLIENT, client); - logger.debug("initialized"); - } catch (RuntimeException e) { - logger.error(e, "error registering"); - throw e; - } - } - - private String findNextNodeName(ChefService client, String pattern) { - Set nodes = client.getContext().getApi().listNodes(); - String nodeName; - Set names = newHashSet(nodes); - int index = 0; - while (true) { - nodeName = String.format(pattern, index++); - if (!names.contains(nodeName)) - break; - } - return nodeName; - } - - private ChefService createService(Properties props, final ServletContextEvent servletContextEvent) { - return new ChefContextFactory().createContext(ImmutableSet.of(new AbstractModule() { - - @Override - protected void configure() { - bind(ServletContext.class).toInstance(servletContextEvent.getServletContext()); - } - - }), props).getChefService(); - } - - private static String getInitParam(ServletContextEvent servletContextEvent, String name) { - return checkNotNull(servletContextEvent.getServletContext().getInitParameter(name)); - } - - @SuppressWarnings("unchecked") - private static T getContextAttributeOrNull(ServletContextEvent servletContextEvent, String name) { - return (T) servletContextEvent.getServletContext().getAttribute(name); - } - - /** - * removes the node and client if found, and closes the client context. - */ - @Override - public void contextDestroyed(ServletContextEvent servletContextEvent) { - ChefService client = getContextAttributeOrNull(servletContextEvent, CHEF_SERVICE_CLIENT); - Node node = getContextAttributeOrNull(servletContextEvent, CHEF_NODE); - if (node != null && client != null) { - client.deleteAllNodesInList(singleton(node.getName())); - } - if (client != null) { - client.getContext().close(); - } - } -} \ No newline at end of file diff --git a/chef/servlet/src/main/java/org/jclouds/chef/servlet/functions/InitParamsToProperties.java b/chef/servlet/src/main/java/org/jclouds/chef/servlet/functions/InitParamsToProperties.java deleted file mode 100644 index e98d857112..0000000000 --- a/chef/servlet/src/main/java/org/jclouds/chef/servlet/functions/InitParamsToProperties.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.servlet.functions; - -import java.util.Enumeration; -import java.util.Properties; - -import javax.inject.Singleton; -import javax.servlet.ServletContext; - -import com.google.common.base.Function; - -/** - * - * @author Adrian Cole - */ -@Singleton -public class InitParamsToProperties implements Function { - - public static final InitParamsToProperties INSTANCE = new InitParamsToProperties(); - - public Properties apply(ServletContext servletContext) { - Properties overrides = new Properties(); - Enumeration e = servletContext.getInitParameterNames(); - while (e.hasMoreElements()) { - String propertyName = e.nextElement().toString(); - overrides.setProperty(propertyName, servletContext.getInitParameter(propertyName)); - } - return overrides; - } -} \ No newline at end of file diff --git a/chef/servlet/src/main/java/org/jclouds/ohai/servlet/config/ServletOhaiModule.java b/chef/servlet/src/main/java/org/jclouds/ohai/servlet/config/ServletOhaiModule.java deleted file mode 100644 index 866a4d0189..0000000000 --- a/chef/servlet/src/main/java/org/jclouds/ohai/servlet/config/ServletOhaiModule.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.ohai.servlet.config; - - -import static org.jclouds.chef.util.ChefUtils.ohaiAutomaticAttributeBinder; - -import org.jclouds.domain.JsonBall; -import org.jclouds.ohai.config.multibindings.MapBinder; -import org.jclouds.ohai.servlet.suppliers.ServletContextInfoSupplier; - -import com.google.common.base.Supplier; -import com.google.inject.AbstractModule; - -/** - * Wires the components needed to parse ohai data - * - * @author Adrian Cole - */ -public class ServletOhaiModule extends AbstractModule { - - @Override - protected void configure() { - MapBinder> mapbinder = ohaiAutomaticAttributeBinder(binder()); - mapbinder.addBinding("webapp").to(ServletContextInfoSupplier.class); - } - -} \ No newline at end of file diff --git a/chef/servlet/src/main/java/org/jclouds/ohai/servlet/suppliers/ServletContextInfoSupplier.java b/chef/servlet/src/main/java/org/jclouds/ohai/servlet/suppliers/ServletContextInfoSupplier.java deleted file mode 100644 index 4637b12978..0000000000 --- a/chef/servlet/src/main/java/org/jclouds/ohai/servlet/suppliers/ServletContextInfoSupplier.java +++ /dev/null @@ -1,50 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.ohai.servlet.suppliers; - -import javax.inject.Inject; -import javax.inject.Singleton; -import javax.servlet.ServletContext; - -import org.jclouds.chef.servlet.functions.InitParamsToProperties; -import org.jclouds.json.Json; - -/** - * - * @author Adrian Cole - */ -@Singleton -public class ServletContextInfoSupplier extends ServletContextSupplier { - private final InitParamsToProperties converter; - private final Json json; - - @Inject - public ServletContextInfoSupplier(ServletContext servletContext, InitParamsToProperties converter, Json json) { - super(servletContext); - this.converter = converter; - this.json = json; - } - - @Override - protected String provideJson(ServletContext servletContext) { - return String.format("{\"server_info\":\"%s\",\"init_params\":%s}", servletContext.getServerInfo(), json - .toJson(converter.apply(servletContext))); - } -} \ No newline at end of file diff --git a/chef/servlet/src/main/java/org/jclouds/ohai/servlet/suppliers/ServletContextSupplier.java b/chef/servlet/src/main/java/org/jclouds/ohai/servlet/suppliers/ServletContextSupplier.java deleted file mode 100644 index 291e2e1f43..0000000000 --- a/chef/servlet/src/main/java/org/jclouds/ohai/servlet/suppliers/ServletContextSupplier.java +++ /dev/null @@ -1,52 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.ohai.servlet.suppliers; - -import javax.inject.Inject; -import javax.inject.Singleton; -import javax.servlet.ServletContext; - -import org.jclouds.domain.JsonBall; - -import com.google.common.base.Supplier; - -/** - * - * @author Adrian Cole - */ -@Singleton -public abstract class ServletContextSupplier implements Supplier { - private final ServletContext servletContext; - - @Inject - public ServletContextSupplier(ServletContext servletContext) { - this.servletContext = servletContext; - } - - @Override - public JsonBall get() { - String path = servletContext.getContextPath(); - if (path == null || path.equals("")) - path = "/"; - return new JsonBall(String.format("{\"%s\":%s}", path, provideJson(servletContext))); - } - - protected abstract String provideJson(ServletContext servletContext); -} \ No newline at end of file diff --git a/chef/servlet/src/test/java/org/jclouds/chef/servlet/suppliers/ServletContextInfoSupplierTest.java b/chef/servlet/src/test/java/org/jclouds/chef/servlet/suppliers/ServletContextInfoSupplierTest.java deleted file mode 100644 index 93ecce72ed..0000000000 --- a/chef/servlet/src/test/java/org/jclouds/chef/servlet/suppliers/ServletContextInfoSupplierTest.java +++ /dev/null @@ -1,157 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.chef.servlet.suppliers; - -import static org.easymock.EasyMock.expect; -import static org.easymock.classextension.EasyMock.createMock; -import static org.easymock.classextension.EasyMock.replay; -import static org.testng.Assert.assertEquals; - -import java.util.Properties; - -import javax.servlet.ServletContext; - -import org.jclouds.chef.servlet.functions.InitParamsToProperties; -import org.jclouds.json.Json; -import org.jclouds.json.config.GsonModule; -import org.jclouds.ohai.servlet.config.ServletOhaiModule; -import org.jclouds.ohai.servlet.suppliers.ServletContextInfoSupplier; -import org.testng.annotations.Test; - -import com.google.inject.Guice; -import com.google.inject.Injector; -import com.google.inject.Provides; - -/** - * - * @author Adrian Cole - */ - -@Test(groups = "unit", testName = "chef.ServletContextInfoSupplierTest") -public class ServletContextInfoSupplierTest { - - @Test - public void testApply() { - - final ServletContext servletContext = createMock(ServletContext.class); - final InitParamsToProperties converter = createMock(InitParamsToProperties.class); - Properties props = new Properties(); - props.setProperty("foo", "bar"); - - expect(servletContext.getContextPath()).andReturn("path"); - expect(servletContext.getServerInfo()).andReturn("serverinfo"); - expect(converter.apply(servletContext)).andReturn(props); - - replay(servletContext); - replay(converter); - - Injector injector = Guice.createInjector(new GsonModule(), new ServletOhaiModule() { - @SuppressWarnings("unused") - @Provides - protected ServletContext provideServletContext() { - return servletContext; - } - - @SuppressWarnings("unused") - @Provides - protected InitParamsToProperties provideInitParamsToProperties() { - return converter; - } - }); - - Json json = injector.getInstance(Json.class); - ServletContextInfoSupplier ohai = injector.getInstance(ServletContextInfoSupplier.class); - assertEquals(json.toJson(ohai.get()), - "{\"path\":{\"server_info\":\"serverinfo\",\"init_params\":{\"foo\":\"bar\"}}}"); - - } - - @Test - public void testApplyNullPath() { - - final ServletContext servletContext = createMock(ServletContext.class); - final InitParamsToProperties converter = createMock(InitParamsToProperties.class); - Properties props = new Properties(); - props.setProperty("foo", "bar"); - - expect(servletContext.getContextPath()).andReturn(null); - expect(servletContext.getServerInfo()).andReturn("serverinfo"); - expect(converter.apply(servletContext)).andReturn(props); - - replay(servletContext); - replay(converter); - - Injector injector = Guice.createInjector(new GsonModule(), new ServletOhaiModule() { - @SuppressWarnings("unused") - @Provides - protected ServletContext provideServletContext() { - return servletContext; - } - - @SuppressWarnings("unused") - @Provides - protected InitParamsToProperties provideInitParamsToProperties() { - return converter; - } - }); - - Json json = injector.getInstance(Json.class); - ServletContextInfoSupplier ohai = injector.getInstance(ServletContextInfoSupplier.class); - assertEquals(json.toJson(ohai.get()), - "{\"/\":{\"server_info\":\"serverinfo\",\"init_params\":{\"foo\":\"bar\"}}}"); - - } - - @Test - public void testApplyEmptyPath() { - - final ServletContext servletContext = createMock(ServletContext.class); - final InitParamsToProperties converter = createMock(InitParamsToProperties.class); - Properties props = new Properties(); - props.setProperty("foo", "bar"); - - expect(servletContext.getContextPath()).andReturn(""); - expect(servletContext.getServerInfo()).andReturn("serverinfo"); - expect(converter.apply(servletContext)).andReturn(props); - - replay(servletContext); - replay(converter); - - Injector injector = Guice.createInjector(new GsonModule(), new ServletOhaiModule() { - @SuppressWarnings("unused") - @Provides - protected ServletContext provideServletContext() { - return servletContext; - } - - @SuppressWarnings("unused") - @Provides - protected InitParamsToProperties provideInitParamsToProperties() { - return converter; - } - }); - - Json json = injector.getInstance(Json.class); - ServletContextInfoSupplier ohai = injector.getInstance(ServletContextInfoSupplier.class); - assertEquals(json.toJson(ohai.get()), - "{\"/\":{\"server_info\":\"serverinfo\",\"init_params\":{\"foo\":\"bar\"}}}"); - - } -} diff --git a/opscodeplatform/pom.xml b/opscodeplatform/pom.xml deleted file mode 100644 index e221246bc7..0000000000 --- a/opscodeplatform/pom.xml +++ /dev/null @@ -1,101 +0,0 @@ - - - - 4.0.0 - - org.jclouds - jclouds-project - 1.0-SNAPSHOT - ../project/pom.xml - - org.jclouds - jclouds-opscodeplatform - jclouds Opscode Platform core - jclouds components to access Opscode Platform - - - scm:svn:http://jclouds.googlecode.com/svn/trunk/opscodeplatform - scm:svn:https://jclouds.googlecode.com/svn/trunk/opscodeplatform - http://jclouds.googlecode.com/svn/trunk/opscodeplatform - - - - - - jclouds-googlecode-deploy - http://jclouds.googlecode.com/svn/repo - - - jclouds-rimu-snapshots-nexus - https://oss.sonatype.org/content/repositories/snapshots - - true - - - - - - MYORG - /etc/chef/validation.pem - ${jclouds.opscodeplatform.org} - ${jclouds.opscodeplatform.rsa-key} - - - - ${project.groupId} - jclouds-chef - ${project.version} - - - ${project.groupId} - jclouds-chef - ${project.version} - test-jar - test - - - ${project.groupId} - jclouds-core - ${project.version} - test-jar - test - - - log4j - log4j - 1.2.14 - test - - - ${project.groupId} - jclouds-log4j - ${project.version} - test - - - diff --git a/opscodeplatform/src/main/java/org/jclouds/opscodeplatform/OpscodePlatformAsyncClient.java b/opscodeplatform/src/main/java/org/jclouds/opscodeplatform/OpscodePlatformAsyncClient.java deleted file mode 100644 index 2ab6a705b7..0000000000 --- a/opscodeplatform/src/main/java/org/jclouds/opscodeplatform/OpscodePlatformAsyncClient.java +++ /dev/null @@ -1,170 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.opscodeplatform; - -import java.util.Set; - -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.HEAD; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.core.MediaType; - -import org.jclouds.chef.ChefAsyncClient; -import org.jclouds.chef.ChefClient; -import org.jclouds.chef.filters.SignedHeaderAuth; -import org.jclouds.chef.functions.ParseKeySetFromJson; -import org.jclouds.opscodeplatform.config.OrganizationName; -import org.jclouds.opscodeplatform.config.Username; -import org.jclouds.opscodeplatform.domain.Organization; -import org.jclouds.opscodeplatform.domain.User; -import org.jclouds.rest.annotations.BinderParam; -import org.jclouds.rest.annotations.ExceptionParser; -import org.jclouds.rest.annotations.Headers; -import org.jclouds.rest.annotations.ParamParser; -import org.jclouds.rest.annotations.RequestFilters; -import org.jclouds.rest.annotations.ResponseParser; -import org.jclouds.rest.binders.BindToJsonPayload; -import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404; -import org.jclouds.rest.functions.ReturnFalseOnNotFoundOr404; -import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; - -import com.google.common.util.concurrent.ListenableFuture; - -/** - * Provides asynchronous access to the Opscode Platform via their REST API. - *

- * - * @see OpscodePlatformClient - * @see - * @author Adrian Cole - */ -@RequestFilters(SignedHeaderAuth.class) -@Consumes(MediaType.APPLICATION_JSON) -@Headers(keys = "X-Chef-Version", values = ChefAsyncClient.VERSION) -public interface OpscodePlatformAsyncClient { - - /** - * @see ChefUser#listUsers - */ - @GET - @Path("/users") - @ResponseParser(ParseKeySetFromJson.class) - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listUsers(); - - /** - * @see ChefRole#userExists - */ - @HEAD - @Path("/users/{username}") - @ExceptionParser(ReturnFalseOnNotFoundOr404.class) - ListenableFuture userExists(@PathParam("username") String username); - - /** - * @see ChefClient#createUser - */ - @POST - @Path("/users") - ListenableFuture createUser(@BinderParam(BindToJsonPayload.class) User user); - - /** - * @see ChefClient#updateUser - */ - @PUT - @Path("/users/{username}") - @Consumes(MediaType.APPLICATION_JSON) - ListenableFuture updateUser( - @PathParam("username") @ParamParser(Username.class) @BinderParam(BindToJsonPayload.class) User user); - - /** - * @see ChefClient#getUser - */ - @GET - @Path("/users/{username}") - @ExceptionParser(ReturnNullOnNotFoundOr404.class) - @Consumes(MediaType.APPLICATION_JSON) - ListenableFuture getUser(@PathParam("username") String username); - - /** - * @see ChefClient#deleteUser - */ - @DELETE - @Path("/users/{username}") - @ExceptionParser(ReturnNullOnNotFoundOr404.class) - @Consumes(MediaType.APPLICATION_JSON) - ListenableFuture deleteUser(@PathParam("username") String username); - - /** - * @see ChefOrganization#listOrganizations - */ - @GET - @Path("/organizations") - @ResponseParser(ParseKeySetFromJson.class) - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listOrganizations(); - - /** - * @see ChefRole#organizationExists - */ - @HEAD - @Path("/organizations/{organizationname}") - @ExceptionParser(ReturnFalseOnNotFoundOr404.class) - ListenableFuture organizationExists(@PathParam("organizationname") String organizationname); - - /** - * @see ChefClient#createOrganization - */ - @POST - @Path("/organizations") - ListenableFuture createOrganization(@BinderParam(BindToJsonPayload.class) Organization org); - - /** - * @see ChefClient#updateOrganization - */ - @PUT - @Path("/organizations/{orgname}") - @Consumes(MediaType.APPLICATION_JSON) - ListenableFuture updateOrganization( - @PathParam("orgname") @ParamParser(OrganizationName.class) @BinderParam(BindToJsonPayload.class) Organization org); - - /** - * @see ChefClient#getOrganization - */ - @GET - @Path("/organizations/{orgname}") - @ExceptionParser(ReturnNullOnNotFoundOr404.class) - @Consumes(MediaType.APPLICATION_JSON) - ListenableFuture getOrganization(@PathParam("orgname") String orgname); - - /** - * @see ChefClient#deleteOrganization - */ - @DELETE - @Path("/organizations/{orgname}") - @ExceptionParser(ReturnNullOnNotFoundOr404.class) - @Consumes(MediaType.APPLICATION_JSON) - ListenableFuture deleteOrganization(@PathParam("orgname") String orgname); - -} diff --git a/opscodeplatform/src/main/java/org/jclouds/opscodeplatform/OpscodePlatformClient.java b/opscodeplatform/src/main/java/org/jclouds/opscodeplatform/OpscodePlatformClient.java deleted file mode 100644 index 1bc8998afc..0000000000 --- a/opscodeplatform/src/main/java/org/jclouds/opscodeplatform/OpscodePlatformClient.java +++ /dev/null @@ -1,181 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.opscodeplatform; - -import java.util.Set; -import java.util.concurrent.TimeUnit; - -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; - -import org.jclouds.chef.ChefClient; -import org.jclouds.concurrent.Timeout; -import org.jclouds.opscodeplatform.domain.Organization; -import org.jclouds.opscodeplatform.domain.User; -import org.jclouds.rest.AuthorizationException; -import org.jclouds.rest.ResourceNotFoundException; -import org.jclouds.rest.annotations.Delegate; - -/** - * Provides synchronous access to the Opscode Platform. - *

- * - * @see OpscodePlatformAsyncClient - * @see - * @author Adrian Cole - */ -@Timeout(duration = 30, timeUnit = TimeUnit.SECONDS) -public interface OpscodePlatformClient { - /** - * @return list of user names. - * - * @throws AuthorizationException - *

- * "401 Unauthorized" if you are not a recognized user. - *

- * "403 Forbidden" if you do not have rights to list users. - */ - Set listUsers(); - - /** - * - * @return true if the specified user name exists. - * - * @throws AuthorizationException - *

- * "401 Unauthorized" if you are not a recognized user. - *

- * "403 Forbidden" if you do not have rights to view the user. - */ - boolean userExists(String name); - - /** - * creates a new user - * - * @return the private key of the user. You can then use this user name and private key to access - * the Opscode API. - * @throws AuthorizationException - *

- * "401 Unauthorized" if the caller is not a recognized user. - *

- * "403 Forbidden" if the caller is not authorized to create a user. - */ - User createUser(User user); - - /** - * updates an existing user. Note: you must have update rights on the user. - * - * @throws AuthorizationException - *

- * "401 Unauthorized" if you are not a recognized user. - *

- * "403 Forbidden" if you do not have Update rights on the user. - * @throws ResourceNotFoundException - * if the user does not exist. - */ - User updateUser(User user); - - /** - * retrieves an existing user. Note: you must have update rights on the user. - * - * @return null, if the user is not found - */ - User getUser(String username); - - /** - * deletes an existing user. Note: you must have delete rights on the user. - * - * @return last state of the user you deleted or null, if not found - * @throws AuthorizationException - *

- * "401 Unauthorized" if you are not a recognized user. - *

- * "403 Forbidden" if you do not have Delete rights on the user. - */ - User deleteUser(String username); - - /** - * @return list of organization names. - * - * @throws AuthorizationException - *

- * "401 Unauthorized" if you are not a recognized user. - *

- * "403 Forbidden" if you do not have rights to list organizations. - */ - Set listOrganizations(); - - /** - * - * @return true if the specified organization name exists. - * - * @throws AuthorizationException - *

- * "401 Unauthorized" if you are not a recognized user. - *

- * "403 Forbidden" if you do not have rights to view the organization. - */ - boolean organizationExists(String name); - - /** - * creates a new organization - * - * @return the private key of the organization. You can then use this organization name and - * private key to access the Opscode API. - * @throws AuthorizationException - *

- * "401 Unauthorized" if the caller is not a recognized organization. - *

- * "403 Forbidden" if the caller is not authorized to create a organization. - */ - Organization createOrganization(Organization organization); - - /** - * updates an existing organization. Note: you must have update rights on the organization. - * - * @throws AuthorizationException - *

- * "401 Unauthorized" if you are not a recognized organization. - *

- * "403 Forbidden" if you do not have Update rights on the organization. - * @throws ResourceNotFoundException - * if the organization does not exist. - */ - Organization updateOrganization(Organization organization); - - /** - * retrieves an existing organization. Note: you must have update rights on the organization. - * - * @return null, if the organization is not found - */ - Organization getOrganization(String organizationname); - - /** - * deletes an existing organization. Note: you must have delete rights on the organization. - * - * @return last state of the org you deleted or null, if not found - * @throws AuthorizationException - *

- * "401 Unauthorized" if you are not a recognized organization. - *

- * "403 Forbidden" if you do not have Delete rights on the organization. - */ - Organization deleteOrganization(String organizationname); -} diff --git a/opscodeplatform/src/main/java/org/jclouds/opscodeplatform/OpscodePlatformContext.java b/opscodeplatform/src/main/java/org/jclouds/opscodeplatform/OpscodePlatformContext.java deleted file mode 100644 index d9fc970d21..0000000000 --- a/opscodeplatform/src/main/java/org/jclouds/opscodeplatform/OpscodePlatformContext.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.opscodeplatform; - -import org.jclouds.opscodeplatform.internal.OpscodePlatformContextImpl; -import org.jclouds.rest.RestContext; - -import com.google.inject.ImplementedBy; - -/** - * - * - * @author Adrian Cole - * - */ -@ImplementedBy(OpscodePlatformContextImpl.class) -public interface OpscodePlatformContext extends RestContext { - -} \ No newline at end of file diff --git a/opscodeplatform/src/main/java/org/jclouds/opscodeplatform/OpscodePlatformContextBuilder.java b/opscodeplatform/src/main/java/org/jclouds/opscodeplatform/OpscodePlatformContextBuilder.java deleted file mode 100644 index 794f114398..0000000000 --- a/opscodeplatform/src/main/java/org/jclouds/opscodeplatform/OpscodePlatformContextBuilder.java +++ /dev/null @@ -1,65 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.opscodeplatform; - -import java.util.List; -import java.util.Properties; - -import org.jclouds.ohai.OhaiContextBuilder; -import org.jclouds.opscodeplatform.functions.OpscodePlatformRestClientModule; - -import com.google.inject.Injector; -import com.google.inject.Module; - -/** - * @author Adrian Cole - */ -public class OpscodePlatformContextBuilder extends OhaiContextBuilder { - - public OpscodePlatformContextBuilder(Properties props) { - super(OpscodePlatformClient.class, OpscodePlatformAsyncClient.class, props); - } - - @Override - protected void addClientModule(List modules) { - modules.add(new OpscodePlatformRestClientModule()); - } - - @Override - public Injector buildInjector() { - addOhaiModuleIfNotPresent(); - return super.buildInjector(); - } - - /** - * {@inheritDoc} - */ - @Override - public OpscodePlatformContextBuilder withModules(Iterable modules) { - return (OpscodePlatformContextBuilder) super.withModules(modules); - } - - @SuppressWarnings("unchecked") - @Override - public OpscodePlatformContext buildContext() { - Injector injector = buildInjector(); - return injector.getInstance(OpscodePlatformContext.class); - } -} \ No newline at end of file diff --git a/opscodeplatform/src/main/java/org/jclouds/opscodeplatform/OpscodePlatformPropertiesBuilder.java b/opscodeplatform/src/main/java/org/jclouds/opscodeplatform/OpscodePlatformPropertiesBuilder.java deleted file mode 100644 index 693c27eb34..0000000000 --- a/opscodeplatform/src/main/java/org/jclouds/opscodeplatform/OpscodePlatformPropertiesBuilder.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.opscodeplatform; - -import static org.jclouds.Constants.PROPERTY_ENDPOINT; - -import java.util.Properties; - -import org.jclouds.chef.internal.BaseChefPropertiesBuilder; - -/** - * Builds properties used in Chef Clients - * - * @author Adrian Cole - */ -public class OpscodePlatformPropertiesBuilder extends BaseChefPropertiesBuilder { - @Override - protected Properties defaultProperties() { - Properties properties = super.defaultProperties(); - properties.setProperty(PROPERTY_ENDPOINT, "https://api.opscode.com"); - return properties; - } - - public OpscodePlatformPropertiesBuilder(Properties properties) { - super(properties); - } - -} diff --git a/opscodeplatform/src/main/java/org/jclouds/opscodeplatform/config/OrganizationName.java b/opscodeplatform/src/main/java/org/jclouds/opscodeplatform/config/OrganizationName.java deleted file mode 100644 index 9a5a0cec35..0000000000 --- a/opscodeplatform/src/main/java/org/jclouds/opscodeplatform/config/OrganizationName.java +++ /dev/null @@ -1,39 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.opscodeplatform.config; - -import javax.inject.Singleton; - -import org.jclouds.opscodeplatform.domain.Organization; - -import com.google.common.base.Function; - -/** - * - * @author Adrian Cole - */ -@Singleton -public class OrganizationName implements Function { - - public String apply(Object from) { - return ((Organization) from).getFullName(); - } - -} \ No newline at end of file diff --git a/opscodeplatform/src/main/java/org/jclouds/opscodeplatform/config/Username.java b/opscodeplatform/src/main/java/org/jclouds/opscodeplatform/config/Username.java deleted file mode 100644 index c811794f04..0000000000 --- a/opscodeplatform/src/main/java/org/jclouds/opscodeplatform/config/Username.java +++ /dev/null @@ -1,39 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.opscodeplatform.config; - -import javax.inject.Singleton; - -import org.jclouds.opscodeplatform.domain.User; - -import com.google.common.base.Function; - -/** - * - * @author Adrian Cole - */ -@Singleton -public class Username implements Function { - - public String apply(Object from) { - return ((User) from).getUsername(); - } - -} \ No newline at end of file diff --git a/opscodeplatform/src/main/java/org/jclouds/opscodeplatform/domain/Organization.java b/opscodeplatform/src/main/java/org/jclouds/opscodeplatform/domain/Organization.java deleted file mode 100644 index 8dc530e3ac..0000000000 --- a/opscodeplatform/src/main/java/org/jclouds/opscodeplatform/domain/Organization.java +++ /dev/null @@ -1,159 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.opscodeplatform.domain; - -import static com.google.common.base.Preconditions.checkNotNull; - -import java.security.PrivateKey; - -import com.google.gson.annotations.SerializedName; - -/** - * Organization object. - * - * @author Adrian Cole - */ -public class Organization { - - public interface Type { - public static final String BUSINESS = "Business"; - public static final String NON_PROFIT = "Non-Profit"; - public static final String PERSONAL = "Personal"; - } - - private String guid; - @SerializedName("name") - private String name; - @SerializedName("full_name") - private String fullName; - private String clientname; - @SerializedName("org_type") - private String orgType; - @SerializedName("private_key") - private PrivateKey privateKey; - - Organization() { - - } - - public Organization(String name, String fullName, String clientname, String orgType) { - this(null, name, fullName, clientname, orgType, null); - } - - public Organization(String name, String orgType) { - this(null, name, name, name + "-validator", orgType, null); - } - - public Organization(String guid, String name, String fullName, String clientname, String orgType, - PrivateKey privateKey) { - this.guid = guid; - this.name = name; - this.fullName = fullName; - this.clientname = checkNotNull(clientname, "clientname"); - this.orgType = checkNotNull(orgType, "orgType"); - this.privateKey = privateKey; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((clientname == null) ? 0 : clientname.hashCode()); - result = prime * result + ((fullName == null) ? 0 : fullName.hashCode()); - result = prime * result + ((guid == null) ? 0 : guid.hashCode()); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((orgType == null) ? 0 : orgType.hashCode()); - result = prime * result + ((privateKey == null) ? 0 : privateKey.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; - Organization other = (Organization) obj; - if (clientname == null) { - if (other.clientname != null) - return false; - } else if (!clientname.equals(other.clientname)) - return false; - if (fullName == null) { - if (other.fullName != null) - return false; - } else if (!fullName.equals(other.fullName)) - return false; - if (guid == null) { - if (other.guid != null) - return false; - } else if (!guid.equals(other.guid)) - return false; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - if (orgType == null) { - if (other.orgType != null) - return false; - } else if (!orgType.equals(other.orgType)) - return false; - if (privateKey == null) { - if (other.privateKey != null) - return false; - } else if (!privateKey.equals(other.privateKey)) - return false; - return true; - } - - public String getGuid() { - return guid; - } - - public String getName() { - return name; - } - - public String getFullName() { - return fullName; - } - - public String getClientname() { - return clientname; - } - - public String getOrgType() { - return orgType; - } - - public PrivateKey getPrivateKey() { - return privateKey; - } - - @Override - public String toString() { - return "[name=" + name + ", clientname=" + clientname + ", fullName=" + fullName + ", guid=" + guid - + ", orgType=" + orgType + ", privateKey=" + (privateKey != null) + "]"; - } - -} diff --git a/opscodeplatform/src/main/java/org/jclouds/opscodeplatform/domain/User.java b/opscodeplatform/src/main/java/org/jclouds/opscodeplatform/domain/User.java deleted file mode 100644 index dc45b201a8..0000000000 --- a/opscodeplatform/src/main/java/org/jclouds/opscodeplatform/domain/User.java +++ /dev/null @@ -1,265 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.opscodeplatform.domain; - -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.cert.X509Certificate; - -import com.google.gson.annotations.SerializedName; - -/** - * User object. - * - * @author Adrian Cole - */ -public class User { - private String username; - @SerializedName("first_name") - private String firstName; - @SerializedName("middle_name") - private String middleName; - @SerializedName("last_name") - private String lastName; - @SerializedName("display_name") - private String displayName; - private String email; - @SerializedName("twitter_account") - private String twitterAccount; - private String city; - private String country; - @SerializedName("image_file_name") - private String imageFileName; - private String password; - @SerializedName("public_key") - private PublicKey publicKey; - @SerializedName("private_key") - private PrivateKey privateKey; - private X509Certificate certificate; - private String salt; - - public User(String username) { - this.username = username; - } - - public User(String username, String firstName, String middleName, String lastName, String displayName, String email, - String twitterAccount, String city, String country, String imageFileName, String password, - PublicKey publicKey, PrivateKey privateKey, X509Certificate certificate, String salt) { - this.username = username; - this.firstName = firstName; - this.middleName = middleName; - this.lastName = lastName; - this.displayName = displayName; - this.email = email; - this.twitterAccount = twitterAccount; - this.city = city; - this.country = country; - this.imageFileName = imageFileName; - this.password = password; - this.publicKey = publicKey; - this.privateKey = privateKey; - this.certificate = certificate; - this.salt = salt; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((certificate == null) ? 0 : certificate.hashCode()); - result = prime * result + ((city == null) ? 0 : city.hashCode()); - result = prime * result + ((country == null) ? 0 : country.hashCode()); - result = prime * result + ((displayName == null) ? 0 : displayName.hashCode()); - result = prime * result + ((email == null) ? 0 : email.hashCode()); - result = prime * result + ((firstName == null) ? 0 : firstName.hashCode()); - result = prime * result + ((imageFileName == null) ? 0 : imageFileName.hashCode()); - result = prime * result + ((lastName == null) ? 0 : lastName.hashCode()); - result = prime * result + ((middleName == null) ? 0 : middleName.hashCode()); - result = prime * result + ((password == null) ? 0 : password.hashCode()); - result = prime * result + ((privateKey == null) ? 0 : privateKey.hashCode()); - result = prime * result + ((publicKey == null) ? 0 : publicKey.hashCode()); - result = prime * result + ((salt == null) ? 0 : salt.hashCode()); - result = prime * result + ((twitterAccount == null) ? 0 : twitterAccount.hashCode()); - result = prime * result + ((username == null) ? 0 : username.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; - User other = (User) obj; - if (certificate == null) { - if (other.certificate != null) - return false; - } else if (!certificate.equals(other.certificate)) - return false; - if (city == null) { - if (other.city != null) - return false; - } else if (!city.equals(other.city)) - return false; - if (country == null) { - if (other.country != null) - return false; - } else if (!country.equals(other.country)) - return false; - if (displayName == null) { - if (other.displayName != null) - return false; - } else if (!displayName.equals(other.displayName)) - return false; - if (email == null) { - if (other.email != null) - return false; - } else if (!email.equals(other.email)) - return false; - if (firstName == null) { - if (other.firstName != null) - return false; - } else if (!firstName.equals(other.firstName)) - return false; - if (imageFileName == null) { - if (other.imageFileName != null) - return false; - } else if (!imageFileName.equals(other.imageFileName)) - return false; - if (lastName == null) { - if (other.lastName != null) - return false; - } else if (!lastName.equals(other.lastName)) - return false; - if (middleName == null) { - if (other.middleName != null) - return false; - } else if (!middleName.equals(other.middleName)) - return false; - if (password == null) { - if (other.password != null) - return false; - } else if (!password.equals(other.password)) - return false; - if (privateKey == null) { - if (other.privateKey != null) - return false; - } else if (!privateKey.equals(other.privateKey)) - return false; - if (publicKey == null) { - if (other.publicKey != null) - return false; - } else if (!publicKey.equals(other.publicKey)) - return false; - if (salt == null) { - if (other.salt != null) - return false; - } else if (!salt.equals(other.salt)) - return false; - if (twitterAccount == null) { - if (other.twitterAccount != null) - return false; - } else if (!twitterAccount.equals(other.twitterAccount)) - return false; - if (username == null) { - if (other.username != null) - return false; - } else if (!username.equals(other.username)) - return false; - return true; - } - - // only for deserialization - User() { - - } - - public String getUsername() { - return username; - } - - public String getFirstName() { - return firstName; - } - - public String getMiddleName() { - return middleName; - } - - public String getLastName() { - return lastName; - } - - public String getDisplayName() { - return displayName; - } - - public String getEmail() { - return email; - } - - public String getTwitterAccount() { - return twitterAccount; - } - - public String getCity() { - return city; - } - - public String getCountry() { - return country; - } - - public String getImageFileName() { - return imageFileName; - } - - public String getPassword() { - return password; - } - - public PublicKey getPublicKey() { - return publicKey; - } - - @Override - public String toString() { - return "[certificate=" + certificate + ", city=" + city + ", country=" + country + ", displayName=" + displayName - + ", email=" + email + ", firstName=" + firstName + ", imageFileName=" + imageFileName + ", lastName=" - + lastName + ", middleName=" + middleName + ", password=" + (password != null) + ", privateKey=" - + (privateKey != null) + ", publicKey=" + publicKey + ", salt=" + salt + ", twitterAccount=" - + twitterAccount + ", username=" + username + "]"; - } - - public PrivateKey getPrivateKey() { - return privateKey; - } - - public X509Certificate getCertificate() { - return certificate; - } - - public String getSalt() { - return salt; - } - -} diff --git a/opscodeplatform/src/main/java/org/jclouds/opscodeplatform/functions/OpscodePlatformRestClientModule.java b/opscodeplatform/src/main/java/org/jclouds/opscodeplatform/functions/OpscodePlatformRestClientModule.java deleted file mode 100644 index 303c7a6fc2..0000000000 --- a/opscodeplatform/src/main/java/org/jclouds/opscodeplatform/functions/OpscodePlatformRestClientModule.java +++ /dev/null @@ -1,51 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.opscodeplatform.functions; - -import java.util.Map; - -import org.jclouds.chef.ChefAsyncClient; -import org.jclouds.chef.ChefClient; -import org.jclouds.chef.config.BaseChefRestClientModule; -import org.jclouds.http.RequiresHttp; -import org.jclouds.opscodeplatform.OpscodePlatformAsyncClient; -import org.jclouds.opscodeplatform.OpscodePlatformClient; -import org.jclouds.rest.ConfiguresRestClient; - -import com.google.common.collect.ImmutableMap; - -/** - * Configures the Opscode Platform connection. - * - * @author Adrian Cole - */ -@RequiresHttp -@ConfiguresRestClient -public class OpscodePlatformRestClientModule extends - BaseChefRestClientModule { - public static final Map, Class> DELEGATE_MAP = ImmutableMap., Class> builder()// - .put(ChefClient.class, ChefAsyncClient.class)// - .build(); - - public OpscodePlatformRestClientModule() { - super(OpscodePlatformClient.class, OpscodePlatformAsyncClient.class, DELEGATE_MAP); - } - -} \ No newline at end of file diff --git a/opscodeplatform/src/main/java/org/jclouds/opscodeplatform/internal/OpscodePlatformContextImpl.java b/opscodeplatform/src/main/java/org/jclouds/opscodeplatform/internal/OpscodePlatformContextImpl.java deleted file mode 100644 index ea6bd99dfc..0000000000 --- a/opscodeplatform/src/main/java/org/jclouds/opscodeplatform/internal/OpscodePlatformContextImpl.java +++ /dev/null @@ -1,54 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.opscodeplatform.internal; - -import java.net.URI; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import org.jclouds.lifecycle.Closer; -import org.jclouds.opscodeplatform.OpscodePlatformAsyncClient; -import org.jclouds.opscodeplatform.OpscodePlatformClient; -import org.jclouds.opscodeplatform.OpscodePlatformContext; -import org.jclouds.rest.Utils; -import org.jclouds.rest.annotations.ApiVersion; -import org.jclouds.rest.annotations.Identity; -import org.jclouds.rest.annotations.Provider; -import org.jclouds.rest.internal.RestContextImpl; - -import com.google.inject.Injector; -import com.google.inject.TypeLiteral; - -/** - * @author Adrian Cole - */ -@Singleton -public class OpscodePlatformContextImpl extends RestContextImpl - implements OpscodePlatformContext { - - @Inject - protected OpscodePlatformContextImpl(Closer closer, Utils utils, Injector injector, - TypeLiteral syncApi, TypeLiteral asyncApi, - @Provider URI endpoint, @Provider String provider, @Identity String identity, @ApiVersion String apiVersion) { - super(closer, utils, injector, syncApi, asyncApi, endpoint, provider, identity, apiVersion); - } - -} diff --git a/opscodeplatform/src/test/java/org/jclouds/opscodeplatform/OpscodePlatformAsyncClientTest.java b/opscodeplatform/src/test/java/org/jclouds/opscodeplatform/OpscodePlatformAsyncClientTest.java deleted file mode 100644 index 1dd07d80ec..0000000000 --- a/opscodeplatform/src/test/java/org/jclouds/opscodeplatform/OpscodePlatformAsyncClientTest.java +++ /dev/null @@ -1,338 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.opscodeplatform; - -import static org.testng.Assert.assertEquals; - -import java.io.IOException; -import java.lang.reflect.Method; -import java.util.Properties; - -import org.jclouds.chef.filters.SignedHeaderAuth; -import org.jclouds.chef.filters.SignedHeaderAuthTest; -import org.jclouds.chef.functions.ParseKeySetFromJson; -import org.jclouds.concurrent.MoreExecutors; -import org.jclouds.concurrent.config.ConfiguresExecutorService; -import org.jclouds.concurrent.config.ExecutorServiceModule; -import org.jclouds.date.TimeStamp; -import org.jclouds.http.HttpRequest; -import org.jclouds.http.RequiresHttp; -import org.jclouds.http.TransformingHttpCommandExecutorService; -import org.jclouds.http.config.ConfiguresHttpCommandExecutorService; -import org.jclouds.http.functions.ParseJson; -import org.jclouds.http.functions.ReturnTrueIf2xx; -import org.jclouds.opscodeplatform.domain.Organization; -import org.jclouds.opscodeplatform.domain.User; -import org.jclouds.opscodeplatform.functions.OpscodePlatformRestClientModule; -import org.jclouds.rest.ConfiguresRestClient; -import org.jclouds.rest.RestClientTest; -import org.jclouds.rest.RestContextFactory; -import org.jclouds.rest.RestContextFactory.ContextSpec; -import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404; -import org.jclouds.rest.functions.ReturnFalseOnNotFoundOr404; -import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; -import org.jclouds.rest.internal.GeneratedHttpRequest; -import org.jclouds.rest.internal.RestAnnotationProcessor; -import org.testng.annotations.Test; - -import com.google.common.base.Supplier; -import com.google.common.collect.Iterables; -import com.google.inject.AbstractModule; -import com.google.inject.Module; -import com.google.inject.TypeLiteral; - -/** - * Tests annotation parsing of {@code OpscodePlatformAsyncClient} - * - * @author Adrian Cole - */ -@Test(groups = "unit", testName = "opscodeplatform.OpscodePlatformAsyncClientTest") -public class OpscodePlatformAsyncClientTest extends RestClientTest { - - public void testListUsers() throws SecurityException, NoSuchMethodException, IOException { - Method method = OpscodePlatformAsyncClient.class.getMethod("listUsers"); - GeneratedHttpRequest httpRequest = processor.createRequest(method); - - assertRequestLineEquals(httpRequest, "GET https://api.opscode.com/users HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - assertPayloadEquals(httpRequest, null, null, false); - - assertResponseParserClassEquals(method, httpRequest, ParseKeySetFromJson.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); - - checkFilters(httpRequest); - - } - - public void testUserExists() throws SecurityException, NoSuchMethodException, IOException { - Method method = OpscodePlatformAsyncClient.class.getMethod("userExists", String.class); - GeneratedHttpRequest httpRequest = processor.createRequest(method, "user"); - assertRequestLineEquals(httpRequest, "HEAD https://api.opscode.com/users/user HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - assertPayloadEquals(httpRequest, null, null, false); - - assertResponseParserClassEquals(method, httpRequest, ReturnTrueIf2xx.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnFalseOnNotFoundOr404.class); - - checkFilters(httpRequest); - - } - - public void testOrganizationExists() throws SecurityException, NoSuchMethodException, IOException { - Method method = OpscodePlatformAsyncClient.class.getMethod("organizationExists", String.class); - GeneratedHttpRequest httpRequest = processor.createRequest(method, "organization"); - assertRequestLineEquals(httpRequest, "HEAD https://api.opscode.com/organizations/organization HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - assertPayloadEquals(httpRequest, null, null, false); - - assertResponseParserClassEquals(method, httpRequest, ReturnTrueIf2xx.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnFalseOnNotFoundOr404.class); - - checkFilters(httpRequest); - - } - - public void testListOrganizations() throws SecurityException, NoSuchMethodException, IOException { - Method method = OpscodePlatformAsyncClient.class.getMethod("listOrganizations"); - GeneratedHttpRequest httpRequest = processor.createRequest(method); - - assertRequestLineEquals(httpRequest, "GET https://api.opscode.com/organizations HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - assertPayloadEquals(httpRequest, null, null, false); - - assertResponseParserClassEquals(method, httpRequest, ParseKeySetFromJson.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); - - checkFilters(httpRequest); - - } - - public void testCreateUser() throws SecurityException, NoSuchMethodException, IOException { - Method method = OpscodePlatformAsyncClient.class.getMethod("createUser", User.class); - GeneratedHttpRequest httpRequest = processor - .createRequest(method, new User("myuser")); - - assertRequestLineEquals(httpRequest, "POST https://api.opscode.com/users HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - assertPayloadEquals(httpRequest, "{\"username\":\"myuser\"}", "application/json", false); - - // now make sure request filters apply by replaying - Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest); - Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest); - - assertRequestLineEquals(httpRequest, "POST https://api.opscode.com/users HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, new StringBuilder("Accept: application/json").append("\n").append( - "X-Chef-Version: 0.9.8").append("\n").append( - "X-Ops-Authorization-1: kfrkDpfgNU26k70R1vl1bEWk0Q0f9Fs/3kxOX7gHd7iNoJq03u7RrcrAOSgL").append("\n") - .append("X-Ops-Authorization-2: ETj5JNeCk18BmFkHMAbCA9hXVo1T4rlHCpbuzAzFlFxUGAT4wj8UoO7V886X").append( - "\n").append( - "X-Ops-Authorization-3: Kf8DvihP6ElthCNuu1xuhN0B4GEmWC9+ut7UMLe0L2T34VzkbCtuInGbf42/").append( - "\n").append( - "X-Ops-Authorization-4: G7iu94/xFOT1gN9cex4pNyTnRCHzob4JVU1usxt/2g5grN2SyYwRS5+4MNLN").append( - "\n").append( - "X-Ops-Authorization-5: WY/iLUPb/9dwtiIQsnUOXqDrs28zNswZulQW4AzYRd7MczJVKU4y4+4XRcB4").append( - "\n").append("X-Ops-Authorization-6: 2+BFLT5o6P6G0D+eCu3zSuaqEJRucPJPaDGWdKIMag==") - .append("\n").append("X-Ops-Content-Hash: yLHOxvgIEtNw5UrZDxslOeMw1gw=").append("\n").append( - "X-Ops-Sign: version=1.0").append("\n").append("X-Ops-Timestamp: timestamp").append("\n") - .append("X-Ops-Userid: user").append("\n").toString()); - assertPayloadEquals(httpRequest, "{\"username\":\"myuser\"}", "application/json", false); - - assertResponseParserClassEquals(method, httpRequest, ParseJson.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); - - checkFilters(httpRequest); - - } - - public void testUpdateUser() throws SecurityException, NoSuchMethodException, IOException { - Method method = OpscodePlatformAsyncClient.class.getMethod("updateUser", User.class); - GeneratedHttpRequest httpRequest = processor - .createRequest(method, new User("myuser")); - - assertRequestLineEquals(httpRequest, "PUT https://api.opscode.com/users/myuser HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - assertPayloadEquals(httpRequest, "{\"username\":\"myuser\"}", "application/json", false); - - assertResponseParserClassEquals(method, httpRequest, ParseJson.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); - - checkFilters(httpRequest); - - } - - public void testGetUser() throws SecurityException, NoSuchMethodException, IOException { - Method method = OpscodePlatformAsyncClient.class.getMethod("getUser", String.class); - GeneratedHttpRequest httpRequest = processor.createRequest(method, "myuser"); - - assertRequestLineEquals(httpRequest, "GET https://api.opscode.com/users/myuser HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - assertPayloadEquals(httpRequest, null, null, false); - - assertResponseParserClassEquals(method, httpRequest, ParseJson.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); - - checkFilters(httpRequest); - - } - - public void testDeleteUser() throws SecurityException, NoSuchMethodException, IOException { - Method method = OpscodePlatformAsyncClient.class.getMethod("deleteUser", String.class); - GeneratedHttpRequest httpRequest = processor.createRequest(method, "myuser"); - - assertRequestLineEquals(httpRequest, "DELETE https://api.opscode.com/users/myuser HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - assertPayloadEquals(httpRequest, null, null, false); - - assertResponseParserClassEquals(method, httpRequest, ParseJson.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); - - checkFilters(httpRequest); - - } - - public void testCreateOrg() throws SecurityException, NoSuchMethodException, IOException { - Method method = OpscodePlatformAsyncClient.class.getMethod("createOrganization", Organization.class); - GeneratedHttpRequest httpRequest = processor.createRequest(method, new Organization( - "myorganization", "myorganization", "myorganization-validator", Organization.Type.BUSINESS)); - - assertRequestLineEquals(httpRequest, "POST https://api.opscode.com/organizations HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - assertPayloadEquals( - httpRequest, - "{\"name\":\"myorganization\",\"full_name\":\"myorganization\",\"clientname\":\"myorganization-validator\",\"org_type\":\"Business\"}", - "application/json", false); - - assertResponseParserClassEquals(method, httpRequest, ParseJson.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); - - checkFilters(httpRequest); - - } - - public void testUpdateOrg() throws SecurityException, NoSuchMethodException, IOException { - Method method = OpscodePlatformAsyncClient.class.getMethod("updateOrganization", Organization.class); - GeneratedHttpRequest httpRequest = processor.createRequest(method, new Organization( - "myorganization", "myorganization", "myorganization-validator", Organization.Type.BUSINESS)); - - assertRequestLineEquals(httpRequest, "PUT https://api.opscode.com/organizations/myorganization HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - assertPayloadEquals( - httpRequest, - "{\"name\":\"myorganization\",\"full_name\":\"myorganization\",\"clientname\":\"myorganization-validator\",\"org_type\":\"Business\"}", - "application/json", false); - - assertResponseParserClassEquals(method, httpRequest, ParseJson.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); - - checkFilters(httpRequest); - - } - - public void testGetOrg() throws SecurityException, NoSuchMethodException, IOException { - Method method = OpscodePlatformAsyncClient.class.getMethod("getOrganization", String.class); - GeneratedHttpRequest httpRequest = processor.createRequest(method, "myorganization"); - - assertRequestLineEquals(httpRequest, "GET https://api.opscode.com/organizations/myorganization HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - assertPayloadEquals(httpRequest, null, null, false); - - assertResponseParserClassEquals(method, httpRequest, ParseJson.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); - - checkFilters(httpRequest); - - } - - public void testDeleteOrg() throws SecurityException, NoSuchMethodException, IOException { - Method method = OpscodePlatformAsyncClient.class.getMethod("deleteOrganization", String.class); - GeneratedHttpRequest httpRequest = processor.createRequest(method, "myorganization"); - - assertRequestLineEquals(httpRequest, "DELETE https://api.opscode.com/organizations/myorganization HTTP/1.1"); - assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.8\n"); - assertPayloadEquals(httpRequest, null, null, false); - - assertResponseParserClassEquals(method, httpRequest, ParseJson.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); - - checkFilters(httpRequest); - - } - - @Override - protected void checkFilters(HttpRequest request) { - assertEquals(request.getFilters().size(), 1); - assertEquals(request.getFilters().get(0).getClass(), SignedHeaderAuth.class); - } - - @Override - protected TypeLiteral> createTypeLiteral() { - return new TypeLiteral>() { - }; - } - - @Override - protected Module createModule() { - return new TestOpscodePlatformRestClientModule(); - } - - @ConfiguresHttpCommandExecutorService - @ConfiguresExecutorService - private static class HttpExecutorModule extends AbstractModule { - private final TransformingHttpCommandExecutorService httpExecutor; - - private HttpExecutorModule(TransformingHttpCommandExecutorService httpExecutor) { - this.httpExecutor = httpExecutor; - } - - @Override - protected void configure() { - bind(TransformingHttpCommandExecutorService.class).toInstance(httpExecutor); - install(new ExecutorServiceModule(MoreExecutors.sameThreadExecutor(), MoreExecutors.sameThreadExecutor())); - } - } - - @RequiresHttp - @ConfiguresRestClient - static class TestOpscodePlatformRestClientModule extends OpscodePlatformRestClientModule { - @Override - protected String provideTimeStamp(@TimeStamp Supplier cache) { - return "timestamp"; - } - - } - - @Override - public ContextSpec createContextSpec() { - return new RestContextFactory().createContextSpec("opscodeplatform", "user", SignedHeaderAuthTest.PRIVATE_KEY, - new Properties()); - } -} diff --git a/opscodeplatform/src/test/java/org/jclouds/opscodeplatform/OpscodePlatformClientLiveTest.java b/opscodeplatform/src/test/java/org/jclouds/opscodeplatform/OpscodePlatformClientLiveTest.java deleted file mode 100644 index aa6ddce680..0000000000 --- a/opscodeplatform/src/test/java/org/jclouds/opscodeplatform/OpscodePlatformClientLiveTest.java +++ /dev/null @@ -1,234 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.opscodeplatform; - -import static com.google.common.base.Preconditions.checkNotNull; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertNull; - -import java.io.File; -import java.io.IOException; -import java.util.Properties; -import java.util.Set; - -import org.jclouds.chef.BaseChefClientLiveTest; -import org.jclouds.chef.ChefClient; -import org.jclouds.chef.config.ChefParserModule; -import org.jclouds.crypto.Pems; -import org.jclouds.json.Json; -import org.jclouds.json.config.GsonModule; -import org.jclouds.logging.log4j.config.Log4JLoggingModule; -import org.jclouds.opscodeplatform.domain.Organization; -import org.jclouds.opscodeplatform.domain.User; -import org.jclouds.rest.AuthorizationException; -import org.jclouds.rest.HttpClient; -import org.jclouds.rest.RestContextFactory; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import com.google.common.base.Charsets; -import com.google.common.collect.ImmutableSet; -import com.google.common.io.Files; -import com.google.inject.Guice; -import com.google.inject.Module; - -/** - * Tests behavior of {@code OpscodePlatformClient} - * - * @author Adrian Cole - */ -@Test(groups = "live", testName = "chef.OpscodePlatformClientLiveTest") -public class OpscodePlatformClientLiveTest extends BaseChefClientLiveTest { - - private OpscodePlatformContext validatorConnection; - private OpscodePlatformContext clientConnection; - private OpscodePlatformContext adminConnection; - - private String validator; - private String adminKey; - private String validatorKey; - - @Override - @BeforeClass(groups = { "live" }) - public void setupClient() throws IOException { - validator = checkNotNull(System.getProperty("jclouds.test.validator"), "jclouds.test.validator"); - orgname = validator.substring(0, validator.lastIndexOf('-')); - String validatorKeyFile = System.getProperty("jclouds.test.validator.key"); - if (validatorKeyFile == null || validatorKeyFile.equals("")) - validatorKeyFile = System.getProperty("user.home") + "/.chef/" + orgname + "-validator.pem"; - user = checkNotNull(System.getProperty("jclouds.test.identity"), "jclouds.test.identity"); - String keyfile = System.getProperty("jclouds.test.credential"); - if (keyfile == null || keyfile.equals("")) - keyfile = System.getProperty("user.home") + "/.chef/" + user + ".pem"; - - validatorKey = Files.toString(new File(validatorKeyFile), Charsets.UTF_8); - adminKey = Files.toString(new File(keyfile), Charsets.UTF_8); - - validatorConnection = createConnection(validator, validatorKey); - adminConnection = createConnection(user, adminKey); - json = Guice.createInjector(new GsonModule(), new ChefParserModule()).getInstance(Json.class); - } - - private OpscodePlatformContext createConnection(String identity, String key) throws IOException { - Properties props = new Properties(); - return (OpscodePlatformContext) new RestContextFactory() - . createContext("opscodeplatform", identity, key, - ImmutableSet. of(new Log4JLoggingModule()), props); - } - - @Override - protected HttpClient getHttp() { - return adminConnection.utils().http(); - } - - @Override - protected ChefClient getAdminConnection() { - return createChefClient(user, adminKey); - } - - private ChefClient createChefClient(String user, String adminKey) { - Properties props = new Properties(); - props.setProperty("chef.endpoint", "https://api.opscode.com/organizations/" + orgname); - return (ChefClient) new RestContextFactory().createContext("chef", user, adminKey, - ImmutableSet. of(new Log4JLoggingModule()), props).getApi(); - } - - @Override - protected ChefClient getValidatorConnection() { - return createChefClient(validator, validatorKey); - } - - @Override - protected ChefClient getClientConnection() { - return createChefClient(PREFIX, clientKey); - } - - @Override - protected void recreateClientConnection() throws IOException { - if (clientConnection != null) - clientConnection.close(); - clientConnection = createConnection(PREFIX, clientKey); - } - - @Override - protected void closeContexts() { - if (orgUser != null) - adminConnection.getApi().deleteUser(PREFIX); - if (createdOrgname != null) - adminConnection.getApi().deleteOrganization(createdOrgname); - if (clientConnection != null) - clientConnection.close(); - if (validatorConnection != null) - validatorConnection.close(); - if (adminConnection != null) - adminConnection.close(); - } - - private String orgname; - private Organization org; - private User orgUser; - private String createdOrgname; - - @Test(expectedExceptions = AuthorizationException.class) - public void testListOrganizations() throws Exception { - Set orgs = adminConnection.getApi().listOrganizations(); - assertNotNull(orgs); - } - - /** - * this test only works when you have a super user not yet supported in the official api - */ - @Test(enabled = false, expectedExceptions = AuthorizationException.class) - public void testCreateOrganization() throws Exception { - createdOrgname = orgname + 1; - adminConnection.getApi().deleteOrganization(createdOrgname); - org = adminConnection.getApi().createOrganization(new Organization(createdOrgname, Organization.Type.BUSINESS)); - assertNotNull(org); - assertNull(org.getName()); - assertNull(org.getFullName()); - assertEquals(org.getClientname(), createdOrgname + "-validator"); - assertNull(org.getOrgType()); - assertNotNull(org.getPrivateKey()); - OpscodePlatformContext connection = null; - try { - connection = createConnection(org.getClientname(), Pems.pem(org.getPrivateKey())); - } finally { - if (connection != null) - connection.close(); - } - } - - public void testOrganizationExists() throws Exception { - assertNotNull(adminConnection.getApi().organizationExists(orgname)); - } - - @Test(enabled = false, dependsOnMethods = "testCreateOrganization", expectedExceptions = AuthorizationException.class) - public void testUpdateOrganization() throws Exception { - Organization org = adminConnection.getApi().getOrganization(createdOrgname); - adminConnection.getApi().updateOrganization(org); - } - - public void testGetOrganization() throws Exception { - adminConnection.getApi().getOrganization(orgname); - } - - @Test(expectedExceptions = AuthorizationException.class) - public void testListUsers() throws Exception { - Set orgs = adminConnection.getApi().listUsers(); - assertNotNull(orgs); - } - - // @Test(expectedExceptions = HttpResponseException.class) - @Test(enabled = false, expectedExceptions = AuthorizationException.class) - public void testCreateUser() throws Exception { - adminConnection.getApi().deleteUser(PREFIX); - adminConnection.getApi().createUser(new User(PREFIX)); - orgUser = adminConnection.getApi().getUser(PREFIX); - assertNotNull(orgUser); - assertEquals(orgUser.getUsername(), PREFIX); - assertNotNull(orgUser.getPrivateKey()); - } - - public void testUserExists() throws Exception { - assertNotNull(adminConnection.getApi().userExists(user)); - } - - public void testGetUser() throws Exception { - adminConnection.getApi().getUser(user); - } - - // disabled while create user fails - @Test(dependsOnMethods = "testCreateUser", enabled = false) - public void testUpdateUser() throws Exception { - User user = adminConnection.getApi().getUser(PREFIX); - adminConnection.getApi().updateUser(user); - } - - @Test(expectedExceptions = AuthorizationException.class) - public void testGetOrganizationFailsForValidationKey() throws Exception { - validatorConnection.getApi().getOrganization(orgname); - } - - @Test(dependsOnMethods = "testGenerateKeyForClient", expectedExceptions = AuthorizationException.class) - public void testGetOrganizationFailsForClient() throws Exception { - clientConnection.getApi().getOrganization(orgname); - } -} diff --git a/opscodeplatform/src/test/java/org/jclouds/opscodeplatform/ProvidersInPropertiesTest.java b/opscodeplatform/src/test/java/org/jclouds/opscodeplatform/ProvidersInPropertiesTest.java deleted file mode 100644 index 08c5191590..0000000000 --- a/opscodeplatform/src/test/java/org/jclouds/opscodeplatform/ProvidersInPropertiesTest.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.opscodeplatform; - -import org.jclouds.util.Utils; -import org.testng.annotations.Test; - -import com.google.common.collect.Iterables; - -/** - * - * @author Adrian Cole - * - */ -@Test(groups = "unit") -public class ProvidersInPropertiesTest { - - @Test - public void testSupportedProviders() { - Iterable providers = Utils.getSupportedProviders(); - assert Iterables.contains(providers, "opscodeplatform") : providers; - } - -} diff --git a/opscodeplatform/src/test/java/org/jclouds/opscodeplatform/functions/ParseOrganizationFromJsonTest.java b/opscodeplatform/src/test/java/org/jclouds/opscodeplatform/functions/ParseOrganizationFromJsonTest.java deleted file mode 100644 index 8ac4490d5b..0000000000 --- a/opscodeplatform/src/test/java/org/jclouds/opscodeplatform/functions/ParseOrganizationFromJsonTest.java +++ /dev/null @@ -1,65 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.opscodeplatform.functions; - -import static org.testng.Assert.assertEquals; - -import java.io.IOException; - -import org.jclouds.chef.config.ChefParserModule; -import org.jclouds.http.HttpResponse; -import org.jclouds.http.functions.ParseJson; -import org.jclouds.io.Payloads; -import org.jclouds.json.config.GsonModule; -import org.jclouds.opscodeplatform.domain.Organization; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.Test; - -import com.google.inject.Guice; -import com.google.inject.Injector; -import com.google.inject.Key; -import com.google.inject.TypeLiteral; - -/** - * Tests behavior of {@code ParseOrganizationFromJson} - * - * @author Adrian Cole - */ -@Test(groups = "unit", sequential = true, testName = "chef.ParseOrganizationFromJsonTest") -public class ParseOrganizationFromJsonTest { - - private ParseJson handler; - - @BeforeTest - protected void setUpInjector() throws IOException { - Injector injector = Guice.createInjector(new ChefParserModule(), new GsonModule()); - handler = injector.getInstance(Key.get(new TypeLiteral>() { - })); - } - - public void test() { - - Organization org = new Organization("486ca3ac66264fea926aa0b4ff74341c", "jclouds", "jclouds", - "jclouds-validator", "Business", null); - - String toParse = "{\"guid\":\"486ca3ac66264fea926aa0b4ff74341c\",\"name\":\"jclouds\",\"full_name\":\"jclouds\",\"clientname\":\"jclouds-validator\",\"org_type\":\"Business\",\"name\":\"jclouds\"}"; - assertEquals(handler.apply(new HttpResponse(200, "ok", Payloads.newStringPayload(toParse))), org); - } -} diff --git a/opscodeplatform/src/test/java/org/jclouds/opscodeplatform/functions/ParseUserFromJsonTest.java b/opscodeplatform/src/test/java/org/jclouds/opscodeplatform/functions/ParseUserFromJsonTest.java deleted file mode 100644 index 8867f1bcb5..0000000000 --- a/opscodeplatform/src/test/java/org/jclouds/opscodeplatform/functions/ParseUserFromJsonTest.java +++ /dev/null @@ -1,89 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.opscodeplatform.functions; - -import static org.testng.Assert.assertEquals; - -import java.io.IOException; -import java.security.cert.CertificateException; -import java.security.spec.InvalidKeySpecException; - -import org.jclouds.chef.config.ChefParserModule; -import org.jclouds.crypto.Crypto; -import org.jclouds.crypto.Pems; -import org.jclouds.http.HttpResponse; -import org.jclouds.http.functions.ParseJson; -import org.jclouds.io.Payloads; -import org.jclouds.json.config.GsonModule; -import org.jclouds.opscodeplatform.domain.User; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.Test; - -import com.google.inject.Guice; -import com.google.inject.Injector; -import com.google.inject.Key; -import com.google.inject.TypeLiteral; - -/** - * Tests behavior of {@code ParseUserFromJson} - * - * @author Adrian Cole - */ -@Test(groups = "unit", sequential = true, testName = "chef.ParseUserFromJsonTest") -public class ParseUserFromJsonTest { - - private ParseJson handler; - private Crypto crypto; - - @BeforeTest - protected void setUpInjector() throws IOException { - Injector injector = Guice.createInjector(new ChefParserModule(), new GsonModule()); - handler = injector.getInstance(Key.get(new TypeLiteral>() { - })); - crypto = injector.getInstance(Crypto.class); - } - - public void test() throws InvalidKeySpecException, CertificateException, IOException { - User user = new User( - "dopey", - "Adrian", - "", - "Cole", - "Adrian Cole", - "adrian+dopey@opscode.com", - null, - null, - null, - null, - "abcdef", - crypto - .rsaKeyFactory() - .generatePublic( - Pems - .publicKeySpec("-----BEGIN RSA PUBLIC KEY-----\nMIIBCgKCAQEAvCKTqPdHv7GsHTjk02g91Aw3T6xQmdRaI70X6E6GGFxZtcH+tb1X\nqHxwhFydECVXhu0WVjTcWvxZ1aMFzn9BLHQYWzZxU/fIKVNR6ujyZ3jRxDXRFpX5\n/zvMdvNbdsJ+8foEbdoP1iujUMZuy6ZMvcbTDCgWjYVQ2omR9CkH/5Fwlbk3cSrF\n6qfGaM7340OGknKUfXdvhCq4vxydlOwfHJyNDWY0PW+8rDKHWxxNtYDDDeIMw2z/\nYC34f1bcAkR+/lyx5b25RwDomZNqXJqp1hjOVJVlo+UMvzWfXph5hgjcgtwzc5Iu\nmWWMUdxLcdw+/iQm6NW9cmU28bvHu0q7FwIDAQAB\n-----END RSA PUBLIC KEY-----\n")), - null, - Pems - .x509Certificate("-----BEGIN CERTIFICATE-----\nMIIClzCCAgCgAwIBAgIBATANBgkqhkiG9w0BAQUFADCBnjELMAkGA1UEBhMCVVMx\nEzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxFjAUBgNVBAoM\nDU9wc2NvZGUsIEluYy4xHDAaBgNVBAsME0NlcnRpZmljYXRlIFNlcnZpY2UxMjAw\nBgNVBAMMKW9wc2NvZGUuY29tL2VtYWlsQWRkcmVzcz1hdXRoQG9wc2NvZGUuY29t\nMB4XDTEwMDgwMzA0MDUzNVoXDTIwMDczMTA0MDUzNVowADCCASIwDQYJKoZIhvcN\nAQEBBQADggEPADCCAQoCggEBALwik6j3R7+xrB045NNoPdQMN0+sUJnUWiO9F+hO\nhhhcWbXB/rW9V6h8cIRcnRAlV4btFlY03Fr8WdWjBc5/QSx0GFs2cVP3yClTUero\n8md40cQ10RaV+f87zHbzW3bCfvH6BG3aD9Yro1DGbsumTL3G0wwoFo2FUNqJkfQp\nB/+RcJW5N3EqxeqnxmjO9+NDhpJylH13b4QquL8cnZTsHxycjQ1mND1vvKwyh1sc\nTbWAww3iDMNs/2At+H9W3AJEfv5cseW9uUcA6JmTalyaqdYYzlSVZaPlDL81n16Y\neYYI3ILcM3OSLplljFHcS3HcPv4kJujVvXJlNvG7x7tKuxcCAwEAATANBgkqhkiG\n9w0BAQUFAAOBgQBcoSP/2tFhP8yjF/dRDRdDed0/Cg0xnpp2wvM38gBRgvhpZbQ3\nI2rqpw5THNzrzBVnrYxd57uAa+y2MMG57XnvNWOmyL6WIYXLfN1QI3nHdpHS/QVF\nCRWpDWxLM1TkqAD9xQZOpUDdByF2exiCDNTzSYYg/ISLlIEzicNJeoPNbA==\n-----END CERTIFICATE-----\n"), - "xBOmipWikVEicS7tNOPdQzPsPmsROMgPme5O19ZHh6R7N9MQT7d5olDiGFpO"); - - assertEquals(handler.apply(new HttpResponse(200, "ok", Payloads.newPayload(ParseUserFromJsonTest.class - .getResourceAsStream("/user.json")))), user); - } -} diff --git a/opscodeplatform/src/test/resources/log4j.xml b/opscodeplatform/src/test/resources/log4j.xml deleted file mode 100644 index 347362575f..0000000000 --- a/opscodeplatform/src/test/resources/log4j.xml +++ /dev/null @@ -1,117 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/opscodeplatform/src/test/resources/user.json b/opscodeplatform/src/test/resources/user.json deleted file mode 100644 index 25c2e3454c..0000000000 --- a/opscodeplatform/src/test/resources/user.json +++ /dev/null @@ -1 +0,0 @@ -{"public_key":"-----BEGIN RSA PUBLIC KEY-----\nMIIBCgKCAQEAvCKTqPdHv7GsHTjk02g91Aw3T6xQmdRaI70X6E6GGFxZtcH+tb1X\nqHxwhFydECVXhu0WVjTcWvxZ1aMFzn9BLHQYWzZxU/fIKVNR6ujyZ3jRxDXRFpX5\n/zvMdvNbdsJ+8foEbdoP1iujUMZuy6ZMvcbTDCgWjYVQ2omR9CkH/5Fwlbk3cSrF\n6qfGaM7340OGknKUfXdvhCq4vxydlOwfHJyNDWY0PW+8rDKHWxxNtYDDDeIMw2z/\nYC34f1bcAkR+/lyx5b25RwDomZNqXJqp1hjOVJVlo+UMvzWfXph5hgjcgtwzc5Iu\nmWWMUdxLcdw+/iQm6NW9cmU28bvHu0q7FwIDAQAB\n-----END RSA PUBLIC KEY-----\n","middle_name":"","certificate":"-----BEGIN CERTIFICATE-----\nMIIClzCCAgCgAwIBAgIBATANBgkqhkiG9w0BAQUFADCBnjELMAkGA1UEBhMCVVMx\nEzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxFjAUBgNVBAoM\nDU9wc2NvZGUsIEluYy4xHDAaBgNVBAsME0NlcnRpZmljYXRlIFNlcnZpY2UxMjAw\nBgNVBAMMKW9wc2NvZGUuY29tL2VtYWlsQWRkcmVzcz1hdXRoQG9wc2NvZGUuY29t\nMB4XDTEwMDgwMzA0MDUzNVoXDTIwMDczMTA0MDUzNVowADCCASIwDQYJKoZIhvcN\nAQEBBQADggEPADCCAQoCggEBALwik6j3R7+xrB045NNoPdQMN0+sUJnUWiO9F+hO\nhhhcWbXB/rW9V6h8cIRcnRAlV4btFlY03Fr8WdWjBc5/QSx0GFs2cVP3yClTUero\n8md40cQ10RaV+f87zHbzW3bCfvH6BG3aD9Yro1DGbsumTL3G0wwoFo2FUNqJkfQp\nB/+RcJW5N3EqxeqnxmjO9+NDhpJylH13b4QquL8cnZTsHxycjQ1mND1vvKwyh1sc\nTbWAww3iDMNs/2At+H9W3AJEfv5cseW9uUcA6JmTalyaqdYYzlSVZaPlDL81n16Y\neYYI3ILcM3OSLplljFHcS3HcPv4kJujVvXJlNvG7x7tKuxcCAwEAATANBgkqhkiG\n9w0BAQUFAAOBgQBcoSP/2tFhP8yjF/dRDRdDed0/Cg0xnpp2wvM38gBRgvhpZbQ3\nI2rqpw5THNzrzBVnrYxd57uAa+y2MMG57XnvNWOmyL6WIYXLfN1QI3nHdpHS/QVF\nCRWpDWxLM1TkqAD9xQZOpUDdByF2exiCDNTzSYYg/ISLlIEzicNJeoPNbA==\n-----END CERTIFICATE-----\n","city":null,"email":"adrian+dopey@opscode.com","country":null,"first_name":"Adrian","password":"abcdef","twitter_account":null,"salt":"xBOmipWikVEicS7tNOPdQzPsPmsROMgPme5O19ZHh6R7N9MQT7d5olDiGFpO","display_name":"Adrian Cole","last_name":"Cole","image_file_name":null,"username":"dopey"} \ No newline at end of file diff --git a/pom.xml b/pom.xml index c3846ada3b..e35bc05bdf 100644 --- a/pom.xml +++ b/pom.xml @@ -45,13 +45,11 @@ azure atmos rackspace + slicehost rimuhosting twitter vcloud gogrid - chef - opscodeplatform - slicehost allcompute allblobstore all