added toString to common functions so that they are easier to see when debugging

This commit is contained in:
Adrian Cole 2011-03-14 01:39:59 -07:00
parent b0f37625ec
commit f5fa2d983b
9 changed files with 166 additions and 127 deletions

View File

@ -82,9 +82,9 @@ public class AtmosAsyncBlobStore extends BaseAsyncBlobStore {
@Inject
AtmosAsyncBlobStore(BlobStoreContext context, BlobUtils blobUtils,
@Named(Constants.PROPERTY_USER_THREADS) ExecutorService service, Supplier<Location> defaultLocation,
@Memoized Supplier<Set<? extends Location>> locations, AtmosAsyncClient async,
AtmosClient sync, ObjectToBlob object2Blob, ObjectToBlobMetadata object2BlobMd,
BlobToObject blob2Object, BlobStoreListOptionsToListOptions container2ContainerListOptions,
@Memoized Supplier<Set<? extends Location>> locations, AtmosAsyncClient async, AtmosClient sync,
ObjectToBlob object2Blob, ObjectToBlobMetadata object2BlobMd, BlobToObject blob2Object,
BlobStoreListOptionsToListOptions container2ContainerListOptions,
DirectoryEntryListToResourceMetadataList container2ResourceList, Crypto crypto,
BlobToHttpGetOptions blob2ObjectGetOptions, Provider<FetchBlobMetadata> fetchBlobMetadataProvider) {
super(context, blobUtils, service, defaultLocation, locations);
@ -235,9 +235,12 @@ public class AtmosAsyncBlobStore extends BaseAsyncBlobStore {
@Override
public String call() throws Exception {
return AtmosUtils.putBlob(sync, crypto, blob2Object, container, blob);
}
@Override
public String toString() {
return "putBlob(" + container + "," + blob.getMetadata().getName() + ")";
}
}), service);
}

View File

