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.
*
* @param md5s
* raw md5s; uses {@code Bytes.asList()} and {@code
* Bytes.toByteArray()} as necessary
* raw md5s; uses {@code Bytes.asList()} and
* {@code Bytes.toByteArray()} as necessary
* @return The URLs against which to PUT files that need to be uploaded.
*/
UploadSandbox getUploadSandboxForChecksums(Set<List<Byte>> md5s);
/**
*
* Uploads the given content to the sandbox at the given URI.
* <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);
@ -157,7 +158,7 @@ public interface ChefApi {
/**
* creates a new administrator client
*
*
* @return the private key of the client. You can then use this client name
* and private key to access the Opscode API.
* @throws AuthorizationException
@ -492,8 +493,7 @@ public interface ChefApi {
/**
* Show indexes you can search on
* <p/>
* By default, the "role", "node" and "api" indexes will always be
* available.
* By default, the "role", "node" and "api" indexes will always be available.
* <p/>
* 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
@ -519,7 +519,7 @@ public interface ChefApi {
* and the rows themselves.
*/
SearchResult<? extends Role> searchRoles();
/**
* search all roles that match the given options.
*
@ -540,7 +540,7 @@ public interface ChefApi {
* and the rows themselves.
*/
SearchResult<? extends Client> searchClients();
/**
* search all clients that match the given options.
*
@ -561,7 +561,7 @@ public interface ChefApi {
* and the rows themselves.
*/
SearchResult<? extends Node> searchNodes();
/**
* search all nodes that match the given options.
*
@ -582,7 +582,7 @@ public interface ChefApi {
* and the rows themselves.
*/
SearchResult<? extends DatabagItem> searchDatabag(String databagName);
/**
* 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.
* @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);
}

View File

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

View File

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

View File

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

View File

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

View File

@ -41,7 +41,7 @@ import org.jclouds.rest.binders.BindToStringPayload;
public class BindChecksumsToJsonPayload extends BindToStringPayload {
@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!");
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 {
@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));
request.getPayload().getContentMetadata().setContentType(MediaType.APPLICATION_JSON);
return request;

View File

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

View File

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

View File

@ -33,7 +33,7 @@ import org.jclouds.rest.binders.BindToStringPayload;
public class BindIsCompletedToJsonPayload extends BindToStringPayload {
@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));
request.getPayload().getContentMetadata().setContentType(MediaType.APPLICATION_JSON);
return request;

View File

@ -33,7 +33,7 @@ import org.jclouds.rest.binders.BindToStringPayload;
public class BindNameToJsonPayload extends BindToStringPayload {
@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));
request.getPayload().getContentMetadata().setContentType(MediaType.APPLICATION_JSON);
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,
Map<Class<?>, Class<?>> delegates) {
Map<Class<?>, Class<?>> delegates) {
super(syncApiType, asyncApiType, delegates);
}
@ -102,7 +102,7 @@ public class BaseChefRestClientModule<S, A> extends RestClientModule<S, A> {
}, seconds, TimeUnit.SECONDS);
}
// TODO: potentially change this
// TODO: potentially change this
@Provides
@Singleton
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
* so that the private key is only recalculated once.
* it is relatively expensive to extract a private key from a PEM. cache the
* relationship between current credentials so that the private key is only
* recalculated once.
*/
@VisibleForTesting
@Singleton
@ -146,35 +147,37 @@ public class BaseChefRestClientModule<S, A> extends RestClientModule<S, A> {
}
}
}
@Provides
@Singleton
@Validator
public Optional<String> provideValidatorName(Injector injector) {
// Named properties can not be injected as optional here, so let's use the injector to bypass it
Key<String> key = Key.get(String.class, Names.named(CHEF_VALIDATOR_NAME));
try {
return Optional.<String> of(injector.getInstance(key));
} catch (ConfigurationException ex) {
return Optional.<String> absent();
}
// Named properties can not be injected as optional here, so let's use the
// injector to bypass it
Key<String> key = Key.get(String.class, Names.named(CHEF_VALIDATOR_NAME));
try {
return Optional.<String> of(injector.getInstance(key));
} catch (ConfigurationException ex) {
return Optional.<String> absent();
}
}
@Provides
@Singleton
@Validator
public Optional<PrivateKey> provideValidatorCredential(Crypto crypto, Injector injector)
throws InvalidKeySpecException, IOException {
// Named properties can not be injected as optional here, so let's use the injector to bypass it
Key<String> key = Key.get(String.class, Names.named(CHEF_VALIDATOR_CREDENTIAL));
try {
String validatorCredential = injector.getInstance(key);
PrivateKey validatorKey = crypto.rsaKeyFactory().generatePrivate(
Pems.privateKeySpec(InputSuppliers.of(validatorCredential)));
return Optional.<PrivateKey> of(validatorKey);
} catch (ConfigurationException ex) {
return Optional.<PrivateKey> absent();
}
throws InvalidKeySpecException, IOException {
// Named properties can not be injected as optional here, so let's use the
// injector to bypass it
Key<String> key = Key.get(String.class, Names.named(CHEF_VALIDATOR_CREDENTIAL));
try {
String validatorCredential = injector.getInstance(key);
PrivateKey validatorKey = crypto.rsaKeyFactory().generatePrivate(
Pems.privateKeySpec(InputSuppliers.of(validatorCredential)));
return Optional.<PrivateKey> of(validatorKey);
} catch (ConfigurationException ex) {
return Optional.<PrivateKey> absent();
}
}
@Override

View File

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

View File

@ -27,42 +27,40 @@ import org.jclouds.chef.ChefService;
*/
public interface ChefProperties {
/**
* The name of the Chef logger.
*/
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";
/**
* The name of the Chef logger.
*/
public static final String CHEF_LOGGER = "jclouds.chef";
/**
* Ddatabag that holds chef bootstrap hints, should be a json ball in the
* following format:
* <p>
* {"tag":{"run_list":["recipe[apache2]"]}}
*/
public static final String CHEF_BOOTSTRAP_DATABAG = "chef.bootstrap-databag";
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";
/**
* The name 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_NAME = "chef.validator-name";
/**
* Ddatabag that holds chef bootstrap hints, should be a json ball in the
* following format:
* <p>
* {"tag":{"run_list":["recipe[apache2]"]}}
*/
public static final String CHEF_BOOTSTRAP_DATABAG = "chef.bootstrap-databag";
/**
* 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";
/**
* The name 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_NAME = "chef.validator-name";
/**
* 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.
* <p>
* Chef Server version 0.9 and 0.10 return a different Json when rquesting the cookbook
* definitions. This annotation can be used to setup the cookbook parser.
* Chef Server version 0.9 and 0.10 return a different Json when rquesting the
* cookbook definitions. This annotation can be used to setup the cookbook
* parser.
*
* @author Ignasi Barrera
*/
@Target({METHOD, PARAMETER, FIELD})
@Target({ METHOD, PARAMETER, FIELD })
@Retention(RUNTIME)
@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.
* <p>
* Chef Server version 0.9 and 0.10 return a different Json when rquesting the cookbook
* versions. This annotation can be used to setup the cookbook versions parser.
* Chef Server version 0.9 and 0.10 return a different Json when rquesting the
* cookbook versions. This annotation can be used to setup the cookbook versions
* parser.
*
* @author Ignasi Barrera
*/
@Target({METHOD, PARAMETER, FIELD})
@Target({ METHOD, PARAMETER, FIELD })
@Retention(RUNTIME)
@Qualifier
public @interface CookbookVersionsParser
{
public @interface CookbookVersionsParser {
}

View File

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

View File

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

View File

@ -29,129 +29,120 @@ import com.google.common.collect.Sets;
* @author Ignasi Barrera
*/
public class CookbookDefinition {
private URI url;
private Set<Version> versions = Sets.newLinkedHashSet();
// only for deserialization
CookbookDefinition() {
}
public CookbookDefinition(URI url, Set<Version> versions) {
this.url = url;
this.versions = versions;
}
public URI getUrl() {
return url;
}
private URI url;
private Set<Version> versions = Sets.newLinkedHashSet();
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;
}
// only for deserialization
CookbookDefinition() {
@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;
if (obj == null)
if (obj == null)
return false;
if (getClass() != obj.getClass())
if (getClass() != obj.getClass())
return false;
CookbookDefinition other = (CookbookDefinition) obj;
if (url == null)
{
Version other = (Version) obj;
if (url == null) {
if (other.url != null)
return false;
}
else if (!url.equals(other.url))
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))
if (version == null) {
if (other.version != null)
return false;
} else if (!version.equals(other.version))
return false;
return true;
}
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;
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 + "]";
}
}
@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,
Metadata metadata, Set<Resource> providers, String cookbookName, Set<Resource> resources,
Set<Resource> templates, Set<Resource> libraries, String version, Set<Resource> recipes,
Set<Resource> rootFiles) {
Metadata metadata, Set<Resource> providers, String cookbookName, Set<Resource> resources,
Set<Resource> templates, Set<Resource> libraries, String version, Set<Resource> recipes,
Set<Resource> rootFiles) {
this.name = name;
Iterables.addAll(this.definitions, definitions);
Iterables.addAll(this.attributes, attributes);
@ -237,9 +237,9 @@ public class CookbookVersion {
@Override
public String toString() {
return "Cookbook [attributes=" + attributes + ", cookbookName=" + cookbookName + ", definitions=" + definitions
+ ", files=" + files + ", libraries=" + libraries + ", metadata=" + metadata + ", name=" + name
+ ", providers=" + providers + ", recipes=" + recipes + ", resources=" + resources + ", rootFiles="
+ rootFiles + ", templates=" + templates + ", version=" + version + "]";
+ ", files=" + files + ", libraries=" + libraries + ", metadata=" + metadata + ", name=" + name
+ ", providers=" + providers + ", recipes=" + recipes + ", resources=" + resources + ", rootFiles="
+ rootFiles + ", templates=" + templates + ", version=" + version + "]";
}
}

View File

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

View File

@ -57,8 +57,8 @@ public class Node {
private String _jsonClass = "Chef::Node";
public Node(String name, Map<String, JsonBall> normal, Map<String, JsonBall> override,
Map<String, JsonBall> defaultA, Map<String, JsonBall> automatic, Iterable<String> runList) {
this(name, normal, override, defaultA, automatic, runList, null);
Map<String, JsonBall> defaultA, Map<String, JsonBall> automatic, Iterable<String> runList) {
this(name, normal, override, defaultA, automatic, runList, null);
}
/**
@ -83,7 +83,7 @@ public class Node {
}
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) {
this(payload.getRawContent().getName(), null, payload.getContentMetadata().getContentMD5(), payload
.getRawContent().getPath(), "default");
.getRawContent().getPath(), "default");
}
public Resource(String name, byte[] checksum, String path) {
@ -127,8 +127,8 @@ public class Resource {
@Override
public String toString() {
return "Resource [checksum=" + Bytes.asList(checksum) + ", name=" + name + ", path=" + path
+ ", specificity=" + specificity + ", url=" + url + "]";
return "Resource [checksum=" + Bytes.asList(checksum) + ", name=" + name + ", path=" + path + ", specificity="
+ specificity + ", url=" + url + "]";
}
}

View File

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

View File

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

View File

@ -48,6 +48,6 @@ public class ParseCookbookDefinitionCheckingChefVersion implements Function<Http
@Override
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;
/**
* 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
*/
@ -48,6 +49,6 @@ public class ParseCookbookDefinitionFromJson implements Function<HttpResponse, S
@Override
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
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.
*
* @author Ignasi Barrera
*/
@Singleton

View File

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

View File

@ -37,45 +37,45 @@ import com.google.gson.annotations.SerializedName;
/**
* Parses the search result into a {@link DatabagItem} object.
* <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
*/
@Singleton
public class ParseSearchDatabagFromJson implements Function<HttpResponse, SearchResult<DatabagItem>> {
private final ParseJson<Response> responseParser;
private final Json json;
private final ParseJson<Response> responseParser;
static class Row {
@SerializedName("raw_data")
JsonBall rawData;
}
private final Json json;
static class Response {
long start;
List<Row> rows;
}
static class Row {
@SerializedName("raw_data")
JsonBall rawData;
}
@Inject
ParseSearchDatabagFromJson(ParseJson<Response> responseParser, Json json) {
this.responseParser = responseParser;
this.json = json;
}
static class Response {
long start;
List<Row> rows;
}
@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);
}
});
@Inject
ParseSearchDatabagFromJson(ParseJson<Response> responseParser, Json json) {
this.responseParser = responseParser;
this.json = json;
}
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
public class UriForResource implements Function<Object, URI> {
@Override
public URI apply(Object input) {
checkArgument(checkNotNull(input, "input") instanceof Resource,
@Override
public URI apply(Object input) {
checkArgument(checkNotNull(input, "input") instanceof Resource,
"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
protected BaseChefService(ChefContext chefContext, CleanupStaleNodesAndClients cleanupStaleNodesAndClients,
CreateNodeAndPopulateAutomaticAttributes createNodeAndPopulateAutomaticAttributes,
DeleteAllNodesInList deleteAllNodesInList, ListNodes listNodes,
DeleteAllClientsInList deleteAllClientsInList, ListClients listClients,
ListCookbookVersions listCookbookVersions, UpdateAutomaticAttributesOnNode updateAutomaticAttributesOnNode,
Supplier<PrivateKey> privateKey, @Named(CHEF_BOOTSTRAP_DATABAG) String databag,
GroupToBootScript groupToBootScript, RunListForGroup runListForGroup) {
CreateNodeAndPopulateAutomaticAttributes createNodeAndPopulateAutomaticAttributes,
DeleteAllNodesInList deleteAllNodesInList, ListNodes listNodes, DeleteAllClientsInList deleteAllClientsInList,
ListClients listClients, ListCookbookVersions listCookbookVersions,
UpdateAutomaticAttributesOnNode updateAutomaticAttributesOnNode, Supplier<PrivateKey> privateKey,
@Named(CHEF_BOOTSTRAP_DATABAG) String databag, GroupToBootScript groupToBootScript,
RunListForGroup runListForGroup) {
this.chefContext = checkNotNull(chefContext, "chefContext");
this.cleanupStaleNodesAndClients = checkNotNull(cleanupStaleNodesAndClients, "cleanupStaleNodesAndClients");
this.createNodeAndPopulateAutomaticAttributes = checkNotNull(createNodeAndPopulateAutomaticAttributes,
"createNodeAndPopulateAutomaticAttributes");
"createNodeAndPopulateAutomaticAttributes");
this.deleteAllNodesInList = checkNotNull(deleteAllNodesInList, "deleteAllNodesInList");
this.listNodes = checkNotNull(listNodes, "listNodes");
this.deleteAllClientsInList = checkNotNull(deleteAllClientsInList, "deleteAllClientsInList");
this.listClients = checkNotNull(listClients, "listClients");
this.listCookbookVersions = checkNotNull(listCookbookVersions, "listCookbookVersions");
this.updateAutomaticAttributesOnNode = checkNotNull(updateAutomaticAttributesOnNode,
"updateAutomaticAttributesOnNode");
"updateAutomaticAttributesOnNode");
this.privateKey = checkNotNull(privateKey, "privateKey");
this.groupToBootScript = checkNotNull(groupToBootScript, "groupToBootScript");
this.databag = checkNotNull(databag, "databag");
@ -176,7 +176,6 @@ public class BaseChefService implements ChefService {
return listCookbookVersions.execute(names);
}
@Override
public void updateAutomaticAttributesOnNode(String nodeName) {
updateAutomaticAttributesOnNode.execute(nodeName);
@ -199,15 +198,17 @@ public class BaseChefService implements ChefService {
} catch (IllegalStateException e) {
}
DatabagItem runlist = new DatabagItem(group, chefContext.utils().json().toJson(
ImmutableMap.<String, List<String>> of("run_list", Lists.newArrayList(runList)),
RunListForGroup.RUN_LIST_TYPE));
DatabagItem runlist = new DatabagItem(group, chefContext
.utils()
.json()
.toJson(ImmutableMap.<String, List<String>> of("run_list", Lists.newArrayList(runList)),
RunListForGroup.RUN_LIST_TYPE));
if (chefContext.getApi().getDatabagItem(databag, group) == null) {
chefContext.getApi().createDatabagItem(databag, runlist);
chefContext.getApi().createDatabagItem(databag, runlist);
} else {
chefContext.getApi().updateDatabagItem(databag, runlist);
chefContext.getApi().updateDatabagItem(databag, runlist);
}
}
@ -219,13 +220,13 @@ public class BaseChefService implements ChefService {
@Override
public byte[] decrypt(InputSupplier<? extends InputStream> supplier) throws IOException {
return ByteStreams.toByteArray(new RSADecryptingPayload(Payloads.newPayload(supplier.getInput()), privateKey
.get()));
.get()));
}
@Override
public byte[] encrypt(InputSupplier<? extends InputStream> supplier) throws IOException {
return ByteStreams.toByteArray(new RSAEncryptingPayload(Payloads.newPayload(supplier.getInput()), privateKey
.get()));
.get()));
}
}

