Removed all compile warnings and applied formatting to all classes

This commit is contained in:
Ignasi Barrera 2013-01-20 13:10:23 +01:00
parent efb5190023
commit 7cf428657e
90 changed files with 1430 additions and 1441 deletions

View File

@ -54,17 +54,18 @@ public interface ChefApi {
* the URLs against which to PUT files that need to be uploaded. * the URLs against which to PUT files that need to be uploaded.
* *
* @param md5s * @param md5s
* raw md5s; uses {@code Bytes.asList()} and {@code * raw md5s; uses {@code Bytes.asList()} and
* Bytes.toByteArray()} as necessary * {@code Bytes.toByteArray()} as necessary
* @return The URLs against which to PUT files that need to be uploaded. * @return The URLs against which to PUT files that need to be uploaded.
*/ */
UploadSandbox getUploadSandboxForChecksums(Set<List<Byte>> md5s); UploadSandbox getUploadSandboxForChecksums(Set<List<Byte>> md5s);
/** /**
* *
* Uploads the given content to the sandbox at the given URI. * Uploads the given content to the sandbox at the given URI.
* <p> * <p>
* The URI must be obtained, after uploading a sandbox, from the {@link UploadSandbox#getUri()}. * The URI must be obtained, after uploading a sandbox, from the
* {@link UploadSandbox#getUri()}.
*/ */
void uploadContent(URI location, Payload content); void uploadContent(URI location, Payload content);
@ -157,7 +158,7 @@ public interface ChefApi {
/** /**
* creates a new administrator client * creates a new administrator client
* *
* @return the private key of the client. You can then use this client name * @return the private key of the client. You can then use this client name
* and private key to access the Opscode API. * and private key to access the Opscode API.
* @throws AuthorizationException * @throws AuthorizationException
@ -492,8 +493,7 @@ public interface ChefApi {
/** /**
* Show indexes you can search on * Show indexes you can search on
* <p/> * <p/>
* By default, the "role", "node" and "api" indexes will always be * By default, the "role", "node" and "api" indexes will always be available.
* available.
* <p/> * <p/>
* Note that the search indexes may lag behind the most current data by at * 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 * least 10 seconds at any given time - so if you need to write data and
@ -519,7 +519,7 @@ public interface ChefApi {
* and the rows themselves. * and the rows themselves.
*/ */
SearchResult<? extends Role> searchRoles(); SearchResult<? extends Role> searchRoles();
/** /**
* search all roles that match the given options. * search all roles that match the given options.
* *
@ -540,7 +540,7 @@ public interface ChefApi {
* and the rows themselves. * and the rows themselves.
*/ */
SearchResult<? extends Client> searchClients(); SearchResult<? extends Client> searchClients();
/** /**
* search all clients that match the given options. * search all clients that match the given options.
* *
@ -561,7 +561,7 @@ public interface ChefApi {
* and the rows themselves. * and the rows themselves.
*/ */
SearchResult<? extends Node> searchNodes(); SearchResult<? extends Node> searchNodes();
/** /**
* search all nodes that match the given options. * search all nodes that match the given options.
* *
@ -582,7 +582,7 @@ public interface ChefApi {
* and the rows themselves. * and the rows themselves.
*/ */
SearchResult<? extends DatabagItem> searchDatabag(String databagName); SearchResult<? extends DatabagItem> searchDatabag(String databagName);
/** /**
* search all items in a databag that match the given options. * search all items in a databag that match the given options.
* *
@ -594,8 +594,10 @@ public interface ChefApi {
/** /**
* Get the contents of the given resource. * Get the contents of the given resource.
* @param resource The resource to get. *
* @return An input stream for the content of the requested resource. * @param resource
* The resource to get.
* @return An input stream for the content of the requested resource.
*/ */
InputStream getResourceContents(Resource resource); InputStream getResourceContents(Resource resource);
} }

View File

