]> source.dussan.org Git - vaadin-framework.git/commitdiff
Convert to for-each loop, Stream and switch-over-strings
authorPer-Åke Minborg <minborg@speedment.com>
Fri, 28 Oct 2016 15:28:56 +0000 (08:28 -0700)
committerPekka Hyvönen <pekka@vaadin.com>
Wed, 2 Nov 2016 15:04:46 +0000 (15:04 +0000)
Change-Id: I80b73b653e97904605dc62484a7448f3bfbf7218

server/src/main/java/com/vaadin/event/EventRouter.java
server/src/main/java/com/vaadin/event/ListenerMethod.java
server/src/main/java/com/vaadin/server/ComponentSizeValidator.java
server/src/main/java/com/vaadin/server/JsonCodec.java
server/src/main/java/com/vaadin/server/widgetsetutils/ClassPathExplorer.java
server/src/main/java/com/vaadin/ui/AbsoluteLayout.java
server/src/main/java/com/vaadin/ui/Upload.java
server/src/main/java/com/vaadin/ui/declarative/DesignAttributeHandler.java
server/src/test/java/com/vaadin/data/BinderConverterValidatorTest.java
server/src/test/java/com/vaadin/tests/server/ClassesSerializableTest.java
server/src/test/java/com/vaadin/tests/server/component/abstractcomponent/AbstractComponentDeclarativeTest.java

index c5237d9acabb975ea4de111573d648b18cef6cbb..6b96e91f25ed42eae3d9b3ab0e4d25c3d7aa96a1 100644 (file)
@@ -28,6 +28,7 @@ import java.util.logging.Logger;
 
 import com.vaadin.server.ErrorEvent;
 import com.vaadin.server.ErrorHandler;
