Skip to content

Commit

Permalink
Cleanup code (#1389)
Browse files Browse the repository at this point in the history
* use lambdas instead of anonymous classes

* remove redundant null-checks and simplify check of the substrings

* use predefined charset constant instead of its string representation

* remove unused imports

* use predefined charset constant instead of its string representation

* replace methods that use single-character strings with equivalent ones that use char

* use classes instead of its name when check equality

* remove unnecessary boxig/unboxing

* replace usage of the deprecated method

* iterate by routes entries instead of get route at every iteration

* remove redundant variables

* replace classic for-loop by foreach-loop

* replace calling a few old api methods by the newone from java 8 api

* replace calling a few old api methods by the newone from java 8 api

* remove redundant suppression
  • Loading branch information
aleksandy authored Mar 8, 2022
1 parent ac25cc6 commit 8fad39b
Show file tree
Hide file tree
Showing 57 changed files with 422 additions and 610 deletions.
18 changes: 5 additions & 13 deletions framework/src/play/Invoker.java
Original file line number Diff line number Diff line change
Expand Up @@ -312,13 +312,10 @@ public void run() {
if (init()) {
before();
final AtomicBoolean executed = new AtomicBoolean(false);
this.withinFilter(new play.libs.F.Function0<Void>() {
@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()) {
Expand Down Expand Up @@ -427,12 +424,7 @@ public WaitForTasksCompletion() {
public static <V> void waitFor(Future<V> task, final Invocation invocation) {
if (task instanceof Promise) {
Promise<V> smartFuture = (Promise<V>) task;
smartFuture.onRedeem(new F.Action<F.Promise<V>>() {
@Override
public void invoke(Promise<V> result) {
executor.submit(invocation);
}
});
smartFuture.onRedeem(result -> executor.submit(invocation));
} else {
synchronized (WaitForTasksCompletion.class) {
if (instance == null) {
Expand Down
23 changes: 8 additions & 15 deletions framework/src/play/Play.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -684,7 +680,6 @@ public static synchronized void detectChanges() {
}
}

@SuppressWarnings("unchecked")
public static <T extends PlayPlugin> T plugin(Class<T> clazz) {
return pluginCollection.getPluginInstance(clazz);
}
Expand All @@ -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 {
Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -776,16 +771,14 @@ public static void loadModules(VirtualFile appRoot) {
modules.addAll(Arrays.asList(localModules.list()));
}

for (Iterator<String> 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()) {
Expand Down
19 changes: 2 additions & 17 deletions framework/src/play/PlayPlugin.java
Original file line number Diff line number Diff line change
Expand Up @@ -552,25 +552,10 @@ public T withinFilter(F.Function0<T> fct) throws Throwable {
private static <T> Function1<F.Function0<T>, T> compose(final Function1<F.Function0<T>, T> outer,
final Function1<F.Function0<T>, T> inner) {

return new Function1<F.Function0<T>, T>() {
@Override
public T apply(final F.Function0<T> arg) throws Throwable {
return outer.apply(new F.Function0<T>() {
@Override
public T apply() throws Throwable {
return inner.apply(arg);
}
});
}
};
return arg -> outer.apply(() -> inner.apply(arg));
}

private final Function1<play.libs.F.Function0<T>, T> _asFunction = new Function1<F.Function0<T>, T>() {
@Override
public T apply(F.Function0<T> arg) throws Throwable {
return withinFilter(arg);
}
};
private final Function1<play.libs.F.Function0<T>, T> _asFunction = this::withinFilter;

public Function1<play.libs.F.Function0<T>, T> asFunction() {
return _asFunction;
Expand Down
2 changes: 1 addition & 1 deletion framework/src/play/ant/PlayConfigurationLoadTask.java
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ private Set<File> 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()};
}
Expand Down
6 changes: 3 additions & 3 deletions framework/src/play/cache/EhCacheImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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
Expand All @@ -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);
Expand Down
13 changes: 5 additions & 8 deletions framework/src/play/classloading/ApplicationClasses.java
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
}

/**
Expand Down Expand Up @@ -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('.', '/');
Expand Down
30 changes: 10 additions & 20 deletions framework/src/play/classloading/ApplicationClassloader.java
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -446,13 +446,7 @@ public List<Class> getAllClasses() {
}
}

Collections.sort(result, new Comparator<Class>() {

@Override
public int compare(Class o1, Class o2) {
return o1.getName().compareTo(o2.getName());
}
});
Collections.sort(result, Comparator.comparing(Class::getName));
}

Map<String, ApplicationClass> byNormalizedName = new HashMap<>(result.size());
Expand Down Expand Up @@ -484,18 +478,14 @@ public List<Class> getAssignableClasses(Class clazz) {
return Collections.emptyList();
}
getAllClasses();
List<Class> 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<ApplicationClass> assignableClasses = Play.classes.getAssignableClasses(clazz);
List<Class<?>> 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
Expand Down
60 changes: 28 additions & 32 deletions framework/src/play/classloading/ApplicationCompiler.java
Original file line number Diff line number Diff line change
Expand Up @@ -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('.');
Expand Down Expand Up @@ -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());
}
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<T2<Integer,String>>() {
@Override
public int compare(T2<Integer, String> o1, T2<Integer, String> o2) {
return o1._1.compareTo(o2._1);
}

});
Collections.sort(parameterNames, Comparator.comparing(o -> o._1));
}
List<String> names = new ArrayList<>();
for (int i = 0; i < method.getParameterTypes().length + (Modifier.isStatic(method.getModifiers()) ? 0 : 1); i++) {
Expand All @@ -86,8 +80,9 @@ public int compare(T2<Integer, String> o1, T2<Integer, String> o2) {
for (Iterator<String> 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("\"");
Expand Down Expand Up @@ -122,8 +117,9 @@ public int compare(T2<Integer, String> o1, T2<Integer, String> 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);
}


Expand Down
Loading

0 comments on commit 8fad39b

Please sign in to comment.