@ -73,22 +73,24 @@ public class ChefApiMetadata extends BaseRestApiMetadata {
} }
public static abstract class Builder<T extends Builder<T>> extends BaseRestApiMetadata.Builder<T> { public static abstract class Builder<T extends Builder<T>> extends BaseRestApiMetadata.Builder<T> {
protected Builder(){ protected Builder() {
this(ChefApi.class, ChefAsyncApi.class); this(ChefApi.class, ChefAsyncApi.class);
} }
protected Builder(Class<?> api, Class<?> asyncApi) { protected Builder(Class<?> api, Class<?> asyncApi) {
super(api, asyncApi); super(api, asyncApi);
id("chef") id("chef")
.name("OpsCode Chef Api") .name("OpsCode Chef Api")
.identityName("User") .identityName("User")
.credentialName("Certificate") .credentialName("Certificate")
.version(ChefAsyncApi.VERSION) .version(ChefAsyncApi.VERSION)
.documentation(URI.create("http://wiki.opscode.com/display/chef/Server+API")) .documentation(URI.create("http://wiki.opscode.com/display/chef/Server+API"))
.defaultEndpoint("http://localhost:4000") .defaultEndpoint("http://localhost:4000")
.defaultProperties(ChefApiMetadata.defaultProperties()) .defaultProperties(ChefApiMetadata.defaultProperties())
.context(typeToken(ChefContext.class)) .context(typeToken(ChefContext.class))
.defaultModules(ImmutableSet.<Class<? extends Module>>of(ChefRestClientModule.class, ChefParserModule.class, JMXOhaiModule.class)); .defaultModules(
ImmutableSet.<Class<? extends Module>> of(ChefRestClientModule.class, ChefParserModule.class,
JMXOhaiModule.class));
} }
@Override @Override
@ -96,7 +98,7 @@ public class ChefApiMetadata extends BaseRestApiMetadata {
return new ChefApiMetadata(this); return new ChefApiMetadata(this);
} }
} }
private static class ConcreteBuilder extends Builder<ConcreteBuilder> { private static class ConcreteBuilder extends Builder<ConcreteBuilder> {
@Override @Override
protected ConcreteBuilder self() { protected ConcreteBuilder self() {

View File

@ -102,7 +102,7 @@ public interface ChefAsyncApi {
@POST @POST
@Path("/sandboxes") @Path("/sandboxes")
ListenableFuture<UploadSandbox> getUploadSandboxForChecksums( ListenableFuture<UploadSandbox> getUploadSandboxForChecksums(
@BinderParam(BindChecksumsToJsonPayload.class) Set<List<Byte>> md5s); @BinderParam(BindChecksumsToJsonPayload.class) Set<List<Byte>> md5s);
/** /**
* @see ChefApi#uploadContent(URI, Payload) * @see ChefApi#uploadContent(URI, Payload)
@ -119,7 +119,7 @@ public interface ChefAsyncApi {
@PUT @PUT
@Path("/sandboxes/{id}") @Path("/sandboxes/{id}")
ListenableFuture<Sandbox> commitSandbox(@PathParam("id") String id, ListenableFuture<Sandbox> commitSandbox(@PathParam("id") String id,
@BinderParam(BindIsCompletedToJsonPayload.class) boolean isCompleted); @BinderParam(BindIsCompletedToJsonPayload.class) boolean isCompleted);
/** /**
* @see ChefApi#listCookbooks() * @see ChefApi#listCookbooks()
@ -138,7 +138,7 @@ public interface ChefAsyncApi {
@PUT @PUT
@Path("/cookbooks/{cookbookname}/{version}") @Path("/cookbooks/{cookbookname}/{version}")
ListenableFuture<CookbookVersion> updateCookbook(@PathParam("cookbookname") String cookbookName, ListenableFuture<CookbookVersion> updateCookbook(@PathParam("cookbookname") String cookbookName,
@PathParam("version") String version, @BinderParam(BindToJsonPayload.class) CookbookVersion cookbook); @PathParam("version") String version, @BinderParam(BindToJsonPayload.class) CookbookVersion cookbook);
/** /**
* @see ChefApi#deleteCookbook(String, String) * @see ChefApi#deleteCookbook(String, String)
@ -148,7 +148,7 @@ public interface ChefAsyncApi {
@Path("/cookbooks/{cookbookname}/{version}") @Path("/cookbooks/{cookbookname}/{version}")
@Fallback(NullOnNotFoundOr404.class) @Fallback(NullOnNotFoundOr404.class)
ListenableFuture<CookbookVersion> deleteCookbook(@PathParam("cookbookname") String cookbookName, ListenableFuture<CookbookVersion> deleteCookbook(@PathParam("cookbookname") String cookbookName,
@PathParam("version") String version); @PathParam("version") String version);
/** /**
* @see ChefApi#getVersionsOfCookbook(String) * @see ChefApi#getVersionsOfCookbook(String)
@ -168,7 +168,7 @@ public interface ChefAsyncApi {
@Path("/cookbooks/{cookbookname}/{version}") @Path("/cookbooks/{cookbookname}/{version}")
@Fallback(NullOnNotFoundOr404.class) @Fallback(NullOnNotFoundOr404.class)
ListenableFuture<CookbookVersion> getCookbook(@PathParam("cookbookname") String cookbookName, ListenableFuture<CookbookVersion> getCookbook(@PathParam("cookbookname") String cookbookName,
@PathParam("version") String version); @PathParam("version") String version);
/** /**
* @see ChefApi#createClient(String) * @see ChefApi#createClient(String)
@ -178,7 +178,7 @@ public interface ChefAsyncApi {
@Path("/clients") @Path("/clients")
@MapBinder(BindToJsonPayload.class) @MapBinder(BindToJsonPayload.class)
ListenableFuture<Client> createClient(@PayloadParam("name") String clientname); ListenableFuture<Client> createClient(@PayloadParam("name") String clientname);
/** /**
* @see ChefApi#createClient(String, CreateApiOptions) * @see ChefApi#createClient(String, CreateApiOptions)
*/ */
@ -195,7 +195,7 @@ public interface ChefAsyncApi {
@PUT @PUT
@Path("/clients/{clientname}") @Path("/clients/{clientname}")
ListenableFuture<Client> generateKeyForClient( ListenableFuture<Client> generateKeyForClient(
@PathParam("clientname") @BinderParam(BindGenerateKeyForClientToJsonPayload.class) String clientname); @PathParam("clientname") @BinderParam(BindGenerateKeyForClientToJsonPayload.class) String clientname);
/** /**
* @see ChefApi#clientExists(String) * @see ChefApi#clientExists(String)
@ -249,7 +249,7 @@ public interface ChefAsyncApi {
@PUT @PUT
@Path("/nodes/{nodename}") @Path("/nodes/{nodename}")
ListenableFuture<Node> updateNode( ListenableFuture<Node> updateNode(
@PathParam("nodename") @ParamParser(NodeName.class) @BinderParam(BindToJsonPayload.class) Node node); @PathParam("nodename") @ParamParser(NodeName.class) @BinderParam(BindToJsonPayload.class) Node node);
/** /**
* @see ChefApi#nodeExists(String) * @see ChefApi#nodeExists(String)
@ -303,7 +303,7 @@ public interface ChefAsyncApi {
@PUT @PUT
@Path("/roles/{rolename}") @Path("/roles/{rolename}")
ListenableFuture<Role> updateRole( ListenableFuture<Role> updateRole(
@PathParam("rolename") @ParamParser(RoleName.class) @BinderParam(BindToJsonPayload.class) Role role); @PathParam("rolename") @ParamParser(RoleName.class) @BinderParam(BindToJsonPayload.class) Role role);
/** /**
* @see ChefApi#roleExists(String) * @see ChefApi#roleExists(String)
@ -395,7 +395,7 @@ public interface ChefAsyncApi {
@POST @POST
@Path("/data/{databagName}") @Path("/data/{databagName}")
ListenableFuture<DatabagItem> createDatabagItem(@PathParam("databagName") String databagName, ListenableFuture<DatabagItem> createDatabagItem(@PathParam("databagName") String databagName,
@BinderParam(BindToJsonPayload.class) DatabagItem databagItem); @BinderParam(BindToJsonPayload.class) DatabagItem databagItem);
/** /**
* @see ChefApi#updateDatabagItem(String, DatabagItem) * @see ChefApi#updateDatabagItem(String, DatabagItem)
@ -404,8 +404,8 @@ public interface ChefAsyncApi {
@PUT @PUT
@Path("/data/{databagName}/{databagItemId}") @Path("/data/{databagName}/{databagItemId}")
ListenableFuture<DatabagItem> updateDatabagItem( ListenableFuture<DatabagItem> updateDatabagItem(
@PathParam("databagName") String databagName, @PathParam("databagName") String databagName,
@PathParam("databagItemId") @ParamParser(DatabagItemId.class) @BinderParam(BindToJsonPayload.class) DatabagItem item); @PathParam("databagItemId") @ParamParser(DatabagItemId.class) @BinderParam(BindToJsonPayload.class) DatabagItem item);
/** /**
* @see ChefApi#databagItemExists(String, String) * @see ChefApi#databagItemExists(String, String)
@ -415,7 +415,7 @@ public interface ChefAsyncApi {
@Path("/data/{databagName}/{databagItemId}") @Path("/data/{databagName}/{databagItemId}")
@Fallback(FalseOnNotFoundOr404.class) @Fallback(FalseOnNotFoundOr404.class)
ListenableFuture<Boolean> databagItemExists(@PathParam("databagName") String databagName, ListenableFuture<Boolean> databagItemExists(@PathParam("databagName") String databagName,
@PathParam("databagItemId") String databagItemId); @PathParam("databagItemId") String databagItemId);
/** /**
* @see ChefApi#getDatabagItem(String, String) * @see ChefApi#getDatabagItem(String, String)
@ -425,7 +425,7 @@ public interface ChefAsyncApi {
@Path("/data/{databagName}/{databagItemId}") @Path("/data/{databagName}/{databagItemId}")
@Fallback(NullOnNotFoundOr404.class) @Fallback(NullOnNotFoundOr404.class)
ListenableFuture<DatabagItem> getDatabagItem(@PathParam("databagName") String databagName, ListenableFuture<DatabagItem> getDatabagItem(@PathParam("databagName") String databagName,
@PathParam("databagItemId") String databagItemId); @PathParam("databagItemId") String databagItemId);
/** /**
* @see ChefApi#deleteDatabagItem(String, String) * @see ChefApi#deleteDatabagItem(String, String)
@ -435,7 +435,7 @@ public interface ChefAsyncApi {
@Path("/data/{databagName}/{databagItemId}") @Path("/data/{databagName}/{databagItemId}")
@Fallback(NullOnNotFoundOr404.class) @Fallback(NullOnNotFoundOr404.class)
ListenableFuture<DatabagItem> deleteDatabagItem(@PathParam("databagName") String databagName, ListenableFuture<DatabagItem> deleteDatabagItem(@PathParam("databagName") String databagName,
@PathParam("databagItemId") String databagItemId); @PathParam("databagItemId") String databagItemId);
/** /**
* @see ChefApi#listSearchIndexes() * @see ChefApi#listSearchIndexes()
@ -455,7 +455,7 @@ public interface ChefAsyncApi {
@Path("/search/role") @Path("/search/role")
@ResponseParser(ParseSearchRolesFromJson.class) @ResponseParser(ParseSearchRolesFromJson.class)
ListenableFuture<? extends SearchResult<? extends Role>> searchRoles(); ListenableFuture<? extends SearchResult<? extends Role>> searchRoles();
/** /**
* @see ChefApi#searchRoles(SearchOptions) * @see ChefApi#searchRoles(SearchOptions)
*/ */
@ -473,7 +473,7 @@ public interface ChefAsyncApi {
@Path("/search/client") @Path("/search/client")
@ResponseParser(ParseSearchClientsFromJson.class) @ResponseParser(ParseSearchClientsFromJson.class)
ListenableFuture<? extends SearchResult<? extends Client>> searchClients(); ListenableFuture<? extends SearchResult<? extends Client>> searchClients();
/** /**
* @see ChefApi#searchClients(SearchOptions) * @see ChefApi#searchClients(SearchOptions)
*/ */
@ -491,7 +491,7 @@ public interface ChefAsyncApi {
@Path("/search/node") @Path("/search/node")
@ResponseParser(ParseSearchNodesFromJson.class) @ResponseParser(ParseSearchNodesFromJson.class)
ListenableFuture<? extends SearchResult<? extends Node>> searchNodes(); ListenableFuture<? extends SearchResult<? extends Node>> searchNodes();
/** /**
* @see ChefApi#searchNodes(SearchOptions) * @see ChefApi#searchNodes(SearchOptions)
*/ */
@ -509,8 +509,8 @@ public interface ChefAsyncApi {
@Path("/search/{databagName}") @Path("/search/{databagName}")
@ResponseParser(ParseSearchDatabagFromJson.class) @ResponseParser(ParseSearchDatabagFromJson.class)
ListenableFuture<? extends SearchResult<? extends DatabagItem>> searchDatabag( ListenableFuture<? extends SearchResult<? extends DatabagItem>> searchDatabag(
@PathParam("databagName") String databagName); @PathParam("databagName") String databagName);
/** /**
* @see ChefApi#searchDatabag(String, SearchOptions) * @see ChefApi#searchDatabag(String, SearchOptions)
*/ */
@ -519,13 +519,13 @@ public interface ChefAsyncApi {
@Path("/search/{databagName}") @Path("/search/{databagName}")
@ResponseParser(ParseSearchDatabagFromJson.class) @ResponseParser(ParseSearchDatabagFromJson.class)
ListenableFuture<? extends SearchResult<? extends DatabagItem>> searchDatabag( ListenableFuture<? extends SearchResult<? extends DatabagItem>> searchDatabag(
@PathParam("databagName") String databagName, SearchOptions options); @PathParam("databagName") String databagName, SearchOptions options);
/** /**
* @see ChefApi#getResourceContents(Resource) * @see ChefApi#getResourceContents(Resource)
*/ */
@Named("content:get") @Named("content:get")
@GET @GET
@Fallback(NullOnNotFoundOr404.class) @Fallback(NullOnNotFoundOr404.class)
ListenableFuture<InputStream> getResourceContents(@EndpointParam(parser=UriForResource.class) Resource resource); ListenableFuture<InputStream> getResourceContents(@EndpointParam(parser = UriForResource.class) Resource resource);
} }

View File

@ -30,7 +30,7 @@ import com.google.inject.ImplementedBy;
* *
*/ */
@ImplementedBy(ChefContextImpl.class) @ImplementedBy(ChefContextImpl.class)
public interface ChefContext extends RestContext<ChefApi, ChefAsyncApi>{ public interface ChefContext extends RestContext<ChefApi, ChefAsyncApi> {
ChefService getChefService(); ChefService getChefService();

View File

@ -70,29 +70,28 @@ public class ChefContextFactory {
/** /**
* @see #createContext(String, String,String, Iterable, Properties) * @see #createContext(String, String,String, Iterable, Properties)
*/ */
public ChefContext createContext(String providerOrApi, Iterable<? extends Module> wiring, public ChefContext createContext(String providerOrApi, Iterable<? extends Module> wiring, Properties overrides) {
Properties overrides) {
return createContext(providerOrApi, null, null, wiring, overrides); return createContext(providerOrApi, null, null, wiring, overrides);
} }
/** /**
* @see #createContext(String, String,String, Iterable, Properties) * @see #createContext(String, String,String, Iterable, Properties)
*/ */
public ChefContext createContext(String providerOrApi, @Nullable String identity, public ChefContext createContext(String providerOrApi, @Nullable String identity, @Nullable String credential,
@Nullable String credential, Properties overrides) { Properties overrides) {
return createContext(providerOrApi, identity, credential, ImmutableSet.<Module> of(), overrides); return createContext(providerOrApi, identity, credential, ImmutableSet.<Module> of(), overrides);
} }
/** /**
* @see createContext(String, String,String, Iterable, Properties) * @see createContext(String, String,String, Iterable, Properties)
*/ */
public ChefContext createContext(String providerOrApi, @Nullable String identity, public ChefContext createContext(String providerOrApi, @Nullable String identity, @Nullable String credential,
@Nullable String credential, Iterable<? extends Module> wiring) { Iterable<? extends Module> wiring) {
return createContext(providerOrApi, identity, credential, wiring, new Properties()); return createContext(providerOrApi, identity, credential, wiring, new Properties());
} }
/** /**
* for porting old code to {@link ContextBuilder} * for porting old code to {@link ContextBuilder}
* *
* @param providerOrApi * @param providerOrApi
* @param identity * @param identity
@ -107,8 +106,8 @@ public class ChefContextFactory {
* @return initialized context ready for use * @return initialized context ready for use
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public ChefContext createContext(String providerOrApi, @Nullable String identity, public ChefContext createContext(String providerOrApi, @Nullable String identity, @Nullable String credential,
@Nullable String credential, Iterable<? extends Module> wiring, Properties overrides) { Iterable<? extends Module> wiring, Properties overrides) {
ContextBuilder builder = null; ContextBuilder builder = null;
try { try {
ProviderMetadata pm = Providers.withId(providerOrApi); ProviderMetadata pm = Providers.withId(providerOrApi);

View File

@ -63,8 +63,8 @@ public interface ChefService {
* *
* @param group * @param group
* corresponds to a configured * corresponds to a configured
* {@link org.jclouds.chef.config.ChefProperties#CHEF_BOOTSTRAP_DATABAG databag} * {@link org.jclouds.chef.config.ChefProperties#CHEF_BOOTSTRAP_DATABAG
* where run_list and other information are stored * databag} where run_list and other information are stored
* @return boot script * @return boot script
* @see #updateRunListForTag * @see #updateRunListForTag
*/ */
@ -74,13 +74,13 @@ public interface ChefService {
* assigns a run list to all nodes bootstrapped with a certain group * assigns a run list to all nodes bootstrapped with a certain group
* *
* @param runList * @param runList
* list of recipes or roles to assign. syntax is {@code recipe[name]} and {@code * list of recipes or roles to assign. syntax is
* role[name]} * {@code recipe[name]} and {@code role[name]}
* *
* @param group * @param group
* corresponds to a configured * corresponds to a configured
* {@link org.jclouds.chef.config.ChefProperties#CHEF_BOOTSTRAP_DATABAG databag} * {@link org.jclouds.chef.config.ChefProperties#CHEF_BOOTSTRAP_DATABAG
* where run_list and other information are stored * databag} where run_list and other information are stored
* @see #makeChefApiBootstrapScriptForTag * @see #makeChefApiBootstrapScriptForTag
*/ */
void updateRunListForGroup(Iterable<String> runList, String group); void updateRunListForGroup(Iterable<String> runList, String group);
@ -88,8 +88,8 @@ public interface ChefService {
/** /**
* @param group * @param group
* corresponds to a configured * corresponds to a configured
* {@link org.jclouds.chef.config.ChefProperties#CHEF_BOOTSTRAP_DATABAG databag} * {@link org.jclouds.chef.config.ChefProperties#CHEF_BOOTSTRAP_DATABAG
* where run_list and other information are stored * databag} where run_list and other information are stored
* @return run list for all nodes bootstrapped with a certain group * @return run list for all nodes bootstrapped with a certain group
* @see #updateRunListForTag * @see #updateRunListForTag
*/ */

View File

@ -41,7 +41,7 @@ import org.jclouds.rest.binders.BindToStringPayload;
public class BindChecksumsToJsonPayload extends BindToStringPayload { public class BindChecksumsToJsonPayload extends BindToStringPayload {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public HttpRequest bindToRequest( HttpRequest request, Object input ) { public HttpRequest bindToRequest(HttpRequest request, Object input) {
checkArgument(checkNotNull(input, "input") instanceof Set, "this binder is only valid for Set!"); checkArgument(checkNotNull(input, "input") instanceof Set, "this binder is only valid for Set!");
Set<List<Byte>> md5s = (Set<List<Byte>>) input; Set<List<Byte>> md5s = (Set<List<Byte>>) input;

View File

@ -33,7 +33,7 @@ import org.jclouds.rest.binders.BindToStringPayload;
public class BindClientnameToJsonPayload extends BindToStringPayload { public class BindClientnameToJsonPayload extends BindToStringPayload {
@Override @Override
public <R extends HttpRequest> R bindToRequest(R request, Object payload ) { public <R extends HttpRequest> R bindToRequest(R request, Object payload) {
super.bindToRequest(request, String.format("{\"clientname\":\"%s\"}", payload)); super.bindToRequest(request, String.format("{\"clientname\":\"%s\"}", payload));
request.getPayload().getContentMetadata().setContentType(MediaType.APPLICATION_JSON); request.getPayload().getContentMetadata().setContentType(MediaType.APPLICATION_JSON);
return request; return request;

View File

@ -40,38 +40,36 @@ import com.google.common.collect.Iterables;
* *
* @author Ignasi Barrera * @author Ignasi Barrera
*/ */
public class BindCreateClientOptionsToJsonPayload extends BindToJsonPayload public class BindCreateClientOptionsToJsonPayload extends BindToJsonPayload {
{ @Inject
@Inject public BindCreateClientOptionsToJsonPayload(Json jsonBinder) {
public BindCreateClientOptionsToJsonPayload(Json jsonBinder) { super(jsonBinder);
super(jsonBinder); }
}
@Override @Override
public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) { public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {
checkArgument(checkNotNull(request, "request") instanceof GeneratedHttpRequest, checkArgument(checkNotNull(request, "request") instanceof GeneratedHttpRequest,
"this binder is only valid for GeneratedHttpRequests"); "this binder is only valid for GeneratedHttpRequests");
GeneratedHttpRequest gRequest = (GeneratedHttpRequest) request; GeneratedHttpRequest gRequest = (GeneratedHttpRequest) request;
checkState(gRequest.getInvocation().getArgs() != null, "args should be initialized at this point"); checkState(gRequest.getInvocation().getArgs() != null, "args should be initialized at this point");
String name = checkNotNull(postParams.remove("name"), "name").toString(); String name = checkNotNull(postParams.remove("name"), "name").toString();
CreateClientOptions options = (CreateClientOptions) Iterables.find(gRequest.getInvocation().getArgs(), CreateClientOptions options = (CreateClientOptions) Iterables.find(gRequest.getInvocation().getArgs(),
Predicates.instanceOf(CreateClientOptions.class)); Predicates.instanceOf(CreateClientOptions.class));
return bindToRequest(request, new CreateClientParams(name, options)); return bindToRequest(request, new CreateClientParams(name, options));
} }
@SuppressWarnings("unused") @SuppressWarnings("unused")
private static class CreateClientParams private static class CreateClientParams {
{ private String name;
private String name;
private boolean admin;
private boolean admin;
public CreateClientParams(String name, CreateClientOptions options) {
public CreateClientParams(String name, CreateClientOptions options) { this.name = name;
this.name = name; this.admin = options.isAdmin();
this.admin = options.isAdmin(); }
} }
}
} }

View File

@ -33,9 +33,8 @@ import org.jclouds.rest.binders.BindToStringPayload;
public class BindGenerateKeyForClientToJsonPayload extends BindToStringPayload { public class BindGenerateKeyForClientToJsonPayload extends BindToStringPayload {
@Override @Override
public <R extends HttpRequest> R bindToRequest(R request, Object payload ) { public <R extends HttpRequest> R bindToRequest(R request, Object payload) {
super.bindToRequest(request, String.format("{\"name\":\"%s\", \"private_key\": true}", super.bindToRequest(request, String.format("{\"name\":\"%s\", \"private_key\": true}", payload));
payload));
request.getPayload().getContentMetadata().setContentType(MediaType.APPLICATION_JSON); request.getPayload().getContentMetadata().setContentType(MediaType.APPLICATION_JSON);
return request; return request;
} }

View File

@ -33,7 +33,7 @@ import org.jclouds.rest.binders.BindToStringPayload;
public class BindIsCompletedToJsonPayload extends BindToStringPayload { public class BindIsCompletedToJsonPayload extends BindToStringPayload {
@Override @Override
public <R extends HttpRequest> R bindToRequest(R request, Object payload ) { public <R extends HttpRequest> R bindToRequest(R request, Object payload) {
super.bindToRequest(request, String.format("{\"is_completed\":%s}", payload)); super.bindToRequest(request, String.format("{\"is_completed\":%s}", payload));
request.getPayload().getContentMetadata().setContentType(MediaType.APPLICATION_JSON); request.getPayload().getContentMetadata().setContentType(MediaType.APPLICATION_JSON);
return request; return request;

View File

@ -33,7 +33,7 @@ import org.jclouds.rest.binders.BindToStringPayload;
public class BindNameToJsonPayload extends BindToStringPayload { public class BindNameToJsonPayload extends BindToStringPayload {
@Override @Override
public <R extends HttpRequest> R bindToRequest(R request, Object payload ) { public <R extends HttpRequest> R bindToRequest(R request, Object payload) {
super.bindToRequest(request, String.format("{\"name\":\"%s\"}", payload)); super.bindToRequest(request, String.format("{\"name\":\"%s\"}", payload));
request.getPayload().getContentMetadata().setContentType(MediaType.APPLICATION_JSON); request.getPayload().getContentMetadata().setContentType(MediaType.APPLICATION_JSON);
return request; return request;

View File

@ -79,7 +79,7 @@ public class BaseChefRestClientModule<S, A> extends RestClientModule<S, A> {
} }
protected BaseChefRestClientModule(TypeToken<S> syncApiType, TypeToken<A> asyncApiType, protected BaseChefRestClientModule(TypeToken<S> syncApiType, TypeToken<A> asyncApiType,
Map<Class<?>, Class<?>> delegates) { Map<Class<?>, Class<?>> delegates) {
super(syncApiType, asyncApiType, delegates); super(syncApiType, asyncApiType, delegates);
} }
@ -102,7 +102,7 @@ public class BaseChefRestClientModule<S, A> extends RestClientModule<S, A> {
}, seconds, TimeUnit.SECONDS); }, seconds, TimeUnit.SECONDS);
} }
// TODO: potentially change this // TODO: potentially change this
@Provides @Provides
@Singleton @Singleton
public Supplier<PrivateKey> supplyKey(final LoadingCache<Credentials, PrivateKey> keyCache, public Supplier<PrivateKey> supplyKey(final LoadingCache<Credentials, PrivateKey> keyCache,
@ -122,8 +122,9 @@ public class BaseChefRestClientModule<S, A> extends RestClientModule<S, A> {
} }
/** /**
* it is relatively expensive to extract a private key from a PEM. cache the relationship between current credentials * it is relatively expensive to extract a private key from a PEM. cache the
* so that the private key is only recalculated once. * relationship between current credentials so that the private key is only
* recalculated once.
*/ */
@VisibleForTesting @VisibleForTesting
@Singleton @Singleton
@ -146,35 +147,37 @@ public class BaseChefRestClientModule<S, A> extends RestClientModule<S, A> {
} }
} }
} }
@Provides @Provides
@Singleton @Singleton
@Validator @Validator
public Optional<String> provideValidatorName(Injector injector) { public Optional<String> provideValidatorName(Injector injector) {
// Named properties can not be injected as optional here, so let's use the injector to bypass it // Named properties can not be injected as optional here, so let's use the
Key<String> key = Key.get(String.class, Names.named(CHEF_VALIDATOR_NAME)); // injector to bypass it
try { Key<String> key = Key.get(String.class, Names.named(CHEF_VALIDATOR_NAME));
return Optional.<String> of(injector.getInstance(key)); try {
} catch (ConfigurationException ex) { return Optional.<String> of(injector.getInstance(key));
return Optional.<String> absent(); } catch (ConfigurationException ex) {
} return Optional.<String> absent();
}
} }
@Provides @Provides
@Singleton @Singleton
@Validator @Validator
public Optional<PrivateKey> provideValidatorCredential(Crypto crypto, Injector injector) public Optional<PrivateKey> provideValidatorCredential(Crypto crypto, Injector injector)
throws InvalidKeySpecException, IOException { throws InvalidKeySpecException, IOException {
// Named properties can not be injected as optional here, so let's use the injector to bypass it // Named properties can not be injected as optional here, so let's use the
Key<String> key = Key.get(String.class, Names.named(CHEF_VALIDATOR_CREDENTIAL)); // injector to bypass it
try { Key<String> key = Key.get(String.class, Names.named(CHEF_VALIDATOR_CREDENTIAL));
String validatorCredential = injector.getInstance(key); try {
PrivateKey validatorKey = crypto.rsaKeyFactory().generatePrivate( String validatorCredential = injector.getInstance(key);
Pems.privateKeySpec(InputSuppliers.of(validatorCredential))); PrivateKey validatorKey = crypto.rsaKeyFactory().generatePrivate(
return Optional.<PrivateKey> of(validatorKey); Pems.privateKeySpec(InputSuppliers.of(validatorCredential)));
} catch (ConfigurationException ex) { return Optional.<PrivateKey> of(validatorKey);
return Optional.<PrivateKey> absent(); } catch (ConfigurationException ex) {
} return Optional.<PrivateKey> absent();
}
} }
@Override @Override

View File

@ -169,13 +169,13 @@ public class ChefParserModule extends AbstractModule {
} }
} }
/** /**
* writes or reads the literal directly * writes or reads the literal directly
*/ */
@Singleton @Singleton
public static class DataBagItemAdapter extends NullHackJsonLiteralAdapter<DatabagItem> { public static class DataBagItemAdapter extends NullHackJsonLiteralAdapter<DatabagItem> {
final Gson gson = new Gson(); final Gson gson = new Gson();
@Override @Override
protected DatabagItem createJsonLiteralFromRawJson(String text) { protected DatabagItem createJsonLiteralFromRawJson(String text) {
IdHolder idHolder = gson.fromJson(text, IdHolder.class); IdHolder idHolder = gson.fromJson(text, IdHolder.class);
@ -184,7 +184,7 @@ public class ChefParserModule extends AbstractModule {
text = text.replaceFirst(String.format("\\{\"id\"[ ]?:\"%s\",", idHolder.id), "{"); text = text.replaceFirst(String.format("\\{\"id\"[ ]?:\"%s\",", idHolder.id), "{");
return new DatabagItem(idHolder.id, text); return new DatabagItem(idHolder.id, text);
} }
@Override @Override
protected String toString(DatabagItem value) { protected String toString(DatabagItem value) {
String text = value.toString(); String text = value.toString();
@ -195,7 +195,7 @@ public class ChefParserModule extends AbstractModule {
text = text.replaceFirst("\\{", String.format("{\"id\":\"%s\",", value.getId())); text = text.replaceFirst("\\{", String.format("{\"id\":\"%s\",", value.getId()));
else else
checkArgument(value.getId().equals(idHolder.id), checkArgument(value.getId().equals(idHolder.id),
"incorrect id in databagItem text, should be %s: was %s", value.getId(), idHolder.id); "incorrect id in databagItem text, should be %s: was %s", value.getId(), idHolder.id);
} catch (JsonSyntaxException e) { } catch (JsonSyntaxException e) {
throw new IllegalArgumentException(e); throw new IllegalArgumentException(e);
} }
@ -203,7 +203,7 @@ public class ChefParserModule extends AbstractModule {
return text; return text;
} }
} }
private static class IdHolder { private static class IdHolder {
private String id; private String id;
} }
@ -215,35 +215,35 @@ public class ChefParserModule extends AbstractModule {
return ImmutableMap.<Type, Object> of(DatabagItem.class, adapter, PrivateKey.class, privateAdapter, return ImmutableMap.<Type, Object> of(DatabagItem.class, adapter, PrivateKey.class, privateAdapter,
PublicKey.class, publicAdapter, X509Certificate.class, certAdapter); PublicKey.class, publicAdapter, X509Certificate.class, certAdapter);
} }
@Provides @Provides
@Singleton @Singleton
@CookbookParser @CookbookParser
public Function<HttpResponse, Set<String>> provideCookbookDefinitionAdapter(@ApiVersion String apiVersion, public Function<HttpResponse, Set<String>> provideCookbookDefinitionAdapter(@ApiVersion String apiVersion,
ParseCookbookDefinitionFromJson v10parser, ParseKeySetFromJson v09parser) { ParseCookbookDefinitionFromJson v10parser, ParseKeySetFromJson v09parser) {
Pattern versionPattern = Pattern.compile("\\d\\.(\\d)\\.\\d"); Pattern versionPattern = Pattern.compile("\\d\\.(\\d)\\.\\d");
Matcher m = versionPattern.matcher(apiVersion); Matcher m = versionPattern.matcher(apiVersion);
if (m.matches()) { if (m.matches()) {
return Integer.valueOf(m.group(1)) > 9? v10parser : v09parser; return Integer.valueOf(m.group(1)) > 9 ? v10parser : v09parser;
} else { } else {
// Default to the latest version of the parser // Default to the latest version of the parser
return v10parser; return v10parser;
} }
} }
@Provides @Provides
@Singleton @Singleton
@CookbookVersionsParser @CookbookVersionsParser
public Function<HttpResponse, Set<String>> provideCookbookDefinitionAdapter(@ApiVersion String apiVersion, public Function<HttpResponse, Set<String>> provideCookbookDefinitionAdapter(@ApiVersion String apiVersion,
ParseCookbookVersionsV10FromJson v10parser, ParseCookbookVersionsV09FromJson v09parser) { ParseCookbookVersionsV10FromJson v10parser, ParseCookbookVersionsV09FromJson v09parser) {
Pattern versionPattern = Pattern.compile("\\d\\.(\\d)\\.\\d"); Pattern versionPattern = Pattern.compile("\\d\\.(\\d)\\.\\d");
Matcher m = versionPattern.matcher(apiVersion); Matcher m = versionPattern.matcher(apiVersion);
if (m.matches()) { if (m.matches()) {
return Integer.valueOf(m.group(1)) > 9? v10parser : v09parser; return Integer.valueOf(m.group(1)) > 9 ? v10parser : v09parser;
} else { } else {
// Default to the latest version of the parser // Default to the latest version of the parser
return v10parser; return v10parser;
} }
} }
@Override @Override

View File

@ -27,42 +27,40 @@ import org.jclouds.chef.ChefService;
*/ */
public interface ChefProperties { public interface ChefProperties {
/** /**
* The name of the Chef logger. * The name of the Chef logger.
*/ */
public static final String CHEF_LOGGER = "jclouds.chef"; public static final String CHEF_LOGGER = "jclouds.chef";
public static final String CHEF_SERVICE_CLIENT = "chef.service-api";
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";
/** public static final String CHEF_SERVICE_CLIENT = "chef.service-api";
* Ddatabag that holds chef bootstrap hints, should be a json ball in the public static final String CHEF_NODE = "chef.node";
* following format: public static final String CHEF_NODE_PATTERN = "chef.node-pattern";
* <p> public static final String CHEF_RUN_LIST = "chef.run-list";
* {"tag":{"run_list":["recipe[apache2]"]}}
*/
public static final String CHEF_BOOTSTRAP_DATABAG = "chef.bootstrap-databag";
/** /**
* The name of the validator client used to allow nodes to autoregister in * Ddatabag that holds chef bootstrap hints, should be a json ball in the
* the Chef server. * following format:
* <p> * <p>
* This property must be set prior to running the * {"tag":{"run_list":["recipe[apache2]"]}}
* {@link ChefService#createBootstrapScriptForGroup(String)} */
* method. public static final String CHEF_BOOTSTRAP_DATABAG = "chef.bootstrap-databag";
*/
public static final String CHEF_VALIDATOR_NAME = "chef.validator-name";
/** /**
* The credential of the validator client used to allow nodes to * The name of the validator client used to allow nodes to autoregister in
* autoregister in the Chef server. * the Chef server.
* <p> * <p>
* This property must be set prior to running the * This property must be set prior to running the
* {@link ChefService#createBootstrapScriptForGroup(String)} * {@link ChefService#createBootstrapScriptForGroup(String)} method.
* method. */
*/ public static final String CHEF_VALIDATOR_NAME = "chef.validator-name";
public static final String CHEF_VALIDATOR_CREDENTIAL = "chef.validator-credential";
/**
* The credential of the validator client used to allow nodes to autoregister
* in the Chef server.
* <p>
* This property must be set prior to running the
* {@link ChefService#createBootstrapScriptForGroup(String)} method.
*/
public static final String CHEF_VALIDATOR_CREDENTIAL = "chef.validator-credential";
} }

View File

@ -31,15 +31,15 @@ import javax.inject.Qualifier;
/** /**
* Used to configure the cookbook Json parser. * Used to configure the cookbook Json parser.
* <p> * <p>
* Chef Server version 0.9 and 0.10 return a different Json when rquesting the cookbook * Chef Server version 0.9 and 0.10 return a different Json when rquesting the
* definitions. This annotation can be used to setup the cookbook parser. * cookbook definitions. This annotation can be used to setup the cookbook
* parser.
* *
* @author Ignasi Barrera * @author Ignasi Barrera
*/ */
@Target({METHOD, PARAMETER, FIELD}) @Target({ METHOD, PARAMETER, FIELD })
@Retention(RUNTIME) @Retention(RUNTIME)
@Qualifier @Qualifier
public @interface CookbookParser public @interface CookbookParser {
{
} }

View File

@ -31,15 +31,15 @@ import javax.inject.Qualifier;
/** /**
* Used to configure the cookbook versions Json parser. * Used to configure the cookbook versions Json parser.
* <p> * <p>
* Chef Server version 0.9 and 0.10 return a different Json when rquesting the cookbook * Chef Server version 0.9 and 0.10 return a different Json when rquesting the
* versions. This annotation can be used to setup the cookbook versions parser. * cookbook versions. This annotation can be used to setup the cookbook versions
* parser.
* *
* @author Ignasi Barrera * @author Ignasi Barrera
*/ */
@Target({METHOD, PARAMETER, FIELD}) @Target({ METHOD, PARAMETER, FIELD })
@Retention(RUNTIME) @Retention(RUNTIME)
@Qualifier @Qualifier
public @interface CookbookVersionsParser public @interface CookbookVersionsParser {
{
} }

View File

@ -36,7 +36,7 @@ import javax.inject.Qualifier;
* *
* @author Ignasi Barrera * @author Ignasi Barrera
*/ */
@Target({METHOD, PARAMETER, FIELD}) @Target({ METHOD, PARAMETER, FIELD })
@Retention(RUNTIME) @Retention(RUNTIME)
@Qualifier @Qualifier
public @interface Validator { public @interface Validator {

View File

@ -71,7 +71,7 @@ public class Client {
@Override @Override
public String toString() { public String toString() {
return "[name=" + name + ", clientname=" + clientname + ", orgname=" + orgname + ", isValidator=" + validator return "[name=" + name + ", clientname=" + clientname + ", orgname=" + orgname + ", isValidator=" + validator
+ ", certificate=" + certificate + ", privateKey=" + (privateKey != null) + "]"; + ", certificate=" + certificate + ", privateKey=" + (privateKey != null) + "]";
} }
@Override @Override
@ -127,7 +127,7 @@ public class Client {
} }
public Client(X509Certificate certificate, String orgname, String clientname, String name, boolean isValidator, public Client(X509Certificate certificate, String orgname, String clientname, String name, boolean isValidator,
@Nullable PrivateKey privateKey) { @Nullable PrivateKey privateKey) {
this.certificate = certificate; this.certificate = certificate;
this.orgname = orgname; this.orgname = orgname;
this.clientname = clientname; this.clientname = clientname;

View File

@ -29,129 +29,120 @@ import com.google.common.collect.Sets;
* @author Ignasi Barrera * @author Ignasi Barrera
*/ */
public class CookbookDefinition { public class CookbookDefinition {
private URI url;
private Set<Version> versions = Sets.newLinkedHashSet();
// only for deserialization
CookbookDefinition() {
} private URI url;
private Set<Version> versions = Sets.newLinkedHashSet();
public CookbookDefinition(URI url, Set<Version> versions) {
this.url = url;
this.versions = versions;
}
public URI getUrl() {
return url;
}
public Set<Version> getVersions() { // only for deserialization
return versions; CookbookDefinition() {
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((url == null) ? 0 : url.hashCode());
result = prime * result + ((versions == null) ? 0 : versions.hashCode());
return result;
}
@Override }
public boolean equals(Object obj) {
if (this == obj) public CookbookDefinition(URI url, Set<Version> versions) {
this.url = url;
this.versions = versions;
}
public URI getUrl() {
return url;
}
public Set<Version> getVersions() {
return versions;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((url == null) ? 0 : url.hashCode());
result = prime * result + ((versions == null) ? 0 : versions.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;
CookbookDefinition other = (CookbookDefinition) obj;
if (url == null) {
if (other.url != null)
return false;
} else if (!url.equals(other.url))
return false;
if (versions == null) {
if (other.versions != null)
return false;
} else if (!versions.equals(other.versions))
return false;
return true;
}
@Override
public String toString() {
return "CookbookDefinition [url=" + url + ", versions=" + versions + "]";
}
public static class Version {
private URI url;
private String version;
// only for deserialization
Version() {
}
public Version(URI url, String version) {
this.url = url;
this.version = version;
}
public URI getUrl() {
return url;
}
public String getVersion() {
return version;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((url == null) ? 0 : url.hashCode());
result = prime * result + ((version == null) ? 0 : version.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true; return true;
if (obj == null) if (obj == null)
return false; return false;
if (getClass() != obj.getClass()) if (getClass() != obj.getClass())
return false; return false;
CookbookDefinition other = (CookbookDefinition) obj; Version other = (Version) obj;
if (url == null) if (url == null) {
{
if (other.url != null) if (other.url != null)
return false; return false;
} } else if (!url.equals(other.url))
else if (!url.equals(other.url))
return false; return false;
if (versions == null) if (version == null) {
{ if (other.version != null)
if (other.versions != null) return false;
return false; } else if (!version.equals(other.version))
}
else if (!versions.equals(other.versions))
return false; return false;
return true; return true;
} }
@Override @Override
public String toString() { public String toString() {
return "CookbookDefinition [url=" + url + ", versions=" + versions + "]"; return "Version [url=" + url + ", version=" + version + "]";
} }
}
public static class Version {
private URI url;
private String version;
// only for deserialization
Version() {
}
public Version(URI url, String version) {
this.url = url;
this.version = version;
}
public URI getUrl() {
return url;
}
public String getVersion() {
return version;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((url == null) ? 0 : url.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;
Version other = (Version) obj;
if (url == null)
{
if (other.url != null)
return false;
}
else if (!url.equals(other.url))
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 "Version [url=" + url + ", version=" + version + "]";
}
}
} }

View File

@ -62,9 +62,9 @@ public class CookbookVersion {
} }
public CookbookVersion(String name, Set<Resource> definitions, Set<Attribute> attributes, Set<Resource> files, public CookbookVersion(String name, Set<Resource> definitions, Set<Attribute> attributes, Set<Resource> files,
Metadata metadata, Set<Resource> providers, String cookbookName, Set<Resource> resources, Metadata metadata, Set<Resource> providers, String cookbookName, Set<Resource> resources,
Set<Resource> templates, Set<Resource> libraries, String version, Set<Resource> recipes, Set<Resource> templates, Set<Resource> libraries, String version, Set<Resource> recipes,
Set<Resource> rootFiles) { Set<Resource> rootFiles) {
this.name = name; this.name = name;
Iterables.addAll(this.definitions, definitions); Iterables.addAll(this.definitions, definitions);
Iterables.addAll(this.attributes, attributes); Iterables.addAll(this.attributes, attributes);
@ -237,9 +237,9 @@ public class CookbookVersion {
@Override @Override
public String toString() { public String toString() {
return "Cookbook [attributes=" + attributes + ", cookbookName=" + cookbookName + ", definitions=" + definitions return "Cookbook [attributes=" + attributes + ", cookbookName=" + cookbookName + ", definitions=" + definitions
+ ", files=" + files + ", libraries=" + libraries + ", metadata=" + metadata + ", name=" + name + ", files=" + files + ", libraries=" + libraries + ", metadata=" + metadata + ", name=" + name
+ ", providers=" + providers + ", recipes=" + recipes + ", resources=" + resources + ", rootFiles=" + ", providers=" + providers + ", recipes=" + recipes + ", resources=" + resources + ", rootFiles="
+ rootFiles + ", templates=" + templates + ", version=" + version + "]"; + rootFiles + ", templates=" + templates + ", version=" + version + "]";
} }
} }

View File

@ -51,10 +51,10 @@ public class Metadata {
private Map<String, String> recommendations = Maps.newLinkedHashMap(); private Map<String, String> recommendations = Maps.newLinkedHashMap();
public Metadata(String license, String maintainer, Map<String, String> suggestions, public Metadata(String license, String maintainer, Map<String, String> suggestions,
Map<String, String> dependencies, String maintainerEmail, Map<String, String> conflicting, Map<String, String> dependencies, String maintainerEmail, Map<String, String> conflicting, String description,
String description, Map<String,String> providing, Map<String, String> platforms, String version, Map<String, String> providing, Map<String, String> platforms, String version, Map<String, String> recipes,
Map<String, String> recipes, Map<String, String> replacing, String name, Map<String, String> groupings, Map<String, String> replacing, String name, Map<String, String> groupings, String longDescription,
String longDescription, Map<String, Attribute> attributes, Map<String, String> recommendations) { Map<String, Attribute> attributes, Map<String, String> recommendations) {
this.license = license; this.license = license;
this.maintainer = maintainer; this.maintainer = maintainer;
this.suggestions.putAll(suggestions); this.suggestions.putAll(suggestions);

View File

@ -57,8 +57,8 @@ public class Node {
private String _jsonClass = "Chef::Node"; private String _jsonClass = "Chef::Node";
public Node(String name, Map<String, JsonBall> normal, Map<String, JsonBall> override, public Node(String name, Map<String, JsonBall> normal, Map<String, JsonBall> override,
Map<String, JsonBall> defaultA, Map<String, JsonBall> automatic, Iterable<String> runList) { Map<String, JsonBall> defaultA, Map<String, JsonBall> automatic, Iterable<String> runList) {
this(name, normal, override, defaultA, automatic, runList, null); this(name, normal, override, defaultA, automatic, runList, null);
} }
/** /**
@ -83,7 +83,7 @@ public class Node {
} }
public Node(String name, Iterable<String> runList) { public Node(String name, Iterable<String> runList) {
this(name, runList, "_default"); this(name, runList, "_default");
} }
/** /**

View File

@ -40,7 +40,7 @@ public class Resource {
public Resource(FilePayload payload) { public Resource(FilePayload payload) {
this(payload.getRawContent().getName(), null, payload.getContentMetadata().getContentMD5(), payload this(payload.getRawContent().getName(), null, payload.getContentMetadata().getContentMD5(), payload
.getRawContent().getPath(), "default"); .getRawContent().getPath(), "default");
} }
public Resource(String name, byte[] checksum, String path) { public Resource(String name, byte[] checksum, String path) {
@ -127,8 +127,8 @@ public class Resource {
@Override @Override
public String toString() { public String toString() {
return "Resource [checksum=" + Bytes.asList(checksum) + ", name=" + name + ", path=" + path return "Resource [checksum=" + Bytes.asList(checksum) + ", name=" + name + ", path=" + path + ", specificity="
+ ", specificity=" + specificity + ", url=" + url + "]"; + specificity + ", url=" + url + "]";
} }
} }

View File

@ -83,7 +83,6 @@ public class SignedHeaderAuth implements HttpRequestFilter {
@Named(Constants.LOGGER_SIGNATURE) @Named(Constants.LOGGER_SIGNATURE)
Logger signatureLog = Logger.NULL; Logger signatureLog = Logger.NULL;
@Inject @Inject
public SignedHeaderAuth(SignatureWire signatureWire, @org.jclouds.location.Provider Supplier<Credentials> creds, public SignedHeaderAuth(SignatureWire signatureWire, @org.jclouds.location.Provider Supplier<Credentials> creds,
Supplier<PrivateKey> supplyKey, @TimeStamp Provider<String> timeStampProvider, HttpUtils utils) { Supplier<PrivateKey> supplyKey, @TimeStamp Provider<String> timeStampProvider, HttpUtils utils) {
@ -95,24 +94,24 @@ public class SignedHeaderAuth implements HttpRequestFilter {
this.utils = utils; this.utils = utils;
} }
public HttpRequest filter( HttpRequest request ) throws HttpException { public HttpRequest filter(HttpRequest request) throws HttpException {
String contentHash = hashBody(request.getPayload()); String contentHash = hashBody(request.getPayload());
Multimap<String, String> headers = ArrayListMultimap.create(); Multimap<String, String> headers = ArrayListMultimap.create();
headers.put( "X-Ops-Content-Hash", contentHash ); headers.put("X-Ops-Content-Hash", contentHash);
String timestamp = timeStampProvider.get(); String timestamp = timeStampProvider.get();
String toSign = createStringToSign(request.getMethod(), hashPath(request.getEndpoint().getPath()), contentHash, String toSign = createStringToSign(request.getMethod(), hashPath(request.getEndpoint().getPath()), contentHash,
timestamp); timestamp);
headers.put("X-Ops-Userid", creds.get().identity); headers.put("X-Ops-Userid", creds.get().identity);
headers.put( "X-Ops-Sign", SIGNING_DESCRIPTION ); headers.put("X-Ops-Sign", SIGNING_DESCRIPTION);
request = calculateAndReplaceAuthorizationHeaders( request, toSign ); request = calculateAndReplaceAuthorizationHeaders(request, toSign);
headers.put( "X-Ops-Timestamp", timestamp ); headers.put("X-Ops-Timestamp", timestamp);
utils.logRequest( signatureLog, request, "<<" ); utils.logRequest(signatureLog, request, "<<");
return request.toBuilder().replaceHeaders(headers).build(); return request.toBuilder().replaceHeaders(headers).build();
} }
@VisibleForTesting @VisibleForTesting
HttpRequest calculateAndReplaceAuthorizationHeaders( HttpRequest request, String toSign ) throws HttpException { HttpRequest calculateAndReplaceAuthorizationHeaders(HttpRequest request, String toSign) throws HttpException {
String signature = sign(toSign); String signature = sign(toSign);
if (signatureWire.enabled()) if (signatureWire.enabled())
signatureWire.input(Strings2.toInputStream(signature)); signatureWire.input(Strings2.toInputStream(signature));
@ -145,8 +144,8 @@ public class SignedHeaderAuth implements HttpRequestFilter {
} }
/** /**
* Build the canonicalized path, which collapses multiple slashes (/) and removes a trailing * Build the canonicalized path, which collapses multiple slashes (/) and
* slash unless the path is only "/" * removes a trailing slash unless the path is only "/"
*/ */
@VisibleForTesting @VisibleForTesting
String canonicalPath(String path) { String canonicalPath(String path) {

View File

@ -59,7 +59,7 @@ public class ClientForGroup implements Function<String, Client> {
Set<String> names = newHashSet(clients); Set<String> names = newHashSet(clients);
int index = 0; int index = 0;
while (true) { while (true) {
clientName = String.format(pattern,index++); clientName = String.format(pattern, index++);
if (!names.contains(clientName)) if (!names.contains(clientName))
break; break;
} }

View File

@ -48,6 +48,6 @@ public class ParseCookbookDefinitionCheckingChefVersion implements Function<Http
@Override @Override
public Set<String> apply(HttpResponse response) { public Set<String> apply(HttpResponse response) {
return parser.apply(response); return parser.apply(response);
} }
} }

View File

@ -31,7 +31,8 @@ import org.jclouds.http.functions.ParseJson;
import com.google.common.base.Function; import com.google.common.base.Function;
/** /**
* Parses a cookbook definition from a Json response, assuming a Chef Server >= 0.10.8. * Parses a cookbook definition from a Json response, assuming a Chef Server >=
* 0.10.8.
* *
* @author Ignasi Barrera * @author Ignasi Barrera
*/ */
@ -48,6 +49,6 @@ public class ParseCookbookDefinitionFromJson implements Function<HttpResponse, S
@Override @Override
public Set<String> apply(HttpResponse response) { public Set<String> apply(HttpResponse response) {
return parser.apply(response).keySet(); return parser.apply(response).keySet();
} }
} }

View File

@ -48,6 +48,6 @@ public class ParseCookbookVersionsCheckingChefVersion implements Function<HttpRe
@Override @Override
public Set<String> apply(HttpResponse response) { public Set<String> apply(HttpResponse response) {
return parser.apply(response); return parser.apply(response);
} }
} }

View File

@ -32,6 +32,7 @@ import com.google.common.collect.Iterables;
/** /**
* Parses the cookbook versions in a Chef Server <= 0.9.8. * Parses the cookbook versions in a Chef Server <= 0.9.8.
*
* @author Ignasi Barrera * @author Ignasi Barrera
*/ */
@Singleton @Singleton

View File

@ -35,13 +35,14 @@ import com.google.common.collect.Sets;
/** /**
* Parses the cookbook versions in a Chef Server >= 0.10.8. * Parses the cookbook versions in a Chef Server >= 0.10.8.
*
* @author Ignasi Barrera * @author Ignasi Barrera
*/ */
@Singleton @Singleton
public class ParseCookbookVersionsV10FromJson implements Function<HttpResponse, Set<String>> { public class ParseCookbookVersionsV10FromJson implements Function<HttpResponse, Set<String>> {
/** Parser for responses from chef server >= 0.10.8 */ /** Parser for responses from chef server >= 0.10.8 */
private final ParseJson<Map<String, CookbookDefinition>> parser; private final ParseJson<Map<String, CookbookDefinition>> parser;
@Inject @Inject
ParseCookbookVersionsV10FromJson(ParseJson<Map<String, CookbookDefinition>> parser) { ParseCookbookVersionsV10FromJson(ParseJson<Map<String, CookbookDefinition>> parser) {
@ -52,11 +53,10 @@ public class ParseCookbookVersionsV10FromJson implements Function<HttpResponse,
public Set<String> apply(HttpResponse response) { public Set<String> apply(HttpResponse response) {
CookbookDefinition def = Iterables.getFirst(parser.apply(response).values(), null); CookbookDefinition def = Iterables.getFirst(parser.apply(response).values(), null);
return Sets.newLinkedHashSet(Iterables.transform(def.getVersions(), new Function<Version, String>() { return Sets.newLinkedHashSet(Iterables.transform(def.getVersions(), new Function<Version, String>() {
@Override @Override
public String apply(Version input) public String apply(Version input) {
{ return input.getVersion();
return input.getVersion(); }
}}) }));
);
} }
} }

View File

@ -37,45 +37,45 @@ import com.google.gson.annotations.SerializedName;
/** /**
* Parses the search result into a {@link DatabagItem} object. * Parses the search result into a {@link DatabagItem} object.
* <p> * <p>
* When searching databags, the items are contained inside the <code>raw_data</code> list. * When searching databags, the items are contained inside the
* <code>raw_data</code> list.
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
@Singleton @Singleton
public class ParseSearchDatabagFromJson implements Function<HttpResponse, SearchResult<DatabagItem>> { public class ParseSearchDatabagFromJson implements Function<HttpResponse, SearchResult<DatabagItem>> {
private final ParseJson<Response> responseParser; private final ParseJson<Response> responseParser;
private final Json json;
static class Row { private final Json json;
@SerializedName("raw_data")
JsonBall rawData;
}
static class Response { static class Row {
long start; @SerializedName("raw_data")
List<Row> rows; JsonBall rawData;
} }
@Inject static class Response {
ParseSearchDatabagFromJson(ParseJson<Response> responseParser, Json json) { long start;
this.responseParser = responseParser; List<Row> rows;
this.json = json; }
}
@Override @Inject
public SearchResult<DatabagItem> apply(HttpResponse arg0) { ParseSearchDatabagFromJson(ParseJson<Response> responseParser, Json json) {
Response returnVal = responseParser.apply(arg0); this.responseParser = responseParser;
Iterable<DatabagItem> items = this.json = json;
Iterables.transform(returnVal.rows, new Function<Row, DatabagItem>() { }
@Override
public DatabagItem apply(Row input) {
return json.fromJson(input.rawData.toString(), DatabagItem.class);
}
});
return new SearchResult<DatabagItem>(returnVal.start, items); @Override
} public SearchResult<DatabagItem> apply(HttpResponse arg0) {
Response returnVal = responseParser.apply(arg0);
Iterable<DatabagItem> items = Iterables.transform(returnVal.rows, new Function<Row, DatabagItem>() {
@Override
public DatabagItem apply(Row input) {
return json.fromJson(input.rawData.toString(), DatabagItem.class);
}
});
return new SearchResult<DatabagItem>(returnVal.start, items);
}
} }

View File

@ -37,11 +37,11 @@ import com.google.common.base.Function;
*/ */
@Singleton @Singleton
public class UriForResource implements Function<Object, URI> { public class UriForResource implements Function<Object, URI> {
@Override @Override
public URI apply(Object input) { public URI apply(Object input) {
checkArgument(checkNotNull(input, "input") instanceof Resource, checkArgument(checkNotNull(input, "input") instanceof Resource,
"This function can only be applied to Resource objects"); "This function can only be applied to Resource objects");
return ((Resource) input).getUrl(); return ((Resource) input).getUrl();
} }
} }

View File

@ -88,23 +88,23 @@ public class BaseChefService implements ChefService {
@Inject @Inject
protected BaseChefService(ChefContext chefContext, CleanupStaleNodesAndClients cleanupStaleNodesAndClients, protected BaseChefService(ChefContext chefContext, CleanupStaleNodesAndClients cleanupStaleNodesAndClients,
CreateNodeAndPopulateAutomaticAttributes createNodeAndPopulateAutomaticAttributes, CreateNodeAndPopulateAutomaticAttributes createNodeAndPopulateAutomaticAttributes,
DeleteAllNodesInList deleteAllNodesInList, ListNodes listNodes, DeleteAllNodesInList deleteAllNodesInList, ListNodes listNodes, DeleteAllClientsInList deleteAllClientsInList,
DeleteAllClientsInList deleteAllClientsInList, ListClients listClients, ListClients listClients, ListCookbookVersions listCookbookVersions,
ListCookbookVersions listCookbookVersions, UpdateAutomaticAttributesOnNode updateAutomaticAttributesOnNode, UpdateAutomaticAttributesOnNode updateAutomaticAttributesOnNode, Supplier<PrivateKey> privateKey,
Supplier<PrivateKey> privateKey, @Named(CHEF_BOOTSTRAP_DATABAG) String databag, @Named(CHEF_BOOTSTRAP_DATABAG) String databag, GroupToBootScript groupToBootScript,
GroupToBootScript groupToBootScript, RunListForGroup runListForGroup) { RunListForGroup runListForGroup) {
this.chefContext = checkNotNull(chefContext, "chefContext"); this.chefContext = checkNotNull(chefContext, "chefContext");
this.cleanupStaleNodesAndClients = checkNotNull(cleanupStaleNodesAndClients, "cleanupStaleNodesAndClients"); this.cleanupStaleNodesAndClients = checkNotNull(cleanupStaleNodesAndClients, "cleanupStaleNodesAndClients");
this.createNodeAndPopulateAutomaticAttributes = checkNotNull(createNodeAndPopulateAutomaticAttributes, this.createNodeAndPopulateAutomaticAttributes = checkNotNull(createNodeAndPopulateAutomaticAttributes,
"createNodeAndPopulateAutomaticAttributes"); "createNodeAndPopulateAutomaticAttributes");
this.deleteAllNodesInList = checkNotNull(deleteAllNodesInList, "deleteAllNodesInList"); this.deleteAllNodesInList = checkNotNull(deleteAllNodesInList, "deleteAllNodesInList");
this.listNodes = checkNotNull(listNodes, "listNodes"); this.listNodes = checkNotNull(listNodes, "listNodes");
this.deleteAllClientsInList = checkNotNull(deleteAllClientsInList, "deleteAllClientsInList"); this.deleteAllClientsInList = checkNotNull(deleteAllClientsInList, "deleteAllClientsInList");
this.listClients = checkNotNull(listClients, "listClients"); this.listClients = checkNotNull(listClients, "listClients");
this.listCookbookVersions = checkNotNull(listCookbookVersions, "listCookbookVersions"); this.listCookbookVersions = checkNotNull(listCookbookVersions, "listCookbookVersions");
this.updateAutomaticAttributesOnNode = checkNotNull(updateAutomaticAttributesOnNode, this.updateAutomaticAttributesOnNode = checkNotNull(updateAutomaticAttributesOnNode,
"updateAutomaticAttributesOnNode"); "updateAutomaticAttributesOnNode");
this.privateKey = checkNotNull(privateKey, "privateKey"); this.privateKey = checkNotNull(privateKey, "privateKey");
this.groupToBootScript = checkNotNull(groupToBootScript, "groupToBootScript"); this.groupToBootScript = checkNotNull(groupToBootScript, "groupToBootScript");
this.databag = checkNotNull(databag, "databag"); this.databag = checkNotNull(databag, "databag");
@ -176,7 +176,6 @@ public class BaseChefService implements ChefService {
return listCookbookVersions.execute(names); return listCookbookVersions.execute(names);
} }
@Override @Override
public void updateAutomaticAttributesOnNode(String nodeName) { public void updateAutomaticAttributesOnNode(String nodeName) {
updateAutomaticAttributesOnNode.execute(nodeName); updateAutomaticAttributesOnNode.execute(nodeName);
@ -199,15 +198,17 @@ public class BaseChefService implements ChefService {
} catch (IllegalStateException e) { } catch (IllegalStateException e) {
} }
DatabagItem runlist = new DatabagItem(group, chefContext.utils().json().toJson( DatabagItem runlist = new DatabagItem(group, chefContext
ImmutableMap.<String, List<String>> of("run_list", Lists.newArrayList(runList)), .utils()
RunListForGroup.RUN_LIST_TYPE)); .json()
.toJson(ImmutableMap.<String, List<String>> of("run_list", Lists.newArrayList(runList)),
RunListForGroup.RUN_LIST_TYPE));
if (chefContext.getApi().getDatabagItem(databag, group) == null) { if (chefContext.getApi().getDatabagItem(databag, group) == null) {
chefContext.getApi().createDatabagItem(databag, runlist); chefContext.getApi().createDatabagItem(databag, runlist);
} else { } else {
chefContext.getApi().updateDatabagItem(databag, runlist); chefContext.getApi().updateDatabagItem(databag, runlist);
} }
} }
@ -219,13 +220,13 @@ public class BaseChefService implements ChefService {
@Override @Override
public byte[] decrypt(InputSupplier<? extends InputStream> supplier) throws IOException { public byte[] decrypt(InputSupplier<? extends InputStream> supplier) throws IOException {
return ByteStreams.toByteArray(new RSADecryptingPayload(Payloads.newPayload(supplier.getInput()), privateKey return ByteStreams.toByteArray(new RSADecryptingPayload(Payloads.newPayload(supplier.getInput()), privateKey
.get())); .get()));
} }
@Override @Override
public byte[] encrypt(InputSupplier<? extends InputStream> supplier) throws IOException { public byte[] encrypt(InputSupplier<? extends InputStream> supplier) throws IOException {
return ByteStreams.toByteArray(new RSAEncryptingPayload(Payloads.newPayload(supplier.getInput()), privateKey return ByteStreams.toByteArray(new RSAEncryptingPayload(Payloads.newPayload(supplier.getInput()), privateKey
.get())); .get()));
} }
} }

View File

@ -18,54 +18,51 @@
*/ */
package org.jclouds.chef.options; package org.jclouds.chef.options;
/** /**
* Options for the create client method. * Options for the create client method.
* *
* @author Ignasi Barrera * @author Ignasi Barrera
*/ */
public class CreateClientOptions implements Cloneable public class CreateClientOptions implements Cloneable {
{ /** Administrator flag. This flag will be ignored in Opscode Hosted Chef. */
/** Administrator flag. This flag will be ignored in Opscode Hosted Chef. */ private boolean admin;
private boolean admin;
public CreateClientOptions() { public CreateClientOptions() {
} }
CreateClientOptions(final boolean admin) { CreateClientOptions(final boolean admin) {
super(); super();
this.admin = admin; this.admin = admin;
} }
public boolean isAdmin() { public boolean isAdmin() {
return admin; return admin;
} }
public CreateClientOptions admin() { public CreateClientOptions admin() {
this.admin = true; this.admin = true;
return this; return this;
} }
@Override @Override
protected Object clone() throws CloneNotSupportedException { protected Object clone() throws CloneNotSupportedException {
return new CreateClientOptions(admin); return new CreateClientOptions(admin);
} }
@Override @Override
public String toString() { public String toString() {
return "[admin=" + admin + "]"; return "[admin=" + admin + "]";
} }
public static class Builder public static class Builder {
{ /**
/** * @see CreateClientOptions#admin()
* @see CreateClientOptions#admin() */
*/ public static CreateClientOptions admin() {
public static CreateClientOptions admin() { CreateClientOptions options = new CreateClientOptions();
CreateClientOptions options = new CreateClientOptions(); return options.admin();
return options.admin(); }
}
} }
} }

View File

@ -29,71 +29,71 @@ import org.jclouds.http.options.BaseHttpRequestOptions;
*/ */
public class SearchOptions extends BaseHttpRequestOptions { public class SearchOptions extends BaseHttpRequestOptions {
/** /**
* A valid search string. * A valid search string.
*/ */
public SearchOptions query(String query) { public SearchOptions query(String query) {
this.queryParameters.put("q", checkNotNull(query, "query")); this.queryParameters.put("q", checkNotNull(query, "query"));
return this; return this;
} }
/** /**
* A sort string, such as 'name DESC'. * A sort string, such as 'name DESC'.
*/ */
public SearchOptions sort(String sort) { public SearchOptions sort(String sort) {
this.queryParameters.put("sort", checkNotNull(sort, "sort")); this.queryParameters.put("sort", checkNotNull(sort, "sort"));
return this; return this;
} }
/** /**
* The number of rows to return. * The number of rows to return.
*/ */
public SearchOptions rows(int rows) { public SearchOptions rows(int rows) {
this.queryParameters.put("rows", String.valueOf(rows)); this.queryParameters.put("rows", String.valueOf(rows));
return this; return this;
} }
/** /**
* The result number to start from. * The result number to start from.
*/ */
public SearchOptions start(int start) { public SearchOptions start(int start) {
this.queryParameters.put("start", String.valueOf(start)); this.queryParameters.put("start", String.valueOf(start));
return this; return this;
} }
public static class Builder { public static class Builder {
/** /**
* @see SearchOptions#query(String) * @see SearchOptions#query(String)
*/ */
public static SearchOptions query(String query) { public static SearchOptions query(String query) {
SearchOptions options = new SearchOptions(); SearchOptions options = new SearchOptions();
return options.query(query); return options.query(query);
} }
/** /**
* @see SearchOptions#sort(String) * @see SearchOptions#sort(String)
*/ */
public static SearchOptions start(String start) { public static SearchOptions start(String start) {
SearchOptions options = new SearchOptions(); SearchOptions options = new SearchOptions();
return options.sort(start); return options.sort(start);
} }
/** /**
* @see SearchOptions#rows(int) * @see SearchOptions#rows(int)
*/ */
public static SearchOptions rows(int rows) { public static SearchOptions rows(int rows) {
SearchOptions options = new SearchOptions(); SearchOptions options = new SearchOptions();
return options.rows(rows); return options.rows(rows);
} }
/** /**
* @see SearchOptions#start(int) * @see SearchOptions#start(int)
*/ */
public static SearchOptions start(int start) { public static SearchOptions start(int start) {
SearchOptions options = new SearchOptions(); SearchOptions options = new SearchOptions();
return options.start(start); return options.start(start);
} }
} }
} }

View File

@ -47,9 +47,10 @@ public class CookbookVersionPredicates {
} }
/** /**
* Note that the default recipe of a cookbook is its name. Otherwise, you prefix the recipe with * Note that the default recipe of a cookbook is its name. Otherwise, you
* the name of the cookbook. ex. {@code apache2} will be the default recipe where {@code * prefix the recipe with the name of the cookbook. ex. {@code apache2} will
* apache2::mod_proxy} is a specific one in the cookbook. * be the default recipe where {@code apache2::mod_proxy} is a specific one
* in the cookbook.
* *
* @param recipes * @param recipes
* names of the recipes. * names of the recipes.
@ -70,21 +71,21 @@ public class CookbookVersionPredicates {
@Override @Override
public boolean apply(final CookbookVersion cookbookVersion) { public boolean apply(final CookbookVersion cookbookVersion) {
return search.containsKey(cookbookVersion.getCookbookName()) return search.containsKey(cookbookVersion.getCookbookName())
&& any(search.get(cookbookVersion.getCookbookName()), new Predicate<String>() { && any(search.get(cookbookVersion.getCookbookName()), new Predicate<String>() {
@Override @Override
public boolean apply(final String recipeName) { public boolean apply(final String recipeName) {
return any(cookbookVersion.getRecipes(), new Predicate<Resource>() { return any(cookbookVersion.getRecipes(), new Predicate<Resource>() {
@Override @Override
public boolean apply(Resource resource) { public boolean apply(Resource resource) {
return resource.getName().equals(recipeName); return resource.getName().equals(recipeName);
} }
}); });
} }
}); });
} }
@Override @Override

View File

@ -63,7 +63,7 @@ public class CleanupStaleNodesAndClientsImpl implements CleanupStaleNodesAndClie
@Inject @Inject
public CleanupStaleNodesAndClientsImpl(DeleteAllNodesInList nodeDeleter, DeleteAllClientsInList clientDeleter, public CleanupStaleNodesAndClientsImpl(DeleteAllNodesInList nodeDeleter, DeleteAllClientsInList clientDeleter,
ListNodes nodeLister) { ListNodes nodeLister) {
this.nodeLister = checkNotNull(nodeLister, "nodeLister"); this.nodeLister = checkNotNull(nodeLister, "nodeLister");
this.nodeDeleter = checkNotNull(nodeDeleter, "nodeDeleter"); this.nodeDeleter = checkNotNull(nodeDeleter, "nodeDeleter");
this.clientDeleter = checkNotNull(clientDeleter, "clientDeleter"); this.clientDeleter = checkNotNull(clientDeleter, "clientDeleter");

View File

@ -60,8 +60,8 @@ public class DeleteAllClientsInListImpl implements DeleteAllClientsInList {
protected Long maxTime; protected Long maxTime;
@Inject @Inject
DeleteAllClientsInListImpl(@Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor, ChefApi getAllApi, DeleteAllClientsInListImpl(@Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor,
ChefAsyncApi ablobstore) { ChefApi getAllApi, ChefAsyncApi ablobstore) {
this.userExecutor = userExecutor; this.userExecutor = userExecutor;
this.chefAsyncApi = ablobstore; this.chefAsyncApi = ablobstore;
this.chefApi = getAllApi; this.chefApi = getAllApi;
@ -75,7 +75,8 @@ public class DeleteAllClientsInListImpl implements DeleteAllClientsInList {
responses.put(name, chefAsyncApi.deleteClient(name)); responses.put(name, chefAsyncApi.deleteClient(name));
} }
try { try {
exceptions = awaitCompletion(responses, userExecutor, maxTime, logger, String.format("deleting apis: %s", names)); exceptions = awaitCompletion(responses, userExecutor, maxTime, logger,
String.format("deleting apis: %s", names));
} catch (TimeoutException e) { } catch (TimeoutException e) {
propagate(e); propagate(e);
} }

View File

@ -60,8 +60,8 @@ public class DeleteAllNodesInListImpl implements DeleteAllNodesInList {
protected Long maxTime; protected Long maxTime;
@Inject @Inject
DeleteAllNodesInListImpl(@Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor, ChefApi getAllNode, DeleteAllNodesInListImpl(@Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor,
ChefAsyncApi ablobstore) { ChefApi getAllNode, ChefAsyncApi ablobstore) {
this.userExecutor = userExecutor; this.userExecutor = userExecutor;
this.chefAsyncApi = ablobstore; this.chefAsyncApi = ablobstore;
this.chefApi = getAllNode; this.chefApi = getAllNode;
@ -75,7 +75,8 @@ public class DeleteAllNodesInListImpl implements DeleteAllNodesInList {
responses.put(name, chefAsyncApi.deleteNode(name)); responses.put(name, chefAsyncApi.deleteNode(name));
} }
try { try {
exceptions = awaitCompletion(responses, userExecutor, maxTime, logger, String.format("deleting nodes: %s", names)); exceptions = awaitCompletion(responses, userExecutor, maxTime, logger,
String.format("deleting nodes: %s", names));
} catch (TimeoutException e) { } catch (TimeoutException e) {
propagate(e); propagate(e);
} }

View File

@ -60,7 +60,7 @@ public class ListClientsImpl implements ListClients {
@Inject @Inject
ListClientsImpl(@Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor, ChefApi getAllApi, ListClientsImpl(@Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor, ChefApi getAllApi,
ChefAsyncApi ablobstore) { ChefAsyncApi ablobstore) {
this.userExecutor = userExecutor; this.userExecutor = userExecutor;
this.chefAsyncApi = ablobstore; this.chefAsyncApi = ablobstore;
this.chefApi = getAllApi; this.chefApi = getAllApi;

View File

@ -62,7 +62,7 @@ public class ListCookbookVersionsImpl implements ListCookbookVersions {
@Inject @Inject
ListCookbookVersionsImpl(@Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor, ListCookbookVersionsImpl(@Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor,
ChefApi getAllCookbookVersion, ChefAsyncApi ablobstore) { ChefApi getAllCookbookVersion, ChefAsyncApi ablobstore) {
this.userExecutor = userExecutor; this.userExecutor = userExecutor;
this.chefAsyncApi = ablobstore; this.chefAsyncApi = ablobstore;
this.chefApi = getAllCookbookVersion; this.chefApi = getAllCookbookVersion;
@ -86,11 +86,11 @@ public class ListCookbookVersionsImpl implements ListCookbookVersions {
public Iterable<? extends CookbookVersion> apply(final String cookbook) { public Iterable<? extends CookbookVersion> apply(final String cookbook) {
// TODO getting each version could also go parallel // TODO getting each version could also go parallel
return transformParallel(chefApi.getVersionsOfCookbook(cookbook), return transformParallel(chefApi.getVersionsOfCookbook(cookbook),
new Function<String, ListenableFuture<? extends CookbookVersion>>() { new Function<String, ListenableFuture<? extends CookbookVersion>>() {
public ListenableFuture<CookbookVersion> apply(String version) { public ListenableFuture<CookbookVersion> apply(String version) {
return chefAsyncApi.getCookbook(cookbook, version); return chefAsyncApi.getCookbook(cookbook, version);
} }
}, userExecutor, maxTime, logger, "getting versions of cookbook " + cookbook); }, userExecutor, maxTime, logger, "getting versions of cookbook " + cookbook);
} }
})); }));

View File

@ -60,7 +60,7 @@ public class ListNodesImpl implements ListNodes {
@Inject @Inject
ListNodesImpl(@Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor, ChefApi getAllNode, ListNodesImpl(@Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor, ChefApi getAllNode,
ChefAsyncApi ablobstore) { ChefAsyncApi ablobstore) {
this.userExecutor = userExecutor; this.userExecutor = userExecutor;
this.chefAsyncApi = ablobstore; this.chefAsyncApi = ablobstore;
this.chefApi = getAllNode; this.chefApi = getAllNode;

View File

@ -54,8 +54,7 @@ public class UpdateAutomaticAttributesOnNodeImpl implements UpdateAutomaticAttri
private final Supplier<Map<String, JsonBall>> automaticSupplier; private final Supplier<Map<String, JsonBall>> automaticSupplier;
@Inject @Inject
public UpdateAutomaticAttributesOnNodeImpl(ChefApi chef, public UpdateAutomaticAttributesOnNodeImpl(ChefApi chef, @Automatic Supplier<Map<String, JsonBall>> automaticSupplier) {
@Automatic Supplier<Map<String, JsonBall>> automaticSupplier) {
this.chef = checkNotNull(chef, "chef"); this.chef = checkNotNull(chef, "chef");
this.automaticSupplier = checkNotNull(automaticSupplier, "automaticSupplier"); this.automaticSupplier = checkNotNull(automaticSupplier, "automaticSupplier");
} }

View File

@ -33,7 +33,7 @@ import com.google.inject.Module;
* @author Adrian Cole * @author Adrian Cole
*/ */
public class TransientChefApiMetadata extends ChefApiMetadata { public class TransientChefApiMetadata extends ChefApiMetadata {
@Override @Override
public Builder toBuilder() { public Builder toBuilder() {
return new Builder().fromApiMetadata(this); return new Builder().fromApiMetadata(this);
@ -51,14 +51,15 @@ public class TransientChefApiMetadata extends ChefApiMetadata {
protected Builder() { protected Builder() {
super(TransientChefApi.class, TransientChefAsyncApi.class); super(TransientChefApi.class, TransientChefAsyncApi.class);
id("transientchef") id("transientchef")
.name("In-memory Chef API") .name("In-memory Chef API")
.identityName("unused") .identityName("unused")
.defaultIdentity("api") .defaultIdentity("api")
.defaultCredential( .defaultCredential(
"-----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") "-----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")
.defaultEndpoint("transientchef").defaultModules( .defaultEndpoint("transientchef")
ImmutableSet.<Class<? extends Module>> of(TransientChefApiModule.class, .defaultModules(
ChefParserModule.class, JMXOhaiModule.class)); ImmutableSet.<Class<? extends Module>> of(TransientChefApiModule.class, ChefParserModule.class,
JMXOhaiModule.class));
} }
@Override @Override

View File

@ -100,8 +100,8 @@ public class TransientChefAsyncApi implements ChefAsyncApi {
private final StorageMetadataToName storageMetadataToName; private final StorageMetadataToName storageMetadataToName;
@Inject @Inject
TransientChefAsyncApi(@Named("databags") LocalAsyncBlobStore databags, TransientChefAsyncApi(@Named("databags") LocalAsyncBlobStore databags, StorageMetadataToName storageMetadataToName,
StorageMetadataToName storageMetadataToName, BlobToDatabagItem blobToDatabagItem, BlobToDatabagItem blobToDatabagItem,
@Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor) { @Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor) {
this.databags = checkNotNull(databags, "databags"); this.databags = checkNotNull(databags, "databags");
this.storageMetadataToName = checkNotNull(storageMetadataToName, "storageMetadataToName"); this.storageMetadataToName = checkNotNull(storageMetadataToName, "storageMetadataToName");
@ -123,7 +123,7 @@ public class TransientChefAsyncApi implements ChefAsyncApi {
public ListenableFuture<Client> createClient(String clientname) { public ListenableFuture<Client> createClient(String clientname) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
@Override @Override
public ListenableFuture<Client> createClient(String clientname, CreateClientOptions options) { public ListenableFuture<Client> createClient(String clientname, CreateClientOptions options) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
@ -131,7 +131,7 @@ public class TransientChefAsyncApi implements ChefAsyncApi {
@Override @Override
public ListenableFuture<Void> createDatabag(String databagName) { public ListenableFuture<Void> createDatabag(String databagName) {
return transform(databags.createContainerInLocation(null, databagName), new Function<Boolean, Void>(){ return transform(databags.createContainerInLocation(null, databagName), new Function<Boolean, Void>() {
public Void apply(Boolean input) { public Void apply(Boolean input) {
return null; return null;
} }
@ -182,7 +182,8 @@ public class TransientChefAsyncApi implements ChefAsyncApi {
@Override @Override
public ListenableFuture<DatabagItem> deleteDatabagItem(String databagName, String databagItemId) { public ListenableFuture<DatabagItem> deleteDatabagItem(String databagName, String databagItemId) {
return immediateFuture(blobToDatabagItem.apply(databags.getContext().createBlobMap(databagName).remove(databagItemId))); return immediateFuture(blobToDatabagItem.apply(databags.getContext().createBlobMap(databagName)
.remove(databagItemId)));
} }
@Override @Override
@ -284,23 +285,22 @@ public class TransientChefAsyncApi implements ChefAsyncApi {
public ListenableFuture<? extends SearchResult<? extends Client>> searchClients() { public ListenableFuture<? extends SearchResult<? extends Client>> searchClients() {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
@Override @Override
public ListenableFuture<? extends SearchResult<? extends Client>> searchClients( public ListenableFuture<? extends SearchResult<? extends Client>> searchClients(SearchOptions options) {
SearchOptions options) { throw new UnsupportedOperationException();
throw new UnsupportedOperationException(); }
}
@Override @Override
public ListenableFuture<? extends SearchResult<? extends DatabagItem>> searchDatabag(String databagName) { public ListenableFuture<? extends SearchResult<? extends DatabagItem>> searchDatabag(String databagName) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
@Override @Override
public ListenableFuture<? extends SearchResult<? extends DatabagItem>> searchDatabag( public ListenableFuture<? extends SearchResult<? extends DatabagItem>> searchDatabag(String databagName,
String databagName, SearchOptions options) { SearchOptions options) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
@Override @Override
public ListenableFuture<? extends SearchResult<? extends Node>> searchNodes() { public ListenableFuture<? extends SearchResult<? extends Node>> searchNodes() {
@ -308,21 +308,19 @@ public class TransientChefAsyncApi implements ChefAsyncApi {
} }
@Override @Override
public ListenableFuture<? extends SearchResult<? extends Node>> searchNodes( public ListenableFuture<? extends SearchResult<? extends Node>> searchNodes(SearchOptions options) {
SearchOptions options) { throw new UnsupportedOperationException();
throw new UnsupportedOperationException(); }
}
@Override @Override
public ListenableFuture<? extends SearchResult<? extends Role>> searchRoles() { public ListenableFuture<? extends SearchResult<? extends Role>> searchRoles() {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
@Override @Override
public ListenableFuture<? extends SearchResult<? extends Role>> searchRoles( public ListenableFuture<? extends SearchResult<? extends Role>> searchRoles(SearchOptions options) {
SearchOptions options) { throw new UnsupportedOperationException();
throw new UnsupportedOperationException(); }
}
@Override @Override
public ListenableFuture<CookbookVersion> updateCookbook(String cookbookName, String version, CookbookVersion cookbook) { public ListenableFuture<CookbookVersion> updateCookbook(String cookbookName, String version, CookbookVersion cookbook) {
@ -346,12 +344,12 @@ public class TransientChefAsyncApi implements ChefAsyncApi {
@Override @Override
public ListenableFuture<Void> uploadContent(URI location, Payload content) { public ListenableFuture<Void> uploadContent(URI location, Payload content) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
@Override @Override
public ListenableFuture<InputStream> getResourceContents(Resource resource) { public ListenableFuture<InputStream> getResourceContents(Resource resource) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
} }

View File

@ -71,12 +71,13 @@ public class TransientChefApiModule extends AbstractModule {
bindBlockingApi(binder(), TransientChefApi.class, ChefAsyncApi.class); bindBlockingApi(binder(), TransientChefApi.class, ChefAsyncApi.class);
bind(ChefApi.class).to(TransientChefApi.class); bind(ChefApi.class).to(TransientChefApi.class);
bind(LocalAsyncBlobStore.class).annotatedWith(Names.named("databags")).toInstance( bind(LocalAsyncBlobStore.class).annotatedWith(Names.named("databags"))
ContextBuilder .toInstance(
.newBuilder(new TransientApiMetadata()) ContextBuilder
.modules(ImmutableSet.<Module> of( .newBuilder(new TransientApiMetadata())
new ExecutorServiceModule(sameThreadExecutor(), sameThreadExecutor()))) .modules(
.buildInjector().getInstance(LocalAsyncBlobStore.class)); ImmutableSet.<Module> of(new ExecutorServiceModule(sameThreadExecutor(),
sameThreadExecutor()))).buildInjector().getInstance(LocalAsyncBlobStore.class));
bind(Statement.class).annotatedWith(Names.named("installChefGems")).to(InstallChefGems.class); bind(Statement.class).annotatedWith(Names.named("installChefGems")).to(InstallChefGems.class);
} }

View File

@ -33,7 +33,7 @@ import javax.inject.Qualifier;
* @author Adrian Cole * @author Adrian Cole
*/ */
@Retention(RUNTIME) @Retention(RUNTIME)
@Target( { TYPE, METHOD, PARAMETER }) @Target({ TYPE, METHOD, PARAMETER })
@Qualifier @Qualifier
public @interface Automatic { public @interface Automatic {
} }

View File

@ -38,11 +38,11 @@ import com.google.common.collect.Multimap;
*/ */
@Singleton @Singleton
public class AutomaticSupplier implements Supplier<Map<String, JsonBall>> { public class AutomaticSupplier implements Supplier<Map<String, JsonBall>> {
private final Multimap<String,Supplier<JsonBall>> autoAttrs; private final Multimap<String, Supplier<JsonBall>> autoAttrs;
private final NestSlashKeys nester; private final NestSlashKeys nester;
@Inject @Inject
AutomaticSupplier(@Automatic Multimap<String,Supplier<JsonBall>> autoAttrs, NestSlashKeys nester) { AutomaticSupplier(@Automatic Multimap<String, Supplier<JsonBall>> autoAttrs, NestSlashKeys nester) {
this.autoAttrs = checkNotNull(autoAttrs, "autoAttrs"); this.autoAttrs = checkNotNull(autoAttrs, "autoAttrs");
this.nester = checkNotNull(nester, "nester"); this.nester = checkNotNull(nester, "nester");
} }

View File

@ -24,14 +24,16 @@ import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.RUNTIME; import static java.lang.annotation.RetentionPolicy.RUNTIME;
/** /**
* An internal binding annotation applied to each element in a multibinding. * An internal binding annotation applied to each element in a multibinding. All
* All elements are assigned a globally-unique id to allow different modules * elements are assigned a globally-unique id to allow different modules to
* to contribute multibindings independently. * contribute multibindings independently.
* *
* @author jessewilson@google.com (Jesse Wilson) * @author jessewilson@google.com (Jesse Wilson)
*/ */
@Retention(RUNTIME) @BindingAnnotation @Retention(RUNTIME)
@BindingAnnotation
@interface Element { @interface Element {
String setName(); String setName();
int uniqueId();
int uniqueId();
} }

View File

@ -75,8 +75,8 @@ import com.google.inject.util.Types;
* </pre> * </pre>
* *
* <p> * <p>
* In addition to binding {@code Map<K, V>}, a mapbinder will also bind {@code * In addition to binding {@code Map<K, V>}, a mapbinder will also bind
* Map<K, Provider<V>>} for lazy value provision: * {@code Map<K, Provider<V>>} for lazy value provision:
* *
* <pre> * <pre>
* <code> * <code>
@ -131,20 +131,21 @@ public abstract class MapBinder<K, V> {
} }
/** /**
* Returns a new mapbinder that collects entries of {@code keyType}/{@code * Returns a new mapbinder that collects entries of {@code keyType}/
* valueType} in a {@link Map} that is itself bound with no binding * {@code valueType} in a {@link Map} that is itself bound with no binding
* annotation. * annotation.
*/ */
public static <K, V> MapBinder<K, V> newMapBinder(Binder binder, TypeLiteral<K> keyType, TypeLiteral<V> valueType) { public static <K, V> MapBinder<K, V> newMapBinder(Binder binder, TypeLiteral<K> keyType, TypeLiteral<V> valueType) {
binder = binder.skipSources(MapBinder.class, RealMapBinder.class); binder = binder.skipSources(MapBinder.class, RealMapBinder.class);
return newMapBinder(binder, valueType, Key.get(mapOf(keyType, valueType)), Key.get(mapOfProviderOf(keyType, return newMapBinder(binder, valueType, Key.get(mapOf(keyType, valueType)),
valueType)), Key.get(mapOf(keyType, setOf(valueType))), Key.get(mapOfSetOfProviderOf(keyType, valueType)), Key.get(mapOfProviderOf(keyType, valueType)), Key.get(mapOf(keyType, setOf(valueType))),
Key.get(mapOfSetOfProviderOf(keyType, valueType)),
Multibinder.newSetBinder(binder, entryOfProviderOf(keyType, valueType))); Multibinder.newSetBinder(binder, entryOfProviderOf(keyType, valueType)));
} }
/** /**
* Returns a new mapbinder that collects entries of {@code keyType}/{@code * Returns a new mapbinder that collects entries of {@code keyType}/
* valueType} in a {@link Map} that is itself bound with no binding * {@code valueType} in a {@link Map} that is itself bound with no binding
* annotation. * annotation.
*/ */
public static <K, V> MapBinder<K, V> newMapBinder(Binder binder, Class<K> keyType, Class<V> valueType) { public static <K, V> MapBinder<K, V> newMapBinder(Binder binder, Class<K> keyType, Class<V> valueType) {
@ -152,21 +153,24 @@ public abstract class MapBinder<K, V> {
} }
/** /**
* Returns a new mapbinder that collects entries of {@code keyType}/{@code * Returns a new mapbinder that collects entries of {@code keyType}/
* valueType} in a {@link Map} that is itself bound with {@code annotation}. * {@code valueType} in a {@link Map} that is itself bound with
* {@code annotation}.
*/ */
public static <K, V> MapBinder<K, V> newMapBinder(Binder binder, TypeLiteral<K> keyType, TypeLiteral<V> valueType, public static <K, V> MapBinder<K, V> newMapBinder(Binder binder, TypeLiteral<K> keyType, TypeLiteral<V> valueType,
Annotation annotation) { Annotation annotation) {
binder = binder.skipSources(MapBinder.class, RealMapBinder.class); binder = binder.skipSources(MapBinder.class, RealMapBinder.class);
return newMapBinder(binder, valueType, Key.get(mapOf(keyType, valueType), annotation), Key.get(mapOfProviderOf( return newMapBinder(binder, valueType, Key.get(mapOf(keyType, valueType), annotation),
keyType, valueType), annotation), Key.get(mapOf(keyType, setOf(valueType)), annotation), Key.get( Key.get(mapOfProviderOf(keyType, valueType), annotation),
mapOfSetOfProviderOf(keyType, valueType), annotation), Multibinder.newSetBinder(binder, entryOfProviderOf( Key.get(mapOf(keyType, setOf(valueType)), annotation),
keyType, 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 * Returns a new mapbinder that collects entries of {@code keyType}/
* valueType} in a {@link Map} that is itself bound with {@code annotation}. * {@code valueType} in a {@link Map} that is itself bound with
* {@code annotation}.
*/ */
public static <K, V> MapBinder<K, V> newMapBinder(Binder binder, Class<K> keyType, Class<V> valueType, public static <K, V> MapBinder<K, V> newMapBinder(Binder binder, Class<K> keyType, Class<V> valueType,
Annotation annotation) { Annotation annotation) {
@ -174,23 +178,24 @@ public abstract class MapBinder<K, V> {
} }
/** /**
* Returns a new mapbinder that collects entries of {@code keyType}/{@code * Returns a new mapbinder that collects entries of {@code keyType}/
* valueType} in a {@link Map} that is itself bound with {@code * {@code valueType} in a {@link Map} that is itself bound with
* annotationType}. * {@code annotationType}.
*/ */
public static <K, V> MapBinder<K, V> newMapBinder(Binder binder, TypeLiteral<K> keyType, TypeLiteral<V> valueType, public static <K, V> MapBinder<K, V> newMapBinder(Binder binder, TypeLiteral<K> keyType, TypeLiteral<V> valueType,
Class<? extends Annotation> annotationType) { Class<? extends Annotation> annotationType) {
binder = binder.skipSources(MapBinder.class, RealMapBinder.class); binder = binder.skipSources(MapBinder.class, RealMapBinder.class);
return newMapBinder(binder, valueType, Key.get(mapOf(keyType, valueType), annotationType), Key.get( return newMapBinder(binder, valueType, Key.get(mapOf(keyType, valueType), annotationType),
mapOfProviderOf(keyType, valueType), annotationType), Key.get(mapOf(keyType, setOf(valueType)), Key.get(mapOfProviderOf(keyType, valueType), annotationType),
annotationType), Key.get(mapOfSetOfProviderOf(keyType, valueType), annotationType), Multibinder Key.get(mapOf(keyType, setOf(valueType)), annotationType),
.newSetBinder(binder, entryOfProviderOf(keyType, 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 * Returns a new mapbinder that collects entries of {@code keyType}/
* valueType} in a {@link Map} that is itself bound with {@code * {@code valueType} in a {@link Map} that is itself bound with
* annotationType}. * {@code annotationType}.
*/ */
public static <K, V> MapBinder<K, V> newMapBinder(Binder binder, Class<K> keyType, Class<V> valueType, public static <K, V> MapBinder<K, V> newMapBinder(Binder binder, Class<K> keyType, Class<V> valueType,
Class<? extends Annotation> annotationType) { Class<? extends Annotation> annotationType) {
@ -207,16 +212,16 @@ public abstract class MapBinder<K, V> {
// a provider map <K, V> is safely a Map<K, Provider<V>> // a provider map <K, V> is safely a Map<K, Provider<V>>
private static <K, V> TypeLiteral<Map<K, Provider<V>>> mapOfProviderOf(TypeLiteral<K> keyType, private static <K, V> TypeLiteral<Map<K, Provider<V>>> mapOfProviderOf(TypeLiteral<K> keyType,
TypeLiteral<V> valueType) { TypeLiteral<V> valueType) {
return (TypeLiteral<Map<K, Provider<V>>>) TypeLiteral.get(Types.mapOf(keyType.getType(), Types return (TypeLiteral<Map<K, Provider<V>>>) TypeLiteral.get(Types.mapOf(keyType.getType(),
.providerOf(valueType.getType()))); Types.providerOf(valueType.getType())));
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
// a provider map <K, Set<V>> is safely a Map<K, Set<Provider<V>>> // a provider map <K, Set<V>> is safely a Map<K, Set<Provider<V>>>
private static <K, V> TypeLiteral<Map<K, Set<Provider<V>>>> mapOfSetOfProviderOf(TypeLiteral<K> keyType, private static <K, V> TypeLiteral<Map<K, Set<Provider<V>>>> mapOfSetOfProviderOf(TypeLiteral<K> keyType,
TypeLiteral<V> valueType) { TypeLiteral<V> valueType) {
return (TypeLiteral<Map<K, Set<Provider<V>>>>) TypeLiteral.get(Types.mapOf(keyType.getType(), Types.setOf(Types return (TypeLiteral<Map<K, Set<Provider<V>>>>) TypeLiteral.get(Types.mapOf(keyType.getType(),
.providerOf(valueType.getType())))); Types.setOf(Types.providerOf(valueType.getType()))));
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@ -260,8 +265,8 @@ public abstract class MapBinder<K, V> {
* time the map is injected. * time the map is injected.
* *
* <p> * <p>
* It is an error to call this method without also calling one of the {@code * It is an error to call this method without also calling one of the
* to} methods on the returned binding builder. * {@code to} methods on the returned binding builder.
* *
* <p> * <p>
* Scoping elements independently is supported. Use the {@code in} method to * Scoping elements independently is supported. Use the {@code in} method to

View File

@ -139,8 +139,8 @@ public abstract class Multibinder<T> {
*/ */
public static <T> Multibinder<T> newSetBinder(Binder binder, TypeLiteral<T> type, Annotation annotation) { public static <T> Multibinder<T> newSetBinder(Binder binder, TypeLiteral<T> type, Annotation annotation) {
binder = binder.skipSources(RealMultibinder.class, Multibinder.class); binder = binder.skipSources(RealMultibinder.class, Multibinder.class);
RealMultibinder<T> result = new RealMultibinder<T>(binder, type, annotation.toString(), Key.get(Multibinder RealMultibinder<T> result = new RealMultibinder<T>(binder, type, annotation.toString(), Key.get(
.<T> setOf(type), annotation)); Multibinder.<T> setOf(type), annotation));
binder.install(result); binder.install(result);
return result; return result;
} }
@ -198,8 +198,8 @@ public abstract class Multibinder<T> {
* time the set is injected. * time the set is injected.
* *
* <p> * <p>
* It is an error to call this method without also calling one of the {@code * It is an error to call this method without also calling one of the
* to} methods on the returned binding builder. * {@code to} methods on the returned binding builder.
* *
* <p> * <p>
* Scoping elements independently is supported. Use the {@code in} method to * Scoping elements independently is supported. Use the {@code in} method to

View File

@ -17,52 +17,50 @@
* under the License. * under the License.
*/ */
package org.jclouds.ohai.config.multibindings; package org.jclouds.ohai.config.multibindings;
import java.lang.annotation.Annotation; import java.lang.annotation.Annotation;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
/** /**
* @author jessewilson@google.com (Jesse Wilson) * @author jessewilson@google.com (Jesse Wilson)
*/ */
class RealElement implements Element { class RealElement implements Element {
private static final AtomicInteger nextUniqueId = new AtomicInteger(1); private static final AtomicInteger nextUniqueId = new AtomicInteger(1);
private final int uniqueId; private final int uniqueId;
private final String setName; private final String setName;
RealElement(String setName) { RealElement(String setName) {
uniqueId = nextUniqueId.getAndIncrement(); uniqueId = nextUniqueId.getAndIncrement();
this.setName = setName; this.setName = setName;
} }
public String setName() { public String setName() {
return setName; return setName;
} }
public int uniqueId() { public int uniqueId() {
return uniqueId; return uniqueId;
} }
public Class<? extends Annotation> annotationType() { public Class<? extends Annotation> annotationType() {
return Element.class; return Element.class;
} }
@Override public String toString() { @Override
return "@" + Element.class.getName() + "(setName=" + setName public String toString() {
+ ",uniqueId=" + uniqueId + ")"; return "@" + Element.class.getName() + "(setName=" + setName + ",uniqueId=" + uniqueId + ")";
} }
@Override public boolean equals(Object o) { @Override
return o instanceof Element public boolean equals(Object o) {
&& ((Element) o).setName().equals(setName()) return o instanceof Element && ((Element) o).setName().equals(setName())
&& ((Element) o).uniqueId() == uniqueId(); && ((Element) o).uniqueId() == uniqueId();
} }
@Override public int hashCode() { @Override
return 127 * ("setName".hashCode() ^ setName.hashCode()) public int hashCode() {
+ 127 * ("uniqueId".hashCode() ^ uniqueId); return 127 * ("setName".hashCode() ^ setName.hashCode()) + 127 * ("uniqueId".hashCode() ^ uniqueId);
} }
} }

View File

@ -35,22 +35,20 @@ import com.google.common.reflect.TypeToken;
@Test(groups = { "live" }) @Test(groups = { "live" })
public class ChefApiLiveTest extends BaseChefApiLiveTest<ChefContext> { public class ChefApiLiveTest extends BaseChefApiLiveTest<ChefContext> {
@Test @Test
public void testListCookbookVersionsWithChefService() throws Exception { public void testListCookbookVersionsWithChefService() throws Exception {
Iterable<? extends CookbookVersion> cookbooks = context.getChefService().listCookbookVersions(); Iterable<? extends CookbookVersion> cookbooks = context.getChefService().listCookbookVersions();
assertNotNull(cookbooks); assertNotNull(cookbooks);
} }
@Override @Override
protected ChefApi getChefApi(ChefContext context) protected ChefApi getChefApi(ChefContext context) {
{ return context.getApi();
return context.getApi(); }
}
@Override
protected TypeToken<ChefContext> contextType() {
return typeToken(ChefContext.class);
}
@Override
protected TypeToken<ChefContext> contextType()
{
return typeToken(ChefContext.class);
}
} }

View File

@ -60,6 +60,7 @@ import org.jclouds.http.functions.ReturnInputStream;
import org.jclouds.http.functions.ReturnTrueIf2xx; import org.jclouds.http.functions.ReturnTrueIf2xx;
import org.jclouds.io.Payload; import org.jclouds.io.Payload;
import org.jclouds.io.payloads.StringPayload; import org.jclouds.io.payloads.StringPayload;
import org.jclouds.reflect.Invocation;
import org.jclouds.rest.ConfiguresRestClient; import org.jclouds.rest.ConfiguresRestClient;
import org.jclouds.rest.internal.BaseAsyncApiTest; import org.jclouds.rest.internal.BaseAsyncApiTest;
import org.jclouds.rest.internal.GeneratedHttpRequest; import org.jclouds.rest.internal.GeneratedHttpRequest;
@ -70,6 +71,7 @@ import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.reflect.Invokable; import com.google.common.reflect.Invokable;
import com.google.inject.Module; import com.google.inject.Module;
/** /**
* Tests annotation parsing of {@code ChefAsyncApi} * Tests annotation parsing of {@code ChefAsyncApi}
* *
@ -81,11 +83,12 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testCommitSandbox() throws SecurityException, NoSuchMethodException, IOException { public void testCommitSandbox() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "commitSandbox", String.class, boolean.class); Invokable<?, ?> method = method(ChefAsyncApi.class, "commitSandbox", String.class, boolean.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,
ImmutableList.<Object> of("0189e76ccc476701d6b374e5a1a27347", true)); ImmutableList.<Object> of("0189e76ccc476701d6b374e5a1a27347", true)));
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"PUT http://localhost:4000/sandboxes/0189e76ccc476701d6b374e5a1a27347 HTTP/1.1"); "PUT http://localhost:4000/sandboxes/0189e76ccc476701d6b374e5a1a27347 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
+ "-test\n");
assertPayloadEquals(httpRequest, "{\"is_completed\":true}", "application/json", false); assertPayloadEquals(httpRequest, "{\"is_completed\":true}", "application/json", false);
assertResponseParserClassEquals(method, httpRequest, ParseJson.class); assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
@ -98,17 +101,16 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testGetUploadSandboxForChecksums() throws SecurityException, NoSuchMethodException, IOException { public void testGetUploadSandboxForChecksums() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "getUploadSandboxForChecksums", Set.class); Invokable<?, ?> method = method(ChefAsyncApi.class, "getUploadSandboxForChecksums", Set.class);
GeneratedHttpRequest httpRequest = processor.createRequest( GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method, ImmutableList
method, ImmutableList.<Object> of( .<Object> of(ImmutableSet.of(asList(base16().lowerCase().decode("0189e76ccc476701d6b374e5a1a27347")),
ImmutableSet.of(asList(base16().lowerCase().decode("0189e76ccc476701d6b374e5a1a27347")), asList(base16().lowerCase().decode("0c5ecd7788cf4f6c7de2a57193897a6c")), asList(base16().lowerCase()
asList(base16().lowerCase().decode("0c5ecd7788cf4f6c7de2a57193897a6c")), .decode("1dda05ed139664f1f89b9dec482b77c0"))))));
asList(base16().lowerCase().decode("1dda05ed139664f1f89b9dec482b77c0")))));
assertRequestLineEquals(httpRequest, "POST http://localhost:4000/sandboxes HTTP/1.1"); assertRequestLineEquals(httpRequest, "POST http://localhost:4000/sandboxes HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
assertPayloadEquals( + "-test\n");
httpRequest, assertPayloadEquals(httpRequest,
"{\"checksums\":{\"0189e76ccc476701d6b374e5a1a27347\":null,\"0c5ecd7788cf4f6c7de2a57193897a6c\":null,\"1dda05ed139664f1f89b9dec482b77c0\":null}}", "{\"checksums\":{\"0189e76ccc476701d6b374e5a1a27347\":null,\"0c5ecd7788cf4f6c7de2a57193897a6c\":null,"
"application/json", false); + "\"1dda05ed139664f1f89b9dec482b77c0\":null}}", "application/json", false);
assertResponseParserClassEquals(method, httpRequest, ParseJson.class); assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
@ -116,28 +118,31 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
checkFilters(httpRequest); checkFilters(httpRequest);
} }
public void testUploadContent() throws SecurityException, NoSuchMethodException, IOException { public void testUploadContent() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "uploadContent", URI.class, Payload.class); Invokable<?, ?> method = method(ChefAsyncApi.class, "uploadContent", URI.class, Payload.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(URI.create("http://foo/bar"), GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,
new StringPayload("{\"foo\": \"bar\"}"))); ImmutableList.<Object> of(URI.create("http://foo/bar"), new StringPayload("{\"foo\": \"bar\"}"))));
assertRequestLineEquals(httpRequest, "PUT http://foo/bar HTTP/1.1"); assertRequestLineEquals(httpRequest, "PUT http://foo/bar HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
assertPayloadEquals(httpRequest, "{\"foo\": \"bar\"}", "application/x-binary", false); + "-test\n");
assertPayloadEquals(httpRequest, "{\"foo\": \"bar\"}", "application/x-binary", false);
assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class); assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, null); assertFallbackClassEquals(method, null);
checkFilters(httpRequest); checkFilters(httpRequest);
} }
public void testGetCookbook() throws SecurityException, NoSuchMethodException, IOException { public void testGetCookbook() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "getCookbook", String.class, String.class); Invokable<?, ?> method = method(ChefAsyncApi.class, "getCookbook", String.class, String.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of("cookbook", "1.0.0")); GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,
ImmutableList.<Object> of("cookbook", "1.0.0")));
assertRequestLineEquals(httpRequest, "GET http://localhost:4000/cookbooks/cookbook/1.0.0 HTTP/1.1"); assertRequestLineEquals(httpRequest, "GET http://localhost:4000/cookbooks/cookbook/1.0.0 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
+ "-test\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseJson.class); assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
@ -150,9 +155,11 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testDeleteCookbook() throws SecurityException, NoSuchMethodException, IOException { public void testDeleteCookbook() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "deleteCookbook", String.class, String.class); Invokable<?, ?> method = method(ChefAsyncApi.class, "deleteCookbook", String.class, String.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of("cookbook", "1.0.0")); GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,
ImmutableList.<Object> of("cookbook", "1.0.0")));
assertRequestLineEquals(httpRequest, "DELETE http://localhost:4000/cookbooks/cookbook/1.0.0 HTTP/1.1"); assertRequestLineEquals(httpRequest, "DELETE http://localhost:4000/cookbooks/cookbook/1.0.0 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
+ "-test\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseJson.class); assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
@ -166,15 +173,21 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testUpdateCookbook() throws SecurityException, NoSuchMethodException, IOException { public void testUpdateCookbook() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "updateCookbook", String.class, String.class, Invokable<?, ?> method = method(ChefAsyncApi.class, "updateCookbook", String.class, String.class,
CookbookVersion.class); CookbookVersion.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of("cookbook", "1.0.1", GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,
new CookbookVersion("cookbook", "1.0.1"))); ImmutableList.<Object> of("cookbook", "1.0.1", new CookbookVersion("cookbook", "1.0.1"))));
assertRequestLineEquals(httpRequest, "PUT http://localhost:4000/cookbooks/cookbook/1.0.1 HTTP/1.1"); assertRequestLineEquals(httpRequest, "PUT http://localhost:4000/cookbooks/cookbook/1.0.1 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
assertPayloadEquals( + "-test\n");
httpRequest, 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\"}", "{\"name\":\"cookbook-1.0.1\",\"definitions\":[],\"attributes\":[],\"files\":[],"
"application/json", false); + "\"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); assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, null); assertFallbackClassEquals(method, null);
@ -185,10 +198,11 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testListCookbooks() throws SecurityException, NoSuchMethodException, IOException { public void testListCookbooks() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "listCookbooks"); Invokable<?, ?> method = method(ChefAsyncApi.class, "listCookbooks");
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of()); GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method, ImmutableList.of()));
assertRequestLineEquals(httpRequest, "GET http://localhost:4000/cookbooks HTTP/1.1"); assertRequestLineEquals(httpRequest, "GET http://localhost:4000/cookbooks HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
+ "-test\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseCookbookDefinitionCheckingChefVersion.class); assertResponseParserClassEquals(method, httpRequest, ParseCookbookDefinitionCheckingChefVersion.class);
@ -198,28 +212,31 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
checkFilters(httpRequest); checkFilters(httpRequest);
} }
public void testGetVersionsOfCookbook() throws SecurityException, NoSuchMethodException, IOException { public void testGetVersionsOfCookbook() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "getVersionsOfCookbook", String.class); Invokable<?, ?> method = method(ChefAsyncApi.class, "getVersionsOfCookbook", String.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of("apache2"));; GeneratedHttpRequest httpRequest = processor
.apply(Invocation.create(method, ImmutableList.<Object> of("apache2")));
assertRequestLineEquals(httpRequest, "GET http://localhost:4000/cookbooks/apache2 HTTP/1.1"); assertRequestLineEquals(httpRequest, "GET http://localhost:4000/cookbooks/apache2 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
assertPayloadEquals(httpRequest, null, null, false); + "-test\n");
assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseCookbookVersionsCheckingChefVersion.class); assertResponseParserClassEquals(method, httpRequest, ParseCookbookVersionsCheckingChefVersion.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class); assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);
checkFilters(httpRequest); checkFilters(httpRequest);
} }
public void testApiExists() throws SecurityException, NoSuchMethodException, IOException { public void testApiExists() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "clientExists", String.class); Invokable<?, ?> method = method(ChefAsyncApi.class, "clientExists", String.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of("api")); GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method, ImmutableList.<Object> of("api")));
assertRequestLineEquals(httpRequest, "HEAD http://localhost:4000/clients/api HTTP/1.1"); assertRequestLineEquals(httpRequest, "HEAD http://localhost:4000/clients/api HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
+ "-test\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ReturnTrueIf2xx.class); assertResponseParserClassEquals(method, httpRequest, ReturnTrueIf2xx.class);
@ -232,9 +249,11 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testDeleteClient() throws SecurityException, NoSuchMethodException, IOException { public void testDeleteClient() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "deleteClient", String.class); Invokable<?, ?> method = method(ChefAsyncApi.class, "deleteClient", String.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of("client")); GeneratedHttpRequest httpRequest = processor
.apply(Invocation.create(method, ImmutableList.<Object> of("client")));
assertRequestLineEquals(httpRequest, "DELETE http://localhost:4000/clients/client HTTP/1.1"); assertRequestLineEquals(httpRequest, "DELETE http://localhost:4000/clients/client HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
+ "-test\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseJson.class); assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
@ -247,10 +266,11 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testCreateApi() throws SecurityException, NoSuchMethodException, IOException { public void testCreateApi() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "createClient", String.class); Invokable<?, ?> method = method(ChefAsyncApi.class, "createClient", String.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of("api")); GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method, ImmutableList.<Object> of("api")));
assertRequestLineEquals(httpRequest, "POST http://localhost:4000/clients HTTP/1.1"); assertRequestLineEquals(httpRequest, "POST http://localhost:4000/clients HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
+ "-test\n");
assertPayloadEquals(httpRequest, "{\"name\":\"api\"}", "application/json", false); assertPayloadEquals(httpRequest, "{\"name\":\"api\"}", "application/json", false);
assertResponseParserClassEquals(method, httpRequest, ParseJson.class); assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
@ -260,29 +280,32 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
checkFilters(httpRequest); checkFilters(httpRequest);
} }
public void testCreateAdminApi() throws SecurityException, NoSuchMethodException, IOException { public void testCreateAdminApi() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "createClient", String.class, CreateClientOptions.class); Invokable<?, ?> method = method(ChefAsyncApi.class, "createClient", String.class, CreateClientOptions.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of("api", CreateClientOptions.Builder.admin())); GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,
ImmutableList.<Object> of("api", CreateClientOptions.Builder.admin())));
assertRequestLineEquals(httpRequest, "POST http://localhost:4000/clients HTTP/1.1"); assertRequestLineEquals(httpRequest, "POST http://localhost:4000/clients HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
assertPayloadEquals(httpRequest, "{\"name\":\"api\",\"admin\":true}", "application/json", false); + "-test\n");
assertPayloadEquals(httpRequest, "{\"name\":\"api\",\"admin\":true}", "application/json", false);
assertResponseParserClassEquals(method, httpRequest, ParseJson.class); assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, null); assertFallbackClassEquals(method, null);
checkFilters(httpRequest); checkFilters(httpRequest);
} }
public void testListClients() throws SecurityException, NoSuchMethodException, IOException { public void testListClients() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "listClients"); Invokable<?, ?> method = method(ChefAsyncApi.class, "listClients");
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of()); GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method, ImmutableList.of()));
assertRequestLineEquals(httpRequest, "GET http://localhost:4000/clients HTTP/1.1"); assertRequestLineEquals(httpRequest, "GET http://localhost:4000/clients HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
+ "-test\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseKeySetFromJson.class); assertResponseParserClassEquals(method, httpRequest, ParseKeySetFromJson.class);
@ -295,9 +318,11 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testGenerateKeyForClient() throws SecurityException, NoSuchMethodException, IOException { public void testGenerateKeyForClient() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "generateKeyForClient", String.class); Invokable<?, ?> method = method(ChefAsyncApi.class, "generateKeyForClient", String.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of("client")); GeneratedHttpRequest httpRequest = processor
.apply(Invocation.create(method, ImmutableList.<Object> of("client")));
assertRequestLineEquals(httpRequest, "PUT http://localhost:4000/clients/client HTTP/1.1"); assertRequestLineEquals(httpRequest, "PUT http://localhost:4000/clients/client HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
+ "-test\n");
assertPayloadEquals(httpRequest, "{\"name\":\"client\", \"private_key\": true}", "application/json", false); assertPayloadEquals(httpRequest, "{\"name\":\"client\", \"private_key\": true}", "application/json", false);
assertResponseParserClassEquals(method, httpRequest, ParseJson.class); assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
@ -310,8 +335,9 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testNodeExists() throws SecurityException, NoSuchMethodException, IOException { public void testNodeExists() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "nodeExists", String.class); Invokable<?, ?> method = method(ChefAsyncApi.class, "nodeExists", String.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of("node")); GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method, ImmutableList.<Object> of("node")));
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
+ "-test\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ReturnTrueIf2xx.class); assertResponseParserClassEquals(method, httpRequest, ReturnTrueIf2xx.class);
@ -324,9 +350,10 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testDeleteNode() throws SecurityException, NoSuchMethodException, IOException { public void testDeleteNode() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "deleteNode", String.class); Invokable<?, ?> method = method(ChefAsyncApi.class, "deleteNode", String.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of("node")); GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method, ImmutableList.<Object> of("node")));
assertRequestLineEquals(httpRequest, "DELETE http://localhost:4000/nodes/node HTTP/1.1"); assertRequestLineEquals(httpRequest, "DELETE http://localhost:4000/nodes/node HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
+ "-test\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseJson.class); assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
@ -339,15 +366,16 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testCreateNode() throws SecurityException, NoSuchMethodException, IOException { public void testCreateNode() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "createNode", Node.class); Invokable<?, ?> method = method(ChefAsyncApi.class, "createNode", Node.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(new Node("testnode", GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,
ImmutableSet.of("recipe[java]"), "_default"))); ImmutableList.<Object> of(new Node("testnode", ImmutableSet.of("recipe[java]"), "_default"))));
assertRequestLineEquals(httpRequest, "POST http://localhost:4000/nodes HTTP/1.1"); assertRequestLineEquals(httpRequest, "POST http://localhost:4000/nodes HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
assertPayloadEquals( + "-test\n");
httpRequest, assertPayloadEquals(httpRequest,
"{\"name\":\"testnode\",\"normal\":{},\"override\":{},\"default\":{},\"automatic\":{},\"run_list\":[\"recipe[java]\"],\"chef_environment\":\"_default\",\"json_class\":\"Chef::Node\",\"chef_type\":\"node\"}", "{\"name\":\"testnode\",\"normal\":{},\"override\":{},\"default\":{},\"automatic\":{},"
"application/json", false); + "\"run_list\":[\"recipe[java]\"],\"chef_environment\":\"_default\",\"json_class\":\"Chef::Node\","
+ "\"chef_type\":\"node\"}", "application/json", false);
assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class); assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
@ -359,15 +387,16 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testUpdateNode() throws SecurityException, NoSuchMethodException, IOException { public void testUpdateNode() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "updateNode", Node.class); Invokable<?, ?> method = method(ChefAsyncApi.class, "updateNode", Node.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(new Node("testnode", GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,
ImmutableSet.of("recipe[java]"), "_default"))); ImmutableList.<Object> of(new Node("testnode", ImmutableSet.of("recipe[java]"), "_default"))));
assertRequestLineEquals(httpRequest, "PUT http://localhost:4000/nodes/testnode HTTP/1.1"); assertRequestLineEquals(httpRequest, "PUT http://localhost:4000/nodes/testnode HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
assertPayloadEquals( + "-test\n");
httpRequest, assertPayloadEquals(httpRequest,
"{\"name\":\"testnode\",\"normal\":{},\"override\":{},\"default\":{},\"automatic\":{},\"run_list\":[\"recipe[java]\"],\"chef_environment\":\"_default\",\"json_class\":\"Chef::Node\",\"chef_type\":\"node\"}", "{\"name\":\"testnode\",\"normal\":{},\"override\":{},\"default\":{},\"automatic\":{},"
"application/json", false); + "\"run_list\":[\"recipe[java]\"],\"chef_environment\":\"_default\",\"json_class\":\"Chef::Node\","
+ "\"chef_type\":\"node\"}", "application/json", false);
assertResponseParserClassEquals(method, httpRequest, ParseJson.class); assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
@ -379,10 +408,11 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testListNodes() throws SecurityException, NoSuchMethodException, IOException { public void testListNodes() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "listNodes"); Invokable<?, ?> method = method(ChefAsyncApi.class, "listNodes");
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of()); GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method, ImmutableList.of()));
assertRequestLineEquals(httpRequest, "GET http://localhost:4000/nodes HTTP/1.1"); assertRequestLineEquals(httpRequest, "GET http://localhost:4000/nodes HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
+ "-test\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseKeySetFromJson.class); assertResponseParserClassEquals(method, httpRequest, ParseKeySetFromJson.class);
@ -395,9 +425,10 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testRoleExists() throws SecurityException, NoSuchMethodException, IOException { public void testRoleExists() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "roleExists", String.class); Invokable<?, ?> method = method(ChefAsyncApi.class, "roleExists", String.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of("role")); GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method, ImmutableList.<Object> of("role")));
assertRequestLineEquals(httpRequest, "HEAD http://localhost:4000/roles/role HTTP/1.1"); assertRequestLineEquals(httpRequest, "HEAD http://localhost:4000/roles/role HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
+ "-test\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ReturnTrueIf2xx.class); assertResponseParserClassEquals(method, httpRequest, ReturnTrueIf2xx.class);
@ -410,9 +441,10 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testDeleteRole() throws SecurityException, NoSuchMethodException, IOException { public void testDeleteRole() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "deleteRole", String.class); Invokable<?, ?> method = method(ChefAsyncApi.class, "deleteRole", String.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of("role")); GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method, ImmutableList.<Object> of("role")));
assertRequestLineEquals(httpRequest, "DELETE http://localhost:4000/roles/role HTTP/1.1"); assertRequestLineEquals(httpRequest, "DELETE http://localhost:4000/roles/role HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
+ "-test\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseJson.class); assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
@ -425,14 +457,14 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testCreateRole() throws SecurityException, NoSuchMethodException, IOException { public void testCreateRole() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "createRole", Role.class); Invokable<?, ?> method = method(ChefAsyncApi.class, "createRole", Role.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(new Role("testrole", GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,
ImmutableSet.of("recipe[java]")))); ImmutableList.<Object> of(new Role("testrole", ImmutableSet.of("recipe[java]")))));
assertRequestLineEquals(httpRequest, "POST http://localhost:4000/roles HTTP/1.1"); assertRequestLineEquals(httpRequest, "POST http://localhost:4000/roles HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
assertPayloadEquals( + "-test\n");
httpRequest, assertPayloadEquals(httpRequest, "{\"name\":\"testrole\",\"override_attributes\":{},\"default_attributes\":{},"
"{\"name\":\"testrole\",\"override_attributes\":{},\"default_attributes\":{},\"run_list\":[\"recipe[java]\"],\"json_class\":\"Chef::Role\",\"chef_type\":\"role\"}", + "\"run_list\":[\"recipe[java]\"],\"json_class\":\"Chef::Role\",\"chef_type\":\"role\"}",
"application/json", false); "application/json", false);
assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class); assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);
@ -445,14 +477,14 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testUpdateRole() throws SecurityException, NoSuchMethodException, IOException { public void testUpdateRole() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "updateRole", Role.class); Invokable<?, ?> method = method(ChefAsyncApi.class, "updateRole", Role.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(new Role("testrole", GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,
ImmutableSet.of("recipe[java]")))); ImmutableList.<Object> of(new Role("testrole", ImmutableSet.of("recipe[java]")))));
assertRequestLineEquals(httpRequest, "PUT http://localhost:4000/roles/testrole HTTP/1.1"); assertRequestLineEquals(httpRequest, "PUT http://localhost:4000/roles/testrole HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
assertPayloadEquals( + "-test\n");
httpRequest, assertPayloadEquals(httpRequest, "{\"name\":\"testrole\",\"override_attributes\":{},\"default_attributes\":{},"
"{\"name\":\"testrole\",\"override_attributes\":{},\"default_attributes\":{},\"run_list\":[\"recipe[java]\"],\"json_class\":\"Chef::Role\",\"chef_type\":\"role\"}", + "\"run_list\":[\"recipe[java]\"],\"json_class\":\"Chef::Role\",\"chef_type\":\"role\"}",
"application/json", false); "application/json", false);
assertResponseParserClassEquals(method, httpRequest, ParseJson.class); assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
@ -465,10 +497,11 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testListRoles() throws SecurityException, NoSuchMethodException, IOException { public void testListRoles() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "listRoles"); Invokable<?, ?> method = method(ChefAsyncApi.class, "listRoles");
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of()); GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method, ImmutableList.of()));
assertRequestLineEquals(httpRequest, "GET http://localhost:4000/roles HTTP/1.1"); assertRequestLineEquals(httpRequest, "GET http://localhost:4000/roles HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
+ "-test\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseKeySetFromJson.class); assertResponseParserClassEquals(method, httpRequest, ParseKeySetFromJson.class);
@ -481,9 +514,11 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testDatabagExists() throws SecurityException, NoSuchMethodException, IOException { public void testDatabagExists() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "databagExists", String.class); Invokable<?, ?> method = method(ChefAsyncApi.class, "databagExists", String.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of("databag")); GeneratedHttpRequest httpRequest = processor
.apply(Invocation.create(method, ImmutableList.<Object> of("databag")));
assertRequestLineEquals(httpRequest, "HEAD http://localhost:4000/data/databag HTTP/1.1"); assertRequestLineEquals(httpRequest, "HEAD http://localhost:4000/data/databag HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
+ "-test\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ReturnTrueIf2xx.class); assertResponseParserClassEquals(method, httpRequest, ReturnTrueIf2xx.class);
@ -496,9 +531,11 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testDeleteDatabag() throws SecurityException, NoSuchMethodException, IOException { public void testDeleteDatabag() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "deleteDatabag", String.class); Invokable<?, ?> method = method(ChefAsyncApi.class, "deleteDatabag", String.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of("databag")); GeneratedHttpRequest httpRequest = processor
.apply(Invocation.create(method, ImmutableList.<Object> of("databag")));
assertRequestLineEquals(httpRequest, "DELETE http://localhost:4000/data/databag HTTP/1.1"); assertRequestLineEquals(httpRequest, "DELETE http://localhost:4000/data/databag HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
+ "-test\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class); assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);
@ -511,10 +548,11 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testCreateDatabag() throws SecurityException, NoSuchMethodException, IOException { public void testCreateDatabag() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "createDatabag", String.class); Invokable<?, ?> method = method(ChefAsyncApi.class, "createDatabag", String.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of("name")); GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method, ImmutableList.<Object> of("name")));
assertRequestLineEquals(httpRequest, "POST http://localhost:4000/data HTTP/1.1"); assertRequestLineEquals(httpRequest, "POST http://localhost:4000/data HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
+ "-test\n");
assertPayloadEquals(httpRequest, "{\"name\":\"name\"}", "application/json", false); assertPayloadEquals(httpRequest, "{\"name\":\"name\"}", "application/json", false);
assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class); assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);
@ -527,10 +565,11 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testListDatabags() throws SecurityException, NoSuchMethodException, IOException { public void testListDatabags() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "listDatabags"); Invokable<?, ?> method = method(ChefAsyncApi.class, "listDatabags");
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of()); GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method, ImmutableList.of()));
assertRequestLineEquals(httpRequest, "GET http://localhost:4000/data HTTP/1.1"); assertRequestLineEquals(httpRequest, "GET http://localhost:4000/data HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
+ "-test\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseKeySetFromJson.class); assertResponseParserClassEquals(method, httpRequest, ParseKeySetFromJson.class);
@ -543,9 +582,11 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testDatabagItemExists() throws SecurityException, NoSuchMethodException, IOException { public void testDatabagItemExists() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "databagItemExists", String.class, String.class); Invokable<?, ?> method = method(ChefAsyncApi.class, "databagItemExists", String.class, String.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of("name", "databagItem")); GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,
ImmutableList.<Object> of("name", "databagItem")));
assertRequestLineEquals(httpRequest, "HEAD http://localhost:4000/data/name/databagItem HTTP/1.1"); assertRequestLineEquals(httpRequest, "HEAD http://localhost:4000/data/name/databagItem HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
+ "-test\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ReturnTrueIf2xx.class); assertResponseParserClassEquals(method, httpRequest, ReturnTrueIf2xx.class);
@ -558,8 +599,10 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testDeleteDatabagItem() throws SecurityException, NoSuchMethodException, IOException { public void testDeleteDatabagItem() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "deleteDatabagItem", String.class, String.class); Invokable<?, ?> method = method(ChefAsyncApi.class, "deleteDatabagItem", String.class, String.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of("name", "databagItem")); GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n"); ImmutableList.<Object> of("name", "databagItem")));
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
+ "-test\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseJson.class); assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
@ -574,14 +617,16 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testCreateDatabagItemThrowsIllegalArgumentOnPrimitive() throws SecurityException, NoSuchMethodException, public void testCreateDatabagItemThrowsIllegalArgumentOnPrimitive() throws SecurityException, NoSuchMethodException,
IOException { IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "createDatabagItem", String.class, DatabagItem.class); Invokable<?, ?> method = method(ChefAsyncApi.class, "createDatabagItem", String.class, DatabagItem.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of("name", new DatabagItem("id", GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,
"100"))); ImmutableList.<Object> of("name", new DatabagItem("id", "100"))));
assertRequestLineEquals(httpRequest, "POST http://localhost:4000/data/name HTTP/1.1"); assertRequestLineEquals(httpRequest, "POST http://localhost:4000/data/name HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
+ "-test\n");
assertPayloadEquals( assertPayloadEquals(
httpRequest, httpRequest,
"{\"name\":\"testdatabagItem\",\"override_attributes\":{},\"default_attributes\":{},\"run_list\":[\"recipe[java]\"],\"json_class\":\"Chef::DatabagItem\",\"chef_type\":\"databagItem\"}", "{\"name\":\"testdatabagItem\",\"override_attributes\":{},\"default_attributes\":{},"
+ "\"run_list\":[\"recipe[java]\"],\"json_class\":\"Chef::DatabagItem\",\"chef_type\":\"databagItem\"}",
"application/json", false); "application/json", false);
assertResponseParserClassEquals(method, httpRequest, ParseJson.class); assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
@ -596,14 +641,16 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testCreateDatabagItemThrowsIllegalArgumentOnWrongId() throws SecurityException, NoSuchMethodException, public void testCreateDatabagItemThrowsIllegalArgumentOnWrongId() throws SecurityException, NoSuchMethodException,
IOException { IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "createDatabagItem", String.class, DatabagItem.class); Invokable<?, ?> method = method(ChefAsyncApi.class, "createDatabagItem", String.class, DatabagItem.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of("name", new DatabagItem("id", GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,
"{\"id\": \"item1\",\"my_key\": \"my_data\"}"))); ImmutableList.<Object> of("name", new DatabagItem("id", "{\"id\": \"item1\",\"my_key\": \"my_data\"}"))));
assertRequestLineEquals(httpRequest, "POST http://localhost:4000/data/name HTTP/1.1"); assertRequestLineEquals(httpRequest, "POST http://localhost:4000/data/name HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
+ "-test\n");
assertPayloadEquals( assertPayloadEquals(
httpRequest, httpRequest,
"{\"name\":\"testdatabagItem\",\"override_attributes\":{},\"default_attributes\":{},\"run_list\":[\"recipe[java]\"],\"json_class\":\"Chef::DatabagItem\",\"chef_type\":\"databagItem\"}", "{\"name\":\"testdatabagItem\",\"override_attributes\":{},\"default_attributes\":{},"
+ "\"run_list\":[\"recipe[java]\"],\"json_class\":\"Chef::DatabagItem\",\"chef_type\":\"databagItem\"}",
"application/json", false); "application/json", false);
assertResponseParserClassEquals(method, httpRequest, ParseJson.class); assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
@ -616,11 +663,12 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testCreateDatabagItem() throws SecurityException, NoSuchMethodException, IOException { public void testCreateDatabagItem() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "createDatabagItem", String.class, DatabagItem.class); Invokable<?, ?> method = method(ChefAsyncApi.class, "createDatabagItem", String.class, DatabagItem.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of("name", new DatabagItem("id", GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,
"{\"id\": \"id\",\"my_key\": \"my_data\"}"))); ImmutableList.<Object> of("name", new DatabagItem("id", "{\"id\": \"id\",\"my_key\": \"my_data\"}"))));
assertRequestLineEquals(httpRequest, "POST http://localhost:4000/data/name HTTP/1.1"); assertRequestLineEquals(httpRequest, "POST http://localhost:4000/data/name HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
+ "-test\n");
assertPayloadEquals(httpRequest, "{\"id\": \"id\",\"my_key\": \"my_data\"}", "application/json", false); assertPayloadEquals(httpRequest, "{\"id\": \"id\",\"my_key\": \"my_data\"}", "application/json", false);
assertResponseParserClassEquals(method, httpRequest, ParseJson.class); assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
@ -633,11 +681,12 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testCreateDatabagItemEvenWhenUserForgotId() throws SecurityException, NoSuchMethodException, IOException { public void testCreateDatabagItemEvenWhenUserForgotId() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "createDatabagItem", String.class, DatabagItem.class); Invokable<?, ?> method = method(ChefAsyncApi.class, "createDatabagItem", String.class, DatabagItem.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of("name", new DatabagItem("id", GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,
"{\"my_key\": \"my_data\"}"))); ImmutableList.<Object> of("name", new DatabagItem("id", "{\"my_key\": \"my_data\"}"))));
assertRequestLineEquals(httpRequest, "POST http://localhost:4000/data/name HTTP/1.1"); assertRequestLineEquals(httpRequest, "POST http://localhost:4000/data/name HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
+ "-test\n");
assertPayloadEquals(httpRequest, "{\"id\":\"id\",\"my_key\": \"my_data\"}", "application/json", false); assertPayloadEquals(httpRequest, "{\"id\":\"id\",\"my_key\": \"my_data\"}", "application/json", false);
assertResponseParserClassEquals(method, httpRequest, ParseJson.class); assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
@ -650,11 +699,12 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testUpdateDatabagItem() throws SecurityException, NoSuchMethodException, IOException { public void testUpdateDatabagItem() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "updateDatabagItem", String.class, DatabagItem.class); Invokable<?, ?> method = method(ChefAsyncApi.class, "updateDatabagItem", String.class, DatabagItem.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of("name", new DatabagItem("id", GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,
"{\"my_key\": \"my_data\"}"))); ImmutableList.<Object> of("name", new DatabagItem("id", "{\"my_key\": \"my_data\"}"))));
assertRequestLineEquals(httpRequest, "PUT http://localhost:4000/data/name/id HTTP/1.1"); assertRequestLineEquals(httpRequest, "PUT http://localhost:4000/data/name/id HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
+ "-test\n");
assertPayloadEquals(httpRequest, "{\"id\":\"id\",\"my_key\": \"my_data\"}", "application/json", false); assertPayloadEquals(httpRequest, "{\"id\":\"id\",\"my_key\": \"my_data\"}", "application/json", false);
@ -668,10 +718,11 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testListDatabagItems() throws SecurityException, NoSuchMethodException, IOException { public void testListDatabagItems() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "listDatabagItems", String.class); Invokable<?, ?> method = method(ChefAsyncApi.class, "listDatabagItems", String.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of("name")); GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method, ImmutableList.<Object> of("name")));
assertRequestLineEquals(httpRequest, "GET http://localhost:4000/data/name HTTP/1.1"); assertRequestLineEquals(httpRequest, "GET http://localhost:4000/data/name HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
+ "-test\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseKeySetFromJson.class); assertResponseParserClassEquals(method, httpRequest, ParseKeySetFromJson.class);
@ -684,10 +735,11 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testListSearchIndexes() throws SecurityException, NoSuchMethodException, IOException { public void testListSearchIndexes() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "listSearchIndexes"); Invokable<?, ?> method = method(ChefAsyncApi.class, "listSearchIndexes");
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of()); GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method, ImmutableList.of()));
assertRequestLineEquals(httpRequest, "GET http://localhost:4000/search HTTP/1.1"); assertRequestLineEquals(httpRequest, "GET http://localhost:4000/search HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
+ "-test\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseKeySetFromJson.class); assertResponseParserClassEquals(method, httpRequest, ParseKeySetFromJson.class);
@ -700,10 +752,11 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testSearchRoles() throws SecurityException, NoSuchMethodException, IOException { public void testSearchRoles() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "searchRoles"); Invokable<?, ?> method = method(ChefAsyncApi.class, "searchRoles");
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of()); GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method, ImmutableList.of()));
assertRequestLineEquals(httpRequest, "GET http://localhost:4000/search/role HTTP/1.1"); assertRequestLineEquals(httpRequest, "GET http://localhost:4000/search/role HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
+ "-test\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseSearchRolesFromJson.class); assertResponseParserClassEquals(method, httpRequest, ParseSearchRolesFromJson.class);
@ -713,14 +766,15 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
checkFilters(httpRequest); checkFilters(httpRequest);
} }
public void testSearchRolesWithOptions() throws SecurityException, NoSuchMethodException, IOException { public void testSearchRolesWithOptions() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "searchRoles", SearchOptions.class); Invokable<?, ?> method = method(ChefAsyncApi.class, "searchRoles", SearchOptions.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of( GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,
SearchOptions.Builder.query("text"))); ImmutableList.<Object> of(SearchOptions.Builder.query("text"))));
assertRequestLineEquals(httpRequest, "GET http://localhost:4000/search/role?q=text HTTP/1.1"); assertRequestLineEquals(httpRequest, "GET http://localhost:4000/search/role?q=text HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
+ "-test\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseSearchRolesFromJson.class); assertResponseParserClassEquals(method, httpRequest, ParseSearchRolesFromJson.class);
@ -733,10 +787,11 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testSearchClients() throws SecurityException, NoSuchMethodException, IOException { public void testSearchClients() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "searchClients"); Invokable<?, ?> method = method(ChefAsyncApi.class, "searchClients");
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of()); GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method, ImmutableList.of()));
assertRequestLineEquals(httpRequest, "GET http://localhost:4000/search/client HTTP/1.1"); assertRequestLineEquals(httpRequest, "GET http://localhost:4000/search/client HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
+ "-test\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseSearchClientsFromJson.class); assertResponseParserClassEquals(method, httpRequest, ParseSearchClientsFromJson.class);
@ -746,30 +801,32 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
checkFilters(httpRequest); checkFilters(httpRequest);
} }
public void testSearchClientsWithOptions() throws SecurityException, NoSuchMethodException, IOException { public void testSearchClientsWithOptions() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "searchClients", SearchOptions.class); Invokable<?, ?> method = method(ChefAsyncApi.class, "searchClients", SearchOptions.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of( GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,
SearchOptions.Builder.query("text").rows(5))); ImmutableList.<Object> of(SearchOptions.Builder.query("text").rows(5))));
assertRequestLineEquals(httpRequest, "GET http://localhost:4000/search/client?q=text&rows=5 HTTP/1.1"); assertRequestLineEquals(httpRequest, "GET http://localhost:4000/search/client?q=text&rows=5 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
assertPayloadEquals(httpRequest, null, null, false); + "-test\n");
assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseSearchClientsFromJson.class); assertResponseParserClassEquals(method, httpRequest, ParseSearchClientsFromJson.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class); assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);
checkFilters(httpRequest); checkFilters(httpRequest);
} }
public void testSearchNodes() throws SecurityException, NoSuchMethodException, IOException { public void testSearchNodes() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "searchNodes"); Invokable<?, ?> method = method(ChefAsyncApi.class, "searchNodes");
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of()); GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method, ImmutableList.of()));
assertRequestLineEquals(httpRequest, "GET http://localhost:4000/search/node HTTP/1.1"); assertRequestLineEquals(httpRequest, "GET http://localhost:4000/search/node HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
+ "-test\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseSearchNodesFromJson.class); assertResponseParserClassEquals(method, httpRequest, ParseSearchNodesFromJson.class);
@ -779,14 +836,15 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
checkFilters(httpRequest); checkFilters(httpRequest);
} }
public void testSearchNodesWithOptions() throws SecurityException, NoSuchMethodException, IOException { public void testSearchNodesWithOptions() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "searchNodes", SearchOptions.class); Invokable<?, ?> method = method(ChefAsyncApi.class, "searchNodes", SearchOptions.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of( GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,
SearchOptions.Builder.query("foo:foo").start(3))); ImmutableList.<Object> of(SearchOptions.Builder.query("foo:foo").start(3))));
assertRequestLineEquals(httpRequest, "GET http://localhost:4000/search/node?q=foo%3Afoo&start=3 HTTP/1.1"); assertRequestLineEquals(httpRequest, "GET http://localhost:4000/search/node?q=foo%3Afoo&start=3 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
+ "-test\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseSearchNodesFromJson.class); assertResponseParserClassEquals(method, httpRequest, ParseSearchNodesFromJson.class);
@ -797,13 +855,13 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
} }
public void testSearchDatabag() throws SecurityException, NoSuchMethodException, IOException { public void testSearchDatabag() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "searchDatabag", String.class); Invokable<?, ?> method = method(ChefAsyncApi.class, "searchDatabag", String.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of("foo")); GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method, ImmutableList.<Object> of("foo")));
assertRequestLineEquals(httpRequest, "GET http://localhost:4000/search/foo HTTP/1.1"); assertRequestLineEquals(httpRequest, "GET http://localhost:4000/search/foo HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
+ "-test\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseSearchDatabagFromJson.class); assertResponseParserClassEquals(method, httpRequest, ParseSearchDatabagFromJson.class);
@ -813,14 +871,15 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
checkFilters(httpRequest); checkFilters(httpRequest);
} }
public void testSearchDatabagWithOptions() throws SecurityException, NoSuchMethodException, IOException { public void testSearchDatabagWithOptions() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "searchDatabag", String.class, SearchOptions.class); Invokable<?, ?> method = method(ChefAsyncApi.class, "searchDatabag", String.class, SearchOptions.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of("foo", GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,
SearchOptions.Builder.query("bar").sort("name DESC"))); ImmutableList.<Object> of("foo", SearchOptions.Builder.query("bar").sort("name DESC"))));
assertRequestLineEquals(httpRequest, "GET http://localhost:4000/search/foo?q=bar&sort=name%20DESC HTTP/1.1"); assertRequestLineEquals(httpRequest, "GET http://localhost:4000/search/foo?q=bar&sort=name%20DESC HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
+ "-test\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseSearchDatabagFromJson.class); assertResponseParserClassEquals(method, httpRequest, ParseSearchDatabagFromJson.class);
@ -830,23 +889,24 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
checkFilters(httpRequest); checkFilters(httpRequest);
} }
public void testGetResourceContents() throws SecurityException, NoSuchMethodException, IOException { public void testGetResourceContents() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "getResourceContents", Resource.class); Invokable<?, ?> method = method(ChefAsyncApi.class, "getResourceContents", Resource.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of( GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,
new Resource("test", URI.create("http://foo/bar"), new byte[]{}, null, null))); ImmutableList.<Object> of(new Resource("test", URI.create("http://foo/bar"), new byte[] {}, null, null))));
assertRequestLineEquals(httpRequest, "GET http://foo/bar HTTP/1.1"); assertRequestLineEquals(httpRequest, "GET http://foo/bar HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
assertPayloadEquals(httpRequest, null, null, false); + "-test\n");
assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ReturnInputStream.class); assertResponseParserClassEquals(method, httpRequest, ReturnInputStream.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, NullOnNotFoundOr404.class); assertFallbackClassEquals(method, NullOnNotFoundOr404.class);
checkFilters(httpRequest); checkFilters(httpRequest);
} }
@Override @Override
protected void checkFilters(HttpRequest request) { protected void checkFilters(HttpRequest request) {
@ -861,9 +921,9 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
@Override @Override
protected Properties setupProperties() { protected Properties setupProperties() {
Properties props = super.setupProperties(); Properties props = super.setupProperties();
props.put(Constants.PROPERTY_API_VERSION, ChefAsyncApi.VERSION + "-test"); props.put(Constants.PROPERTY_API_VERSION, ChefAsyncApi.VERSION + "-test");
return props; return props;
} }
@ConfiguresRestClient @ConfiguresRestClient

View File

@ -44,13 +44,12 @@ import com.google.inject.Injector;
public class BindHexEncodedMD5sToJsonPayloadTest { public class BindHexEncodedMD5sToJsonPayloadTest {
Injector injector = Guice.createInjector(new AbstractModule() { Injector injector = Guice.createInjector(new AbstractModule() {
@Override @Override
protected void configure() protected void configure() {
{ bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefAsyncApi.VERSION);
bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefAsyncApi.VERSION); }
} }, new ChefParserModule(), new GsonModule());
}, new ChefParserModule(), new GsonModule());
BindChecksumsToJsonPayload binder = injector.getInstance(BindChecksumsToJsonPayload.class); BindChecksumsToJsonPayload binder = injector.getInstance(BindChecksumsToJsonPayload.class);
@Test(expectedExceptions = IllegalArgumentException.class) @Test(expectedExceptions = IllegalArgumentException.class)
@ -62,7 +61,8 @@ public class BindHexEncodedMD5sToJsonPayloadTest {
@Test(enabled = false) @Test(enabled = false)
public void testCorrect() { public void testCorrect() {
HttpRequest request = HttpRequest.builder().method(HttpMethod.POST).endpoint("http://localhost").build(); HttpRequest request = HttpRequest.builder().method(HttpMethod.POST).endpoint("http://localhost").build();
binder.bindToRequest(request, ImmutableSet.of(base16().lowerCase().decode("abddef"), base16().lowerCase().decode("1234"))); binder.bindToRequest(request,
ImmutableSet.of(base16().lowerCase().decode("abddef"), base16().lowerCase().decode("1234")));
assertEquals(request.getPayload().getRawContent(), "{\"checksums\":{\"abddef\":null,\"1234\":null}}"); assertEquals(request.getPayload().getRawContent(), "{\"checksums\":{\"abddef\":null,\"1234\":null}}");
} }

View File

@ -80,30 +80,31 @@ public class SignedHeaderAuthTest {
"NMzYZgyooSvU85qkIUmKuCqgG2AIlvYa2Q/2ctrMhoaHhLOCWWoqYNMaEqPc", "NMzYZgyooSvU85qkIUmKuCqgG2AIlvYa2Q/2ctrMhoaHhLOCWWoqYNMaEqPc",
"3tKHE+CfvP+WuPdWk4jv4wpIkAz6ZLxToxcGhXmZbXpk56YTmqgBW2cbbw4O", "3tKHE+CfvP+WuPdWk4jv4wpIkAz6ZLxToxcGhXmZbXpk56YTmqgBW2cbbw4O",
"IWPZDHSiPcw//AYNgW1CCDptt+UFuaFYbtqZegcBd2n/jzcWODA7zL4KWEUy", "IWPZDHSiPcw//AYNgW1CCDptt+UFuaFYbtqZegcBd2n/jzcWODA7zL4KWEUy",
"9q4rlh/+1tBReg60QdsmDRsw/cdO1GZrKtuCwbuD4+nbRdVBKv72rqHX9cu0", "9q4rlh/+1tBReg60QdsmDRsw/cdO1GZrKtuCwbuD4+nbRdVBKv72rqHX9cu0", "utju9jzczCyB+sSAQWrxSsXB/b8vV2qs0l4VD2ML+w==" };
"utju9jzczCyB+sSAQWrxSsXB/b8vV2qs0l4VD2ML+w==" };
// We expect Mixlib::Authentication::SignedHeaderAuth//sign to return this // We expect Mixlib::Authentication::SignedHeaderAuth//sign to return this
// if passed the BODY above. // if passed the BODY above.
public static final Multimap<String, String> EXPECTED_SIGN_RESULT = ImmutableMultimap.<String, String> builder() public static final Multimap<String, String> EXPECTED_SIGN_RESULT = ImmutableMultimap.<String, String> 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-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", .put("X-Ops-Authorization-1", X_OPS_AUTHORIZATION_LINES[0])
X_OPS_AUTHORIZATION_LINES[1]).put("X-Ops-Authorization-3", X_OPS_AUTHORIZATION_LINES[2]).put( .put("X-Ops-Authorization-2", X_OPS_AUTHORIZATION_LINES[1])
"X-Ops-Authorization-4", X_OPS_AUTHORIZATION_LINES[3]).put("X-Ops-Authorization-5", .put("X-Ops-Authorization-3", X_OPS_AUTHORIZATION_LINES[2])
X_OPS_AUTHORIZATION_LINES[4]).put("X-Ops-Authorization-6", X_OPS_AUTHORIZATION_LINES[5]).put( .put("X-Ops-Authorization-4", X_OPS_AUTHORIZATION_LINES[3])
"X-Ops-Timestamp", TIMESTAMP_ISO8601).build(); .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 // Content hash for empty string
public static final String X_OPS_CONTENT_HASH_EMPTY = "2jmj7l5rSw0yVb/vlWAYkK/YBwk="; public static final String X_OPS_CONTENT_HASH_EMPTY = "2jmj7l5rSw0yVb/vlWAYkK/YBwk=";
public static final Multimap<String, String> EXPECTED_SIGN_RESULT_EMPTY = ImmutableMultimap public static final Multimap<String, String> EXPECTED_SIGN_RESULT_EMPTY = ImmutableMultimap
.<String, String> builder().put("X-Ops-Content-Hash", X_OPS_CONTENT_HASH_EMPTY).put("X-Ops-Userid", USER_ID) .<String, String> 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", .put("X-Ops-Sign", "version=1.0")
"N6U75kopDK64cEFqrB6vw+PnubnXr0w5LQeXnIGNGLRP2LvifwIeisk7QxEx").put("X-Ops-Authorization-2", .put("X-Ops-Authorization-1", "N6U75kopDK64cEFqrB6vw+PnubnXr0w5LQeXnIGNGLRP2LvifwIeisk7QxEx")
"mtpQOWAw8HvnWErjzuk9AvUsqVmWpv14ficvkaD79qsPMvbje+aLcIrCGT1P").put("X-Ops-Authorization-3", .put("X-Ops-Authorization-2", "mtpQOWAw8HvnWErjzuk9AvUsqVmWpv14ficvkaD79qsPMvbje+aLcIrCGT1P")
"3d2uvf4w7iqwzrIscPnkxLR6o6pymR90gvJXDPzV7Le0jbfD8kmZ8AAK0sGG").put("X-Ops-Authorization-4", .put("X-Ops-Authorization-3", "3d2uvf4w7iqwzrIscPnkxLR6o6pymR90gvJXDPzV7Le0jbfD8kmZ8AAK0sGG")
"09F1ftW80bLatJTA66Cw2wBz261r6x/abZhIKFJFDWLzyQGJ8ZNOkUrDDtgI").put("X-Ops-Authorization-5", .put("X-Ops-Authorization-4", "09F1ftW80bLatJTA66Cw2wBz261r6x/abZhIKFJFDWLzyQGJ8ZNOkUrDDtgI")
"svLVXpOJKZZfKunsElpWjjsyNt3k8vpI1Y4ANO8Eg2bmeCPeEK+YriGm5fbC").put("X-Ops-Authorization-6", .put("X-Ops-Authorization-5", "svLVXpOJKZZfKunsElpWjjsyNt3k8vpI1Y4ANO8Eg2bmeCPeEK+YriGm5fbC")
"DzWNPylHJqMeGKVYwGQKpg62QDfe5yXh3wZLiQcXow==").put("X-Ops-Timestamp", TIMESTAMP_ISO8601).build(); .put("X-Ops-Authorization-6", "DzWNPylHJqMeGKVYwGQKpg62QDfe5yXh3wZLiQcXow==")
.put("X-Ops-Timestamp", TIMESTAMP_ISO8601).build();
public static String PUBLIC_KEY; public static String PUBLIC_KEY;
public static String PRIVATE_KEY; public static String PRIVATE_KEY;
@ -131,9 +132,8 @@ public class SignedHeaderAuthTest {
@Test @Test
void shouldGenerateTheCorrectStringToSignAndSignature() { void shouldGenerateTheCorrectStringToSignAndSignature() {
HttpRequest request = HttpRequest.builder().method(HttpMethod.POST) HttpRequest request = HttpRequest.builder().method(HttpMethod.POST).endpoint("http://localhost/" + PATH)
.endpoint("http://localhost/" + PATH) .payload(BODY).build();
.payload(BODY).build();
String expected_string_to_sign = new StringBuilder().append("Method:POST").append("\n").append("Hashed Path:") 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(HASHED_CANONICAL_PATH).append("\n").append("X-Ops-Content-Hash:").append(HASHED_BODY).append("\n")
@ -146,19 +146,20 @@ public class SignedHeaderAuthTest {
request = signing_obj.filter(request); request = signing_obj.filter(request);
Multimap<String, String> headersWithoutContentLength = LinkedHashMultimap.create(request.getHeaders()); Multimap<String, String> headersWithoutContentLength = LinkedHashMultimap.create(request.getHeaders());
headersWithoutContentLength.removeAll( HttpHeaders.CONTENT_LENGTH ); headersWithoutContentLength.removeAll(HttpHeaders.CONTENT_LENGTH);
assertEqualsNoOrder( headersWithoutContentLength.values().toArray(), EXPECTED_SIGN_RESULT.values().toArray() ); assertEqualsNoOrder(headersWithoutContentLength.values().toArray(), EXPECTED_SIGN_RESULT.values().toArray());
} }
@Test @Test
void shouldGenerateTheCorrectStringToSignAndSignatureWithNoBody() { void shouldGenerateTheCorrectStringToSignAndSignatureWithNoBody() {
HttpRequest request = HttpRequest.builder().method(HttpMethod.DELETE) HttpRequest request = HttpRequest.builder().method(HttpMethod.DELETE).endpoint("http://localhost/" + PATH)
.endpoint("http://localhost/" + PATH).build(); .build();
request = signing_obj.filter(request); request = signing_obj.filter(request);
Multimap<String, String> headersWithoutContentLength = LinkedHashMultimap.create(request.getHeaders()); Multimap<String, String> headersWithoutContentLength = LinkedHashMultimap.create(request.getHeaders());
assertEqualsNoOrder(headersWithoutContentLength.entries().toArray(), EXPECTED_SIGN_RESULT_EMPTY.entries().toArray()); assertEqualsNoOrder(headersWithoutContentLength.entries().toArray(), EXPECTED_SIGN_RESULT_EMPTY.entries()
.toArray());
} }
@Test @Test
@ -167,8 +168,7 @@ public class SignedHeaderAuthTest {
for (int i = 0; i < 100; i++) for (int i = 0; i < 100; i++)
path.append('A'); path.append('A');
HttpRequest request = HttpRequest.builder().method(HttpMethod.PUT) HttpRequest request = HttpRequest.builder().method(HttpMethod.PUT)
.endpoint("http://localhost/" + path.toString()) .endpoint("http://localhost/" + path.toString()).payload(BODY).build();
.payload(BODY).build();
signing_obj.filter(request); signing_obj.filter(request);
} }

View File

@ -70,7 +70,7 @@ public class ClientForGroupTest {
ClientForGroup fn = new ClientForGroup(chefApi); ClientForGroup fn = new ClientForGroup(chefApi);
expect(chefApi.listClients()).andReturn( expect(chefApi.listClients()).andReturn(
ImmutableSet.<String> of("foo-client-00", "foo-client-01", "foo-client-02")); ImmutableSet.<String> of("foo-client-00", "foo-client-01", "foo-client-02"));
expect(chefApi.createClient("foo-client-03")).andReturn(client); expect(chefApi.createClient("foo-client-03")).andReturn(client);
expect(client.getPrivateKey()).andReturn(privateKey); expect(client.getPrivateKey()).andReturn(privateKey);

View File

@ -65,14 +65,13 @@ public class ParseClientFromJsonTest {
@BeforeTest @BeforeTest
protected void setUpInjector() throws IOException, CertificateException, InvalidKeySpecException { protected void setUpInjector() throws IOException, CertificateException, InvalidKeySpecException {
Injector injector = Guice.createInjector(new AbstractModule() { Injector injector = Guice.createInjector(new AbstractModule() {
@Override @Override
protected void configure() protected void configure() {
{ bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefAsyncApi.VERSION);
bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefAsyncApi.VERSION); }
} }, new ChefParserModule(), new GsonModule());
}, new ChefParserModule(), new GsonModule());
handler = injector.getInstance(Key.get(new TypeLiteral<ParseJson<Client>>() { handler = injector.getInstance(Key.get(new TypeLiteral<ParseJson<Client>>() {
})); }));
crypto = injector.getInstance(Crypto.class); crypto = injector.getInstance(Crypto.class);
@ -83,15 +82,17 @@ public class ParseClientFromJsonTest {
public void test() throws IOException { public void test() throws IOException {
Client user = new Client(certificate, "jclouds", "adriancole-jcloudstest", "adriancole-jcloudstest", false, Client user = new Client(certificate, "jclouds", "adriancole-jcloudstest", "adriancole-jcloudstest", false,
privateKey); privateKey);
byte[] encrypted = ByteStreams.toByteArray(new RSAEncryptingPayload(Payloads.newPayload("fooya"), user byte[] encrypted = ByteStreams.toByteArray(new RSAEncryptingPayload(Payloads.newPayload("fooya"), user
.getCertificate().getPublicKey())); .getCertificate().getPublicKey()));
assertEquals(ByteStreams.toByteArray(new RSADecryptingPayload(Payloads.newPayload(encrypted), user assertEquals(
.getPrivateKey())), "fooya".getBytes()); ByteStreams.toByteArray(new RSADecryptingPayload(Payloads.newPayload(encrypted), user.getPrivateKey())),
"fooya".getBytes());
assertEquals(handler.apply(HttpResponse.builder().statusCode(200).message("ok").payload(ParseClientFromJsonTest.class assertEquals(
.getResourceAsStream("/client.json")).build()), user); handler.apply(HttpResponse.builder().statusCode(200).message("ok")
.payload(ParseClientFromJsonTest.class.getResourceAsStream("/client.json")).build()), user);
} }
} }

View File

@ -38,29 +38,29 @@ import com.google.inject.Injector;
public class ParseCookbookDefinitionCheckingChefVersionTest { public class ParseCookbookDefinitionCheckingChefVersionTest {
public void testParserFor09() { public void testParserFor09() {
Injector injector = Guice.createInjector(new AbstractModule() { Injector injector = Guice.createInjector(new AbstractModule() {
@Override @Override
protected void configure() protected void configure() {
{ bind(String.class).annotatedWith(ApiVersion.class).toInstance("0.9.8");
bind(String.class).annotatedWith(ApiVersion.class).toInstance("0.9.8"); }
} }, new ChefParserModule(), new GsonModule());
}, new ChefParserModule(), new GsonModule());
ParseCookbookDefinitionCheckingChefVersion parser = injector
ParseCookbookDefinitionCheckingChefVersion parser = injector.getInstance(ParseCookbookDefinitionCheckingChefVersion.class); .getInstance(ParseCookbookDefinitionCheckingChefVersion.class);
assertTrue(parser.parser instanceof ParseKeySetFromJson); assertTrue(parser.parser instanceof ParseKeySetFromJson);
} }
public void testParserFor010() { public void testParserFor010() {
Injector injector = Guice.createInjector(new AbstractModule() { Injector injector = Guice.createInjector(new AbstractModule() {
@Override @Override
protected void configure() protected void configure() {
{ bind(String.class).annotatedWith(ApiVersion.class).toInstance("0.10.8");
bind(String.class).annotatedWith(ApiVersion.class).toInstance("0.10.8"); }
} }, new ChefParserModule(), new GsonModule());
}, new ChefParserModule(), new GsonModule());
ParseCookbookDefinitionCheckingChefVersion parser = injector
ParseCookbookDefinitionCheckingChefVersion parser = injector.getInstance(ParseCookbookDefinitionCheckingChefVersion.class); .getInstance(ParseCookbookDefinitionCheckingChefVersion.class);
assertTrue(parser.parser instanceof ParseCookbookDefinitionFromJson); assertTrue(parser.parser instanceof ParseCookbookDefinitionFromJson);
} }
} }

View File

@ -47,43 +47,30 @@ public class ParseCookbookDefinitionFromJsonTest {
@BeforeTest @BeforeTest
protected void setUpInjector() throws IOException { protected void setUpInjector() throws IOException {
Injector injector = Guice.createInjector(new AbstractModule() { Injector injector = Guice.createInjector(new AbstractModule() {
@Override @Override
protected void configure() protected void configure() {
{ bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefAsyncApi.VERSION);
bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefAsyncApi.VERSION); }
} }, new ChefParserModule(), new GsonModule());
}, new ChefParserModule(), new GsonModule());
handler = injector.getInstance(ParseCookbookDefinitionFromJson.class); handler = injector.getInstance(ParseCookbookDefinitionFromJson.class);
} }
public void testParse010Response() { public void testParse010Response() {
assertEquals( assertEquals(handler.apply(HttpResponse
handler .builder()
.apply(HttpResponse.builder() .statusCode(200)
.statusCode(200) .message("ok")
.message("ok") .payload(
.payload("{" + "{" + "\"apache2\" => {" + "\"url\" => \"http://localhost:4000/cookbooks/apache2\","
"\"apache2\" => {" + + "\"versions\" => [" + "{\"url\" => \"http://localhost:4000/cookbooks/apache2/5.1.0\","
"\"url\" => \"http://localhost:4000/cookbooks/apache2\"," + + "\"version\" => \"5.1.0\"},"
"\"versions\" => [" + + "{\"url\" => \"http://localhost:4000/cookbooks/apache2/4.2.0\","
"{\"url\" => \"http://localhost:4000/cookbooks/apache2/5.1.0\"," + + "\"version\" => \"4.2.0\"}" + "]" + "}," + "\"nginx\" => {"
"\"version\" => \"5.1.0\"}," + + "\"url\" => \"http://localhost:4000/cookbooks/nginx\"," + "\"versions\" => ["
"{\"url\" => \"http://localhost:4000/cookbooks/apache2/4.2.0\"," + + "{\"url\" => \"http://localhost:4000/cookbooks/nginx/1.0.0\"," + "\"version\" => \"1.0.0\"},"
"\"version\" => \"4.2.0\"}" + + "{\"url\" => \"http://localhost:4000/cookbooks/nginx/0.3.0\"," + "\"version\" => \"0.3.0\"}"
"]" + + "]" + "}" + "}").build()), ImmutableSet.of("apache2", "nginx"));
"}," +
"\"nginx\" => {" +
"\"url\" => \"http://localhost:4000/cookbooks/nginx\"," +
"\"versions\" => [" +
"{\"url\" => \"http://localhost:4000/cookbooks/nginx/1.0.0\"," +
"\"version\" => \"1.0.0\"}," +
"{\"url\" => \"http://localhost:4000/cookbooks/nginx/0.3.0\"," +
"\"version\" => \"0.3.0\"}" +
"]" +
"}" +
"}").build()),
ImmutableSet.of("apache2", "nginx"));
} }
} }

View File

@ -60,14 +60,13 @@ public class ParseCookbookVersionFromJsonTest {
@BeforeTest @BeforeTest
protected void setUpInjector() throws IOException { protected void setUpInjector() throws IOException {
injector = Guice.createInjector(new AbstractModule() { injector = Guice.createInjector(new AbstractModule() {
@Override @Override
protected void configure() protected void configure() {
{ bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefAsyncApi.VERSION);
bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefAsyncApi.VERSION); }
} }, new ChefParserModule(), new GsonModule());
}, new ChefParserModule(), new GsonModule());
json = injector.getInstance(Json.class); json = injector.getInstance(Json.class);
handler = injector.getInstance(Key.get(new TypeLiteral<ParseJson<CookbookVersion>>() { handler = injector.getInstance(Key.get(new TypeLiteral<ParseJson<CookbookVersion>>() {
})); }));
@ -75,88 +74,69 @@ public class ParseCookbookVersionFromJsonTest {
@Test(enabled = false) @Test(enabled = false)
public void testBrew() throws IOException { public void testBrew() throws IOException {
CookbookVersion cookbook = handler.apply(HttpResponse.builder() CookbookVersion cookbook = handler.apply(HttpResponse.builder().statusCode(200).message("ok")
.statusCode(200) .payload(ParseCookbookVersionFromJsonTest.class.getResourceAsStream("/brew-cookbook.json")).build());
.message("ok")
.payload(ParseCookbookVersionFromJsonTest.class.getResourceAsStream("/brew-cookbook.json")).build());
assertEquals(cookbook, handler.apply(HttpResponse.builder() assertEquals(cookbook,
.statusCode(200) handler.apply(HttpResponse.builder().statusCode(200).message("ok").payload(json.toJson(cookbook)).build()));
.message("ok")
.payload(json
.toJson(cookbook)).build()));
} }
@Test(enabled = false) @Test(enabled = false)
public void testTomcat() { public void testTomcat() {
CookbookVersion cookbook = handler.apply(HttpResponse.builder() CookbookVersion cookbook = handler.apply(HttpResponse.builder().statusCode(200).message("ok")
.statusCode(200) .payload(ParseCookbookVersionFromJsonTest.class.getResourceAsStream("/tomcat-cookbook.json")).build());
.message("ok")
.payload(ParseCookbookVersionFromJsonTest.class.getResourceAsStream("/tomcat-cookbook.json")).build());
assertEquals(cookbook, handler.apply(HttpResponse.builder() assertEquals(cookbook,
.statusCode(200) handler.apply(HttpResponse.builder().statusCode(200).message("ok").payload(json.toJson(cookbook)).build()));
.message("ok")
.payload(json
.toJson(cookbook)).build()));
} }
@Test(enabled = false) @Test(enabled = false)
public void testMysql() throws IOException { public void testMysql() throws IOException {
CookbookVersion cookbook = handler.apply(HttpResponse.builder() CookbookVersion cookbook = handler.apply(HttpResponse.builder().statusCode(200).message("ok")
.statusCode(200) .payload(ParseCookbookVersionFromJsonTest.class.getResourceAsStream("/mysql-cookbook.json")).build());
.message("ok")
.payload(ParseCookbookVersionFromJsonTest.class.getResourceAsStream("/mysql-cookbook.json")).build());
assertEquals(cookbook, handler.apply(HttpResponse.builder() assertEquals(cookbook,
.statusCode(200) handler.apply(HttpResponse.builder().statusCode(200).message("ok").payload(json.toJson(cookbook)).build()));
.message("ok")
.payload(json
.toJson(cookbook)).build()));
} }
@Test(enabled = false) @Test(enabled = false)
public void testApache() { public void testApache() {
assertEquals( assertEquals(
handler.apply(HttpResponse.builder() handler.apply(HttpResponse
.statusCode(200) .builder()
.message("ok") .statusCode(200)
.payload(ParseCookbookVersionFromJsonTest.class .message("ok")
.getResourceAsStream("/apache-chef-demo-cookbook.json")).build()), .payload(
new CookbookVersion( ParseCookbookVersionFromJsonTest.class.getResourceAsStream("/apache-chef-demo-cookbook.json"))
"apache-chef-demo-0.0.0", .build()),
ImmutableSet.<Resource> of(), new CookbookVersion(
ImmutableSet.<Attribute> of(), "apache-chef-demo-0.0.0",
ImmutableSet.<Resource> of(), ImmutableSet.<Resource> of(),
new Metadata("Apache v2.0", "Your Name", ImmutableMap.<String, String> of(), ImmutableMap ImmutableSet.<Attribute> of(),
.<String, String> of(), "youremail@example.com", ImmutableMap ImmutableSet.<Resource> of(),
.<String, String> of(), "A fabulous new cookbook", ImmutableMap new Metadata("Apache v2.0", "Your Name", ImmutableMap.<String, String> of(), ImmutableMap
.<String, String> of(), ImmutableMap.<String, String> of(), "0.0.0", .<String, String> of(), "youremail@example.com", ImmutableMap.<String, String> of(),
ImmutableMap.<String, String> of(), ImmutableMap.<String, String> of(), "A fabulous new cookbook", ImmutableMap.<String, String> of(), ImmutableMap
"apache-chef-demo", ImmutableMap.<String, String> of(), "", ImmutableMap .<String, String> of(), "0.0.0", ImmutableMap.<String, String> of(), ImmutableMap
.<String, Attribute> of(), ImmutableMap.<String, String> of()), .<String, String> of(), "apache-chef-demo", ImmutableMap.<String, String> of(), "",
ImmutableSet.<Resource> of(), ImmutableMap.<String, Attribute> of(), ImmutableMap.<String, String> of()),
"apache-chef-demo", ImmutableSet.<Resource> of(),
ImmutableSet.<Resource> of(), "apache-chef-demo",
ImmutableSet.<Resource> of(), ImmutableSet.<Resource> of(),
ImmutableSet.<Resource> of(), ImmutableSet.<Resource> of(),
"0.0.0", ImmutableSet.<Resource> of(),
ImmutableSet.<Resource> of(), "0.0.0",
ImmutableSet ImmutableSet.<Resource> of(),
.<Resource> of( ImmutableSet.<Resource> of(
new Resource( new Resource(
"README", "README",
URI URI.create("https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-11637f98942eafbf49c71b7f2f048b78?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277766181&Signature=zgpNl6wSxjTNovqZu2nJq0JztU8%3D"),
.create("https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-11637f98942eafbf49c71b7f2f048b78?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277766181&Signature=zgpNl6wSxjTNovqZu2nJq0JztU8%3D"), base16().lowerCase().decode("11637f98942eafbf49c71b7f2f048b78"), "README", "default"),
base16().lowerCase().decode("11637f98942eafbf49c71b7f2f048b78"), "README", new Resource(
"default"), "Rakefile",
new Resource( URI.create("https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-ebcf925a1651b4e04b9cd8aac2bc54eb?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277766181&Signature=EFzzDSKKytTl7b%2FxrCeNLh05zj4%3D"),
"Rakefile", base16().lowerCase().decode("ebcf925a1651b4e04b9cd8aac2bc54eb"), "Rakefile", "default"))));
URI
.create("https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-ebcf925a1651b4e04b9cd8aac2bc54eb?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277766181&Signature=EFzzDSKKytTl7b%2FxrCeNLh05zj4%3D"),
base16().lowerCase().decode("ebcf925a1651b4e04b9cd8aac2bc54eb"), "Rakefile",
"default"))));
} }
} }

View File

@ -38,29 +38,29 @@ import com.google.inject.Injector;
public class ParseCookbookVersionsCheckingChefVersionTest { public class ParseCookbookVersionsCheckingChefVersionTest {
public void testParserFor09() { public void testParserFor09() {
Injector injector = Guice.createInjector(new AbstractModule() { Injector injector = Guice.createInjector(new AbstractModule() {
@Override @Override
protected void configure() protected void configure() {
{ bind(String.class).annotatedWith(ApiVersion.class).toInstance("0.9.8");
bind(String.class).annotatedWith(ApiVersion.class).toInstance("0.9.8"); }
} }, new ChefParserModule(), new GsonModule());
}, new ChefParserModule(), new GsonModule());
ParseCookbookVersionsCheckingChefVersion parser = injector
ParseCookbookVersionsCheckingChefVersion parser = injector.getInstance(ParseCookbookVersionsCheckingChefVersion.class); .getInstance(ParseCookbookVersionsCheckingChefVersion.class);
assertTrue(parser.parser instanceof ParseCookbookVersionsV09FromJson); assertTrue(parser.parser instanceof ParseCookbookVersionsV09FromJson);
} }
public void testParserFor010() { public void testParserFor010() {
Injector injector = Guice.createInjector(new AbstractModule() { Injector injector = Guice.createInjector(new AbstractModule() {
@Override @Override
protected void configure() protected void configure() {
{ bind(String.class).annotatedWith(ApiVersion.class).toInstance("0.10.8");
bind(String.class).annotatedWith(ApiVersion.class).toInstance("0.10.8"); }
} }, new ChefParserModule(), new GsonModule());
}, new ChefParserModule(), new GsonModule());
ParseCookbookVersionsCheckingChefVersion parser = injector
ParseCookbookVersionsCheckingChefVersion parser = injector.getInstance(ParseCookbookVersionsCheckingChefVersion.class); .getInstance(ParseCookbookVersionsCheckingChefVersion.class);
assertTrue(parser.parser instanceof ParseCookbookVersionsV10FromJson); assertTrue(parser.parser instanceof ParseCookbookVersionsV10FromJson);
} }
} }

View File

@ -47,24 +47,19 @@ public class ParseCookbookVersionsV09FromJsonTest {
@BeforeTest @BeforeTest
protected void setUpInjector() throws IOException { protected void setUpInjector() throws IOException {
Injector injector = Guice.createInjector(new AbstractModule() { Injector injector = Guice.createInjector(new AbstractModule() {
@Override @Override
protected void configure() protected void configure() {
{ bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefAsyncApi.VERSION);
bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefAsyncApi.VERSION); }
} }, new ChefParserModule(), new GsonModule());
}, new ChefParserModule(), new GsonModule());
handler = injector.getInstance(ParseCookbookVersionsV09FromJson.class); handler = injector.getInstance(ParseCookbookVersionsV09FromJson.class);
} }
public void testRegex() { public void testRegex() {
assertEquals( assertEquals(
handler handler.apply(HttpResponse.builder().statusCode(200).message("ok")
.apply(HttpResponse.builder() .payload("{\"apache2\": [\"0.1.8\", \"0.2\"]}").build()), ImmutableSet.of("0.1.8", "0.2"));
.statusCode(200)
.message("ok")
.payload("{\"apache2\": [\"0.1.8\", \"0.2\"]}").build()),
ImmutableSet.of("0.1.8", "0.2"));
} }
} }

View File

@ -47,34 +47,26 @@ public class ParseCookbookVersionsV10FromJsonTest {
@BeforeTest @BeforeTest
protected void setUpInjector() throws IOException { protected void setUpInjector() throws IOException {
Injector injector = Guice.createInjector(new AbstractModule() { Injector injector = Guice.createInjector(new AbstractModule() {
@Override @Override
protected void configure() protected void configure() {
{ bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefAsyncApi.VERSION);
bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefAsyncApi.VERSION); }
} }, new ChefParserModule(), new GsonModule());
}, new ChefParserModule(), new GsonModule());
handler = injector.getInstance(ParseCookbookVersionsV10FromJson.class); handler = injector.getInstance(ParseCookbookVersionsV10FromJson.class);
} }
public void testRegex() { public void testRegex() {
assertEquals( assertEquals(handler.apply(HttpResponse
handler .builder()
.apply(HttpResponse.builder() .statusCode(200)
.statusCode(200) .message("ok")
.message("ok") .payload(
.payload("{" + "{" + "\"apache2\" => {" + "\"url\" => \"http://localhost:4000/cookbooks/apache2\","
"\"apache2\" => {" + + "\"versions\" => [" + "{\"url\" => \"http://localhost:4000/cookbooks/apache2/5.1.0\","
"\"url\" => \"http://localhost:4000/cookbooks/apache2\"," + + "\"version\" => \"5.1.0\"},"
"\"versions\" => [" + + "{\"url\" => \"http://localhost:4000/cookbooks/apache2/4.2.0\","
"{\"url\" => \"http://localhost:4000/cookbooks/apache2/5.1.0\"," + + "\"version\" => \"4.2.0\"}" + "]" + "}" + "}").build()), ImmutableSet.of("5.1.0", "4.2.0"));
"\"version\" => \"5.1.0\"}," +
"{\"url\" => \"http://localhost:4000/cookbooks/apache2/4.2.0\"," +
"\"version\" => \"4.2.0\"}" +
"]" +
"}" +
"}").build()),
ImmutableSet.of("5.1.0", "4.2.0"));
} }
} }

View File

@ -49,14 +49,13 @@ public class ParseDataBagItemFromJsonTest {
@BeforeTest @BeforeTest
protected void setUpInjector() throws IOException { protected void setUpInjector() throws IOException {
Injector injector = Guice.createInjector(new AbstractModule() { Injector injector = Guice.createInjector(new AbstractModule() {
@Override @Override
protected void configure() protected void configure() {
{ bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefAsyncApi.VERSION);
bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefAsyncApi.VERSION); }
} }, new ChefParserModule(), new GsonModule());
}, new ChefParserModule(), new GsonModule());
handler = injector.getInstance(Key.get(new TypeLiteral<ParseJson<DatabagItem>>() { handler = injector.getInstance(Key.get(new TypeLiteral<ParseJson<DatabagItem>>() {
})); }));
mapper = injector.getInstance(Json.class); mapper = injector.getInstance(Json.class);
@ -65,10 +64,7 @@ public class ParseDataBagItemFromJsonTest {
public void test1() { public void test1() {
String json = "{\"my_key\":\"my_data\",\"id\":\"item1\"}"; String json = "{\"my_key\":\"my_data\",\"id\":\"item1\"}";
DatabagItem item = new DatabagItem("item1", json); DatabagItem item = new DatabagItem("item1", json);
assertEquals(handler.apply(HttpResponse.builder() assertEquals(handler.apply(HttpResponse.builder().statusCode(200).message("ok").payload(json).build()), item);
.statusCode(200)
.message("ok")
.payload(json).build()), item);
assertEquals(mapper.toJson(item), json); assertEquals(mapper.toJson(item), json);
} }
} }

View File

@ -37,14 +37,10 @@ public class ParseErrorFromJsonOrReturnBodyTest {
@Test @Test
public void testApplyInputStreamDetails() throws UnknownHostException { public void testApplyInputStreamDetails() throws UnknownHostException {
InputStream is = Strings2 InputStream is = Strings2
.toInputStream("{\"error\":[\"invalid tarball: tarball root must contain java-bytearray\"]}"); .toInputStream("{\"error\":[\"invalid tarball: tarball root must contain java-bytearray\"]}");
ParseErrorFromJsonOrReturnBody parser = new ParseErrorFromJsonOrReturnBody( ParseErrorFromJsonOrReturnBody parser = new ParseErrorFromJsonOrReturnBody(new ReturnStringIf2xx());
new ReturnStringIf2xx()); String response = parser.apply(HttpResponse.builder().statusCode(200).message("ok").payload(is).build());
String response = parser.apply(HttpResponse.builder()
.statusCode(200)
.message("ok")
.payload(is).build());
assertEquals(response, "invalid tarball: tarball root must contain java-bytearray"); assertEquals(response, "invalid tarball: tarball root must contain java-bytearray");
} }

View File

@ -47,24 +47,24 @@ public class ParseKeySetFromJsonTest {
@BeforeTest @BeforeTest
protected void setUpInjector() throws IOException { protected void setUpInjector() throws IOException {
Injector injector = Guice.createInjector(new AbstractModule() { Injector injector = Guice.createInjector(new AbstractModule() {
@Override @Override
protected void configure() protected void configure() {
{ bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefAsyncApi.VERSION);
bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefAsyncApi.VERSION); }
} }, new ChefParserModule(), new GsonModule());
}, new ChefParserModule(), new GsonModule());
handler = injector.getInstance(ParseKeySetFromJson.class); handler = injector.getInstance(ParseKeySetFromJson.class);
} }
public void testRegex() { public void testRegex() {
assertEquals( assertEquals(
handler handler.apply(HttpResponse
.apply(HttpResponse.builder() .builder()
.statusCode(200) .statusCode(200)
.message("ok") .message("ok")
.payload("{\n\"opscode-validator\": \"https://api.opscode.com/...\", \"pimp-validator\": \"https://api.opscode.com/...\"}").build()), .payload(
ImmutableSet.of("opscode-validator", "pimp-validator")); "{\n\"opscode-validator\": \"https://api.opscode.com/...\", \"pimp-validator\": \"https://api.opscode.com/...\"}")
.build()), ImmutableSet.of("opscode-validator", "pimp-validator"));
} }
} }

View File

@ -53,14 +53,13 @@ public class ParseNodeFromJsonTest {
@BeforeTest @BeforeTest
protected void setUpInjector() throws IOException { protected void setUpInjector() throws IOException {
Injector injector = Guice.createInjector(new AbstractModule() { Injector injector = Guice.createInjector(new AbstractModule() {
@Override @Override
protected void configure() protected void configure() {
{ bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefAsyncApi.VERSION);
bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefAsyncApi.VERSION); }
} }, new ChefParserModule(), new GsonModule());
}, new ChefParserModule(), new GsonModule());
handler = injector.getInstance(Key.get(new TypeLiteral<ParseJson<Node>>() { handler = injector.getInstance(Key.get(new TypeLiteral<ParseJson<Node>>() {
})); }));
} }
@ -71,10 +70,8 @@ public class ParseNodeFromJsonTest {
"{\"ssl_port\":8433}")), ImmutableMap.<String, JsonBall> of(), ImmutableMap.<String, JsonBall> of(), "{\"ssl_port\":8433}")), ImmutableMap.<String, JsonBall> of(), ImmutableMap.<String, JsonBall> of(),
ImmutableMap.<String, JsonBall> of(), Collections.singleton("recipe[java]"), "prod"); ImmutableMap.<String, JsonBall> of(), Collections.singleton("recipe[java]"), "prod");
assertEquals(handler.apply(HttpResponse.builder() assertEquals(
.statusCode(200) handler.apply(HttpResponse.builder().statusCode(200).message("ok")
.message("ok") .payload(ParseCookbookVersionFromJsonTest.class.getResourceAsStream("/node.json")).build()), node);
.payload(ParseCookbookVersionFromJsonTest.class
.getResourceAsStream("/node.json")).build()), node);
} }
} }

View File

@ -53,26 +53,24 @@ public class ParseSandboxFromJsonTest {
@BeforeTest @BeforeTest
protected void setUpInjector() throws IOException { protected void setUpInjector() throws IOException {
Injector injector = Guice.createInjector(new AbstractModule() { Injector injector = Guice.createInjector(new AbstractModule() {
@Override @Override
protected void configure() protected void configure() {
{ bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefAsyncApi.VERSION);
bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefAsyncApi.VERSION); }
} }, new ChefParserModule(), new GsonModule());
}, new ChefParserModule(), new GsonModule());
handler = injector.getInstance(Key.get(new TypeLiteral<ParseJson<Sandbox>>() { handler = injector.getInstance(Key.get(new TypeLiteral<ParseJson<Sandbox>>() {
})); }));
dateService = injector.getInstance(DateService.class); dateService = injector.getInstance(DateService.class);
} }
public void test() { public void test() {
assertEquals(handler.apply(HttpResponse.builder() assertEquals(
.statusCode(200) handler.apply(HttpResponse.builder().statusCode(200).message("ok")
.message("ok") .payload(ParseSandboxFromJsonTest.class.getResourceAsStream("/sandbox.json")).build()),
.payload(ParseSandboxFromJsonTest.class new Sandbox("1-8c27b0ea4c2b7aaedbb44cfbdfcc11b2", false, dateService
.getResourceAsStream("/sandbox.json")).build()), new Sandbox("1-8c27b0ea4c2b7aaedbb44cfbdfcc11b2", false, .iso8601SecondsDateParse("2010-07-07T03:36:00+00:00"), ImmutableSet.<String> of(),
dateService.iso8601SecondsDateParse("2010-07-07T03:36:00+00:00"), ImmutableSet.<String> of(), "f9d6d9b72bae465890aae87969f98a9c", "f9d6d9b72bae465890aae87969f98a9c"));
"f9d6d9b72bae465890aae87969f98a9c", "f9d6d9b72bae465890aae87969f98a9c"));
} }
} }

View File

@ -45,25 +45,22 @@ public class ParseSearchDataBagItemFromJsonTest {
@BeforeTest @BeforeTest
protected void setUpInjector() throws IOException { protected void setUpInjector() throws IOException {
Injector injector = Guice.createInjector(new AbstractModule() { Injector injector = Guice.createInjector(new AbstractModule() {
@Override @Override
protected void configure() protected void configure() {
{ bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefAsyncApi.VERSION);
bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefAsyncApi.VERSION); }
} }, new ChefParserModule(), new GsonModule());
}, new ChefParserModule(), new GsonModule());
handler = injector.getInstance(ParseSearchDatabagFromJson.class); handler = injector.getInstance(ParseSearchDatabagFromJson.class);
} }
public void test1() { public void test1() {
String itemJson = "{\"my_key\":\"my_data\"}"; String itemJson = "{\"my_key\":\"my_data\"}";
String searchJson = "{\"rows\":[{\"raw_data\": {\"id\":\"item1\",\"my_key\":\"my_data\"}}]}"; String searchJson = "{\"rows\":[{\"raw_data\": {\"id\":\"item1\",\"my_key\":\"my_data\"}}]}";
DatabagItem item = new DatabagItem("item1", itemJson); DatabagItem item = new DatabagItem("item1", itemJson);
SearchResult<DatabagItem> result = handler.apply(HttpResponse.builder() SearchResult<DatabagItem> result = handler.apply(HttpResponse.builder().statusCode(200).message("ok")
.statusCode(200) .payload(searchJson).build());
.message("ok")
.payload(searchJson).build());
assertEquals(result.size(), 1); assertEquals(result.size(), 1);
assertEquals(result.iterator().next(), item); assertEquals(result.iterator().next(), item);
} }

View File

@ -58,34 +58,28 @@ public class ParseUploadSandboxFromJsonTest {
@BeforeTest @BeforeTest
protected void setUpInjector() throws IOException { protected void setUpInjector() throws IOException {
injector = Guice.createInjector(new AbstractModule() { injector = Guice.createInjector(new AbstractModule() {
@Override @Override
protected void configure() protected void configure() {
{ bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefAsyncApi.VERSION);
bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefAsyncApi.VERSION); }
} }, new ChefParserModule(), new GsonModule());
}, new ChefParserModule(), new GsonModule());
handler = injector.getInstance(Key.get(new TypeLiteral<ParseJson<UploadSandbox>>() { handler = injector.getInstance(Key.get(new TypeLiteral<ParseJson<UploadSandbox>>() {
})); }));
} }
public void test() { public void test() {
assertEquals( assertEquals(
handler.apply(HttpResponse.builder() handler.apply(HttpResponse.builder().statusCode(200).message("ok")
.statusCode(200) .payload(ParseUploadSandboxFromJsonTest.class.getResourceAsStream("/upload-site.json")).build()),
.message("ok") new UploadSandbox(
.payload(ParseUploadSandboxFromJsonTest.class URI.create("https://api.opscode.com/organizations/jclouds/sandboxes/d454f71e2a5f400c808d0c5d04c2c88c"),
.getResourceAsStream("/upload-site.json")).build()), ImmutableMap.<List<Byte>, ChecksumStatus> of(
new UploadSandbox( asList(base16().lowerCase().decode("0c5ecd7788cf4f6c7de2a57193897a6c")),
URI new ChecksumStatus(
.create("https://api.opscode.com/organizations/jclouds/sandboxes/d454f71e2a5f400c808d0c5d04c2c88c"), URI.create("https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/sandbox-d454f71e2a5f400c808d0c5d04c2c88c/checksum-0c5ecd7788cf4f6c7de2a57193897a6c?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277344702&Signature=FtKyqvYEjhhEKmRY%2B0M8aGPMM7g%3D"),
ImmutableMap true), asList(base16().lowerCase().decode("0189e76ccc476701d6b374e5a1a27347")),
.<List<Byte>, ChecksumStatus> of( new ChecksumStatus(), asList(base16().lowerCase().decode("1dda05ed139664f1f89b9dec482b77c0")),
asList(base16().lowerCase().decode("0c5ecd7788cf4f6c7de2a57193897a6c")), new ChecksumStatus()), "d454f71e2a5f400c808d0c5d04c2c88c"));
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), asList(base16().lowerCase().decode("0189e76ccc476701d6b374e5a1a27347")), new ChecksumStatus(),
asList(base16().lowerCase().decode("1dda05ed139664f1f89b9dec482b77c0")),
new ChecksumStatus()), "d454f71e2a5f400c808d0c5d04c2c88c"));
} }
} }

View File

@ -48,13 +48,12 @@ import com.google.inject.Injector;
@Test(groups = "unit", testName = "RunListForGroupTest") @Test(groups = "unit", testName = "RunListForGroupTest")
public class RunListForGroupTest { public class RunListForGroupTest {
Injector injector = Guice.createInjector(new AbstractModule() { Injector injector = Guice.createInjector(new AbstractModule() {
@Override @Override
protected void configure() protected void configure() {
{ bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefAsyncApi.VERSION);
bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefAsyncApi.VERSION); }
}
}, new ChefParserModule(), new GsonModule()); }, new ChefParserModule(), new GsonModule());
Json json = injector.getInstance(Json.class); Json json = injector.getInstance(Json.class);
@Test(expectedExceptions = IllegalStateException.class) @Test(expectedExceptions = IllegalStateException.class)
@ -83,7 +82,7 @@ public class RunListForGroupTest {
RunListForGroup fn = new RunListForGroup("jclouds", chefApi, json); RunListForGroup fn = new RunListForGroup("jclouds", chefApi, json);
expect(chefApi.getDatabagItem("jclouds", "foo")).andReturn( expect(chefApi.getDatabagItem("jclouds", "foo")).andReturn(
new DatabagItem("foo", "{\"run_list\":[\"recipe[apache2]\"]}")); new DatabagItem("foo", "{\"run_list\":[\"recipe[apache2]\"]}"));
replay(api); replay(api);
replay(chefApi); replay(chefApi);
@ -102,7 +101,7 @@ public class RunListForGroupTest {
RunListForGroup fn = new RunListForGroup("jclouds", chefApi, json); RunListForGroup fn = new RunListForGroup("jclouds", chefApi, json);
expect(chefApi.getDatabagItem("jclouds", "foo")).andReturn( expect(chefApi.getDatabagItem("jclouds", "foo")).andReturn(
new DatabagItem("foo", "{\"run_list\":[\"recipe[apache2]\",\"recipe[mysql]\"]}")); new DatabagItem("foo", "{\"run_list\":[\"recipe[apache2]\",\"recipe[mysql]\"]}"));
replay(api); replay(api);
replay(chefApi); replay(chefApi);

View File

@ -34,25 +34,25 @@ import com.google.common.base.Function;
*/ */
@Test(groups = { "unit" }) @Test(groups = { "unit" })
public class UriForResourceTest { public class UriForResourceTest {
@Test(expectedExceptions = NullPointerException.class) @Test(expectedExceptions = NullPointerException.class)
public void testWithNullInput() { public void testWithNullInput() {
Function<Object, URI> function = new UriForResource(); Function<Object, URI> function = new UriForResource();
function.apply(null); function.apply(null);
} }
@Test(expectedExceptions = IllegalArgumentException.class) @Test(expectedExceptions = IllegalArgumentException.class)
public void testWithInvalidInput() { public void testWithInvalidInput() {
Function<Object, URI> function = new UriForResource(); Function<Object, URI> function = new UriForResource();
function.apply(new Object()); function.apply(new Object());
} }
@Test @Test
public void testWithValidResource() { public void testWithValidResource() {
Function<Object, URI> function = new UriForResource(); Function<Object, URI> function = new UriForResource();
Resource res = new Resource("test", URI.create("http://foo/bar"), null, null, null); Resource res = new Resource("test", URI.create("http://foo/bar"), null, null, null);
URI result = function.apply(res); URI result = function.apply(res);
assertEquals(res.getUrl().toString(), result.toString()); assertEquals(res.getUrl().toString(), result.toString());
} }
} }

View File

@ -91,11 +91,15 @@ public class ChefApiErrorRetryHandlerTest {
BackoffLimitedRetryHandler retry = createMock(BackoffLimitedRetryHandler.class); BackoffLimitedRetryHandler retry = createMock(BackoffLimitedRetryHandler.class);
HttpRequest request = HttpRequest.builder().method("PUT") HttpRequest request = HttpRequest.builder().method("PUT")
.endpoint("https://api.opscode.com/organizations/jclouds/sandboxes/bfd68d4052f44053b2e593a33b5e1cd5").build(); .endpoint("https://api.opscode.com/organizations/jclouds/sandboxes/bfd68d4052f44053b2e593a33b5e1cd5")
HttpResponse response = HttpResponse.builder() .build();
.statusCode(400) HttpResponse response = HttpResponse
.message("400 Bad Request") .builder()
.payload("{\"error\":[\"Cannot update sandbox bfd68d4052f44053b2e593a33b5e1cd5: checksum 9b7c23369f4b576451216c39f214af6c was not uploaded\"]}").build(); .statusCode(400)
.message("400 Bad Request")
.payload(
"{\"error\":[\"Cannot update sandbox bfd68d4052f44053b2e593a33b5e1cd5: checksum 9b7c23369f4b576451216c39f214af6c was not uploaded\"]}")
.build();
expect(command.getFailureCount()).andReturn(0); expect(command.getFailureCount()).andReturn(0);
expect(command.getCurrentRequest()).andReturn(request).atLeastOnce(); expect(command.getCurrentRequest()).andReturn(request).atLeastOnce();

View File

@ -354,22 +354,21 @@ public abstract class BaseChefApiLiveTest<C extends Context> extends BaseChefCon
@Test(dependsOnMethods = { "testListSearchIndexes", "testCreateNode" }) @Test(dependsOnMethods = { "testListSearchIndexes", "testCreateNode" })
public void testSearchNodesWithOptions() throws Exception { public void testSearchNodesWithOptions() throws Exception {
Predicate<SearchOptions> waitForIndex = retry( Predicate<SearchOptions> waitForIndex = retry(new Predicate<SearchOptions>() {
new Predicate<SearchOptions>() { @Override
@Override public boolean apply(SearchOptions input) {
public boolean apply(SearchOptions input) { SearchResult<? extends Node> results = chefApi.searchNodes(input);
SearchResult<? extends Node> results = chefApi.searchNodes(input); assertNotNull(results);
assertNotNull(results); if (results.size() > 0) {
if (results.size() > 0) { assertEquals(results.size(), 1);
assertEquals(results.size(), 1); assertEquals(results.iterator().next().getName(), PREFIX);
assertEquals(results.iterator().next().getName(), PREFIX); return true;
return true; } else {
} else { // The index may still not be populated
// The index may still not be populated return false;
return false; }
} }
} }, maxWaitForIndexInMs, 5000L, MILLISECONDS);
}, maxWaitForIndexInMs, 5000L, MILLISECONDS);
SearchOptions options = SearchOptions.Builder.query("name:" + PREFIX); SearchOptions options = SearchOptions.Builder.query("name:" + PREFIX);
assertTrue(waitForIndex.apply(options)); assertTrue(waitForIndex.apply(options));
@ -383,22 +382,21 @@ public abstract class BaseChefApiLiveTest<C extends Context> extends BaseChefCon
@Test(dependsOnMethods = { "testListSearchIndexes", "testCreateClient" }) @Test(dependsOnMethods = { "testListSearchIndexes", "testCreateClient" })
public void testSearchClientsWithOptions() throws Exception { public void testSearchClientsWithOptions() throws Exception {
Predicate<SearchOptions> waitForIndex = retry( Predicate<SearchOptions> waitForIndex = retry(new Predicate<SearchOptions>() {
new Predicate<SearchOptions>() { @Override
@Override public boolean apply(SearchOptions input) {
public boolean apply(SearchOptions input) { SearchResult<? extends Client> results = chefApi.searchClients(input);
SearchResult<? extends Client> results = chefApi.searchClients(input); assertNotNull(results);
assertNotNull(results); if (results.size() > 0) {
if (results.size() > 0) { assertEquals(results.size(), 1);
assertEquals(results.size(), 1); assertEquals(results.iterator().next().getName(), PREFIX);
assertEquals(results.iterator().next().getName(), PREFIX); return true;
return true; } else {
} else { // The index may still not be populated
// The index may still not be populated return false;
return false; }
} }
} }, maxWaitForIndexInMs, 5000L, MILLISECONDS);
}, maxWaitForIndexInMs, 5000L, MILLISECONDS);
SearchOptions options = SearchOptions.Builder.query("name:" + PREFIX); SearchOptions options = SearchOptions.Builder.query("name:" + PREFIX);
assertTrue(waitForIndex.apply(options)); assertTrue(waitForIndex.apply(options));
@ -412,22 +410,21 @@ public abstract class BaseChefApiLiveTest<C extends Context> extends BaseChefCon
@Test(dependsOnMethods = { "testListSearchIndexes", "testCreateRole" }) @Test(dependsOnMethods = { "testListSearchIndexes", "testCreateRole" })
public void testSearchRolesWithOptions() throws Exception { public void testSearchRolesWithOptions() throws Exception {
Predicate<SearchOptions> waitForIndex = retry( Predicate<SearchOptions> waitForIndex = retry(new Predicate<SearchOptions>() {
new Predicate<SearchOptions>() { @Override
@Override public boolean apply(SearchOptions input) {
public boolean apply(SearchOptions input) { SearchResult<? extends Role> results = chefApi.searchRoles(input);
SearchResult<? extends Role> results = chefApi.searchRoles(input); assertNotNull(results);
assertNotNull(results); if (results.size() > 0) {
if (results.size() > 0) { assertEquals(results.size(), 1);
assertEquals(results.size(), 1); assertEquals(results.iterator().next().getName(), PREFIX);
assertEquals(results.iterator().next().getName(), PREFIX); return true;
return true; } else {
} else { // The index may still not be populated
// The index may still not be populated return false;
return false; }
} }
} }, maxWaitForIndexInMs, 5000L, MILLISECONDS);
}, maxWaitForIndexInMs, 5000L, MILLISECONDS);
SearchOptions options = SearchOptions.Builder.query("name:" + PREFIX); SearchOptions options = SearchOptions.Builder.query("name:" + PREFIX);
assertTrue(waitForIndex.apply(options)); assertTrue(waitForIndex.apply(options));
@ -441,22 +438,21 @@ public abstract class BaseChefApiLiveTest<C extends Context> extends BaseChefCon
@Test(dependsOnMethods = { "testListSearchIndexes", "testDatabagItemExists" }) @Test(dependsOnMethods = { "testListSearchIndexes", "testDatabagItemExists" })
public void testSearchDatabagWithOptions() throws Exception { public void testSearchDatabagWithOptions() throws Exception {
Predicate<SearchOptions> waitForIndex = retry( Predicate<SearchOptions> waitForIndex = retry(new Predicate<SearchOptions>() {
new Predicate<SearchOptions>() { @Override
@Override public boolean apply(SearchOptions input) {
public boolean apply(SearchOptions input) { SearchResult<? extends DatabagItem> results = chefApi.searchDatabag(PREFIX, input);
SearchResult<? extends DatabagItem> results = chefApi.searchDatabag(PREFIX, input); assertNotNull(results);
assertNotNull(results); if (results.size() > 0) {
if (results.size() > 0) { assertEquals(results.size(), 1);
assertEquals(results.size(), 1); assertEquals(results.iterator().next().getId(), databagItem.getId());
assertEquals(results.iterator().next().getId(), databagItem.getId()); return true;
return true; } else {
} else { // The index may still not be populated
// The index may still not be populated return false;
return false; }
} }
} }, maxWaitForIndexInMs, 5000L, MILLISECONDS);
}, maxWaitForIndexInMs, 5000L, MILLISECONDS);
SearchOptions options = SearchOptions.Builder.query("id:" + databagItem.getId()); SearchOptions options = SearchOptions.Builder.query("id:" + databagItem.getId());
assertTrue(waitForIndex.apply(options)); assertTrue(waitForIndex.apply(options));

View File

@ -41,34 +41,34 @@ public abstract class BaseChefContextLiveTest<C extends Context> extends BaseCon
public BaseChefContextLiveTest() { public BaseChefContextLiveTest() {
provider = "chef"; provider = "chef";
} }
protected abstract ChefApi getChefApi(C context); protected abstract ChefApi getChefApi(C context);
/** /**
* the credential is a path to the pem file. * the credential is a path to the pem file.
*/ */
@Override @Override
protected Properties setupProperties() { protected Properties setupProperties() {
Properties overrides = super.setupProperties(); Properties overrides = super.setupProperties();
credential = setCredentialFromPemFile(overrides, identity, provider + ".credential"); credential = setCredentialFromPemFile(overrides, identity, provider + ".credential");
return overrides; return overrides;
} }
protected String setCredentialFromPemFile(Properties overrides, String identity, String key) { protected String setCredentialFromPemFile(Properties overrides, String identity, String key) {
String val = null; String val = null;
String credentialFromFile = null; String credentialFromFile = null;
if (System.getProperties().containsKey("test." + key)) { if (System.getProperties().containsKey("test." + key)) {
val = System.getProperty("test." + key); val = System.getProperty("test." + key);
} else { } else {
val = System.getProperty("user.home") + "/.chef/" + identity + ".pem"; val = System.getProperty("user.home") + "/.chef/" + identity + ".pem";
} }
try { try {
credentialFromFile = Files.toString(new File(val), Charsets.UTF_8); credentialFromFile = Files.toString(new File(val), Charsets.UTF_8);
} catch (IOException e) { } catch (IOException e) {
throw Throwables.propagate(e); throw Throwables.propagate(e);
} }
overrides.setProperty(key, credentialFromFile); overrides.setProperty(key, credentialFromFile);
return credentialFromFile; return credentialFromFile;
} }
} }

View File

@ -48,7 +48,7 @@ import com.google.inject.Module;
@Test(groups = "live") @Test(groups = "live")
@Deprecated @Deprecated
public class BaseStubbedOhaiLiveTest extends BaseChefContextLiveTest<ChefContext> { public class BaseStubbedOhaiLiveTest extends BaseChefContextLiveTest<ChefContext> {
@ConfiguresOhai @ConfiguresOhai
static class TestOhaiModule extends OhaiModule { static class TestOhaiModule extends OhaiModule {
@ -60,19 +60,20 @@ public class BaseStubbedOhaiLiveTest extends BaseChefContextLiveTest<ChefContext
@Override @Override
protected ApiMetadata createApiMetadata() { protected ApiMetadata createApiMetadata() {
return new ChefApiMetadata().toBuilder().defaultModules( return new ChefApiMetadata()
ImmutableSet.<Class<? extends Module>> of(ChefRestClientModule.class, ChefParserModule.class, TestOhaiModule.class)).build(); .toBuilder()
.defaultModules(
ImmutableSet.<Class<? extends Module>> of(ChefRestClientModule.class, ChefParserModule.class,
TestOhaiModule.class)).build();
} }
@Override @Override
protected ChefApi getChefApi(ChefContext context) protected ChefApi getChefApi(ChefContext context) {
{ return context.getApi();
return context.getApi(); }
}
@Override
@Override protected TypeToken<ChefContext> contextType() {
protected TypeToken<ChefContext> contextType() return typeToken(ChefContext.class);
{ }
return typeToken(ChefContext.class);
}
} }

View File

@ -18,7 +18,6 @@
*/ */
package org.jclouds.chef.strategy.internal; package org.jclouds.chef.strategy.internal;
import static org.jclouds.reflect.Reflection2.typeToken; import static org.jclouds.reflect.Reflection2.typeToken;
import org.jclouds.chef.ChefApi; import org.jclouds.chef.ChefApi;
@ -40,7 +39,7 @@ public class CleanupStaleNodesAndClientsImplLiveTest extends BaseChefContextLive
private CreateNodeAndPopulateAutomaticAttributesImpl creater; private CreateNodeAndPopulateAutomaticAttributesImpl creater;
private CleanupStaleNodesAndClientsImpl strategy; private CleanupStaleNodesAndClientsImpl strategy;
@BeforeClass(groups = { "integration", "live" }) @BeforeClass(groups = { "integration", "live" })
@Override @Override
public void setupContext() { public void setupContext() {
@ -65,17 +64,15 @@ public class CleanupStaleNodesAndClientsImplLiveTest extends BaseChefContextLive
context.getApi().deleteNode(prefix); context.getApi().deleteNode(prefix);
} }
} }
@Override @Override
protected ChefApi getChefApi(ChefContext context) protected ChefApi getChefApi(ChefContext context) {
{ return context.getApi();
return context.getApi();
} }
@Override @Override
protected TypeToken<ChefContext> contextType() protected TypeToken<ChefContext> contextType() {
{ return typeToken(ChefContext.class);
return typeToken(ChefContext.class);
} }
} }

View File

@ -35,28 +35,29 @@ import com.google.common.collect.ImmutableSet;
import com.google.common.reflect.TypeToken; import com.google.common.reflect.TypeToken;
/** /**
* Tests behavior of {@code CreateNodeAndPopulateAutomaticAttributesImpl} strategies * Tests behavior of {@code CreateNodeAndPopulateAutomaticAttributesImpl}
* strategies
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
@Test(groups = "live", testName = "CreateNodeAndPopulateAutomaticAttributesImplLiveTest") @Test(groups = "live", testName = "CreateNodeAndPopulateAutomaticAttributesImplLiveTest")
public class CreateNodeAndPopulateAutomaticAttributesImplLiveTest extends BaseChefContextLiveTest<ChefContext> { public class CreateNodeAndPopulateAutomaticAttributesImplLiveTest extends BaseChefContextLiveTest<ChefContext> {
private CurrentUserProvider currentUserProvider; private CurrentUserProvider currentUserProvider;
@BeforeClass(groups = { "integration", "live" }) @BeforeClass(groups = { "integration", "live" })
@Override @Override
public void setupContext() { public void setupContext() {
super.setupContext(); super.setupContext();
this.currentUserProvider = context.utils().injector().getInstance(CurrentUserProvider.class); this.currentUserProvider = context.utils().injector().getInstance(CurrentUserProvider.class);
} }
@Test @Test
public void testExecute() { public void testExecute() {
Set<String> runList = ImmutableSet.of("role[" + prefix + "]"); Set<String> runList = ImmutableSet.of("role[" + prefix + "]");
try { try {
context.utils().injector().getInstance(CreateNodeAndPopulateAutomaticAttributesImpl.class).execute(prefix, context.utils().injector().getInstance(CreateNodeAndPopulateAutomaticAttributesImpl.class)
runList); .execute(prefix, runList);
Node node = context.getApi().getNode(prefix); Node node = context.getApi().getNode(prefix);
assertEquals(node.getName(), prefix); assertEquals(node.getName(), prefix);
assertEquals(node.getRunList(), runList); assertEquals(node.getRunList(), runList);
@ -65,17 +66,15 @@ public class CreateNodeAndPopulateAutomaticAttributesImplLiveTest extends BaseCh
context.getApi().deleteNode(prefix); context.getApi().deleteNode(prefix);
} }
} }
@Override @Override
protected ChefApi getChefApi(ChefContext context) protected ChefApi getChefApi(ChefContext context) {
{ return context.getApi();
return context.getApi();
} }
@Override @Override
protected TypeToken<ChefContext> contextType() protected TypeToken<ChefContext> contextType() {
{ return typeToken(ChefContext.class);
return typeToken(ChefContext.class);
} }
} }

View File

@ -52,16 +52,17 @@ public class CreateNodeAndPopulateAutomaticAttributesImplTest {
Supplier<Map<String, JsonBall>> automaticSupplier = Suppliers.<Map<String, JsonBall>> ofInstance(automatic); Supplier<Map<String, JsonBall>> automaticSupplier = Suppliers.<Map<String, JsonBall>> ofInstance(automatic);
Node nodeWithAutomatic = new Node("name", ImmutableMap.<String, JsonBall> of(), ImmutableMap Node nodeWithAutomatic = new Node("name", ImmutableMap.<String, JsonBall> of(),
.<String, JsonBall> of(), ImmutableMap.<String, JsonBall> of(), automatic, ImmutableSet.<String> of(), ImmutableMap.<String, JsonBall> of(), ImmutableMap.<String, JsonBall> of(), automatic,
"_default"); ImmutableSet.<String> of(), "_default");
node.getAutomatic().putAll(automaticSupplier.get()); node.getAutomatic().putAll(automaticSupplier.get());
chef.createNode(nodeWithAutomatic); chef.createNode(nodeWithAutomatic);
replay(chef); replay(chef);
CreateNodeAndPopulateAutomaticAttributesImpl updater = new CreateNodeAndPopulateAutomaticAttributesImpl(chef, automaticSupplier); CreateNodeAndPopulateAutomaticAttributesImpl updater = new CreateNodeAndPopulateAutomaticAttributesImpl(chef,
automaticSupplier);
updater.execute("name", ImmutableSet.<String> of()); updater.execute("name", ImmutableSet.<String> of());
verify(chef); verify(chef);

View File

@ -18,7 +18,6 @@
*/ */
package org.jclouds.chef.strategy.internal; package org.jclouds.chef.strategy.internal;
import static org.jclouds.reflect.Reflection2.typeToken; import static org.jclouds.reflect.Reflection2.typeToken;
import org.jclouds.chef.ChefApi; import org.jclouds.chef.ChefApi;
@ -70,16 +69,14 @@ public class DeleteAllApisAndNodesInListImplLiveTest extends BaseChefContextLive
chef.deleteNode(prefix + 1); chef.deleteNode(prefix + 1);
} }
} }
@Override @Override
protected ChefApi getChefApi(ChefContext context) protected ChefApi getChefApi(ChefContext context) {
{ return context.getApi();
return context.getApi();
} }
@Override @Override
protected TypeToken<ChefContext> contextType() protected TypeToken<ChefContext> contextType() {
{ return typeToken(ChefContext.class);
return typeToken(ChefContext.class);
} }
} }

View File

@ -40,7 +40,7 @@ import com.google.common.reflect.TypeToken;
*/ */
@Test(groups = "live", testName = "GetNodesImplLiveTest") @Test(groups = "live", testName = "GetNodesImplLiveTest")
public class GetNodesImplLiveTest extends BaseChefContextLiveTest<ChefContext> { public class GetNodesImplLiveTest extends BaseChefContextLiveTest<ChefContext> {
private ListNodesImpl strategy; private ListNodesImpl strategy;
private CreateNodeAndPopulateAutomaticAttributesImpl creater; private CreateNodeAndPopulateAutomaticAttributesImpl creater;
private ChefApi chef; private ChefApi chef;
@ -85,17 +85,15 @@ public class GetNodesImplLiveTest extends BaseChefContextLiveTest<ChefContext> {
public void testExecuteIterableOfString() { public void testExecuteIterableOfString() {
assertEquals(size(strategy.execute(ImmutableSet.of(prefix, prefix + 1))), 2); assertEquals(size(strategy.execute(ImmutableSet.of(prefix, prefix + 1))), 2);
} }
@Override @Override
protected ChefApi getChefApi(ChefContext context) protected ChefApi getChefApi(ChefContext context) {
{ return context.getApi();
return context.getApi();
} }
@Override @Override
protected TypeToken<ChefContext> contextType() protected TypeToken<ChefContext> contextType() {
{ return typeToken(ChefContext.class);
return typeToken(ChefContext.class);
} }
} }

View File

@ -42,14 +42,15 @@ import com.google.common.reflect.TypeToken;
@Test(groups = "live", testName = "UpdateAutomaticAttributesOnNodeImplLiveTest") @Test(groups = "live", testName = "UpdateAutomaticAttributesOnNodeImplLiveTest")
public class UpdateAutomaticAttributesOnNodeImplLiveTest extends BaseChefContextLiveTest<ChefContext> { public class UpdateAutomaticAttributesOnNodeImplLiveTest extends BaseChefContextLiveTest<ChefContext> {
private CurrentUserProvider currentUserProvider; private CurrentUserProvider currentUserProvider;
@BeforeClass(groups = { "integration", "live" }) @BeforeClass(groups = { "integration", "live" })
@Override @Override
public void setupContext() { public void setupContext() {
super.setupContext(); super.setupContext();
this.currentUserProvider = context.utils().injector().getInstance(CurrentUserProvider.class); this.currentUserProvider = context.utils().injector().getInstance(CurrentUserProvider.class);
} }
@Test @Test
public void testExecute() { public void testExecute() {
Set<String> runList = ImmutableSet.of("role[" + prefix + "]"); Set<String> runList = ImmutableSet.of("role[" + prefix + "]");
@ -64,16 +65,14 @@ public class UpdateAutomaticAttributesOnNodeImplLiveTest extends BaseChefContext
context.getApi().deleteNode(prefix); context.getApi().deleteNode(prefix);
} }
} }
@Override @Override
protected ChefApi getChefApi(ChefContext context) protected ChefApi getChefApi(ChefContext context) {
{ return context.getApi();
return context.getApi();
} }
@Override @Override
protected TypeToken<ChefContext> contextType() protected TypeToken<ChefContext> contextType() {
{ return typeToken(ChefContext.class);
return typeToken(ChefContext.class);
} }
} }

View File

@ -53,9 +53,9 @@ public class UpdateAutomaticAttributesOnNodeImplTest {
Supplier<Map<String, JsonBall>> automaticSupplier = Suppliers.<Map<String, JsonBall>> ofInstance(automatic); Supplier<Map<String, JsonBall>> automaticSupplier = Suppliers.<Map<String, JsonBall>> ofInstance(automatic);
Node nodeWithAutomatic = new Node("name", ImmutableMap.<String, JsonBall> of(), ImmutableMap Node nodeWithAutomatic = new Node("name", ImmutableMap.<String, JsonBall> of(),
.<String, JsonBall> of(), ImmutableMap.<String, JsonBall> of(), automatic, ImmutableSet.<String> of(), ImmutableMap.<String, JsonBall> of(), ImmutableMap.<String, JsonBall> of(), automatic,
"_default"); ImmutableSet.<String> of(), "_default");
expect(chef.getNode("name")).andReturn(node); expect(chef.getNode("name")).andReturn(node);
node.getAutomatic().putAll(automaticSupplier.get()); node.getAutomatic().putAll(automaticSupplier.get());

View File

@ -35,39 +35,41 @@ public class RunListBuilderTest {
public void testRecipeAndRole() { public void testRecipeAndRole() {
RunListBuilder options = new RunListBuilder(); RunListBuilder options = new RunListBuilder();
options.addRecipe("recipe").addRole("role"); options.addRecipe("recipe").addRole("role");
assertEquals(options.build(),ImmutableList.of("recipe[recipe]","role[role]")); assertEquals(options.build(), ImmutableList.of("recipe[recipe]", "role[role]"));
} }
@Test @Test
public void testRecipe() { public void testRecipe() {
RunListBuilder options = new RunListBuilder(); RunListBuilder options = new RunListBuilder();
options.addRecipe("test"); options.addRecipe("test");
assertEquals(options.build(),ImmutableList.of("recipe[test]")); assertEquals(options.build(), ImmutableList.of("recipe[test]"));
} }
@Test @Test
public void testRecipes() { public void testRecipes() {
RunListBuilder options = new RunListBuilder(); RunListBuilder options = new RunListBuilder();
options.addRecipes("test", "test2"); options.addRecipes("test", "test2");
assertEquals(options.build(),ImmutableList.of("recipe[test]","recipe[test2]")); assertEquals(options.build(), ImmutableList.of("recipe[test]", "recipe[test2]"));
} }
@Test @Test
public void testRole() { public void testRole() {
RunListBuilder options = new RunListBuilder(); RunListBuilder options = new RunListBuilder();
options.addRole("test"); options.addRole("test");
assertEquals(options.build(),ImmutableList.of("role[test]")); assertEquals(options.build(), ImmutableList.of("role[test]"));
} }
@Test @Test
public void testRoles() { public void testRoles() {
RunListBuilder options = new RunListBuilder(); RunListBuilder options = new RunListBuilder();
options.addRoles("test", "test2"); options.addRoles("test", "test2");
assertEquals(options.build(),ImmutableList.of("role[test]","role[test2]")); assertEquals(options.build(), ImmutableList.of("role[test]", "role[test2]"));
} }
@Test @Test
public void testNoneRecipe() { public void testNoneRecipe() {
RunListBuilder options = new RunListBuilder(); RunListBuilder options = new RunListBuilder();
assertEquals(options.build(), ImmutableList.<String>of()); assertEquals(options.build(), ImmutableList.<String> of());
} }
} }

View File

@ -61,12 +61,11 @@ public class JMXTest {
replay(runtime); replay(runtime);
Injector injector = Guice.createInjector(new AbstractModule() { Injector injector = Guice.createInjector(new AbstractModule() {
@Override @Override
protected void configure() protected void configure() {
{ bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefAsyncApi.VERSION);
bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefAsyncApi.VERSION); }
} }, new ChefParserModule(), new GsonModule(), new JMXOhaiModule() {
}, new ChefParserModule(), new GsonModule(), new JMXOhaiModule() {
@Override @Override
protected RuntimeMXBean provideRuntimeMXBean() { protected RuntimeMXBean provideRuntimeMXBean() {
return runtime; return runtime;

View File

@ -63,12 +63,11 @@ public class OhaiModuleTest {
sysProperties.setProperty("user.name", "user"); sysProperties.setProperty("user.name", "user");
Injector injector = Guice.createInjector(new AbstractModule() { Injector injector = Guice.createInjector(new AbstractModule() {
@Override @Override
protected void configure() protected void configure() {
{ bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefAsyncApi.VERSION);
bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefAsyncApi.VERSION); }
} }, new ChefParserModule(), new GsonModule(), new OhaiModule() {
}, new ChefParserModule(), new GsonModule(), new OhaiModule() {
@Override @Override
protected Long millis() { protected Long millis() {
return 127999291932529l; return 127999291932529l;
@ -98,12 +97,11 @@ public class OhaiModuleTest {
sysProperties.setProperty("user.name", "user"); sysProperties.setProperty("user.name", "user");
Injector injector = Guice.createInjector(new AbstractModule() { Injector injector = Guice.createInjector(new AbstractModule() {
@Override @Override
protected void configure() protected void configure() {
{ bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefAsyncApi.VERSION);
bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefAsyncApi.VERSION); }
} }, new ChefParserModule(), new GsonModule(), new OhaiModule() {
}, new ChefParserModule(), new GsonModule(), new OhaiModule() {
@Override @Override
protected Long millis() { protected Long millis() {
return 1279992919l; return 1279992919l;

View File

@ -32,7 +32,6 @@ import org.testng.annotations.Test;
public class ByteArrayToMacAddressTest { public class ByteArrayToMacAddressTest {
public void test() { public void test() {
assertEquals(new ByteArrayToMacAddress().apply(base16().lowerCase().decode("0026bb09e6c4")), assertEquals(new ByteArrayToMacAddress().apply(base16().lowerCase().decode("0026bb09e6c4")), "00:26:bb:09:e6:c4");
"00:26:bb:09:e6:c4");
} }
} }

View File

@ -52,11 +52,10 @@ public class NestSlashKeysTest {
@BeforeTest @BeforeTest
protected void setUpInjector() throws IOException { protected void setUpInjector() throws IOException {
Injector injector = Guice.createInjector(new AbstractModule() { Injector injector = Guice.createInjector(new AbstractModule() {
@Override @Override
protected void configure() protected void configure() {
{ bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefAsyncApi.VERSION);
bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefAsyncApi.VERSION); }
}
}, new ChefParserModule(), new GsonModule()); }, new ChefParserModule(), new GsonModule());
converter = injector.getInstance(NestSlashKeys.class); converter = injector.getInstance(NestSlashKeys.class);
json = injector.getInstance(Json.class); json = injector.getInstance(Json.class);
@ -64,47 +63,59 @@ public class NestSlashKeysTest {
@Test @Test
public void testBase() { public void testBase() {
assertEquals(json.toJson(converter.apply(ImmutableMultimap.<String, Supplier<JsonBall>> of("java", Suppliers assertEquals(
.ofInstance(new JsonBall("java"))))), "{\"java\":\"java\"}"); json.toJson(converter.apply(ImmutableMultimap.<String, Supplier<JsonBall>> of("java",
Suppliers.ofInstance(new JsonBall("java"))))), "{\"java\":\"java\"}");
} }
@Test(expectedExceptions = IllegalArgumentException.class) @Test(expectedExceptions = IllegalArgumentException.class)
public void testIllegal() { public void testIllegal() {
json.toJson(converter.apply(ImmutableMultimap.<String, Supplier<JsonBall>> of("java", Suppliers json.toJson(converter.apply(ImmutableMultimap.<String, Supplier<JsonBall>> of("java",
.ofInstance(new JsonBall("java")), "java/system", Suppliers.ofInstance(new JsonBall("system"))))); Suppliers.ofInstance(new JsonBall("java")), "java/system", Suppliers.ofInstance(new JsonBall("system")))));
} }
@Test @Test
public void testOne() { public void testOne() {
assertEquals(json.toJson(converter.apply(ImmutableMultimap.<String, Supplier<JsonBall>> of("java", Suppliers assertEquals(
.ofInstance(new JsonBall("{\"time\":\"time\"}")), "java/system", Suppliers json.toJson(converter.apply(ImmutableMultimap.<String, Supplier<JsonBall>> of("java",
.ofInstance(new JsonBall("system"))))), "{\"java\":{\"time\":\"time\",\"system\":\"system\"}}"); Suppliers.ofInstance(new JsonBall("{\"time\":\"time\"}")), "java/system",
Suppliers.ofInstance(new JsonBall("system"))))),
"{\"java\":{\"time\":\"time\",\"system\":\"system\"}}");
} }
@Test @Test
public void testOneDuplicate() { public void testOneDuplicate() {
assertEquals(json.toJson(converter.apply(ImmutableMultimap.<String, Supplier<JsonBall>> of("java", Suppliers assertEquals(
.ofInstance(new JsonBall("{\"time\":\"time\"}")), "java", Suppliers.ofInstance(new JsonBall( json.toJson(converter.apply(ImmutableMultimap.<String, Supplier<JsonBall>> of("java",
"{\"system\":\"system\"}"))))), "{\"java\":{\"time\":\"time\",\"system\":\"system\"}}"); Suppliers.ofInstance(new JsonBall("{\"time\":\"time\"}")), "java",
Suppliers.ofInstance(new JsonBall("{\"system\":\"system\"}"))))),
"{\"java\":{\"time\":\"time\",\"system\":\"system\"}}");
} }
@Test @Test
public void testMerge() { public void testMerge() {
assertEquals(json.toJson(converter.apply(ImmutableMultimap.<String, Supplier<JsonBall>> of("java", Suppliers assertEquals(
.ofInstance(new JsonBall("{\"time\":{\"1\":\"hello\"}}")), "java/time", Suppliers.ofInstance(new JsonBall( json.toJson(converter.apply(ImmutableMultimap.<String, Supplier<JsonBall>> of("java",
"{\"2\":\"goodbye\"}"))))), "{\"java\":{\"time\":{\"1\":\"hello\",\"2\":\"goodbye\"}}}"); Suppliers.ofInstance(new JsonBall("{\"time\":{\"1\":\"hello\"}}")), "java/time",
Suppliers.ofInstance(new JsonBall("{\"2\":\"goodbye\"}"))))),
"{\"java\":{\"time\":{\"1\":\"hello\",\"2\":\"goodbye\"}}}");
} }
@Test @Test
public void testMergeNestedTwice() { public void testMergeNestedTwice() {
assertEquals(json.toJson(converter.apply(ImmutableMultimap.<String, Supplier<JsonBall>> of("java", Suppliers assertEquals(
.ofInstance(new JsonBall("{\"time\":{\"1\":\"hello\"}}")), "java", Suppliers.ofInstance(new JsonBall( json.toJson(converter.apply(ImmutableMultimap.<String, Supplier<JsonBall>> of("java",
"{\"time\":{\"2\":\"goodbye\"}}"))))), "{\"java\":{\"time\":{\"1\":\"hello\",\"2\":\"goodbye\"}}}"); Suppliers.ofInstance(new JsonBall("{\"time\":{\"1\":\"hello\"}}")), "java",
Suppliers.ofInstance(new JsonBall("{\"time\":{\"2\":\"goodbye\"}}"))))),
"{\"java\":{\"time\":{\"1\":\"hello\",\"2\":\"goodbye\"}}}");
} }
@Test @Test
public void testReplaceList() { public void testReplaceList() {
assertEquals(json.toJson(converter.apply(ImmutableMultimap.<String, Supplier<JsonBall>> of("java", Suppliers assertEquals(
.ofInstance(new JsonBall("{\"time\":{\"1\":[\"hello\"]}}")), "java/time", Suppliers.ofInstance(new JsonBall( json.toJson(converter.apply(ImmutableMultimap.<String, Supplier<JsonBall>> of("java",
"{\"1\":[\"goodbye\"]}"))))), "{\"java\":{\"time\":{\"1\":[\"goodbye\"]}}}"); Suppliers.ofInstance(new JsonBall("{\"time\":{\"1\":[\"hello\"]}}")), "java/time",
Suppliers.ofInstance(new JsonBall("{\"1\":[\"goodbye\"]}"))))),
"{\"java\":{\"time\":{\"1\":[\"goodbye\"]}}}");
} }
} }