From 2789a515418100c69d32a51fa377ef372d876c84 Mon Sep 17 00:00:00 2001 From: Stu Arnett <4664091+twincitiesguy@users.noreply.github.com> Date: Fri, 16 Jul 2021 16:34:10 -0500 Subject: [PATCH] general code cleanup to remove most IntelliJ warnings (#16) --- src/main/java/com/emc/rest/smart/Host.java | 7 ++- .../java/com/emc/rest/smart/HostStats.java | 5 -- .../java/com/emc/rest/smart/LoadBalancer.java | 14 +++--- .../rest/smart/OctetStreamXmlProvider.java | 2 +- .../com/emc/rest/smart/PollingDaemon.java | 6 +-- .../emc/rest/smart/SizeOverrideWriter.java | 4 +- .../emc/rest/smart/SmartClientFactory.java | 2 +- .../java/com/emc/rest/smart/SmartConfig.java | 6 +-- .../java/com/emc/rest/smart/SmartFilter.java | 14 ++---- .../rest/smart/ecs/EcsHostListProvider.java | 22 ++++----- .../com/emc/rest/smart/ecs/ListDataNode.java | 2 +- .../com/emc/rest/smart/ecs/PingResponse.java | 6 +-- src/main/java/com/emc/rest/smart/ecs/Vdc.java | 6 +-- .../java/com/emc/rest/smart/ecs/VdcHost.java | 2 +- .../com/emc/rest/util/SizedInputStream.java | 4 +- .../java/com/emc/rest/util/StreamUtil.java | 4 +- .../java/com/emc/rest/smart/HostTest.java | 4 +- .../com/emc/rest/smart/LoadBalancerTest.java | 8 +-- .../com/emc/rest/smart/SmartClientTest.java | 33 ++++++------- .../com/emc/rest/smart/TestHealthCheck.java | 6 +-- .../smart/ecs/EcsHostListProviderTest.java | 19 +++---- .../java/com/emc/util/RequestSimulator.java | 49 +++++++++---------- 22 files changed, 101 insertions(+), 124 deletions(-) diff --git a/src/main/java/com/emc/rest/smart/Host.java b/src/main/java/com/emc/rest/smart/Host.java index 45c5a74..c1a91d3 100644 --- a/src/main/java/com/emc/rest/smart/Host.java +++ b/src/main/java/com/emc/rest/smart/Host.java @@ -42,14 +42,13 @@ * */ public class Host implements HostStats { - private static final Logger log = LoggerFactory.getLogger(Host.class); public static final int DEFAULT_ERROR_WAIT_MS = 1500; public static final int LOG_DELAY = 60000; // 1 minute public static final int MAX_COOL_DOWN_EXP = 4; - private String name; + private final String name; private boolean healthy = true; protected int errorWaitTime = DEFAULT_ERROR_WAIT_MS; @@ -81,7 +80,7 @@ public synchronized void connectionClosed() { if (openConnections < 0) { long currentTime = System.currentTimeMillis(); if (currentTime - lastLogTime > LOG_DELAY) { - log.warn("openConnections for host {} is {} !", this.toString(), Integer.toString(openConnections)); + log.warn("openConnections for host {} is {} !", this, openConnections); lastLogTime = currentTime; } } @@ -174,7 +173,7 @@ public int hashCode() { @Override public String toString() { return String.format("%s{totalConnections=%d, totalErrors=%d, openConnections=%d, lastConnectionTime=%s}", - name, totalConnections, totalErrors, openConnections, new Date(lastConnectionTime).toString()); + name, totalConnections, totalErrors, openConnections, new Date(lastConnectionTime)); } public int getErrorWaitTime() { diff --git a/src/main/java/com/emc/rest/smart/HostStats.java b/src/main/java/com/emc/rest/smart/HostStats.java index 4452c96..4fc6f91 100644 --- a/src/main/java/com/emc/rest/smart/HostStats.java +++ b/src/main/java/com/emc/rest/smart/HostStats.java @@ -29,16 +29,11 @@ import java.util.Date; public interface HostStats { - long getTotalConnections(); - long getTotalErrors(); - int getOpenConnections(); - Date getLastConnectionTime(); - } diff --git a/src/main/java/com/emc/rest/smart/LoadBalancer.java b/src/main/java/com/emc/rest/smart/LoadBalancer.java index 97e4d34..3eebc14 100644 --- a/src/main/java/com/emc/rest/smart/LoadBalancer.java +++ b/src/main/java/com/emc/rest/smart/LoadBalancer.java @@ -29,7 +29,7 @@ import java.util.*; public class LoadBalancer { - private final Deque hosts = new ArrayDeque(); + private final Deque hosts = new ArrayDeque<>(); private List vetoRules; public LoadBalancer(List initialHosts) { @@ -92,14 +92,14 @@ protected boolean shouldVeto(Host host, Map requestProperties) { * Returns a list of all known hosts. This list is a clone; modification will not affect the load balancer */ public synchronized List getAllHosts() { - return new ArrayList(hosts); + return new ArrayList<>(hosts); } /** * Returns stats for all active hosts in this load balancer */ public synchronized HostStats[] getHostStats() { - return hosts.toArray(new HostStats[hosts.size()]); + return hosts.toArray(new HostStats[0]); } /** @@ -138,9 +138,9 @@ public long getOpenConnections() { /** * Ensure this method is called sparingly as it will block getTopHost() calls, pausing all new connections! */ - protected void updateHosts(List updatedHosts) throws Exception { + protected void updateHosts(List updatedHosts) { // don't modify the parameter - List hostList = new ArrayList(updatedHosts); + List hostList = new ArrayList<>(updatedHosts); // remove hosts from stored list that are not present in updated list // remove hosts in updated list that are already present in stored list @@ -166,9 +166,7 @@ protected void updateHosts(List updatedHosts) throws Exception { } // what's left in the updated list are new hosts, so add them - for (Host newHost : hostList) { - hosts.add(newHost); - } + hosts.addAll(hostList); } } diff --git a/src/main/java/com/emc/rest/smart/OctetStreamXmlProvider.java b/src/main/java/com/emc/rest/smart/OctetStreamXmlProvider.java index 55e084d..326da78 100644 --- a/src/main/java/com/emc/rest/smart/OctetStreamXmlProvider.java +++ b/src/main/java/com/emc/rest/smart/OctetStreamXmlProvider.java @@ -48,7 +48,7 @@ @Produces("application/octet-stream") @Consumes("application/octet-stream") public class OctetStreamXmlProvider implements MessageBodyReader { - private MessageBodyReader delegate; + private final MessageBodyReader delegate; public OctetStreamXmlProvider(@Context Injectable spf, @Context Providers ps) { this.delegate = new XMLRootElementProvider.General(spf, ps); diff --git a/src/main/java/com/emc/rest/smart/PollingDaemon.java b/src/main/java/com/emc/rest/smart/PollingDaemon.java index 1f3b33b..3710bc5 100644 --- a/src/main/java/com/emc/rest/smart/PollingDaemon.java +++ b/src/main/java/com/emc/rest/smart/PollingDaemon.java @@ -37,7 +37,7 @@ public class PollingDaemon extends Thread { private static final Logger log = LoggerFactory.getLogger(PollingDaemon.class); - private SmartConfig smartConfig; + private final SmartConfig smartConfig; private boolean running = true; public PollingDaemon(SmartConfig smartConfig) { @@ -85,9 +85,9 @@ public void run() { long callTime = System.currentTimeMillis() - start; try { - long sleepTime = smartConfig.getPollInterval() * 1000 - callTime; + long sleepTime = smartConfig.getPollInterval() * 1000L - callTime; if (sleepTime < 0) sleepTime = 0; - log.debug("polling daemon finished; will poll again in {}ms..", Long.toString(sleepTime)); + log.debug("polling daemon finished; will poll again in {}ms..", sleepTime); if (sleepTime > 0) Thread.sleep(sleepTime); } catch (InterruptedException e) { log.warn("interrupted while sleeping", e); diff --git a/src/main/java/com/emc/rest/smart/SizeOverrideWriter.java b/src/main/java/com/emc/rest/smart/SizeOverrideWriter.java index 1400798..ab62dab 100644 --- a/src/main/java/com/emc/rest/smart/SizeOverrideWriter.java +++ b/src/main/java/com/emc/rest/smart/SizeOverrideWriter.java @@ -41,7 +41,7 @@ import java.lang.reflect.Type; public class SizeOverrideWriter implements MessageBodyWriter { - private static final ThreadLocal entitySize = new ThreadLocal(); + private static final ThreadLocal entitySize = new ThreadLocal<>(); public static Long getEntitySize() { return entitySize.get(); @@ -51,7 +51,7 @@ public static void setEntitySize(Long size) { entitySize.set(size); } - private MessageBodyWriter delegate; + private final MessageBodyWriter delegate; public SizeOverrideWriter(MessageBodyWriter delegate) { this.delegate = delegate; diff --git a/src/main/java/com/emc/rest/smart/SmartClientFactory.java b/src/main/java/com/emc/rest/smart/SmartClientFactory.java index b7b2b06..7edeb19 100644 --- a/src/main/java/com/emc/rest/smart/SmartClientFactory.java +++ b/src/main/java/com/emc/rest/smart/SmartClientFactory.java @@ -147,7 +147,7 @@ static ApacheHttpClient4Handler createApacheClientHandler(SmartConfig smartConfi ClientConfig clientConfig = new DefaultClientConfig(); // set up multi-threaded connection pool - org.apache.http.impl.conn.PoolingClientConnectionManager connectionManager = new org.apache.http.impl.conn.PoolingClientConnectionManager(); + org.apache.http.impl.conn.PoolingHttpClientConnectionManager connectionManager = new org.apache.http.impl.conn.PoolingHttpClientConnectionManager(); // 999 maximum active connections (max allowed) connectionManager.setDefaultMaxPerRoute(999); connectionManager.setMaxTotal(999); diff --git a/src/main/java/com/emc/rest/smart/SmartConfig.java b/src/main/java/com/emc/rest/smart/SmartConfig.java index 306c7db..d67d1ea 100644 --- a/src/main/java/com/emc/rest/smart/SmartConfig.java +++ b/src/main/java/com/emc/rest/smart/SmartConfig.java @@ -42,19 +42,19 @@ public class SmartConfig { private String proxyUser; private String proxyPass; - private LoadBalancer loadBalancer; + private final LoadBalancer loadBalancer; private HostListProvider hostListProvider; private int pollInterval = DEFAULT_POLL_INTERVAL; private boolean hostUpdateEnabled = true; private boolean healthCheckEnabled = true; - private Map properties = new HashMap(); + private final Map properties = new HashMap<>(); /** * @see #SmartConfig(LoadBalancer) */ public SmartConfig(String... initialHostNames) { - List hostList = new ArrayList(); + List hostList = new ArrayList<>(); for (String hostName : initialHostNames) { hostList.add(new Host(hostName)); } diff --git a/src/main/java/com/emc/rest/smart/SmartFilter.java b/src/main/java/com/emc/rest/smart/SmartFilter.java index a2c10c4..07e0312 100644 --- a/src/main/java/com/emc/rest/smart/SmartFilter.java +++ b/src/main/java/com/emc/rest/smart/SmartFilter.java @@ -40,7 +40,7 @@ public class SmartFilter extends ClientFilter { public static final String BYPASS_LOAD_BALANCER = "com.emc.rest.smart.bypassLoadBalancer"; - private SmartConfig smartConfig; + private final SmartConfig smartConfig; public SmartFilter(SmartConfig smartConfig) { this.smartConfig = smartConfig; @@ -75,12 +75,8 @@ public ClientResponse handle(ClientRequest request) throws ClientHandlerExceptio ClientResponse response = getNext().handle(request); // capture request stats - if (response.getStatus() >= 500 && response.getStatus() != 501) { - // except for 501 (not implemented), all 50x responses are considered server errors - host.callComplete(true); - } else { - host.callComplete(false); - } + // except for 501 (not implemented), all 50x responses are considered server errors + host.callComplete(response.getStatus() >= 500 && response.getStatus() != 501); // wrap the input stream so we can capture the actual connection close response.setEntityInputStream(new WrappedInputStream(response.getEntityInputStream(), host)); @@ -99,8 +95,8 @@ public ClientResponse handle(ClientRequest request) throws ClientHandlerExceptio /** * captures closure in host statistics */ - protected class WrappedInputStream extends FilterInputStream { - private Host host; + protected static class WrappedInputStream extends FilterInputStream { + private final Host host; private boolean closed = false; public WrappedInputStream(InputStream in, Host host) { diff --git a/src/main/java/com/emc/rest/smart/ecs/EcsHostListProvider.java b/src/main/java/com/emc/rest/smart/ecs/EcsHostListProvider.java index 263ca5e..1c204ea 100644 --- a/src/main/java/com/emc/rest/smart/ecs/EcsHostListProvider.java +++ b/src/main/java/com/emc/rest/smart/ecs/EcsHostListProvider.java @@ -39,6 +39,7 @@ import javax.crypto.spec.SecretKeySpec; import java.net.URI; import java.net.URISyntaxException; +import java.nio.charset.StandardCharsets; import java.text.SimpleDateFormat; import java.util.*; @@ -50,10 +51,10 @@ public class EcsHostListProvider implements HostListProvider { public static final int DEFAULT_PORT = 9021; protected final SimpleDateFormat rfc822DateFormat; - private Client client; - private LoadBalancer loadBalancer; - private String user; - private String secret; + private final Client client; + private final LoadBalancer loadBalancer; + private final String user; + private final String secret; private String protocol = DEFAULT_PROTOCOL; private int port = DEFAULT_PORT; private List vdcs; @@ -70,7 +71,7 @@ public EcsHostListProvider(Client client, LoadBalancer loadBalancer, String user public List getHostList() { if (vdcs == null || vdcs.isEmpty()) return getDataNodes(loadBalancer.getTopHost(null)); - List hostList = new ArrayList(); + List hostList = new ArrayList<>(); for (Vdc vdc : vdcs) { if (vdc.getHosts().isEmpty()) log.warn("VDC " + vdc.getName() + " has no hosts!"); @@ -111,8 +112,7 @@ public void runHealthCheck(Host host) { PingItem pingItem = response.getPingItemMap().get(PingItem.MAINTENANCE_MODE); if (pingItem != null) status = pingItem.getStatus(); } - if (status == PingItem.Status.ON) ((VdcHost) host).setMaintenanceMode(true); - else ((VdcHost) host).setMaintenanceMode(false); + ((VdcHost) host).setMaintenanceMode(status == PingItem.Status.ON); } } @@ -153,7 +153,7 @@ protected List getDataNodes(Host host) { log.debug("retrieving VDC node list from {}", host.getName()); List dataNodes = request.get(ListDataNode.class).getDataNodes(); - List hosts = new ArrayList(); + List hosts = new ArrayList<>(); for (String node : dataNodes) { hosts.add(new Host(node)); } @@ -171,8 +171,8 @@ protected URI getRequestUri(Host host, String path) { protected String getSignature(String canonicalString, String secret) throws Exception { Mac mac = Mac.getInstance("HmacSHA1"); - mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA1")); - String signature = new String(Base64.encodeBase64(mac.doFinal(canonicalString.getBytes("UTF-8")))); + mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA1")); + String signature = new String(Base64.encodeBase64(mac.doFinal(canonicalString.getBytes(StandardCharsets.UTF_8)))); log.debug("canonicalString:\n" + canonicalString); log.debug("signature:\n" + signature); return signature; @@ -182,7 +182,7 @@ protected void updateVdcNodes(Vdc vdc, List nodeList) { if (nodeList == null || nodeList.isEmpty()) throw new RuntimeException("node list is empty"); // make sure the hosts are associated with the VDC first - List vdcNodeList = new ArrayList(); + List vdcNodeList = new ArrayList<>(); for (Host host : nodeList) { vdcNodeList.add(new VdcHost(vdc, host.getName())); } diff --git a/src/main/java/com/emc/rest/smart/ecs/ListDataNode.java b/src/main/java/com/emc/rest/smart/ecs/ListDataNode.java index 083babb..de96ce4 100644 --- a/src/main/java/com/emc/rest/smart/ecs/ListDataNode.java +++ b/src/main/java/com/emc/rest/smart/ecs/ListDataNode.java @@ -34,7 +34,7 @@ @XmlRootElement(name = "ListDataNode") public class ListDataNode { - private List dataNodes = new ArrayList(); + private List dataNodes = new ArrayList<>(); private String versionInfo; @XmlElements(@XmlElement(name = "DataNodes")) diff --git a/src/main/java/com/emc/rest/smart/ecs/PingResponse.java b/src/main/java/com/emc/rest/smart/ecs/PingResponse.java index f3eaafd..7e93ec7 100644 --- a/src/main/java/com/emc/rest/smart/ecs/PingResponse.java +++ b/src/main/java/com/emc/rest/smart/ecs/PingResponse.java @@ -36,7 +36,7 @@ @XmlRootElement(name = "PingList") public class PingResponse { - private List pingItems = new ArrayList(); + private List pingItems = new ArrayList<>(); @XmlElement(name = "PingItem") public List getPingItems() { @@ -51,7 +51,7 @@ public void setPingItems(List pingItems) { public Map getPingItemMap() { Map pingItemMap = null; if (pingItems != null) { - pingItemMap = new HashMap(); + pingItemMap = new HashMap<>(); for (PingItem item : pingItems) { pingItemMap.put(item.getName(), item); } @@ -60,6 +60,6 @@ public Map getPingItemMap() { } public void setPingItemMap(Map pingItemMap) { - this.pingItems = new ArrayList(pingItemMap.values()); + this.pingItems = new ArrayList<>(pingItemMap.values()); } } diff --git a/src/main/java/com/emc/rest/smart/ecs/Vdc.java b/src/main/java/com/emc/rest/smart/ecs/Vdc.java index dbcb85e..726340e 100644 --- a/src/main/java/com/emc/rest/smart/ecs/Vdc.java +++ b/src/main/java/com/emc/rest/smart/ecs/Vdc.java @@ -34,11 +34,11 @@ public class Vdc implements Iterable { private String name; - private List hosts; + private final List hosts; public Vdc(String... hostNames) { this.name = hostNames[0]; - hosts = new ArrayList(); + hosts = new ArrayList<>(); for (String hostName : hostNames) { hosts.add(new VdcHost(this, hostName)); } @@ -66,7 +66,7 @@ public boolean isHealthy() { } protected List createVdcHosts(List hosts) { - List vdcHosts = new ArrayList(); + List vdcHosts = new ArrayList<>(); for (Host host : hosts) { vdcHosts.add(new VdcHost(this, host.getName())); } diff --git a/src/main/java/com/emc/rest/smart/ecs/VdcHost.java b/src/main/java/com/emc/rest/smart/ecs/VdcHost.java index a819c16..96aff74 100644 --- a/src/main/java/com/emc/rest/smart/ecs/VdcHost.java +++ b/src/main/java/com/emc/rest/smart/ecs/VdcHost.java @@ -29,7 +29,7 @@ import com.emc.rest.smart.Host; public class VdcHost extends Host { - private Vdc vdc; + private final Vdc vdc; private boolean maintenanceMode; public VdcHost(Vdc vdc, String name) { diff --git a/src/main/java/com/emc/rest/util/SizedInputStream.java b/src/main/java/com/emc/rest/util/SizedInputStream.java index fdaac3c..ffe4b0c 100644 --- a/src/main/java/com/emc/rest/util/SizedInputStream.java +++ b/src/main/java/com/emc/rest/util/SizedInputStream.java @@ -34,8 +34,8 @@ * reached its end when the specified size has been read. */ public class SizedInputStream extends InputStream { - private InputStream source; - private long size; + private final InputStream source; + private final long size; private long read = 0; public SizedInputStream(InputStream source, long size) { diff --git a/src/main/java/com/emc/rest/util/StreamUtil.java b/src/main/java/com/emc/rest/util/StreamUtil.java index 60bbe58..e086127 100644 --- a/src/main/java/com/emc/rest/util/StreamUtil.java +++ b/src/main/java/com/emc/rest/util/StreamUtil.java @@ -40,7 +40,7 @@ public final class StreamUtil { /** * Closes streams no matter what. */ - public static String readAsString(InputStream inputStream) throws IOException { + public static String readAsString(InputStream inputStream) { if (inputStream == null) return null; try { return new java.util.Scanner(inputStream, "UTF-8").useDelimiter("\\A").next(); @@ -65,7 +65,7 @@ public static long copy(InputStream is, OutputStream os, long maxBytes) throws I try { while (count < maxBytes) { - maxRead = (int) Math.min((long) buffer.length, maxBytes - count); + maxRead = (int) Math.min(buffer.length, maxBytes - count); if (-1 == (read = is.read(buffer, 0, maxRead))) break; os.write(buffer, 0, read); count += read; diff --git a/src/test/java/com/emc/rest/smart/HostTest.java b/src/test/java/com/emc/rest/smart/HostTest.java index 151469e..2539096 100644 --- a/src/test/java/com/emc/rest/smart/HostTest.java +++ b/src/test/java/com/emc/rest/smart/HostTest.java @@ -86,7 +86,7 @@ public void testHost() throws Exception { Assert.assertFalse(host.isHealthy()); // cool down should be compounded for consecutive errors (multiplied by powers of 2) - Thread.sleep(2 * errorWaitTime - 500); // wait until just before cool down is over + Thread.sleep(2L * errorWaitTime - 500); // wait until just before cool down is over Assert.assertFalse(host.isHealthy()); Thread.sleep(600); // wait until cool down period is over @@ -104,7 +104,7 @@ public void testHost() throws Exception { Assert.assertFalse(host.isHealthy()); // cool down should be compounded for consecutive errors (multiplied by powers of 2) - Thread.sleep(2 * 2 * errorWaitTime - 500); // wait until just before cool down is over + Thread.sleep(2L * 2 * errorWaitTime - 500); // wait until just before cool down is over Assert.assertFalse(host.isHealthy()); Thread.sleep(600); // wait until cool down period is over diff --git a/src/test/java/com/emc/rest/smart/LoadBalancerTest.java b/src/test/java/com/emc/rest/smart/LoadBalancerTest.java index 5796158..d593cf4 100644 --- a/src/test/java/com/emc/rest/smart/LoadBalancerTest.java +++ b/src/test/java/com/emc/rest/smart/LoadBalancerTest.java @@ -45,7 +45,7 @@ public class LoadBalancerTest { private static final Logger l4j = Logger.getLogger(LoadBalancerTest.class); @Test - public void testDistribution() throws Exception { + public void testDistribution() { String[] hostList = new String[]{"foo", "bar", "baz", "biz"}; final int callCount = 1000; @@ -80,7 +80,7 @@ public void testEfficiency() throws Exception { // make one meeeeeellion calls ;) ExecutorService service = Executors.newFixedThreadPool(32); - List> futures = new ArrayList>(); + List> futures = new ArrayList<>(); for (int i = 0; i < 1000000; i++) { futures.add(service.submit(new LBOverheadTask(loadBalancer))); @@ -100,7 +100,7 @@ public void testEfficiency() throws Exception { Assert.assertTrue("call overhead too high", perCallOverhead < 100000); // must be less than .1ms } - class LBOverheadTask implements Callable { + static class LBOverheadTask implements Callable { LoadBalancer loadBalancer; public LBOverheadTask(LoadBalancer loadBalancer) { @@ -108,7 +108,7 @@ public LBOverheadTask(LoadBalancer loadBalancer) { } @Override - public Long call() throws Exception { + public Long call() { long start = System.nanoTime(); Host host = loadBalancer.getTopHost(null); host.connectionOpened(); diff --git a/src/test/java/com/emc/rest/smart/SmartClientTest.java b/src/test/java/com/emc/rest/smart/SmartClientTest.java index 6a2a1a2..510d2cb 100644 --- a/src/test/java/com/emc/rest/smart/SmartClientTest.java +++ b/src/test/java/com/emc/rest/smart/SmartClientTest.java @@ -45,6 +45,7 @@ import javax.crypto.spec.SecretKeySpec; import java.io.ByteArrayInputStream; import java.net.URI; +import java.nio.charset.StandardCharsets; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; @@ -59,7 +60,7 @@ public class SmartClientTest { public static final String PROP_ATMOS_SECRET = "atmos.secret"; private static final String HEADER_FORMAT = "EEE, d MMM yyyy HH:mm:ss z"; - private static final ThreadLocal headerFormat = new ThreadLocal(); + private static final ThreadLocal headerFormat = new ThreadLocal<>(); @Test public void testAtmosOnEcs() throws Exception { @@ -76,7 +77,7 @@ public void testAtmosOnEcs() throws Exception { String[] endpoints = endpointStr.split(","); final URI serverUri = new URI(endpointStr.split(",")[0]); - List initialHosts = new ArrayList(); + List initialHosts = new ArrayList<>(); for (String endpoint : endpoints) { initialHosts.add(new Host(new URI(endpoint).getHost())); } @@ -87,15 +88,12 @@ public void testAtmosOnEcs() throws Exception { ExecutorService service = Executors.newFixedThreadPool(10); final AtomicInteger successCount = new AtomicInteger(); - List> futures = new ArrayList>(); + List> futures = new ArrayList<>(); for (int i = 0; i < 100; i++) { - futures.add(service.submit(new Runnable() { - @Override - public void run() { - getServiceInfo(client, serverUri, uid, secret); - successCount.incrementAndGet(); - } + futures.add(service.submit(() -> { + getServiceInfo(client, serverUri, uid, secret); + successCount.incrementAndGet(); })); } @@ -113,7 +111,7 @@ public void run() { public void testPutJsonStream() throws Exception { String endpointStr = TestConfig.getPropertyNotEmpty(PROP_ATMOS_ENDPOINTS); String[] endpoints = endpointStr.split(","); - List initialHosts = new ArrayList(); + List initialHosts = new ArrayList<>(); for (String endpoint : endpoints) { initialHosts.add(new Host(new URI(endpoint).getHost())); } @@ -142,12 +140,9 @@ public void testConnTimeout() throws Exception { final Client client = SmartClientFactory.createStandardClient(smartConfig); - Future future = Executors.newSingleThreadExecutor().submit(new Runnable() { - @Override - public void run() { - client.resource("http://8.8.4.4:9020/?ping").get(String.class); - Assert.fail("response was not expected; choose an IP that is not in use"); - } + Future future = Executors.newSingleThreadExecutor().submit(() -> { + client.resource("http://8.8.4.4:9020/?ping").get(String.class); + Assert.fail("response was not expected; choose an IP that is not in use"); }); try { @@ -183,8 +178,8 @@ private void getServiceInfo(Client client, URI serverUri, String uid, String sec private String sign(String canonicalString, String secretKey) { try { - byte[] hashKey = Base64.decodeBase64(secretKey.getBytes("UTF-8")); - byte[] input = canonicalString.getBytes("UTF-8"); + byte[] hashKey = Base64.decodeBase64(secretKey.getBytes(StandardCharsets.UTF_8)); + byte[] input = canonicalString.getBytes(StandardCharsets.UTF_8); Mac mac = Mac.getInstance("HmacSHA1"); SecretKeySpec key = new SecretKeySpec(hashKey, "HmacSHA1"); @@ -192,7 +187,7 @@ private String sign(String canonicalString, String secretKey) { byte[] hashBytes = mac.doFinal(input); - return new String(Base64.encodeBase64(hashBytes), "UTF-8"); + return new String(Base64.encodeBase64(hashBytes), StandardCharsets.UTF_8); } catch (Exception e) { throw new RuntimeException("Error signing string:\n" + canonicalString + "\n", e); } diff --git a/src/test/java/com/emc/rest/smart/TestHealthCheck.java b/src/test/java/com/emc/rest/smart/TestHealthCheck.java index aee4c11..f85e167 100644 --- a/src/test/java/com/emc/rest/smart/TestHealthCheck.java +++ b/src/test/java/com/emc/rest/smart/TestHealthCheck.java @@ -38,7 +38,7 @@ public class TestHealthCheck { private static final Logger l4j = Logger.getLogger(TestHealthCheck.class); @Test - public void testUnhealthyHostIgnored() throws Exception { + public void testUnhealthyHostIgnored() { String[] hostList = new String[]{"foo", "bar", "baz", "biz"}; final int callCount = 1000; @@ -131,8 +131,8 @@ public void testHealthyUpdate() throws Exception { } } - class TestHostListProvider implements HostListProvider { - private Host host; + static class TestHostListProvider implements HostListProvider { + private final Host host; boolean healthy; public TestHostListProvider(Host host, boolean healthy) { diff --git a/src/test/java/com/emc/rest/smart/ecs/EcsHostListProviderTest.java b/src/test/java/com/emc/rest/smart/ecs/EcsHostListProviderTest.java index 5ddb9d9..d9ed099 100644 --- a/src/test/java/com/emc/rest/smart/ecs/EcsHostListProviderTest.java +++ b/src/test/java/com/emc/rest/smart/ecs/EcsHostListProviderTest.java @@ -60,9 +60,6 @@ public class EcsHostListProviderTest { public static final String PROXY_URI = "http.proxyUri"; private URI serverURI; - private String user; - private String secret; - private String proxyUri; private Client client; private EcsHostListProvider hostListProvider; @@ -71,9 +68,9 @@ public void before() throws Exception { Properties properties = TestConfig.getProperties(); serverURI = new URI(TestConfig.getPropertyNotEmpty(properties, S3_ENDPOINT)); - user = TestConfig.getPropertyNotEmpty(properties, S3_ACCESS_KEY); - secret = TestConfig.getPropertyNotEmpty(properties, S3_SECRET_KEY); - proxyUri = properties.getProperty(PROXY_URI); + String user = TestConfig.getPropertyNotEmpty(properties, S3_ACCESS_KEY); + String secret = TestConfig.getPropertyNotEmpty(properties, S3_SECRET_KEY); + String proxyUri = properties.getProperty(PROXY_URI); ClientConfig clientConfig = new DefaultClientConfig(); clientConfig.getProperties().put(ApacheHttpClient4Config.PROPERTY_CONNECTION_MANAGER, new PoolingClientConnectionManager()); @@ -93,7 +90,7 @@ public void after() { } @Test - public void testEcsHostListProvider() throws Exception { + public void testEcsHostListProvider() { List hostList = hostListProvider.getHostList(); Assert.assertTrue("server list is empty", hostList.size() > 0); @@ -130,7 +127,7 @@ public void testNoKeepAlive() { } @Test - public void testHealthCheck() throws Exception { + public void testHealthCheck() { for (Host host : hostListProvider.getHostList()) { hostListProvider.runHealthCheck(host); } @@ -172,7 +169,7 @@ public void testMaintenanceMode() { } @Test - public void testPing() throws Exception { + public void testPing() { String portStr = serverURI.getPort() > 0 ? ":" + serverURI.getPort() : ""; PingResponse response = client.resource( @@ -183,7 +180,7 @@ public void testPing() throws Exception { } @Test - public void testVdcs() throws Exception { + public void testVdcs() { Vdc vdc1 = new Vdc(serverURI.getHost()).withName("vdc1"); Vdc vdc2 = new Vdc(serverURI.getHost()).withName("vdc2"); Vdc vdc3 = new Vdc(serverURI.getHost()).withName("vdc3"); @@ -209,7 +206,7 @@ public void testPingMarshalling() throws Exception { ""; PingResponse object = new PingResponse(); - Map map = new TreeMap(); + Map map = new TreeMap<>(); map.put("LOAD_FACTOR", new PingItem("LOAD_FACTOR", null, null, "1")); map.put("MAINTENANCE_MODE", new PingItem("MAINTENANCE_MODE", PingItem.Status.OFF, "Data Node is Available", null)); object.setPingItemMap(map); diff --git a/src/test/java/com/emc/util/RequestSimulator.java b/src/test/java/com/emc/util/RequestSimulator.java index 2793ca6..7a01a50 100644 --- a/src/test/java/com/emc/util/RequestSimulator.java +++ b/src/test/java/com/emc/util/RequestSimulator.java @@ -37,10 +37,10 @@ import java.util.concurrent.Future; public class RequestSimulator implements Runnable { - private LoadBalancer loadBalancer; - private int callCount; + private final LoadBalancer loadBalancer; + private final int callCount; private RequestExecutor requestExecutor; - private List errors = new ArrayList(); + private final List errors = new ArrayList<>(); public RequestSimulator(LoadBalancer loadBalancer, int callCount) { this.loadBalancer = loadBalancer; @@ -53,35 +53,32 @@ public void run() { // simulate callCount successful calls with identical response times ExecutorService executorService = Executors.newFixedThreadPool(10); - List futures = new ArrayList(); + List> futures = new ArrayList<>(); for (int i = 0; i < callCount; i++) { - futures.add(executorService.submit(new Runnable() { - @Override - public void run() { - int waitMs; - synchronized (random) { - waitMs = random.nextInt(20); - } - try { - Thread.sleep(waitMs); - } catch (InterruptedException e) { - e.printStackTrace(); - } - Host host = loadBalancer.getTopHost(null); - host.connectionOpened(); - try { - if (requestExecutor != null) requestExecutor.execute(host); - host.callComplete(false); - } catch (Throwable t) { - host.callComplete(true); - } - host.connectionClosed(); + futures.add(executorService.submit(() -> { + int waitMs; + synchronized (random) { + waitMs = random.nextInt(20); } + try { + Thread.sleep(waitMs); + } catch (InterruptedException e) { + e.printStackTrace(); + } + Host host = loadBalancer.getTopHost(null); + host.connectionOpened(); + try { + if (requestExecutor != null) requestExecutor.execute(host); + host.callComplete(false); + } catch (Throwable t) { + host.callComplete(true); + } + host.connectionClosed(); })); } // wait for tasks to finish - for (Future future : futures) { + for (Future future : futures) { try { future.get(); } catch (Throwable t) {