Use Map.entrySet where possible

Improves run-time efficiency and addresses FindBugs warnings.
This commit is contained in:
Andrew Gaul 2013-01-21 22:18:18 -08:00
parent b890e1d36b
commit af963df92d
27 changed files with 115 additions and 119 deletions

View File

@ -127,10 +127,10 @@ public class DeployVirtualMachineOptions extends AccountInDomainOptions {
*/ */
public DeployVirtualMachineOptions ipsToNetworks(Map<String, String> ipsToNetworks) { public DeployVirtualMachineOptions ipsToNetworks(Map<String, String> ipsToNetworks) {
int count = 0; int count = 0;
for (String ip : ipsToNetworks.keySet()) { for (Map.Entry<String, String> entry : ipsToNetworks.entrySet()) {
this.queryParameters.replaceValues(String.format("iptonetworklist[%d].ip", count), ImmutableSet.of(ip)); this.queryParameters.replaceValues(String.format("iptonetworklist[%d].ip", count), ImmutableSet.of(entry.getKey()));
this.queryParameters.replaceValues(String.format("iptonetworklist[%d].networkid", count), this.queryParameters.replaceValues(String.format("iptonetworklist[%d].networkid", count),
ImmutableSet.of("" + ipsToNetworks.get(ip))); ImmutableSet.of(entry.getValue()));
count += 1; count += 1;
} }
return this; return this;

View File

@ -169,7 +169,10 @@ public class EC2ComputeService extends BaseComputeService {
Map<String, ? extends NodeMetadata> instancesById = Maps.uniqueIndex(input, instanceId); Map<String, ? extends NodeMetadata> instancesById = Maps.uniqueIndex(input, instanceId);
ImmutableSet.Builder<NodeMetadata> builder = ImmutableSet.<NodeMetadata> builder(); ImmutableSet.Builder<NodeMetadata> builder = ImmutableSet.<NodeMetadata> builder();
if (generateInstanceNames && !common.containsKey("Name")) { if (generateInstanceNames && !common.containsKey("Name")) {
for (String id : instancesById.keySet()) { for (Map.Entry<String, ? extends NodeMetadata> entry : instancesById.entrySet()) {
String id = entry.getKey();
NodeMetadata instance = entry.getValue();
Map<String, String> tags = ImmutableMap.<String, String> builder().putAll(common) Map<String, String> tags = ImmutableMap.<String, String> builder().putAll(common)
.put("Name", id.replaceAll(".*-", group + "-")).build(); .put("Name", id.replaceAll(".*-", group + "-")).build();
logger.debug(">> applying tags %s to instance %s in region %s", tags, id, region); logger.debug(">> applying tags %s to instance %s in region %s", tags, id, region);

View File

@ -27,6 +27,7 @@ import static org.jclouds.ec2.compute.domain.RegionAndName.nameFunction;
import static org.jclouds.ec2.compute.domain.RegionAndName.regionFunction; import static org.jclouds.ec2.compute.domain.RegionAndName.regionFunction;
import java.util.Collection; import java.util.Collection;
import java.util.Map;
import java.util.Set; import java.util.Set;
import javax.annotation.Resource; import javax.annotation.Resource;
@ -68,8 +69,9 @@ public class PresentInstances implements Function<Set<RegionAndName>, Set<Runnin
Builder<RunningInstance> builder = ImmutableSet.<RunningInstance> builder(); Builder<RunningInstance> builder = ImmutableSet.<RunningInstance> builder();
Multimap<String, String> regionToInstanceIds = transformValues(index(regionAndIds, regionFunction()), Multimap<String, String> regionToInstanceIds = transformValues(index(regionAndIds, regionFunction()),
nameFunction()); nameFunction());
for (String region : regionToInstanceIds.keySet()) { for (Map.Entry<String, Collection<String>> entry : regionToInstanceIds.asMap().entrySet()) {
Collection<String> instanceIds = regionToInstanceIds.get(region); String region = entry.getKey();
Collection<String> instanceIds = entry.getValue();
logger.trace("looking for instances %s in region %s", instanceIds, region); logger.trace("looking for instances %s in region %s", instanceIds, region);
builder.addAll(concat(client.getInstanceServices().describeInstancesInRegion(region, builder.addAll(concat(client.getInstanceServices().describeInstancesInRegion(region,
toArray(instanceIds, String.class)))); toArray(instanceIds, String.class))));

View File

@ -188,14 +188,16 @@ public class EC2CreateNodesInGroupThenAddToSet implements CreateNodesInGroupThen
private void blockUntilRunningAndAssignElasticIpsToInstancesOrPutIntoBadMap(Set<RunningInstance> input, private void blockUntilRunningAndAssignElasticIpsToInstancesOrPutIntoBadMap(Set<RunningInstance> input,
Map<NodeMetadata, Exception> badNodes) { Map<NodeMetadata, Exception> badNodes) {
Map<RegionAndName, RunningInstance> instancesById = Maps.uniqueIndex(input, instanceToRegionAndName); Map<RegionAndName, RunningInstance> instancesById = Maps.uniqueIndex(input, instanceToRegionAndName);
for (RegionAndName id : instancesById.keySet()) { for (Map.Entry<RegionAndName, RunningInstance> entry : instancesById.entrySet()) {
RegionAndName id = entry.getKey();
RunningInstance instance = entry.getValue();
try { try {
logger.debug("<< allocating elastic IP instance(%s)", id); logger.debug("<< allocating elastic IP instance(%s)", id);
String ip = client.getElasticIPAddressServices().allocateAddressInRegion(id.getRegion()); String ip = client.getElasticIPAddressServices().allocateAddressInRegion(id.getRegion());
// block until instance is running // block until instance is running
logger.debug(">> awaiting status running instance(%s)", id); logger.debug(">> awaiting status running instance(%s)", id);
AtomicReference<NodeMetadata> node = newReference(runningInstanceToNodeMetadata AtomicReference<NodeMetadata> node = newReference(runningInstanceToNodeMetadata
.apply(instancesById.get(id))); .apply(instance));
nodeRunning.apply(node); nodeRunning.apply(node);
logger.trace("<< running instance(%s)", id); logger.trace("<< running instance(%s)", id);
logger.debug(">> associating elastic IP %s to instance %s", ip, id); logger.debug(">> associating elastic IP %s to instance %s", ip, id);

View File

@ -125,8 +125,9 @@ public class LocationIdToURIFromAccessForTypeAndVersion implements Supplier<Map<
@VisibleForTesting @VisibleForTesting
Map<String, Endpoint> firstEndpointInLocation(Multimap<String, Endpoint> locationToEndpoints) { Map<String, Endpoint> firstEndpointInLocation(Multimap<String, Endpoint> locationToEndpoints) {
Builder<String, Endpoint> locationToEndpointBuilder = ImmutableMap.<String, Endpoint> builder(); Builder<String, Endpoint> locationToEndpointBuilder = ImmutableMap.<String, Endpoint> builder();
for (String locationId : locationToEndpoints.keySet()) { for (Map.Entry<String, Collection<Endpoint>> entry : locationToEndpoints.asMap().entrySet()) {
Collection<Endpoint> endpoints = locationToEndpoints.get(locationId); String locationId = entry.getKey();
Collection<Endpoint> endpoints = entry.getValue();
switch (endpoints.size()) { switch (endpoints.size()) {
case 0: case 0:
logNoEndpointsInLocation(locationId); logNoEndpointsInLocation(locationId);
@ -141,8 +142,9 @@ public class LocationIdToURIFromAccessForTypeAndVersion implements Supplier<Map<
@VisibleForTesting @VisibleForTesting
Map<String, Endpoint> refineToVersionSpecificEndpoint(Multimap<String, Endpoint> locationToEndpoints) { Map<String, Endpoint> refineToVersionSpecificEndpoint(Multimap<String, Endpoint> locationToEndpoints) {
Builder<String, Endpoint> locationToEndpointBuilder = ImmutableMap.<String, Endpoint> builder(); Builder<String, Endpoint> locationToEndpointBuilder = ImmutableMap.<String, Endpoint> builder();
for (String locationId : locationToEndpoints.keySet()) { for (Map.Entry<String, Collection<Endpoint>> entry : locationToEndpoints.asMap().entrySet()) {
Collection<Endpoint> endpoints = locationToEndpoints.get(locationId); String locationId = entry.getKey();
Collection<Endpoint> endpoints = entry.getValue();
switch (endpoints.size()) { switch (endpoints.size()) {
case 0: case 0:
logNoEndpointsInLocation(locationId); logNoEndpointsInLocation(locationId);

View File

@ -23,6 +23,7 @@ import static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_S
import static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_TERMINATED; import static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_TERMINATED;
import static org.jclouds.openstack.nova.v2_0.predicates.KeyPairPredicates.nameMatches; import static org.jclouds.openstack.nova.v2_0.predicates.KeyPairPredicates.nameMatches;
import java.util.Collection;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
@ -124,8 +125,8 @@ public class NovaComputeService extends BaseComputeService {
@Override @Override
protected void cleanUpIncidentalResourcesOfDeadNodes(Set<? extends NodeMetadata> deadNodes) { protected void cleanUpIncidentalResourcesOfDeadNodes(Set<? extends NodeMetadata> deadNodes) {
Multimap<String, String> zoneToZoneAndGroupNames = orphanedGroupsByZoneId.apply(deadNodes); Multimap<String, String> zoneToZoneAndGroupNames = orphanedGroupsByZoneId.apply(deadNodes);
for (String zoneId : zoneToZoneAndGroupNames.keySet()) { for (Map.Entry<String, Collection<String>> entry : zoneToZoneAndGroupNames.asMap().entrySet()) {
cleanOrphanedGroupsInZone(ImmutableSet.copyOf(zoneToZoneAndGroupNames.get(zoneId)), zoneId); cleanOrphanedGroupsInZone(ImmutableSet.copyOf(entry.getValue()), entry.getKey());
} }
} }

View File

@ -105,14 +105,14 @@ public class HostAggregateApiLiveTest extends BaseNovaApiLiveTest {
HostAggregate details = api.setMetadata(testAggregate.getId(), theMetaData); HostAggregate details = api.setMetadata(testAggregate.getId(), theMetaData);
// bug in openstack - metadata values are never removed, so we just checking what we've set // bug in openstack - metadata values are never removed, so we just checking what we've set
for (String key : theMetaData.keySet()) { for (Map.Entry<String, String> entry : theMetaData.entrySet()) {
assertEquals(details.getMetadata().get(key), theMetaData.get(key)); assertEquals(details.getMetadata().get(entry.getKey()), entry.getValue());
} }
// Re-fetch to double-check // Re-fetch to double-check
details = api.get(testAggregate.getId()); details = api.get(testAggregate.getId());
for (String key : theMetaData.keySet()) { for (Map.Entry<String, String> entry : theMetaData.entrySet()) {
assertEquals(details.getMetadata().get(key), theMetaData.get(key)); assertEquals(details.getMetadata().get(entry.getKey()), entry.getValue());
} }
} }
} }

View File

@ -58,10 +58,10 @@ public class BindMetadataToJsonPayload implements Binder {
Map<String, String> metadata = (Map<String, String>) input; Map<String, String> metadata = (Map<String, String>) input;
List<Map<String, String>> clbMetadata = Lists.newArrayList(); List<Map<String, String>> clbMetadata = Lists.newArrayList();
for (String key: metadata.keySet()) { for (Map.Entry<String, String> entry : metadata.entrySet()) {
clbMetadata.add(ImmutableMap.<String, String> of( clbMetadata.add(ImmutableMap.<String, String> of(
"key", key, "key", entry.getKey(),
"value", metadata.get(key))); "value", entry.getValue()));
} }
String json = jsonBinder.toJson(ImmutableMap.of("metadata", clbMetadata)); String json = jsonBinder.toJson(ImmutableMap.of("metadata", clbMetadata));

View File

@ -59,12 +59,6 @@ public class Metadata extends ForwardingMap<String, String> {
} }
public Iterable<Integer> getIds() { public Iterable<Integer> getIds() {
Set<Integer> ids = Sets.newHashSet(); return Sets.newHashSet(keyToId.values());
for (String key: keyToId.keySet()) {
ids.add(keyToId.get(key));
}
return ids;
} }
} }

View File

@ -72,7 +72,9 @@ public class NodeApiLiveTest extends BaseCloudLoadBalancersApiLiveTest {
@Test(dependsOnMethods = "testCreateLoadBalancers") @Test(dependsOnMethods = "testCreateLoadBalancers")
public void testAddNodes() throws Exception { public void testAddNodes() throws Exception {
for (LoadBalancer lb : nodes.keySet()) { for (Map.Entry<LoadBalancer, Set<Node>> entry : nodes.entrySet()) {
LoadBalancer lb = entry.getKey();
Set<Node> nodeSet = entry.getValue();
String region = lb.getRegion(); String region = lb.getRegion();
Logger.getAnonymousLogger().info("starting node on loadbalancer " + lb.getId() + " in region " + region); Logger.getAnonymousLogger().info("starting node on loadbalancer " + lb.getId() + " in region " + region);
Set<Node> newNodes = clbApi.getNodeApiForZoneAndLoadBalancer(region, lb.getId()).add( Set<Node> newNodes = clbApi.getNodeApiForZoneAndLoadBalancer(region, lb.getId()).add(
@ -80,7 +82,7 @@ public class NodeApiLiveTest extends BaseCloudLoadBalancersApiLiveTest {
for (Node n : newNodes) { for (Node n : newNodes) {
assertEquals(n.getStatus(), Node.Status.ONLINE); assertEquals(n.getStatus(), Node.Status.ONLINE);
nodes.get(lb).add(n); nodeSet.add(n);
assertEquals(clbApi.getNodeApiForZoneAndLoadBalancer(region, lb.getId()).get(n.getId()).getStatus(), assertEquals(clbApi.getNodeApiForZoneAndLoadBalancer(region, lb.getId()).get(n.getId()).getStatus(),
Node.Status.ONLINE); Node.Status.ONLINE);
} }

View File

@ -260,8 +260,9 @@ public class CopyObjectOptions extends BaseHttpRequestOptions {
} }
if (metadata != null) { if (metadata != null) {
returnVal.put(METADATA_DIRECTIVE.replace(DEFAULT_AMAZON_HEADERTAG, headerTag), "REPLACE"); returnVal.put(METADATA_DIRECTIVE.replace(DEFAULT_AMAZON_HEADERTAG, headerTag), "REPLACE");
for (String key : metadata.keySet()) { for (Map.Entry<String, String> entry : metadata.entrySet()) {
returnVal.put(key.startsWith(metadataPrefix) ? key : metadataPrefix + key, metadata.get(key)); String key = entry.getKey();
returnVal.put(key.startsWith(metadataPrefix) ? key : metadataPrefix + key, entry.getValue());
} }
} }
return returnVal.build(); return returnVal.build();

View File

@ -23,6 +23,7 @@ import static org.jclouds.blobstore.options.ListContainerOptions.Builder.inDirec
import static org.jclouds.blobstore.options.ListContainerOptions.Builder.maxResults; import static org.jclouds.blobstore.options.ListContainerOptions.Builder.maxResults;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import java.io.InputStream;
import java.io.IOException; import java.io.IOException;
import java.util.Collection; import java.util.Collection;
import java.util.Map; import java.util.Map;
@ -204,10 +205,11 @@ public abstract class BaseBlobMapIntegrationTest extends BaseMapIntegrationTest<
try { try {
Map<String, Blob> map = createMap(view, bucketName); Map<String, Blob> map = createMap(view, bucketName);
ImmutableMap.Builder<String, Blob> newMap = ImmutableMap.builder(); ImmutableMap.Builder<String, Blob> newMap = ImmutableMap.builder();
for (String key : fiveInputs.keySet()) { for (Map.Entry<String, InputStream> entry : fiveInputs.entrySet()) {
String key = entry.getKey();
newMap.put( newMap.put(
key, key,
view.getBlobStore().blobBuilder(key).payload(fiveInputs.get(key)) view.getBlobStore().blobBuilder(key).payload(entry.getValue())
.contentLength((long) fiveBytes.get(key).length).build()); .contentLength((long) fiveBytes.get(key).length).build());
} }
map.putAll(newMap.build()); map.putAll(newMap.build());

View File

@ -22,6 +22,7 @@ import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static org.jclouds.aws.reference.AWSConstants.PROPERTY_HEADER_TAG; import static org.jclouds.aws.reference.AWSConstants.PROPERTY_HEADER_TAG;
import java.util.Collection;
import java.util.Map; import java.util.Map;
import javax.annotation.Resource; import javax.annotation.Resource;
@ -169,10 +170,10 @@ public class AWSUtils {
Multimap<Object, Object> map = (Multimap<Object, Object>) input; Multimap<Object, Object> map = (Multimap<Object, Object>) input;
Builder<String, String> builder = ImmutableMultimap.builder(); Builder<String, String> builder = ImmutableMultimap.builder();
int i = 1; int i = 1;
for (Object k : map.keySet()) { for (Map.Entry<Object, Collection<Object>> entry : map.asMap().entrySet()) {
builder.put(prefix + "." + i + "." + keySuffix, checkNotNull(k.toString(), keySuffix.toLowerCase() + "s[" + i + "]")); builder.put(prefix + "." + i + "." + keySuffix, checkNotNull(entry.getKey().toString(), keySuffix.toLowerCase() + "s[" + i + "]"));
int j = 1; int j = 1;
for (Object v : map.get(k)) { for (Object v : entry.getValue()) {
builder.put(prefix + "." + i + "." + valueSuffix + "." + j, v.toString()); builder.put(prefix + "." + i + "." + valueSuffix + "." + j, v.toString());
j++; j++;
} }
@ -187,11 +188,12 @@ public class AWSUtils {
Map<Object, Iterable<Object>> map = (Map<Object, Iterable<Object>>) input; Map<Object, Iterable<Object>> map = (Map<Object, Iterable<Object>>) input;
Builder<String, String> builder = ImmutableMultimap.builder(); Builder<String, String> builder = ImmutableMultimap.builder();
int i = 1; int i = 1;
for (Object k : map.keySet()) { for (Map.Entry<Object, Iterable<Object>> entry : map.entrySet()) {
builder.put(prefix + "." + i + "." + keySuffix, checkNotNull(k.toString(), keySuffix.toLowerCase() + "s[" + i + "]")); builder.put(prefix + "." + i + "." + keySuffix, checkNotNull(entry.getKey().toString(), keySuffix.toLowerCase() + "s[" + i + "]"));
if (!Iterables.isEmpty(map.get(k))) { Iterable<Object> iterable = entry.getValue();
if (!Iterables.isEmpty(iterable)) {
int j = 1; int j = 1;
for (Object v : map.get(k)) { for (Object v : iterable) {
builder.put(prefix + "." + i + "." + valueSuffix + "." + j, v.toString()); builder.put(prefix + "." + i + "." + valueSuffix + "." + j, v.toString());
j++; j++;
} }

View File

@ -25,6 +25,7 @@ import static org.jclouds.http.utils.Queries.queryParser;
import static org.jclouds.io.Payloads.newUrlEncodedFormPayload; import static org.jclouds.io.Payloads.newUrlEncodedFormPayload;
import java.net.URI; import java.net.URI;
import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -188,8 +189,8 @@ public class HttpRequest extends HttpMessage {
checkNotNull(endpoint, "endpoint"); checkNotNull(endpoint, "endpoint");
Multimap<String, String> map = payload != null ? queryParser().apply(payload.getRawContent().toString()) Multimap<String, String> map = payload != null ? queryParser().apply(payload.getRawContent().toString())
: LinkedHashMultimap.<String, String> create(); : LinkedHashMultimap.<String, String> create();
for (String key : parameters.keySet()) { for (Map.Entry<String, Collection<String>> entry : parameters.asMap().entrySet()) {
map.replaceValues(key, parameters.get(key)); map.replaceValues(entry.getKey(), entry.getValue());
} }
payload = newUrlEncodedFormPayload(map); payload = newUrlEncodedFormPayload(map);
return self(); return self();

View File

@ -84,8 +84,9 @@ public class ZoneToRegionToProviderOrJustProvider implements LocationsSupplier {
Builder<Location> locations = ImmutableSet.builder(); Builder<Location> locations = ImmutableSet.builder();
if (!Iterables.all(regionsOrJustProvider, LocationPredicates.isProvider())) if (!Iterables.all(regionsOrJustProvider, LocationPredicates.isProvider()))
locations.addAll(regionsOrJustProvider); locations.addAll(regionsOrJustProvider);
for (String zoneId : zoneIdToParent.keySet()) { for (Map.Entry<String, Location> entry : zoneIdToParent.entrySet()) {
Location parent = zoneIdToParent.get(zoneId); String zoneId = entry.getKey();
Location parent = entry.getValue();
LocationBuilder builder = new LocationBuilder().scope(LocationScope.ZONE).id(zoneId).description(zoneId) LocationBuilder builder = new LocationBuilder().scope(LocationScope.ZONE).id(zoneId).description(zoneId)
.parent(parent); .parent(parent);
if (isoCodesById.containsKey(zoneId)) if (isoCodesById.containsKey(zoneId))

View File

@ -94,8 +94,8 @@ public class RestModule extends AbstractModule {
static Cache<Invokable<?, ?>, Invokable<?, ?>> seedKnownSync2AsyncInvokables(Map<Class<?>, Class<?>> sync2Async) { static Cache<Invokable<?, ?>, Invokable<?, ?>> seedKnownSync2AsyncInvokables(Map<Class<?>, Class<?>> sync2Async) {
Cache<Invokable<?, ?>, Invokable<?, ?>> sync2AsyncBuilder = CacheBuilder.newBuilder().build(); Cache<Invokable<?, ?>, Invokable<?, ?>> sync2AsyncBuilder = CacheBuilder.newBuilder().build();
putInvokables(HttpClient.class, HttpAsyncClient.class, sync2AsyncBuilder); putInvokables(HttpClient.class, HttpAsyncClient.class, sync2AsyncBuilder);
for (Class<?> s : sync2Async.keySet()) { for (Map.Entry<Class<?>, Class<?>> entry : sync2Async.entrySet()) {
putInvokables(s, sync2Async.get(s), sync2AsyncBuilder); putInvokables(entry.getKey(), entry.getValue(), sync2AsyncBuilder);
} }
return sync2AsyncBuilder; return sync2AsyncBuilder;
} }

View File

@ -440,10 +440,11 @@ public abstract class BaseRestApiExpectTest<S> {
public HttpResponse apply(HttpRequest input) { public HttpResponse apply(HttpRequest input) {
HttpRequest matchedRequest = null; HttpRequest matchedRequest = null;
HttpResponse response = null; HttpResponse response = null;
for (HttpRequest request : requestToResponse.keySet()) { for (Map.Entry<HttpRequest, HttpResponse> entry : requestToResponse.entrySet()) {
HttpRequest request = entry.getKey();
if (httpRequestsAreEqual(input, request)) { if (httpRequestsAreEqual(input, request)) {
matchedRequest = request; matchedRequest = request;
response = requestToResponse.get(request); response = entry.getValue();
} }
} }

View File

@ -122,11 +122,11 @@ public class ApacheHCUtils {
apacheRequest.addHeader(HttpHeaders.CONTENT_LENGTH, "0"); apacheRequest.addHeader(HttpHeaders.CONTENT_LENGTH, "0");
} }
for (String header : request.getHeaders().keySet()) { for (Map.Entry<String, String> entry : request.getHeaders().entries()) {
for (String value : request.getHeaders().get(header)) String header = entry.getKey();
// apache automatically tries to add content length header // apache automatically tries to add content length header
if (!header.equals(HttpHeaders.CONTENT_LENGTH)) if (!header.equals(HttpHeaders.CONTENT_LENGTH))
apacheRequest.addHeader(header, value); apacheRequest.addHeader(header, entry.getValue());
} }
apacheRequest.addHeader(HttpHeaders.USER_AGENT, USER_AGENT); apacheRequest.addHeader(HttpHeaders.USER_AGENT, USER_AGENT);
return apacheRequest; return apacheRequest;

View File

@ -25,6 +25,7 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.net.URL; import java.net.URL;
import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Set; import java.util.Set;
@ -87,11 +88,10 @@ public class ConvertToGaeRequest implements Function<HttpRequest, HTTPRequest> {
HTTPRequest gaeRequest = new HTTPRequest(url, HTTPMethod.valueOf(request.getMethod().toString()), options); HTTPRequest gaeRequest = new HTTPRequest(url, HTTPMethod.valueOf(request.getMethod().toString()), options);
for (String header : request.getHeaders().keySet()) { for (Entry<String, String> entry : request.getHeaders().entries()) {
for (String value : request.getHeaders().get(header)) { String header = entry.getKey();
if (!prohibitedHeaders.contains(header)) if (!prohibitedHeaders.contains(header))
gaeRequest.addHeader(new HTTPHeader(header, value)); gaeRequest.addHeader(new HTTPHeader(header, entry.getValue()));
}
} }
gaeRequest.addHeader(new HTTPHeader(HttpHeaders.USER_AGENT, USER_AGENT)); gaeRequest.addHeader(new HTTPHeader(HttpHeaders.USER_AGENT, USER_AGENT));
/** /**

View File

@ -192,10 +192,9 @@ public class CDMIObject {
userMetaDataIn = Maps.newHashMap(); userMetaDataIn = Maps.newHashMap();
systemMetaDataIn = Maps.newHashMap(); systemMetaDataIn = Maps.newHashMap();
aclMetaDataIn = Lists.newArrayList(); aclMetaDataIn = Lists.newArrayList();
Iterator<String> keys = metadata.keySet().iterator(); for (Map.Entry<String, JsonBall> entry : metadata.entrySet()) {
while (keys.hasNext()) { String key = entry.getKey();
String key = keys.next(); JsonBall value = entry.getValue();
JsonBall value = metadata.get(key);
if (key.startsWith("cdmi")) { if (key.startsWith("cdmi")) {
if (key.matches("cdmi_acl")) { if (key.matches("cdmi_acl")) {
String[] cdmi_acl_array = value.toString().split("[{}]"); String[] cdmi_acl_array = value.toString().split("[{}]");

View File

@ -48,7 +48,6 @@ public class ContainerApiLiveTest extends BaseCDMIApiLiveTest {
public void testCreateContainer() throws Exception { public void testCreateContainer() throws Exception {
String pContainerName = "MyContainer" + System.currentTimeMillis() + "/"; String pContainerName = "MyContainer" + System.currentTimeMillis() + "/";
Map<String, String> pContainerMetaDataIn = Maps.newHashMap(); Map<String, String> pContainerMetaDataIn = Maps.newHashMap();
Iterator<String> keys;
pContainerMetaDataIn.put("containerkey1", "value1"); pContainerMetaDataIn.put("containerkey1", "value1");
pContainerMetaDataIn.put("containerkey2", "value2"); pContainerMetaDataIn.put("containerkey2", "value2");
pContainerMetaDataIn.put("containerkey3", "value3"); pContainerMetaDataIn.put("containerkey3", "value3");
@ -76,19 +75,15 @@ public class ContainerApiLiveTest extends BaseCDMIApiLiveTest {
System.out.println("Children: " + container.getChildren()); System.out.println("Children: " + container.getChildren());
assertNotNull(container.getMetadata()); assertNotNull(container.getMetadata());
System.out.println("Raw metadata: " + container.getMetadata()); System.out.println("Raw metadata: " + container.getMetadata());
keys = container.getMetadata().keySet().iterator(); for (Map.Entry<String, JsonBall> entry : container.getMetadata().entrySet()) {
while (keys.hasNext()) { System.out.println(entry.getKey() + ":" + entry.getValue());
String key = keys.next();
JsonBall value = container.getMetadata().get(key);
System.out.println(key + ":" + value);
} }
assertNotNull(container.getUserMetadata()); assertNotNull(container.getUserMetadata());
Map<String, String> pContainerMetaDataOut = container.getUserMetadata(); Map<String, String> pContainerMetaDataOut = container.getUserMetadata();
keys = pContainerMetaDataIn.keySet().iterator(); for (Map.Entry<String, String> entry : pContainerMetaDataIn.entrySet()) {
while (keys.hasNext()) { String key = entry.getKey();
String key = keys.next();
assertEquals(pContainerMetaDataOut.containsKey(key), true); assertEquals(pContainerMetaDataOut.containsKey(key), true);
assertEquals(pContainerMetaDataOut.get(key), pContainerMetaDataIn.get(key)); assertEquals(pContainerMetaDataOut.get(key), entry.getValue());
} }
System.out.println("UserMetaData: " + container.getUserMetadata()); System.out.println("UserMetaData: " + container.getUserMetadata());
assertNotNull(container.getSystemMetadata()); assertNotNull(container.getSystemMetadata());
@ -136,7 +131,6 @@ public class ContainerApiLiveTest extends BaseCDMIApiLiveTest {
public void testGetContainer() throws Exception { public void testGetContainer() throws Exception {
String pContainerName = "MyContainer" + System.currentTimeMillis() + "/"; String pContainerName = "MyContainer" + System.currentTimeMillis() + "/";
Map<String, String> pContainerMetaDataIn = Maps.newHashMap(); Map<String, String> pContainerMetaDataIn = Maps.newHashMap();
Iterator<String> keys;
pContainerMetaDataIn.put("containerkey1", "value1"); pContainerMetaDataIn.put("containerkey1", "value1");
pContainerMetaDataIn.put("containerkey2", "value2"); pContainerMetaDataIn.put("containerkey2", "value2");
pContainerMetaDataIn.put("containerkey3", "value3"); pContainerMetaDataIn.put("containerkey3", "value3");
@ -163,19 +157,15 @@ public class ContainerApiLiveTest extends BaseCDMIApiLiveTest {
System.out.println("Children: " + container.getChildren()); System.out.println("Children: " + container.getChildren());
assertNotNull(container.getMetadata()); assertNotNull(container.getMetadata());
System.out.println("Raw metadata: " + container.getMetadata()); System.out.println("Raw metadata: " + container.getMetadata());
keys = container.getMetadata().keySet().iterator(); for (Map.Entry<String, JsonBall> entry : container.getMetadata().entrySet()) {
while (keys.hasNext()) { System.out.println(entry.getKey() + ":" + entry.getValue());
String key = keys.next();
JsonBall value = container.getMetadata().get(key);
System.out.println(key + ":" + value);
} }
assertNotNull(container.getUserMetadata()); assertNotNull(container.getUserMetadata());
Map<String, String> pContainerMetaDataOut = container.getUserMetadata(); Map<String, String> pContainerMetaDataOut = container.getUserMetadata();
keys = pContainerMetaDataIn.keySet().iterator(); for (Map.Entry<String, String> entry : pContainerMetaDataIn.entrySet()) {
while (keys.hasNext()) { String key = entry.getKey();
String key = keys.next();
assertEquals(pContainerMetaDataOut.containsKey(key), true); assertEquals(pContainerMetaDataOut.containsKey(key), true);
assertEquals(pContainerMetaDataOut.get(key), pContainerMetaDataIn.get(key)); assertEquals(pContainerMetaDataOut.get(key), entry.getValue());
} }
System.out.println("UserMetaData: " + container.getUserMetadata()); System.out.println("UserMetaData: " + container.getUserMetadata());
assertNotNull(container.getSystemMetadata()); assertNotNull(container.getSystemMetadata());
@ -202,11 +192,10 @@ public class ContainerApiLiveTest extends BaseCDMIApiLiveTest {
container = api.get(pContainerName, ContainerQueryParams.Builder.metadata()); container = api.get(pContainerName, ContainerQueryParams.Builder.metadata());
assertNotNull(container); assertNotNull(container);
pContainerMetaDataOut = container.getUserMetadata(); pContainerMetaDataOut = container.getUserMetadata();
keys = pContainerMetaDataIn.keySet().iterator(); for (Map.Entry<String, String> entry : pContainerMetaDataIn.entrySet()) {
while (keys.hasNext()) { String key = entry.getKey();
String key = keys.next();
assertEquals(pContainerMetaDataOut.containsKey(key), true); assertEquals(pContainerMetaDataOut.containsKey(key), true);
assertEquals(pContainerMetaDataOut.get(key), pContainerMetaDataIn.get(key)); assertEquals(pContainerMetaDataOut.get(key), entry.getValue());
} }
System.out.println(container); System.out.println(container);

View File

@ -66,7 +66,6 @@ public class DataApiLiveTest extends BaseCDMIApiLiveTest {
CreateDataObjectOptions pCreateDataObjectOptions; CreateDataObjectOptions pCreateDataObjectOptions;
DataObject dataObject; DataObject dataObject;
Iterator<String> keys;
Map<String, String> dataObjectMetaDataOut; Map<String, String> dataObjectMetaDataOut;
Map<String, String> pContainerMetaDataIn = Maps.newHashMap(); Map<String, String> pContainerMetaDataIn = Maps.newHashMap();
Map<String, String> pDataObjectMetaDataIn = Maps.newLinkedHashMap(); Map<String, String> pDataObjectMetaDataIn = Maps.newLinkedHashMap();
@ -101,11 +100,10 @@ public class DataApiLiveTest extends BaseCDMIApiLiveTest {
assertEquals(dataObject.getValueAsString(), value); assertEquals(dataObject.getValueAsString(), value);
dataObjectMetaDataOut = dataObject.getUserMetadata(); dataObjectMetaDataOut = dataObject.getUserMetadata();
assertNotNull(dataObjectMetaDataOut); assertNotNull(dataObjectMetaDataOut);
keys = pDataObjectMetaDataIn.keySet().iterator(); for (Map.Entry<String, String> entry : pDataObjectMetaDataIn.entrySet()) {
while (keys.hasNext()) { String key = entry.getKey();
String key = keys.next();
assertEquals(dataObjectMetaDataOut.containsKey(key), true); assertEquals(dataObjectMetaDataOut.containsKey(key), true);
assertEquals(dataObjectMetaDataOut.get(key), pDataObjectMetaDataIn.get(key)); assertEquals(dataObjectMetaDataOut.get(key), entry.getValue());
} }
assertEquals(Integer.parseInt(dataObject.getSystemMetadata().get("cdmi_size")), value.length()); assertEquals(Integer.parseInt(dataObject.getSystemMetadata().get("cdmi_size")), value.length());
assertEquals(dataObject.getObjectName(), dataObjectNameIn); assertEquals(dataObject.getObjectName(), dataObjectNameIn);
@ -130,11 +128,10 @@ public class DataApiLiveTest extends BaseCDMIApiLiveTest {
assertEquals(dataObject.getValueAsString(), value); assertEquals(dataObject.getValueAsString(), value);
dataObjectMetaDataOut = dataObject.getUserMetadata(); dataObjectMetaDataOut = dataObject.getUserMetadata();
assertNotNull(dataObjectMetaDataOut); assertNotNull(dataObjectMetaDataOut);
keys = pDataObjectMetaDataIn.keySet().iterator(); for (Map.Entry<String, String> entry : pDataObjectMetaDataIn.entrySet()) {
while (keys.hasNext()) { String key = entry.getKey();
String key = keys.next();
assertEquals(dataObjectMetaDataOut.containsKey(key), true); assertEquals(dataObjectMetaDataOut.containsKey(key), true);
assertEquals(dataObjectMetaDataOut.get(key), pDataObjectMetaDataIn.get(key)); assertEquals(dataObjectMetaDataOut.get(key), entry.getValue());
} }
assertEquals(Integer.parseInt(dataObject.getSystemMetadata().get("cdmi_size")), value.length()); assertEquals(Integer.parseInt(dataObject.getSystemMetadata().get("cdmi_size")), value.length());
assertEquals(dataObject.getObjectName(), dataObjectNameIn); assertEquals(dataObject.getObjectName(), dataObjectNameIn);
@ -484,7 +481,6 @@ public class DataApiLiveTest extends BaseCDMIApiLiveTest {
CreateDataObjectOptions pCreateDataObjectOptions; CreateDataObjectOptions pCreateDataObjectOptions;
DataObject dataObject; DataObject dataObject;
Iterator<String> keys;
Map<String, String> dataObjectMetaDataOut; Map<String, String> dataObjectMetaDataOut;
Map<String, String> pContainerMetaDataIn = Maps.newHashMap(); Map<String, String> pContainerMetaDataIn = Maps.newHashMap();
Map<String, String> pDataObjectMetaDataIn = Maps.newLinkedHashMap(); Map<String, String> pDataObjectMetaDataIn = Maps.newLinkedHashMap();
@ -519,11 +515,10 @@ public class DataApiLiveTest extends BaseCDMIApiLiveTest {
assertEquals(dataObject.getValueAsString(), value); assertEquals(dataObject.getValueAsString(), value);
dataObjectMetaDataOut = dataObject.getUserMetadata(); dataObjectMetaDataOut = dataObject.getUserMetadata();
assertNotNull(dataObjectMetaDataOut); assertNotNull(dataObjectMetaDataOut);
keys = pDataObjectMetaDataIn.keySet().iterator(); for (Map.Entry<String, String> entry : pDataObjectMetaDataIn.entrySet()) {
while (keys.hasNext()) { String key = entry.getKey();
String key = keys.next();
assertEquals(dataObjectMetaDataOut.containsKey(key), true); assertEquals(dataObjectMetaDataOut.containsKey(key), true);
assertEquals(dataObjectMetaDataOut.get(key), pDataObjectMetaDataIn.get(key)); assertEquals(dataObjectMetaDataOut.get(key), entry.getValue());
} }
assertEquals(Integer.parseInt(dataObject.getSystemMetadata().get("cdmi_size")), value.length()); assertEquals(Integer.parseInt(dataObject.getSystemMetadata().get("cdmi_size")), value.length());
assertEquals(dataObject.getObjectName(), dataObjectNameIn); assertEquals(dataObject.getObjectName(), dataObjectNameIn);
@ -560,11 +555,10 @@ public class DataApiLiveTest extends BaseCDMIApiLiveTest {
assertEquals(dataObject.getMimetype(), "text/plain"); assertEquals(dataObject.getMimetype(), "text/plain");
dataObjectMetaDataOut = dataObject.getUserMetadata(); dataObjectMetaDataOut = dataObject.getUserMetadata();
assertNotNull(dataObjectMetaDataOut); assertNotNull(dataObjectMetaDataOut);
keys = pDataObjectMetaDataIn.keySet().iterator(); for (Map.Entry<String, String> entry : pDataObjectMetaDataIn.entrySet()) {
while (keys.hasNext()) { String key = entry.getKey();
String key = keys.next();
assertEquals(dataObjectMetaDataOut.containsKey(key), true); assertEquals(dataObjectMetaDataOut.containsKey(key), true);
assertEquals(dataObjectMetaDataOut.get(key), pDataObjectMetaDataIn.get(key)); assertEquals(dataObjectMetaDataOut.get(key), entry.getValue());
} }
assertEquals(Integer.parseInt(dataObject.getSystemMetadata().get("cdmi_size")), value.length()); assertEquals(Integer.parseInt(dataObject.getSystemMetadata().get("cdmi_size")), value.length());

View File

@ -23,6 +23,7 @@ import static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_R
import static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_SUSPENDED; import static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_SUSPENDED;
import static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_TERMINATED; import static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_TERMINATED;
import java.util.Collection;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
@ -119,8 +120,8 @@ public class JoyentCloudComputeService extends BaseComputeService {
@Override @Override
protected void cleanUpIncidentalResourcesOfDeadNodes(Set<? extends NodeMetadata> deadNodes) { protected void cleanUpIncidentalResourcesOfDeadNodes(Set<? extends NodeMetadata> deadNodes) {
Multimap<String, String> zoneToZoneAndGroupNames = orphanedGroupsByDatacenterId.apply(deadNodes); Multimap<String, String> zoneToZoneAndGroupNames = orphanedGroupsByDatacenterId.apply(deadNodes);
for (String datacenterId : zoneToZoneAndGroupNames.keySet()) { for (Map.Entry<String, Collection<String>> entry : zoneToZoneAndGroupNames.asMap().entrySet()) {
cleanupOrphanedKeysInZone(ImmutableSet.copyOf(zoneToZoneAndGroupNames.get(datacenterId)), datacenterId); cleanupOrphanedKeysInZone(ImmutableSet.copyOf(entry.getValue()), entry.getKey());
} }
} }

View File

@ -30,6 +30,7 @@ import static org.jclouds.ec2.compute.domain.RegionAndName.nameFunction;
import static org.jclouds.ec2.compute.domain.RegionAndName.regionFunction; import static org.jclouds.ec2.compute.domain.RegionAndName.regionFunction;
import java.util.Collection; import java.util.Collection;
import java.util.Map;
import java.util.Set; import java.util.Set;
import javax.inject.Singleton; import javax.inject.Singleton;
@ -79,8 +80,9 @@ public class PresentSpotRequestsAndInstances extends PresentInstances {
protected Set<RunningInstance> getSpots(Set<RegionAndName> regionAndIds) { protected Set<RunningInstance> getSpots(Set<RegionAndName> regionAndIds) {
Builder<RunningInstance> builder = ImmutableSet.<RunningInstance> builder(); Builder<RunningInstance> builder = ImmutableSet.<RunningInstance> builder();
Multimap<String, String> regionToSpotIds = transformValues(index(regionAndIds, regionFunction()), nameFunction()); Multimap<String, String> regionToSpotIds = transformValues(index(regionAndIds, regionFunction()), nameFunction());
for (String region : regionToSpotIds.keySet()) { for (Map.Entry<String, Collection<String>> entry : regionToSpotIds.asMap().entrySet()) {
Collection<String> spotIds = regionToSpotIds.get(region); String region = entry.getKey();
Collection<String> spotIds = entry.getValue();
logger.trace("looking for spots %s in region %s", spotIds, region); logger.trace("looking for spots %s in region %s", spotIds, region);
builder.addAll(transform( builder.addAll(transform(
client.getSpotInstanceServices().describeSpotInstanceRequestsInRegion(region, client.getSpotInstanceServices().describeSpotInstanceRequestsInRegion(region,

View File

@ -50,7 +50,8 @@ public class CreateServerOptions implements MapBinder {
"this binder is only valid for GeneratedHttpRequests!"); "this binder is only valid for GeneratedHttpRequests!");
GeneratedHttpRequest gRequest = (GeneratedHttpRequest) request; GeneratedHttpRequest gRequest = (GeneratedHttpRequest) request;
ImmutableMultimap.Builder<String, String> formParams = ImmutableMultimap.builder(); ImmutableMultimap.Builder<String, String> formParams = ImmutableMultimap.builder();
for(String key : postParams.keySet()) formParams.put(key, (String) postParams.get(key)); for (Map.Entry<String, Object> entry : postParams.entrySet())
formParams.put(entry.getKey(), (String) entry.getValue());
ServerSpec serverSpec = ServerSpec.class.cast(find(gRequest.getInvocation().getArgs(), ServerSpec serverSpec = ServerSpec.class.cast(find(gRequest.getInvocation().getArgs(),
instanceOf(ServerSpec.class))); instanceOf(ServerSpec.class)));
formParams.put("datacenter", serverSpec.getDatacenter()); formParams.put("datacenter", serverSpec.getDatacenter());

View File

@ -51,12 +51,10 @@ public class BindAttributesToIndexedFormParams implements Binder {
Builder<String, String> builder = ImmutableMultimap.builder(); Builder<String, String> builder = ImmutableMultimap.builder();
int amazonOneBasedIndex = 1; // according to docs, counters must start with 1 int amazonOneBasedIndex = 1; // according to docs, counters must start with 1
for (String itemName : attributeMap.getAttributes().keySet()) { for (Map.Entry<String, Collection<AttributePair>> entry : attributeMap.getAttributes().entrySet());
String itemName = entry.getKey();
Collection<AttributePair> c = attributeMap.getAttributes().get(itemName); for (AttributePair attr : = entry.getValue()) {
Iterator<AttributePair> it = c.iterator();
while (it.hasNext()) {
AttributePair attr = it.next();
// not null by contract // not null by contract
String value = attr.getValue(); String value = attr.getValue();

View File

@ -156,10 +156,8 @@ public class NingHttpCommandExecutorService implements HttpCommandExecutorServic
} }
builder.addHeader(HttpHeaders.USER_AGENT, USER_AGENT); builder.addHeader(HttpHeaders.USER_AGENT, USER_AGENT);
for (String header : request.getHeaders().keySet()) { for (Map<String, String> entry : request.getHeaders().entries()) {
for (String value : request.getHeaders().get(header)) { builder.addHeader(entry.getKey(), entry.getValue());
builder.addHeader(header, value);
}
} }
return builder.build(); return builder.build();