@ -62,8 +62,8 @@ public abstract class BaseAsyncBlobStore implements AsyncBlobStore {
@Inject
protected BaseAsyncBlobStore(BlobStoreContext context, BlobUtils blobUtils,
@Named(Constants.PROPERTY_USER_THREADS) ExecutorService service, Supplier<Location> defaultLocation,
@Memoized Supplier<Set<? extends Location>> locations) {
@Named(Constants.PROPERTY_USER_THREADS) ExecutorService service, Supplier<Location> defaultLocation,
@Memoized Supplier<Set<? extends Location>> locations) {
this.context = checkNotNull(context, "context");
this.blobUtils = checkNotNull(blobUtils, "blobUtils");
this.service = checkNotNull(service, "service");
@ -129,6 +129,10 @@ public abstract class BaseAsyncBlobStore implements AsyncBlobStore {
return blobUtils.countBlobs(containerName, options);
}
@Override
public String toString() {
return "countBlobs(" + containerName + ")";
}
}), service);
}
@ -159,6 +163,10 @@ public abstract class BaseAsyncBlobStore implements AsyncBlobStore {
return null;
}
@Override
public String toString() {
return "clearContainer(" + containerName + ")";
}
}), service);
}
@ -177,6 +185,10 @@ public abstract class BaseAsyncBlobStore implements AsyncBlobStore {
return null;
}
@Override
public String toString() {
return "deleteDirectory(" + containerName + "," + directory + ")";
}
}), service);
}
@ -195,6 +207,10 @@ public abstract class BaseAsyncBlobStore implements AsyncBlobStore {
return blobUtils.directoryExists(containerName, directory);
}
@Override
public String toString() {
return "directoryExists(" + containerName + "," + directory + ")";
}
}), service);
}
@ -210,12 +226,17 @@ public abstract class BaseAsyncBlobStore implements AsyncBlobStore {
public ListenableFuture<Void> createDirectory(final String containerName, final String directory) {
return blobUtils.directoryExists(containerName, directory) ? Futures.immediateFuture((Void) null)
: org.jclouds.concurrent.Futures.makeListenable(service.submit(new Callable<Void>() {
public Void call() throws Exception {
blobUtils.createDirectory(containerName, directory);
return null;
}
}), service);
: org.jclouds.concurrent.Futures.makeListenable(service.submit(new Callable<Void>() {
public Void call() throws Exception {
blobUtils.createDirectory(containerName, directory);
return null;
}
@Override
public String toString() {
return "createDirectory(" + containerName + "," + directory + ")";
}
}), service);
}
/**
@ -247,6 +268,10 @@ public abstract class BaseAsyncBlobStore implements AsyncBlobStore {
return null;
}
@Override
public String toString() {
return "deleteContainer(" + container + ")";
}
}), service);
}

View File

@ -72,7 +72,7 @@ import com.google.common.collect.Multimap;
public class FormSigner implements HttpRequestFilter, RequestSigner {
public static String[] mandatoryParametersForSignature = new String[] { ACTION, SIGNATURE_METHOD, SIGNATURE_VERSION,
VERSION };
VERSION };
private final SignatureWire signatureWire;
private final String accessKey;
private final String secretKey;
@ -86,8 +86,8 @@ public class FormSigner implements HttpRequestFilter, RequestSigner {
@Inject
public FormSigner(SignatureWire signatureWire, @Named(Constants.PROPERTY_IDENTITY) String accessKey,
@Named(Constants.PROPERTY_CREDENTIAL) String secretKey, @TimeStamp Provider<String> dateService,
Crypto crypto, HttpUtils utils) {
@Named(Constants.PROPERTY_CREDENTIAL) String secretKey, @TimeStamp Provider<String> dateService,
Crypto crypto, HttpUtils utils) {
this.signatureWire = signatureWire;
this.accessKey = accessKey;
this.secretKey = secretKey;
@ -99,7 +99,7 @@ public class FormSigner implements HttpRequestFilter, RequestSigner {
public HttpRequest filter(HttpRequest request) throws HttpException {
checkNotNull(request.getFirstHeaderOrNull(HttpHeaders.HOST), "request is not ready to sign; host not present");
Multimap<String, String> decodedParams = ModifyRequest.parseQueryToMap(request.getPayload().getRawContent()
.toString());
.toString());
addSigningParams(decodedParams);
validateParams(decodedParams);
String stringToSign = createStringToSign(request, decodedParams);
@ -155,8 +155,8 @@ public class FormSigner implements HttpRequestFilter, RequestSigner {
public String sign(String stringToSign) {
String signature;
try {
signature = CryptoStreams.base64(CryptoStreams.mac(InputSuppliers.of(stringToSign),
crypto.hmacSHA256(secretKey.getBytes())));
signature = CryptoStreams.base64(CryptoStreams.mac(InputSuppliers.of(stringToSign), crypto
.hmacSHA256(secretKey.getBytes())));
if (signatureWire.enabled())
signatureWire.input(Strings2.toInputStream(signature));
} catch (Exception e) {
@ -184,15 +184,17 @@ public class FormSigner implements HttpRequestFilter, RequestSigner {
@VisibleForTesting
String buildCanonicalizedString(Multimap<String, String> decodedParams) {
return ModifyRequest.makeQueryLine(decodedParams, new Comparator<Map.Entry<String, String>>() {
public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
if (o1.getKey().startsWith("AWSAccessKeyId"))
return -1;
return o1.getKey().compareTo(o2.getKey());
}
});
return ModifyRequest.makeQueryLine(decodedParams, sortAWSFirst);
}
public static final Comparator<Map.Entry<String, String>> sortAWSFirst = new Comparator<Map.Entry<String, String>>() {
public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
if (o1.getKey().startsWith("AWSAccessKeyId"))
return -1;
return o1.getKey().compareTo(o2.getKey());
}
};
@VisibleForTesting
void addSigningParams(Multimap<String, String> params) {
params.replaceValues(SIGNATURE_METHOD, ImmutableList.of("HmacSHA256"));

View File

@ -83,6 +83,10 @@ public class VCloudHardwareSupplier implements Supplier<Set<? extends Hardware>>
return sizesInOrg.apply(from);
}
@Override
public String toString() {
return "sizesInOrg(" + from.getHref() + ")";
}
});
}

View File

@ -83,6 +83,10 @@ public class VCloudImageSupplier implements Supplier<Set<? extends Image>> {
return imagesInOrg.apply(from);
}
@Override
public String toString() {
return "imagesInOrg(" + from.getHref() + ")";
}
});
}

View File

@ -133,17 +133,19 @@ public class BaseComputeService implements ComputeService {
@Inject
protected BaseComputeService(ComputeServiceContext context, Map<String, Credentials> credentialStore,
@Memoized Supplier<Set<? extends Image>> images, @Memoized Supplier<Set<? extends Hardware>> hardwareProfiles,
@Memoized Supplier<Set<? extends Location>> locations, ListNodesStrategy listNodesStrategy,
GetNodeMetadataStrategy getNodeMetadataStrategy, CreateNodesInGroupThenAddToSet runNodesAndAddToSetStrategy,
RebootNodeStrategy rebootNodeStrategy, DestroyNodeStrategy destroyNodeStrategy,
ResumeNodeStrategy resumeNodeStrategy, SuspendNodeStrategy suspendNodeStrategy,
Provider<TemplateBuilder> templateBuilderProvider, Provider<TemplateOptions> templateOptionsProvider,
@Named("NODE_RUNNING") Predicate<NodeMetadata> nodeRunning,
@Named("NODE_TERMINATED") Predicate<NodeMetadata> nodeTerminated,
@Named("NODE_SUSPENDED") Predicate<NodeMetadata> nodeSuspended,
InitializeRunScriptOnNodeOrPlaceInBadMap.Factory initScriptRunnerFactory, Timeouts timeouts,
@Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor) {
@Memoized Supplier<Set<? extends Image>> images,
@Memoized Supplier<Set<? extends Hardware>> hardwareProfiles,
@Memoized Supplier<Set<? extends Location>> locations, ListNodesStrategy listNodesStrategy,
GetNodeMetadataStrategy getNodeMetadataStrategy,
CreateNodesInGroupThenAddToSet runNodesAndAddToSetStrategy, RebootNodeStrategy rebootNodeStrategy,
DestroyNodeStrategy destroyNodeStrategy, ResumeNodeStrategy resumeNodeStrategy,
SuspendNodeStrategy suspendNodeStrategy, Provider<TemplateBuilder> templateBuilderProvider,
Provider<TemplateOptions> templateOptionsProvider,
@Named("NODE_RUNNING") Predicate<NodeMetadata> nodeRunning,
@Named("NODE_TERMINATED") Predicate<NodeMetadata> nodeTerminated,
@Named("NODE_SUSPENDED") Predicate<NodeMetadata> nodeSuspended,
InitializeRunScriptOnNodeOrPlaceInBadMap.Factory initScriptRunnerFactory, Timeouts timeouts,
@Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor) {
this.context = checkNotNull(context, "context");
this.credentialStore = checkNotNull(credentialStore, "credentialStore");
this.images = checkNotNull(images, "images");
@ -179,7 +181,7 @@ public class BaseComputeService implements ComputeService {
*/
@Override
public Set<? extends NodeMetadata> runNodesWithTag(String group, int count, Template template)
throws RunNodesException {
throws RunNodesException {
return createNodesInGroup(group, count, template);
}
@ -188,7 +190,7 @@ public class BaseComputeService implements ComputeService {
*/
@Override
public Set<? extends NodeMetadata> runNodesWithTag(String group, int count, TemplateOptions templateOptions)
throws RunNodesException {
throws RunNodesException {
return createNodesInGroup(group, count, templateBuilder().any().options(templateOptions).build());
}
@ -202,20 +204,20 @@ public class BaseComputeService implements ComputeService {
@Override
public Set<? extends NodeMetadata> createNodesInGroup(String group, int count, Template template)
throws RunNodesException {
throws RunNodesException {
checkNotNull(group, "group cannot be null");
checkNotNull(template.getLocation(), "location");
logger.debug(">> running %d node%s group(%s) location(%s) image(%s) hardwareProfile(%s) options(%s)", count,
count > 1 ? "s" : "", group, template.getLocation().getId(), template.getImage().getId(), template
.getHardware().getId(), template.getOptions());
count > 1 ? "s" : "", group, template.getLocation().getId(), template.getImage().getId(), template
.getHardware().getId(), template.getOptions());
Set<NodeMetadata> goodNodes = newLinkedHashSet();
Map<NodeMetadata, Exception> badNodes = newLinkedHashMap();
Multimap<NodeMetadata, CustomizationResponse> customizationResponses = LinkedHashMultimap.create();
Map<?, Future<Void>> responses = runNodesAndAddToSetStrategy.execute(group, count, template, goodNodes, badNodes,
customizationResponses);
customizationResponses);
Map<?, Exception> executionExceptions = awaitCompletion(responses, executor, null, logger, "runNodesWithTag("
+ group + ")");
+ group + ")");
for (NodeMetadata node : concat(goodNodes, badNodes.keySet()))
if (node.getCredentials() != null)
credentialStore.put("node#" + node.getId(), node.getCredentials());
@ -227,7 +229,7 @@ public class BaseComputeService implements ComputeService {
@Override
public Set<? extends NodeMetadata> createNodesInGroup(String group, int count, TemplateOptions templateOptions)
throws RunNodesException {
throws RunNodesException {
return createNodesInGroup(group, count, templateBuilder().any().options(templateOptions).build());
}
@ -274,23 +276,27 @@ public class BaseComputeService implements ComputeService {
public Set<? extends NodeMetadata> destroyNodesMatching(Predicate<NodeMetadata> filter) {
logger.debug(">> destroying nodes matching(%s)", filter);
Set<NodeMetadata> set = newLinkedHashSet(transformParallel(nodesMatchingFilterAndNotTerminated(filter),
new Function<NodeMetadata, Future<NodeMetadata>>() {
new Function<NodeMetadata, Future<NodeMetadata>>() {
// TODO make an async interface instead of re-wrapping
@Override
public Future<NodeMetadata> apply(final NodeMetadata from) {
return executor.submit(new Callable<NodeMetadata>() {
// TODO make an async interface instead of re-wrapping
@Override
public Future<NodeMetadata> apply(final NodeMetadata from) {
return executor.submit(new Callable<NodeMetadata>() {
@Override
public NodeMetadata call() throws Exception {
destroyNode(from.getId());
return from;
}
@Override
public NodeMetadata call() throws Exception {
destroyNode(from.getId());
return from;
}
});
}
@Override
public String toString() {
return "destroyNode(" + from.getId() + ")";
}
});
}
}, executor, null, logger, "destroyNodesMatching(" + filter + ")"));
}, executor, null, logger, "destroyNodesMatching(" + filter + ")"));
logger.debug("<< destroyed(%d)", set.size());
return set;
}
@ -304,7 +310,7 @@ public class BaseComputeService implements ComputeService {
* if none found
*/
Iterable<? extends NodeMetadata> nodesMatchingFilterAndNotTerminatedExceptionIfNotFound(
Predicate<NodeMetadata> filter) {
Predicate<NodeMetadata> filter) {
Iterable<? extends NodeMetadata> nodes = nodesMatchingFilterAndNotTerminated(filter);
if (Iterables.size(nodes) == 0)
throw new NoSuchElementException("no nodes matched filter: " + filter);
@ -394,15 +400,15 @@ public class BaseComputeService implements ComputeService {
public void rebootNodesMatching(Predicate<NodeMetadata> filter) {
logger.debug(">> rebooting nodes matching(%s)", filter);
transformParallel(nodesMatchingFilterAndNotTerminatedExceptionIfNotFound(filter),
new Function<NodeMetadata, Future<Void>>() {
// TODO use native async
@Override
public Future<Void> apply(NodeMetadata from) {
rebootNode(from.getId());
return immediateFuture(null);
}
new Function<NodeMetadata, Future<Void>>() {
// TODO use native async
@Override
public Future<Void> apply(NodeMetadata from) {
rebootNode(from.getId());
return immediateFuture(null);
}
}, executor, null, logger, "rebootNodesMatching(" + filter + ")");
}, executor, null, logger, "rebootNodesMatching(" + filter + ")");
logger.debug("<< rebooted");
}
@ -425,15 +431,15 @@ public class BaseComputeService implements ComputeService {
public void resumeNodesMatching(Predicate<NodeMetadata> filter) {
logger.debug(">> resuming nodes matching(%s)", filter);
transformParallel(nodesMatchingFilterAndNotTerminatedExceptionIfNotFound(filter),
new Function<NodeMetadata, Future<Void>>() {
// TODO use native async
@Override
public Future<Void> apply(NodeMetadata from) {
resumeNode(from.getId());
return immediateFuture(null);
}
new Function<NodeMetadata, Future<Void>>() {
// TODO use native async
@Override
public Future<Void> apply(NodeMetadata from) {
resumeNode(from.getId());
return immediateFuture(null);
}
}, executor, null, logger, "resumeNodesMatching(" + filter + ")");
}, executor, null, logger, "resumeNodesMatching(" + filter + ")");
logger.debug("<< resumed");
}
@ -456,15 +462,15 @@ public class BaseComputeService implements ComputeService {
public void suspendNodesMatching(Predicate<NodeMetadata> filter) {
logger.debug(">> suspending nodes matching(%s)", filter);
transformParallel(nodesMatchingFilterAndNotTerminatedExceptionIfNotFound(filter),
new Function<NodeMetadata, Future<Void>>() {
// TODO use native async
@Override
public Future<Void> apply(NodeMetadata from) {
suspendNode(from.getId());
return immediateFuture(null);
}
new Function<NodeMetadata, Future<Void>>() {
// TODO use native async
@Override
public Future<Void> apply(NodeMetadata from) {
suspendNode(from.getId());
return immediateFuture(null);
}
}, executor, null, logger, "suspendNodesMatching(" + filter + ")");
}, executor, null, logger, "suspendNodesMatching(" + filter + ")");
logger.debug("<< suspended");
}
@ -473,7 +479,7 @@ public class BaseComputeService implements ComputeService {
*/
@Override
public Map<NodeMetadata, ExecResponse> runScriptOnNodesMatching(Predicate<NodeMetadata> filter, Payload runScript)
throws RunScriptOnNodesException {
throws RunScriptOnNodesException {
return runScriptOnNodesMatching(filter, runScript, RunScriptOptions.NONE);
}
@ -482,10 +488,10 @@ public class BaseComputeService implements ComputeService {
*/
@Override
public Map<NodeMetadata, ExecResponse> runScriptOnNodesMatching(Predicate<NodeMetadata> filter, Payload runScript,
RunScriptOptions options) throws RunScriptOnNodesException {
RunScriptOptions options) throws RunScriptOnNodesException {
try {
return runScriptOnNodesMatching(filter,
Statements.exec(Strings2.toStringAndClose(checkNotNull(runScript, "runScript").getInput())), options);
return runScriptOnNodesMatching(filter, Statements.exec(Strings2.toStringAndClose(checkNotNull(runScript,
"runScript").getInput())), options);
} catch (IOException e) {
Throwables.propagate(e);
return null;
@ -497,7 +503,7 @@ public class BaseComputeService implements ComputeService {
*/
@Override
public Map<NodeMetadata, ExecResponse> runScriptOnNodesMatching(Predicate<NodeMetadata> filter, String runScript)
throws RunScriptOnNodesException {
throws RunScriptOnNodesException {
return runScriptOnNodesMatching(filter, Statements.exec(checkNotNull(runScript, "runScript")));
}
@ -506,15 +512,15 @@ public class BaseComputeService implements ComputeService {
*/
@Override
public Map<NodeMetadata, ExecResponse> runScriptOnNodesMatching(Predicate<NodeMetadata> filter, Statement runScript)
throws RunScriptOnNodesException {
throws RunScriptOnNodesException {
return runScriptOnNodesMatching(filter, runScript, RunScriptOptions.NONE);
}
@Override
public Map<? extends NodeMetadata, ExecResponse> runScriptOnNodesMatching(Predicate<NodeMetadata> filter,
String runScript, RunScriptOptions options) throws RunScriptOnNodesException {
String runScript, RunScriptOptions options) throws RunScriptOnNodesException {
return runScriptOnNodesMatching(filter, Statements.exec(checkNotNull(runScript, "runScript")),
RunScriptOptions.NONE);
RunScriptOptions.NONE);
}
/**
@ -522,7 +528,7 @@ public class BaseComputeService implements ComputeService {
*/
@Override
public Map<NodeMetadata, ExecResponse> runScriptOnNodesMatching(Predicate<NodeMetadata> filter, Statement runScript,
RunScriptOptions options) throws RunScriptOnNodesException {
RunScriptOptions options) throws RunScriptOnNodesException {
checkNotNull(filter, "filter");
checkNotNull(runScript, "runScript");
@ -534,11 +540,11 @@ public class BaseComputeService implements ComputeService {
Map<?, Exception> exceptions = ImmutableMap.<Object, Exception> of();
Iterable<? extends RunScriptOnNode> scriptRunners = transformNodesIntoInitializedScriptRunners(
nodesMatchingFilterAndNotTerminatedExceptionIfNotFound(filter), runScript, options, badNodes);
nodesMatchingFilterAndNotTerminatedExceptionIfNotFound(filter), runScript, options, badNodes);
if (Iterables.size(scriptRunners) > 0) {
for (RunScriptOnNode runner : scriptRunners) {
responses.put(runner.getNode(), executor.submit(new RunScriptOnNodeAndAddToGoodMapOrPutExceptionIntoBadMap(
runner, goodNodes, badNodes)));
runner, goodNodes, badNodes)));
}
exceptions = awaitCompletion(responses, executor, null, logger, "runScriptOnNodesMatching(" + filter + ")");
}
@ -550,11 +556,10 @@ public class BaseComputeService implements ComputeService {
}
private Iterable<? extends RunScriptOnNode> transformNodesIntoInitializedScriptRunners(
Iterable<? extends NodeMetadata> nodes, Statement script, RunScriptOptions options,
Map<NodeMetadata, Exception> badNodes) {
return filter(
transformParallel(nodes, new TransformNodesIntoInitializedScriptRunners(script, options, badNodes),
executor, null, logger, "initialize script runners"), notNull());
Iterable<? extends NodeMetadata> nodes, Statement script, RunScriptOptions options,
Map<NodeMetadata, Exception> badNodes) {
return filter(transformParallel(nodes, new TransformNodesIntoInitializedScriptRunners(script, options, badNodes),
executor, null, logger, "initialize script runners"), notNull());
}
private Set<? extends NodeMetadata> detailsOnAllNodes() {
@ -567,13 +572,13 @@ public class BaseComputeService implements ComputeService {
}
private final class TransformNodesIntoInitializedScriptRunners implements
Function<NodeMetadata, Future<RunScriptOnNode>> {
Function<NodeMetadata, Future<RunScriptOnNode>> {
private final Map<NodeMetadata, Exception> badNodes;
private final Statement script;
private final RunScriptOptions options;
private TransformNodesIntoInitializedScriptRunners(Statement script, RunScriptOptions options,
Map<NodeMetadata, Exception> badNodes) {
Map<NodeMetadata, Exception> badNodes) {
this.badNodes = checkNotNull(badNodes, "badNodes");
this.script = checkNotNull(script, "script");
this.options = checkNotNull(options, "options");
@ -584,7 +589,7 @@ public class BaseComputeService implements ComputeService {
checkNotNull(node, "node");
if (options.getOverridingCredentials() != null) {
Builder<? extends Credentials> builder = node.getCredentials() != null ? node.getCredentials().toBuilder()
: new Credentials.Builder<Credentials>();
: new Credentials.Builder<Credentials>();
if (options.getOverridingCredentials().identity != null)
builder.identity(options.getOverridingCredentials().identity);
if (options.getOverridingCredentials().credential != null)

View File

@ -150,7 +150,7 @@ public abstract class BaseHttpCommandExecutorService<Q> implements HttpCommandEx
request = filter.filter(request);
}
checkRequestHasContentLengthOrChunkedEncoding(request,
"After filtering, the request has niether chunked encoding nor content length: " + request);
"After filtering, the request has neither chunked encoding nor content length: " + request);
logger.debug("Sending request %s: %s", request.hashCode(), request.getRequestLine());
wirePayloadIfEnabled(wire, request);
utils.logRequest(headerLog, request, ">>");
@ -203,6 +203,11 @@ public abstract class BaseHttpCommandExecutorService<Q> implements HttpCommandEx
return shouldContinue;
}
@Override
public String toString() {
return "[command=" + command + "]";
}
}
protected abstract Q convert(HttpRequest request) throws IOException, InterruptedException;

View File

@ -20,16 +20,12 @@
package org.jclouds.http.utils;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Sets.newTreeSet;
import static org.jclouds.io.Payloads.newUrlEncodedFormPayload;
import java.net.URI;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.SortedSet;
import javax.annotation.Nullable;
import javax.ws.rs.core.UriBuilder;
@ -40,6 +36,7 @@ import org.jclouds.util.Strings2;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.LinkedListMultimap;
import com.google.common.collect.Multimap;
@ -51,11 +48,9 @@ import com.google.common.collect.Multimap;
public class ModifyRequest {
@SuppressWarnings("unchecked")
public static <R extends HttpRequest> R putHeaders(R request, Multimap<String, String> moreHeaders) {
return (R) request
.toBuilder()
.headers(
ImmutableMultimap.<String, String> builder().putAll(request.getHeaders()).putAll(moreHeaders).build())
.build();
return (R) request.toBuilder().headers(
ImmutableMultimap.<String, String> builder().putAll(request.getHeaders()).putAll(moreHeaders).build())
.build();
}
@SuppressWarnings("unchecked")
@ -99,7 +94,7 @@ public class ModifyRequest {
@SuppressWarnings("unchecked")
public static <R extends HttpRequest> R addQueryParam(R request, String key, Iterable<?> values, UriBuilder builder,
char... skips) {
char... skips) {
builder.uri(request.getEndpoint());
Multimap<String, String> map = parseQueryToMap(request.getEndpoint().getQuery());
for (Object o : values)
@ -114,7 +109,7 @@ public class ModifyRequest {
@SuppressWarnings("unchecked")
public static <R extends HttpRequest> R replaceMatrixParam(R request, String name, Object[] values,
UriBuilder builder) {
UriBuilder builder) {
builder.uri(request.getEndpoint());
builder.replaceMatrixParam(name, values);
return (R) request.toBuilder().endpoint(builder.build()).build();
@ -127,7 +122,7 @@ public class ModifyRequest {
@SuppressWarnings("unchecked")
public static <R extends HttpRequest> R addFormParam(R request, String key, Iterable<?> values) {
Multimap<String, String> map = request.getPayload() != null ? parseQueryToMap(request.getPayload()
.getRawContent().toString()) : LinkedHashMultimap.<String, String> create();
.getRawContent().toString()) : LinkedHashMultimap.<String, String> create();
for (Object o : values)
map.put(key, o.toString());
return (R) request.toBuilder().payload(newUrlEncodedFormPayload(map)).build();
@ -136,7 +131,7 @@ public class ModifyRequest {
@SuppressWarnings("unchecked")
public static <R extends HttpRequest> R putFormParams(R request, Multimap<String, String> params) {
Multimap<String, String> map = request.getPayload() != null ? parseQueryToMap(request.getPayload()
.getRawContent().toString()) : LinkedHashMultimap.<String, String> create();
.getRawContent().toString()) : LinkedHashMultimap.<String, String> create();
map.putAll(params);
return (R) request.toBuilder().payload(newUrlEncodedFormPayload(map)).build();
}
@ -167,9 +162,9 @@ public class ModifyRequest {
}
public static String makeQueryLine(Multimap<String, String> params,
@Nullable Comparator<Map.Entry<String, String>> sorter, char... skips) {
Iterator<Map.Entry<String, String>> pairs = ((sorter == null) ? params.entries() : sortEntries(params.entries(),
sorter)).iterator();
@Nullable Comparator<Map.Entry<String, String>> sorter, char... skips) {
Iterator<Map.Entry<String, String>> pairs = ((sorter == null) ? params.entries() : ImmutableSortedSet.copyOf(
sorter, params.entries())).iterator();
StringBuilder formBuilder = new StringBuilder();
while (pairs.hasNext()) {
Map.Entry<String, String> pair = pairs.next();
@ -183,12 +178,4 @@ public class ModifyRequest {
}
return formBuilder.toString();
}
public static SortedSet<Entry<String, String>> sortEntries(Collection<Map.Entry<String, String>> in,
Comparator<Map.Entry<String, String>> sorter) {
SortedSet<Entry<String, String>> entries = newTreeSet(sorter);
entries.addAll(in);
return entries;
}
}

View File

@ -69,7 +69,7 @@ public class FutureExceptionParserTest {
assertEquals(future.get(1, TimeUnit.SECONDS), "foo");
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@SuppressWarnings( { "unchecked", "rawtypes" })
private Future<?> createFuture(final Exception exception) {
ListenableFuture<?> future = Futures.makeListenable(executorService.submit(new Callable<String>() {
@ -77,6 +77,10 @@ public class FutureExceptionParserTest {
throw exception;
}
@Override
public String toString() {
return "throwException(" + exception + ")";
}
}), executorService);
future = new ExceptionParsingListenableFuture(future, new Function<Exception, String>() {