+import java.util.stream.Stream;
 
 /**
  * <code>EventRouter</code> class implementing the inheritable event listening
@@ -124,15 +125,10 @@ public class EventRouter implements MethodEventSource {
 
         // Find the correct method
         final Method[] methods = target.getClass().getMethods();
-        Method method = null;
-        for (int i = 0; i < methods.length; i++) {
-            if (methods[i].getName().equals(methodName)) {
-                method = methods[i];
-            }
-        }
-        if (method == null) {
-            throw new IllegalArgumentException();
-        }
+        
+        final Method method = Stream.of(methods)
+            .filter(m -> methodName.equals(m.getName()))
+            .findAny().orElseThrow(IllegalArgumentException::new);        
 
         // Remove the listeners
         if (listenerList != null) {
@@ -191,8 +187,8 @@ public class EventRouter implements MethodEventSource {
             // Send the event to all listeners. The listeners themselves
             // will filter out unwanted events.
             final Object[] listeners = listenerList.toArray();
-            for (int i = 0; i < listeners.length; i++) {
-                ListenerMethod listenerMethod = (ListenerMethod) listeners[i];
+            for (Object listener : listeners) {
+                ListenerMethod listenerMethod = (ListenerMethod) listener;
                 if (null != errorHandler) {
                     try {
                         listenerMethod.receiveEvent(event);
index ff556f41179eb6776065c25acc07292d82fc1cb1..b81ebd28bcd4044855894a84098076b5871209ba 100644 (file)
@@ -25,6 +25,7 @@ import java.util.EventListener;
 import java.util.EventObject;
 import java.util.logging.Level;
 import java.util.logging.Logger;
+import java.util.stream.Stream;
 
 /**
  * <p>
@@ -118,9 +119,8 @@ public class ListenerMethod implements EventListener, Serializable {
     private static Method findHighestMethod(Class<?> cls, String method,
             Class<?>[] paramTypes) {
         Class<?>[] ifaces = cls.getInterfaces();
-        for (int i = 0; i < ifaces.length; i++) {
-            Method ifaceMethod = findHighestMethod(ifaces[i], method,
-                    paramTypes);
+        for (Class<?> iface : ifaces) {
+            Method ifaceMethod = findHighestMethod(iface, method, paramTypes);
             if (ifaceMethod != null) {
                 return ifaceMethod;
             }
@@ -132,14 +132,12 @@ public class ListenerMethod implements EventListener, Serializable {
                 return parentMethod;
             }
         }
-        Method[] methods = cls.getMethods();
-        for (int i = 0; i < methods.length; i++) {
-            // we ignore parameter types for now - you need to add this
-            if (methods[i].getName().equals(method)) {
-                return methods[i];
-            }
-        }
-        return null;
+        
+        // we ignore parameter types for now - you need to add this
+        return Stream.of(cls.getMethods())
+            .filter(m -> method.equals(m.getName()))
+            .findAny().orElse(null);
+        
     }
 
     /**
@@ -247,9 +245,9 @@ public class ListenerMethod implements EventListener, Serializable {
         // Finds the correct method
         final Method[] methods = target.getClass().getMethods();
         Method method = null;
-        for (int i = 0; i < methods.length; i++) {
-            if (methods[i].getName().equals(methodName)) {
-                method = methods[i];
+        for (Method method1 : methods) {
+            if (method1.getName().equals(methodName)) {
+                method = method1;
             }
         }
         if (method == null) {
@@ -359,9 +357,9 @@ public class ListenerMethod implements EventListener, Serializable {
         // Find the correct method
         final Method[] methods = target.getClass().getMethods();
         Method method = null;
-        for (int i = 0; i < methods.length; i++) {
-            if (methods[i].getName().equals(methodName)) {
-                method = methods[i];
+        for (Method method1 : methods) {
+            if (method1.getName().equals(methodName)) {
+                method = method1;
             }
         }
         if (method == null) {
@@ -461,9 +459,9 @@ public class ListenerMethod implements EventListener, Serializable {
         // Finds the correct method
         final Method[] methods = target.getClass().getMethods();
         Method method = null;
-        for (int i = 0; i < methods.length; i++) {
-            if (methods[i].getName().equals(methodName)) {
-                method = methods[i];
+        for (Method method1 : methods) {
+            if (method1.getName().equals(methodName)) {
+                method = method1;
             }
         }
         if (method == null) {
index e68fbb59033f8e4048ff64ff4ebb6171fea7f8a6..c7c6541c9ef0c0a09d9478e7f91bfdc5cc91b087 100644 (file)
@@ -92,9 +92,7 @@ public class ComponentSizeValidator implements Serializable {
             }
         } else if (isForm(component)) {
             HasComponents form = (HasComponents) component;
-            for (Iterator<Component> iterator = form.iterator(); iterator
-                    .hasNext();) {
-                Component child = iterator.next();
+            for (Component child : form) {
                 errors = validateComponentRelativeSizes(child, errors, parent);
             }
         }
index 588443d55bb3cf5b78fb50e1dcee7f4279a238f1..a85dd5c0e9522a31b345b0a4c055c90f154ea08b 100644 (file)
@@ -398,16 +398,19 @@ public class JsonCodec implements Serializable {
                     connectorTracker);
         }
 
-        // Collections
-        if (JsonConstants.VTYPE_LIST.equals(transportType)) {
-            return decodeList(targetType, restrictToInternalTypes,
+        if (null != transportType) // Collections
+        switch (transportType) {
+            case JsonConstants.VTYPE_LIST:
+                return decodeList(targetType, restrictToInternalTypes,
                     (JsonArray) encodedJsonValue, connectorTracker);
-        } else if (JsonConstants.VTYPE_SET.equals(transportType)) {
-            return decodeSet(targetType, restrictToInternalTypes,
+            case JsonConstants.VTYPE_SET:
+                return decodeSet(targetType, restrictToInternalTypes,
                     (JsonArray) encodedJsonValue, connectorTracker);
-        } else if (JsonConstants.VTYPE_MAP.equals(transportType)) {
-            return decodeMap(targetType, restrictToInternalTypes,
+            case JsonConstants.VTYPE_MAP:
+                return decodeMap(targetType, restrictToInternalTypes,
                     encodedJsonValue, connectorTracker);
+            default:
+                break;
         }
 
         // Arrays
@@ -427,20 +430,23 @@ public class JsonCodec implements Serializable {
             return connectorTracker.getConnector(encodedJsonValue.asString());
         }
 
-        // Legacy types
-
-        if (JsonConstants.VTYPE_STRING.equals(transportType)) {
-            return encodedJsonValue.asString();
-        } else if (JsonConstants.VTYPE_INTEGER.equals(transportType)) {
-            return (int) encodedJsonValue.asNumber();
-        } else if (JsonConstants.VTYPE_LONG.equals(transportType)) {
-            return (long) encodedJsonValue.asNumber();
-        } else if (JsonConstants.VTYPE_FLOAT.equals(transportType)) {
-            return (float) encodedJsonValue.asNumber();
-        } else if (JsonConstants.VTYPE_DOUBLE.equals(transportType)) {
-            return encodedJsonValue.asNumber();
-        } else if (JsonConstants.VTYPE_BOOLEAN.equals(transportType)) {
-            return encodedJsonValue.asBoolean();
+
+        if (null != transportType) // Legacy types
+        switch (transportType) {
+            case JsonConstants.VTYPE_STRING:
+                return encodedJsonValue.asString();
+            case JsonConstants.VTYPE_INTEGER:
+                return (int) encodedJsonValue.asNumber();
+            case JsonConstants.VTYPE_LONG:
+                return (long) encodedJsonValue.asNumber();
+            case JsonConstants.VTYPE_FLOAT:
+                return (float) encodedJsonValue.asNumber();
+            case JsonConstants.VTYPE_DOUBLE:
+                return encodedJsonValue.asNumber();
+            case JsonConstants.VTYPE_BOOLEAN:
+                return encodedJsonValue.asBoolean();
+            default:
+                break;
         }
 
         throw new JsonException("Unknown type " + transportType);
index 7aec10025550ed528d8b9c014fa8de53f1708ec0..42320cb02fafe89445d541049093d9cd2ddcd3eb 100644 (file)
@@ -203,45 +203,42 @@ public class ClassPathExplorer {
         if (directory.exists() && !directory.isHidden()) {
             // Get the list of the files contained in the directory
             String[] files = directory.list();
-            for (int i = 0; i < files.length; i++) {
+            for (String file : files) {
                 // we are only interested in .gwt.xml files
-                if (!files[i].endsWith(".gwt.xml")) {
+                if (!file.endsWith(".gwt.xml")) {
                     continue;
                 }
-
                 // remove the .gwt.xml extension
-                String classname = files[i].substring(0, files[i].length() - 8);
+                String classname = file.substring(0, file.length() - 8);
                 String packageName = locationString
-                        .substring(locationString.lastIndexOf("/") + 1);
+                    .substring(locationString.lastIndexOf("/") + 1);
                 classname = packageName + "." + classname;
-
                 if (!WidgetSetBuilder.isWidgetset(classname)) {
                     // Only return widgetsets and not GWT modules to avoid
                     // comparing modules and widgetsets
                     continue;
                 }
-
                 if (!widgetsets.containsKey(classname)) {
                     String packagePath = packageName.replaceAll("\\.", "/");
 
                     String basePath = location.getFile();
                     if (basePath.endsWith("/" + packagePath)) {
                         basePath = basePath.replaceAll("/" + packagePath + "$",
-                                "");
+                            "");
                     } else if (basePath.endsWith("/" + packagePath + "/")) {
                         basePath = basePath.replaceAll("/" + packagePath + "/$",
-                                "");
+                            "");
                     } else {
                         throw new IllegalStateException(
-                                "Error trying to find base path, location ("
-                                        + location.getFile()
-                                        + ") does not end in expected '/"
-                                        + packagePath + "'");
+                            "Error trying to find base path, location ("
+                                + location.getFile()
+                                + ") does not end in expected '/"
+                                + packagePath + "'");
                     }
                     try {
                         URL url = new URL(location.getProtocol(),
-                                location.getHost(), location.getPort(),
-                                basePath);
+                            location.getHost(), location.getPort(),
+                            basePath);
                         widgetsets.put(classname, url);
                     } catch (MalformedURLException e) {
                         // should never happen as based on an existing URL,
@@ -273,8 +270,8 @@ public class ClassPathExplorer {
                             .getValue("Vaadin-Widgetsets");
                     if (value != null) {
                         String[] widgetsetNames = value.split(",");
-                        for (int i = 0; i < widgetsetNames.length; i++) {
-                            String widgetsetname = widgetsetNames[i].trim();
+                        for (String widgetsetName : widgetsetNames) {
+                            String widgetsetname = widgetsetName.trim();
                             if (!widgetsetname.equals("")) {
                                 widgetsets.put(widgetsetname, location);
                             }
@@ -286,8 +283,8 @@ public class ClassPathExplorer {
                             .getValue("Vaadin-Stylesheets");
                     if (value != null) {
                         String[] stylesheets = value.split(",");
-                        for (int i = 0; i < stylesheets.length; i++) {
-                            String stylesheet = stylesheets[i].trim();
+                        for (String untrimmedStylesheet : stylesheets) {
+                            String stylesheet = untrimmedStylesheet.trim();
                             if (!stylesheet.equals("")) {
                                 addonStyles.put(stylesheet, location);
                             }
@@ -326,8 +323,7 @@ public class ClassPathExplorer {
         debug("Classpath: " + classpath);
 
         String[] split = classpath.split(pathSep);
-        for (int i = 0; i < split.length; i++) {
-            String classpathEntry = split[i];
+        for (String classpathEntry : split) {
             if (acceptClassPathEntry(classpathEntry)) {
                 locations.add(classpathEntry);
             }
@@ -459,20 +455,18 @@ public class ClassPathExplorer {
 
         // add all directories recursively
         File[] dirs = file.listFiles(DIRECTORIES_ONLY);
-        for (int i = 0; i < dirs.length; i++) {
+        for (File dir : dirs) {
             try {
                 // add the present directory
-                if (!dirs[i].isHidden()
-                        && !dirs[i].getPath().contains(File.separator + ".")) {
-                    String key = dirs[i].getCanonicalPath() + "/" + name
-                            + dirs[i].getName();
-                    URL url = dirs[i].getCanonicalFile().toURI().toURL();
+                if (!dir.isHidden() && !dir.getPath().contains(File.separator + ".")) {
+                    String key = dir.getCanonicalPath() + "/" + name + dir.getName();
+                    URL url = dir.getCanonicalFile().toURI().toURL();
                     locations.put(key, url);
                 }
-            } catch (Exception ioe) {
+            }catch (Exception ioe) {
                 return;
             }
-            include(name + dirs[i].getName(), dirs[i], locations);
+            include(name + dir.getName(), dir, locations);
         }
     }
 
index 5aa008e8293bb9627e27b29d93df835fad675e44..cb0e1445ab1675506b5e6327b29e4f8f5ca3b656 100644 (file)
@@ -301,8 +301,8 @@ public class AbsoluteLayout extends AbstractLayout
             }
 
             String[] cssProperties = css.split(";");
-            for (int i = 0; i < cssProperties.length; i++) {
-                String[] keyValuePair = cssProperties[i].split(":");
+            for (String cssProperty : cssProperties) {
+                String[] keyValuePair = cssProperty.split(":");
                 String key = keyValuePair[0].trim();
                 if (key.equals("")) {
                     continue;
@@ -319,22 +319,27 @@ public class AbsoluteLayout extends AbstractLayout
                     String symbol = value.replaceAll("[0-9\\.\\-]+", "");
                     if (!symbol.equals("")) {
                         value = value.substring(0, value.indexOf(symbol))
-                                .trim();
+                            .trim();
                     }
                     float v = Float.parseFloat(value);
                     Unit unit = Unit.getUnitFromSymbol(symbol);
-                    if (key.equals("top")) {
-                        topValue = v;
-                        topUnits = unit;
-                    } else if (key.equals("right")) {
-                        rightValue = v;
-                        rightUnits = unit;
-                    } else if (key.equals("bottom")) {
-                        bottomValue = v;
-                        bottomUnits = unit;
-                    } else if (key.equals("left")) {
-                        leftValue = v;
-                        leftUnits = unit;
+                    switch (key) {
+                        case "top":
+                            topValue = v;
+                            topUnits = unit;
+                            break;
+                        case "right":
+                            rightValue = v;
+                            rightUnits = unit;
+                            break;
+                        case "bottom":
+                            bottomValue = v;
+                            bottomUnits = unit;
+                            break;
+                        case "left":
+                            leftValue = v;
+                            leftUnits = unit;
+                            break;
                     }
                 }
             }
index a08fce099e26c42d7d8cd49556f27811a418baca..155bdfb811f2bb62dd2ee71f998ec686e194cee0 100644 (file)
@@ -840,9 +840,7 @@ public class Upload extends AbstractComponent
         // this is implemented differently than other listeners to maintain
         // backwards compatibility
         if (progressListeners != null) {
-            for (Iterator<ProgressListener> it = progressListeners
-                    .iterator(); it.hasNext();) {
-                ProgressListener l = it.next();
+            for (ProgressListener l : progressListeners) {
                 l.updateProgress(totalBytes, contentLength);
             }
         }
index 44248d095b587b63815f1bf432b35c9daeb0fb92..2fad5fb14f1cfc13e69704a3e0bbc31e51a31529 100644 (file)
@@ -318,11 +318,11 @@ public class DesignAttributeHandler implements Serializable {
         propertyName = removeSubsequentUppercase(propertyName);
         String[] words = propertyName.split("(?<!^)(?=[A-Z])");
         StringBuilder builder = new StringBuilder();
-        for (int i = 0; i < words.length; i++) {
+        for (String word : words) {
             if (builder.length() > 0) {
                 builder.append("-");
             }
-            builder.append(words[i].toLowerCase());
+            builder.append(word.toLowerCase());
         }
         return builder.toString();
     }
index 0711ae24bf5a2bc14576f85de159546935805b68..ac530c266f6cf1591d5a218a33f69ae9beb5d382 100644 (file)
@@ -235,14 +235,15 @@ public class BinderConverterValidatorTest
                     throw new IllegalArgumentException(
                             "Value must be OK or NOTOK");
                 }, model -> {
-                    if (model.equals("1")) {
-                        return "OK";
-                    } else if (model.equals("2")) {
-                        return "NOTOK";
-                    } else {
-                        throw new IllegalArgumentException(
-                                "Value in model must be 1 or 2");
-                    }
+            switch (model) {
+                case "1":
+                    return "OK";
+                case "2":
+                    return "NOTOK";
+                default:
+                    throw new IllegalArgumentException(
+                        "Value in model must be 1 or 2");
+            }
                 });
         binding.bind(StatusBean::getStatus, StatusBean::setStatus);
         binder.setBean(bean);
index 0a1629c2f9b0441ad6bc11d8a73c6370c190fdd7..1d30e413822a048f091cdce233c04a009e64a2ed 100644 (file)
@@ -269,8 +269,7 @@ public class ClassesSerializableTest {
         }
 
         String[] split = classpath.split(pathSep);
-        for (int i = 0; i < split.length; i++) {
-            String classpathEntry = split[i];
+        for (String classpathEntry : split) {
             locations.add(classpathEntry);
         }
 
index b13499983e656b6d3c0086a68de903297a3fe605..b8875c34fd89866f90cfa73153d3a11d60378df6 100644 (file)
@@ -97,10 +97,8 @@ public class AbstractComponentDeclarativeTest
         Boolean[] explicitImmediate = { null, Boolean.FALSE, Boolean.TRUE,
                 Boolean.TRUE };
         boolean[] immediate = { true, false, true, true };
-        for (int i = 0; i < design.length; i++) {
-            component = (AbstractComponent) Design
-                    .read(new ByteArrayInputStream(
-                            design[i].getBytes(Charset.forName("UTF-8"))));
+        for (String designElements : design) {
+            component = (AbstractComponent) Design.read(new ByteArrayInputStream(designElements.getBytes(Charset.forName("UTF-8"))));
         }
     }