diff --git a/framework/src/play/Invoker.java b/framework/src/play/Invoker.java index 1531eae74b..2c11ce19d3 100644 --- a/framework/src/play/Invoker.java +++ b/framework/src/play/Invoker.java @@ -312,13 +312,10 @@ public void run() { if (init()) { before(); final AtomicBoolean executed = new AtomicBoolean(false); - this.withinFilter(new play.libs.F.Function0() { - @Override - public Void apply() throws Throwable { - executed.set(true); - execute(); - return null; - } + this.withinFilter(() -> { + executed.set(true); + execute(); + return null; }); // No filter function found => we need to execute anyway( as before the use of withinFilter ) if (!executed.get()) { @@ -427,12 +424,7 @@ public WaitForTasksCompletion() { public static void waitFor(Future task, final Invocation invocation) { if (task instanceof Promise) { Promise smartFuture = (Promise) task; - smartFuture.onRedeem(new F.Action>() { - @Override - public void invoke(Promise result) { - executor.submit(invocation); - } - }); + smartFuture.onRedeem(result -> executor.submit(invocation)); } else { synchronized (WaitForTasksCompletion.class) { if (instance == null) { diff --git a/framework/src/play/Play.java b/framework/src/play/Play.java index 32b6b16509..4e4a88c83c 100644 --- a/framework/src/play/Play.java +++ b/framework/src/play/Play.java @@ -7,6 +7,7 @@ import java.io.LineNumberReader; import java.net.URI; import java.net.URL; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; @@ -348,7 +349,7 @@ public static void guessFrameworkPath() { if (frameworkPath == null || !frameworkPath.exists()) { if (uri.getScheme().equals("jar")) { String jarPath = uri.getSchemeSpecificPart().substring(5, - uri.getSchemeSpecificPart().lastIndexOf("!")); + uri.getSchemeSpecificPart().lastIndexOf('!')); frameworkPath = new File(jarPath).getParentFile().getParentFile().getAbsoluteFile(); } else if (uri.getScheme().equals("file")) { frameworkPath = new File(uri).getParentFile().getParentFile().getParentFile().getParentFile(); @@ -482,12 +483,7 @@ public static synchronized void start() { // our plugins that we're going down when some calls ctrl+c or just kills our // process.. shutdownHookEnabled = true; - Thread hook = new Thread() { - @Override - public void run() { - Play.stop(); - } - }; + Thread hook = new Thread(Play::stop); hook.setContextClassLoader(ClassLoader.getSystemClassLoader()); Runtime.getRuntime().addShutdownHook(hook); } @@ -684,7 +680,6 @@ public static synchronized void detectChanges() { } } - @SuppressWarnings("unchecked") public static T plugin(Class clazz) { return pluginCollection.getPluginInstance(clazz); } @@ -702,7 +697,7 @@ public static void initStaticStuff() { while (urls != null && urls.hasMoreElements()) { URL url = urls.nextElement(); try { - BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8")); + BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8)); String line = null; while ((line = reader.readLine()) != null) { try { @@ -745,7 +740,7 @@ public static void loadModules(VirtualFile appRoot) { } else { String modulePathName = modulePath.getName(); String moduleName = modulePathName.contains("-") - ? modulePathName.substring(0, modulePathName.lastIndexOf("-")) + ? modulePathName.substring(0, modulePathName.lastIndexOf('-')) : modulePathName; addModule(appRoot, moduleName, modulePath); } @@ -776,16 +771,14 @@ public static void loadModules(VirtualFile appRoot) { modules.addAll(Arrays.asList(localModules.list())); } - for (Iterator iter = modules.iterator(); iter.hasNext();) { - String moduleName = iter.next(); - + for (String moduleName : modules) { File module = new File(localModules, moduleName); if (moduleName.contains("-")) { - moduleName = moduleName.substring(0, moduleName.indexOf("-")); + moduleName = moduleName.substring(0, moduleName.indexOf('-')); } - if (module == null || !module.exists()) { + if (!module.exists()) { Logger.error("Module %s will not be loaded because %s does not exist", moduleName, module.getAbsolutePath()); } else if (module.isDirectory()) { diff --git a/framework/src/play/PlayPlugin.java b/framework/src/play/PlayPlugin.java index 9781e4f5ec..543bbf802c 100644 --- a/framework/src/play/PlayPlugin.java +++ b/framework/src/play/PlayPlugin.java @@ -552,25 +552,10 @@ public T withinFilter(F.Function0 fct) throws Throwable { private static Function1, T> compose(final Function1, T> outer, final Function1, T> inner) { - return new Function1, T>() { - @Override - public T apply(final F.Function0 arg) throws Throwable { - return outer.apply(new F.Function0() { - @Override - public T apply() throws Throwable { - return inner.apply(arg); - } - }); - } - }; + return arg -> outer.apply(() -> inner.apply(arg)); } - private final Function1, T> _asFunction = new Function1, T>() { - @Override - public T apply(F.Function0 arg) throws Throwable { - return withinFilter(arg); - } - }; + private final Function1, T> _asFunction = this::withinFilter; public Function1, T> asFunction() { return _asFunction; diff --git a/framework/src/play/ant/PlayConfigurationLoadTask.java b/framework/src/play/ant/PlayConfigurationLoadTask.java index be9168da1c..41512ef295 100644 --- a/framework/src/play/ant/PlayConfigurationLoadTask.java +++ b/framework/src/play/ant/PlayConfigurationLoadTask.java @@ -186,7 +186,7 @@ private Set modules() { } private static String[] splitLine(String line) { - if (line.indexOf("=") == -1) return null; + if (line.indexOf('=') == -1) return null; String[] splitted = line.split("="); return new String[]{splitted[0].trim(), splitted[1].trim()}; } diff --git a/framework/src/play/cache/EhCacheImpl.java b/framework/src/play/cache/EhCacheImpl.java index d84a6ab991..a8f604620d 100644 --- a/framework/src/play/cache/EhCacheImpl.java +++ b/framework/src/play/cache/EhCacheImpl.java @@ -64,7 +64,7 @@ public synchronized long decr(String key, int by) { if (e == null) { return -1; } - long newValue = ((Number) e.getValue()).longValue() - by; + long newValue = ((Number) e.getObjectValue()).longValue() - by; Element newE = new Element(key, newValue); newE.setTimeToLive(e.getTimeToLive()); cache.put(newE); @@ -79,7 +79,7 @@ public void delete(String key) { @Override public Object get(String key) { Element e = cache.get(key); - return (e == null) ? null : e.getValue(); + return (e == null) ? null : e.getObjectValue(); } @Override @@ -97,7 +97,7 @@ public synchronized long incr(String key, int by) { if (e == null) { return -1; } - long newValue = ((Number) e.getValue()).longValue() + by; + long newValue = ((Number) e.getObjectValue()).longValue() + by; Element newE = new Element(key, newValue); newE.setTimeToLive(e.getTimeToLive()); cache.put(newE); diff --git a/framework/src/play/classloading/ApplicationClasses.java b/framework/src/play/classloading/ApplicationClasses.java index beb70dfc74..3874f6ad9d 100644 --- a/framework/src/play/classloading/ApplicationClasses.java +++ b/framework/src/play/classloading/ApplicationClasses.java @@ -47,13 +47,10 @@ public void clear() { * @return The ApplicationClass or null */ public ApplicationClass getApplicationClass(String name) { - if (!classes.containsKey(name)) { - VirtualFile javaFile = getJava(name); - if (javaFile != null) { - classes.put(name, new ApplicationClass(name, javaFile)); - } - } - return classes.get(name); + return classes.computeIfAbsent(name, className -> { + VirtualFile javaFile = getJava(className); + return javaFile == null ? null : new ApplicationClass(className, javaFile); + }); } /** @@ -358,7 +355,7 @@ public String toString() { public static VirtualFile getJava(String name) { String fileName = name; if (fileName.contains("$")) { - fileName = fileName.substring(0, fileName.indexOf("$")); + fileName = fileName.substring(0, fileName.indexOf('$')); } // the local variable fileOrDir is important! String fileOrDir = fileName.replace('.', '/'); diff --git a/framework/src/play/classloading/ApplicationClassloader.java b/framework/src/play/classloading/ApplicationClassloader.java index f29eb454f8..279c63a4c7 100644 --- a/framework/src/play/classloading/ApplicationClassloader.java +++ b/framework/src/play/classloading/ApplicationClassloader.java @@ -197,11 +197,11 @@ private String getPackageName(String name) { private void loadPackage(String className) { // find the package class name - int symbol = className.indexOf("$"); + int symbol = className.indexOf('$'); if (symbol > -1) { className = className.substring(0, symbol); } - symbol = className.lastIndexOf("."); + symbol = className.lastIndexOf('.'); if (symbol > -1) { className = className.substring(0, symbol) + ".package-info"; } else { @@ -446,13 +446,7 @@ public List getAllClasses() { } } - Collections.sort(result, new Comparator() { - - @Override - public int compare(Class o1, Class o2) { - return o1.getName().compareTo(o2.getName()); - } - }); + Collections.sort(result, Comparator.comparing(Class::getName)); } Map byNormalizedName = new HashMap<>(result.size()); @@ -484,18 +478,14 @@ public List getAssignableClasses(Class clazz) { return Collections.emptyList(); } getAllClasses(); - List results = assignableClassesByName.get(clazz.getName()); - if (results != null) { - return results; - } else { - results = new ArrayList<>(); - for (ApplicationClass c : Play.classes.getAssignableClasses(clazz)) { - results.add(c.javaClass); + return assignableClassesByName.computeIfAbsent(clazz.getName(), className -> { + List assignableClasses = Play.classes.getAssignableClasses(clazz); + List> results = new ArrayList<>(assignableClasses.size()); + for (ApplicationClass assignableClass : assignableClasses) { + results.add(assignableClass.javaClass); } - // cache assignable classes - assignableClassesByName.put(clazz.getName(), unmodifiableList(results)); - } - return results; + return unmodifiableList(results); + }); } // assignable classes cache diff --git a/framework/src/play/classloading/ApplicationCompiler.java b/framework/src/play/classloading/ApplicationCompiler.java index 1c1c079d8d..5fe7ed56d6 100644 --- a/framework/src/play/classloading/ApplicationCompiler.java +++ b/framework/src/play/classloading/ApplicationCompiler.java @@ -98,7 +98,7 @@ final class CompilationUnit implements ICompilationUnit { CompilationUnit(String pClazzName) { clazzName = pClazzName; if (pClazzName.contains("$")) { - pClazzName = pClazzName.substring(0, pClazzName.indexOf("$")); + pClazzName = pClazzName.substring(0, pClazzName.indexOf('$')); } fileName = pClazzName.replace('.', '/') + ".java"; int dot = pClazzName.lastIndexOf('.'); @@ -265,42 +265,38 @@ public void cleanup() { /** * Compilation result */ - ICompilerRequestor compilerRequestor = new ICompilerRequestor() { - - @Override - public void acceptResult(CompilationResult result) { - // If error - if (result.hasErrors()) { - for (IProblem problem : result.getErrors()) { - String className = new String(problem.getOriginatingFileName()).replace('/', '.'); - className = className.substring(0, className.length() - 5); - String message = problem.getMessage(); - if (problem.getID() == IProblem.CannotImportPackage) { - // Non sense ! - message = problem.getArguments()[0] + " cannot be resolved"; - } - throw new CompilationException(Play.classes.getApplicationClass(className).javaFile, message, - problem.getSourceLineNumber(), problem.getSourceStart(), problem.getSourceEnd()); + ICompilerRequestor compilerRequestor = result -> { + // If error + if (result.hasErrors()) { + for (IProblem problem : result.getErrors()) { + String className = new String(problem.getOriginatingFileName()).replace('/', '.'); + className = className.substring(0, className.length() - 5); + String message = problem.getMessage(); + if (problem.getID() == IProblem.CannotImportPackage) { + // Non sense ! + message = problem.getArguments()[0] + " cannot be resolved"; } + throw new CompilationException(Play.classes.getApplicationClass(className).javaFile, message, + problem.getSourceLineNumber(), problem.getSourceStart(), problem.getSourceEnd()); } - // Something has been compiled - ClassFile[] clazzFiles = result.getClassFiles(); - for (final ClassFile clazzFile : clazzFiles) { - char[][] compoundName = clazzFile.getCompoundName(); - StringBuilder clazzName = new StringBuilder(); - for (int j = 0; j < compoundName.length; j++) { - if (j != 0) { - clazzName.append('.'); - } - clazzName.append(compoundName[j]); - } - - if (Logger.isTraceEnabled()) { - Logger.trace("Compiled %s", clazzName); + } + // Something has been compiled + ClassFile[] clazzFiles = result.getClassFiles(); + for (final ClassFile clazzFile : clazzFiles) { + char[][] compoundName = clazzFile.getCompoundName(); + StringBuilder clazzName = new StringBuilder(); + for (int j = 0; j < compoundName.length; j++) { + if (j != 0) { + clazzName.append('.'); } + clazzName.append(compoundName[j]); + } - applicationClasses.getApplicationClass(clazzName.toString()).compiled(clazzFile.getBytes()); + if (Logger.isTraceEnabled()) { + Logger.trace("Compiled %s", clazzName); } + + applicationClasses.getApplicationClass(clazzName.toString()).compiled(clazzFile.getBytes()); } }; diff --git a/framework/src/play/classloading/enhancers/LocalvariablesNamesEnhancer.java b/framework/src/play/classloading/enhancers/LocalvariablesNamesEnhancer.java index 48d1b88df7..fc41da7ab1 100644 --- a/framework/src/play/classloading/enhancers/LocalvariablesNamesEnhancer.java +++ b/framework/src/play/classloading/enhancers/LocalvariablesNamesEnhancer.java @@ -64,8 +64,9 @@ public void enhanceThisClass(ApplicationClass applicationClass) throws Exception // Normalize the variable name // For several reasons, both variables name and name$1 will be aliased to name String aliasedName = name; - if (aliasedName.contains("$")) { - aliasedName = aliasedName.substring(0, aliasedName.indexOf("$")); + int dollarIndex = aliasedName.indexOf('$'); + if (dollarIndex >= 0) { + aliasedName = aliasedName.substring(0, dollarIndex); } if ("this".equals(name)) { diff --git a/framework/src/play/classloading/enhancers/LocalvariablesNamesEnhancerJava7.java b/framework/src/play/classloading/enhancers/LocalvariablesNamesEnhancerJava7.java index 993cc80f89..6fd8929bec 100644 --- a/framework/src/play/classloading/enhancers/LocalvariablesNamesEnhancerJava7.java +++ b/framework/src/play/classloading/enhancers/LocalvariablesNamesEnhancerJava7.java @@ -56,13 +56,7 @@ public void enhanceThisClass(ApplicationClass applicationClass) throws Exception parameterNames.add(new T2<>(localVariableAttribute.startPc(i) + localVariableAttribute.index(i), localVariableAttribute.variableName(i))); } } - Collections.sort(parameterNames, new Comparator>() { - @Override - public int compare(T2 o1, T2 o2) { - return o1._1.compareTo(o2._1); - } - - }); + Collections.sort(parameterNames, Comparator.comparing(o -> o._1)); } List names = new ArrayList<>(); for (int i = 0; i < method.getParameterTypes().length + (Modifier.isStatic(method.getModifiers()) ? 0 : 1); i++) { @@ -86,8 +80,9 @@ public int compare(T2 o1, T2 o2) { for (Iterator i = names.iterator(); i.hasNext();) { iv.append("\""); String aliasedName = i.next(); - if (aliasedName.contains("$")) { - aliasedName = aliasedName.substring(0, aliasedName.indexOf("$")); + int dollarIndex = aliasedName.indexOf('$'); + if (dollarIndex >= 0) { + aliasedName = aliasedName.substring(0, dollarIndex); } iv.append(aliasedName); iv.append("\""); @@ -122,8 +117,9 @@ public int compare(T2 o1, T2 o2) { // Normalize the variable name // For several reasons, both variables name and name$1 will be aliased to name String aliasedName = name; - if (aliasedName.contains("$")) { - aliasedName = aliasedName.substring(0, aliasedName.indexOf("$")); + int dollarIndex = aliasedName.indexOf('$'); + if (dollarIndex >= 0) { + aliasedName = aliasedName.substring(0, dollarIndex); } diff --git a/framework/src/play/data/binding/Binder.java b/framework/src/play/data/binding/Binder.java index d274e1ee23..96266587cf 100644 --- a/framework/src/play/data/binding/Binder.java +++ b/framework/src/play/data/binding/Binder.java @@ -84,11 +84,7 @@ public static void unregister(Class clazz) { static Map, BeanWrapper> beanwrappers = new HashMap<>(); static BeanWrapper getBeanWrapper(Class clazz) { - if (!beanwrappers.containsKey(clazz)) { - BeanWrapper beanwrapper = new BeanWrapper(clazz); - beanwrappers.put(clazz, beanwrapper); - } - return beanwrappers.get(clazz); + return beanwrappers.computeIfAbsent(clazz, BeanWrapper::new); } public static class MethodAndParamInfo { @@ -521,9 +517,9 @@ private static Object bindCollection(Class clazz, Type type, ParamNode paramN l = (Collection) createNewInstance(clazz); } boolean hasMissing = false; - for (int i = 0; i < values.length; i++) { + for (String paramNodeValue : values) { try { - Object value = internalDirectBind(paramNode.getOriginalKey(), bindingAnnotations.annotations, values[i], componentClass, + Object value = internalDirectBind(paramNode.getOriginalKey(), bindingAnnotations.annotations, paramNodeValue, componentClass, componentType); if (value == DIRECTBINDING_NO_RESULT) { hasMissing = true; @@ -548,14 +544,11 @@ private static Object bindCollection(Class clazz, Type type, ParamNode paramN List l = (List) r; // must get all indexes and sort them so we add items in correct order. - Set indexes = new TreeSet<>(new Comparator() { - @Override - public int compare(String arg0, String arg1) { - try { - return Integer.parseInt(arg0) - Integer.parseInt(arg1); - } catch (NumberFormatException e) { - return arg0.compareTo(arg1); - } + Set indexes = new TreeSet<>((arg0, arg1) -> { + try { + return Integer.parseInt(arg0) - Integer.parseInt(arg1); + } catch (NumberFormatException e) { + return arg0.compareTo(arg1); } }); indexes.addAll(paramNode.getAllChildrenKeys()); @@ -737,43 +730,43 @@ private static Object internalDirectBind(String name, Annotation[] annotations, } // int or Integer binding - if (clazz.getName().equals("int") || clazz.equals(Integer.class)) { + if (clazz.equals(int.class) || clazz.equals(Integer.class)) { if (nullOrEmpty) { return clazz.isPrimitive() ? 0 : null; } - return Integer.parseInt(value.contains(".") ? value.substring(0, value.indexOf(".")) : value); + return Integer.parseInt(value.contains(".") ? value.substring(0, value.indexOf('.')) : value); } // long or Long binding - if (clazz.getName().equals("long") || clazz.equals(Long.class)) { + if (clazz.equals(long.class) || clazz.equals(Long.class)) { if (nullOrEmpty) { return clazz.isPrimitive() ? 0l : null; } - return Long.parseLong(value.contains(".") ? value.substring(0, value.indexOf(".")) : value); + return Long.parseLong(value.contains(".") ? value.substring(0, value.indexOf('.')) : value); } // byte or Byte binding - if (clazz.getName().equals("byte") || clazz.equals(Byte.class)) { + if (clazz.equals(byte.class) || clazz.equals(Byte.class)) { if (nullOrEmpty) { return clazz.isPrimitive() ? (byte) 0 : null; } - return Byte.parseByte(value.contains(".") ? value.substring(0, value.indexOf(".")) : value); + return Byte.parseByte(value.contains(".") ? value.substring(0, value.indexOf('.')) : value); } // short or Short binding - if (clazz.getName().equals("short") || clazz.equals(Short.class)) { + if (clazz.equals(short.class) || clazz.equals(Short.class)) { if (nullOrEmpty) { return clazz.isPrimitive() ? (short) 0 : null; } - return Short.parseShort(value.contains(".") ? value.substring(0, value.indexOf(".")) : value); + return Short.parseShort(value.contains(".") ? value.substring(0, value.indexOf('.')) : value); } // float or Float binding - if (clazz.getName().equals("float") || clazz.equals(Float.class)) { + if (clazz.equals(float.class) || clazz.equals(Float.class)) { if (nullOrEmpty) { return clazz.isPrimitive() ? 0f : null; } @@ -782,7 +775,7 @@ private static Object internalDirectBind(String name, Annotation[] annotations, } // double or Double binding - if (clazz.getName().equals("double") || clazz.equals(Double.class)) { + if (clazz.equals(double.class) || clazz.equals(Double.class)) { if (nullOrEmpty) { return clazz.isPrimitive() ? 0d : null; } @@ -801,7 +794,7 @@ private static Object internalDirectBind(String name, Annotation[] annotations, } // boolean or Boolean binding - if (clazz.getName().equals("boolean") || clazz.equals(Boolean.class)) { + if (clazz.equals(boolean.class) || clazz.equals(Boolean.class)) { if (nullOrEmpty) { return clazz.isPrimitive() ? false : null; } diff --git a/framework/src/play/data/binding/ParamNode.java b/framework/src/play/data/binding/ParamNode.java index e9a4edb047..ab62a26699 100644 --- a/framework/src/play/data/binding/ParamNode.java +++ b/framework/src/play/data/binding/ParamNode.java @@ -102,8 +102,8 @@ public static void restoreRemovedChildren( List removedNodesList ) private ParamNode getChild(String[] nestedNames) { ParamNode currentChildNode = this; - for (int i=0; i map, String name, String value) { - String[] newValues; - String[] oldValues = map.get(name); - if (oldValues == null) { - newValues = new String[1]; - newValues[0] = value; - } else { - newValues = new String[oldValues.length + 1]; + map.compute(name, (key, oldValues) -> { + if (oldValues == null) { + return new String[] { value }; + } + + String[] newValues = new String[oldValues.length + 1]; System.arraycopy(oldValues, 0, newValues, 0, oldValues.length); newValues[oldValues.length] = value; - } - map.put(name, newValues); + + return newValues; + }); } /* @@ -547,11 +547,7 @@ public Map parse(InputStream body) { putMapEntry(result, fileItem.getFieldName(), fileItem.getString(_encoding)); } else { @SuppressWarnings("unchecked") - List uploads = (List) Request.current().args.get("__UPLOADS"); - if (uploads == null) { - uploads = new ArrayList<>(); - Request.current().args.put("__UPLOADS", uploads); - } + List uploads = (List) Request.current().args.computeIfAbsent("__UPLOADS", k -> new ArrayList<>()); try { uploads.add(new FileUpload(fileItem)); } catch (Exception e) { diff --git a/framework/src/play/data/parsing/MultipartStream.java b/framework/src/play/data/parsing/MultipartStream.java index 6dae8b6453..796449e9da 100644 --- a/framework/src/play/data/parsing/MultipartStream.java +++ b/framework/src/play/data/parsing/MultipartStream.java @@ -478,7 +478,6 @@ public String readHeaders() byte[] b = new byte[1]; // to support multi-byte characters ByteArrayOutputStream baos = new ByteArrayOutputStream(); - int sizeMax = HEADER_PART_SIZE_MAX; int size = 0; while (i < HEADER_SEPARATOR.length) { try { @@ -492,7 +491,7 @@ public String readHeaders() } else { i = 0; } - if (size <= sizeMax) { + if (size <= HEADER_PART_SIZE_MAX) { baos.write(b[0]); } } diff --git a/framework/src/play/data/validation/IPv4AddressCheck.java b/framework/src/play/data/validation/IPv4AddressCheck.java index 4d2faf07b9..d10488e7f5 100644 --- a/framework/src/play/data/validation/IPv4AddressCheck.java +++ b/framework/src/play/data/validation/IPv4AddressCheck.java @@ -28,12 +28,12 @@ public boolean isSatisfied(Object validatedObject, Object value, OValContext con return false; } - for (int i = 0; i < parts.length; i++) { + for (String part : parts) { // Check that we don't have empty part or (+-) sign - if (parts[i].isEmpty() || !parts[i].matches("[0-9]{1,3}")) { + if (part.isEmpty() || !part.matches("[0-9]{1,3}")) { return false; } - int p = Integer.valueOf(parts[i]); + int p = Integer.parseInt(part); if (p < 0 || p > 255) { return false; } diff --git a/framework/src/play/data/validation/ValidationPlugin.java b/framework/src/play/data/validation/ValidationPlugin.java index be3a8a0584..f51c4fb1fe 100644 --- a/framework/src/play/data/validation/ValidationPlugin.java +++ b/framework/src/play/data/validation/ValidationPlugin.java @@ -18,6 +18,7 @@ import java.lang.reflect.Modifier; import java.net.URLDecoder; import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -135,7 +136,7 @@ static Validation restore() { Validation validation = new Validation(); Http.Cookie cookie = Http.Request.current().cookies.get(Scope.COOKIE_PREFIX + "_ERRORS"); if (cookie != null) { - String errorsData = URLDecoder.decode(cookie.value, "utf-8"); + String errorsData = URLDecoder.decode(cookie.value, StandardCharsets.UTF_8); Matcher matcher = errorsParser.matcher(errorsData); while (matcher.find()) { String[] g2 = matcher.group(2).split("\u0001", -1); @@ -178,7 +179,7 @@ static void save() { errors.append("\u0000"); } } - String errorsData = URLEncoder.encode(errors.toString(), "utf-8"); + String errorsData = URLEncoder.encode(errors.toString(), StandardCharsets.UTF_8); Http.Response.current().setCookie(Scope.COOKIE_PREFIX + "_ERRORS", errorsData, null, "/", null, Scope.COOKIE_SECURE, Scope.SESSION_HTTPONLY); } catch (Exception e) { throw new UnexpectedException("Errors serializationProblem", e); diff --git a/framework/src/play/db/Configuration.java b/framework/src/play/db/Configuration.java index 29cb20360b..ae14a04639 100644 --- a/framework/src/play/db/Configuration.java +++ b/framework/src/play/db/Configuration.java @@ -110,10 +110,9 @@ public Map getProperties() { if (matcher.matches()) { final String key_prefix_for_db_related_setting = matcher.group(1); if (keyName.startsWith(key_prefix_for_db_related_setting + "." + this.configName)) { - String type = key_prefix_for_db_related_setting; - String newKey = type; - if (keyName.length() > (type + "." + this.configName).length()) { - newKey += "." + keyName.substring((type + "." + this.configName).length() + 1); + String newKey = key_prefix_for_db_related_setting; + if (keyName.length() > (key_prefix_for_db_related_setting + "." + this.configName).length()) { + newKey += "." + keyName.substring((key_prefix_for_db_related_setting + "." + this.configName).length() + 1); } properties.put(newKey, props.get(key).toString()); } else if (this.isDefault()) { diff --git a/framework/src/play/db/Evolutions.java b/framework/src/play/db/Evolutions.java index 6c6ec42956..554a0a77fe 100644 --- a/framework/src/play/db/Evolutions.java +++ b/framework/src/play/db/Evolutions.java @@ -322,8 +322,8 @@ public boolean rawInvocation(Request request, Response response) throws Exceptio int index = request.url.lastIndexOf("/@evolutions/force/") + "/@evolutions/force/".length(); String dbName = DB.DEFAULT; - String moduleKey = request.url.substring(index, request.url.lastIndexOf("/")); - int revision = Integer.parseInt(request.url.substring(request.url.lastIndexOf("/") + 1)); + String moduleKey = request.url.substring(index, request.url.lastIndexOf('/')); + int revision = Integer.parseInt(request.url.substring(request.url.lastIndexOf('/') + 1)); resolve(dbName, moduleKey, revision); new Redirect("/").apply(request, response); @@ -596,9 +596,9 @@ public static synchronized Stack listApplicationEvolutions(String dBN int version = 0; if (evolution.getName().contains(dBName)) { version = Integer.parseInt( - evolution.getName().substring(evolution.getName().indexOf(".") + 1, evolution.getName().lastIndexOf("."))); + evolution.getName().substring(evolution.getName().indexOf('.') + 1, evolution.getName().lastIndexOf('.'))); } else { - version = Integer.parseInt(evolution.getName().substring(0, evolution.getName().indexOf("."))); + version = Integer.parseInt(evolution.getName().substring(0, evolution.getName().indexOf('.'))); } String sql = IO.readContentAsString(evolution); diff --git a/framework/src/play/db/helper/JdbcResultFactories.java b/framework/src/play/db/helper/JdbcResultFactories.java index 89c77fe684..0dfa4d6dca 100644 --- a/framework/src/play/db/helper/JdbcResultFactories.java +++ b/framework/src/play/db/helper/JdbcResultFactories.java @@ -108,7 +108,7 @@ public void init(ResultSet result) throws SQLException { @Override public T create(ResultSet result) throws SQLException { Object value = result.getObject(columnIndex); - if (value instanceof BigDecimal) value = new Long(((BigDecimal)value).longValue()); + if (value instanceof BigDecimal) value = ((BigDecimal) value).longValue(); if (!objectClass.isInstance(value)) throw new IllegalArgumentException(); return (T) value; } @@ -144,7 +144,7 @@ public T create(ResultSet result) throws SQLException { T obj = objectClass.newInstance(); for (String field : fields) { Object value = result.getObject(field); - if (value instanceof BigDecimal) value = new Long(((BigDecimal)value).longValue()); + if (value instanceof BigDecimal) value = ((BigDecimal) value).longValue(); objectClass.getDeclaredField(field).set(obj, value); } return obj; diff --git a/framework/src/play/db/jpa/Blob.java b/framework/src/play/db/jpa/Blob.java index f29c503245..a9ad9ab8bf 100644 --- a/framework/src/play/db/jpa/Blob.java +++ b/framework/src/play/db/jpa/Blob.java @@ -10,7 +10,6 @@ import java.sql.Types; import org.hibernate.HibernateException; -import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.type.StringType; import org.hibernate.usertype.UserType; diff --git a/framework/src/play/db/jpa/JPA.java b/framework/src/play/db/jpa/JPA.java index a1fd986b58..a733ece071 100644 --- a/framework/src/play/db/jpa/JPA.java +++ b/framework/src/play/db/jpa/JPA.java @@ -24,12 +24,7 @@ public class JPA { protected static Map emfs = new ConcurrentHashMap<>(); - public static final ThreadLocal> currentEntityManager = new ThreadLocal>() { - @Override - protected Map initialValue() { - return new ConcurrentHashMap<>(); - } - }; + public static final ThreadLocal> currentEntityManager = ThreadLocal.withInitial(ConcurrentHashMap::new); public static String DEFAULT = "default"; public static class JPAContext { diff --git a/framework/src/play/db/jpa/JPAModelLoader.java b/framework/src/play/db/jpa/JPAModelLoader.java index dd81ecb6e1..64d60803d9 100644 --- a/framework/src/play/db/jpa/JPAModelLoader.java +++ b/framework/src/play/db/jpa/JPAModelLoader.java @@ -404,26 +404,14 @@ Model.Property buildProperty(final Field field) { modelProperty.isRelation = true; modelProperty.relationType = field.getType(); final String modelDbName = JPA.getDBName(modelProperty.relationType); - modelProperty.choices = new Model.Choices() { - @SuppressWarnings("unchecked") - @Override - public List list() { - return JPA.em(modelDbName).createQuery("from " + field.getType().getName()).getResultList(); - } - }; + modelProperty.choices = () -> JPA.em(modelDbName).createQuery("from " + field.getType().getName()).getResultList(); } } if (field.isAnnotationPresent(ManyToOne.class)) { modelProperty.isRelation = true; modelProperty.relationType = field.getType(); final String modelDbName = JPA.getDBName(modelProperty.relationType); - modelProperty.choices = new Model.Choices() { - @SuppressWarnings("unchecked") - @Override - public List list() { - return JPA.em(modelDbName).createQuery("from " + field.getType().getName()).getResultList(); - } - }; + modelProperty.choices = () -> JPA.em(modelDbName).createQuery("from " + field.getType().getName()).getResultList(); } } if (Collection.class.isAssignableFrom(field.getType())) { @@ -434,13 +422,7 @@ public List list() { modelProperty.isMultiple = true; modelProperty.relationType = fieldType; final String modelDbName = JPA.getDBName(modelProperty.relationType); - modelProperty.choices = new Model.Choices() { - @SuppressWarnings("unchecked") - @Override - public List list() { - return JPA.em(modelDbName).createQuery("from " + fieldType.getName()).getResultList(); - } - }; + modelProperty.choices = () -> JPA.em(modelDbName).createQuery("from " + fieldType.getName()).getResultList(); } } if (field.isAnnotationPresent(ManyToMany.class)) { @@ -449,26 +431,12 @@ public List list() { modelProperty.isMultiple = true; modelProperty.relationType = fieldType; final String modelDbName = JPA.getDBName(field.getType()); - modelProperty.choices = new Model.Choices() { - - @SuppressWarnings("unchecked") - @Override - public List list() { - return JPA.em(modelDbName).createQuery("from " + fieldType.getName()).getResultList(); - } - }; + modelProperty.choices = () -> JPA.em(modelDbName).createQuery("from " + fieldType.getName()).getResultList(); } } } if (field.getType().isEnum()) { - modelProperty.choices = new Model.Choices() { - - @SuppressWarnings("unchecked") - @Override - public List list() { - return (List) Arrays.asList(field.getType().getEnumConstants()); - } - }; + modelProperty.choices = () -> (List) Arrays.asList(field.getType().getEnumConstants()); } modelProperty.name = field.getName(); if (field.getType().equals(String.class)) { diff --git a/framework/src/play/deps/HumanReadyLogger.java b/framework/src/play/deps/HumanReadyLogger.java index d7cfc9167a..b91c7e9161 100644 --- a/framework/src/play/deps/HumanReadyLogger.java +++ b/framework/src/play/deps/HumanReadyLogger.java @@ -88,7 +88,7 @@ public void niceLog(String msg, int level) { } if (msg.startsWith("[SUCCESSFUL")) { - msg = msg.substring(msg.indexOf("(")); + msg = msg.substring(msg.indexOf('(')); System.out.println("\r~ \t" + (downloading + " ").replace("(jar)", "").replace("downloading", "downloaded").replace("...", " ")); } diff --git a/framework/src/play/i18n/Lang.java b/framework/src/play/i18n/Lang.java index 4d830973f6..7e02aed994 100644 --- a/framework/src/play/i18n/Lang.java +++ b/framework/src/play/i18n/Lang.java @@ -112,13 +112,13 @@ private static String findClosestMatch(Collection desiredLocales) { } // Exact match not found, try language-only match. for (String a : cleanLocales) { - int splitPos = a.indexOf("_"); + int splitPos = a.indexOf('_'); if (splitPos > 0) { a = a.substring(0, splitPos); } for (String locale : Play.langs) { String langOnlyLocale; - int localeSplitPos = locale.indexOf("_"); + int localeSplitPos = locale.indexOf('_'); if (localeSplitPos > 0) { langOnlyLocale = locale.substring(0, localeSplitPos); } else { @@ -211,7 +211,7 @@ public static Locale getLocale(String localeStr) { private static Locale findLocale(String localeStr) { String lang = localeStr; - int splitPos = lang.indexOf("_"); + int splitPos = lang.indexOf('_'); if (splitPos > 0) { lang = lang.substring(0, splitPos); } diff --git a/framework/src/play/i18n/Localized.java b/framework/src/play/i18n/Localized.java index 960db2ae32..4ca6f5392f 100644 --- a/framework/src/play/i18n/Localized.java +++ b/framework/src/play/i18n/Localized.java @@ -28,7 +28,6 @@ public T get(String lang) { return this.values.get(lang); } - @SuppressWarnings("unchecked") public Set values() { return new HashSet<>(values.values()); } diff --git a/framework/src/play/jobs/Job.java b/framework/src/play/jobs/Job.java index 901ce062b8..aa3a7493d3 100644 --- a/framework/src/play/jobs/Job.java +++ b/framework/src/play/jobs/Job.java @@ -128,21 +128,18 @@ public Promise in(int seconds) { } private Callable getJobCallingCallable(final Promise smartFuture) { - return new Callable() { - @Override - public V call() throws Exception { - try { - V result = Job.this.call(); - if (smartFuture != null) { - smartFuture.invoke(result); - } - return result; - } catch (Exception e) { - if (smartFuture != null) { - smartFuture.invokeWithException(e); - } - return null; + return () -> { + try { + V result = Job.this.call(); + if (smartFuture != null) { + smartFuture.invoke(result); + } + return result; + } catch (Exception e) { + if (smartFuture != null) { + smartFuture.invokeWithException(e); } + return null; } }; } @@ -217,12 +214,9 @@ public V call() { // If we have a plugin, get him to execute the job within the filter. final AtomicBoolean executed = new AtomicBoolean(false); - result = this.withinFilter(new play.libs.F.Function0() { - @Override - public V apply() throws Throwable { - executed.set(true); - return doJobWithResult(); - } + result = this.withinFilter(() -> { + executed.set(true); + return doJobWithResult(); }); // No filter function found => we need to execute anyway( as before the use of withinFilter ) diff --git a/framework/src/play/libs/Codec.java b/framework/src/play/libs/Codec.java index e95b284d3f..6563f9d4a1 100644 --- a/framework/src/play/libs/Codec.java +++ b/framework/src/play/libs/Codec.java @@ -1,6 +1,5 @@ package play.libs; -import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.util.UUID; diff --git a/framework/src/play/libs/CronExpression.java b/framework/src/play/libs/CronExpression.java index a31de92202..09d9dcd5a2 100644 --- a/framework/src/play/libs/CronExpression.java +++ b/framework/src/play/libs/CronExpression.java @@ -174,32 +174,32 @@ public class CronExpression implements Serializable, Cloneable { protected static final int YEAR = 6; protected static final int ALL_SPEC_INT = 99; // '*' protected static final int NO_SPEC_INT = 98; // '?' - protected static final Integer ALL_SPEC = new Integer(ALL_SPEC_INT); - protected static final Integer NO_SPEC = new Integer(NO_SPEC_INT); + protected static final Integer ALL_SPEC = ALL_SPEC_INT; + protected static final Integer NO_SPEC = NO_SPEC_INT; protected static Map monthMap = new HashMap<>(20); protected static Map dayMap = new HashMap<>(60); static { - monthMap.put("JAN", new Integer(0)); - monthMap.put("FEB", new Integer(1)); - monthMap.put("MAR", new Integer(2)); - monthMap.put("APR", new Integer(3)); - monthMap.put("MAY", new Integer(4)); - monthMap.put("JUN", new Integer(5)); - monthMap.put("JUL", new Integer(6)); - monthMap.put("AUG", new Integer(7)); - monthMap.put("SEP", new Integer(8)); - monthMap.put("OCT", new Integer(9)); - monthMap.put("NOV", new Integer(10)); - monthMap.put("DEC", new Integer(11)); - - dayMap.put("SUN", new Integer(1)); - dayMap.put("MON", new Integer(2)); - dayMap.put("TUE", new Integer(3)); - dayMap.put("WED", new Integer(4)); - dayMap.put("THU", new Integer(5)); - dayMap.put("FRI", new Integer(6)); - dayMap.put("SAT", new Integer(7)); + monthMap.put("JAN", 0); + monthMap.put("FEB", 1); + monthMap.put("MAR", 2); + monthMap.put("APR", 3); + monthMap.put("MAY", 4); + monthMap.put("JUN", 5); + monthMap.put("JUL", 6); + monthMap.put("AUG", 7); + monthMap.put("SEP", 8); + monthMap.put("OCT", 9); + monthMap.put("NOV", 10); + monthMap.put("DEC", 11); + + dayMap.put("SUN", 1); + dayMap.put("MON", 2); + dayMap.put("TUE", 3); + dayMap.put("WED", 4); + dayMap.put("THU", 5); + dayMap.put("FRI", 6); + dayMap.put("SAT", 7); } private String cronExpression = null; private TimeZone timeZone = null; @@ -615,7 +615,7 @@ protected int checkNext(int pos, String s, int val, int type) throws ParseExcept throw new ParseException("'L' option is not valid here. (pos=" + i + ")", i); } TreeSet set = getSet(type); - set.add(new Integer(val)); + set.add(val); i++; return i; } @@ -627,7 +627,7 @@ protected int checkNext(int pos, String s, int val, int type) throws ParseExcept throw new ParseException("'W' option is not valid here. (pos=" + i + ")", i); } TreeSet set = getSet(type); - set.add(new Integer(val)); + set.add(val); i++; return i; } @@ -647,7 +647,7 @@ protected int checkNext(int pos, String s, int val, int type) throws ParseExcept } TreeSet set = getSet(type); - set.add(new Integer(val)); + set.add(val); i++; return i; } @@ -665,8 +665,7 @@ protected int checkNext(int pos, String s, int val, int type) throws ParseExcept c = s.charAt(i); if (c >= '0' && c <= '9') { ValueSet vs = getValue(v, s, i); - int v1 = vs.value; - end = v1; + end = vs.value; i = vs.pos; } if (i < s.length() && ((c = s.charAt(i)) == '/')) { @@ -859,7 +858,7 @@ protected void addToSet(int val, int end, int incr, int type) throws ParseExcept if ((incr == 0 || incr == -1) && val != ALL_SPEC_INT) { if (val != -1) { - set.add(new Integer(val)); + set.add(val); } else { set.add(NO_SPEC); } @@ -920,7 +919,7 @@ protected void addToSet(int val, int end, int incr, int type) throws ParseExcept } for (int i = startAt; i <= stopAt; i += incr) { - set.add(new Integer(i)); + set.add(i); } } @@ -1020,11 +1019,11 @@ protected Date getTimeAfter(Date afterTime) { int min = cl.get(Calendar.MINUTE); // get second................................................. - st = seconds.tailSet(new Integer(sec)); - if (st != null && st.size() != 0) { - sec = st.first().intValue(); + st = seconds.tailSet(sec); + if (st.size() != 0) { + sec = st.first(); } else { - sec = seconds.first().intValue(); + sec = seconds.first(); min++; cl.set(Calendar.MINUTE, min); } @@ -1035,12 +1034,12 @@ protected Date getTimeAfter(Date afterTime) { t = -1; // get minute................................................. - st = minutes.tailSet(new Integer(min)); - if (st != null && st.size() != 0) { + st = minutes.tailSet(min); + if (st.size() != 0) { t = min; - min = st.first().intValue(); + min = st.first(); } else { - min = minutes.first().intValue(); + min = minutes.first(); hr++; } if (min != t) { @@ -1056,12 +1055,12 @@ protected Date getTimeAfter(Date afterTime) { t = -1; // get hour................................................... - st = hours.tailSet(new Integer(hr)); - if (st != null && st.size() != 0) { + st = hours.tailSet(hr); + if (st.size() != 0) { t = hr; - hr = st.first().intValue(); + hr = st.first(); } else { - hr = hours.first().intValue(); + hr = hours.first(); day++; } if (hr != t) { @@ -1084,7 +1083,7 @@ protected Date getTimeAfter(Date afterTime) { boolean dayOfMSpec = !daysOfMonth.contains(NO_SPEC); boolean dayOfWSpec = !daysOfWeek.contains(NO_SPEC); if (dayOfMSpec && !dayOfWSpec) { // get day by day of month rule - st = daysOfMonth.tailSet(new Integer(day)); + st = daysOfMonth.tailSet(day); if (lastdayOfMonth) { if (!nearestWeekday) { t = day; @@ -1272,11 +1271,11 @@ protected Date getTimeAfter(Date afterTime) { } else { int cDow = cl.get(Calendar.DAY_OF_WEEK); // current // d-o-w - int dow = daysOfWeek.first().intValue(); // desired + int dow = daysOfWeek.first(); // desired // d-o-w - st = daysOfWeek.tailSet(new Integer(cDow)); - if (st != null && st.size() > 0) { - dow = st.first().intValue(); + st = daysOfWeek.tailSet(cDow); + if (st.size() > 0) { + dow = st.first(); } int daysToAdd = 0; @@ -1328,12 +1327,12 @@ protected Date getTimeAfter(Date afterTime) { } // get month................................................... - st = months.tailSet(new Integer(mon)); - if (st != null && st.size() != 0) { + st = months.tailSet(mon); + if (st.size() != 0) { t = mon; - mon = st.first().intValue(); + mon = st.first(); } else { - mon = months.first().intValue(); + mon = months.first(); year++; } if (mon != t) { @@ -1356,10 +1355,10 @@ protected Date getTimeAfter(Date afterTime) { t = -1; // get year................................................... - st = years.tailSet(new Integer(year)); - if (st != null && st.size() != 0) { + st = years.tailSet(year); + if (st.size() != 0) { t = year; - year = st.first().intValue(); + year = st.first(); } else { return null; // ran out of years... } diff --git a/framework/src/play/libs/F.java b/framework/src/play/libs/F.java index c612b666db..bf6b993e00 100644 --- a/framework/src/play/libs/F.java +++ b/framework/src/play/libs/F.java @@ -193,17 +193,13 @@ public List get(long timeout, TimeUnit unit) throws InterruptedException, Exe return get(); } }; - F.Action> action = new F.Action>() { - - @Override - public void invoke(Promise completed) { - waitAllLock.countDown(); - if (waitAllLock.getCount() == 0) { - try { - result.invoke(result.get()); - } catch (Exception e) { - result.invokeWithException(e); - } + F.Action> action = completed -> { + waitAllLock.countDown(); + if (waitAllLock.getCount() == 0) { + try { + result.invoke(result.get()); + } catch (Exception e) { + result.invokeWithException(e); } } }; @@ -219,17 +215,13 @@ public void invoke(Promise completed) { public static Promise> wait2(Promise tA, Promise tB) { final Promise> result = new Promise<>(); Promise> t = waitAll(new Promise[]{tA, tB}); - t.onRedeem(new F.Action>>() { - - @Override - public void invoke(Promise> completed) { - List values = completed.getOrNull(); - if(values != null) { - result.invoke(new F.Tuple((A) values.get(0), (B) values.get(1))); - } - else { - result.invokeWithException(completed.exception); - } + t.onRedeem(completed -> { + List values = completed.getOrNull(); + if(values != null) { + result.invoke(new Tuple((A) values.get(0), (B) values.get(1))); + } + else { + result.invokeWithException(completed.exception); } }); return result; @@ -238,17 +230,13 @@ public void invoke(Promise> completed) { public static Promise> wait3(Promise tA, Promise tB, Promise tC) { final Promise> result = new Promise<>(); Promise> t = waitAll(new Promise[]{tA, tB, tC}); - t.onRedeem(new F.Action>>() { - - @Override - public void invoke(Promise> completed) { - List values = completed.getOrNull(); - if(values != null) { - result.invoke(new F.T3((A) values.get(0), (B) values.get(1), (C) values.get(2))); - } - else { - result.invokeWithException(completed.exception); - } + t.onRedeem(completed -> { + List values = completed.getOrNull(); + if(values != null) { + result.invoke(new T3((A) values.get(0), (B) values.get(1), (C) values.get(2))); + } + else { + result.invokeWithException(completed.exception); } }); return result; @@ -257,17 +245,13 @@ public void invoke(Promise> completed) { public static Promise> wait4(Promise tA, Promise tB, Promise tC, Promise tD) { final Promise> result = new Promise<>(); Promise> t = waitAll(new Promise[]{tA, tB, tC, tD}); - t.onRedeem(new F.Action>>() { - - @Override - public void invoke(Promise> completed) { - List values = completed.getOrNull(); - if(values != null) { - result.invoke(new F.T4((A) values.get(0), (B) values.get(1), (C) values.get(2), (D) values.get(3))); - } - else { - result.invokeWithException(completed.exception); - } + t.onRedeem(completed -> { + List values = completed.getOrNull(); + if(values != null) { + result.invoke(new T4((A) values.get(0), (B) values.get(1), (C) values.get(2), (D) values.get(3))); + } + else { + result.invokeWithException(completed.exception); } }); return result; @@ -276,17 +260,13 @@ public void invoke(Promise> completed) { public static Promise> wait5(Promise tA, Promise tB, Promise tC, Promise tD, Promise tE) { final Promise> result = new Promise<>(); Promise> t = waitAll(new Promise[]{tA, tB, tC, tD, tE}); - t.onRedeem(new F.Action>>() { - - @Override - public void invoke(Promise> completed) { - List values = completed.getOrNull(); - if(values != null) { - result.invoke(new F.T5((A) values.get(0), (B) values.get(1), (C) values.get(2), (D) values.get(3), (E) values.get(4))); - } - else { - result.invokeWithException(completed.exception); - } + t.onRedeem(completed -> { + List values = completed.getOrNull(); + if(values != null) { + result.invoke(new T5((A) values.get(0), (B) values.get(1), (C) values.get(2), (D) values.get(3), (E) values.get(4))); + } + else { + result.invokeWithException(completed.exception); } }); return result; @@ -296,13 +276,7 @@ private static Promise>> waitEitherInternal(Pro final Promise>> result = new Promise<>(); for (int i = 0; i < futures.length; i++) { final int index = i + 1; - ((Promise) futures[i]).onRedeem(new F.Action>() { - - @Override - public void invoke(Promise completed) { - result.invoke(new F.Tuple(index, completed)); - } - }); + futures[i].onRedeem(completed -> result.invoke(new Tuple(index, completed))); } return result; } @@ -311,20 +285,15 @@ public static Promise> waitEither(Promise tA, Promise> result = new Promise<>(); Promise>> t = waitEitherInternal(tA, tB); - t.onRedeem(new F.Action>>>() { - - @Override - public void invoke(Promise>> completed) { - F.Tuple> value = completed.getOrNull(); - switch (value._1) { - case 1: - result.invoke(F.Either._1((A) value._2.getOrNull())); - break; - case 2: - result.invoke(F.Either._2((B) value._2.getOrNull())); - break; - } - + t.onRedeem(completed -> { + Tuple> value = completed.getOrNull(); + switch (value._1) { + case 1: + result.invoke(Either._1((A) value._2.getOrNull())); + break; + case 2: + result.invoke(Either._2((B) value._2.getOrNull())); + break; } }); @@ -335,23 +304,18 @@ public static Promise> waitEither(Promise tA, Promise final Promise> result = new Promise<>(); Promise>> t = waitEitherInternal(tA, tB, tC); - t.onRedeem(new F.Action>>>() { - - @Override - public void invoke(Promise>> completed) { - F.Tuple> value = completed.getOrNull(); - switch (value._1) { - case 1: - result.invoke(F.E3._1((A) value._2.getOrNull())); - break; - case 2: - result.invoke(F.E3._2((B) value._2.getOrNull())); - break; - case 3: - result.invoke(F.E3._3((C) value._2.getOrNull())); - break; - } - + t.onRedeem(completed -> { + Tuple> value = completed.getOrNull(); + switch (value._1) { + case 1: + result.invoke(E3._1((A) value._2.getOrNull())); + break; + case 2: + result.invoke(E3._2((B) value._2.getOrNull())); + break; + case 3: + result.invoke(E3._3((C) value._2.getOrNull())); + break; } }); @@ -362,26 +326,21 @@ public static Promise> waitEither(Promise tA, P final Promise> result = new Promise<>(); Promise>> t = waitEitherInternal(tA, tB, tC, tD); - t.onRedeem(new F.Action>>>() { - - @Override - public void invoke(Promise>> completed) { - F.Tuple> value = completed.getOrNull(); - switch (value._1) { - case 1: - result.invoke(F.E4._1((A) value._2.getOrNull())); - break; - case 2: - result.invoke(F.E4._2((B) value._2.getOrNull())); - break; - case 3: - result.invoke(F.E4._3((C) value._2.getOrNull())); - break; - case 4: - result.invoke(F.E4._4((D) value._2.getOrNull())); - break; - } - + t.onRedeem(completed -> { + Tuple> value = completed.getOrNull(); + switch (value._1) { + case 1: + result.invoke(E4._1((A) value._2.getOrNull())); + break; + case 2: + result.invoke(E4._2((B) value._2.getOrNull())); + break; + case 3: + result.invoke(E4._3((C) value._2.getOrNull())); + break; + case 4: + result.invoke(E4._4((D) value._2.getOrNull())); + break; } }); @@ -392,30 +351,24 @@ public static Promise> waitEither(Promise final Promise> result = new Promise<>(); Promise>> t = waitEitherInternal(tA, tB, tC, tD, tE); - t.onRedeem(new F.Action>>>() { - - @Override - public void invoke(Promise>> completed) { - F.Tuple> value = completed.getOrNull(); - switch (value._1) { - case 1: - result.invoke(F.E5._1((A) value._2.getOrNull())); - break; - case 2: - result.invoke(F.E5._2((B) value._2.getOrNull())); - break; - case 3: - result.invoke(F.E5._3((C) value._2.getOrNull())); - break; - case 4: - result.invoke(F.E5._4((D) value._2.getOrNull())); - break; - case 5: - result.invoke(F.E5._5((E) value._2.getOrNull())); - break; - - } - + t.onRedeem(completed -> { + Tuple> value = completed.getOrNull(); + switch (value._1) { + case 1: + result.invoke(E5._1((A) value._2.getOrNull())); + break; + case 2: + result.invoke(E5._2((B) value._2.getOrNull())); + break; + case 3: + result.invoke(E5._3((C) value._2.getOrNull())); + break; + case 4: + result.invoke(E5._4((D) value._2.getOrNull())); + break; + case 5: + result.invoke(E5._5((E) value._2.getOrNull())); + break; } }); diff --git a/framework/src/play/libs/Mail.java b/framework/src/play/libs/Mail.java index 4f46cfcb2b..146083621e 100644 --- a/framework/src/play/libs/Mail.java +++ b/framework/src/play/libs/Mail.java @@ -3,7 +3,6 @@ import java.util.Date; import java.util.Map; import java.util.Properties; -import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; @@ -194,19 +193,15 @@ public static Session getSession() { */ public static Future sendMessage(final Email msg) { if (asynchronousSend) { - return executor.submit(new Callable() { - - @Override - public Boolean call() { - try { - msg.setSentDate(new Date()); - msg.send(); - return true; - } catch (Throwable e) { - MailException me = new MailException("Error while sending email", e); - Logger.error(me, "The email has not been sent"); - return false; - } + return executor.submit(() -> { + try { + msg.setSentDate(new Date()); + msg.send(); + return true; + } catch (Throwable e) { + MailException me = new MailException("Error while sending email", e); + Logger.error(me, "The email has not been sent"); + return false; } }); } else { diff --git a/framework/src/play/libs/MimeTypes.java b/framework/src/play/libs/MimeTypes.java index 3670356c45..1ebcab8fd9 100644 --- a/framework/src/play/libs/MimeTypes.java +++ b/framework/src/play/libs/MimeTypes.java @@ -103,7 +103,7 @@ public static String getContentType(String filename, String defaultContentType) public static boolean isValidMimeType(String mimeType) { if (mimeType == null) { return false; - } else if (mimeType.indexOf(";") != -1) { + } else if (mimeType.contains(";")) { return mimetypes().contains(mimeType.split(";")[0]); } else { return mimetypes().contains(mimeType); diff --git a/framework/src/play/libs/OpenID.java b/framework/src/play/libs/OpenID.java index 8e1c612318..358172aebb 100644 --- a/framework/src/play/libs/OpenID.java +++ b/framework/src/play/libs/OpenID.java @@ -3,6 +3,7 @@ import java.io.StringReader; import java.net.URI; import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -134,35 +135,35 @@ public boolean verify() { url += "&"; } - url += "openid.ns=" + URLEncoder.encode("http://specs.openid.net/auth/2.0", "UTF-8"); + url += "openid.ns=" + URLEncoder.encode("http://specs.openid.net/auth/2.0", StandardCharsets.UTF_8); url += "&openid.mode=checkid_setup"; - url += "&openid.claimed_id=" + URLEncoder.encode(claimedId, "utf8"); - url += "&openid.identity=" + URLEncoder.encode(delegate == null ? claimedId : delegate, "utf8"); + url += "&openid.claimed_id=" + URLEncoder.encode(claimedId, StandardCharsets.UTF_8); + url += "&openid.identity=" + URLEncoder.encode(delegate == null ? claimedId : delegate, StandardCharsets.UTF_8); if (returnAction != null && (returnAction.startsWith("http://") || returnAction.startsWith("https://"))) { - url += "&openid.return_to=" + URLEncoder.encode(returnAction, "utf8"); + url += "&openid.return_to=" + URLEncoder.encode(returnAction, StandardCharsets.UTF_8); } else { - url += "&openid.return_to=" + URLEncoder.encode(Request.current().getBase() + Router.reverse(returnAction), "utf8"); + url += "&openid.return_to=" + URLEncoder.encode(Request.current().getBase() + Router.reverse(returnAction), StandardCharsets.UTF_8); } if (realmAction != null && (realmAction.startsWith("http://") || realmAction.startsWith("https://"))) { - url += "&openid.realm=" + URLEncoder.encode(realmAction, "utf8"); + url += "&openid.realm=" + URLEncoder.encode(realmAction, StandardCharsets.UTF_8); } else { - url += "&openid.realm=" + URLEncoder.encode(Request.current().getBase() + Router.reverse(realmAction), "utf8"); + url += "&openid.realm=" + URLEncoder.encode(Request.current().getBase() + Router.reverse(realmAction), StandardCharsets.UTF_8); } if (!sregOptional.isEmpty() || !sregRequired.isEmpty()) { - url += "&openid.ns.sreg=" + URLEncoder.encode("http://openid.net/extensions/sreg/1.1", "UTF-8"); + url += "&openid.ns.sreg=" + URLEncoder.encode("http://openid.net/extensions/sreg/1.1", StandardCharsets.UTF_8); } String sregO = ""; for (String a : sregOptional) { - sregO += URLEncoder.encode(a, "UTF-8") + ","; + sregO += URLEncoder.encode(a, StandardCharsets.UTF_8) + ","; } if (!StringUtils.isEmpty(sregO)) { url += "&openid.sreg.optional=" + sregO.substring(0, sregO.length() - 1); } String sregR = ""; for (String a : sregRequired) { - sregR += URLEncoder.encode(a, "UTF-8") + ","; + sregR += URLEncoder.encode(a, StandardCharsets.UTF_8) + ","; } if (!StringUtils.isEmpty(sregR)) { url += "&openid.sreg.required=" + sregR.substring(0, sregR.length() - 1); @@ -172,10 +173,10 @@ public boolean verify() { url += "&openid.ns.ax=http%3A%2F%2Fopenid.net%2Fsrv%2Fax%2F1.0"; url += "&openid.ax.mode=fetch_request"; for (String a : axOptional.keySet()) { - url += "&openid.ax.type." + a + "=" + URLEncoder.encode(axOptional.get(a), "UTF-8"); + url += "&openid.ax.type." + a + "=" + URLEncoder.encode(axOptional.get(a), StandardCharsets.UTF_8); } for (String a : axRequired.keySet()) { - url += "&openid.ax.type." + a + "=" + URLEncoder.encode(axRequired.get(a), "UTF-8"); + url += "&openid.ax.type." + a + "=" + URLEncoder.encode(axRequired.get(a), StandardCharsets.UTF_8); } if (!axRequired.isEmpty()) { String r = ""; diff --git a/framework/src/play/libs/URLs.java b/framework/src/play/libs/URLs.java index 969c93e954..cd421c9b6f 100644 --- a/framework/src/play/libs/URLs.java +++ b/framework/src/play/libs/URLs.java @@ -1,6 +1,8 @@ package play.libs; import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; + import play.exceptions.UnexpectedException; public class URLs { @@ -11,7 +13,7 @@ public static String addParam(String originalUrl, String name, String value) { public static String encodePart(String part) { try { - return URLEncoder.encode(part, "utf-8"); + return URLEncoder.encode(part, StandardCharsets.UTF_8); } catch (Exception e) { throw new UnexpectedException(e); } diff --git a/framework/src/play/libs/WS.java b/framework/src/play/libs/WS.java index 1ddb4ea1a6..3a47e49f1c 100644 --- a/framework/src/play/libs/WS.java +++ b/framework/src/play/libs/WS.java @@ -823,7 +823,7 @@ public Map getQueryString() { Map result = new HashMap<>(); String body = getString(); for (String entry : body.split("&")) { - int pos = entry.indexOf("="); + int pos = entry.indexOf('='); if (pos > -1) { result.put(entry.substring(0, pos), entry.substring(pos + 1)); } else { diff --git a/framework/src/play/libs/ws/WSUrlFetch.java b/framework/src/play/libs/ws/WSUrlFetch.java index dc54c7eb4a..9403a8956b 100644 --- a/framework/src/play/libs/ws/WSUrlFetch.java +++ b/framework/src/play/libs/ws/WSUrlFetch.java @@ -63,7 +63,7 @@ private String getPreparedUrl(String method) { if (!("PUT".equals(method) || "POST".equals(method))) { // must add params to queryString/url StringBuilder sb = new StringBuilder(url); - if (url.indexOf("?") > 0) { + if (url.indexOf('?') > 0) { sb.append('&'); } else { sb.append('?'); diff --git a/framework/src/play/mvc/ActionInvoker.java b/framework/src/play/mvc/ActionInvoker.java index 56cc851e96..a69dc463fe 100644 --- a/framework/src/play/mvc/ActionInvoker.java +++ b/framework/src/play/mvc/ActionInvoker.java @@ -581,8 +581,8 @@ public static Object[] getActionMethod(String fullAction) { if (!fullAction.startsWith("controllers.")) { fullAction = "controllers." + fullAction; } - String controller = fullAction.substring(0, fullAction.lastIndexOf(".")); - String action = fullAction.substring(fullAction.lastIndexOf(".") + 1); + String controller = fullAction.substring(0, fullAction.lastIndexOf('.')); + String action = fullAction.substring(fullAction.lastIndexOf('.') + 1); controllerClass = Play.classloader.getClassIgnoreCase(controller); if (controllerClass == null) { throw new ActionNotFoundException(fullAction, new Exception("Controller " + controller + " not found")); diff --git a/framework/src/play/mvc/CookieDataCodec.java b/framework/src/play/mvc/CookieDataCodec.java index d1a4a7ab67..eb220728e7 100644 --- a/framework/src/play/mvc/CookieDataCodec.java +++ b/framework/src/play/mvc/CookieDataCodec.java @@ -3,6 +3,7 @@ import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -33,7 +34,7 @@ public static void decode(Map map, String data) throws Unsupport // support old Play 1.2.5 session data encoding so that the cookie data doesn't become invalid when // applications are upgraded to a newer version of Play if (data.startsWith("%00") && data.contains("%3A") && data.endsWith("%00")) { - String sessionData = URLDecoder.decode(data, "utf-8"); + String sessionData = URLDecoder.decode(data, StandardCharsets.UTF_8); Matcher matcher = oldCookieSessionParser.matcher(sessionData); while (matcher.find()) { map.put(matcher.group(1), matcher.group(2)); @@ -45,7 +46,7 @@ public static void decode(Map map, String data) throws Unsupport for (String keyValue : keyValues) { String[] split = keyValue.split("=", 2); if (split.length == 2) { - map.put(URLDecoder.decode(split[0], "utf-8"), URLDecoder.decode(split[1], "utf-8")); + map.put(URLDecoder.decode(split[0], StandardCharsets.UTF_8), URLDecoder.decode(split[1], StandardCharsets.UTF_8)); } } } @@ -62,8 +63,8 @@ public static String encode(Map map) throws UnsupportedEncodingE String separator = ""; for (Map.Entry entry : map.entrySet()) { if (entry.getValue() != null) { - data.append(separator).append(URLEncoder.encode(entry.getKey(), "utf-8")).append("=") - .append(URLEncoder.encode(entry.getValue(), "utf-8")); + data.append(separator).append(URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8)).append("=") + .append(URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8)); separator = "&"; } } diff --git a/framework/src/play/mvc/CookieSessionStore.java b/framework/src/play/mvc/CookieSessionStore.java index fc302984d6..30f41f6582 100644 --- a/framework/src/play/mvc/CookieSessionStore.java +++ b/framework/src/play/mvc/CookieSessionStore.java @@ -23,7 +23,7 @@ public Session restore() { if (cookie != null && Play.started && cookie.value != null && !cookie.value.trim().equals("")) { String value = cookie.value; - int firstDashIndex = value.indexOf("-"); + int firstDashIndex = value.indexOf('-'); if (firstDashIndex > -1) { String sign = value.substring(0, firstDashIndex); String data = value.substring(firstDashIndex + 1); diff --git a/framework/src/play/mvc/Http.java b/framework/src/play/mvc/Http.java index f5a15e4df1..a1a02f0c25 100644 --- a/framework/src/play/mvc/Http.java +++ b/framework/src/play/mvc/Http.java @@ -5,11 +5,9 @@ import java.io.InputStream; import java.io.Serializable; import java.lang.reflect.Method; -import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; -import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.List; @@ -464,7 +462,7 @@ protected void authorizationInit() { String decoded = new String(Codec.decodeBASE64(data)); // splitting on ONLY first : allows user's password to contain a // : - int indexOf = decoded.indexOf(":"); + int indexOf = decoded.indexOf(':'); if (indexOf < 0) return; @@ -578,22 +576,18 @@ public List acceptLanguage() { } String acceptLanguage = headers.get("accept-language").value(); List languages = Arrays.asList(acceptLanguage.split(",")); - Collections.sort(languages, new Comparator() { - - @Override - public int compare(String lang1, String lang2) { - double q1 = 1.0; - double q2 = 1.0; - Matcher m1 = qpattern.matcher(lang1); - Matcher m2 = qpattern.matcher(lang2); - if (m1.find()) { - q1 = Double.parseDouble(m1.group(1)); - } - if (m2.find()) { - q2 = Double.parseDouble(m2.group(1)); - } - return (int) (q2 - q1); + Collections.sort(languages, (lang1, lang2) -> { + double q1 = 1.0; + double q2 = 1.0; + Matcher m1 = qpattern.matcher(lang1); + Matcher m2 = qpattern.matcher(lang2); + if (m1.find()) { + q1 = Double.parseDouble(m1.group(1)); + } + if (m2.find()) { + q2 = Double.parseDouble(m2.group(1)); } + return (int) (q2 - q1); }); List result = new ArrayList<>(10); for (String lang : languages) { diff --git a/framework/src/play/mvc/Mailer.java b/framework/src/play/mvc/Mailer.java index eacfdfd208..4b705021a3 100644 --- a/framework/src/play/mvc/Mailer.java +++ b/framework/src/play/mvc/Mailer.java @@ -68,7 +68,6 @@ public static void setSubject(String subject, Object... args) { infos.set(map); } - @SuppressWarnings("unchecked") public static void addRecipient(String... recipients) { List recipientsParam = Arrays.asList(recipients); addRecipients(recipientsParam); @@ -428,7 +427,7 @@ public static Future send(Object... args) { if (templateName.startsWith("controllers.")) { templateName = templateName.substring("controllers.".length()); } - templateName = templateName.substring(0, templateName.indexOf("(")); + templateName = templateName.substring(0, templateName.indexOf('(')); templateName = templateName.replace('.', '/'); // overrides Template name diff --git a/framework/src/play/mvc/Router.java b/framework/src/play/mvc/Router.java index 0f1c5539aa..dea0a61e8c 100644 --- a/framework/src/play/mvc/Router.java +++ b/framework/src/play/mvc/Router.java @@ -289,8 +289,8 @@ static void parse(String content, String prefix, String fileAbsolutePath) { newPrefix = newPrefix.substring(0, newPrefix.length() - 1); } if (moduleName.equals("*")) { - for (String p : Play.modulesRoutes.keySet()) { - parse(Play.modulesRoutes.get(p), newPrefix + p); + for (Map.Entry routeEntry : Play.modulesRoutes.entrySet()) { + parse(routeEntry.getValue(), newPrefix + routeEntry.getKey()); } } else if (Play.modulesRoutes.containsKey(moduleName)) { parse(Play.modulesRoutes.get(moduleName), newPrefix); @@ -379,7 +379,7 @@ public static Route route(Http.Request request) { if (args.containsKey("format")) { request.format = args.get("format"); } - if (request.action.indexOf("{") > -1) { // more optimization ? + if (request.action.indexOf('{') > -1) { // more optimization ? for (String arg : request.routeArgs.keySet()) { request.action = request.action.replace("{" + arg + "}", request.routeArgs.get(arg)); } @@ -469,7 +469,7 @@ public static String reverse(VirtualFile file, boolean absolute) { throw new NoRouteFoundException("File not found (" + file + ")"); } String path = file.relativePath(); - path = path.substring(path.indexOf("}") + 1); + path = path.substring(path.indexOf('}') + 1); for (Route route : routes) { String staticDir = route.staticDir; if (staticDir != null) { @@ -839,8 +839,9 @@ public void compute() { // Is there is a host argument, append it. if (!path.startsWith("/")) { String p = this.path; - this.path = p.substring(p.indexOf("/")); - this.host = p.substring(0, p.indexOf("/")); + int slashIndex = p.indexOf('/'); + this.path = p.substring(slashIndex); + this.host = p.substring(0, slashIndex); if (this.host.contains("{")) { Logger.warn("Static route cannot have a dynamic host name"); return; @@ -869,8 +870,9 @@ public void compute() { // Is there is a host argument, append it. if (!path.startsWith("/")) { String p = this.path; - this.path = p.substring(p.indexOf("/")); - this.host = p.substring(0, p.indexOf("/")); + int slashIndex = p.indexOf('/'); + this.path = p.substring(slashIndex); + this.host = p.substring(0, slashIndex); String pattern = host.replaceAll("\\.", "\\\\.").replaceAll("\\{.*\\}", "(.*)"); if (Logger.isTraceEnabled()) { diff --git a/framework/src/play/plugins/PluginCollection.java b/framework/src/play/plugins/PluginCollection.java index 4b74c4a013..1cefe15153 100644 --- a/framework/src/play/plugins/PluginCollection.java +++ b/framework/src/play/plugins/PluginCollection.java @@ -5,11 +5,11 @@ import java.io.IOException; import java.io.InputStreamReader; import java.lang.annotation.Annotation; -import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.net.MalformedURLException; import java.net.URL; +import java.nio.charset.StandardCharsets; import java.util.*; import java.util.stream.Stream; @@ -152,7 +152,7 @@ public void loadPlugins() { SortedSet pluginsToLoad = new TreeSet<>(); for (URL url : urls) { Logger.trace("Found one plugins descriptor, %s", url); - try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8"))) { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8))) { String line; while ((line = reader.readLine()) != null) { if (line.trim().length() == 0) { diff --git a/framework/src/play/server/FileService.java b/framework/src/play/server/FileService.java index 9ece656da0..1213e9ebb1 100644 --- a/framework/src/play/server/FileService.java +++ b/framework/src/play/server/FileService.java @@ -202,8 +202,7 @@ private void initRanges() { String headerValue = request.headers().get("range").trim().substring("bytes=".length()); String[] rangesValues = headerValue.split(","); ArrayList ranges = new ArrayList<>(rangesValues.length); - for(int i = 0; i < rangesValues.length; i++) { - String rangeValue = rangesValues[i]; + for (String rangeValue : rangesValues) { long start, end; if(rangeValue.startsWith("-")) { end = fileLength - 1; @@ -251,12 +250,7 @@ private static long[][] reduceRanges(long[]... chunks) { if (chunks.length == 0) return new long[0][]; long[][] sortedChunks = Arrays.copyOf(chunks, chunks.length); - Arrays.sort(sortedChunks, new Comparator() { - @Override - public int compare(long[] t1, long[] t2) { - return new Long(t1[0]).compareTo(t2[0]); - } - }); + Arrays.sort(sortedChunks, Comparator.comparingLong(t -> t[0])); ArrayList result = new ArrayList<>(); result.add(sortedChunks[0]); for (int i = 1; i < sortedChunks.length; i++) { diff --git a/framework/src/play/server/HttpServerPipelineFactory.java b/framework/src/play/server/HttpServerPipelineFactory.java index 2e4244679e..4dac6212cb 100644 --- a/framework/src/play/server/HttpServerPipelineFactory.java +++ b/framework/src/play/server/HttpServerPipelineFactory.java @@ -60,8 +60,9 @@ public ChannelPipeline getPipeline() throws Exception { } protected String getName(String name) { - if (name.lastIndexOf(".") > 0) - return name.substring(name.lastIndexOf(".") + 1); + int dotIndex = name.lastIndexOf('.'); + if (dotIndex > 0) + return name.substring(dotIndex + 1); return name; } diff --git a/framework/src/play/server/PlayHandler.java b/framework/src/play/server/PlayHandler.java index 782925284d..c2474e19d8 100644 --- a/framework/src/play/server/PlayHandler.java +++ b/framework/src/play/server/PlayHandler.java @@ -24,7 +24,6 @@ import play.exceptions.PlayException; import play.exceptions.UnexpectedException; import play.i18n.Messages; -import play.libs.F.Action; import play.libs.F.Promise; import play.libs.MimeTypes; import play.mvc.*; @@ -42,10 +41,10 @@ import java.net.InetSocketAddress; import java.net.URLEncoder; import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; -import java.text.ParseException; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; @@ -138,13 +137,7 @@ public void messageReceived(final ChannelHandlerContext ctx, MessageEvent messag response.direct = null; // Streamed output (using response.writeChunk) - response.onWriteChunk(new Action() { - - @Override - public void invoke(Object result) { - writeChunk(request, response, ctx, nettyRequest, result); - } - }); + response.onWriteChunk(result -> writeChunk(request, response, ctx, nettyRequest, result)); // Raw invocation boolean raw = Play.pluginCollection.rawInvocation(request, response); @@ -337,7 +330,7 @@ void saveExceededSizeError(HttpRequest nettyRequest, Request request, Response r && request.cookies.get(Scope.COOKIE_PREFIX + "_ERRORS").value != null) { error.append(request.cookies.get(Scope.COOKIE_PREFIX + "_ERRORS").value); } - String errorData = URLEncoder.encode(error.toString(), "utf-8"); + String errorData = URLEncoder.encode(error.toString(), StandardCharsets.UTF_8); Http.Cookie c = new Http.Cookie(); c.value = errorData; c.name = Scope.COOKIE_PREFIX + "_ERRORS"; @@ -523,9 +516,9 @@ static String getRemoteIPAddress(MessageEvent e) { String fullAddress = ((InetSocketAddress) e.getRemoteAddress()).getAddress().getHostAddress(); if (fullAddress.matches("/[0-9]+[.][0-9]+[.][0-9]+[.][0-9]+[:][0-9]+")) { fullAddress = fullAddress.substring(1); - fullAddress = fullAddress.substring(0, fullAddress.indexOf(":")); + fullAddress = fullAddress.substring(0, fullAddress.indexOf(':')); } else if (fullAddress.matches(".*[%].*")) { - fullAddress = fullAddress.substring(0, fullAddress.indexOf("%")); + fullAddress = fullAddress.substring(0, fullAddress.indexOf('%')); } return fullAddress; } @@ -561,7 +554,7 @@ public Request parseRequest(ChannelHandlerContext ctx, HttpRequest nettyRequest, } } - int i = uri.indexOf("?"); + int i = uri.indexOf('?'); String querystring = ""; String path = uri; if (i != -1) { @@ -1142,13 +1135,9 @@ public boolean isOpen() { synchronized void writeAndClose(ChannelFuture writeFuture) { if (!writeFuture.isDone()) { writeFutures.add(writeFuture); - writeFuture.addListener(new ChannelFutureListener() { - - @Override - public void operationComplete(ChannelFuture cf) throws Exception { - writeFutures.remove(cf); - futureClose(); - } + writeFuture.addListener(cf -> { + writeFutures.remove(cf); + futureClose(); }); } } @@ -1184,14 +1173,10 @@ public synchronized boolean isOpen() { @Override public synchronized void close() { closeTask = new Promise<>(); - closeTask.onRedeem(new Action>() { - - @Override - public void invoke(Promise completed) { - writeFutures.clear(); - ctx.getChannel().disconnect(); - closeTask = null; - } + closeTask.onRedeem(completed -> { + writeFutures.clear(); + ctx.getChannel().disconnect(); + closeTask = null; }); futureClose(); } diff --git a/framework/src/play/server/ssl/SslHttpServerContextFactory.java b/framework/src/play/server/ssl/SslHttpServerContextFactory.java index 644ea9fc74..b4da404886 100644 --- a/framework/src/play/server/ssl/SslHttpServerContextFactory.java +++ b/framework/src/play/server/ssl/SslHttpServerContextFactory.java @@ -7,7 +7,6 @@ import org.bouncycastle.openssl.PEMEncryptedKeyPair; import org.bouncycastle.openssl.PEMKeyPair; import org.bouncycastle.openssl.PEMParser; -import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; import org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder; import play.Logger; import play.Play; diff --git a/framework/src/play/templates/FastTags.java b/framework/src/play/templates/FastTags.java index cf1aa0cc91..ebc5448302 100644 --- a/framework/src/play/templates/FastTags.java +++ b/framework/src/play/templates/FastTags.java @@ -199,7 +199,7 @@ public static void _field(Map args, Closure body, PrintWriter out, Executa if (obj != null) { if (pieces.length > 1) { try { - String path = _arg.substring(_arg.indexOf(".") + 1); + String path = _arg.substring(_arg.indexOf('.') + 1); Object value = PropertyUtils.getProperty(obj, path); field.put("value", value); } catch (Exception e) { @@ -386,9 +386,9 @@ public static void _extends(Map args, Closure body, PrintWriter out, Execu if (name.startsWith("./")) { String ct = BaseTemplate.currentTemplate.get().name; if (ct.matches("^/lib/[^/]+/app/views/.*")) { - ct = ct.substring(ct.indexOf("/", 5)); + ct = ct.substring(ct.indexOf('/', 5)); } - ct = ct.substring(0, ct.lastIndexOf("/")); + ct = ct.substring(0, ct.lastIndexOf('/')); name = ct + name.substring(1); } BaseTemplate.layout.set((BaseTemplate) TemplateLoader.load(name)); @@ -408,9 +408,9 @@ public static void _include(Map args, Closure body, PrintWriter out, Execu if (name.startsWith("./")) { String ct = BaseTemplate.currentTemplate.get().name; if (ct.matches("^/lib/[^/]+/app/views/.*")) { - ct = ct.substring(ct.indexOf("/", 5)); + ct = ct.substring(ct.indexOf('/', 5)); } - ct = ct.substring(0, ct.lastIndexOf("/")); + ct = ct.substring(0, ct.lastIndexOf('/')); name = ct + name.substring(1); } BaseTemplate t = (BaseTemplate) TemplateLoader.load(name); @@ -434,9 +434,9 @@ public static void _render(Map args, Closure body, PrintWriter out, Execut if (name.startsWith("./")) { String ct = BaseTemplate.currentTemplate.get().name; if (ct.matches("^/lib/[^/]+/app/views/.*")) { - ct = ct.substring(ct.indexOf("/", 5)); + ct = ct.substring(ct.indexOf('/', 5)); } - ct = ct.substring(0, ct.lastIndexOf("/")); + ct = ct.substring(0, ct.lastIndexOf('/')); name = ct + name.substring(1); } args.remove("arg"); diff --git a/framework/src/play/templates/GroovyTemplate.java b/framework/src/play/templates/GroovyTemplate.java index 77946191fa..970939a9bb 100644 --- a/framework/src/play/templates/GroovyTemplate.java +++ b/framework/src/play/templates/GroovyTemplate.java @@ -106,7 +106,7 @@ public Class defineTemplate(String name, byte[] byteCode) { @Override void directLoad(byte[] code) throws Exception { try (TClassLoader tClassLoader = new TClassLoader()) { - String[] lines = new String(code, "utf-8").split("\n"); + String[] lines = new String(code, UTF_8).split("\n"); this.linesMatrix = (HashMap) Java.deserialize(Codec.decodeBASE64(lines[1])); this.doBodyLines = (HashSet) Java.deserialize(Codec.decodeBASE64(lines[3])); for (int i = 4; i < lines.length; i = i + 2) { @@ -211,8 +211,8 @@ public void call(GroovyClass gclass) { line = 0; } String message = syntaxException.getMessage(); - if (message.indexOf("@") > 0) { - message = message.substring(0, message.lastIndexOf("@")); + if (message.indexOf('@') > 0) { + message = message.substring(0, message.lastIndexOf('@')); } throw new TemplateCompilationException(this, line, message); } else { @@ -352,17 +352,19 @@ protected Throwable cleanStackTrace(Throwable e) { // See GroovyTemplateCompiler.head() for more info. if (se.getClassName().startsWith("Template_")) { String tn = se.getClassName().substring(9); - if (tn.indexOf("$") > -1) { - tn = tn.substring(0, tn.indexOf("$")); + int charIndex = tn.indexOf('$'); + if (charIndex > -1) { + tn = tn.substring(0, charIndex); } BaseTemplate template = TemplateLoader.templates.get(tn); if (template != null) { Integer line = template.linesMatrix.get(se.getLineNumber()); if (line != null) { String ext = ""; - if (tn.indexOf(".") > -1) { - ext = tn.substring(tn.indexOf(".") + 1); - tn = tn.substring(0, tn.indexOf(".")); + charIndex = tn.indexOf('.'); + if (charIndex > -1) { + ext = tn.substring(charIndex + 1); + tn = tn.substring(0, charIndex); } StackTraceElement nse = new StackTraceElement(TemplateLoader.templates.get(tn).name, ext, "line", line); cleanTrace.add(nse); @@ -390,7 +392,7 @@ public abstract static class ExecutableTemplate extends Script { public void init(GroovyTemplate t) { template = t; - int index = template.name.lastIndexOf("."); + int index = template.name.lastIndexOf('.'); if (index > 0) { extension = template.name.substring(index + 1); } diff --git a/framework/src/play/templates/GroovyTemplateCompiler.java b/framework/src/play/templates/GroovyTemplateCompiler.java index d1bbf35466..41e9234beb 100644 --- a/framework/src/play/templates/GroovyTemplateCompiler.java +++ b/framework/src/play/templates/GroovyTemplateCompiler.java @@ -4,7 +4,6 @@ import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; -import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -80,12 +79,7 @@ protected String checkScalaCompatibility(String source) { originalNames.put(name, clazz.getName()); } } - Collections.sort(names, new Comparator() { - @Override - public int compare(String o1, String o2) { - return o2.length() - o1.length(); - } - }); + Collections.sort(names, (o1, o2) -> o2.length() - o1.length()); // We're about to do many many String.replaceAll() so we do some // checking first @@ -269,9 +263,10 @@ protected void startTag() { String tagName; String tagArgs; boolean hasBody = !parser.checkNext().endsWith("/"); - if (tagText.indexOf(" ") > 0) { - tagName = tagText.substring(0, tagText.indexOf(" ")); - tagArgs = tagText.substring(tagText.indexOf(" ") + 1).trim(); + int spaceIndex = tagText.indexOf(' '); + if (spaceIndex > 0) { + tagName = tagText.substring(0, spaceIndex); + tagArgs = tagText.substring(spaceIndex + 1).trim(); if (!tagArgs.matches("^[_a-zA-Z0-9]+\\s*:.*$")) { tagArgs = "arg:" + tagArgs; } @@ -368,9 +363,10 @@ protected void endTag() { Method m = null; String tName = tag.name; String tSpace = ""; - if (tName.indexOf(".") > 0) { - tSpace = tName.substring(0, tName.lastIndexOf(".")); - tName = tName.substring(tName.lastIndexOf(".") + 1); + if (tName.indexOf('.') > 0) { + int dotIndex = tName.lastIndexOf('.'); + tSpace = tName.substring(0, dotIndex); + tName = tName.substring(dotIndex + 1); } for (Class c : fastClasses) { if (!c.isAnnotationPresent(FastTags.Namespace.class) && tSpace.length() > 0) { diff --git a/framework/src/play/templates/TemplateParser.java b/framework/src/play/templates/TemplateParser.java index dcaa597b05..f5cf13298f 100644 --- a/framework/src/play/templates/TemplateParser.java +++ b/framework/src/play/templates/TemplateParser.java @@ -41,7 +41,7 @@ private Token found(Token newState, int skip) { public Integer getLine() { String token = pageSource.substring(0, begin2); - if (token.indexOf("\n") == -1) { + if (token.indexOf('\n') == -1) { return 1; } else { return token.split("\n").length; diff --git a/framework/src/play/test/FunctionalTest.java b/framework/src/play/test/FunctionalTest.java index 9f4fc0e5bf..330d5ff08e 100644 --- a/framework/src/play/test/FunctionalTest.java +++ b/framework/src/play/test/FunctionalTest.java @@ -11,7 +11,6 @@ import play.Invoker; import play.Invoker.InvocationContext; import play.classloading.enhancers.ControllersEnhancer.ControllerInstrumentation; -import play.libs.F.Action; import play.exceptions.JavaExecutionException; import play.exceptions.UnexpectedException; import play.mvc.ActionInvoker; @@ -108,9 +107,10 @@ public static Response GET(Request request, Object url) { String path; String queryString = ""; String turl = url.toString(); - if (turl.contains("?")) { - path = turl.substring(0, turl.indexOf("?")); - queryString = turl.substring(turl.indexOf("?") + 1); + int questionIndex = turl.indexOf('?'); + if (questionIndex >= 0) { + path = turl.substring(0, questionIndex); + queryString = turl.substring(questionIndex + 1); } else { path = turl; } @@ -162,9 +162,10 @@ public static Response POST(Request request, Object url, String contenttype, Inp String path; String queryString = ""; String turl = url.toString(); - if (turl.contains("?")) { - path = turl.substring(0, turl.indexOf("?")); - queryString = turl.substring(turl.indexOf("?") + 1); + int questionIndex = turl.indexOf('?'); + if (questionIndex >= 0) { + path = turl.substring(0, questionIndex); + queryString = turl.substring(questionIndex + 1); } else { path = turl; } @@ -261,9 +262,10 @@ public static Response PUT(Request request, Object url, String contenttype, Stri String path; String queryString = ""; String turl = url.toString(); - if (turl.contains("?")) { - path = turl.substring(0, turl.indexOf("?")); - queryString = turl.substring(turl.indexOf("?") + 1); + int questionIndex = turl.indexOf('?'); + if (questionIndex >= 0) { + path = turl.substring(0, questionIndex); + queryString = turl.substring(questionIndex + 1); } else { path = turl; } @@ -295,9 +297,10 @@ public static Response DELETE(Request request, Object url) { String path; String queryString = ""; String turl = url.toString(); - if (turl.contains("?")) { - path = turl.substring(0, turl.indexOf("?")); - queryString = turl.substring(turl.indexOf("?") + 1); + int questionIndex = turl.indexOf('?'); + if (questionIndex >= 0) { + path = turl.substring(0, questionIndex); + queryString = turl.substring(questionIndex + 1); } else { path = turl; } diff --git a/framework/src/play/test/TestEngine.java b/framework/src/play/test/TestEngine.java index 1996e444c0..2c0623ae62 100644 --- a/framework/src/play/test/TestEngine.java +++ b/framework/src/play/test/TestEngine.java @@ -209,7 +209,7 @@ public Listener(String className, TestResults results) { @Override public void testStarted(Description description) throws Exception { current = new TestResult(); - current.name = description.getDisplayName().substring(0, description.getDisplayName().indexOf("(")); + current.name = description.getDisplayName().substring(0, description.getDisplayName().indexOf('(')); current.time = System.currentTimeMillis(); } diff --git a/framework/src/play/utils/Java.java b/framework/src/play/utils/Java.java index d2b9457f6e..d718777d34 100644 --- a/framework/src/play/utils/Java.java +++ b/framework/src/play/utils/Java.java @@ -15,7 +15,6 @@ import java.lang.reflect.Modifier; import java.lang.reflect.Parameter; import java.util.ArrayList; -import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -544,17 +543,14 @@ public List findAllAnnotatedMethods(Class clazz, Class methods, final Class annotationType) { try { final Method priority = annotationType.getMethod("priority"); - sort(methods, new Comparator() { - @Override - public int compare(Method m1, Method m2) { - try { - Integer priority1 = (Integer) priority.invoke(m1.getAnnotation(annotationType)); - Integer priority2 = (Integer) priority.invoke(m2.getAnnotation(annotationType)); - return priority1.compareTo(priority2); - } catch (Exception e) { - // should not happen - throw new RuntimeException(e); - } + sort(methods, (m1, m2) -> { + try { + Integer priority1 = (Integer) priority.invoke(m1.getAnnotation(annotationType)); + Integer priority2 = (Integer) priority.invoke(m2.getAnnotation(annotationType)); + return priority1.compareTo(priority2); + } catch (Exception e) { + // should not happen + throw new RuntimeException(e); } }); } catch (NoSuchMethodException e) { diff --git a/framework/src/play/utils/OS.java b/framework/src/play/utils/OS.java index 9f60cdb6c3..a34a6e0b99 100644 --- a/framework/src/play/utils/OS.java +++ b/framework/src/play/utils/OS.java @@ -7,21 +7,21 @@ public class OS { public static boolean isWindows() { String os = System.getProperty("os.name").toLowerCase(); - return os != null && os.indexOf("win") >= 0; + return os.contains("win"); } public static boolean isMac() { String os = System.getProperty("os.name").toLowerCase(); - return os != null && (os.toLowerCase().indexOf("mac") >= 0); + return os.contains("mac"); } public static boolean isUnix() { String os = System.getProperty("os.name").toLowerCase(); - return os != null && (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0 || os.indexOf("aix") > 0); + return os.contains("nix") || os.contains("nux") || os.contains("aix"); } public static boolean isSolaris() { String os = System.getProperty("os.name").toLowerCase(); - return (os != null && os.indexOf("sunos") >= 0); + return os.contains("sunos"); } } diff --git a/framework/src/play/vfs/VirtualFile.java b/framework/src/play/vfs/VirtualFile.java index da3d12c63f..8cb4096287 100644 --- a/framework/src/play/vfs/VirtualFile.java +++ b/framework/src/play/vfs/VirtualFile.java @@ -81,7 +81,7 @@ String isRoot(File f) { for (VirtualFile vf : Play.roots) { if (vf.realFile.getAbsolutePath().equals(f.getAbsolutePath())) { String modulePathName = vf.getName(); - String moduleName = modulePathName.contains("-") ? modulePathName.substring(0, modulePathName.lastIndexOf("-")) + String moduleName = modulePathName.contains("-") ? modulePathName.substring(0, modulePathName.lastIndexOf('-')) : modulePathName; return "{module:" + moduleName + "}"; } diff --git a/framework/test-src/play/LoggerTest.java b/framework/test-src/play/LoggerTest.java index 4ab24bcf2d..e7f043e6af 100755 --- a/framework/test-src/play/LoggerTest.java +++ b/framework/test-src/play/LoggerTest.java @@ -5,7 +5,6 @@ import java.io.File; import java.net.MalformedURLException; -import java.net.URISyntaxException; import java.net.URL; import java.util.Properties; import org.apache.logging.log4j.Level; diff --git a/framework/test-src/play/libs/XMLTest.java b/framework/test-src/play/libs/XMLTest.java index ca4b5de42c..87776236f5 100644 --- a/framework/test-src/play/libs/XMLTest.java +++ b/framework/test-src/play/libs/XMLTest.java @@ -6,7 +6,6 @@ import org.w3c.dom.Node; import java.io.ByteArrayInputStream; -import java.io.File; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map;