Commits

Ruwan Linton committed 9700c80

JDK7 changes and code optimizations, getting rid of unused classes

  • Participants
  • Parent commits 793f998

Comments (0)

Files changed (31)

modules/as2/src/main/java/org/adroitlogic/as2/manager/AS2Manager.java

             MessageFile messageFile = fileCache.getFile();
             msg.addMessageFileForRelease(messageFile);
 
-            OutputStream os = messageFile.getOutputStream();
-            try {
+            try (OutputStream os = messageFile.getOutputStream()) {
                 payload.writeTo(os);
                 attachments.add(new AttachmentDetails(messageFile, null));
             } catch (IOException e) {
                 handleException("Error converting current message or its attachments into a list of AS2 attachments", e);
-            } finally {
-                try {
-                    os.close();
-                } catch (IOException ignore) {}
             }
         }
     }

modules/core/src/main/java/org/adroitlogic/ultraesb/core/compile/HotSwapClassLoader.java

     private static final Logger logger = LoggerFactory.getLogger(HotSwapClassLoader.class);
     private static final Random RANDOM = new Random(System.currentTimeMillis());
 
-    public static final ThreadLocal<ClassLoader> PARENT = new ThreadLocal<ClassLoader>();
+    public static final ThreadLocal<ClassLoader> PARENT = new ThreadLocal<>();
 
     /**
      * The internal separator used for class searching, even though this is highly related to {@link File#separator} it
     public static final String CLASS_DEF_SEPARATOR = "/";
 
     private final Object lock = new Object();
-    private final Map<String, String> instanceJarPathHashes = new HashMap<String, String>();
-    private final Map<String, String> instanceClassPathHashes = new HashMap<String, String>();
-    private final Map<String, String> instanceResourcePathHashes = new HashMap<String, String>();
-    private final Map<String, List<HotSwapClassLoader>> existingLoaders
-            = new HashMap<String, List<HotSwapClassLoader>>();
+    private final Map<String, String> instanceJarPathHashes = new HashMap<>();
+    private final Map<String, String> instanceClassPathHashes = new HashMap<>();
+    private final Map<String, String> instanceResourcePathHashes = new HashMap<>();
+    private final Map<String, List<HotSwapClassLoader>> existingLoaders = new HashMap<>();
 
-    private Map<String, Class<?>> swappableClasses = new HashMap<String, Class<?>>();
-    private Map<String, URI> availableDefinitions = new HashMap<String, URI>();
-    private Map<String, URI> availableClassDefinitions = new HashMap<String, URI>();
-    private Map<String, URI> availableResourceDefinitions = new HashMap<String, URI>();
+    private Map<String, Class<?>> swappableClasses = new HashMap<>();
+    private Map<String, URI> availableDefinitions = new HashMap<>();
+    private Map<String, URI> availableClassDefinitions = new HashMap<>();
+    private Map<String, URI> availableResourceDefinitions = new HashMap<>();
     private File instanceJarPath;
     private File instanceClassPath;
     private File instanceResourcePath;
                         instanceJarPath.mkdirs();
                         instanceJarPath.deleteOnExit();
                         instanceLibPath = new File(instanceJarPath, "lib");
-                        loaders = new ArrayList<HotSwapClassLoader>();
+                        loaders = new ArrayList<>();
                         loaders.add(this);
                         try {
                             FileUtils.copyDirectory(customJarDir, instanceLibPath, true);
                         instanceClassPath.mkdirs();
                         instanceClassPath.deleteOnExit();
                         instanceClassesPath = new File(instanceClassPath, "classes");
-                        loaders = new ArrayList<HotSwapClassLoader>();
+                        loaders = new ArrayList<>();
                         loaders.add(this);
                         try {
                             FileUtils.copyDirectory(customClassDir, instanceClassesPath, true);
                         instanceResourcePath.mkdirs();
                         instanceResourcePath.deleteOnExit();
                         instanceResourcesPath = new File(instanceResourcePath, "resources");
-                        loaders = new ArrayList<HotSwapClassLoader>();
+                        loaders = new ArrayList<>();
                         loaders.add(this);
                         try {
                             FileUtils.copyDirectory(customResourceDir, instanceResourcesPath, true);
             throw new IllegalStateException("Hot-swap class loader is not active");
         }
 
-        List<JavaFileObject> javaFiles = new ArrayList<JavaFileObject>();
+        List<JavaFileObject> javaFiles = new ArrayList<>();
         String packageDef = packageName.replace(".", CLASS_DEF_SEPARATOR);
         for (String definitionName : availableDefinitions.keySet()) {
             if (definitionName.startsWith(packageDef)) {

modules/core/src/main/java/org/adroitlogic/ultraesb/core/compile/InMemoryClassLoader.java

 
         this.classLoader = classLoader;
         fileManager.setClassLoader(classLoader);
-        List<JavaSource> list = new ArrayList<JavaSource>();
+        List<JavaSource> list = new ArrayList<>();
 
         list.add(new JavaSource(name, javaSource, id, proxyID));
-        List<String> compilerFlags = new ArrayList<String>();
+        List<String> compilerFlags = new ArrayList<>();
         compilerFlags.add("-Xlint:all");
 
         ClassLoader toolClassLoader = ToolProvider.getSystemToolClassLoader();

modules/core/src/main/java/org/adroitlogic/ultraesb/core/compile/InMemoryFileManager.java

  */
 public class InMemoryFileManager extends ForwardingJavaFileManager<JavaFileManager> {
     
-    private final Map<String, ByteArrayBackedClass> map = new HashMap<String, ByteArrayBackedClass>();
+    private final Map<String, ByteArrayBackedClass> map = new HashMap<>();
     private ClassLoader classLoader;
 
     InMemoryFileManager(JavaCompiler compiler) {
                                          boolean recurse) throws IOException {
         if (classLoader != null && classLoader instanceof HotSwapClassLoader &&
                 "CLASS_PATH".equals(location.getName()) && kinds.contains(JavaFileObject.Kind.CLASS)) {
-            return new WrappedIterator<JavaFileObject>(((HotSwapClassLoader) classLoader).listSwappableClasses(
+            return new WrappedIterator<>(((HotSwapClassLoader) classLoader).listSwappableClasses(
                     packageName, recurse).iterator(),
                     super.list(location, packageName, kinds, recurse).iterator()).getWrapper();
         } else {

modules/core/src/main/java/org/adroitlogic/ultraesb/core/compile/WrappedIterator.java

  */
 public class WrappedIterator<E> implements Iterator<E> {
 
-    List<Iterator<E>> iterators = new ArrayList<Iterator<E>>();
+    List<Iterator<E>> iterators = new ArrayList<>();
     int iteratorIndex = 0;
 
+    @SafeVarargs
     public WrappedIterator(Iterator<E> ... iterators) {
         this.iterators.addAll(Arrays.asList(iterators));
     }
      * @return the {@link Iterable} representing this wrapped iterator
      */
     public IteratorWrapper<E> getWrapper() {
-        return new IteratorWrapper<E>(this);
+        return new IteratorWrapper<>(this);
     }
 
     /**

modules/core/src/main/java/org/adroitlogic/ultraesb/core/config/JavaSequencePreparationException.java

  * An exception thrown during the preparation/compilation of a sequence
  * @author asankha
  */
+@SuppressWarnings("UnusedDeclaration")
 public class JavaSequencePreparationException extends RuntimeException {
-    public JavaSequencePreparationException() {
-    }
+
+    public JavaSequencePreparationException() {}
 
     public JavaSequencePreparationException(String message) {
         super(message);

modules/core/src/main/java/org/adroitlogic/ultraesb/core/deployment/DeploymentUnit.java

 import org.adroitlogic.ultraesb.core.PooledMessageFileCache;
 import org.adroitlogic.ultraesb.core.ProxyService;
 import org.adroitlogic.ultraesb.core.Sequence;
-import org.adroitlogic.ultraesb.core.compile.HotSwapClassLoader;
 import org.adroitlogic.ultraesb.core.endpoint.Endpoint;
 import org.adroitlogic.ultraesb.core.template.impl.TemplateCaller;
 import org.adroitlogic.ultraesb.jmx.view.DeploymentUnitView;
 
     public static final Logger logger = LoggerFactory.getLogger(DeploymentUnit.class);
 
-    public static final ThreadLocal<ClassLoader> DU_CLASS_LOADER = new ThreadLocal<ClassLoader>();
+    public static final ThreadLocal<ClassLoader> DU_CLASS_LOADER = new ThreadLocal<>();
 
     protected String id;
     protected int version;
     protected final ClassLoader classLoader;
     protected MetricsEngine metricsEngine;
 
-    protected Map<String, ProxyService> proxyServices = new HashMap<String, ProxyService>();
-    protected Map<String, Sequence> sequences = new HashMap<String, Sequence>();
-    protected Map<String, Endpoint> endpoints = new HashMap<String, Endpoint>();
-    protected Map<String, TemplateCaller> templates = new HashMap<String, TemplateCaller>();
-    protected Map<String, Object> localBeans = new HashMap<String, Object>();
+    protected Map<String, ProxyService> proxyServices = new HashMap<>();
+    protected Map<String, Sequence> sequences = new HashMap<>();
+    protected Map<String, Endpoint> endpoints = new HashMap<>();
+    protected Map<String, TemplateCaller> templates = new HashMap<>();
+    protected Map<String, Object> localBeans = new HashMap<>();
 
     public DeploymentUnit(String id, ConfigurationImpl config, ClassLoader classLoader) {
         this.id = id;
     }
 
     public <T> Map<String, T> getBeansOfType(Class<T> type) {
-        Map<String, T> beans = new HashMap<String, T>();
+        Map<String, T> beans = new HashMap<>();
         if (!isRoot()) {
             beans.putAll(getRoot().getBeansOfType(type));
         }
     }
 
     public DeploymentUnitView toDetailedView() {
-        List<SequenceView> sequenceViews = new ArrayList<SequenceView>(sequences.size());
-        List<EndpointView> endpointViews = new ArrayList<EndpointView>(endpoints.size());
-        List<ProxyServiceView> proxyServiceViews = new ArrayList<ProxyServiceView>(proxyServices.size());
+        List<SequenceView> sequenceViews = new ArrayList<>(sequences.size());
+        List<EndpointView> endpointViews = new ArrayList<>(endpoints.size());
+        List<ProxyServiceView> proxyServiceViews = new ArrayList<>(proxyServices.size());
         for (ProxyService ps : proxyServices.values()) {
             proxyServiceViews.add(ps.toDetailedView());
         }

modules/core/src/main/java/org/adroitlogic/ultraesb/core/deployment/RootDeploymentUnit.java

 public class RootDeploymentUnit extends DeploymentUnit {
 
     /** Local transport senders map as this will be accessed frequently and to provide senders for protocols */
-    private Map<String, TransportSender> registeredTransportSenders = new HashMap<String, TransportSender>();
+    private Map<String, TransportSender> registeredTransportSenders = new HashMap<>();
     /** Shared sequences of all deployment units */
-    private Map<String, Sequence> sharedSequences = new HashMap<String, Sequence>();
+    private Map<String, Sequence> sharedSequences = new HashMap<>();
     /** Shared endpoints of all deployment units */
-    private Map<String, Endpoint> sharedEndpoints = new HashMap<String, Endpoint>();
+    private Map<String, Endpoint> sharedEndpoints = new HashMap<>();
     /** Local reference to the cache manager singular bean */
     private CacheManager cacheManager;
     /** System information reporter into the metrics engine */
         // define the default response endpoint
         Endpoint defaultResponseEndpoint = new Endpoint();
         defaultResponseEndpoint.setId(ConfigurationConstants.MEDIATION_RESPONSE_ENDPOINT_NAME);
-        List<Address> addressList = new ArrayList<Address>();
+        List<Address> addressList = new ArrayList<>();
         Address responseAddr = new Address();
         responseAddr.setAddressType(AddressDefinition.Type.RESPONSE);
         addressList.add(responseAddr);

modules/core/src/main/java/org/adroitlogic/ultraesb/core/endpoint/AddressViewMXBean.java

-/*
- * AdroitLogic UltraESB Enterprise Service Bus
- *
- * Copyright (c) 2010-2014 AdroitLogic Private Ltd. (http://adroitlogic.org). All Rights Reserved.
- *
- * GNU Affero General Public License Usage
- *
- * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General
- * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option)
- * any later version.
- *
- * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
- * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for
- * more details.
- *
- * You should have received a copy of the GNU Affero General Public License along with this program (See LICENSE-AGPL.TXT).
- * If not, see http://www.gnu.org/licenses/agpl-3.0.html
- *
- * Commercial Usage
- *
- * Licensees holding valid UltraESB Commercial licenses may use this file in accordance with the UltraESB Commercial
- * License Agreement provided with the Software or, alternatively, in accordance with the terms contained in a written
- * agreement between you and AdroitLogic.
- *
- * If you are unsure which license is appropriate for your use, or have questions regarding the use of this file,
- * please contact AdroitLogic at info@adroitlogic.com
- */
-
-package org.adroitlogic.ultraesb.core.endpoint;
-
-import org.adroitlogic.ultraesb.jmx.core.GenericMXBean;
-
-import javax.management.MXBean;
-import java.util.Date;
-
-/**
- * @author asankha
- */
-@MXBean(true)
-public interface AddressViewMXBean extends GenericMXBean {
-
-    public String getStateAsString();
-    public String getTypeAsString();
-    public boolean isReadyToSend();
-    public String getAddressValue();
-    public double getWeight();
-    public Date getNextRetryTime();
-    public int getRemainingRetries();
-    public long getLastSuspendDuration();
-
-    // metrics
-    public int getSuccessCount();
-    public int getFaultCount();
-    public int getTimeoutCount();
-    public int getTotalCount();
-
-    public long getMinimumTime();
-    public long getMaximumTime();
-    public double getAverageTime();
-
-    public int getActiveStateCount();
-    public int getTimeoutStateCount();
-    public int getSuspendStateCount();
-    public int getMaintenanceStateCount();
-
-    public Date getLastStatisticsResetTime();
-    public long getMetricsWindow();
-
-    // JMX operations
-    public void switchOn();
-    public void switchOff();
-    public void resetStatistics();
-}

modules/core/src/main/java/org/adroitlogic/ultraesb/core/endpoint/Endpoint.java

     private long maximumDuration = EndpointDefinition.Defaults.MAXIMUM_DURATION;
 
     /** Error codes on which are harmless for retrying (defaults to connection refused, and connect timeout) */
-    private List<Integer> safeToRetryErrorCodes = new ArrayList<Integer>();
+    private List<Integer> safeToRetryErrorCodes = new ArrayList<>();
     /** Error codes on which to move the endpoint into retry, and the number of times encountered */
-    private Map<Integer, AtomicLong> temporaryErrorIndicationCodes = new HashMap<Integer, AtomicLong>();
+    private Map<Integer, AtomicLong> temporaryErrorIndicationCodes = new HashMap<>();
     /** Error codes on which to move the endpoint into suspension, and the number of times encountered */
-    private Map<Integer, AtomicLong> suspendErrorIndicationCodes = new HashMap<Integer, AtomicLong>();
+    private Map<Integer, AtomicLong> suspendErrorIndicationCodes = new HashMap<>();
 
     /**
      * The time to wait for a response, before considering a timeout. For HTTP and other applicable transports, this
      * An optional list of properties to be considered as message context properties when sending via this endpoint.
      * These properties will be set into the message when passing through this endpoint
      */
-    private Map<String, String> properties = new HashMap<String, String>();
+    private Map<String, String> properties = new HashMap<>();
 
     /** A RNG for use with weighted and random endpoints */
     private Random random = new Random(System.currentTimeMillis());
 
         } else {
             singleAddress = null;
-            fullAddressMap = new LinkedHashMap<String, Address>(list.size());
+            fullAddressMap = new LinkedHashMap<>(list.size());
 
             int pos = 1;
             for (Address a : list) {
                 msg.setLastEndpoint(this);
                 msg.beginProcessing(id);
                 // this is the first time this endpoint is trying to send this message
-                attemptedAddresses = new HashSet<String>();
+                attemptedAddresses = new HashSet<>();
                 msg.addMessageProperty(LAST_ATTEMPTED_ADDRESSES, attemptedAddresses);
             } else {
                 metricsEngine.exceptionalIncrement(failOverMessageStream);
         final boolean initialRequest = lastSelectedAddressId == null;
 
         logger.debug("Selecting address to use from map of size : {} last address used was : {}", fullAddressMap.size(), lastSelectedAddressId);
-        List<Address> candidates = new ArrayList<Address>(fullAddressMap.size());
+        List<Address> candidates = new ArrayList<>(fullAddressMap.size());
         long now = System.nanoTime();
         boolean updated = false;
         int lastSelectedPos = -1;
 
         EndpointView view = new EndpointView(id, state.toString(), debugOn);
 
-        List<AddressView> addressViewList = new ArrayList<AddressView>();
+        List<AddressView> addressViewList = new ArrayList<>();
         if (singleAddress != null) {
             addressViewList.add(singleAddress.getBasicAddressView());
         } else {
 
     public List<AddressView> getAddressViews() {
 
-        List<AddressView> addressViewList = new ArrayList<AddressView>();
+        List<AddressView> addressViewList = new ArrayList<>();
         if (singleAddress != null) {
             addressViewList.add(singleAddress.getDetailedAddressView());
         } else {
 
         EndpointView view = new EndpointView(id, state.toString(), debugOn);
 
-        Map<String, Integer> metricsStreams = new HashMap<String, Integer>();
+        Map<String, Integer> metricsStreams = new HashMap<>();
         metricsStreams.put("processedMessageStream", processedMessageStream);
         metricsStreams.put("uniqueMessageStream", uniqueMessageStream);
         metricsStreams.put("failOverMessageStream", failOverMessageStream);
 
         view.setSafeToRetryErrorCodes(ConverterUtil.convertToCommaSeparatedString(safeToRetryErrorCodes));
 
-        final Map<Integer, Long> tempFailure = new HashMap<Integer, Long>();
+        final Map<Integer, Long> tempFailure = new HashMap<>();
         for (Map.Entry<Integer, AtomicLong> e : temporaryErrorIndicationCodes.entrySet()) {
             tempFailure.put(e.getKey(), e.getValue().longValue());
         }
         view.setTemporaryFailureErrorCodes(tempFailure);
 
-        final Map<Integer, Long> suspend = new HashMap<Integer, Long>();
+        final Map<Integer, Long> suspend = new HashMap<>();
         for (Map.Entry<Integer, AtomicLong> e : suspendErrorIndicationCodes.entrySet()) {
             suspend.put(e.getKey(), e.getValue().longValue());
         }
         view.setSuspendErrorCodes(suspend);
 
         // addresses
-        List<AddressView> addressViewList = new ArrayList<AddressView>();
+        List<AddressView> addressViewList = new ArrayList<>();
         if (singleAddress != null) {
             AddressView av = singleAddress.getDetailedAddressView();
             addressViewList.add(av);
             }
         } else {
             if (fullAddressMap == null) {
-                fullAddressMap = new HashMap<String, Address>();
+                fullAddressMap = new HashMap<>();
             }
             if (singleAddress != null) {
                 fullAddressMap.put(singleAddress.getId(), singleAddress);
         ep.setShared(epDef.isShared());
         ep.setProxyID(epDef.getProxyID());
         
-        List<Address> addressList = new ArrayList<Address>();
+        List<Address> addressList = new ArrayList<>();
         for (AddressDefinition def : epDef.getAddresses()) {
             Address address = new Address();
             address.setId(def.getId());

modules/core/src/main/java/org/adroitlogic/ultraesb/core/format/ByteArrayMessage.java

     }
 
     public void writeTo(OutputStream os) throws IOException {
-        try {
-            os.write(bytes);
+        try (OutputStream tmpOs = os) {
+            tmpOs.write(bytes);
         } catch (Exception e) {
             handleFormatException("Error writing Byte Array message into an OutputStream", e);
-        } finally {
-            if (os != null) {
-                try { os.close(); } catch (IOException ignore) {}
-            }
         }
     }
 

modules/core/src/main/java/org/adroitlogic/ultraesb/core/format/DOMMessage.java

     private static final String S12_URI = "http://www.w3.org/2003/05/soap-envelope";
 
     /** The DOM Document held internally */
-    private Document document = null;
+    private final Document document;
     /** Simple SOAP headers if the payload is SOAP - as detected */
     private Map<String, String> soapHeaders;
     /** The file cache reference */
-    private FileCache fileCache;
+    private final FileCache fileCache;
 
     /**
      * Create a DOM message from the given message format, optionally parsing the existing payload
         if (mf instanceof DOMMessage) {
             this.document = ((DOMMessage) mf).getDocument();
         } else {
-            InputStream is = null;
-            try {
-                is = mf.getInputStream();
+            try (InputStream is = mf.getInputStream()) {
                 document = XMLFeatures.getInstance().parse(is);
                 this.modified = mf.isModified();
             } catch (Exception e) {
-                handleFormatException("Error converting " + mf.getMessageFormat() + " to a DOM message", e);
-            } finally {
-                if (is != null) try {  is.close(); } catch (IOException ignore) {}
+                String errorMsg = "Error converting " + mf.getMessageFormat() + " to a DOM message";
+                logger.error(errorMsg, e);
+                throw new FormatConversionException(errorMsg, e);
             }
         }
     }
     @Override
     public String getSimpleSOAPHeader(String uri, String name) {
         if (soapHeaders == null) {
-            soapHeaders = new HashMap<String, String>();
+            soapHeaders = new HashMap<>();
             populateSoapHeadersIfAny();
         }
         return soapHeaders.get((uri == null ? ":" : uri+":") + name);

modules/core/src/main/java/org/adroitlogic/ultraesb/core/format/DataHandlerMessage.java

     public String toString() {
 
         StringBuilder sb = new StringBuilder(4 * 1024);
-        BufferedReader in = null;
-        InputStream is = null;
-
-        try {
-            is = getInputStream();
-            in = new BufferedReader(new InputStreamReader(is));
+        try (InputStream is = getInputStream();
+             BufferedReader in = new BufferedReader(new InputStreamReader(is))) {
             String str;
             while ((str = in.readLine()) != null && sb.length() < 64 * 1024) {
                 sb.append(str);
                 sb.append("\r\n");
             }
-            in.close();
         } catch (IOException e) {
             handleFormatException("Error converting contents of DataHandler message to a String", e);
-        } finally {
-            if (in != null) try { in.close(); } catch (Exception ignore) {}
-            if (is != null) try { is.close(); } catch (Exception ignore) {}
         }
         return sb.toString();
     }

modules/core/src/main/java/org/adroitlogic/ultraesb/core/format/JacksonMessage.java

         } else if (jsonNode.isArray()) {
             if (value instanceof Collection) {
                 Collection valueCollection = (Collection) value;
-                ArrayList<JsonNode> newNodes = new ArrayList<JsonNode>(valueCollection.size());
+                ArrayList<JsonNode> newNodes = new ArrayList<>(valueCollection.size());
                 for (Object o : valueCollection) {
                     newNodes.add(convertToJSON(o));
                 }

modules/core/src/main/java/org/adroitlogic/ultraesb/core/format/MapMessage.java

 public class MapMessage<K, V> extends GenericMessage implements Map<K, V>,
         org.adroitlogic.ultraesb.api.format.MapMessage<K, V> {
 
-    private Map<K, V> map = null;
+    private final Map<K, V> map;
 
     /**
      * Create an empty map message
      */
     public MapMessage() {
-        map = new HashMap<K, V>();
+        map = new HashMap<>();
     }
 
     /**
      * @return the payload as a Serializable Map
      * @throws FormatConversionException is not thrown
      */
+    @Override
     public Serializable asSerializableObject() throws FormatConversionException {
         return (Serializable) map;
     }
      * @param os the OutputStream to serialize the message into
      * @throws IOException
      */
+    @Override
     public void writeTo(OutputStream os) throws IOException {
-        ObjectOutputStream out = null;
-        try {
-            ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
-            out = new ObjectOutputStream(bos) ;
+        try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
+             ObjectOutputStream out = new ObjectOutputStream(bos)) {
             out.writeObject(map);
-            out.close();
-        } finally {
-            if (out != null) {
-                try { out.close(); } catch (Exception ignore) {}
-            }
+        } catch (IOException e) {
+            handleFormatException("Error serializing the map", e);
         }
     }
 
     }
 
     // --------------- delegate methods ----------------
+    @Override
     public int size() {
         return map.size();
     }
 
+    @Override
     public boolean isEmpty() {
         return map.isEmpty();
     }
 
+    @Override
     public boolean containsKey(Object key) {
         return map.containsKey(key);
     }
 
+    @Override
     public boolean containsValue(Object value) {
         return map.containsValue(value);
     }
 
+    @Override
     public V get(Object key) {
         return map.get(key);
     }
 
+    @Override
     public V put(K key, V value) {
         modified = true;
         return map.put(key, value);
     }
 
+    @Override
     public V remove(Object key) {
         modified = true;
         return map.remove(key);
     }
 
+    @Override
     public void putAll(Map<? extends K, ? extends V> m) {
         modified = true;
         map.putAll(m);
     }
 
+    @Override
     public void clear() {
         modified = true;
         map.clear();
         return map.keySet();
     }
 
+    @Override
     public Collection<V> values() {
         return map.values();
     }
 
+    @Override
     public Set<Entry<K, V>> entrySet() {
         return map.entrySet();
     }
 
+    @Override
     public boolean equals(Object o) {
         return map.equals(o);
     }
 
+    @Override
     public int hashCode() {
         return map.hashCode();
     }

modules/core/src/main/java/org/adroitlogic/ultraesb/core/format/ObjectMessage.java

 public class ObjectMessage extends GenericMessage implements org.adroitlogic.ultraesb.api.format.ObjectMessage {
 
     /** The Object over which the message is defined */
-    private Object obj;
+    private final Object obj;
 
     /**
      * Create an Object message over the given Java Object

modules/core/src/main/java/org/adroitlogic/ultraesb/core/format/RawFileMessage.java

      */
     public String toString() {
         StringBuilder sb = new StringBuilder((int) Math.min(file.length(), 64 * 1024));
-        BufferedReader in = null;
-        InputStream is = null;
-
-        try {
-            is = getInputStream();
-            in = new BufferedReader(new InputStreamReader(is));
+        try (InputStream is = getInputStream();
+             BufferedReader in = new BufferedReader(new InputStreamReader(is))) {
             String str;
             while ((str = in.readLine()) != null && sb.length() < 64 * 1024) {
                 sb.append(str);
             }
-            in.close();
         } catch (IOException e) {
             handleFormatException("Error converting contents of file : " + file.getName() + " to a String", e);
-        } finally {
-            if (in != null) try { in.close(); } catch (Exception ignore) {}
-            if (is != null) try { is.close(); } catch (Exception ignore) {}
         }
         return sb.toString();
     }

modules/core/src/main/java/org/adroitlogic/ultraesb/core/format/StringMessage.java

     }
 
     public void writeTo(OutputStream os) throws IOException {
-        try {
-            os.write(message.getBytes());
+        try (OutputStream tmpOs = os) {
+            tmpOs.write(message.getBytes());
         } catch (Exception e) {
             handleFormatException("Error writing String message into an OutputStream", e);
-        } finally {
-            if (os != null) {
-                try { os.close(); } catch (IOException ignore) {}
-            }
         }
     }
 

modules/core/src/main/java/org/adroitlogic/ultraesb/core/helper/CustomStreamHandlerFactory.java

         @Override
         protected URLConnection openConnection(URL url) throws IOException {
 
-            URL resourceUrl = null;
+            URL resourceUrl;
 
             // find if the current thread stems from a DU
             final MessageImpl currentMessage = MessageImpl.CURRENT_MESSAGE.get();

modules/core/src/main/java/org/adroitlogic/ultraesb/core/helper/FixedByteArrayOutputStream.java

  * @author asankha
  */
 public class FixedByteArrayOutputStream extends ByteArrayOutputStream {
+
     private final int size;
 
     public FixedByteArrayOutputStream(int size) {

modules/core/src/main/java/org/adroitlogic/ultraesb/core/helper/InMemoryMessageAggregator.java

     private final DurationTimer dt = new DurationTimer(this);
 
     /** The collected messages pending aggregation */
-    private Map<UUID, List<Message>> pendingStore = new HashMap<UUID, List<Message>>();
+    private Map<UUID, List<Message>> pendingStore = new HashMap<>();
     /** A Map to keep track of timeouts */
-    private final Map<Long, List<UUID>> timeoutMap = new TreeMap<Long, List<UUID>>();
+    private final Map<Long, List<UUID>> timeoutMap = new TreeMap<>();
     /** The configuration */
     private final ConfigurationImpl config;
     /** The number of messages per aggregation*/
             }
             
             logger.debug("Aggregating new group : {}", reqUUID);
-            long expiryNano = -1;
+            long expiryNano;
             if (timeoutDurationMillis > 0) {
                 expiryNano = System.nanoTime() + timeoutDurationMillis * MILLIS_TO_NANO;
-                List<UUID> list = new ArrayList<UUID>();
+                List<UUID> list = new ArrayList<>();
                 list.add(reqUUID);
                 timeoutMap.put(expiryNano, list);
                 dt.requestTrigger(timeoutDurationMillis);
             }
-            messageList = new ArrayList<Message>();
+            messageList = new ArrayList<>();
             pendingStore.put(reqUUID, messageList);
         }
         msg.beginProcessing(AggregationConstants.AGGREGATION);
         List<Message> messageList = pendingStore.get(reqUUID);
         if (messageList == null) {
             logger.debug("Aggregating new group : {}", reqUUID);
-            long expiryNano = -1;
+            long expiryNano;
             if (timeoutDurationMillis > 0) {
                 expiryNano = System.nanoTime() + timeoutDurationMillis * MILLIS_TO_NANO;
-                List<UUID> list = new ArrayList<UUID>();
+                List<UUID> list = new ArrayList<>();
                 list.add(reqUUID);
                 timeoutMap.put(expiryNano, list);
                 dt.requestTrigger(timeoutDurationMillis);
                 m.addResponseCorrelation(AggregationConstants.EXPIRY_TIME, System.currentTimeMillis() + timeoutDurationMillis);
             }
 
-            messageList = new ArrayList<Message>();
+            messageList = new ArrayList<>();
             pendingStore.put(reqUUID, messageList);
         }
     }

modules/core/src/main/java/org/adroitlogic/ultraesb/core/helper/JSONAggregator.java

         this.parentMessage = parentMessage;
         this.size = size;
         this.executor = executor;
-        messageList = new ArrayList<JacksonMessage>(size);
+        messageList = new ArrayList<>(size);
     }
 
     public synchronized void start(long timeout) {

modules/core/src/main/java/org/adroitlogic/ultraesb/core/helper/LoggerUtilsManager.java

     public static final org.adroitlogic.logging.api.Logger auditLog = LoggerFactory.getLogger(LoggerUtilsManager.class);
 
     public List<LoggerView> getLoggers() {
-        List<LoggerView> loggersList = new ArrayList<LoggerView>();
+        List<LoggerView> loggersList = new ArrayList<>();
 
         Logger rootLogger = LogManager.getRootLogger();
         LoggerView rootLoggers = new LoggerView();
     }
 
     public List<AppenderView> getAppenders() {
-        List<AppenderView> appenderList = new ArrayList<AppenderView>();
+        List<AppenderView> appenderList = new ArrayList<>();
 
         Enumeration appenders = LogManager.getRootLogger().getAllAppenders();
         while (appenders.hasMoreElements()) {

modules/core/src/main/java/org/adroitlogic/ultraesb/core/helper/SplitAggregate.java

+/*
+ * AdroitLogic UltraESB Enterprise Service Bus
+ *
+ * Copyright (c) 2010-2014 AdroitLogic Private Ltd. (http://adroitlogic.org). All Rights Reserved.
+ *
+ * GNU Affero General Public License Usage
+ *
+ * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General
+ * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option)
+ * any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
+ * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License along with this program (See LICENSE-AGPL.TXT).
+ * If not, see http://www.gnu.org/licenses/agpl-3.0.html
+ *
+ * Commercial Usage
+ *
+ * Licensees holding valid UltraESB Commercial licenses may use this file in accordance with the UltraESB Commercial
+ * License Agreement provided with the Software or, alternatively, in accordance with the terms contained in a written
+ * agreement between you and AdroitLogic.
+ *
+ * If you are unsure which license is appropriate for your use, or have questions regarding the use of this file,
+ * please contact AdroitLogic at info@adroitlogic.com
+ */
+
 package org.adroitlogic.ultraesb.core.helper;
 
 import org.adroitlogic.ultraesb.api.Message;

modules/core/src/main/java/org/adroitlogic/ultraesb/core/helper/StreamingAggregator.java

-/*
- * AdroitLogic UltraESB Enterprise Service Bus
- *
- * Copyright (c) 2010-2014 AdroitLogic Private Ltd. (http://adroitlogic.org). All Rights Reserved.
- *
- * GNU Affero General Public License Usage
- *
- * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General
- * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option)
- * any later version.
- *
- * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
- * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for
- * more details.
- *
- * You should have received a copy of the GNU Affero General Public License along with this program (See LICENSE-AGPL.TXT).
- * If not, see http://www.gnu.org/licenses/agpl-3.0.html
- *
- * Commercial Usage
- *
- * Licensees holding valid UltraESB Commercial licenses may use this file in accordance with the UltraESB Commercial
- * License Agreement provided with the Software or, alternatively, in accordance with the terms contained in a written
- * agreement between you and AdroitLogic.
- *
- * If you are unsure which license is appropriate for your use, or have questions regarding the use of this file,
- * please contact AdroitLogic at info@adroitlogic.com
- */
-
-package org.adroitlogic.ultraesb.core.helper;
-
-import org.adroitlogic.logging.api.Logger;
-import org.adroitlogic.logging.api.LoggerFactory;
-import org.adroitlogic.ultraesb.api.Message;
-import org.adroitlogic.ultraesb.api.helper.MessageAggregator;
-import org.adroitlogic.ultraesb.core.ConfigurationImpl;
-import org.adroitlogic.ultraesb.core.DurationTimer;
-import org.adroitlogic.ultraesb.core.MessageImpl;
-import org.adroitlogic.ultraesb.core.work.WorkException;
-
-import java.util.*;
-
-/**
- * A simple in-memory message aggregator, that allows streaming of multiple responses over HTTP/S.
- * <b>Must</b> be initialised with the maximum size for an aggregated message
- *
- * @author asankha
- */
-public class StreamingAggregator implements MessageAggregator, DurationTimer.Trigger {
-
-    private static final Logger logger = LoggerFactory.getLogger(StreamingAggregator.class);
-
-    private static final int MILLIS_TO_NANO = 1000000;
-    /** The message property name that identifies the part position within the size (e.g. part i of n ; 1<=i<=n )*/
-    public static final String PART = "ultra.mediation.aggregator.part";
-    /** The message property name that identifies the total size of the complete message */
-    public static final String SIZE = "ultra.mediation.aggregator.size";
-
-    /** An efficient duration timer */
-    private final DurationTimer dt = new DurationTimer(this);
-    /** Map of group UUID to response count */
-    private final Map<UUID, Integer> metrics = new HashMap<UUID, Integer>();
-    /** A Map to keep track of timeouts */
-    private final Map<Long, List<Message>> timeoutMap = new TreeMap<Long, List<Message>>();
-    /** Reference to config */
-    private final ConfigurationImpl config;
-    /** The number of messages per aggregation */
-    private int completionSize = -1;
-    /** The timeout duration in milli seconds (negative means disabled - default) */
-    private int timeoutDurationMillis = -1;
-
-    public StreamingAggregator(ConfigurationImpl config) {
-        this.config = config;
-    }
-
-    /**
-     * Aggregate the current message
-     *
-     * @param msg the message to be aggregated
-     */
-    public synchronized void aggregate(Message msg) {
-
-        UUID reqUUID = msg.getCorrelatedRequestUUID();
-
-        Long expiry = (Long) msg.getMessageProperty(AggregationConstants.EXPIRY_TIME);
-        if (expiry != null && System.currentTimeMillis() > expiry) {
-            logger.debug("Response message : {} expired for group : {}", msg.getMessageUUID(), reqUUID);
-            msg.addMessageProperty(AggregationConstants.EXPIRED, Boolean.TRUE);
-            return;
-        }
-
-        Integer count = metrics.get(reqUUID);
-        if (count == null) {
-            logger.debug("Aggregating new group. First message of group : {}", reqUUID);
-            count = 0;
-
-            long expiryNano = -1;
-            if (timeoutDurationMillis > 0) {
-                expiryNano = System.nanoTime() + timeoutDurationMillis * MILLIS_TO_NANO;
-                List<Message> list = new ArrayList<Message>();
-                list.add(msg.cloneMessage());
-
-                synchronized (timeoutMap) {
-                    timeoutMap.put(expiryNano, list);
-                }
-                dt.requestTrigger(timeoutDurationMillis);
-            }
-        }
-
-        metrics.put(reqUUID, ++count);
-        msg.addMessageProperty(PART, count);
-        msg.addMessageProperty(SIZE, completionSize);
-
-        if (count >= completionSize) {
-            metrics.remove(reqUUID);
-            logger.debug("Completed aggregation. Last message of group : {}", reqUUID);
-        }
-    }
-
-    /**
-     * Begin the timeout timer (typically to be called from the inSequence)
-     * @param m the parent message
-     */
-    public void beginTimer(Message m) {
-
-        if (timeoutDurationMillis <= 0) {
-            logger.warn("Cannot begin timer - Timeout processing disabled in configuration");
-
-        } else {
-            m.addResponseCorrelation(AggregationConstants.EXPIRY_TIME, System.currentTimeMillis() + timeoutDurationMillis);
-
-            synchronized (timeoutMap) {
-                long expiryNano = -1;
-                expiryNano = System.nanoTime() + timeoutDurationMillis * MILLIS_TO_NANO;
-                List<Message> list = new ArrayList<Message>();
-                list.add(m.createDefaultResponseMessage());
-                timeoutMap.put(expiryNano, list);
-            }
-            synchronized (metrics) {
-                metrics.put(m.getMessageUUID(), 0);
-            }
-
-            dt.requestTrigger(timeoutDurationMillis);
-            logger.debug("Requested timeout in : " + timeoutDurationMillis);
-        }
-    }
-
-    public void destroy() {
-        logger.info("Clean shutdown of the streaming aggregator ...");
-        if (metrics.size() > 0) {
-            logger.warn("{} incomplete message groups found. Message IDs : ", metrics.size());
-            for (UUID uuid : metrics.keySet()) {
-                logger.warn(uuid.toString());
-            }
-        }
-    }
-
-    public void setCompletionSize(int completionSize) {
-        this.completionSize = completionSize;
-    }
-
-    public void setTimeoutDurationMillis(int timeoutDurationMillis) {
-        this.timeoutDurationMillis = timeoutDurationMillis;
-    }
-
-    public void onFire() {
-        final long now = System.nanoTime();
-        logger.trace("Fire timeout!!");
-
-        synchronized (timeoutMap) {
-            Iterator iter = timeoutMap.keySet().iterator();
-            while (iter.hasNext()) {
-                Long key = (Long) iter.next();
-                if (key < now) {
-                    for (Message resp : timeoutMap.get(key)) {
-                        UUID uuid = resp.getCorrelatedRequestUUID();
-                        completed(uuid, resp);
-                    }
-                    iter.remove();
-                } else {
-                    break;
-                }
-            }
-        }
-    }
-
-    private void completed(UUID uuid, Message resp) {
-
-        final Integer count;
-        synchronized (metrics) {
-            count = metrics.remove(uuid);
-        }
-
-        if (count == null) return;
-        logger.debug("Timeout group : {} by sending part : {}", uuid, (count+1));
-
-        resp.addMessageProperty(PART, count+1);
-        resp.addMessageProperty(SIZE, -1);
-        resp.addMessageProperty(AggregationConstants.MERGED, Boolean.TRUE);
-
-        try {
-            ((MessageImpl) resp).getProxyService().submitNewMessage((MessageImpl) resp, true);
-        } catch (WorkException e) {
-            logger.error("Error submitting aggregated message to proxy service : " + resp.getProxyServiceID(), e);
-            // TODO centrally report (e.g. to a console)
-        }
-    }
-}

modules/core/src/main/java/org/adroitlogic/ultraesb/core/helper/ValidationUtils.java

     private static final Logger logger = LoggerFactory.getLogger(ValidationUtils.class);
 
     private static final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
-    private static final Map<String, Schema> schemaMap = new HashMap<String, Schema>();
+    private static final Map<String, Schema> schemaMap = new HashMap<>();
 
     private ValidationUtils() {}
 
                     }
                     schema = factory.newSchema(sources);
                     schemaMap.put(key, schema);
-                } catch (SAXException e) {
-                    handleException("Error processing schemas : " + Arrays.toString(schemas) + " for validation", e);
-                    return;
-                } catch (IOException e) {
+                } catch (SAXException | IOException e) {
                     handleException("Error processing schemas : " + Arrays.toString(schemas) + " for validation", e);
                     return;
                 }
                 handleException("Schema validation failed : " +  errorHandler.getSaxParseException().getMessage());
             }
 
-        } catch (SAXException e) {
-            handleException("SAXException validating message against schemas : " +
-                    Arrays.toString(schemas) + " : " + e.getMessage(), e);
-        } catch (IOException e) {
-            handleException("IOException validating message against schemas : " +
+        } catch (SAXException | IOException e) {
+            handleException("Error validating message against schemas : " +
                     Arrays.toString(schemas) + " : " + e.getMessage(), e);
         }
     }

modules/core/src/main/java/org/adroitlogic/ultraesb/core/helper/XMLFeatures.java

     private final BlockingQueue<LSParser> lsParserQueue;
     private final BlockingQueue<LSSerializer> lsSerializerQueue;
     private final BlockingQueue<XPathFactory> xpathFactoryQueue;
-    private final Map<String, BlockingQueue<Transformer>> transformerMap = new HashMap<String, BlockingQueue<Transformer>>();
+    private final Map<String, BlockingQueue<Transformer>> transformerMap = new HashMap<>();
     private final int transformerCount;
 
     /**
     private XMLFeatures(int parserCount, int serializerCount, int xPathCount, int transformerCount,
                         boolean secureProcessingEnabled, boolean loadExternalDTDEnabled, boolean omitXMLDeclaration) {
 
-        lsParserQueue = new ArrayBlockingQueue<LSParser>(parserCount);
-        lsSerializerQueue = new ArrayBlockingQueue<LSSerializer>(serializerCount);
-        xpathFactoryQueue = new ArrayBlockingQueue<XPathFactory>(xPathCount);
+        lsParserQueue = new ArrayBlockingQueue<>(parserCount);
+        lsSerializerQueue = new ArrayBlockingQueue<>(serializerCount);
+        xpathFactoryQueue = new ArrayBlockingQueue<>(xPathCount);
         this.transformerCount = transformerCount;
 
         DOMImplementation implementation;
 
         BlockingQueue<Transformer> transformerQueue = transformerMap.get(xsltFilename);
         if (transformerQueue == null) {
-            transformerQueue = new ArrayBlockingQueue<Transformer>(transformerCount);
+            transformerQueue = new ArrayBlockingQueue<>(transformerCount);
             transformerMap.put(xsltFilename, transformerQueue);
         }
 

modules/core/src/main/java/org/adroitlogic/ultraesb/core/helper/XMLSplitAggregator.java

 import org.adroitlogic.ultraesb.ServerManager;
 import org.adroitlogic.ultraesb.api.FileCache;
 import org.adroitlogic.ultraesb.api.Message;
-import org.adroitlogic.ultraesb.api.mediation.XMLSupport;
-import org.adroitlogic.ultraesb.core.MediationImpl;
 import org.adroitlogic.ultraesb.core.MessageImpl;
-import org.adroitlogic.ultraesb.core.mediation.XMLSupportImpl;
 import org.springframework.beans.factory.BeanNameAware;
 import org.springframework.beans.factory.InitializingBean;
 import org.w3c.dom.Document;
                     continue;
                 }
 
-                Element currentElement = null;
+                Element currentElement;
                 int colon = token.indexOf(':');
 
                 if (colon != -1) {

modules/core/src/main/java/org/adroitlogic/ultraesb/core/helper/XMLUtils.java

         factory.setNamespaceAware(true);
         Map<QName, String> map = null;
 
-        try {
-            map = new HashMap<QName, String>();
+        try (InputStream isRef = is) {
+            map = new HashMap<>();
             SAXParser saxParser = factory.newSAXParser();
-            saxParser.parse(is, new SaxHandler(map));
+            saxParser.parse(isRef, new SaxHandler(map));
             return map;
         } catch (SAXException e) {
             if (SaxHandler.ABANDON_PARSE.equals(e.getMessage())) {
             handleException("IO error while trying to extract SOAP headers from an XML payload", e);
         } catch (ParserConfigurationException e) {
             handleException("SAX parser config error while trying to extract SOAP headers from an XML payload", e);
-        } finally {
-            if (is != null) {
-                try { is.close(); } catch (IOException ignore) {}
-            }
         }
 
         return null;

modules/core/src/main/java/org/adroitlogic/ultraesb/core/helper/audit/AuditSupportImpl.java

         }
         if (mode.shouldAuditProperties() || (properties != null && !properties.isEmpty())) {
             columns.append(", props");
-            Map<String, Object> props = new HashMap<String, Object>();
+            Map<String, Object> props = new HashMap<>();
             if (mode.shouldAuditProperties()) {
                 props.putAll(msg.getMessageProperties());
             }

modules/core/src/main/java/org/adroitlogic/ultraesb/core/helper/memoryappender/LogList.java

 
 public class LogList {
 
-    /**
-     * Specifies the number of log messages appended. Is incremented each time, a log is added to the linked list
-     */
+    /** Specifies the number of log messages appended. Is incremented each time, a log is added to the linked list */
     private int usedSize = 0;
-    /**
-     * Size of the hash map
-     */
+    /** Size of the hash map */
     private int capacity = 500;
     private final Map<Long, LogEntry> map;
     private final LinkedList<LogEntry> linkedList;
     private static final FastDateFormat dfm = FastDateFormat.getInstance("yyyy-MM-dd'&nbsp;'HH:mm:ss");
 
     public LogList() {
-        map = new HashMap<Long, LogEntry>(capacity);
-        linkedList = new LinkedList<LogEntry>();
+        map = new HashMap<>(capacity);
+        linkedList = new LinkedList<>();
     }
 
     public void setSize(int hashMapSize) {