Prefer isEmpty() for collections rather than size()

This commit is contained in:
Jeremy Daggett 2014-08-13 13:16:43 -07:00 committed by Jeremy Daggett
parent 192785dbae
commit e711275fb1
165 changed files with 616 additions and 620 deletions

View File

@ -35,7 +35,7 @@ import com.google.common.collect.Multimaps;
@Singleton
public class BindUserMetadataToHeaders implements Binder, Function<UserMetadata, Map<String, String>> {
@SuppressWarnings("unchecked")
@Override
public <R extends HttpRequest> R bindToRequest(R request, Object input) {
@ -48,19 +48,19 @@ public class BindUserMetadataToHeaders implements Binder, Function<UserMetadata,
@Override
public Map<String, String> apply(UserMetadata md) {
Builder<String, String> headers = ImmutableMap.builder();
if (md.getMetadata().size() > 0) {
if (!md.getMetadata().isEmpty()) {
String header = Joiner.on(',').withKeyValueSeparator("=").join(md.getMetadata());
headers.put("x-emc-meta", header);
}
if (md.getListableMetadata().size() > 0) {
if (!md.getListableMetadata().isEmpty()) {
String header = Joiner.on(',').withKeyValueSeparator("=").join(md.getListableMetadata());
headers.put("x-emc-listable-meta", header);
}
if (md.getTags().size() > 0) {
if (!md.getTags().isEmpty()) {
String header = Joiner.on(',').join(md.getTags());
headers.put("x-emc-tags", header);
}
if (md.getListableTags().size() > 0) {
if (!md.getListableTags().isEmpty()) {
String header = Joiner.on(',').join(md.getListableTags());
headers.put("x-emc-listable-tags", header);
}

View File

@ -98,7 +98,7 @@ public class BYONComputeServiceAdapter implements JCloudsNativeComputeServiceAda
return arg0.getLocationId();
}
}), Predicates.notNull()));
if (zones.size() == 0)
if (zones.isEmpty())
return locations.add(provider).build();
else
for (String zone : zones) {
@ -110,7 +110,7 @@ public class BYONComputeServiceAdapter implements JCloudsNativeComputeServiceAda
@Override
public NodeMetadata getNode(String id) {
Node node = null;
try {
node = nodes.get().getUnchecked(id);
@ -124,7 +124,7 @@ public class BYONComputeServiceAdapter implements JCloudsNativeComputeServiceAda
public Image getImage(final String id) {
throw new UnsupportedOperationException();
}
@Override
public void destroyNode(final String id) {
throw new UnsupportedOperationException();

View File

@ -92,9 +92,9 @@ public class CreateServerOptions implements MapBinder {
ServerRequest server = new ServerRequest(checkNotNull(postParams.get("name"), "name parameter not present").toString(),
Integer.parseInt(checkNotNull(postParams.get("imageId"), "imageId parameter not present").toString()),
Integer.parseInt(checkNotNull(postParams.get("flavorId"), "flavorId parameter not present").toString()));
if (metadata.size() > 0)
if (!metadata.isEmpty())
server.metadata = metadata;
if (files.size() > 0)
if (!files.isEmpty())
server.personality = files;
if (sharedIpGroupId != null)
server.sharedIpGroupId = this.sharedIpGroupId;
@ -130,16 +130,16 @@ public class CreateServerOptions implements MapBinder {
* group. Any server in a group can share one or more public IPs with any other server in the
* group. With the exception of the first server in a shared IP group, servers must be launched
* into shared IP groups. A server may only be a member of one shared IP group.
*
*
* <p/>
* Servers in the same shared IP group can share public IPs for various high availability and
* load balancing configurations. To launch an HA server, include the optional sharedIpGroupId
* element and the server will be launched into that shared IP group.
* <p />
*
*
* Note: sharedIpGroupId is an optional parameter and for optimal performance, should ONLY be
* specified when intending to share IPs between servers.
*
*
* @see #withSharedIp(String)
*/
public CreateServerOptions withSharedIpGroup(int id) {
@ -177,7 +177,7 @@ public class CreateServerOptions implements MapBinder {
* specify that the target server network configuration be modified). Shared IP addresses can be
* used with many standard heartbeat facilities (e.g. keepalived) that monitor for failure and
* manage IP failover.
*
*
* <p/>
* If you intend to use a shared IP on the server being created and have no need for a separate
* public IP address, you may launch the server into a shared IP group and specify an IP address

View File

@ -94,8 +94,8 @@ public class CloudServersClientLiveTest extends BaseComputeServiceContextLiveTes
public void testLimits() throws Exception {
Limits response = client.getLimits();
assert null != response;
assertTrue(response.getAbsolute().size() > 0);
assertTrue(response.getRate().size() > 0);
assertTrue(!response.getAbsolute().isEmpty());
assertTrue(!response.getRate().isEmpty());
}
public void testListServers() throws Exception {

View File

@ -39,11 +39,11 @@ public class BaseDriveToMap implements Function<Drive, Map<String, String>> {
builder.put("size", from.getSize() + "");
if (from.getClaimType() != ClaimType.EXCLUSIVE)
builder.put("claim:type", from.getClaimType().toString());
if (from.getTags().size() != 0)
if (!from.getTags().isEmpty())
builder.put("tags", Joiner.on(' ').join(from.getTags()));
if (from.getReaders().size() != 0)
if (!from.getReaders().isEmpty())
builder.put("readers", Joiner.on(' ').join(from.getReaders()));
if (from.getUse().size() != 0)
if (!from.getUse().isEmpty())
builder.put("use", Joiner.on(' ').join(from.getUse()));
return builder.build();
}

View File

@ -39,7 +39,7 @@ public class KeyValuesDelimitedByBlankLinesToDriveInfo implements Function<HttpR
@Override
public DriveInfo apply(HttpResponse response) {
Set<DriveInfo> drives = setParser.apply(response);
if (drives.size() == 0)
if (drives.isEmpty())
return null;
return Iterables.get(drives, 0);
}

View File

@ -39,7 +39,7 @@ public class KeyValuesDelimitedByBlankLinesToProfileInfo implements Function<Htt
@Override
public ProfileInfo apply(HttpResponse response) {
Set<ProfileInfo> drives = setParser.apply(response);
if (drives.size() == 0)
if (drives.isEmpty())
return null;
return Iterables.get(drives, 0);
}

View File

@ -39,7 +39,7 @@ public class KeyValuesDelimitedByBlankLinesToServerInfo implements Function<Http
@Override
public ServerInfo apply(HttpResponse response) {
Set<ServerInfo> drives = setParser.apply(response);
if (drives.size() == 0)
if (drives.isEmpty())
return null;
return Iterables.get(drives, 0);
}

View File

@ -39,7 +39,7 @@ public class KeyValuesDelimitedByBlankLinesToStaticIPInfo implements Function<Ht
@Override
public StaticIPInfo apply(HttpResponse response) {
Set<StaticIPInfo> drives = setParser.apply(response);
if (drives.size() == 0)
if (drives.isEmpty())
return null;
return Iterables.get(drives, 0);
}

View File

@ -39,7 +39,7 @@ public class KeyValuesDelimitedByBlankLinesToVLANInfo implements Function<HttpRe
@Override
public VLANInfo apply(HttpResponse response) {
Set<VLANInfo> drives = setParser.apply(response);
if (drives.size() == 0)
if (drives.isEmpty())
return null;
return Iterables.get(drives, 0);
}

View File

@ -45,7 +45,7 @@ public class ListOfKeyValuesDelimitedByBlankLinesToListOfMaps implements Functio
}
}
}
if (map.size() != 0)
if (!map.isEmpty())
maps.add(map);
}
}

View File

@ -42,7 +42,7 @@ public class MapToDriveInfo implements Function<Map<String, String>, DriveInfo>
@Override
public DriveInfo apply(Map<String, String> from) {
if (from.size() == 0)
if (from.isEmpty())
return null;
DriveInfo.Builder builder = new DriveInfo.Builder();
builder.name(from.get("name"));

View File

@ -35,9 +35,7 @@ public class MapToProfileInfo implements Function<Map<String, String>, ProfileIn
@Override
public ProfileInfo apply(Map<String, String> from) {
if (from.size() == 0)
return null;
if (from.size() == 0)
if (from.isEmpty())
return null;
ProfileInfo.Builder builder = new ProfileInfo.Builder();
builder.uuid(from.get("uuid"));

View File

@ -51,7 +51,7 @@ public class MapToServerInfo implements Function<Map<String, String>, ServerInfo
@Override
public ServerInfo apply(Map<String, String> from) {
if (from.size() == 0)
if (from.isEmpty())
return null;
ServerInfo.Builder builder = new ServerInfo.Builder();
builder.name(from.get("name"));

View File

@ -35,9 +35,7 @@ public class MapToStaticIPInfo implements Function<Map<String, String>, StaticIP
@Override
public StaticIPInfo apply(Map<String, String> from) {
if (from.size() == 0)
return null;
if (from.size() == 0)
if (from.isEmpty())
return null;
StaticIPInfo.Builder builder = new StaticIPInfo.Builder();
builder.ip(from.get("resource"));

View File

@ -34,9 +34,7 @@ public class MapToVLANInfo implements Function<Map<String, String>, VLANInfo> {
@Override
public VLANInfo apply(Map<String, String> from) {
if (from.size() == 0)
return null;
if (from.size() == 0)
if (from.isEmpty())
return null;
VLANInfo.Builder builder = new VLANInfo.Builder();
builder.uuid(from.get("resource"));

View File

@ -45,7 +45,7 @@ public class ServerToMap implements Function<Server, Map<String, String>> {
builder.put("smp", "auto");
builder.put("mem", from.getMem() + "");
builder.put("persistent", from.isPersistent() + "");
if (from.getBootDeviceIds().size() != 0)
if (!from.getBootDeviceIds().isEmpty())
builder.put("boot", Joiner.on(' ').join(from.getBootDeviceIds()));
for (Entry<String, ? extends Device> entry : from.getDevices().entrySet()) {
builder.put(entry.getKey(), entry.getValue().getDriveUuid());
@ -67,7 +67,7 @@ public class ServerToMap implements Function<Server, Map<String, String>> {
builder.put("vnc:password", from.getVnc().getPassword());
if (from.getVnc().isTls())
builder.put("vnc:tls", "on");
if (from.getUse().size() != 0)
if (!from.getUse().isEmpty())
builder.put("use", Joiner.on(' ').join(from.getUse()));
return builder.build();
}

View File

@ -47,7 +47,7 @@ public class DriveClaimed implements Predicate<DriveInfo> {
if (drive == null)
return false;
logger.trace("%s: looking for drive claims: currently: %s", drive.getUuid(), drive.getClaimed());
return drive.getClaimed().size() > 0;
return !drive.getClaimed().isEmpty();
}
private DriveInfo refresh(DriveInfo drive) {

View File

@ -41,7 +41,7 @@ public class BindAccountSecurityGroupPairsToIndexedQueryParams implements Binder
public <R extends HttpRequest> R bindToRequest(R request, Object input) {
checkArgument(input instanceof Multimap<?, ?>, "this binder is only valid for Multimaps!");
Multimap<String, String> pairs = (Multimap<String, String>) checkNotNull(input, "account group pairs");
checkArgument(pairs.size() > 0, "you must specify at least one account, group pair");
checkArgument(!pairs.isEmpty(), "you must specify at least one account, group pair");
Multimap<String, String> existingParams = queryParser().apply(request.getEndpoint().getQuery());
Builder<String, String> map = ImmutableMultimap.<String, String> builder().putAll(existingParams);

View File

@ -35,7 +35,7 @@ public class BindCIDRsToCommaDelimitedQueryParam implements Binder {
public <R extends HttpRequest> R bindToRequest(R request, Object input) {
checkArgument(input instanceof Iterable<?>, "this binder is only valid for Iterables!");
Iterable<String> cidrs = (Iterable<String>) checkNotNull(input, "cidr list");
checkArgument(Iterables.size(cidrs) > 0, "you must specify at least one cidr range");
checkArgument(!Iterables.isEmpty(cidrs), "you must specify at least one cidr range");
return (R) request.toBuilder().replaceQueryParam("cidrlist", Joiner.on(',').join(cidrs)).build();
}
}

View File

@ -35,7 +35,7 @@ public class BindIdListToCommaDelimitedQueryParam implements Binder {
public <R extends HttpRequest> R bindToRequest(R request, Object input) {
checkArgument(input instanceof Iterable<?>, "this binder is only valid for Iterables!");
Iterable<Long> numbers = (Iterable<Long>) checkNotNull(input, "list of Longs");
checkArgument(Iterables.size(numbers) > 0, "you must specify at least one element");
checkArgument(!Iterables.isEmpty(numbers), "you must specify at least one element");
return (R) request.toBuilder().replaceQueryParam("ids", Joiner.on(',').join(numbers)).build();
}
}

View File

@ -164,7 +164,7 @@ public class CloudStackComputeServiceAdapter implements
} else if (templateOptions.getDomainId() != null) {
options.domainId(templateOptions.getDomainId());
}
OptionsConverter optionsConverter = optionsConverters.get(zone.getNetworkType());
options = optionsConverter.apply(templateOptions, networks, zoneId, options);
@ -174,7 +174,7 @@ public class CloudStackComputeServiceAdapter implements
options.ipOnDefaultNetwork(templateOptions.getIpOnDefaultNetwork());
}
if (templateOptions.getIpsToNetworks().size() > 0) {
if (!templateOptions.getIpsToNetworks().isEmpty()) {
options.ipsToNetworks(templateOptions.getIpsToNetworks());
}
@ -211,8 +211,8 @@ public class CloudStackComputeServiceAdapter implements
if (supportsSecurityGroups().apply(zone)) {
List<Integer> inboundPorts = Ints.asList(templateOptions.getInboundPorts());
if (templateOptions.getSecurityGroupIds().size() == 0
&& inboundPorts.size() > 0
if (templateOptions.getSecurityGroupIds().isEmpty()
&& !inboundPorts.isEmpty()
&& templateOptions.shouldGenerateSecurityGroup()) {
String securityGroupName = namingConvention.create().sharedNameForGroup(group);
SecurityGroup sg = securityGroupCache.getUnchecked(ZoneSecurityGroupNamePortsCidrs.builder()
@ -223,7 +223,7 @@ public class CloudStackComputeServiceAdapter implements
options.securityGroupId(sg.getId());
}
}
String templateId = template.getImage().getId();
String serviceOfferingId = template.getHardware().getId();
@ -241,7 +241,7 @@ public class CloudStackComputeServiceAdapter implements
assert vm.getPassword() != null : vm;
credentialsBuilder.password(vm.getPassword());
}
try {
if (templateOptions.shouldSetupStaticNat()) {
Capabilities capabilities = client.getConfigurationApi().listCapabilities();

View File

@ -65,11 +65,11 @@ public class CreateFirewallRulesForIP {
public Set<FirewallRule> apply(PublicIPAddress ip, Iterable<Integer> ports) {
return apply(ip, "tcp", ports);
}
public Set<FirewallRule> apply(PublicIPAddress ip, String protocol, Iterable<Integer> ports) {
checkState(ip.getVirtualMachineId() != null,
"ip %s should be static NATed to a virtual machine before applying rules", ip);
if (Iterables.size(ports) == 0)
if (Iterables.isEmpty(ports))
return ImmutableSet.<FirewallRule> of();
Builder<AsyncCreateResponse> responses = ImmutableSet.builder();
for (int port : ports) {

View File

@ -68,7 +68,7 @@ public class CreatePortForwardingRulesForIP {
public Set<IPForwardingRule> apply(PublicIPAddress ip, String protocol, Iterable<Integer> ports) {
checkState(ip.getVirtualMachineId() != null,
"ip %s should be static NATed to a virtual machine before applying rules", ip);
if (Iterables.size(ports) == 0)
if (Iterables.isEmpty(ports))
return ImmutableSet.<IPForwardingRule> of();
Builder<AsyncCreateResponse> responses = ImmutableSet.builder();
for (int port : ports) {

View File

@ -75,7 +75,7 @@ public class CreateSecurityGroupIfNeeded implements Function<ZoneSecurityGroupNa
logger.debug("<< created securityGroup(%s)", securityGroup);
ImmutableSet<String> cidrs;
if (input.getCidrs().size() > 0) {
if (!input.getCidrs().isEmpty()) {
cidrs = ImmutableSet.copyOf(input.getCidrs());
} else {
cidrs = ImmutableSet.of("0.0.0.0/0");

View File

@ -76,7 +76,7 @@ public class CorrectHypervisorForZone implements Function<String, Predicate<Temp
} catch (NullPointerException e) {
throw new IllegalArgumentException("unknown zone: " + zoneId);
}
if (acceptableHypervisorsInZone.size() == 0)
if (acceptableHypervisorsInZone.isEmpty())
return Predicates.alwaysFalse();
return new Predicate<Template>() {

View File

@ -76,7 +76,7 @@ public class CloudStackExperimentLiveTest extends BaseCloudStackApiLiveTest {
Network network = null;
Set<? extends NodeMetadata> nodes = null;
try {
assert view.getComputeService().listAssignableLocations().size() > 0;
assert !view.getComputeService().listAssignableLocations().isEmpty();
Template template = view.getComputeService().templateBuilder().build();
@ -103,7 +103,7 @@ public class CloudStackExperimentLiveTest extends BaseCloudStackApiLiveTest {
// launch the VM
nodes = view.getComputeService().createNodesInGroup(group, 1, template);
assert nodes.size() > 0;
assert !nodes.isEmpty();
} catch (RunNodesException e) {
Logger.getAnonymousLogger().log(Level.SEVERE, "error creating nodes", e);

View File

@ -42,7 +42,7 @@ public class AddressApiLiveTest extends BaseCloudStackApiLiveTest {
@BeforeGroups(groups = "live")
void networksEnabled() {
networksEnabled = client.getNetworkApi().listNetworks().size() > 0;
networksEnabled = !client.getNetworkApi().listNetworks().isEmpty();
}
private PublicIPAddress ip = null;

View File

@ -43,7 +43,7 @@ public class DomainUserApiLiveTest extends BaseCloudStackApiLiveTest {
Set<User> users = domainAdminClient.getUserClient().listUsers();
assert users.size() > 0;
assert !users.isEmpty();
assert users.contains(user); // contains the current user
for (User user : users) {

View File

@ -143,7 +143,7 @@ public class FirewallApiLiveTest extends BaseCloudStackApiLiveTest {
Set<FirewallRule> rules = client.getFirewallApi().listFirewallRules();
assert rules != null;
assertTrue(rules.size() > 0);
assertTrue(!rules.isEmpty());
for (FirewallRule rule : rules) {
checkFirewallRule(rule);
@ -172,7 +172,7 @@ public class FirewallApiLiveTest extends BaseCloudStackApiLiveTest {
Set<FirewallRule> rules = client.getFirewallApi().listEgressFirewallRules();
assert rules != null;
assertTrue(rules.size() > 0);
assertTrue(!rules.isEmpty());
for (FirewallRule rule : rules) {
checkEgressFirewallRule(rule);

View File

@ -41,7 +41,7 @@ public class GlobalHostApiLiveTest extends BaseCloudStackApiLiveTest {
skipIfNotGlobalAdmin();
Set<Host> hosts = globalAdminClient.getHostClient().listHosts();
assert hosts.size() > 0 : hosts;
assert !hosts.isEmpty() : hosts;
for (Host host : hosts) {
checkHost(host);
@ -68,7 +68,7 @@ public class GlobalHostApiLiveTest extends BaseCloudStackApiLiveTest {
skipIfNotGlobalAdmin();
Set<Cluster> clusters = globalAdminClient.getHostClient().listClusters();
assert clusters.size() > 0 : clusters;
assert !clusters.isEmpty() : clusters;
for (Cluster cluster : clusters) {
checkCluster(cluster);

View File

@ -41,7 +41,7 @@ public class GlobalStoragePoolApiLiveTest extends BaseCloudStackApiLiveTest {
Set<StoragePool> result = globalAdminClient.getStoragePoolClient().listStoragePools();
assertNotNull(result);
assertTrue(result.size() > 0);
assertTrue(!result.isEmpty());
for (StoragePool pool : result) {
assertNotNull(pool.getId());
assertFalse(Strings.isNullOrEmpty(pool.getName()));

View File

@ -89,7 +89,7 @@ public class GlobalUserApiLiveTest extends BaseCloudStackApiLiveTest {
CloudStackApi client = context.getApi();
Set<Account> accounts = client.getAccountApi().listAccounts();
assert accounts.size() > 0;
assert !accounts.isEmpty();
context.close();
}

View File

@ -98,17 +98,17 @@ public class GlobalVlanApiLiveTest extends BaseCloudStackApiLiveTest {
return network.getNetworkOfferingId().equals(offering.getId());
}
});
if (suitableNetworks.size() > 0) {
if (!suitableNetworks.isEmpty()) {
network = Iterables.get(suitableNetworks, 0);
usingExistingNetwork = true;
} else if (network == null) {
network = client.getNetworkApi().createNetworkInZone(zone.getId(),
offering.getId(), "net-" + prefix, "jclouds test " + prefix);
usingExistingNetwork = false;
}
range = globalAdminClient.getVlanClient().createVlanIPRange("172.19.1.1", "172.19.1.199", CreateVlanIPRangeOptions.Builder
.accountInDomain(user.getAccount(), user.getDomainId())
.forVirtualNetwork(true)

View File

@ -84,7 +84,7 @@ public class VirtualMachineApiLiveTest extends BaseCloudStackApiLiveTest {
public static VirtualMachine createVirtualMachine(CloudStackApi client, String defaultTemplate,
Predicate<String> jobComplete, Predicate<VirtualMachine> virtualMachineRunning) {
Set<Network> networks = client.getNetworkApi().listNetworks(isDefault(true));
if (networks.size() > 0) {
if (!networks.isEmpty()) {
Network network = get(filter(networks, new Predicate<Network>() {
@Override
public boolean apply(Network network) {
@ -367,7 +367,7 @@ public class VirtualMachineApiLiveTest extends BaseCloudStackApiLiveTest {
// assert vm.getRootDeviceType() != null : vm;
if (vm.getJobId() != null)
assert vm.getJobStatus() != null : vm;
assert vm.getNICs() != null && vm.getNICs().size() > 0 : vm;
assert vm.getNICs() != null && !vm.getNICs().isEmpty() : vm;
for (NIC nic : vm.getNICs()) {
assert nic.getId() != null : vm;
assert nic.getNetworkId() != null : vm;

View File

@ -58,7 +58,7 @@ public class AlarmApiLiveTest extends BaseCloudWatchApiLiveTest {
protected void beforeClass() throws Exception {
IterableWithMarker<Metric> metrics = metricApi().list(new ListMetricsOptions().metricName(metricName));
if (Iterables.size(metrics) == 0) {
if (Iterables.isEmpty(metrics)) {
metricApi().putMetricsInNamespace(ImmutableSet.of(
MetricDatum.builder()
.metricName(metricName)
@ -92,7 +92,7 @@ public class AlarmApiLiveTest extends BaseCloudWatchApiLiveTest {
@AfterClass
protected void afterClass() throws Exception {
IterableWithMarker<Alarm> alarms = api().list(new ListAlarmsOptions().alarmName(alarmName)).get(0);
if (Iterables.size(alarms) > 0) {
if (!Iterables.isEmpty(alarms)) {
api().delete(ImmutableSet.of(alarmName));
}
}
@ -249,7 +249,7 @@ public class AlarmApiLiveTest extends BaseCloudWatchApiLiveTest {
success = retry(new Predicate<ListAlarmsOptions>() {
public boolean apply(ListAlarmsOptions options) {
return Iterables.size(api().list(options).get(0)) == 0;
return Iterables.isEmpty(api().list(options).get(0));
}
}, 5, 1, MINUTES).apply(dmo);

View File

@ -166,7 +166,7 @@ public class MetricApiLiveTest extends BaseCloudWatchApiLiveTest {
.unit(Unit.PERCENT).build();
GetMetricStatisticsResponse response = api().getMetricStatistics(options);
if (response.size() > 0) {
if (!response.isEmpty()) {
checkNotNull(response.getLabel());
for (Datapoint datapoint : response) {
@ -200,13 +200,13 @@ public class MetricApiLiveTest extends BaseCloudWatchApiLiveTest {
performDefaultMetricsTests(response);
if (Iterables.size(response) > 0) {
if (!Iterables.isEmpty(response)) {
Metric metric = response.iterator().next();
testMetricName = metric.getMetricName();
testNamespace = metric.getNamespace();
if (metric.getDimensions().size() > 0) {
if (!metric.getDimensions().isEmpty()) {
Dimension dimension = metric.getDimensions().iterator().next();
testDimensionName = dimension.getName();
@ -217,7 +217,7 @@ public class MetricApiLiveTest extends BaseCloudWatchApiLiveTest {
for (Metric metric1 : response) {
Set<Dimension> dimensions = metric1.getDimensions();
if (dimensions.size() > 0) {
if (!dimensions.isEmpty()) {
Dimension dimension = metric.getDimensions().iterator().next();
testDimensionName = dimension.getName();

View File

@ -39,7 +39,7 @@ public class BindIpPermissionsToIndexedFormParams implements Binder {
for (IpPermission perm : (Iterable<IpPermission>) input)
formBuilder.putAll(IpPermissions.buildFormParametersForIndex(index++, perm));
ImmutableMultimap<String, String> forms = formBuilder.build();
return forms.size() == 0 ? request : (R) request.toBuilder().replaceFormParams(forms).build();
return forms.isEmpty() ? request : (R) request.toBuilder().replaceFormParams(forms).build();
}
}

View File

@ -164,7 +164,7 @@ public class EC2ComputeService extends BaseComputeService {
return in.getProviderId();
}
};
private Set<NodeMetadata> addTagsAndNamesToInstancesInRegion(Map<String, String> common, Set<String> nodeNames,
Set<? extends NodeMetadata> input, String region,
String group) {
@ -219,8 +219,8 @@ public class EC2ComputeService extends BaseComputeService {
checkNotNull(emptyToNull(region), "region must be defined");
checkNotNull(emptyToNull(group), "group must be defined");
String groupName = namingConvention.create().sharedNameForGroup(group);
if (client.getSecurityGroupApi().get().describeSecurityGroupsInRegion(region, groupName).size() > 0) {
if (!client.getSecurityGroupApi().get().describeSecurityGroupsInRegion(region, groupName).isEmpty()) {
logger.debug(">> deleting securityGroup(%s)", groupName);
client.getSecurityGroupApi().get().deleteSecurityGroupInRegion(region, groupName);
// TODO: test this clear happens
@ -240,7 +240,7 @@ public class EC2ComputeService extends BaseComputeService {
Predicate<String> keyNameMatcher = namingConvention.create().containsGroup(group);
String oldKeyNameRegex = String.format("jclouds#%s#%s#%s", group, region, "[0-9a-f]+").replace('#', delimiter);
// old keypair pattern too verbose as it has an unnecessary region qualifier
if (keyNameMatcher.apply(keyName) || keyName.matches(oldKeyNameRegex)) {
Set<String> instancesUsingKeyPair = extractIdsFromInstances(concat(client.getInstanceApi().get()
.describeInstancesInRegionWithFilter(region, ImmutableMultimap.<String, String>builder()
@ -248,7 +248,7 @@ public class EC2ComputeService extends BaseComputeService {
.put("instance-state-name", InstanceState.SHUTTING_DOWN.toString())
.put("key-name", keyPair.getKeyName()).build())));
if (instancesUsingKeyPair.size() > 0) {
if (!instancesUsingKeyPair.isEmpty()) {
logger.debug("<< inUse keyPair(%s), by (%s)", keyPair.getKeyName(), instancesUsingKeyPair);
} else {
logger.debug(">> deleting keyPair(%s)", keyPair.getKeyName());
@ -292,12 +292,12 @@ public class EC2ComputeService extends BaseComputeService {
// For issue #445, tries to delete security groups first: ec2 throws exception if in use, but
// deleting a key pair does not.
// This is "belt-and-braces" because deleteKeyPair also does extractIdsFromInstances & usingKeyPairAndNotDead
// for us to check if any instances are using the key-pair before we delete it.
// There is (probably?) still a race if someone is creating instances at the same time as deleting them:
// we may delete the key-pair just when the node-being-created was about to rely on the incidental
// for us to check if any instances are using the key-pair before we delete it.
// There is (probably?) still a race if someone is creating instances at the same time as deleting them:
// we may delete the key-pair just when the node-being-created was about to rely on the incidental
// resources existing.
// Also in #445, in aws-ec2 the deleteSecurityGroup sometimes fails after terminating the final VM using a
// Also in #445, in aws-ec2 the deleteSecurityGroup sometimes fails after terminating the final VM using a
// given security group, if called very soon after the VM's state reports terminated. Empirically, it seems that
// waiting a small time (e.g. enabling logging or debugging!) then the tests pass. We therefore retry.
// TODO: this could be moved to a config module, also the narrative above made more concise

View File

@ -77,7 +77,7 @@ public class EC2SecurityGroupExtension implements SecurityGroupExtension {
@Memoized Supplier<Set<? extends Location>> locations,
@Named("SECURITY") LoadingCache<RegionAndName, String> groupCreator,
GroupNamingConvention.Factory namingConvention) {
this.client = checkNotNull(client, "client");
this.userExecutor = checkNotNull(userExecutor, "userExecutor");
this.regions = checkNotNull(regions, "regions");
@ -111,24 +111,24 @@ public class EC2SecurityGroupExtension implements SecurityGroupExtension {
groupConverter);
return ImmutableSet.copyOf(groups);
}
@Override
public Set<SecurityGroup> listSecurityGroupsForNode(String id) {
checkNotNull(id, "id");
String[] parts = AWSUtils.parseHandle(id);
String region = parts[0];
String instanceId = parts[1];
RunningInstance instance = getOnlyElement(Iterables.concat(client.getInstanceApi().get().describeInstancesInRegion(region, instanceId)));
if (instance == null) {
return ImmutableSet.of();
}
Set<String> groupNames = instance.getGroupNames();
Set<? extends org.jclouds.ec2.domain.SecurityGroup> rawGroups =
client.getSecurityGroupApi().get().describeSecurityGroupsInRegion(region, Iterables.toArray(groupNames, String.class));
return ImmutableSet.copyOf(transform(filter(rawGroups, notNull()), groupConverter));
}
@ -141,7 +141,7 @@ public class EC2SecurityGroupExtension implements SecurityGroupExtension {
Set<? extends org.jclouds.ec2.domain.SecurityGroup> rawGroups =
client.getSecurityGroupApi().get().describeSecurityGroupsInRegion(region, groupId);
return getOnlyElement(transform(filter(rawGroups, notNull()), groupConverter));
}
@ -154,7 +154,7 @@ public class EC2SecurityGroupExtension implements SecurityGroupExtension {
return null;
}
}
public SecurityGroup createSecurityGroup(String name, String region) {
String markerGroup = namingConvention.create().sharedNameForGroup(name);
RegionNameAndIngressRules regionAndName = new RegionNameAndIngressRules(region, markerGroup, new int[] {},
@ -171,8 +171,8 @@ public class EC2SecurityGroupExtension implements SecurityGroupExtension {
String[] parts = AWSUtils.parseHandle(id);
String region = parts[0];
String groupName = parts[1];
if (client.getSecurityGroupApi().get().describeSecurityGroupsInRegion(region, groupName).size() > 0) {
if (!client.getSecurityGroupApi().get().describeSecurityGroupsInRegion(region, groupName).isEmpty()) {
client.getSecurityGroupApi().get().deleteSecurityGroupInRegion(region, groupName);
// TODO: test this clear happens
groupCreator.invalidate(new RegionNameAndIngressRules(region, groupName, null, false));
@ -188,7 +188,7 @@ public class EC2SecurityGroupExtension implements SecurityGroupExtension {
String region = AWSUtils.getRegionFromLocationOrNull(group.getLocation());
String name = group.getName();
if (ipPermission.getCidrBlocks().size() > 0) {
if (!ipPermission.getCidrBlocks().isEmpty()) {
for (String cidr : ipPermission.getCidrBlocks()) {
client.getSecurityGroupApi().get().
authorizeSecurityGroupIngressInRegion(region,
@ -200,7 +200,7 @@ public class EC2SecurityGroupExtension implements SecurityGroupExtension {
}
}
if (ipPermission.getTenantIdGroupNamePairs().size() > 0) {
if (!ipPermission.getTenantIdGroupNamePairs().isEmpty()) {
for (String userId : ipPermission.getTenantIdGroupNamePairs().keySet()) {
for (String groupName : ipPermission.getTenantIdGroupNamePairs().get(userId)) {
client.getSecurityGroupApi().get().
@ -222,7 +222,7 @@ public class EC2SecurityGroupExtension implements SecurityGroupExtension {
String region = AWSUtils.getRegionFromLocationOrNull(group.getLocation());
String name = group.getName();
if (Iterables.size(ipRanges) > 0) {
if (!Iterables.isEmpty(ipRanges)) {
for (String cidr : ipRanges) {
client.getSecurityGroupApi().get().
authorizeSecurityGroupIngressInRegion(region,
@ -234,7 +234,7 @@ public class EC2SecurityGroupExtension implements SecurityGroupExtension {
}
}
if (tenantIdGroupNamePairs.size() > 0) {
if (!tenantIdGroupNamePairs.isEmpty()) {
for (String userId : tenantIdGroupNamePairs.keySet()) {
for (String groupName : tenantIdGroupNamePairs.get(userId)) {
client.getSecurityGroupApi().get().
@ -244,16 +244,16 @@ public class EC2SecurityGroupExtension implements SecurityGroupExtension {
}
}
}
return getSecurityGroupById(new RegionAndName(region, group.getName()).slashEncode());
}
@Override
public SecurityGroup removeIpPermission(IpPermission ipPermission, SecurityGroup group) {
String region = AWSUtils.getRegionFromLocationOrNull(group.getLocation());
String name = group.getName();
if (ipPermission.getCidrBlocks().size() > 0) {
if (!ipPermission.getCidrBlocks().isEmpty()) {
for (String cidr : ipPermission.getCidrBlocks()) {
client.getSecurityGroupApi().get().
revokeSecurityGroupIngressInRegion(region,
@ -265,7 +265,7 @@ public class EC2SecurityGroupExtension implements SecurityGroupExtension {
}
}
if (ipPermission.getTenantIdGroupNamePairs().size() > 0) {
if (!ipPermission.getTenantIdGroupNamePairs().isEmpty()) {
for (String userId : ipPermission.getTenantIdGroupNamePairs().keySet()) {
for (String groupName : ipPermission.getTenantIdGroupNamePairs().get(userId)) {
client.getSecurityGroupApi().get().
@ -287,7 +287,7 @@ public class EC2SecurityGroupExtension implements SecurityGroupExtension {
String region = AWSUtils.getRegionFromLocationOrNull(group.getLocation());
String name = group.getName();
if (Iterables.size(ipRanges) > 0) {
if (!Iterables.isEmpty(ipRanges)) {
for (String cidr : ipRanges) {
client.getSecurityGroupApi().get().
revokeSecurityGroupIngressInRegion(region,
@ -299,7 +299,7 @@ public class EC2SecurityGroupExtension implements SecurityGroupExtension {
}
}
if (tenantIdGroupNamePairs.size() > 0) {
if (!tenantIdGroupNamePairs.isEmpty()) {
for (String userId : tenantIdGroupNamePairs.keySet()) {
for (String groupName : tenantIdGroupNamePairs.get(userId)) {
client.getSecurityGroupApi().get().
@ -309,7 +309,7 @@ public class EC2SecurityGroupExtension implements SecurityGroupExtension {
}
}
}
return getSecurityGroupById(new RegionAndName(region, group.getName()).slashEncode());
}
@ -336,23 +336,23 @@ public class EC2SecurityGroupExtension implements SecurityGroupExtension {
protected Iterable<? extends org.jclouds.ec2.domain.SecurityGroup> pollSecurityGroups() {
Iterable<? extends Set<? extends org.jclouds.ec2.domain.SecurityGroup>> groups
= transform(regions.get(), allSecurityGroupsInRegion());
return concat(groups);
}
protected Iterable<? extends org.jclouds.ec2.domain.SecurityGroup> pollSecurityGroupsByRegion(String region) {
return allSecurityGroupsInRegion().apply(region);
}
protected Function<String, Set<? extends org.jclouds.ec2.domain.SecurityGroup>> allSecurityGroupsInRegion() {
return new Function<String, Set<? extends org.jclouds.ec2.domain.SecurityGroup>>() {
@Override
public Set<? extends org.jclouds.ec2.domain.SecurityGroup> apply(String from) {
return client.getSecurityGroupApi().get().describeSecurityGroupsInRegion(from);
}
};
}

View File

@ -70,11 +70,11 @@ public class EC2TemplateOptions extends TemplateOptions implements Cloneable {
super.copyTo(to);
if (to instanceof EC2TemplateOptions) {
EC2TemplateOptions eTo = EC2TemplateOptions.class.cast(to);
if (getGroups().size() > 0)
if (!getGroups().isEmpty())
eTo.securityGroups(getGroups());
if (getKeyPair() != null)
eTo.keyPair(getKeyPair());
if (getBlockDeviceMappings().size() > 0)
if (!getBlockDeviceMappings().isEmpty())
eTo.blockDeviceMappings(getBlockDeviceMappings());
if (!shouldAutomaticallyCreateKeyPair())
eTo.noKeyPair();
@ -119,15 +119,15 @@ public class EC2TemplateOptions extends TemplateOptions implements Cloneable {
@Override
public ToStringHelper string() {
ToStringHelper toString = super.string();
if (groupNames.size() != 0)
if (!groupNames.isEmpty())
toString.add("groupNames", groupNames);
if (noKeyPair)
toString.add("noKeyPair", noKeyPair);
toString.add("keyPair", keyPair);
if (userData != null && userData.size() > 0)
if (userData != null && !userData.isEmpty())
toString.add("userDataCksum", Hashing.crc32().hashBytes(Bytes.toArray(userData)));
ImmutableSet<BlockDeviceMapping> mappings = blockDeviceMappings.build();
if (mappings.size() != 0)
if (!mappings.isEmpty())
toString.add("blockDeviceMappings", mappings);
if (maxCount != null && maxCount.intValue() > 0)
toString.add("maxCount", maxCount);
@ -139,7 +139,7 @@ public class EC2TemplateOptions extends TemplateOptions implements Cloneable {
public static final EC2TemplateOptions NONE = new EC2TemplateOptions();
/**
*
*
* @see EC2TemplateOptions#securityGroups(Iterable<String>)
*/
public EC2TemplateOptions securityGroups(String... groupNames) {
@ -150,7 +150,7 @@ public class EC2TemplateOptions extends TemplateOptions implements Cloneable {
* Specifies the security groups to be used for nodes with this template
*/
public EC2TemplateOptions securityGroups(Iterable<String> groupNames) {
checkArgument(Iterables.size(groupNames) > 0, "you must specify at least one security group");
checkArgument(!Iterables.isEmpty(groupNames), "you must specify at least one security group");
for (String groupId : groupNames)
checkNotNull(emptyToNull(groupId), "all security groups must be non-empty");
this.groupNames = ImmutableSet.copyOf(groupNames);
@ -425,7 +425,7 @@ public class EC2TemplateOptions extends TemplateOptions implements Cloneable {
EC2TemplateOptions options = new EC2TemplateOptions();
return options.runScript(script);
}
public static EC2TemplateOptions runScript(String script) {
EC2TemplateOptions options = new EC2TemplateOptions();
return options.runScript(script);
@ -477,7 +477,7 @@ public class EC2TemplateOptions extends TemplateOptions implements Cloneable {
public EC2TemplateOptions authorizePublicKey(String publicKey) {
return EC2TemplateOptions.class.cast(super.authorizePublicKey(publicKey));
}
/**
* {@inheritDoc}
*/
@ -485,7 +485,7 @@ public class EC2TemplateOptions extends TemplateOptions implements Cloneable {
public EC2TemplateOptions installPrivateKey(String privateKey) {
return EC2TemplateOptions.class.cast(super.installPrivateKey(privateKey));
}
/**
* {@inheritDoc}
*/
@ -629,7 +629,7 @@ public class EC2TemplateOptions extends TemplateOptions implements Cloneable {
public EC2TemplateOptions blockOnComplete(boolean blockOnComplete) {
return EC2TemplateOptions.class.cast(super.blockOnComplete(blockOnComplete));
}
/**
* @return groupNames the user specified to run instances with, or zero
* length set to create an implicit group

View File

@ -90,7 +90,7 @@ public class CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions {
Set<BlockDeviceMapping> blockDeviceMappings = EC2TemplateOptions.class.cast(template.getOptions())
.getBlockDeviceMappings();
if (blockDeviceMappings.size() > 0) {
if (!blockDeviceMappings.isEmpty()) {
checkState("ebs".equals(template.getImage().getUserMetadata().get("rootDeviceType")),
"BlockDeviceMapping only available on ebs boot");
instanceOptions.withBlockDeviceMappings(blockDeviceMappings);
@ -188,7 +188,7 @@ public class CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions {
}
protected boolean userSpecifiedTheirOwnGroups(TemplateOptions options) {
return options instanceof EC2TemplateOptions && EC2TemplateOptions.class.cast(options).getGroups().size() > 0;
return options instanceof EC2TemplateOptions && !EC2TemplateOptions.class.cast(options).getGroups().isEmpty();
}
// allows us to mock this method

View File

@ -130,7 +130,7 @@ public class EC2CreateNodesInGroupThenAddToSet implements CreateNodesInGroupThen
Template mutableTemplate = template.clone();
Set<RunningInstance> started = runInstancesAndWarnOnInvisible(group, count, mutableTemplate);
if (started.size() == 0) {
if (started.isEmpty()) {
logger.warn("<< unable to start instances(%s)", mutableTemplate);
return ImmutableMap.of();
}
@ -151,7 +151,7 @@ public class EC2CreateNodesInGroupThenAddToSet implements CreateNodesInGroupThen
Set<RunningInstance> started = createKeyPairAndSecurityGroupsAsNeededThenRunInstances(group, count,
mutableTemplate);
Set<RegionAndName> startedIds = ImmutableSet.copyOf(transform(started, instanceToRegionAndName));
if (startedIds.size() == 0) {
if (startedIds.isEmpty()) {
return ImmutableSet.copyOf(started);
}
logger.debug("<< started instances(%s)", startedIds);
@ -161,7 +161,7 @@ public class EC2CreateNodesInGroupThenAddToSet implements CreateNodesInGroupThen
// add an exception for each of the nodes we cannot customize
Set<RegionAndName> invisibleIds = difference(startedIds, visibleIds);
if (invisibleIds.size() > 0) {
if (!invisibleIds.isEmpty()) {
logger.warn("<< not api visible instances(%s)", invisibleIds);
}
return started;

View File

@ -214,7 +214,7 @@ public class SecurityGroup extends ForwardingSet<IpPermission> {
protected ToStringHelper string() {
return MoreObjects.toStringHelper(this).omitNullValues().add("region", region).add("id", id).add("name", name)
.add("ownerId", ownerId).add("description", description)
.add("ipPermissions", ipPermissions.size() == 0 ? null : ipPermissions);
.add("ipPermissions", ipPermissions.isEmpty() ? null : ipPermissions);
}
@Override

View File

@ -30,7 +30,7 @@ import com.google.common.collect.Sets;
import com.google.inject.Inject;
/**
*
*
* Tests to see if a volume is attached.
*/
@Singleton
@ -49,7 +49,7 @@ public class VolumeAttached implements Predicate<Attachment> {
logger.trace("looking for volume %s", attachment.getVolumeId());
Volume volume = Iterables.getOnlyElement(client.describeVolumesInRegion(attachment
.getRegion(), attachment.getVolumeId()));
if (volume.getAttachments().size() == 0) {
if (volume.getAttachments().isEmpty()) {
return false;
}
Attachment lastAttachment = Sets.newTreeSet(volume.getAttachments()).last();

View File

@ -51,7 +51,7 @@ public class VolumeDetached implements Predicate<Attachment> {
.getRegion(), attachment.getVolumeId()));
/*If attachment size is 0 volume is detached for sure.*/
if (volume.getAttachments().size() == 0) {
if (volume.getAttachments().isEmpty()) {
return true;
}

View File

@ -70,7 +70,7 @@ public class DescribeAvailabilityZonesInRegion implements RegionIdToZoneIdsSuppl
}
}));
if (zones.size() > 0)
if (!zones.isEmpty())
map.put(region, zones);
} catch (HttpResponseException e) {
// TODO: this should be in retry handler, not here.

View File

@ -41,7 +41,7 @@ public class IpPermissions extends IpPermission {
protected IpPermissions(IpProtocol ipProtocol, int fromPort, int toPort,
Multimap<String, String> userIdGroupPairs, Iterable<String> groupIds, Iterable<String> ipRanges) {
super(ipProtocol, fromPort, toPort, userIdGroupPairs, groupIds, userIdGroupPairs.size() == 0 ? ipRanges
super(ipProtocol, fromPort, toPort, userIdGroupPairs, groupIds, userIdGroupPairs.isEmpty() ? ipRanges
: ImmutableSet.<String> of());
}

View File

@ -80,7 +80,7 @@ import com.google.inject.Injector;
* Adapted from the following sources: {@link http://gist.github.com/249915}, {@link http
* ://www.capsunlock.net/2009/12/create-ebs-boot-ami.html}
* <p/>
*
*
* Generally disabled, as it incurs higher fees.
*/
@Test(groups = "live", enabled = false, singleThreaded = true, testName = "EBSBootEC2ApiLiveTest")
@ -334,7 +334,7 @@ public class EBSBootEC2ApiLiveTest extends BaseComputeServiceContextLiveTest {
void testAMIFromBundle() {
volume = Iterables.getOnlyElement(client.getElasticBlockStoreApi().get().describeVolumesInRegion(
volume.getRegion(), volume.getId()));
if (volume.getAttachments().size() > 0) {
if (!volume.getAttachments().isEmpty()) {
// should be cleanly unmounted, so force is not necessary.
client.getElasticBlockStoreApi().get().detachVolumeInRegion(instance.getRegion(), volume.getId(), false);
System.out.printf("%d: %s awaiting detachment to complete%n", System.currentTimeMillis(), volume.getId());
@ -483,7 +483,7 @@ public class EBSBootEC2ApiLiveTest extends BaseComputeServiceContextLiveTest {
/**
* this tests "personality" as the file looked up was sent during instance creation
*
*
* @throws UnknownHostException
*/
private void sshPing(RunningInstance newDetails) throws UnknownHostException {

View File

@ -40,9 +40,9 @@ public class BaseDriveToMap implements Function<Drive, Map<String, String>> {
builder.put("size", from.getSize() + "");
if (from.getClaimType() != ClaimType.EXCLUSIVE)
builder.put("claim:type", from.getClaimType().toString());
if (from.getReaders().size() != 0)
if (!from.getReaders().isEmpty())
builder.put("readers", Joiner.on(' ').join(from.getReaders()));
if (from.getTags().size() != 0)
if (!from.getTags().isEmpty())
builder.put("tags", Joiner.on(' ').join(from.getTags()));
for (Entry<String, String> entry : from.getUserMetadata().entrySet())
builder.put("user:" + entry.getKey(), entry.getValue());

View File

@ -43,7 +43,7 @@ public class CreateDriveRequestToMap implements Function<Drive, Map<String, Stri
builder.putAll(baseDriveToMap.apply(from));
if (from instanceof CreateDriveRequest) {
CreateDriveRequest create = CreateDriveRequest.class.cast(from);
if (create.getAvoid().size() != 0)
if (!create.getAvoid().isEmpty())
builder.put("avoid", Joiner.on(' ').join(create.getAvoid()));
if (create.getEncryptionCipher() != null)
builder.put("encryption:cipher", create.getEncryptionCipher());

View File

@ -39,7 +39,7 @@ public class KeyValuesDelimitedByBlankLinesToDriveInfo implements Function<HttpR
@Override
public DriveInfo apply(HttpResponse response) {
Set<DriveInfo> drives = setParser.apply(response);
if (drives.size() == 0)
if (drives.isEmpty())
return null;
return Iterables.get(drives, 0);
}

View File

@ -39,7 +39,7 @@ public class KeyValuesDelimitedByBlankLinesToServerInfo implements Function<Http
@Override
public ServerInfo apply(HttpResponse response) {
Set<ServerInfo> drives = setParser.apply(response);
if (drives.size() == 0)
if (drives.isEmpty())
return null;
return Iterables.get(drives, 0);
}

View File

@ -45,7 +45,7 @@ public class ListOfKeyValuesDelimitedByBlankLinesToListOfMaps implements Functio
}
}
}
if (map.size() != 0)
if (!map.isEmpty())
maps.add(map);
}
}

View File

@ -40,7 +40,7 @@ public class MapToDriveInfo implements Function<Map<String, String>, DriveInfo>
@Override
public DriveInfo apply(Map<String, String> from) {
if (from.size() == 0)
if (from.isEmpty())
return null;
DriveInfo.Builder builder = new DriveInfo.Builder();
builder.name(from.get("name"));

View File

@ -51,7 +51,7 @@ public class MapToServerInfo implements Function<Map<String, String>, ServerInfo
@Override
public ServerInfo apply(Map<String, String> from) {
if (from.size() == 0)
if (from.isEmpty())
return null;
ServerInfo.Builder builder = new ServerInfo.Builder();
builder.name(from.get("name"));

View File

@ -60,7 +60,7 @@ public class ServerToMap implements Function<Server, Map<String, String>> {
builder.put("smp", "auto");
builder.put("mem", from.getMem() + "");
builder.put("persistent", from.isPersistent() + "");
if (from.getBootDeviceIds().size() != 0)
if (!from.getBootDeviceIds().isEmpty())
builder.put("boot", Joiner.on(' ').join(from.getBootDeviceIds()));
for (Entry<String, ? extends Device> entry : from.getDevices().entrySet()) {
builder.put(entry.getKey(), entry.getValue().getDriveUuid());
@ -89,7 +89,7 @@ public class ServerToMap implements Function<Server, Map<String, String>> {
builder.put("password", from.getVnc().getPassword());
if (from.getVnc().isTls())
builder.put("vnc:tls", "on");
if (from.getTags().size() != 0)
if (!from.getTags().isEmpty())
builder.put("tags", Joiner.on(' ').join(from.getTags()));
for (Entry<String, String> entry : from.getUserMetadata().entrySet())
builder.put("user:" + entry.getKey(), entry.getValue());

View File

@ -47,7 +47,7 @@ public class DriveClaimed implements Predicate<DriveInfo> {
if (drive == null)
return false;
logger.trace("%s: looking for drive claims: currently: %s", drive.getUuid(), drive.getClaimed());
return drive.getClaimed().size() > 0;
return !drive.getClaimed().isEmpty();
}
private DriveInfo refresh(DriveInfo drive) {

View File

@ -18,10 +18,11 @@ package org.jclouds.openstack.keystone.v2_0.suppliers;
import static com.google.common.collect.Iterables.any;
import static com.google.common.collect.Iterables.concat;
import static com.google.common.collect.Iterables.size;
import static com.google.common.collect.Iterables.isEmpty;
import static com.google.common.collect.Iterables.tryFind;
import static com.google.common.collect.Multimaps.index;
import java.net.URI;
import java.util.Collection;
import java.util.Map;
@ -93,12 +94,12 @@ public class LocationIdToURIFromAccessForTypeAndVersion implements Supplier<Map<
@Override
public Map<String, Supplier<URI>> get() {
FluentIterable<Service> services = FluentIterable.from(access.get()).filter(apiTypeEquals);
if (services.toSet().size() == 0)
if (services.isEmpty())
throw new NoSuchElementException(String.format("apiType %s not found in catalog %s", apiType, services));
Iterable<Endpoint> endpoints = concat(services);
if (size(endpoints) == 0)
if (isEmpty(endpoints))
throw new NoSuchElementException(
String.format("no endpoints for apiType %s in services %s", apiType, services));

View File

@ -164,15 +164,15 @@ public class NovaComputeServiceAdapter implements
public Iterable<ImageInRegion> listImages() {
Builder<ImageInRegion> builder = ImmutableSet.builder();
Set<String> regions = regionIds.get();
checkState(regions.size() > 0, "no regions found in supplier %s", regionIds);
checkState(!regions.isEmpty(), "no regions found in supplier %s", regionIds);
for (final String regionId : regions) {
Set<? extends Image> images = novaApi.getImageApi(regionId).listInDetail().concat().toSet();
if (images.size() == 0) {
if (images.isEmpty()) {
logger.debug("no images found in region %s", regionId);
continue;
}
Iterable<? extends Image> active = filter(images, ImagePredicates.statusEquals(Image.Status.ACTIVE));
if (images.size() == 0) {
if (images.isEmpty()) {
logger.debug("no images with status active in region %s; non-active: %s", regionId,
transform(active, new Function<Image, String>() {

View File

@ -209,7 +209,7 @@ public class NovaSecurityGroupExtension implements SecurityGroupExtension {
return null;
}
if (ipPermission.getCidrBlocks().size() > 0) {
if (!ipPermission.getCidrBlocks().isEmpty()) {
for (String cidr : ipPermission.getCidrBlocks()) {
sgApi.get().createRuleAllowingCidrBlock(id,
Ingress.builder()
@ -221,7 +221,7 @@ public class NovaSecurityGroupExtension implements SecurityGroupExtension {
}
}
if (ipPermission.getGroupIds().size() > 0) {
if (!ipPermission.getGroupIds().isEmpty()) {
for (String regionAndGroupRaw : ipPermission.getGroupIds()) {
RegionAndId regionAndId = RegionAndId.fromSlashEncoded(regionAndGroupRaw);
String groupId = regionAndId.getId();
@ -268,7 +268,7 @@ public class NovaSecurityGroupExtension implements SecurityGroupExtension {
org.jclouds.openstack.nova.v2_0.domain.SecurityGroup securityGroup = sgApi.get().get(id);
if (ipPermission.getCidrBlocks().size() > 0) {
if (!ipPermission.getCidrBlocks().isEmpty()) {
for (String cidr : ipPermission.getCidrBlocks()) {
for (SecurityGroupRule rule : filter(securityGroup.getRules(),
and(ruleCidr(cidr), ruleProtocol(ipPermission.getIpProtocol()),
@ -279,7 +279,7 @@ public class NovaSecurityGroupExtension implements SecurityGroupExtension {
}
}
if (ipPermission.getGroupIds().size() > 0) {
if (!ipPermission.getGroupIds().isEmpty()) {
for (String groupId : ipPermission.getGroupIds()) {
for (SecurityGroupRule rule : filter(securityGroup.getRules(),
and(ruleGroup(groupId), ruleProtocol(ipPermission.getIpProtocol()),

View File

@ -35,11 +35,11 @@ import com.google.common.collect.ImmutableSet;
*/
public class SecurityGroup {
public static Builder<?> builder() {
public static Builder<?> builder() {
return new ConcreteBuilder();
}
public Builder<?> toBuilder() {
public Builder<?> toBuilder() {
return new ConcreteBuilder().fromSecurityGroup(this);
}
@ -51,8 +51,8 @@ public class SecurityGroup {
protected String name;
protected String description;
protected Set<SecurityGroupRule> rules = ImmutableSet.of();
/**
/**
* @see SecurityGroup#getId()
*/
public T id(String id) {
@ -60,7 +60,7 @@ public class SecurityGroup {
return self();
}
/**
/**
* @see SecurityGroup#getTenantId()
*/
public T tenantId(String tenantId) {
@ -68,7 +68,7 @@ public class SecurityGroup {
return self();
}
/**
/**
* @see SecurityGroup#getName()
*/
public T name(String name) {
@ -76,7 +76,7 @@ public class SecurityGroup {
return self();
}
/**
/**
* @see SecurityGroup#getDescription()
*/
public T description(String description) {
@ -84,11 +84,11 @@ public class SecurityGroup {
return self();
}
/**
/**
* @see SecurityGroup#getRules()
*/
public T rules(Set<SecurityGroupRule> rules) {
this.rules = ImmutableSet.copyOf(checkNotNull(rules, "rules"));
this.rules = ImmutableSet.copyOf(checkNotNull(rules, "rules"));
return self();
}
@ -99,7 +99,7 @@ public class SecurityGroup {
public SecurityGroup build() {
return new SecurityGroup(id, tenantId, name, description, rules);
}
public T fromSecurityGroup(SecurityGroup in) {
return this
.id(in.getId())
@ -133,7 +133,7 @@ public class SecurityGroup {
this.name = name;
this.description = description;
// if empty, leave null so this doesn't serialize to json
this.rules = checkNotNull(rules, "rules").size() == 0 ? null : ImmutableSet.copyOf(rules);
this.rules = checkNotNull(rules, "rules").isEmpty() ? null : ImmutableSet.copyOf(rules);
}
public String getId() {
@ -175,12 +175,12 @@ public class SecurityGroup {
&& Objects.equal(this.description, that.description)
&& Objects.equal(this.rules, that.rules);
}
protected ToStringHelper string() {
return MoreObjects.toStringHelper(this)
.add("id", id).add("tenantId", tenantId).add("name", name).add("description", description).add("rules", rules);
}
@Override
public String toString() {
return string().toString();

View File

@ -136,11 +136,11 @@ public class CreateServerOptions implements MapBinder {
protected ToStringHelper string() {
ToStringHelper toString = MoreObjects.toStringHelper("").omitNullValues();
toString.add("keyName", keyName);
if (securityGroupNames.size() > 0)
if (!securityGroupNames.isEmpty())
toString.add("securityGroupNames", securityGroupNames);
if (metadata.size() > 0)
if (!metadata.isEmpty())
toString.add("metadata", metadata);
if (personality.size() > 0)
if (!personality.isEmpty())
toString.add("personality", personality);
if (adminPass != null)
toString.add("adminPassPresent", true);
@ -191,9 +191,9 @@ public class CreateServerOptions implements MapBinder {
ServerRequest server = new ServerRequest(checkNotNull(postParams.get("name"), "name parameter not present").toString(),
checkNotNull(postParams.get("imageRef"), "imageRef parameter not present").toString(),
checkNotNull(postParams.get("flavorRef"), "flavorRef parameter not present").toString());
if (metadata.size() > 0)
if (!metadata.isEmpty())
server.metadata = metadata;
if (personality.size() > 0)
if (!personality.isEmpty())
server.personality = personality;
if (keyName != null)
server.key_name = keyName;
@ -203,7 +203,7 @@ public class CreateServerOptions implements MapBinder {
server.user_data = base64().encode(userData);
if (configDrive)
server.configDrive = "true";
if (securityGroupNames.size() > 0) {
if (!securityGroupNames.isEmpty()) {
server.securityGroupNames = Sets.newLinkedHashSet();
for (String groupName : securityGroupNames) {
server.securityGroupNames.add(new NamedThingy(groupName));

View File

@ -126,15 +126,15 @@ public class LoadBalancer extends BaseLoadBalancer<Node, LoadBalancer> {
}
/**
* Broken out as a separate field because when LoadBalancers are returned from
* Broken out as a separate field because when LoadBalancers are returned from
* {@link LoadBalancerApi#list()}, no Nodes are returned (so you can't rely on getNodes().size())
* but a nodeCount is returned. When {@link LoadBalancerApi#get(int)} is called, nodes are
* returned but no nodeCount is returned.
*
* @return The number of Nodes in this LoadBalancer
*
* @return The number of Nodes in this LoadBalancer
*/
public int getNodeCount() {
return nodes.size() > 0 ? nodes.size() : nodeCount;
return !nodes.isEmpty() ? nodes.size() : nodeCount;
}
/**
@ -165,7 +165,7 @@ public class LoadBalancer extends BaseLoadBalancer<Node, LoadBalancer> {
public Metadata getMetadata() {
return metadata;
}
public URI getUri() {
return uri;
}
@ -343,7 +343,7 @@ public class LoadBalancer extends BaseLoadBalancer<Node, LoadBalancer> {
this.metadata = checkNotNull(metadata, "metadata");
return this;
}
public Builder uri(URI uri) {
this.uri = uri;
return this;

View File

@ -45,17 +45,17 @@ public class ParseAlgorithms implements Function<HttpResponse, List<String>>, In
@Override
public List<String> apply(HttpResponse response) {
Map<String, List<Map<String, String>>> map = json.apply(response);
if (map == null || map.size() == 0)
if (map == null || map.isEmpty())
throw new HttpResponseException("Unexpected JSON format returned.", null, response);
List<Map<String, String>> list = Iterables.get(map.values(), 0);
List<String> algorithms = Lists.newArrayList();
for (Map<String, String> nameAlgorithmPair : list) {
algorithms.add(Iterables.get(nameAlgorithmPair.values(), 0));
}
return algorithms;
}

View File

@ -51,7 +51,7 @@ public class ParseLoadBalancer implements Function<HttpResponse, LoadBalancer>,
public LoadBalancer apply(HttpResponse arg0) {
checkState(convertLB != null, "convertLB should be set by InvocationContext");
Map<String, LB> map = json.apply(arg0);
if (map == null || map.size() == 0)
if (map == null || map.isEmpty())
return null;
LB lb = Iterables.get(map.values(), 0);
return convertLB.apply(lb);
@ -64,9 +64,9 @@ public class ParseLoadBalancer implements Function<HttpResponse, LoadBalancer>,
ParseLoadBalancer setEndpointAndRegion(URI endpoint) {
String region = endpoint.getHost().substring(0, endpoint.getHost().indexOf('.'));
this.convertLB = factory.createForEndpointAndRegion(endpoint, region);
return this;
}
}

View File

@ -61,7 +61,7 @@ public class ParseLoadBalancers implements Function<HttpResponse, IterableWithMa
public IterableWithMarker<LoadBalancer> apply(HttpResponse arg0) {
LoadBalancers lbs = json.apply(arg0);
if (lbs.size() == 0)
if (lbs.isEmpty())
return IterableWithMarkers.EMPTY;
Iterable<LoadBalancer> transform = Iterables.transform(lbs, convertLB);

View File

@ -43,10 +43,10 @@ public class ParseNestedBoolean implements Function<HttpResponse, Boolean>, Invo
@Override
public Boolean apply(HttpResponse response) {
Map<String, Map<String, Boolean>> map = json.apply(response);
if (map == null || map.size() == 0)
if (map == null || map.isEmpty())
throw new HttpResponseException("Unexpected JSON format returned.", null, response);
return Iterables.get(Iterables.get(map.values(), 0).values(), 0);
}

View File

@ -44,7 +44,7 @@ public class ParseNestedString implements Function<HttpResponse, String>, Invoca
public String apply(HttpResponse response) {
Map<String, Map<String, String>> map = json.apply(response);
if (map == null || map.size() == 0)
if (map == null || map.isEmpty())
throw new HttpResponseException("Unexpected JSON format returned.", null, response);
return Iterables.get(Iterables.get(map.values(), 0).values(), 0);

View File

@ -47,10 +47,10 @@ public class ParseNode implements Function<HttpResponse, Node>, InvocationContex
@Override
public Node apply(HttpResponse response) {
Map<String, NodeWithCLBMetadata> map = json.apply(response);
if (map == null || map.size() == 0)
if (map == null || map.isEmpty())
return null;
NodeWithCLBMetadata nodeWithCLBMetadata = Iterables.get(map.values(), 0);
Node node = Node.builder()
.address(nodeWithCLBMetadata.getAddress())
@ -62,7 +62,7 @@ public class ParseNode implements Function<HttpResponse, Node>, InvocationContex
.status(nodeWithCLBMetadata.status)
.metadata(ParseMetadata.transformCLBMetadataToMetadata(nodeWithCLBMetadata.metadata))
.build();
return node;
}
@ -70,7 +70,7 @@ public class ParseNode implements Function<HttpResponse, Node>, InvocationContex
public ParseNode setContext(HttpRequest request) {
return this;
}
/**
* This class is here only to deal with the metadata format in CLB.
*/

View File

@ -44,10 +44,10 @@ public class ParseSessionPersistence implements Function<HttpResponse, SessionPe
@Override
public SessionPersistence apply(HttpResponse response) {
Map<String, Map<String, SessionPersistence>> map = json.apply(response);
if (map == null || map.size() == 0)
if (map == null || map.isEmpty())
throw new HttpResponseException("Unexpected connection logging format returned.", null, response);
else if (Iterables.get(map.values(), 0).size() == 0)
else if (Iterables.get(map.values(), 0).isEmpty())
return null;
else
return Iterables.get(Iterables.get(map.values(), 0).values(), 0);

View File

@ -122,7 +122,7 @@ public class LoadBalancerApiLiveTest extends BaseCloudLoadBalancersApiLiveTest {
assert lb.getStatus() != null : lb;
assert lb.getCreated() != null : lb;
assert lb.getUpdated() != null : lb;
assert lb.getVirtualIPs().size() > 0 : lb;
assert !lb.getVirtualIPs().isEmpty() : lb;
// node info not available during list;
assert lb.getNodes().size() == 0 : lb;
@ -139,7 +139,7 @@ public class LoadBalancerApiLiveTest extends BaseCloudLoadBalancersApiLiveTest {
assertEquals(getDetails.getUpdated(), lb.getUpdated());
assertEquals(getDetails.getVirtualIPs(), lb.getVirtualIPs());
// node info not available during list;
assert getDetails.getNodes().size() > 0 : lb;
assert !getDetails.getNodes().isEmpty() : lb;
} catch (AssertionError e) {
throw new AssertionError(String.format("%s\n%s - %s", e.getMessage(), getDetails, lb));
}

View File

@ -51,7 +51,7 @@ public class NodeApiLiveTest extends BaseCloudLoadBalancersApiLiveTest {
private Map<LoadBalancer, Set<Node>> nodes = Maps.newHashMap();
public void testCreateLoadBalancers() {
assertTrue(api.getConfiguredRegions().size() > 0, "Need to have some regions!");
assertTrue(!api.getConfiguredRegions().isEmpty(), "Need to have some regions!");
Logger.getAnonymousLogger().info("running against regions " + api.getConfiguredRegions());
for (String region : api.getConfiguredRegions()) {
Logger.getAnonymousLogger().info("starting lb in region " + region);

View File

@ -77,11 +77,11 @@ public class HostedZoneApiLiveTest extends BaseRoute53ApiLiveTest {
try {
checkHostedZone(newHostedZone.getZone());
assertEquals(newHostedZone.getChange().getStatus(), PENDING, "invalid status on zone " + newHostedZone);
assertTrue(newHostedZone.getNameServers().size() > 0, "no name servers for zone " + newHostedZone);
assertTrue(!newHostedZone.getNameServers().isEmpty(), "no name servers for zone " + newHostedZone);
assertEquals(newHostedZone.getZone().getName(), name);
assertEquals(newHostedZone.getZone().getCallerReference(), nonce);
assertEquals(newHostedZone.getZone().getComment().get(), comment);
assertTrue(inSync.apply(newHostedZone.getChange()), "zone didn't sync " + newHostedZone);
} finally {
Change delete = api().delete(newHostedZone.getZone().getId());

View File

@ -86,7 +86,7 @@ public class S3RestClientModule<S extends S3Client, A extends S3AsyncClient> ext
protected CacheLoader<String, Optional<String>> bucketToRegion(@Region Supplier<Set<String>> regionSupplier,
final S3Client client) {
Set<String> regions = regionSupplier.get();
if (regions.size() == 0) {
if (regions.isEmpty()) {
return new CacheLoader<String, Optional<String>>() {
@Override

View File

@ -51,6 +51,7 @@ import org.jclouds.http.options.GetOptions;
import org.jclouds.javax.annotation.Nullable;
import org.jclouds.lifecycle.Closer;
import org.jclouds.s3.S3AsyncClient;
import org.jclouds.s3.blobstore.S3AsyncBlobStore;
import org.jclouds.s3.blobstore.functions.BlobToObject;
import org.jclouds.s3.blobstore.functions.BlobToObjectMetadata;
import org.jclouds.s3.blobstore.functions.BucketToContainerListOptions;
@ -223,7 +224,7 @@ public class StubS3AsyncClient implements S3AsyncClient {
* to match S3 which substitutes each email address grantee with that user's corresponding ID. In
* short, although you can PUT email address grantees, these are actually subsequently returned
* by S3 as canonical user grantees.
*
*
* @param acl
* @return
*/
@ -258,7 +259,7 @@ public class StubS3AsyncClient implements S3AsyncClient {
public ListenableFuture<Boolean> deleteBucketIfEmpty(String bucketName) {
Boolean returnVal = true;
if (containerToBlobs.containsKey(bucketName)) {
if (containerToBlobs.get(bucketName).size() == 0)
if (containerToBlobs.get(bucketName).isEmpty())
containerToBlobs.remove(bucketName);
else
returnVal = false;

View File

@ -42,7 +42,7 @@ public class BindAttributeNamesToIndexedFormParams implements Binder {
builder.put("AttributeName." + (i++ + 1), o.toString());
}
ImmutableMultimap<String, String> forms = builder.build();
return (R) (forms.size() == 0 ? request : request.toBuilder().replaceFormParams(forms).build());
return (R) (forms.isEmpty() ? request : request.toBuilder().replaceFormParams(forms).build());
}
}

View File

@ -28,7 +28,7 @@ import com.google.common.collect.Multimap;
/**
* Options used to receive a message from a queue.
*
*
* @see <a
* href="http://docs.amazonwebservices.com/AWSSimpleQueueService/2011-10-01/APIReference/Query_QueryCreateQueue.html"
* >docs</a>
@ -41,10 +41,10 @@ public class CreateQueueOptions extends BaseHttpRequestOptions implements Clonea
* The duration (in seconds) that the received messages are hidden from
* subsequent retrieve requests after being retrieved by a CreateQueue
* request.
*
*
* @param visibilityTimeout
* Constraints: 0 to 43200 (maximum 12 hours)
*
*
* Default: The visibility timeout for the queue
*/
public CreateQueueOptions visibilityTimeout(int visibilityTimeout) {
@ -94,7 +94,7 @@ public class CreateQueueOptions extends BaseHttpRequestOptions implements Clonea
public Multimap<String, String> buildFormParameters() {
Multimap<String, String> params = super.buildFormParameters();
ImmutableMap<String, String> attributes = this.attributes.build();
if (attributes.size() > 0) {
if (!attributes.isEmpty()) {
int nameIndex = 1;
for (Entry<String, String> attribute : attributes.entrySet()) {
params.put("Attribute." + nameIndex + ".Name", attribute.getKey());
@ -139,7 +139,7 @@ public class CreateQueueOptions extends BaseHttpRequestOptions implements Clonea
@Override
public String toString() {
ImmutableMap<String, String> attributes = this.attributes.build();
return MoreObjects.toStringHelper(this).omitNullValues().add("attributes", attributes.size() > 0 ? attributes : null)
return MoreObjects.toStringHelper(this).omitNullValues().add("attributes", !attributes.isEmpty() ? attributes : null)
.toString();
}
}

View File

@ -25,7 +25,7 @@ import com.google.common.collect.Multimap;
/**
* Options used to receive a message from a queue.
*
*
* @see <a
* href="http://docs.amazonwebservices.com/AWSSimpleQueueService/2011-10-01/APIReference/Query_QueryReceiveMessage.html"
* >docs</a>
@ -39,10 +39,10 @@ public class ReceiveMessageOptions extends BaseHttpRequestOptions implements Clo
* The duration (in seconds) that the received messages are hidden from
* subsequent retrieve requests after being retrieved by a ReceiveMessage
* request.
*
*
* @param visibilityTimeout
* Constraints: 0 to 43200 (maximum 12 hours)
*
*
* Default: The visibility timeout for the queue
*/
public ReceiveMessageOptions visibilityTimeout(Integer visibilityTimeout) {
@ -52,18 +52,18 @@ public class ReceiveMessageOptions extends BaseHttpRequestOptions implements Clo
/**
* The attribute you want to get.
*
*
* All - returns all values.
*
*
* SenderId - returns the AWS account number (or the IP address, if anonymous
* access is allowed) of the sender.
*
*
* SentTimestamp - returns the time when the message was sent (epoch time in
* milliseconds).
*
*
* ApproximateReceiveCount - returns the number of times a message has been
* received but not deleted.
*
*
* ApproximateFirstReceiveTimestamp - returns the time when the message was
* first received (epoch time in milliseconds).
*/
@ -110,7 +110,7 @@ public class ReceiveMessageOptions extends BaseHttpRequestOptions implements Clo
if (visibilityTimeout != null)
params.put("VisibilityTimeout", visibilityTimeout.toString());
ImmutableSet<String> attributes = this.attributes.build();
if (attributes.size() > 0) {
if (!attributes.isEmpty()) {
int nameIndex = 1;
for (String attribute : attributes) {
params.put("AttributeName." + nameIndex, attribute);
@ -156,6 +156,6 @@ public class ReceiveMessageOptions extends BaseHttpRequestOptions implements Clo
public String toString() {
ImmutableSet<String> attributes = this.attributes.build();
return MoreObjects.toStringHelper(this).omitNullValues().add("visibilityTimeout", visibilityTimeout)
.add("attributes", attributes.size() > 0 ? attributes : null).toString();
.add("attributes", !attributes.isEmpty() ? attributes : null).toString();
}
}

View File

@ -67,7 +67,7 @@ public class BindMapToIndexedFormParams implements Binder {
amazonOneBasedIndex++;
}
Multimap<String, String> forms = Multimaps.forMap(builder.build());
return forms.size() == 0 ? request : (R) request.toBuilder().replaceFormParams(forms).build();
return forms.isEmpty() ? request : (R) request.toBuilder().replaceFormParams(forms).build();
}
}

View File

@ -70,7 +70,7 @@ public class BindTableToIndexedFormParams implements Binder {
amazonOneBasedIndex++;
}
Multimap<String, String> forms = Multimaps.forMap(builder.build());
return forms.size() == 0 ? request : (R) request.toBuilder().replaceFormParams(forms).build();
return forms.isEmpty() ? request : (R) request.toBuilder().replaceFormParams(forms).build();
}
}

View File

@ -130,7 +130,7 @@ public class AWSUtils {
builder.put(prefix + "." + (i++ + 1), checkNotNull(o.toString(), prefix.toLowerCase() + "s[" + i + "]"));
}
ImmutableMultimap<String, String> forms = builder.build();
return forms.size() == 0 ? request : (R) request.toBuilder().replaceFormParams(forms).build();
return forms.isEmpty() ? request : (R) request.toBuilder().replaceFormParams(forms).build();
}
public static <R extends HttpRequest> R indexStringArrayToFormValuesWithPrefix(R request, String prefix, Object input) {
@ -142,7 +142,7 @@ public class AWSUtils {
builder.put(prefix + "." + (i + 1), checkNotNull(values[i], prefix.toLowerCase() + "s[" + i + "]"));
}
ImmutableMultimap<String, String> forms = builder.build();
return forms.size() == 0 ? request : (R) request.toBuilder().replaceFormParams(forms).build();
return forms.isEmpty() ? request : (R) request.toBuilder().replaceFormParams(forms).build();
}
public static <R extends HttpRequest> R indexMapToFormValuesWithPrefix(R request, String prefix, String keySuffix, String valueSuffix, Object input) {
@ -158,7 +158,7 @@ public class AWSUtils {
i++;
}
ImmutableMultimap<String, String> forms = builder.build();
return forms.size() == 0 ? request : (R) request.toBuilder().replaceFormParams(forms).build();
return forms.isEmpty() ? request : (R) request.toBuilder().replaceFormParams(forms).build();
}
public static <R extends HttpRequest> R indexMultimapToFormValuesWithPrefix(R request, String prefix, String keySuffix, String valueSuffix, Object input) {

View File

@ -207,7 +207,7 @@ public class ParallelMultipartUploadStrategy implements AsyncMultipartUploadStra
}
latch.await();
// handling retries
while (errors.get() <= maxRetries && toRetry.size() > 0) {
while (errors.get() <= maxRetries && !toRetry.isEmpty()) {
int atOnce = Math.min(Math.min(toRetry.size(), errors.get()), parallelDegree);
CountDownLatch retryLatch = new CountDownLatch(atOnce);
for (int i = 0; i < atOnce; i++) {

View File

@ -95,7 +95,7 @@ public class BindInstantiateVAppTemplateParamsToXmlPayload implements MapBinder
InstantiateVAppTemplateOptions options = findOptionsInArgsOrNull(gRequest);
if (options != null) {
if (options.getNetworkConfig().size() > 0)
if (!options.getNetworkConfig().isEmpty())
networkConfig = ImmutableSet
.copyOf(transform(options.getNetworkConfig(), networkConfigDecorator));
} else {
@ -125,7 +125,7 @@ public class BindInstantiateVAppTemplateParamsToXmlPayload implements MapBinder
VAppTemplate vAppTemplate = templateCache.getUnchecked(template);
checkArgument(vAppTemplate != null, "vAppTemplate %s not found!", template);
vms = vAppTemplate.getChildren();
checkArgument(vms.size() > 0, "no vms found in vAppTemplate %s", vAppTemplate);
checkArgument(!vms.isEmpty(), "no vms found in vAppTemplate %s", vAppTemplate);
}
return vms;
}

View File

@ -53,7 +53,7 @@ public class HardwareForVApp implements Function<VApp, Hardware> {
public Hardware apply(VApp from) {
checkNotNull(from, "VApp");
// TODO make this work with composite vApps
Vm vm = from.getChildren().size() == 0 ? null : Iterables.get(from.getChildren(), 0);
Vm vm = from.getChildren().isEmpty() ? null : Iterables.get(from.getChildren(), 0);
if (vm == null)
return null;

View File

@ -63,7 +63,7 @@ public class ValidateVAppTemplateAndReturnEnvelopeOrThrowIllegalArgumentExceptio
Envelope ovf;
try {
ovf = envelopes.get(from.getHref());
checkArgument(ovf.getVirtualSystem().getVirtualHardwareSections().size() > 0,
checkArgument(!ovf.getVirtualSystem().getVirtualHardwareSections().isEmpty(),
"no hardware sections exist in ovf %s", ovf);
} catch (ExecutionException e) {
throw new IllegalArgumentException("no ovf envelope found for: " + from, e);

View File

@ -85,7 +85,7 @@ public class InstantiateVAppTemplateWithGroupEncodedIntoNameThenCustomizeDeployA
this.networkConfigurationForNetworkAndOptions = networkConfigurationForNetworkAndOptions;
this.buildVersion = buildVersion;
}
/**
* per john ellis at bluelock, vCloud Director 1.5 is more strict than earlier versions.
* <p/>
@ -95,19 +95,19 @@ public class InstantiateVAppTemplateWithGroupEncodedIntoNameThenCustomizeDeployA
*/
public static enum ComputerNameValidator {
INSTANCE;
private DnsNameValidator validator;
ComputerNameValidator() {
this.validator = new DnsNameValidator(3, 15);
}
public void validate(@Nullable String t) throws IllegalArgumentException {
this.validator.validate(t);
}
}
public NodeAndInitialCredentials<VApp> createNodeWithGroupEncodedIntoName(String group, String name, Template template) {
// no sense waiting until failures occur later
ComputerNameValidator.INSTANCE.validate(name);
@ -156,11 +156,11 @@ public class InstantiateVAppTemplateWithGroupEncodedIntoNameThenCustomizeDeployA
getCredentialsFrom(vAppResponse));
}
@VisibleForTesting
protected VApp instantiateVAppFromTemplate(String name, Template template) {
VCloudTemplateOptions vOptions = VCloudTemplateOptions.class.cast(template.getOptions());
URI templateId = URI.create(template.getImage().getId());
VAppTemplate vAppTemplate = vAppTemplates.getUnchecked(templateId);
@ -175,7 +175,7 @@ public class InstantiateVAppTemplateWithGroupEncodedIntoNameThenCustomizeDeployA
Network networkToConnect = get(vAppTemplate.getNetworkSection().getNetworks(), 0);
NetworkConfig config = networkConfigurationForNetworkAndOptions.apply(networkToConnect, vOptions);
// note that in VCD 1.5, the network name after instantiation will be the same as the parent
@ -217,7 +217,7 @@ public class InstantiateVAppTemplateWithGroupEncodedIntoNameThenCustomizeDeployA
}
};
public void waitForTask(Task task) {
if (!successTester.apply(task.getHref())) {
throw new TaskStillRunningException(task);
@ -251,7 +251,7 @@ public class InstantiateVAppTemplateWithGroupEncodedIntoNameThenCustomizeDeployA
Vm vm = get(vApp.getChildren(), 0);
NetworkConnectionSection net = vm.getNetworkConnectionSection();
checkArgument(net.getConnections().size() > 0, "no connections on vm %s", vm);
checkArgument(!net.getConnections().isEmpty(), "no connections on vm %s", vm);
NetworkConnection toConnect = findWithPoolAllocationOrFirst(net);

View File

@ -179,13 +179,13 @@ public class VCloudComputeServiceAdapter implements ComputeServiceAdapter<VApp,
URI id = URI.create(in);
return client.getVAppApi().getVApp(id);
}
@Override
public VAppTemplate getImage(String in) {
URI id = URI.create(in);
return client.getVAppTemplateApi().getVAppTemplate(id);
}
@Override
public void destroyNode(String id) {
URI vappId = URI.create(checkNotNull(id, "node.id"));
@ -215,7 +215,7 @@ public class VCloudComputeServiceAdapter implements ComputeServiceAdapter<VApp,
VApp waitForPendingTasksToComplete(URI vappId) {
VApp vApp = client.getVAppApi().getVApp(vappId);
if (vApp.getTasks().size() == 0)
if (vApp.getTasks().isEmpty())
return vApp;
for (Task task : vApp.getTasks())
waitForTask(task);
@ -224,7 +224,7 @@ public class VCloudComputeServiceAdapter implements ComputeServiceAdapter<VApp,
VApp cancelAnyRunningTasks(URI vappId) {
VApp vApp = client.getVAppApi().getVApp(vappId);
if (vApp.getTasks().size() == 0)
if (vApp.getTasks().isEmpty())
return vApp;
for (Task task : vApp.getTasks()) {
try {
@ -238,7 +238,7 @@ public class VCloudComputeServiceAdapter implements ComputeServiceAdapter<VApp,
}
public void waitForTask(Task task) {
if (!successTester.apply(task.getHref()))
if (!successTester.apply(task.getHref()))
throw new TaskStillRunningException(task);
}

View File

@ -44,7 +44,7 @@ public class VCloudComputeUtils {
public static CIMOperatingSystem toComputeOs(VApp vApp) {
// TODO we need to change the design so that it doesn't assume single-vms
return vApp.getChildren().size() > 0 ? toComputeOs(Iterables.get(vApp.getChildren(), 0)) : null;
return !vApp.getChildren().isEmpty() ? toComputeOs(Iterables.get(vApp.getChildren(), 0)) : null;
}
public static CIMOperatingSystem toComputeOs(Vm vm) {
@ -52,7 +52,7 @@ public class VCloudComputeUtils {
}
public static String getVirtualSystemIdentifierOfFirstVMIn(VApp vApp) {
return vApp.getChildren().size() > 0 ? getVirtualSystemIdentifierOf(Iterables.get(vApp.getChildren(), 0)) : null;
return !vApp.getChildren().isEmpty() ? getVirtualSystemIdentifierOf(Iterables.get(vApp.getChildren(), 0)) : null;
}
public static String getVirtualSystemIdentifierOf(Vm vm) {
@ -62,11 +62,11 @@ public class VCloudComputeUtils {
}
public static LoginCredentials getCredentialsFrom(VApp vApp) {
return vApp.getChildren().size() > 0 ? getCredentialsFrom(Iterables.get(vApp.getChildren(), 0)) : null;
return !vApp.getChildren().isEmpty() ? getCredentialsFrom(Iterables.get(vApp.getChildren(), 0)) : null;
}
public static LoginCredentials getCredentialsFrom(VAppTemplate vApp) {
return vApp.getChildren().size() > 0 ? getCredentialsFrom(Iterables.get(vApp.getChildren(), 0)) : null;
return !vApp.getChildren().isEmpty() ? getCredentialsFrom(Iterables.get(vApp.getChildren(), 0)) : null;
}
public static LoginCredentials getCredentialsFrom(Vm vm) {
@ -78,7 +78,7 @@ public class VCloudComputeUtils {
public static Set<String> getIpsFromVApp(VApp vApp) {
// TODO make this work with composite vApps
if (vApp.getChildren().size() == 0)
if (vApp.getChildren().isEmpty())
return ImmutableSet.of();
Builder<String> ips = ImmutableSet.builder();
Vm vm = Iterables.get(vApp.getChildren(), 0);

View File

@ -122,7 +122,7 @@ public class VCloudHttpApiModule extends HttpApiModule<VCloudApi> {
public VCloudSession get() {
return login.login();
}
@Override
public String toString() {
return MoreObjects.toStringHelper(login).add("method", "login").toString();
@ -362,7 +362,7 @@ public class VCloudHttpApiModule extends HttpApiModule<VCloudApi> {
@Override
public URI get() {
SortedMap<String, URI> versions = versionService.getSupportedVersions();
checkState(versions.size() > 0, "No versions present");
checkState(!versions.isEmpty(), "No versions present");
checkState(versions.containsKey(version), "version " + version + " not present in: " + versions);
return versions.get(version);
}

View File

@ -45,7 +45,7 @@ public class FirewallService {
/**
* @return Firewall rules for the network
*
*
* @since vcloud api 0.8
*/
public List<FirewallRule> getFirewallRules() {
@ -54,7 +54,7 @@ public class FirewallService {
/**
* @return true if the service is enabled
*
*
* @since vcloud api 0.9
*/
@Nullable
@ -80,7 +80,7 @@ public class FirewallService {
@Override
public String toString() {
ToStringHelper helper = MoreObjects.toStringHelper("").omitNullValues().add("enabled", enabled);
if (firewallRules.size() > 0)
if (!firewallRules.isEmpty())
helper.add("firewallRules", firewallRules);
return helper.toString();
}

View File

@ -72,7 +72,7 @@ public class IpScope {
/**
* @return IP address of the network gateway
*
*
* @since vcloud api 0.8
*/
@Nullable
@ -82,7 +82,7 @@ public class IpScope {
/**
* @return netmask to apply to addresses on the network
*
*
* @since vcloud api 0.8
*/
@Nullable
@ -92,7 +92,7 @@ public class IpScope {
/**
* @return IP address of the primary DNS server for this network
*
*
* @since vcloud api 0.9
*/
@Nullable
@ -102,7 +102,7 @@ public class IpScope {
/**
* @return IP address of the secondary DNS server for this network
*
*
* @since vcloud api 0.9
*/
@Nullable
@ -112,7 +112,7 @@ public class IpScope {
/**
* @return suffix to be applied when resolving hostnames that are not fullyqualified.
*
*
* @since vcloud api 0.9
*/
@Nullable
@ -122,7 +122,7 @@ public class IpScope {
/**
* @return A container for IpRange elements.
*
*
* @since vcloud api 0.9
*/
public Set<IpRange> getIpRanges() {
@ -131,7 +131,7 @@ public class IpScope {
/**
* @return A list of addresses allocated from any of the specified IpRanges
*
*
* @since vcloud api 0.9
*/
public Set<String> getAllocatedIpAddresses() {
@ -161,9 +161,9 @@ public class IpScope {
public String toString() {
ToStringHelper helper = MoreObjects.toStringHelper("").omitNullValues().add("inherited", inherited).add("gateway", gateway)
.add("netmask", netmask).add("dns1", dns1).add("dns2", dns2).add("dnsSuffix", dnsSuffix);
if (ipRanges.size() > 0)
if (!ipRanges.isEmpty())
helper.add("ipRanges", ipRanges);
if (allocatedIpAddresses.size() > 0)
if (!allocatedIpAddresses.isEmpty())
helper.add("allocatedIpAddresses", allocatedIpAddresses);
return helper.toString();
}

View File

@ -53,7 +53,7 @@ public class NatService {
/**
* @return Nat rules for the network
*
*
* @since vcloud api 0.8
*/
public List<NatRule> getNatRules() {
@ -62,7 +62,7 @@ public class NatService {
/**
* @return true if the service is enabled
*
*
* @since vcloud api 0.9
*/
public boolean isEnabled() {
@ -71,7 +71,7 @@ public class NatService {
/**
* @return specifies how Network Address Translation is implemented by the NAT service
*
*
* @since vcloud api 0.9
*/
@Nullable
@ -81,7 +81,7 @@ public class NatService {
/**
* @return specifies how packets are handled by the NAT service.
*
*
* @since vcloud api 0.9
*/
@Nullable
@ -109,7 +109,7 @@ public class NatService {
public String toString() {
ToStringHelper helper = MoreObjects.toStringHelper("").omitNullValues().add("enabled", enabled)
.add("type", type).add("policy", policy);
if (natRules.size() > 0)
if (!natRules.isEmpty())
helper.add("natRules", natRules);
return helper.toString();
}

View File

@ -189,9 +189,9 @@ public class OrgNetworkImpl extends ReferenceTypeImpl implements OrgNetwork {
public ToStringHelper string() {
ToStringHelper helper = super.string().add("org", org).add("description", description)
.add("configuration", configuration).add("networkPool", networkPool);
if (allowedExternalIpAddresses.size() > 0)
if (!allowedExternalIpAddresses.isEmpty())
helper.add("allowedExternalIpAddresses", allowedExternalIpAddresses);
if (tasks.size() > 0)
if (!tasks.isEmpty())
helper.add("tasks", tasks);
return helper;
}

View File

@ -39,7 +39,7 @@ public class DefaultNetworkNameInTemplate implements Function<VAppTemplate, Stri
public String apply(VAppTemplate vAppTemplate) {
checkArgument(vAppTemplate != null, "vAppTemplate was null!");
Set<Network> networks = vAppTemplate.getNetworkSection().getNetworks();
checkArgument(networks.size() > 0, "no networks found in vAppTemplate %s", vAppTemplate);
checkArgument(!networks.isEmpty(), "no networks found in vAppTemplate %s", vAppTemplate);
if (networks.size() > 1)
logger.warn("multiple networks found for %s, choosing first from: %s", vAppTemplate.getName(), networks);
return get(networks, 0).getName();

View File

@ -67,7 +67,7 @@ public class OrgAndVDCToLocationSupplier extends JustProvider implements Locatio
protected Builder<Location> buildJustProviderOrVDCs() {
Builder<Location> locations = ImmutableSet.builder();
Location provider = Iterables.getOnlyElement(super.get());
if (orgNameToResource.get().size() == 0)
if (orgNameToResource.get().isEmpty())
return locations.add(provider);
Map<String, Supplier<Set<String>>> isoCodesById = isoCodesByIdSupplier.get();
for (ReferenceType org : orgNameToResource.get().values()) {

View File

@ -76,7 +76,7 @@ public class InstantiateVAppTemplateOptions {
/**
* {@networkConfig VAppTemplate}s have internal networks that can be
* connected in order to access the internet or other external networks.
*
*
* <h4>default behaviour if you don't use this option</h4> By default, we
* connect the first internal {@networkConfig
* org.jclouds.vcloud.domain.VAppTemplate#getNetworkSection network in the
@ -153,16 +153,16 @@ public class InstantiateVAppTemplateOptions {
public int hashCode() {
return Objects.hashCode(networkConfig, customizeOnInstantiate, description, deploy, powerOn);
}
@Override
public String toString() {
return string().toString();
}
protected ToStringHelper string() {
ToStringHelper toString = MoreObjects.toStringHelper("").omitNullValues();
toString.add("customizeOnInstantiate", customizeOnInstantiate).add("description", description);
if (networkConfig.size() > 0)
if (!networkConfig.isEmpty())
toString.add("networkConfig", networkConfig);
if (!deploy)
toString.add("deploy", deploy);

View File

@ -46,7 +46,7 @@ public class OnlyReferenceTypeFirstWithNameMatchingConfigurationKeyOrDefault imp
@Override
public ReferenceType apply(Iterable<ReferenceType> referenceTypes) {
checkNotNull(referenceTypes, "referenceTypes");
checkArgument(Iterables.size(referenceTypes) > 0,
checkArgument(!Iterables.isEmpty(referenceTypes),
"No referenceTypes corresponding to configuration key %s present", configurationKey);
if (Iterables.size(referenceTypes) == 1)
return Iterables.getLast(referenceTypes);

View File

@ -71,11 +71,11 @@ public class VCloudResourceAllocationSettingDataHandler extends ResourceAllocati
Map<String, String> attributes = SaxUtils.cleanseAttributes(attrs);
if (qName.endsWith("Link")) {
this.edit = Utils.newReferenceType(attributes);
} else if (qName.endsWith("HostResource") && attributes.size() > 0) {
} else if (qName.endsWith("HostResource") && !attributes.isEmpty()) {
capacity = Long.parseLong(attributes.get("capacity"));
busType = Integer.parseInt(attributes.get("busType"));
busSubType = attributes.get("busSubType");
} else if (qName.endsWith("Connection") && attributes.size() > 0) {
} else if (qName.endsWith("Connection") && !attributes.isEmpty()) {
ipAddress = attributes.get("ipAddress");
primaryNetworkConnection = Boolean.parseBoolean(attributes.get("primaryNetworkConnection"));
ipAddressingMode = attributes.get("ipAddressingMode");

View File

@ -467,7 +467,7 @@ public class LocalAsyncBlobStore extends BaseAsyncBlobStore {
}
blob = copyBlob(blob);
if (options.getRanges() != null && options.getRanges().size() > 0) {
if (options.getRanges() != null && !options.getRanges().isEmpty()) {
byte[] data;
try {
data = ByteStreams2.toByteArrayAndClose(blob.getPayload().openStream());

Some files were not shown because too many files have changed in this diff Show More