View File

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

View File

@ -29,71 +29,71 @@ import org.jclouds.http.options.BaseHttpRequestOptions;
*/
public class SearchOptions extends BaseHttpRequestOptions {
/**
* A valid search string.
*/
public SearchOptions query(String query) {
this.queryParameters.put("q", checkNotNull(query, "query"));
return this;
}
/**
* A valid search string.
*/
public SearchOptions query(String query) {
this.queryParameters.put("q", checkNotNull(query, "query"));
return this;
}
/**
* A sort string, such as 'name DESC'.
*/
public SearchOptions sort(String sort) {
this.queryParameters.put("sort", checkNotNull(sort, "sort"));
return this;
}
/**
* A sort string, such as 'name DESC'.
*/
public SearchOptions sort(String sort) {
this.queryParameters.put("sort", checkNotNull(sort, "sort"));
return this;
}
/**
* The number of rows to return.
*/
public SearchOptions rows(int rows) {
this.queryParameters.put("rows", String.valueOf(rows));
return this;
}
/**
* The number of rows to return.
*/
public SearchOptions rows(int rows) {
this.queryParameters.put("rows", String.valueOf(rows));
return this;
}
/**
* The result number to start from.
*/
public SearchOptions start(int start) {
this.queryParameters.put("start", String.valueOf(start));
return this;
}
/**
* The result number to start from.
*/
public SearchOptions start(int start) {
this.queryParameters.put("start", String.valueOf(start));
return this;
}
public static class Builder {
public static class Builder {
/**
* @see SearchOptions#query(String)
*/
public static SearchOptions query(String query) {
SearchOptions options = new SearchOptions();
return options.query(query);
}
/**
* @see SearchOptions#query(String)
*/
public static SearchOptions query(String query) {
SearchOptions options = new SearchOptions();
return options.query(query);
}
/**
* @see SearchOptions#sort(String)
*/
public static SearchOptions start(String start) {
SearchOptions options = new SearchOptions();
return options.sort(start);
}
/**
* @see SearchOptions#sort(String)
*/
public static SearchOptions start(String start) {
SearchOptions options = new SearchOptions();
return options.sort(start);
}
/**
* @see SearchOptions#rows(int)
*/
public static SearchOptions rows(int rows) {
SearchOptions options = new SearchOptions();
return options.rows(rows);
}
/**
* @see SearchOptions#rows(int)
*/
public static SearchOptions rows(int rows) {
SearchOptions options = new SearchOptions();
return options.rows(rows);
}
/**
* @see SearchOptions#start(int)
*/
public static SearchOptions start(int start) {
SearchOptions options = new SearchOptions();
return options.start(start);
}
}
/**
* @see SearchOptions#start(int)
*/
public static SearchOptions start(int start) {
SearchOptions options = new SearchOptions();
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
* the name of the cookbook. ex. {@code apache2} will be the default recipe where {@code
* apache2::mod_proxy} is a specific one in the cookbook.
* Note that the default recipe of a cookbook is its name. Otherwise, you
* prefix the recipe with the name of the cookbook. ex. {@code apache2} will
* be the default recipe where {@code apache2::mod_proxy} is a specific one
* in the cookbook.
*
* @param recipes
* names of the recipes.
@ -70,21 +71,21 @@ public class CookbookVersionPredicates {
@Override
public boolean apply(final CookbookVersion cookbookVersion) {
return search.containsKey(cookbookVersion.getCookbookName())
&& any(search.get(cookbookVersion.getCookbookName()), new Predicate<String>() {
&& any(search.get(cookbookVersion.getCookbookName()), new Predicate<String>() {
@Override
public boolean apply(final String recipeName) {
return any(cookbookVersion.getRecipes(), new Predicate<Resource>() {
@Override
public boolean apply(final String recipeName) {
return any(cookbookVersion.getRecipes(), new Predicate<Resource>() {
@Override
public boolean apply(Resource resource) {
return resource.getName().equals(recipeName);
}
@Override
public boolean apply(Resource resource) {
return resource.getName().equals(recipeName);
}
});
}
});
}
});
});
}
@Override

View File

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

View File

@ -60,8 +60,8 @@ public class DeleteAllClientsInListImpl implements DeleteAllClientsInList {
protected Long maxTime;
@Inject
DeleteAllClientsInListImpl(@Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor, ChefApi getAllApi,
ChefAsyncApi ablobstore) {
DeleteAllClientsInListImpl(@Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor,
ChefApi getAllApi, ChefAsyncApi ablobstore) {
this.userExecutor = userExecutor;
this.chefAsyncApi = ablobstore;
this.chefApi = getAllApi;
@ -75,7 +75,8 @@ public class DeleteAllClientsInListImpl implements DeleteAllClientsInList {
responses.put(name, chefAsyncApi.deleteClient(name));
}
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) {
propagate(e);
}

View File

@ -60,8 +60,8 @@ public class DeleteAllNodesInListImpl implements DeleteAllNodesInList {
protected Long maxTime;
@Inject
DeleteAllNodesInListImpl(@Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor, ChefApi getAllNode,
ChefAsyncApi ablobstore) {
DeleteAllNodesInListImpl(@Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor,
ChefApi getAllNode, ChefAsyncApi ablobstore) {
this.userExecutor = userExecutor;
this.chefAsyncApi = ablobstore;
this.chefApi = getAllNode;
@ -75,7 +75,8 @@ public class DeleteAllNodesInListImpl implements DeleteAllNodesInList {
responses.put(name, chefAsyncApi.deleteNode(name));
}
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) {
propagate(e);
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -38,11 +38,11 @@ import com.google.common.collect.Multimap;
*/
@Singleton
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;
@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.nester = checkNotNull(nester, "nester");
}

View File

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

View File

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

View File

@ -17,52 +17,50 @@
* under the License.
*/
package org.jclouds.ohai.config.multibindings;
import java.lang.annotation.Annotation;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author jessewilson@google.com (Jesse Wilson)
*/
class RealElement implements Element {
private static final AtomicInteger nextUniqueId = new AtomicInteger(1);
private static final AtomicInteger nextUniqueId = new AtomicInteger(1);
private final int uniqueId;
private final String setName;
private final int uniqueId;
private final String setName;
RealElement(String setName) {
uniqueId = nextUniqueId.getAndIncrement();
this.setName = setName;
}
RealElement(String setName) {
uniqueId = nextUniqueId.getAndIncrement();
this.setName = setName;
}
public String setName() {
return setName;
}
public String setName() {
return setName;
}
public int uniqueId() {
return uniqueId;
}
public int uniqueId() {
return uniqueId;
}
public Class<? extends Annotation> annotationType() {
return Element.class;
}
public Class<? extends Annotation> annotationType() {
return Element.class;
}
@Override public String toString() {
return "@" + Element.class.getName() + "(setName=" + setName
+ ",uniqueId=" + uniqueId + ")";
}
@Override
public String toString() {
return "@" + Element.class.getName() + "(setName=" + setName + ",uniqueId=" + uniqueId + ")";
}
@Override public boolean equals(Object o) {
return o instanceof Element
&& ((Element) o).setName().equals(setName())
&& ((Element) o).uniqueId() == uniqueId();
}
@Override
public boolean equals(Object o) {
return o instanceof Element && ((Element) o).setName().equals(setName())
&& ((Element) o).uniqueId() == uniqueId();
}
@Override public int hashCode() {
return 127 * ("setName".hashCode() ^ setName.hashCode())
+ 127 * ("uniqueId".hashCode() ^ uniqueId);
}
@Override
public int hashCode() {
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" })
public class ChefApiLiveTest extends BaseChefApiLiveTest<ChefContext> {
@Test
public void testListCookbookVersionsWithChefService() throws Exception {
Iterable<? extends CookbookVersion> cookbooks = context.getChefService().listCookbookVersions();
assertNotNull(cookbooks);
}
@Test
public void testListCookbookVersionsWithChefService() throws Exception {
Iterable<? extends CookbookVersion> cookbooks = context.getChefService().listCookbookVersions();
assertNotNull(cookbooks);
}
@Override
protected ChefApi getChefApi(ChefContext context)
{
return context.getApi();
}
@Override
protected ChefApi getChefApi(ChefContext context) {
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.io.Payload;
import org.jclouds.io.payloads.StringPayload;
import org.jclouds.reflect.Invocation;
import org.jclouds.rest.ConfiguresRestClient;
import org.jclouds.rest.internal.BaseAsyncApiTest;
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.reflect.Invokable;
import com.google.inject.Module;
/**
* Tests annotation parsing of {@code ChefAsyncApi}
*
@ -81,11 +83,12 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testCommitSandbox() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "commitSandbox", String.class, boolean.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method,
ImmutableList.<Object> of("0189e76ccc476701d6b374e5a1a27347", true));
GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,
ImmutableList.<Object> of("0189e76ccc476701d6b374e5a1a27347", true)));
assertRequestLineEquals(httpRequest,
"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);
assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
@ -98,17 +101,16 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testGetUploadSandboxForChecksums() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "getUploadSandboxForChecksums", Set.class);
GeneratedHttpRequest httpRequest = processor.createRequest(
method, ImmutableList.<Object> of(
ImmutableSet.of(asList(base16().lowerCase().decode("0189e76ccc476701d6b374e5a1a27347")),
asList(base16().lowerCase().decode("0c5ecd7788cf4f6c7de2a57193897a6c")),
asList(base16().lowerCase().decode("1dda05ed139664f1f89b9dec482b77c0")))));
GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method, ImmutableList
.<Object> of(ImmutableSet.of(asList(base16().lowerCase().decode("0189e76ccc476701d6b374e5a1a27347")),
asList(base16().lowerCase().decode("0c5ecd7788cf4f6c7de2a57193897a6c")), asList(base16().lowerCase()
.decode("1dda05ed139664f1f89b9dec482b77c0"))))));
assertRequestLineEquals(httpRequest, "POST http://localhost:4000/sandboxes HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n");
assertPayloadEquals(
httpRequest,
"{\"checksums\":{\"0189e76ccc476701d6b374e5a1a27347\":null,\"0c5ecd7788cf4f6c7de2a57193897a6c\":null,\"1dda05ed139664f1f89b9dec482b77c0\":null}}",
"application/json", false);
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
+ "-test\n");
assertPayloadEquals(httpRequest,
"{\"checksums\":{\"0189e76ccc476701d6b374e5a1a27347\":null,\"0c5ecd7788cf4f6c7de2a57193897a6c\":null,"
+ "\"1dda05ed139664f1f89b9dec482b77c0\":null}}", "application/json", false);
assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
assertSaxResponseParserClassEquals(method, null);
@ -116,28 +118,31 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
checkFilters(httpRequest);
}
public void testUploadContent() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "uploadContent", URI.class, Payload.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(URI.create("http://foo/bar"),
new StringPayload("{\"foo\": \"bar\"}")));
assertRequestLineEquals(httpRequest, "PUT http://foo/bar HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n");
assertPayloadEquals(httpRequest, "{\"foo\": \"bar\"}", "application/x-binary", false);
Invokable<?, ?> method = method(ChefAsyncApi.class, "uploadContent", URI.class, Payload.class);
GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,
ImmutableList.<Object> of(URI.create("http://foo/bar"), new StringPayload("{\"foo\": \"bar\"}"))));
assertRequestLineEquals(httpRequest, "PUT http://foo/bar HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
+ "-test\n");
assertPayloadEquals(httpRequest, "{\"foo\": \"bar\"}", "application/x-binary", false);
assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, null);
assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, null);
checkFilters(httpRequest);
checkFilters(httpRequest);
}
}
public void testGetCookbook() throws SecurityException, NoSuchMethodException, IOException {
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");
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);
assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
@ -150,9 +155,11 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testDeleteCookbook() throws SecurityException, NoSuchMethodException, IOException {
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");
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);
assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
@ -166,15 +173,21 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testUpdateCookbook() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "updateCookbook", String.class, String.class,
CookbookVersion.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of("cookbook", "1.0.1",
new CookbookVersion("cookbook", "1.0.1")));
GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,
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");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n");
assertPayloadEquals(
httpRequest,
"{\"name\":\"cookbook-1.0.1\",\"definitions\":[],\"attributes\":[],\"files\":[],\"metadata\":{\"suggestions\":{},\"dependencies\":{},\"conflicting\":{},\"providing\":{},\"platforms\":{},\"recipes\":{},\"replacing\":{},\"groupings\":{},\"attributes\":{},\"recommendations\":{}},\"providers\":[],\"cookbook_name\":\"cookbook\",\"resources\":[],\"templates\":[],\"libraries\":[],\"version\":\"1.0.1\",\"recipes\":[],\"root_files\":[],\"json_class\":\"Chef::CookbookVersion\",\"chef_type\":\"cookbook_version\"}",
"application/json", false);
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
+ "-test\n");
assertPayloadEquals(httpRequest,
"{\"name\":\"cookbook-1.0.1\",\"definitions\":[],\"attributes\":[],\"files\":[],"
+ "\"metadata\":{\"suggestions\":{},\"dependencies\":{},\"conflicting\":{},\"providing\":{},"
+ "\"platforms\":{},\"recipes\":{},\"replacing\":{},"
+ "\"groupings\":{},\"attributes\":{},\"recommendations\":{}},"
+ "\"providers\":[],\"cookbook_name\":\"cookbook\",\"resources\":[],\"templates\":[],"
+ "\"libraries\":[],\"version\":\"1.0.1\","
+ "\"recipes\":[],\"root_files\":[],\"json_class\":\"Chef::CookbookVersion\","
+ "\"chef_type\":\"cookbook_version\"}", "application/json", false);
assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, null);
@ -185,10 +198,11 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testListCookbooks() throws SecurityException, NoSuchMethodException, IOException {
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");
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);
assertResponseParserClassEquals(method, httpRequest, ParseCookbookDefinitionCheckingChefVersion.class);
@ -198,28 +212,31 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
checkFilters(httpRequest);
}
public void testGetVersionsOfCookbook() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "getVersionsOfCookbook", String.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of("apache2"));;
Invokable<?, ?> method = method(ChefAsyncApi.class, "getVersionsOfCookbook", String.class);
GeneratedHttpRequest httpRequest = processor
.apply(Invocation.create(method, ImmutableList.<Object> of("apache2")));
assertRequestLineEquals(httpRequest, "GET http://localhost:4000/cookbooks/apache2 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n");
assertPayloadEquals(httpRequest, null, null, false);
assertRequestLineEquals(httpRequest, "GET http://localhost:4000/cookbooks/apache2 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
+ "-test\n");
assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseCookbookVersionsCheckingChefVersion.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);
assertResponseParserClassEquals(method, httpRequest, ParseCookbookVersionsCheckingChefVersion.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);
checkFilters(httpRequest);
checkFilters(httpRequest);
}
}
public void testApiExists() throws SecurityException, NoSuchMethodException, IOException {
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");
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);
assertResponseParserClassEquals(method, httpRequest, ReturnTrueIf2xx.class);
@ -232,9 +249,11 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testDeleteClient() throws SecurityException, NoSuchMethodException, IOException {
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");
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);
assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
@ -247,10 +266,11 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testCreateApi() throws SecurityException, NoSuchMethodException, IOException {
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");
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);
assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
@ -260,29 +280,32 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
checkFilters(httpRequest);
}
public void testCreateAdminApi() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "createClient", String.class, CreateClientOptions.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of("api", CreateClientOptions.Builder.admin()));
Invokable<?, ?> method = method(ChefAsyncApi.class, "createClient", String.class, CreateClientOptions.class);
GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,
ImmutableList.<Object> of("api", CreateClientOptions.Builder.admin())));
assertRequestLineEquals(httpRequest, "POST http://localhost:4000/clients HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n");
assertPayloadEquals(httpRequest, "{\"name\":\"api\",\"admin\":true}", "application/json", false);
assertRequestLineEquals(httpRequest, "POST http://localhost:4000/clients HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
+ "-test\n");
assertPayloadEquals(httpRequest, "{\"name\":\"api\",\"admin\":true}", "application/json", false);
assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, null);
assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, null);
checkFilters(httpRequest);
checkFilters(httpRequest);
}
}
public void testListClients() throws SecurityException, NoSuchMethodException, IOException {
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");
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);
assertResponseParserClassEquals(method, httpRequest, ParseKeySetFromJson.class);
@ -295,9 +318,11 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testGenerateKeyForClient() throws SecurityException, NoSuchMethodException, IOException {
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");
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);
assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
@ -310,8 +335,9 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testNodeExists() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "nodeExists", String.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of("node"));
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n");
GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method, ImmutableList.<Object> of("node")));
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
+ "-test\n");
assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ReturnTrueIf2xx.class);
@ -324,9 +350,10 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testDeleteNode() throws SecurityException, NoSuchMethodException, IOException {
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");
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);
assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
@ -339,15 +366,16 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testCreateNode() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "createNode", Node.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(new Node("testnode",
ImmutableSet.of("recipe[java]"), "_default")));
GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,
ImmutableList.<Object> of(new Node("testnode", ImmutableSet.of("recipe[java]"), "_default"))));
assertRequestLineEquals(httpRequest, "POST http://localhost:4000/nodes HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n");
assertPayloadEquals(
httpRequest,
"{\"name\":\"testnode\",\"normal\":{},\"override\":{},\"default\":{},\"automatic\":{},\"run_list\":[\"recipe[java]\"],\"chef_environment\":\"_default\",\"json_class\":\"Chef::Node\",\"chef_type\":\"node\"}",
"application/json", false);
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
+ "-test\n");
assertPayloadEquals(httpRequest,
"{\"name\":\"testnode\",\"normal\":{},\"override\":{},\"default\":{},\"automatic\":{},"
+ "\"run_list\":[\"recipe[java]\"],\"chef_environment\":\"_default\",\"json_class\":\"Chef::Node\","
+ "\"chef_type\":\"node\"}", "application/json", false);
assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);
assertSaxResponseParserClassEquals(method, null);
@ -359,15 +387,16 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testUpdateNode() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "updateNode", Node.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(new Node("testnode",
ImmutableSet.of("recipe[java]"), "_default")));
GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,
ImmutableList.<Object> of(new Node("testnode", ImmutableSet.of("recipe[java]"), "_default"))));
assertRequestLineEquals(httpRequest, "PUT http://localhost:4000/nodes/testnode HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n");
assertPayloadEquals(
httpRequest,
"{\"name\":\"testnode\",\"normal\":{},\"override\":{},\"default\":{},\"automatic\":{},\"run_list\":[\"recipe[java]\"],\"chef_environment\":\"_default\",\"json_class\":\"Chef::Node\",\"chef_type\":\"node\"}",
"application/json", false);
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
+ "-test\n");
assertPayloadEquals(httpRequest,
"{\"name\":\"testnode\",\"normal\":{},\"override\":{},\"default\":{},\"automatic\":{},"
+ "\"run_list\":[\"recipe[java]\"],\"chef_environment\":\"_default\",\"json_class\":\"Chef::Node\","
+ "\"chef_type\":\"node\"}", "application/json", false);
assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
assertSaxResponseParserClassEquals(method, null);
@ -379,10 +408,11 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testListNodes() throws SecurityException, NoSuchMethodException, IOException {
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");
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);
assertResponseParserClassEquals(method, httpRequest, ParseKeySetFromJson.class);
@ -395,9 +425,10 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testRoleExists() throws SecurityException, NoSuchMethodException, IOException {
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");
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);
assertResponseParserClassEquals(method, httpRequest, ReturnTrueIf2xx.class);
@ -410,9 +441,10 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testDeleteRole() throws SecurityException, NoSuchMethodException, IOException {
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");
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);
assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
@ -425,14 +457,14 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testCreateRole() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "createRole", Role.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(new Role("testrole",
ImmutableSet.of("recipe[java]"))));
GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,
ImmutableList.<Object> of(new Role("testrole", ImmutableSet.of("recipe[java]")))));
assertRequestLineEquals(httpRequest, "POST http://localhost:4000/roles HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n");
assertPayloadEquals(
httpRequest,
"{\"name\":\"testrole\",\"override_attributes\":{},\"default_attributes\":{},\"run_list\":[\"recipe[java]\"],\"json_class\":\"Chef::Role\",\"chef_type\":\"role\"}",
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
+ "-test\n");
assertPayloadEquals(httpRequest, "{\"name\":\"testrole\",\"override_attributes\":{},\"default_attributes\":{},"
+ "\"run_list\":[\"recipe[java]\"],\"json_class\":\"Chef::Role\",\"chef_type\":\"role\"}",
"application/json", false);
assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);
@ -445,14 +477,14 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testUpdateRole() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "updateRole", Role.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(new Role("testrole",
ImmutableSet.of("recipe[java]"))));
GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,
ImmutableList.<Object> of(new Role("testrole", ImmutableSet.of("recipe[java]")))));
assertRequestLineEquals(httpRequest, "PUT http://localhost:4000/roles/testrole HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n");
assertPayloadEquals(
httpRequest,
"{\"name\":\"testrole\",\"override_attributes\":{},\"default_attributes\":{},\"run_list\":[\"recipe[java]\"],\"json_class\":\"Chef::Role\",\"chef_type\":\"role\"}",
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
+ "-test\n");
assertPayloadEquals(httpRequest, "{\"name\":\"testrole\",\"override_attributes\":{},\"default_attributes\":{},"
+ "\"run_list\":[\"recipe[java]\"],\"json_class\":\"Chef::Role\",\"chef_type\":\"role\"}",
"application/json", false);
assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
@ -465,10 +497,11 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testListRoles() throws SecurityException, NoSuchMethodException, IOException {
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");
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);
assertResponseParserClassEquals(method, httpRequest, ParseKeySetFromJson.class);
@ -481,9 +514,11 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testDatabagExists() throws SecurityException, NoSuchMethodException, IOException {
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");
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);
assertResponseParserClassEquals(method, httpRequest, ReturnTrueIf2xx.class);
@ -496,9 +531,11 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testDeleteDatabag() throws SecurityException, NoSuchMethodException, IOException {
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");
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);
assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);
@ -511,10 +548,11 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testCreateDatabag() throws SecurityException, NoSuchMethodException, IOException {
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");
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);
assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);
@ -527,10 +565,11 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testListDatabags() throws SecurityException, NoSuchMethodException, IOException {
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");
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);
assertResponseParserClassEquals(method, httpRequest, ParseKeySetFromJson.class);
@ -543,9 +582,11 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testDatabagItemExists() throws SecurityException, NoSuchMethodException, IOException {
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");
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);
assertResponseParserClassEquals(method, httpRequest, ReturnTrueIf2xx.class);
@ -558,8 +599,10 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testDeleteDatabagItem() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "deleteDatabagItem", String.class, String.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of("name", "databagItem"));
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n");
GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,
ImmutableList.<Object> of("name", "databagItem")));
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
+ "-test\n");
assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
@ -574,14 +617,16 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testCreateDatabagItemThrowsIllegalArgumentOnPrimitive() throws SecurityException, NoSuchMethodException,
IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "createDatabagItem", String.class, DatabagItem.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of("name", new DatabagItem("id",
"100")));
GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,
ImmutableList.<Object> of("name", new DatabagItem("id", "100"))));
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,
"{\"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);
assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
@ -596,14 +641,16 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testCreateDatabagItemThrowsIllegalArgumentOnWrongId() throws SecurityException, NoSuchMethodException,
IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "createDatabagItem", String.class, DatabagItem.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of("name", new DatabagItem("id",
"{\"id\": \"item1\",\"my_key\": \"my_data\"}")));
GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,
ImmutableList.<Object> of("name", new DatabagItem("id", "{\"id\": \"item1\",\"my_key\": \"my_data\"}"))));
assertRequestLineEquals(httpRequest, "POST http://localhost:4000/data/name HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
+ "-test\n");
assertPayloadEquals(
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);
assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
@ -616,11 +663,12 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testCreateDatabagItem() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "createDatabagItem", String.class, DatabagItem.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of("name", new DatabagItem("id",
"{\"id\": \"id\",\"my_key\": \"my_data\"}")));
GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,
ImmutableList.<Object> of("name", new DatabagItem("id", "{\"id\": \"id\",\"my_key\": \"my_data\"}"))));
assertRequestLineEquals(httpRequest, "POST http://localhost:4000/data/name HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + 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);
assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
@ -633,11 +681,12 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testCreateDatabagItemEvenWhenUserForgotId() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "createDatabagItem", String.class, DatabagItem.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of("name", new DatabagItem("id",
"{\"my_key\": \"my_data\"}")));
GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,
ImmutableList.<Object> of("name", new DatabagItem("id", "{\"my_key\": \"my_data\"}"))));
assertRequestLineEquals(httpRequest, "POST http://localhost:4000/data/name HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + 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);
assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
@ -650,11 +699,12 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testUpdateDatabagItem() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "updateDatabagItem", String.class, DatabagItem.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of("name", new DatabagItem("id",
"{\"my_key\": \"my_data\"}")));
GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,
ImmutableList.<Object> of("name", new DatabagItem("id", "{\"my_key\": \"my_data\"}"))));
assertRequestLineEquals(httpRequest, "PUT http://localhost:4000/data/name/id HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + 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);
@ -668,10 +718,11 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testListDatabagItems() throws SecurityException, NoSuchMethodException, IOException {
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");
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);
assertResponseParserClassEquals(method, httpRequest, ParseKeySetFromJson.class);
@ -684,10 +735,11 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testListSearchIndexes() throws SecurityException, NoSuchMethodException, IOException {
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");
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);
assertResponseParserClassEquals(method, httpRequest, ParseKeySetFromJson.class);
@ -700,10 +752,11 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testSearchRoles() throws SecurityException, NoSuchMethodException, IOException {
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");
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);
assertResponseParserClassEquals(method, httpRequest, ParseSearchRolesFromJson.class);
@ -713,14 +766,15 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
checkFilters(httpRequest);
}
public void testSearchRolesWithOptions() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "searchRoles", SearchOptions.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(
SearchOptions.Builder.query("text")));
GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,
ImmutableList.<Object> of(SearchOptions.Builder.query("text"))));
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);
assertResponseParserClassEquals(method, httpRequest, ParseSearchRolesFromJson.class);
@ -733,10 +787,11 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
public void testSearchClients() throws SecurityException, NoSuchMethodException, IOException {
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");
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);
assertResponseParserClassEquals(method, httpRequest, ParseSearchClientsFromJson.class);
@ -746,30 +801,32 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
checkFilters(httpRequest);
}
public void testSearchClientsWithOptions() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "searchClients", SearchOptions.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(
SearchOptions.Builder.query("text").rows(5)));
Invokable<?, ?> method = method(ChefAsyncApi.class, "searchClients", SearchOptions.class);
GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,
ImmutableList.<Object> of(SearchOptions.Builder.query("text").rows(5))));
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");
assertPayloadEquals(httpRequest, null, null, false);
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");
assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseSearchClientsFromJson.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);
assertResponseParserClassEquals(method, httpRequest, ParseSearchClientsFromJson.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);
checkFilters(httpRequest);
checkFilters(httpRequest);
}
}
public void testSearchNodes() throws SecurityException, NoSuchMethodException, IOException {
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");
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);
assertResponseParserClassEquals(method, httpRequest, ParseSearchNodesFromJson.class);
@ -779,14 +836,15 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
checkFilters(httpRequest);
}
public void testSearchNodesWithOptions() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "searchNodes", SearchOptions.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(
SearchOptions.Builder.query("foo:foo").start(3)));
GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,
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");
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);
assertResponseParserClassEquals(method, httpRequest, ParseSearchNodesFromJson.class);
@ -797,13 +855,13 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
}
public void testSearchDatabag() throws SecurityException, NoSuchMethodException, IOException {
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");
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);
assertResponseParserClassEquals(method, httpRequest, ParseSearchDatabagFromJson.class);
@ -813,14 +871,15 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
checkFilters(httpRequest);
}
public void testSearchDatabagWithOptions() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "searchDatabag", String.class, SearchOptions.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of("foo",
SearchOptions.Builder.query("bar").sort("name DESC")));
GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,
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");
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);
assertResponseParserClassEquals(method, httpRequest, ParseSearchDatabagFromJson.class);
@ -830,23 +889,24 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
checkFilters(httpRequest);
}
public void testGetResourceContents() throws SecurityException, NoSuchMethodException, IOException {
Invokable<?, ?> method = method(ChefAsyncApi.class, "getResourceContents", Resource.class);
GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(
new Resource("test", URI.create("http://foo/bar"), new byte[]{}, null, null)));
Invokable<?, ?> method = method(ChefAsyncApi.class, "getResourceContents", Resource.class);
GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,
ImmutableList.<Object> of(new Resource("test", URI.create("http://foo/bar"), new byte[] {}, null, null))));
assertRequestLineEquals(httpRequest, "GET http://foo/bar HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION + "-test\n");
assertPayloadEquals(httpRequest, null, null, false);
assertRequestLineEquals(httpRequest, "GET http://foo/bar HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: " + ChefAsyncApi.VERSION
+ "-test\n");
assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ReturnInputStream.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, NullOnNotFoundOr404.class);
assertResponseParserClassEquals(method, httpRequest, ReturnInputStream.class);
assertSaxResponseParserClassEquals(method, null);
assertFallbackClassEquals(method, NullOnNotFoundOr404.class);
checkFilters(httpRequest);
checkFilters(httpRequest);
}
}
@Override
protected void checkFilters(HttpRequest request) {
@ -861,9 +921,9 @@ public class ChefAsyncApiTest extends BaseAsyncApiTest<ChefAsyncApi> {
@Override
protected Properties setupProperties() {
Properties props = super.setupProperties();
props.put(Constants.PROPERTY_API_VERSION, ChefAsyncApi.VERSION + "-test");
return props;
Properties props = super.setupProperties();
props.put(Constants.PROPERTY_API_VERSION, ChefAsyncApi.VERSION + "-test");
return props;
}
@ConfiguresRestClient

View File

@ -44,13 +44,12 @@ import com.google.inject.Injector;
public class BindHexEncodedMD5sToJsonPayloadTest {
Injector injector = Guice.createInjector(new AbstractModule() {
@Override
protected void configure()
{
bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefAsyncApi.VERSION);
}
}, new ChefParserModule(), new GsonModule());
@Override
protected void configure() {
bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefAsyncApi.VERSION);
}
}, new ChefParserModule(), new GsonModule());
BindChecksumsToJsonPayload binder = injector.getInstance(BindChecksumsToJsonPayload.class);
@Test(expectedExceptions = IllegalArgumentException.class)
@ -62,7 +61,8 @@ public class BindHexEncodedMD5sToJsonPayloadTest {
@Test(enabled = false)
public void testCorrect() {
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}}");
}

View File

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

View File

@ -70,7 +70,7 @@ public class ClientForGroupTest {
ClientForGroup fn = new ClientForGroup(chefApi);
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(client.getPrivateKey()).andReturn(privateKey);

View File

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

View File

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

View File

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

View File

@ -47,24 +47,19 @@ public class ParseCookbookVersionsV09FromJsonTest {
@BeforeTest
protected void setUpInjector() throws IOException {
Injector injector = Guice.createInjector(new AbstractModule() {
@Override
protected void configure()
{
bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefAsyncApi.VERSION);
}
}, new ChefParserModule(), new GsonModule());
Injector injector = Guice.createInjector(new AbstractModule() {
@Override
protected void configure() {
bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefAsyncApi.VERSION);
}
}, new ChefParserModule(), new GsonModule());
handler = injector.getInstance(ParseCookbookVersionsV09FromJson.class);
}
public void testRegex() {
assertEquals(
handler
.apply(HttpResponse.builder()
.statusCode(200)
.message("ok")
.payload("{\"apache2\": [\"0.1.8\", \"0.2\"]}").build()),
ImmutableSet.of("0.1.8", "0.2"));
handler.apply(HttpResponse.builder().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
protected void setUpInjector() throws IOException {
Injector injector = Guice.createInjector(new AbstractModule() {
@Override
protected void configure()
{
bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefAsyncApi.VERSION);
}
}, new ChefParserModule(), new GsonModule());
Injector injector = Guice.createInjector(new AbstractModule() {
@Override
protected void configure() {
bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefAsyncApi.VERSION);
}
}, new ChefParserModule(), new GsonModule());
handler = injector.getInstance(ParseCookbookVersionsV10FromJson.class);
}
public void testRegex() {
assertEquals(
handler
.apply(HttpResponse.builder()
.statusCode(200)
.message("ok")
.payload("{" +
"\"apache2\" => {" +
"\"url\" => \"http://localhost:4000/cookbooks/apache2\"," +
"\"versions\" => [" +
"{\"url\" => \"http://localhost:4000/cookbooks/apache2/5.1.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"));
assertEquals(handler.apply(HttpResponse
.builder()
.statusCode(200)
.message("ok")
.payload(
"{" + "\"apache2\" => {" + "\"url\" => \"http://localhost:4000/cookbooks/apache2\","
+ "\"versions\" => [" + "{\"url\" => \"http://localhost:4000/cookbooks/apache2/5.1.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
protected void setUpInjector() throws IOException {
Injector injector = Guice.createInjector(new AbstractModule() {
@Override
protected void configure()
{
bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefAsyncApi.VERSION);
}
}, new ChefParserModule(), new GsonModule());
Injector injector = Guice.createInjector(new AbstractModule() {
@Override
protected void configure() {
bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefAsyncApi.VERSION);
}
}, new ChefParserModule(), new GsonModule());
handler = injector.getInstance(Key.get(new TypeLiteral<ParseJson<DatabagItem>>() {
}));
mapper = injector.getInstance(Json.class);
@ -65,10 +64,7 @@ public class ParseDataBagItemFromJsonTest {
public void test1() {
String json = "{\"my_key\":\"my_data\",\"id\":\"item1\"}";
DatabagItem item = new DatabagItem("item1", json);
assertEquals(handler.apply(HttpResponse.builder()
.statusCode(200)
.message("ok")
.payload(json).build()), item);
assertEquals(handler.apply(HttpResponse.builder().statusCode(200).message("ok").payload(json).build()), item);
assertEquals(mapper.toJson(item), json);
}
}

View File

@ -37,14 +37,10 @@ public class ParseErrorFromJsonOrReturnBodyTest {
@Test
public void testApplyInputStreamDetails() throws UnknownHostException {
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(
new ReturnStringIf2xx());
String response = parser.apply(HttpResponse.builder()
.statusCode(200)
.message("ok")
.payload(is).build());
ParseErrorFromJsonOrReturnBody parser = new ParseErrorFromJsonOrReturnBody(new ReturnStringIf2xx());
String response = parser.apply(HttpResponse.builder().statusCode(200).message("ok").payload(is).build());
assertEquals(response, "invalid tarball: tarball root must contain java-bytearray");
}

View File

@ -47,24 +47,24 @@ public class ParseKeySetFromJsonTest {
@BeforeTest
protected void setUpInjector() throws IOException {
Injector injector = Guice.createInjector(new AbstractModule() {
@Override
protected void configure()
{
bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefAsyncApi.VERSION);
}
}, new ChefParserModule(), new GsonModule());
Injector injector = Guice.createInjector(new AbstractModule() {
@Override
protected void configure() {
bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefAsyncApi.VERSION);
}
}, new ChefParserModule(), new GsonModule());
handler = injector.getInstance(ParseKeySetFromJson.class);
}
public void testRegex() {
assertEquals(
handler
.apply(HttpResponse.builder()
.statusCode(200)
.message("ok")
.payload("{\n\"opscode-validator\": \"https://api.opscode.com/...\", \"pimp-validator\": \"https://api.opscode.com/...\"}").build()),
ImmutableSet.of("opscode-validator", "pimp-validator"));
handler.apply(HttpResponse
.builder()
.statusCode(200)
.message("ok")
.payload(
"{\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
protected void setUpInjector() throws IOException {
Injector injector = Guice.createInjector(new AbstractModule() {
@Override
protected void configure()
{
bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefAsyncApi.VERSION);
}
}, new ChefParserModule(), new GsonModule());
Injector injector = Guice.createInjector(new AbstractModule() {
@Override
protected void configure() {
bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefAsyncApi.VERSION);
}
}, new ChefParserModule(), new GsonModule());
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(),
ImmutableMap.<String, JsonBall> of(), Collections.singleton("recipe[java]"), "prod");
assertEquals(handler.apply(HttpResponse.builder()
.statusCode(200)
.message("ok")
.payload(ParseCookbookVersionFromJsonTest.class
.getResourceAsStream("/node.json")).build()), node);
assertEquals(
handler.apply(HttpResponse.builder().statusCode(200).message("ok")
.payload(ParseCookbookVersionFromJsonTest.class.getResourceAsStream("/node.json")).build()), node);
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -35,39 +35,41 @@ public class RunListBuilderTest {
public void testRecipeAndRole() {
RunListBuilder options = new RunListBuilder();
options.addRecipe("recipe").addRole("role");
assertEquals(options.build(),ImmutableList.of("recipe[recipe]","role[role]"));
assertEquals(options.build(), ImmutableList.of("recipe[recipe]", "role[role]"));
}
@Test
public void testRecipe() {
RunListBuilder options = new RunListBuilder();
options.addRecipe("test");
assertEquals(options.build(),ImmutableList.of("recipe[test]"));
assertEquals(options.build(), ImmutableList.of("recipe[test]"));
}
@Test
public void testRecipes() {
RunListBuilder options = new RunListBuilder();
options.addRecipes("test", "test2");
assertEquals(options.build(),ImmutableList.of("recipe[test]","recipe[test2]"));
assertEquals(options.build(), ImmutableList.of("recipe[test]", "recipe[test2]"));
}
@Test
public void testRole() {
RunListBuilder options = new RunListBuilder();
options.addRole("test");
assertEquals(options.build(),ImmutableList.of("role[test]"));
assertEquals(options.build(), ImmutableList.of("role[test]"));
}
@Test
public void testRoles() {
RunListBuilder options = new RunListBuilder();
options.addRoles("test", "test2");
assertEquals(options.build(),ImmutableList.of("role[test]","role[test2]"));
assertEquals(options.build(), ImmutableList.of("role[test]", "role[test2]"));
}
@Test
public void testNoneRecipe() {
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);
Injector injector = Guice.createInjector(new AbstractModule() {
@Override
protected void configure()
{
bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefAsyncApi.VERSION);
}
}, new ChefParserModule(), new GsonModule(), new JMXOhaiModule() {
@Override
protected void configure() {
bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefAsyncApi.VERSION);
}
}, new ChefParserModule(), new GsonModule(), new JMXOhaiModule() {
@Override
protected RuntimeMXBean provideRuntimeMXBean() {
return runtime;

View File

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

View File

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

View File

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