From 913ec06b4f72a2f8a42ff2bad9f541721a3362d2 Mon Sep 17 00:00:00 2001 From: aleksandy Date: Tue, 12 Apr 2022 00:33:01 +0600 Subject: [PATCH 01/22] ThreadLocal#remove() instead of ThreadLocal#set(null) see details here https://doanduyhai.wordpress.com/2011/12/04/threadlocal-explained/ --- .../enhancers/LocalvariablesNamesEnhancer.java | 4 +--- .../src/play/classloading/enhancers/MailerEnhancer.java | 2 +- framework/src/play/jobs/JobsPlugin.java | 2 +- framework/src/play/server/PlayHandler.java | 8 ++++---- framework/src/play/templates/GroovyTemplate.java | 2 +- 5 files changed, 8 insertions(+), 10 deletions(-) diff --git a/framework/src/play/classloading/enhancers/LocalvariablesNamesEnhancer.java b/framework/src/play/classloading/enhancers/LocalvariablesNamesEnhancer.java index fc41da7ab1..fd69035410 100644 --- a/framework/src/play/classloading/enhancers/LocalvariablesNamesEnhancer.java +++ b/framework/src/play/classloading/enhancers/LocalvariablesNamesEnhancer.java @@ -181,9 +181,7 @@ public static void checkEmpty() { } public static void clear() { - if (localVariables.get() != null) { - localVariables.set(null); - } + localVariables.remove(); } public static void enter() { diff --git a/framework/src/play/classloading/enhancers/MailerEnhancer.java b/framework/src/play/classloading/enhancers/MailerEnhancer.java index 49a468cf9e..92d0fe5d9d 100644 --- a/framework/src/play/classloading/enhancers/MailerEnhancer.java +++ b/framework/src/play/classloading/enhancers/MailerEnhancer.java @@ -30,7 +30,7 @@ public void enhanceThisClass(ApplicationClass applicationClass) throws Exception if (Modifier.isPublic(ctMethod.getModifiers()) && Modifier.isStatic(ctMethod.getModifiers())) { try { ctMethod.insertBefore("if(infos.get() != null) {play.Logger.warn(\"You call " + ctMethod.getLongName() + " from \" + ((java.util.Map)infos.get()).get(\"method\") + \". It's forbidden in a Mailer. It will probably fail...\", new Object[0]);}; infos.set(new java.util.HashMap());((java.util.Map)infos.get()).put(\"method\", \"" + ctMethod.getLongName() + "\");"); - ctMethod.insertAfter("infos.set(null);", true); + ctMethod.insertAfter("infos.remove();", true); } catch (Exception e) { Logger.error(e, "Error in MailerEnhancer"); throw new UnexpectedException("Error in MailerEnhancer", e); diff --git a/framework/src/play/jobs/JobsPlugin.java b/framework/src/play/jobs/JobsPlugin.java index e47f8ca45c..93bfe33044 100644 --- a/framework/src/play/jobs/JobsPlugin.java +++ b/framework/src/play/jobs/JobsPlugin.java @@ -263,7 +263,7 @@ public void beforeInvocation() { @Override public void afterInvocation() { List> currentActions = afterInvocationActions.get(); - afterInvocationActions.set(null); + afterInvocationActions.remove(); for (Callable callable : currentActions) { executor.submit(callable); } diff --git a/framework/src/play/server/PlayHandler.java b/framework/src/play/server/PlayHandler.java index c2474e19d8..989b3c48d8 100644 --- a/framework/src/play/server/PlayHandler.java +++ b/framework/src/play/server/PlayHandler.java @@ -197,10 +197,10 @@ public boolean init() { Response.current.set(response); Scope.Params.current.set(request.params); - Scope.RenderArgs.current.set(null); - Scope.RouteArgs.current.set(null); - Scope.Session.current.set(null); - Scope.Flash.current.set(null); + Scope.RenderArgs.current.remove(); + Scope.RouteArgs.current.remove(); + Scope.Session.current.remove(); + Scope.Flash.current.remove(); CachedBoundActionMethodArgs.init(); try { diff --git a/framework/src/play/templates/GroovyTemplate.java b/framework/src/play/templates/GroovyTemplate.java index fb0a71cbf5..7600aa1d79 100644 --- a/framework/src/play/templates/GroovyTemplate.java +++ b/framework/src/play/templates/GroovyTemplate.java @@ -277,7 +277,7 @@ protected String internalRender(Map args) { // We have to set up the PrintWriter that this (and all sub-templates) are going // to write the output to.. applyLayouts = true; - layout.set(null); + layout.remove(); writer = new StringWriter(); binding.setProperty("out", new PrintWriter(writer)); currentTemplate.set(this); From 678d7e470420d47b9091790803d1841dff225af9 Mon Sep 17 00:00:00 2001 From: aleksandy Date: Tue, 12 Apr 2022 00:35:41 +0600 Subject: [PATCH 02/22] cleanup code --- framework/src/play/db/DB.java | 30 ++++++++++++----------------- framework/src/play/db/DBPlugin.java | 14 +++----------- 2 files changed, 15 insertions(+), 29 deletions(-) diff --git a/framework/src/play/db/DB.java b/framework/src/play/db/DB.java index c8bd3c05f1..c2620bcd72 100644 --- a/framework/src/play/db/DB.java +++ b/framework/src/play/db/DB.java @@ -85,10 +85,8 @@ public DataSource getDataSource() { static final ThreadLocal> localConnection = new ThreadLocal<>(); public static DataSource getDataSource(String name) { - if (datasources.get(name) != null) { - return datasources.get(name).getDataSource(); - } - return null; + ExtendedDatasource datasource = datasources.get(name); + return datasource == null ? null : datasource.getDataSource(); } public static DataSource getDataSource() { @@ -109,8 +107,7 @@ public static Connection getConnection(String name, boolean autocommit) { private static Connection getLocalConnection(String name) { Map map = localConnection.get(); if (map != null) { - Connection connection = map.get(name); - return connection; + return map.get(name); } return null; } @@ -119,9 +116,9 @@ private static void registerLocalConnection(String name, Connection connection) Map map = localConnection.get(); if (map == null) { map = new HashMap<>(); + localConnection.set(map); } map.put(name, connection); - localConnection.set(map); } /** @@ -145,7 +142,7 @@ public static void close() { } /** - * Close an given open connections for the current thread + * Close a given open connections for the current thread * * @param name * Name of the DB @@ -153,10 +150,8 @@ public static void close() { public static void close(String name) { Map map = localConnection.get(); if (map != null) { - Connection connection = map.get(name); + Connection connection = map.remove(name); if (connection != null) { - map.remove(name); - localConnection.set(map); try { connection.close(); } catch (Exception e) { @@ -176,7 +171,7 @@ public static void close(String name) { public static Connection getConnection(String name) { try { if (JPA.isEnabled()) { - return ((SessionImpl) ((org.hibernate.Session) JPA.em(name)).getSession()).connection(); + return JPA.em(name).unwrap(SessionImpl.class).getSession().connection(); } Connection localConnection = getLocalConnection(name); @@ -185,14 +180,13 @@ public static Connection getConnection(String name) { } // We have no connection - Connection connection = getDataSource(name).getConnection(); + DataSource ds = getDataSource(name); + if (ds == null) { + throw new DatabaseException("No database found. Check the configuration of your application."); + } + Connection connection = ds.getConnection(); registerLocalConnection(name, connection); return connection; - } catch (NullPointerException e) { - if (getDataSource(name) == null) { - throw new DatabaseException("No database found. Check the configuration of your application.", e); - } - throw e; } catch (Exception e) { // Exception throw new DatabaseException(e.getMessage()); diff --git a/framework/src/play/db/DBPlugin.java b/framework/src/play/db/DBPlugin.java index ba4b24b9a3..335f4ff050 100644 --- a/framework/src/play/db/DBPlugin.java +++ b/framework/src/play/db/DBPlugin.java @@ -48,9 +48,8 @@ public void onApplicationStart() { } Set dbNames = Configuration.getDbNames(); - Iterator it = dbNames.iterator(); - while (it.hasNext()) { - dbName = it.next(); + for (String name : dbNames) { + dbName = name; Configuration dbConfig = new Configuration(dbName); boolean isJndiDatasource = false; @@ -287,16 +286,9 @@ public boolean jdbcCompliant() { return this.driver.jdbcCompliant(); } - // Method not annotated with @Override since getParentLogger() is a new method - // in the CommonDataSource interface starting with JDK7 and this annotation - // would cause compilation errors with JDK6. @Override public java.util.logging.Logger getParentLogger() throws SQLFeatureNotSupportedException { - try { - return (java.util.logging.Logger) Driver.class.getDeclaredMethod("getParentLogger").invoke(this.driver); - } catch (Throwable e) { - return null; - } + return this.driver.getParentLogger(); } } } From de2816d5e82a6354d705ca9a27f6f58c19dec4e1 Mon Sep 17 00:00:00 2001 From: aleksandy Date: Fri, 22 Apr 2022 23:58:20 +0600 Subject: [PATCH 03/22] set valid source and target levels --- framework/build.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/framework/build.xml b/framework/build.xml index 7a2a2315cd..38a1271559 100644 --- a/framework/build.xml +++ b/framework/build.xml @@ -233,7 +233,7 @@ - + From 2f3c2326c839f5b3a55afbd1541f70294a80b203 Mon Sep 17 00:00:00 2001 From: aleksandy Date: Sat, 23 Apr 2022 00:07:54 +0600 Subject: [PATCH 04/22] cleanup code * remove unnecessary checks for null * remove the use of the deprecated methods and constructors * use computeIfAbsent() instead of get()/put() --- framework/src/play/db/DB.java | 12 +++++----- .../play/db/helper/JdbcResultFactories.java | 2 +- framework/src/play/db/jpa/JPAPlugin.java | 2 +- framework/src/play/libs/WS.java | 2 +- .../server/HttpServerPipelineFactory.java | 22 ++++++++++--------- framework/src/play/utils/HTML.java | 2 +- .../test-src/play/db/SQLSplitterTest.java | 5 +++-- .../play/test/PlayJUnitRunnerTest.java | 4 ++-- 8 files changed, 26 insertions(+), 25 deletions(-) diff --git a/framework/src/play/db/DB.java b/framework/src/play/db/DB.java index c2620bcd72..952c48f02a 100644 --- a/framework/src/play/db/DB.java +++ b/framework/src/play/db/DB.java @@ -307,13 +307,11 @@ public static void destroy(String name) { try { ExtendedDatasource extDatasource = datasources.get(name); if (extDatasource != null && extDatasource.getDestroyMethod() != null) { - Method close = extDatasource.datasource.getClass().getMethod(extDatasource.getDestroyMethod(), new Class[] {}); - if (close != null) { - close.invoke(extDatasource.getDataSource(), new Object[] {}); - datasources.remove(name); - DB.datasource = null; - Logger.trace("Datasource destroyed"); - } + Method close = extDatasource.datasource.getClass().getMethod(extDatasource.getDestroyMethod()); + close.invoke(extDatasource.getDataSource()); + datasources.remove(name); + DB.datasource = null; + Logger.trace("Datasource destroyed"); } } catch (Throwable t) { Logger.error("Couldn't destroy the datasource", t); diff --git a/framework/src/play/db/helper/JdbcResultFactories.java b/framework/src/play/db/helper/JdbcResultFactories.java index 0dfa4d6dca..6f5cca525a 100644 --- a/framework/src/play/db/helper/JdbcResultFactories.java +++ b/framework/src/play/db/helper/JdbcResultFactories.java @@ -133,7 +133,7 @@ public void init(ResultSet result) throws SQLException { int count = meta.getColumnCount(); for (int i = 1; i <= count; i++) { String label = meta.getColumnLabel(i); - if (label.length()>0) fields.add(label); + if (!label.isEmpty()) fields.add(label); } } } diff --git a/framework/src/play/db/jpa/JPAPlugin.java b/framework/src/play/db/jpa/JPAPlugin.java index 0ceec845a1..627504623c 100644 --- a/framework/src/play/db/jpa/JPAPlugin.java +++ b/framework/src/play/db/jpa/JPAPlugin.java @@ -198,7 +198,7 @@ protected EntityManagerFactory newEntityManagerFactory(String dbName, Configurat protected PersistenceUnitInfoImpl persistenceUnitInfo(String dbName, Configuration dbConfig) { final List managedClasses = entityClasses(dbName); final Properties properties = properties(dbName, dbConfig); - properties.put(org.hibernate.jpa.AvailableSettings.LOADED_CLASSES,managedClasses); + properties.put(org.hibernate.cfg.AvailableSettings.LOADED_CLASSES,managedClasses); return new PersistenceUnitInfoImpl(dbName, managedClasses, mappingFiles(dbConfig), properties); } diff --git a/framework/src/play/libs/WS.java b/framework/src/play/libs/WS.java index 3a47e49f1c..5cc8043338 100644 --- a/framework/src/play/libs/WS.java +++ b/framework/src/play/libs/WS.java @@ -852,7 +852,7 @@ public Map getQueryString() { public JsonElement getJson() { String json = getString(); try { - return new JsonParser().parse(json); + return JsonParser.parseString(json); } catch (Exception e) { Logger.error("Bad JSON: \n%s", json); throw new RuntimeException("Cannot parse JSON (check logs)", e); diff --git a/framework/src/play/server/HttpServerPipelineFactory.java b/framework/src/play/server/HttpServerPipelineFactory.java index 4dac6212cb..69c2bb2cba 100644 --- a/framework/src/play/server/HttpServerPipelineFactory.java +++ b/framework/src/play/server/HttpServerPipelineFactory.java @@ -5,6 +5,8 @@ import org.jboss.netty.channel.ChannelHandler; import play.Play; import play.Logger; +import play.exceptions.UnexpectedException; + import java.util.Map; import java.util.HashMap; @@ -51,11 +53,9 @@ public ChannelPipeline getPipeline() throws Exception { } } - if (playHandler != null) { - pipeline.addLast("handler", playHandler); - playHandler.pipelines.put("handler", playHandler); - } - + pipeline.addLast("handler", playHandler); + playHandler.pipelines.put("handler", playHandler); + return pipeline; } @@ -68,11 +68,13 @@ protected String getName(String name) { protected ChannelHandler getInstance(String name) throws Exception { - Class clazz = classes.get(name); - if (clazz == null) { - clazz = Class.forName(name); - classes.put(name, clazz); - } + Class clazz = classes.computeIfAbsent(name, className -> { + try { + return Class.forName(className); + } catch (ClassNotFoundException e) { + throw new UnexpectedException(e); + } + }); if (ChannelHandler.class.isAssignableFrom(clazz)) return (ChannelHandler)clazz.newInstance(); return null; diff --git a/framework/src/play/utils/HTML.java b/framework/src/play/utils/HTML.java index 68bd2ac380..9099c737d4 100644 --- a/framework/src/play/utils/HTML.java +++ b/framework/src/play/utils/HTML.java @@ -110,7 +110,7 @@ public HtmlCharacterEntityReferences() { int index = (referredChar < 1000 ? referredChar : referredChar - 7000); String reference = entityReferences.getProperty(key); this.characterToEntityReferenceMap[index] = REFERENCE_START + reference + REFERENCE_END; - this.entityReferenceToCharacterMap.put(reference, new Character((char) referredChar)); + this.entityReferenceToCharacterMap.put(reference, (char) referredChar); } } diff --git a/framework/test-src/play/db/SQLSplitterTest.java b/framework/test-src/play/db/SQLSplitterTest.java index c1f2851cd9..ff6f226dde 100644 --- a/framework/test-src/play/db/SQLSplitterTest.java +++ b/framework/test-src/play/db/SQLSplitterTest.java @@ -2,6 +2,7 @@ import org.junit.*; +import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import java.io.File; @@ -110,11 +111,11 @@ public void verifyTestSplitting() throws Exception { CharSequence[] srcArr = new CharSequence[(int) srcArrList.size()]; srcArr = srcArrList.toArray(srcArr); - assertEquals(readFile("/play/db/test.out.sql").split("==="), srcArr); + assertArrayEquals(readFile("/play/db/test.out.sql").split("==="), srcArr); srcArrList = SQLSplitter.splitSQL(readFile("/play/db/test2.sql")); srcArr = new CharSequence[(int) srcArrList.size()]; srcArr = srcArrList.toArray(srcArr); - assertEquals(readFile("/play/db/test2.out.sql").split("==="), srcArr); + assertArrayEquals(readFile("/play/db/test2.out.sql").split("==="), srcArr); } } diff --git a/framework/test-src/play/test/PlayJUnitRunnerTest.java b/framework/test-src/play/test/PlayJUnitRunnerTest.java index ea2ea8a45b..56770d9350 100644 --- a/framework/test-src/play/test/PlayJUnitRunnerTest.java +++ b/framework/test-src/play/test/PlayJUnitRunnerTest.java @@ -1,7 +1,7 @@ package play.test; import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doCallRealMethod; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -17,7 +17,7 @@ public class PlayJUnitRunnerTest { public void testFilter() throws Exception { PlayJUnitRunner runner = mock(PlayJUnitRunner.class); runner.jUnit4 = new JUnit4(PlayJUnitRunnerTest.class); - doCallRealMethod().when(runner).filter((Filter) any()); + doCallRealMethod().when(runner).filter(any()); runner.filter(new Filter() { From fd05a73ea7d67097ec7627b6b5590daa27836035 Mon Sep 17 00:00:00 2001 From: aleksandy Date: Sat, 23 Apr 2022 00:09:16 +0600 Subject: [PATCH 05/22] use standard java.nio instead of third party library --- framework/src/play/libs/IO.java | 82 ++++++++++++++++++++------------- 1 file changed, 50 insertions(+), 32 deletions(-) diff --git a/framework/src/play/libs/IO.java b/framework/src/play/libs/IO.java index cb09da0ff7..970be89b1b 100644 --- a/framework/src/play/libs/IO.java +++ b/framework/src/play/libs/IO.java @@ -1,17 +1,22 @@ package play.libs; +import static java.nio.charset.Charset.defaultCharset; +import static java.nio.charset.StandardCharsets.UTF_8; +import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; +import static org.apache.commons.io.Charsets.toCharset; import static org.apache.commons.io.IOUtils.closeQuietly; import java.io.File; -import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.List; import java.util.Properties; +import java.util.stream.Stream; -import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import play.exceptions.UnexpectedException; @@ -77,7 +82,11 @@ public static String readContentAsString(InputStream is, String encoding) { * @return The String content */ public static String readContentAsString(File file) { - return readContentAsString(file, "utf-8"); + try { + return Files.readString(file.toPath(), UTF_8); + } catch (IOException e) { + throw new UnexpectedException(e); + } } /** @@ -91,32 +100,34 @@ public static String readContentAsString(File file) { */ public static String readContentAsString(File file, String encoding) { try { - return FileUtils.readFileToString(file, encoding); + return Files.readString(file.toPath(), toCharset(encoding)); } catch (IOException e) { throw new UnexpectedException(e); } } public static List readLines(InputStream is) { - List lines = null; try { - lines = IOUtils.readLines(is); + return IOUtils.readLines(is, defaultCharset()); } catch (IOException ex) { throw new UnexpectedException(ex); } - return lines; } public static List readLines(File file, String encoding) { try { - return FileUtils.readLines(file, encoding); + return Files.readAllLines(file.toPath(), toCharset(encoding)); } catch (IOException ex) { throw new UnexpectedException(ex); } } public static List readLines(File file) { - return readLines(file, "utf-8"); + try { + return Files.readAllLines(file.toPath(), UTF_8); + } catch (IOException ex) { + throw new UnexpectedException(ex); + } } /** @@ -128,7 +139,7 @@ public static List readLines(File file) { */ public static byte[] readContent(File file) { try { - return FileUtils.readFileToByteArray(file); + return Files.readAllBytes(file.toPath()); } catch (IOException e) { throw new UnexpectedException(e); } @@ -158,7 +169,13 @@ public static byte[] readContent(InputStream is) { * The stream to write */ public static void writeContent(CharSequence content, OutputStream os) { - writeContent(content, os, "utf-8"); + try { + IOUtils.write(content, os, UTF_8); + } catch (IOException e) { + throw new UnexpectedException(e); + } finally { + closeQuietly(os); + } } /** @@ -190,7 +207,11 @@ public static void writeContent(CharSequence content, OutputStream os, String en * The file to write */ public static void writeContent(CharSequence content, File file) { - writeContent(content, file, "utf-8"); + try { + Files.writeString(file.toPath(), content, UTF_8); + } catch (IOException e) { + throw new UnexpectedException(e); + } } /** @@ -205,7 +226,7 @@ public static void writeContent(CharSequence content, File file) { */ public static void writeContent(CharSequence content, File file, String encoding) { try { - FileUtils.write(file, content, encoding); + Files.writeString(file.toPath(), content, toCharset(encoding)); } catch (IOException e) { throw new UnexpectedException(e); } @@ -221,14 +242,14 @@ public static void writeContent(CharSequence content, File file, String encoding */ public static void write(byte[] data, File file) { try { - FileUtils.writeByteArrayToFile(file, data); + Files.write(file.toPath(), data); } catch (IOException e) { throw new UnexpectedException(e); } } /** - * Copy an stream to another one. + * Copy a stream to another one. By the end of the method the input stream {@code is} will be closed. * * @param is * The source stream @@ -237,7 +258,7 @@ public static void write(byte[] data, File file) { */ public static void copy(InputStream is, OutputStream os) { try { - IOUtils.copyLarge(is, os); + is.transferTo(os); } catch (IOException e) { throw new UnexpectedException(e); } finally { @@ -246,7 +267,7 @@ public static void copy(InputStream is, OutputStream os) { } /** - * Copy an stream to another one. + * Copy a stream to another one. By the end of the method both of streams {@code is} and {@code os} will be closed. * * @param is * The source stream @@ -255,7 +276,7 @@ public static void copy(InputStream is, OutputStream os) { */ public static void write(InputStream is, OutputStream os) { try { - IOUtils.copyLarge(is, os); + is.transferTo(os); } catch (IOException e) { throw new UnexpectedException(e); } finally { @@ -276,7 +297,7 @@ public static void write(InputStream is, File f) { try { OutputStream os = new FileOutputStream(f); try { - IOUtils.copyLarge(is, os); + is.transferTo(os); } finally { closeQuietly(is); closeQuietly(os); @@ -288,19 +309,16 @@ public static void write(InputStream is, File f) { // If targetLocation does not exist, it will be created. public static void copyDirectory(File source, File target) { - if (source.isDirectory()) { - if (!target.exists()) { - target.mkdir(); - } - for (String child : source.list()) { - copyDirectory(new File(source, child), new File(target, child)); - } - } else { - try { - write(new FileInputStream(source), new FileOutputStream(target)); - } catch (IOException e) { - throw new UnexpectedException(e); - } + try (Stream dirs = Files.walk(source.toPath())) { + dirs.forEach(src -> { + try { + Files.copy(source.toPath(), target.toPath(), REPLACE_EXISTING); + } catch (IOException e) { + throw new UnexpectedException(e); + } + }); + } catch (IOException e) { + throw new UnexpectedException(e); } } From d874f3307909b719387d0c532866df66935f19ad Mon Sep 17 00:00:00 2001 From: aleksandy Date: Sat, 23 Apr 2022 00:27:43 +0600 Subject: [PATCH 06/22] cleanup modules --- modules/crud/app/controllers/CRUD.java | 8 ++++---- .../src/play/modules/testrunner/FirePhoque.java | 15 ++++++++------- 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/modules/crud/app/controllers/CRUD.java b/modules/crud/app/controllers/CRUD.java index f0294073e3..0b7b1a65c0 100644 --- a/modules/crud/app/controllers/CRUD.java +++ b/modules/crud/app/controllers/CRUD.java @@ -79,7 +79,7 @@ public static void attachment(String id, String field) throws Exception { Object att = object.getClass().getField(field).get(object); if(att instanceof Model.BinaryField) { Model.BinaryField attachment = (Model.BinaryField)att; - if (attachment == null || !attachment.exists()) { + if (!attachment.exists()) { notFound(); } response.contentType = attachment.type(); @@ -88,7 +88,7 @@ public static void attachment(String id, String field) throws Exception { // DEPRECATED if(att instanceof play.db.jpa.FileAttachment) { play.db.jpa.FileAttachment attachment = (play.db.jpa.FileAttachment)att; - if (attachment == null || !attachment.exists()) { + if (!attachment.exists()) { notFound(); } renderBinary(attachment.get(), attachment.filename); @@ -274,13 +274,13 @@ public Object getBlankAction() { public Long count(String search, String searchFields, String where) { - return factory.count(searchFields == null ? new ArrayList() : Arrays.asList(searchFields.split("[ ]")), search, where); + return factory.count(searchFields == null ? new ArrayList() : Arrays.asList(searchFields.split(" ")), search, where); } @SuppressWarnings("unchecked") public List findPage(int page, String search, String searchFields, String orderBy, String order, String where) { int offset = (page - 1) * getPageSize(); - List properties = searchFields == null ? new ArrayList(0) : Arrays.asList(searchFields.split("[ ]")); + List properties = searchFields == null ? new ArrayList(0) : Arrays.asList(searchFields.split(" ")); return Model.Manager.factoryFor(entityClass).fetch(offset, getPageSize(), orderBy, order, properties, search, where); } diff --git a/modules/testrunner/src/play/modules/testrunner/FirePhoque.java b/modules/testrunner/src/play/modules/testrunner/FirePhoque.java index 9d61b93456..906bbf5acf 100644 --- a/modules/testrunner/src/play/modules/testrunner/FirePhoque.java +++ b/modules/testrunner/src/play/modules/testrunner/FirePhoque.java @@ -17,6 +17,7 @@ import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; @@ -47,18 +48,18 @@ public static void main(String[] args) throws Exception { if(runUnitTests != null || runFunctionalTests != null || runSeleniumTests != null){ urlStringBuilder.append("?"); - urlStringBuilder.append("runUnitTests=").append(runUnitTests != null ? true : false); - System.out.println("~ Run unit tests:" + (runUnitTests != null ? true : false)); + urlStringBuilder.append("runUnitTests=").append(runUnitTests != null); + System.out.println("~ Run unit tests:" + (runUnitTests != null)); - urlStringBuilder.append("&runFunctionalTests=").append(runFunctionalTests != null ? true : false); - System.out.println("~ Run functional tests:" + (runFunctionalTests != null ? true : false)); + urlStringBuilder.append("&runFunctionalTests=").append(runFunctionalTests != null); + System.out.println("~ Run functional tests:" + (runFunctionalTests != null)); - urlStringBuilder.append("&runSeleniumTests=").append(runSeleniumTests != null ? true : false); - System.out.println("~ Run selenium tests:" + (runSeleniumTests != null ? true : false)); + urlStringBuilder.append("&runSeleniumTests=").append(runSeleniumTests != null); + System.out.println("~ Run selenium tests:" + (runSeleniumTests != null)); } try { - in = new BufferedReader(new InputStreamReader(new URL(urlStringBuilder.toString()).openStream(), "utf-8")); + in = new BufferedReader(new InputStreamReader(new URL(urlStringBuilder.toString()).openStream(), StandardCharsets.UTF_8)); String marker = in.readLine(); if (!marker.equals("---")) { throw new RuntimeException("Oops"); From 45085fa72d7ccf7da75bed37c5165f71c960fb48 Mon Sep 17 00:00:00 2001 From: aleksandy Date: Sat, 23 Apr 2022 12:28:25 +0600 Subject: [PATCH 07/22] reorganize fields order and make them final --- framework/src/play/Invoker.java | 3 +-- framework/src/play/Logger.java | 2 +- framework/src/play/Play.java | 8 ++++---- framework/src/play/PlayPlugin.java | 2 +- framework/src/play/cache/EhCacheImpl.java | 7 +++---- .../play/classloading/ApplicationClasses.java | 2 +- .../ApplicationClassloaderState.java | 2 +- .../play/classloading/enhancers/Enhancer.java | 2 +- .../enhancers/PropertiesEnhancer.java | 4 ++-- framework/src/play/data/MemoryUpload.java | 2 +- .../play/data/binding/AnnotationHelper.java | 4 ++-- .../src/play/data/binding/BeanWrapper.java | 16 ++++++++-------- framework/src/play/data/binding/Binder.java | 4 ++-- .../binding/CachedBoundActionMethodArgs.java | 2 +- .../data/binding/types/DateTimeBinder.java | 2 +- .../data/parsing/ApacheMultipartParser.java | 10 +++------- .../src/play/data/parsing/MultipartStream.java | 4 ++-- .../src/play/data/parsing/TempFilePlugin.java | 3 +-- .../play/data/validation/CheckWithCheck.java | 2 +- .../src/play/data/validation/EmailCheck.java | 2 +- .../src/play/data/validation/PhoneCheck.java | 2 +- .../src/play/data/validation/URLCheck.java | 2 +- .../src/play/data/validation/Validation.java | 6 +++--- .../play/data/validation/ValidationPlugin.java | 2 +- framework/src/play/db/Configuration.java | 2 +- framework/src/play/db/DB.java | 4 ++-- framework/src/play/db/DBPlugin.java | 2 +- framework/src/play/db/Evolutions.java | 7 ++++--- .../src/play/db/evolutions/Evolution.java | 12 ++++++------ .../exceptions/InconsistentDatabase.java | 10 +++++----- .../exceptions/InvalidDatabaseRevision.java | 4 ++-- framework/src/play/db/helper/SqlQuery.java | 3 +-- framework/src/play/db/jpa/JPA.java | 4 ++-- framework/src/play/db/jpa/JPAModelLoader.java | 4 ++-- framework/src/play/db/jpa/JPAPlugin.java | 2 +- .../src/play/deps/DependenciesManager.java | 6 +++--- framework/src/play/deps/HumanReadyLogger.java | 16 ++++++++-------- .../src/play/deps/PlayConflictManager.java | 2 +- framework/src/play/deps/YamlParser.java | 2 +- .../exceptions/ActionNotFoundException.java | 2 +- .../play/exceptions/CompilationException.java | 2 +- .../src/play/exceptions/PlayException.java | 2 +- .../src/play/exceptions/TemplateException.java | 4 ++-- .../exceptions/TemplateNotFoundException.java | 2 +- .../src/play/exceptions/YAMLException.java | 4 ++-- framework/src/play/i18n/Lang.java | 2 +- framework/src/play/i18n/Localized.java | 2 +- framework/src/play/i18n/Messages.java | 4 ++-- framework/src/play/i18n/MessagesPlugin.java | 2 +- framework/src/play/jobs/JobsPlugin.java | 2 +- framework/src/play/libs/Crypto.java | 2 +- framework/src/play/libs/Expression.java | 2 +- framework/src/play/libs/Images.java | 4 ++-- framework/src/play/libs/Mail.java | 6 +++--- framework/src/play/libs/MimeTypes.java | 6 +----- framework/src/play/libs/OAuth.java | 18 +++++++++--------- framework/src/play/libs/OAuth2.java | 8 ++++---- framework/src/play/libs/OpenID.java | 12 ++++++------ framework/src/play/libs/WS.java | 4 ++-- .../libs/mail/test/LegacyMockMailSystem.java | 2 +- framework/src/play/mvc/CookieDataCodec.java | 2 +- framework/src/play/mvc/Http.java | 6 +++--- framework/src/play/mvc/Router.java | 14 +++++++------- framework/src/play/mvc/Scope.java | 14 +++++++------- .../src/play/plugins/PluginCollection.java | 6 +++--- framework/src/play/server/FileService.java | 6 +++--- .../play/server/HttpServerPipelineFactory.java | 4 ++-- framework/src/play/server/PlayHandler.java | 4 ++-- framework/src/play/server/ServletWrapper.java | 8 ++++---- .../ssl/SslHttpServerContextFactory.java | 2 +- .../ssl/SslHttpServerPipelineFactory.java | 2 +- framework/src/play/templates/BaseTemplate.java | 4 ++-- .../play/templates/GroovyTemplateCompiler.java | 2 +- framework/src/play/templates/TagContext.java | 4 ++-- .../src/play/templates/TemplateCompiler.java | 4 ++-- .../src/play/templates/TemplateLoader.java | 6 +++--- .../src/play/templates/TemplateParser.java | 2 +- framework/src/play/test/Fixtures.java | 6 +++--- framework/src/play/test/FunctionalTest.java | 4 ++-- framework/src/play/test/Helpers.java | 2 +- framework/src/play/test/TestEngine.java | 6 +++--- framework/src/play/utils/Default.java | 2 +- framework/src/play/utils/Java.java | 2 +- framework/src/play/utils/SmartFuture.java | 2 +- framework/src/play/utils/Utils.java | 5 ++--- framework/src/play/vfs/VirtualFile.java | 2 +- 86 files changed, 188 insertions(+), 200 deletions(-) diff --git a/framework/src/play/Invoker.java b/framework/src/play/Invoker.java index 2c11ce19d3..3f2b91bc2b 100644 --- a/framework/src/play/Invoker.java +++ b/framework/src/play/Invoker.java @@ -413,10 +413,9 @@ public String getErrorDescription() { static class WaitForTasksCompletion extends Thread { static WaitForTasksCompletion instance; - Map, Invocation> queue; + final Map, Invocation> queue = new ConcurrentHashMap<>(); public WaitForTasksCompletion() { - queue = new ConcurrentHashMap<>(); setName("WaitForTasksCompletion"); setDaemon(true); } diff --git a/framework/src/play/Logger.java b/framework/src/play/Logger.java index 6eedae5a4c..d2cb7ae1be 100644 --- a/framework/src/play/Logger.java +++ b/framework/src/play/Logger.java @@ -47,7 +47,7 @@ public class Logger { /** * When using java.util.logging. */ - public static java.util.logging.Logger juli = java.util.logging.Logger.getLogger("play"); + public static final java.util.logging.Logger juli = java.util.logging.Logger.getLogger("play"); /** * true if logger is configured manually (log4j-config file supplied by application) */ diff --git a/framework/src/play/Play.java b/framework/src/play/Play.java index 4e4a88c83c..5d14bfd1a6 100644 --- a/framework/src/play/Play.java +++ b/framework/src/play/Play.java @@ -115,7 +115,7 @@ public boolean isProd() { /** * All paths to search for files */ - public static List roots = new ArrayList<>(16); + public static final List roots = new ArrayList<>(16); /** * All paths to search for Java files */ @@ -123,7 +123,7 @@ public boolean isProd() { /** * All paths to search for templates files */ - public static List templatesPath = new ArrayList<>(2); + public static final List templatesPath = new ArrayList<>(2); /** * Main routes file */ @@ -131,7 +131,7 @@ public boolean isProd() { /** * Plugin routes files */ - public static Map modulesRoutes = new HashMap<>(16); + public static final Map modulesRoutes = new HashMap<>(16); /** * The loaded configuration files */ @@ -166,7 +166,7 @@ public boolean isProd() { /** * Modules */ - public static Map modules = new HashMap<>(16); + public static final Map modules = new HashMap<>(16); /** * Framework version */ diff --git a/framework/src/play/PlayPlugin.java b/framework/src/play/PlayPlugin.java index 543bbf802c..d5337bba8e 100644 --- a/framework/src/play/PlayPlugin.java +++ b/framework/src/play/PlayPlugin.java @@ -514,7 +514,7 @@ public Collection getFunctionalTests() { * transaction around an action. The filter applies a transaction to the current Action. */ public abstract static class Filter { - String name; + final String name; public Filter(String name) { this.name = name; diff --git a/framework/src/play/cache/EhCacheImpl.java b/framework/src/play/cache/EhCacheImpl.java index a8f604620d..3b08410737 100644 --- a/framework/src/play/cache/EhCacheImpl.java +++ b/framework/src/play/cache/EhCacheImpl.java @@ -20,16 +20,15 @@ */ public class EhCacheImpl implements CacheImpl { + private static final String cacheName = "play"; private static EhCacheImpl uniqueInstance; - CacheManager cacheManager; + final CacheManager cacheManager = CacheManager.create(); - net.sf.ehcache.Cache cache; + final net.sf.ehcache.Cache cache; - private static final String cacheName = "play"; private EhCacheImpl() { - this.cacheManager = CacheManager.create(); this.cacheManager.addCache(cacheName); this.cache = cacheManager.getCache(cacheName); } diff --git a/framework/src/play/classloading/ApplicationClasses.java b/framework/src/play/classloading/ApplicationClasses.java index a832515d02..9e7eec9d5a 100644 --- a/framework/src/play/classloading/ApplicationClasses.java +++ b/framework/src/play/classloading/ApplicationClasses.java @@ -26,7 +26,7 @@ public class ApplicationClasses { /** * Reference to the eclipse compiler. */ - ApplicationCompiler compiler = new ApplicationCompiler(this); + final ApplicationCompiler compiler = new ApplicationCompiler(this); /** * Cache of all compiled classes */ diff --git a/framework/src/play/classloading/ApplicationClassloaderState.java b/framework/src/play/classloading/ApplicationClassloaderState.java index 20bbc73191..4b70f9991b 100644 --- a/framework/src/play/classloading/ApplicationClassloaderState.java +++ b/framework/src/play/classloading/ApplicationClassloaderState.java @@ -13,7 +13,7 @@ * they could check if the state of the ApplicationClassloader has changed.. */ public class ApplicationClassloaderState { - private static AtomicLong nextStateValue = new AtomicLong(); + private static final AtomicLong nextStateValue = new AtomicLong(); private final long currentStateValue = nextStateValue.getAndIncrement(); diff --git a/framework/src/play/classloading/enhancers/Enhancer.java b/framework/src/play/classloading/enhancers/Enhancer.java index 5203f07d2d..04743fb644 100644 --- a/framework/src/play/classloading/enhancers/Enhancer.java +++ b/framework/src/play/classloading/enhancers/Enhancer.java @@ -29,7 +29,7 @@ */ public abstract class Enhancer { - protected ClassPool classPool; + protected final ClassPool classPool; public Enhancer() { this.classPool = newClassPool(); diff --git a/framework/src/play/classloading/enhancers/PropertiesEnhancer.java b/framework/src/play/classloading/enhancers/PropertiesEnhancer.java index 125f4194e7..12c5e2bb23 100644 --- a/framework/src/play/classloading/enhancers/PropertiesEnhancer.java +++ b/framework/src/play/classloading/enhancers/PropertiesEnhancer.java @@ -28,8 +28,8 @@ */ public class PropertiesEnhancer extends Enhancer { - private boolean enabled = Boolean.parseBoolean(Play.configuration.getProperty("play.propertiesEnhancer.enabled", "true")); - private boolean generateAccessors = Boolean.parseBoolean(Play.configuration.getProperty("play.propertiesEnhancer.generateAccessors", "true")); + private final boolean enabled = Boolean.parseBoolean(Play.configuration.getProperty("play.propertiesEnhancer.enabled", "true")); + private final boolean generateAccessors = Boolean.parseBoolean(Play.configuration.getProperty("play.propertiesEnhancer.generateAccessors", "true")); @Override public void enhanceThisClass(ApplicationClass applicationClass) throws Exception { diff --git a/framework/src/play/data/MemoryUpload.java b/framework/src/play/data/MemoryUpload.java index be13600c9b..3489c1d4b2 100644 --- a/framework/src/play/data/MemoryUpload.java +++ b/framework/src/play/data/MemoryUpload.java @@ -7,7 +7,7 @@ public class MemoryUpload implements Upload { - FileItem fileItem; + final FileItem fileItem; public MemoryUpload(FileItem fileItem) { this.fileItem = fileItem; diff --git a/framework/src/play/data/binding/AnnotationHelper.java b/framework/src/play/data/binding/AnnotationHelper.java index 8b5153ce3f..16ae1bb031 100644 --- a/framework/src/play/data/binding/AnnotationHelper.java +++ b/framework/src/play/data/binding/AnnotationHelper.java @@ -88,8 +88,8 @@ public static Tuple getLocale(String[] langs) { */ private static class Tuple { - public int index = -1; - public Locale locale; + public final int index; + public final Locale locale; public Tuple(int index, Locale locale) { this.locale = locale; diff --git a/framework/src/play/data/binding/BeanWrapper.java b/framework/src/play/data/binding/BeanWrapper.java index 1a1d854749..1b16333869 100644 --- a/framework/src/play/data/binding/BeanWrapper.java +++ b/framework/src/play/data/binding/BeanWrapper.java @@ -16,12 +16,12 @@ public class BeanWrapper { static final int notwritableField = Modifier.FINAL | Modifier.NATIVE | Modifier.STATIC; static final int notaccessibleMethod = Modifier.NATIVE | Modifier.STATIC; - private Class beanClass; - - /** + /** * a cache for our properties and setters */ - private Map wrappers = new HashMap<>(); + private final Map wrappers = new HashMap<>(); + + private final Class beanClass; public BeanWrapper(Class forClass) { if (Logger.isTraceEnabled()) { @@ -143,12 +143,12 @@ private void registerSetters(Class clazz, boolean isScala) { public static class Property { - private Annotation[] annotations; + private final Annotation[] annotations; + private final Class type; + private final Type genericType; + private final String name; private Method setter; private Field field; - private Class type; - private Type genericType; - private String name; private String[] profiles; Property(String propertyName, Method setterMethod) { diff --git a/framework/src/play/data/binding/Binder.java b/framework/src/play/data/binding/Binder.java index 96266587cf..e2a02b6143 100644 --- a/framework/src/play/data/binding/Binder.java +++ b/framework/src/play/data/binding/Binder.java @@ -81,7 +81,7 @@ public static void unregister(Class clazz) { supportedTypes.remove(clazz); } - static Map, BeanWrapper> beanwrappers = new HashMap<>(); + static final Map, BeanWrapper> beanwrappers = new HashMap<>(); static BeanWrapper getBeanWrapper(Class clazz) { return beanwrappers.computeIfAbsent(clazz, BeanWrapper::new); @@ -90,7 +90,7 @@ static BeanWrapper getBeanWrapper(Class clazz) { public static class MethodAndParamInfo { public final Object objectInstance; public final Method method; - public int parameterIndex; + public final int parameterIndex; public MethodAndParamInfo(Object objectInstance, Method method, int parameterIndex) { this.objectInstance = objectInstance; diff --git a/framework/src/play/data/binding/CachedBoundActionMethodArgs.java b/framework/src/play/data/binding/CachedBoundActionMethodArgs.java index db8e4caeaa..0acd1000af 100644 --- a/framework/src/play/data/binding/CachedBoundActionMethodArgs.java +++ b/framework/src/play/data/binding/CachedBoundActionMethodArgs.java @@ -11,7 +11,7 @@ public class CachedBoundActionMethodArgs { private static final ThreadLocal current = new ThreadLocal<>(); - private Map preBoundActionMethodArgs = new HashMap<>(1); + private final Map preBoundActionMethodArgs = new HashMap<>(1); public static void init() { current.set( new CachedBoundActionMethodArgs()); diff --git a/framework/src/play/data/binding/types/DateTimeBinder.java b/framework/src/play/data/binding/types/DateTimeBinder.java index 3fb6d1ecea..5dacf56f85 100644 --- a/framework/src/play/data/binding/types/DateTimeBinder.java +++ b/framework/src/play/data/binding/types/DateTimeBinder.java @@ -12,7 +12,7 @@ */ public class DateTimeBinder implements TypeBinder { - private static DateBinder dateBinder = new DateBinder(); + private static final DateBinder dateBinder = new DateBinder(); @Override public DateTime bind(String name, Annotation[] annotations, String value, Class actualClass, Type genericType) throws Exception { diff --git a/framework/src/play/data/parsing/ApacheMultipartParser.java b/framework/src/play/data/parsing/ApacheMultipartParser.java index 90d2c4cdea..f1800b14af 100644 --- a/framework/src/play/data/parsing/ApacheMultipartParser.java +++ b/framework/src/play/data/parsing/ApacheMultipartParser.java @@ -99,11 +99,7 @@ private static void putMapEntry(Map map, String name, String v */ public static class AutoFileItem implements FileItem { - private static FileCleaningTracker fileTracker; - - static { - fileTracker = new FileCleaningTracker(); - } + private static final FileCleaningTracker fileTracker = new FileCleaningTracker(); // ----------------------------------------------------- Manifest constants /** @@ -604,12 +600,12 @@ public Map parse(InputStream body) { * The maximum size permitted for the complete request, as opposed to * {@link #maxFileSize}. A value of -1 indicates no maximum. */ - private long maxRequestSize = Integer.parseInt(Play.configuration.getProperty("upload.maxRequestSize", "-1")); + private final long maxRequestSize = Integer.parseInt(Play.configuration.getProperty("upload.maxRequestSize", "-1")); /** * The maximum size permitted for a single uploaded file, as opposed to * {@link #maxRequestSize}. A value of -1 indicates no maximum. */ - private long maxFileSize = Integer.parseInt(Play.configuration.getProperty("upload.maxFileSize", "-1")); + private final long maxFileSize = Integer.parseInt(Play.configuration.getProperty("upload.maxFileSize", "-1")); // ------------------------------------------------------ Protected methods diff --git a/framework/src/play/data/parsing/MultipartStream.java b/framework/src/play/data/parsing/MultipartStream.java index 796449e9da..e4991d4909 100644 --- a/framework/src/play/data/parsing/MultipartStream.java +++ b/framework/src/play/data/parsing/MultipartStream.java @@ -195,11 +195,11 @@ private void notifyListener() { * The amount of data, in bytes, that must be kept in the buffer in order * to detect delimiters reliably. */ - private int keepRegion; + private final int keepRegion; /** * The byte sequence that partitions the stream. */ - private byte[] boundary; + private final byte[] boundary; /** * The length of the buffer used for processing the request. */ diff --git a/framework/src/play/data/parsing/TempFilePlugin.java b/framework/src/play/data/parsing/TempFilePlugin.java index d2d8e1c505..fc7d07b8e6 100644 --- a/framework/src/play/data/parsing/TempFilePlugin.java +++ b/framework/src/play/data/parsing/TempFilePlugin.java @@ -15,8 +15,7 @@ */ public class TempFilePlugin extends PlayPlugin { - private static DecimalFormat format = new DecimalFormat("##########"); - + private static final DecimalFormat format = new DecimalFormat("##########"); static { format.setMinimumIntegerDigits(10); diff --git a/framework/src/play/data/validation/CheckWithCheck.java b/framework/src/play/data/validation/CheckWithCheck.java index b81e131dfa..e44c47335f 100644 --- a/framework/src/play/data/validation/CheckWithCheck.java +++ b/framework/src/play/data/validation/CheckWithCheck.java @@ -14,7 +14,7 @@ public class CheckWithCheck extends AbstractAnnotationCheck { static final String mes = "validation.invalid"; - Map variables = new TreeMap<>(); + final Map variables = new TreeMap<>(); Check check; @Override diff --git a/framework/src/play/data/validation/EmailCheck.java b/framework/src/play/data/validation/EmailCheck.java index 7bc20a7053..ca91c7f642 100644 --- a/framework/src/play/data/validation/EmailCheck.java +++ b/framework/src/play/data/validation/EmailCheck.java @@ -9,7 +9,7 @@ public class EmailCheck extends AbstractAnnotationCheck { static final String mes = "validation.email"; - static Pattern emailPattern = Pattern.compile("[\\w!#$%&'*+/=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[a-zA-Z0-9](?:[\\w-]*[\\w])?"); + static final Pattern emailPattern = Pattern.compile("[\\w!#$%&'*+/=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[a-zA-Z0-9](?:[\\w-]*[\\w])?"); @Override public void configure(Email email) { diff --git a/framework/src/play/data/validation/PhoneCheck.java b/framework/src/play/data/validation/PhoneCheck.java index dd2893468a..3aade43327 100644 --- a/framework/src/play/data/validation/PhoneCheck.java +++ b/framework/src/play/data/validation/PhoneCheck.java @@ -11,7 +11,7 @@ public class PhoneCheck extends AbstractAnnotationCheck { static final String mes = "validation.phone"; - static Pattern phonePattern = Pattern.compile("^([\\+][0-9]{1,3}([ \\.\\-]))?([\\(]{1}[0-9]{1,6}[\\)])?([0-9 \\.\\-/]{3,20})((x|ext|extension)[ ]?[0-9]{1,4})?$"); + static final Pattern phonePattern = Pattern.compile("^([\\+][0-9]{1,3}([ \\.\\-]))?([\\(]{1}[0-9]{1,6}[\\)])?([0-9 \\.\\-/]{3,20})((x|ext|extension)[ ]?[0-9]{1,4})?$"); @Override public void configure(Phone phone) { diff --git a/framework/src/play/data/validation/URLCheck.java b/framework/src/play/data/validation/URLCheck.java index f288c1e801..f109a5db1c 100644 --- a/framework/src/play/data/validation/URLCheck.java +++ b/framework/src/play/data/validation/URLCheck.java @@ -9,7 +9,7 @@ public class URLCheck extends AbstractAnnotationCheck { static final String mes = "validation.url"; - static Pattern urlPattern = Pattern.compile("^(http|https|ftp)\\://[a-zA-Z0-9\\-\\.]+\\.[a-z" + + static final Pattern urlPattern = Pattern.compile("^(http|https|ftp)\\://[a-zA-Z0-9\\-\\.]+\\.[a-z" + "A-Z]{2,3}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\\-\\._\\?\\,\\'/\\\\\\+&%\\$#\\=~\\!])*$"); @Override diff --git a/framework/src/play/data/validation/Validation.java b/framework/src/play/data/validation/Validation.java index 7042acf39c..bb6366beb7 100644 --- a/framework/src/play/data/validation/Validation.java +++ b/framework/src/play/data/validation/Validation.java @@ -20,7 +20,7 @@ public class Validation { public static final ThreadLocal current = new ThreadLocal<>(); - List errors = new ArrayList<>(); + final List errors = new ArrayList<>(); boolean keep = false; protected Validation() { @@ -274,8 +274,8 @@ static void searchValidator(Class clazz, String name, Map params = new HashMap<>(); + public final Annotation annotation; + public final Map params = new HashMap<>(); public Validator(Annotation annotation) { this.annotation = annotation; diff --git a/framework/src/play/data/validation/ValidationPlugin.java b/framework/src/play/data/validation/ValidationPlugin.java index f51c4fb1fe..bd091da234 100644 --- a/framework/src/play/data/validation/ValidationPlugin.java +++ b/framework/src/play/data/validation/ValidationPlugin.java @@ -129,7 +129,7 @@ public List validateAction(Method actionMethod) throws Exce return violations; } } - static Pattern errorsParser = Pattern.compile("\u0000([^:]*):([^\u0000]*)\u0000"); + static final Pattern errorsParser = Pattern.compile("\u0000([^:]*):([^\u0000]*)\u0000"); static Validation restore() { try { diff --git a/framework/src/play/db/Configuration.java b/framework/src/play/db/Configuration.java index ae14a04639..5adc079fce 100644 --- a/framework/src/play/db/Configuration.java +++ b/framework/src/play/db/Configuration.java @@ -21,7 +21,7 @@ public class Configuration { /** compiled regex as a pattern for reuse to filter all db related settings. */ final java.util.regex.Pattern compiledRegexDbRelatedSettings = java.util.regex.Pattern.compile(regexDbRelatedSettings +".*"); - public String configName; + public final String configName; public boolean isDefault() { return DB.DEFAULT.equals(this.configName); diff --git a/framework/src/play/db/DB.java b/framework/src/play/db/DB.java index 952c48f02a..8c2de5eaee 100644 --- a/framework/src/play/db/DB.java +++ b/framework/src/play/db/DB.java @@ -39,12 +39,12 @@ public static class ExtendedDatasource { /** * Connection to the physical data source */ - private DataSource datasource; + private final DataSource datasource; /** * The method used to destroy the data source */ - private String destroyMethod; + private final String destroyMethod; public ExtendedDatasource(DataSource ds, String destroyMethod) { this.datasource = ds; diff --git a/framework/src/play/db/DBPlugin.java b/framework/src/play/db/DBPlugin.java index 335f4ff050..31a73df31c 100644 --- a/framework/src/play/db/DBPlugin.java +++ b/framework/src/play/db/DBPlugin.java @@ -250,7 +250,7 @@ private boolean changed() { */ public static class ProxyDriver implements Driver { - private Driver driver; + private final Driver driver; ProxyDriver(Driver d) { this.driver = d; diff --git a/framework/src/play/db/Evolutions.java b/framework/src/play/db/Evolutions.java index d4f7d5d7b4..ae36fa32af 100644 --- a/framework/src/play/db/Evolutions.java +++ b/framework/src/play/db/Evolutions.java @@ -39,10 +39,11 @@ */ public class Evolutions extends PlayPlugin { - private static String EVOLUTIONS_TABLE_NAME = "play_evolutions"; - protected static File evolutionsDirectory = Play.getFile("db/evolutions"); + private static final String EVOLUTIONS_TABLE_NAME = "play_evolutions"; + private static final Map modulesWithEvolutions = new LinkedHashMap<>(); + + protected static final File evolutionsDirectory = Play.getFile("db/evolutions"); - private static Map modulesWithEvolutions = new LinkedHashMap<>(); public static void main(String[] args) throws SQLException { /** Start the DB plugin **/ diff --git a/framework/src/play/db/evolutions/Evolution.java b/framework/src/play/db/evolutions/Evolution.java index c167c4ff10..3c4c6d348a 100644 --- a/framework/src/play/db/evolutions/Evolution.java +++ b/framework/src/play/db/evolutions/Evolution.java @@ -4,13 +4,13 @@ public class Evolution implements Comparable { - public int revision; - public String sql_up; - public String sql_down; - public String hash; - public boolean applyUp; + public final int revision; + public final String sql_up; + public final String sql_down; + public final String hash; + public final boolean applyUp; - public String moduleKey; + public final String moduleKey; public Evolution(String moduleKey, int revision, String sql_up, String sql_down, boolean applyUp) { this.moduleKey = moduleKey; diff --git a/framework/src/play/db/evolutions/exceptions/InconsistentDatabase.java b/framework/src/play/db/evolutions/exceptions/InconsistentDatabase.java index 9bc23dadf6..a2faea9308 100644 --- a/framework/src/play/db/evolutions/exceptions/InconsistentDatabase.java +++ b/framework/src/play/db/evolutions/exceptions/InconsistentDatabase.java @@ -7,11 +7,11 @@ public class InconsistentDatabase extends PlayException { /** * The name of the Database concern by the exception */ - private String dbName; - private String evolutionScript; - private String error; - private int revision; - private String moduleKey; + private final String dbName; + private final String evolutionScript; + private final String error; + private final int revision; + private final String moduleKey; public InconsistentDatabase(String dbName, String evolutionScript, String error, int revision, String moduleKey) { this.dbName = dbName; diff --git a/framework/src/play/db/evolutions/exceptions/InvalidDatabaseRevision.java b/framework/src/play/db/evolutions/exceptions/InvalidDatabaseRevision.java index a88dcf247a..a952f9115d 100644 --- a/framework/src/play/db/evolutions/exceptions/InvalidDatabaseRevision.java +++ b/framework/src/play/db/evolutions/exceptions/InvalidDatabaseRevision.java @@ -8,8 +8,8 @@ public class InvalidDatabaseRevision extends PlayException { /** * The name of the Database concern by the exception */ - private String dbName; - private String evolutionScript; + private final String dbName; + private final String evolutionScript; public InvalidDatabaseRevision(String dbName, String evolutionScript) { this.dbName = dbName; diff --git a/framework/src/play/db/helper/SqlQuery.java b/framework/src/play/db/helper/SqlQuery.java index 97383ead8a..ce6adab219 100644 --- a/framework/src/play/db/helper/SqlQuery.java +++ b/framework/src/play/db/helper/SqlQuery.java @@ -5,10 +5,9 @@ public abstract class SqlQuery { - protected List params; + protected final List params = new ArrayList<>(); protected SqlQuery() { - params = new ArrayList<>(); } public SqlQuery param(Object obj) { params.add(obj); return this; } diff --git a/framework/src/play/db/jpa/JPA.java b/framework/src/play/db/jpa/JPA.java index a733ece071..d925c9ed8f 100644 --- a/framework/src/play/db/jpa/JPA.java +++ b/framework/src/play/db/jpa/JPA.java @@ -23,9 +23,9 @@ */ public class JPA { - protected static Map emfs = new ConcurrentHashMap<>(); + protected static final Map emfs = new ConcurrentHashMap<>(); public static final ThreadLocal> currentEntityManager = ThreadLocal.withInitial(ConcurrentHashMap::new); - public static String DEFAULT = "default"; + public static final String DEFAULT = "default"; public static class JPAContext { public String dbName = JPA.DEFAULT; diff --git a/framework/src/play/db/jpa/JPAModelLoader.java b/framework/src/play/db/jpa/JPAModelLoader.java index 64d60803d9..4040854404 100644 --- a/framework/src/play/db/jpa/JPAModelLoader.java +++ b/framework/src/play/db/jpa/JPAModelLoader.java @@ -36,8 +36,8 @@ public class JPAModelLoader implements Model.Factory { - private String dbName; - private Class clazz; + private final String dbName; + private final Class clazz; private Map properties; public JPAModelLoader(Class clazz) { diff --git a/framework/src/play/db/jpa/JPAPlugin.java b/framework/src/play/db/jpa/JPAPlugin.java index 627504623c..e8e08f0357 100644 --- a/framework/src/play/db/jpa/JPAPlugin.java +++ b/framework/src/play/db/jpa/JPAPlugin.java @@ -319,7 +319,7 @@ public Object withinFilter(play.libs.F.Function0 fct) throws Throwable { } } - private TransactionalFilter txFilter = new TransactionalFilter("TransactionalFilter"); + private final TransactionalFilter txFilter = new TransactionalFilter("TransactionalFilter"); @Override public Filter getFilter() { diff --git a/framework/src/play/deps/DependenciesManager.java b/framework/src/play/deps/DependenciesManager.java index 7427a31403..e5c823f68a 100644 --- a/framework/src/play/deps/DependenciesManager.java +++ b/framework/src/play/deps/DependenciesManager.java @@ -76,9 +76,9 @@ public static void main(String[] args) throws Exception { } } - File application; - File framework; - File userHome; + final File application; + final File framework; + final File userHome; HumanReadyLogger logger; final FileFilter dirsToTrim = new FileFilter() { diff --git a/framework/src/play/deps/HumanReadyLogger.java b/framework/src/play/deps/HumanReadyLogger.java index b91c7e9161..088c32988d 100644 --- a/framework/src/play/deps/HumanReadyLogger.java +++ b/framework/src/play/deps/HumanReadyLogger.java @@ -13,18 +13,18 @@ public class HumanReadyLogger implements MessageLogger, TransferListener { - Set notFound = new HashSet<>(); - Set dynamics = new HashSet<>(); - Set evicteds = new HashSet<>(); - Pattern dep = Pattern.compile("found ([^#]+)#([^;]+);([^\\s]+) in (.*)"); - Pattern depNotFound = Pattern.compile("module not found: ([^#]+)#([^;]+);([^\\s]+)"); - Pattern dynamic = Pattern.compile("\\[(.*)\\] ([^#]+)#([^;]+);([^\\s]+)"); - Pattern evicted = Pattern.compile("([^#]+)#([^;]+);([^\\s]+) by \\[([^#]+)#([^;]+);([^\\s]+)\\].*"); + final Set notFound = new HashSet<>(); + final Set dynamics = new HashSet<>(); + final Set evicteds = new HashSet<>(); + final Pattern dep = Pattern.compile("found ([^#]+)#([^;]+);([^\\s]+) in (.*)"); + final Pattern depNotFound = Pattern.compile("module not found: ([^#]+)#([^;]+);([^\\s]+)"); + final Pattern dynamic = Pattern.compile("\\[(.*)\\] ([^#]+)#([^;]+);([^\\s]+)"); + final Pattern evicted = Pattern.compile("([^#]+)#([^;]+);([^\\s]+) by \\[([^#]+)#([^;]+);([^\\s]+)\\].*"); + final String[] progressBar = {". ", ".. ", "...", " "}; String downloading = null; long length = 0; int progress = 0; long lastTime = System.currentTimeMillis(); - String[] progressBar = new String[]{". ", ".. ", "...", " "}; public void niceLog(String msg, int level) { try { diff --git a/framework/src/play/deps/PlayConflictManager.java b/framework/src/play/deps/PlayConflictManager.java index b70fcbc8ff..61b1fd77a2 100644 --- a/framework/src/play/deps/PlayConflictManager.java +++ b/framework/src/play/deps/PlayConflictManager.java @@ -15,7 +15,7 @@ public class PlayConflictManager extends AbstractConflictManager { - public LatestConflictManager delegate = new LatestConflictManager(new LatestRevisionStrategy()); + public final LatestConflictManager delegate = new LatestConflictManager(new LatestRevisionStrategy()); @Override public Collection resolveConflicts(IvyNode in, Collection conflictsUntyped) { diff --git a/framework/src/play/deps/YamlParser.java b/framework/src/play/deps/YamlParser.java index 4031b08a0a..1a5e39b5e7 100644 --- a/framework/src/play/deps/YamlParser.java +++ b/framework/src/play/deps/YamlParser.java @@ -367,7 +367,7 @@ private static String filterModuleName(ModuleRevisionId rev) { } private static class ModuleFilter implements FilenameFilter { - private ModuleRevisionId moduleRevision; + private final ModuleRevisionId moduleRevision; public ModuleFilter(ModuleRevisionId moduleRevision) { this.moduleRevision = moduleRevision; diff --git a/framework/src/play/exceptions/ActionNotFoundException.java b/framework/src/play/exceptions/ActionNotFoundException.java index 353461a1b8..a358c65dbf 100644 --- a/framework/src/play/exceptions/ActionNotFoundException.java +++ b/framework/src/play/exceptions/ActionNotFoundException.java @@ -2,7 +2,7 @@ public class ActionNotFoundException extends PlayException { - private String action; + private final String action; public ActionNotFoundException(String action, Throwable cause) { super(String.format("Action %s not found", action.startsWith("controllers.") ? action.substring(12) : action), cause); diff --git a/framework/src/play/exceptions/CompilationException.java b/framework/src/play/exceptions/CompilationException.java index be74498742..d2fb98be41 100644 --- a/framework/src/play/exceptions/CompilationException.java +++ b/framework/src/play/exceptions/CompilationException.java @@ -9,7 +9,7 @@ */ public class CompilationException extends PlayException implements SourceAttachment { - private String problem; + private final String problem; private VirtualFile source; private Integer line; private Integer start; diff --git a/framework/src/play/exceptions/PlayException.java b/framework/src/play/exceptions/PlayException.java index 65bb7ab638..fe679e5efe 100644 --- a/framework/src/play/exceptions/PlayException.java +++ b/framework/src/play/exceptions/PlayException.java @@ -9,7 +9,7 @@ */ public abstract class PlayException extends RuntimeException { - private static AtomicLong atomicLong = new AtomicLong(System.currentTimeMillis()); + private static final AtomicLong atomicLong = new AtomicLong(System.currentTimeMillis()); private String id; public PlayException() { diff --git a/framework/src/play/exceptions/TemplateException.java b/framework/src/play/exceptions/TemplateException.java index 5c26db5285..7e0aafc7e9 100644 --- a/framework/src/play/exceptions/TemplateException.java +++ b/framework/src/play/exceptions/TemplateException.java @@ -9,8 +9,8 @@ */ public abstract class TemplateException extends PlayException implements SourceAttachment { - private Template template; - private Integer lineNumber; + private final Template template; + private final Integer lineNumber; public TemplateException(Template template, Integer lineNumber, String message) { super(message); diff --git a/framework/src/play/exceptions/TemplateNotFoundException.java b/framework/src/play/exceptions/TemplateNotFoundException.java index 629244044b..5fbaaf2ec0 100644 --- a/framework/src/play/exceptions/TemplateNotFoundException.java +++ b/framework/src/play/exceptions/TemplateNotFoundException.java @@ -8,7 +8,7 @@ public class TemplateNotFoundException extends PlayException implements SourceAttachment { - private String path; + private final String path; private String sourceFile; private List source; private Integer line; diff --git a/framework/src/play/exceptions/YAMLException.java b/framework/src/play/exceptions/YAMLException.java index 7179d8a98f..c294cfb6ff 100644 --- a/framework/src/play/exceptions/YAMLException.java +++ b/framework/src/play/exceptions/YAMLException.java @@ -7,8 +7,8 @@ public class YAMLException extends PlayException implements SourceAttachment { - ScannerException e; - VirtualFile yaml; + final ScannerException e; + final VirtualFile yaml; public YAMLException(ScannerException e, VirtualFile yaml) { super(e.getMessage() + " (in file " + yaml.relativePath() + " line " + (e.getProblemMark().getLine() + 1) + ", column " + (e.getProblemMark().getColumn() + 1) + ")", e); diff --git a/framework/src/play/i18n/Lang.java b/framework/src/play/i18n/Lang.java index 7e02aed994..6c174bd948 100644 --- a/framework/src/play/i18n/Lang.java +++ b/framework/src/play/i18n/Lang.java @@ -16,7 +16,7 @@ public class Lang { static final ThreadLocal current = new ThreadLocal<>(); - private static Map cache = new HashMap<>(); + private static final Map cache = new HashMap<>(); /** * Retrieve the current language or null diff --git a/framework/src/play/i18n/Localized.java b/framework/src/play/i18n/Localized.java index 4ca6f5392f..1186b38070 100644 --- a/framework/src/play/i18n/Localized.java +++ b/framework/src/play/i18n/Localized.java @@ -10,7 +10,7 @@ */ public class Localized { - private Map values = new HashMap<>(); + private final Map values = new HashMap<>(); public void set(T value) { this.values.put(Lang.get(), value); diff --git a/framework/src/play/i18n/Messages.java b/framework/src/play/i18n/Messages.java index 6688deaf29..7123a6bda6 100644 --- a/framework/src/play/i18n/Messages.java +++ b/framework/src/play/i18n/Messages.java @@ -34,7 +34,7 @@ public class Messages { public static Properties defaults = new Properties(); - public static Map locales = new HashMap<>(); + public static final Map locales = new HashMap<>(); private static final Pattern recursive = Pattern.compile("&\\{(.*?)\\}"); @@ -133,7 +133,7 @@ public static String formatString(Locale locale, String value, Object... args) { return sb.toString(); } - static Pattern formatterPattern = Pattern.compile("%((\\d+)\\$)?([-#+ 0,(]+)?(\\d+)?([.]\\d+)?([bBhHsScCdoxXeEfgGaAtT])"); + static final Pattern formatterPattern = Pattern.compile("%((\\d+)\\$)?([-#+ 0,(]+)?(\\d+)?([.]\\d+)?([bBhHsScCdoxXeEfgGaAtT])"); @SuppressWarnings("unchecked") static Object[] coolStuff(String pattern, Object[] args) { diff --git a/framework/src/play/i18n/MessagesPlugin.java b/framework/src/play/i18n/MessagesPlugin.java index e79ce8f28e..6108190a3f 100644 --- a/framework/src/play/i18n/MessagesPlugin.java +++ b/framework/src/play/i18n/MessagesPlugin.java @@ -23,7 +23,7 @@ public class MessagesPlugin extends PlayPlugin { static Long lastLoading = 0L; - private static List includeMessageFilenames = new ArrayList<>(); + private static final List includeMessageFilenames = new ArrayList<>(); @Override public void onApplicationStart() { diff --git a/framework/src/play/jobs/JobsPlugin.java b/framework/src/play/jobs/JobsPlugin.java index 93bfe33044..b6da2a55f6 100644 --- a/framework/src/play/jobs/JobsPlugin.java +++ b/framework/src/play/jobs/JobsPlugin.java @@ -25,7 +25,7 @@ public class JobsPlugin extends PlayPlugin { public static ScheduledThreadPoolExecutor executor; - public static List scheduledJobs = new ArrayList<>(); + public static final List scheduledJobs = new ArrayList<>(); private static final ThreadLocal>> afterInvocationActions = new ThreadLocal<>(); @Override diff --git a/framework/src/play/libs/Crypto.java b/framework/src/play/libs/Crypto.java index 10873c0df5..4a0059fce2 100644 --- a/framework/src/play/libs/Crypto.java +++ b/framework/src/play/libs/Crypto.java @@ -24,7 +24,7 @@ public class Crypto { */ public enum HashType { MD5("MD5"), SHA1("SHA-1"), SHA256("SHA-256"), SHA512("SHA-512"); - private String algorithm; + private final String algorithm; HashType(String algorithm) { this.algorithm = algorithm; diff --git a/framework/src/play/libs/Expression.java b/framework/src/play/libs/Expression.java index 5f60e76163..abeff1fa38 100644 --- a/framework/src/play/libs/Expression.java +++ b/framework/src/play/libs/Expression.java @@ -28,7 +28,7 @@ public class Expression { - static Pattern expression = Pattern.compile("^\\$\\{(.*)\\}$"); + static final Pattern expression = Pattern.compile("^\\$\\{(.*)\\}$"); public static Object evaluate(String value, String defaultValue) { Matcher matcher = expression.matcher(value); diff --git a/framework/src/play/libs/Images.java b/framework/src/play/libs/Images.java index fa501f2255..3f7013a098 100644 --- a/framework/src/play/libs/Images.java +++ b/framework/src/play/libs/Images.java @@ -234,11 +234,11 @@ public static Captcha captcha() { */ public static class Captcha extends InputStream { + public final GimpyRenderer gimpy = new RippleGimpyRenderer(); + public final List fonts = new ArrayList<>(2); public String text = null; public BackgroundProducer background = new TransparentBackgroundProducer(); - public GimpyRenderer gimpy = new RippleGimpyRenderer(); public Color textColor = Color.BLACK; - public List fonts = new ArrayList<>(2); public int w, h; public Color noise = null; diff --git a/framework/src/play/libs/Mail.java b/framework/src/play/libs/Mail.java index 146083621e..5eff4b485d 100644 --- a/framework/src/play/libs/Mail.java +++ b/framework/src/play/libs/Mail.java @@ -243,12 +243,12 @@ public Boolean get(long timeout, TimeUnit unit) { } } - static ExecutorService executor = Executors.newCachedThreadPool(); + static final ExecutorService executor = Executors.newCachedThreadPool(); public static class SMTPAuthenticator extends Authenticator { - private String user; - private String password; + private final String user; + private final String password; public SMTPAuthenticator(String user, String password) { this.user = user; diff --git a/framework/src/play/libs/MimeTypes.java b/framework/src/play/libs/MimeTypes.java index 1ebcab8fd9..9e653c1dca 100644 --- a/framework/src/play/libs/MimeTypes.java +++ b/framework/src/play/libs/MimeTypes.java @@ -18,11 +18,7 @@ public class MimeTypes { private static Properties mimetypes = null; - private static Pattern extPattern; - - static { - extPattern = Pattern.compile("^.*\\.([^.]+)$"); - } + private static final Pattern extPattern = Pattern.compile("^.*\\.([^.]+)$"); /** * return the mimetype from a file name diff --git a/framework/src/play/libs/OAuth.java b/framework/src/play/libs/OAuth.java index 59444626f7..e9876b2058 100644 --- a/framework/src/play/libs/OAuth.java +++ b/framework/src/play/libs/OAuth.java @@ -18,8 +18,8 @@ */ public class OAuth { - private ServiceInfo info; - private OAuthProvider provider; + private final ServiceInfo info; + private final OAuthProvider provider; private OAuth(ServiceInfo info) { this.info = info; @@ -139,11 +139,11 @@ public String redirectUrl(TokenPair tokenPair) { * */ public static class ServiceInfo { - public String requestTokenURL; - public String accessTokenURL; - public String authorizationURL; - public String consumerKey; - public String consumerSecret; + public final String requestTokenURL; + public final String accessTokenURL; + public final String authorizationURL; + public final String consumerKey; + public final String consumerSecret; public ServiceInfo(String requestTokenURL, String accessTokenURL, String authorizationURL, String consumerKey, String consumerSecret) { @@ -229,8 +229,8 @@ public String toString() { @Deprecated public static class TokenPair { - public String token; - public String secret; + public final String token; + public final String secret; public TokenPair(String token, String secret) { this.token = token; diff --git a/framework/src/play/libs/OAuth2.java b/framework/src/play/libs/OAuth2.java index 85944c9028..355c9f14b8 100644 --- a/framework/src/play/libs/OAuth2.java +++ b/framework/src/play/libs/OAuth2.java @@ -20,10 +20,10 @@ public class OAuth2 { private static final String CLIENT_ID_NAME = "client_id"; private static final String REDIRECT_URI = "redirect_uri"; - public String authorizationURL; - public String accessTokenURL; - public String clientid; - public String secret; + public final String authorizationURL; + public final String accessTokenURL; + public final String clientid; + public final String secret; public OAuth2(String authorizationURL, String accessTokenURL, String clientid, String secret) { this.accessTokenURL = accessTokenURL; diff --git a/framework/src/play/libs/OpenID.java b/framework/src/play/libs/OpenID.java index 358172aebb..80f5d3b247 100644 --- a/framework/src/play/libs/OpenID.java +++ b/framework/src/play/libs/OpenID.java @@ -33,13 +33,13 @@ private OpenID(String id) { } // ~~~ API - String id; + final List sregRequired = new ArrayList<>(); + final List sregOptional = new ArrayList<>(); + final Map axRequired = new HashMap<>(); + final Map axOptional = new HashMap<>(); + final String id; String returnAction; String realmAction; - List sregRequired = new ArrayList<>(); - List sregOptional = new ArrayList<>(); - Map axRequired = new HashMap<>(); - Map axOptional = new HashMap<>(); public OpenID returnTo(String action) { this.returnAction = action; @@ -359,7 +359,7 @@ public static class UserInfo { /** * Extensions values */ - public Map extensions = new HashMap<>(); + public final Map extensions = new HashMap<>(); @Override public String toString() { diff --git a/framework/src/play/libs/WS.java b/framework/src/play/libs/WS.java index 5cc8043338..f9af9d49fb 100644 --- a/framework/src/play/libs/WS.java +++ b/framework/src/play/libs/WS.java @@ -667,8 +667,8 @@ protected String createQueryString() { } public static class FileParam { - public File file; - public String paramName; + public final File file; + public final String paramName; public FileParam(File file, String name) { this.file = file; diff --git a/framework/src/play/libs/mail/test/LegacyMockMailSystem.java b/framework/src/play/libs/mail/test/LegacyMockMailSystem.java index 77c4c6921a..9a4e28da04 100644 --- a/framework/src/play/libs/mail/test/LegacyMockMailSystem.java +++ b/framework/src/play/libs/mail/test/LegacyMockMailSystem.java @@ -27,7 +27,7 @@ public class LegacyMockMailSystem implements MailSystem { // Has to remain static to preserve the possibility of testing mail sending within Selenium tests - static Map emails = new HashMap<>(); + static final Map emails = new HashMap<>(); @Override public Future sendMessage(Email email) { diff --git a/framework/src/play/mvc/CookieDataCodec.java b/framework/src/play/mvc/CookieDataCodec.java index eb220728e7..e5cdda1fcf 100644 --- a/framework/src/play/mvc/CookieDataCodec.java +++ b/framework/src/play/mvc/CookieDataCodec.java @@ -20,7 +20,7 @@ public class CookieDataCodec { * applications are upgraded to a newer version of Play *

*/ - public static Pattern oldCookieSessionParser = Pattern.compile("\u0000([^:]*):([^\u0000]*)\u0000"); + public static final Pattern oldCookieSessionParser = Pattern.compile("\u0000([^:]*):([^\u0000]*)\u0000"); /** * @param map diff --git a/framework/src/play/mvc/Http.java b/framework/src/play/mvc/Http.java index a1a02f0c25..b2004c07f5 100644 --- a/framework/src/play/mvc/Http.java +++ b/framework/src/play/mvc/Http.java @@ -268,7 +268,7 @@ public static class Request implements Serializable { /** * Free space to store your request specific data */ - public Map args = new HashMap<>(16); + public final Map args = new HashMap<>(16); /** * When the request has been received */ @@ -621,11 +621,11 @@ public static class Response { /** * Response headers */ - public Map headers = new HashMap<>(16); + public final Map headers = new HashMap<>(16); /** * Response cookies */ - public Map cookies = new HashMap<>(16); + public final Map cookies = new HashMap<>(16); /** * Response body stream */ diff --git a/framework/src/play/mvc/Router.java b/framework/src/play/mvc/Router.java index dea0a61e8c..8c81936faa 100644 --- a/framework/src/play/mvc/Router.java +++ b/framework/src/play/mvc/Router.java @@ -28,12 +28,12 @@ */ public class Router { - static Pattern routePattern = new Pattern( + static final Pattern routePattern = new Pattern( "^({method}GET|POST|PUT|PATCH|DELETE|OPTIONS|HEAD|WS|\\*)[(]?({headers}[^)]*)(\\))?\\s+({path}.*/[^\\s]*)\\s+({action}[^\\s(]+)({params}.+)?(\\s*)$"); /** * Pattern used to locate a method override instruction in request.querystring */ - static Pattern methodOverride = new Pattern("^.*x-http-method-override=({method}GET|PUT|POST|PATCH|DELETE).*$"); + static final Pattern methodOverride = new Pattern("^.*x-http-method-override=({method}GET|PUT|POST|PATCH|DELETE).*$"); /** * Timestamp the routes file was last loaded at. */ @@ -341,7 +341,7 @@ public static void detectChanges(String prefix) { /** * All the loaded routes. */ - public static List routes = new CopyOnWriteArrayList<>(); + public static final List routes = new CopyOnWriteArrayList<>(); public static void routeOnlyStatic(Http.Request request) { for (Route route : routes) { @@ -714,8 +714,8 @@ private static List findActionRoutes(String action) { } private static final class ActionRoute { + private final Map args = new HashMap<>(2); private Route route; - private Map args = new HashMap<>(2); } public static class ActionDefinition { @@ -828,9 +828,9 @@ public static class Route { Arg hostArg = null; public int routesFileLine; public String routesFile; - static Pattern customRegexPattern = new Pattern("\\{([a-zA-Z_][a-zA-Z_0-9]*)\\}"); - static Pattern argsPattern = new Pattern("\\{<([^>]+)>([a-zA-Z_0-9]+)\\}"); - static Pattern paramPattern = new Pattern("([a-zA-Z_0-9]+):'(.*)'"); + static final Pattern customRegexPattern = new Pattern("\\{([a-zA-Z_][a-zA-Z_0-9]*)\\}"); + static final Pattern argsPattern = new Pattern("\\{<([^>]+)>([a-zA-Z_0-9]+)\\}"); + static final Pattern paramPattern = new Pattern("([a-zA-Z_0-9]+):'(.*)'"); public void compute() { this.host = ""; diff --git a/framework/src/play/mvc/Scope.java b/framework/src/play/mvc/Scope.java index b7c53908d0..de11721d80 100644 --- a/framework/src/play/mvc/Scope.java +++ b/framework/src/play/mvc/Scope.java @@ -33,7 +33,7 @@ public class Scope { public static boolean SESSION_SEND_ONLY_IF_CHANGED = Play.configuration .getProperty("application.session.sendOnlyIfChanged", "false").toLowerCase().equals("true"); - public static SessionStore sessionStore = createSessionStore(); + public static final SessionStore sessionStore = createSessionStore(); private static SessionStore createSessionStore() { String sessionStoreClass = Play.configuration.getProperty("application.session.storeClass"); @@ -55,8 +55,8 @@ private static SessionStore createSessionStore() { */ public static class Flash { - Map data = new HashMap<>(); - Map out = new HashMap<>(); + final Map data = new HashMap<>(); + final Map out = new HashMap<>(); public static Flash restore() { try { @@ -179,7 +179,7 @@ public static Session restore() { return sessionStore.restore(); } - Map data = new HashMap<>(); // ThreadLocal access + final Map data = new HashMap<>(); // ThreadLocal access boolean changed = false; public static final ThreadLocal current = new ThreadLocal<>(); @@ -292,7 +292,7 @@ public static Params current() { } boolean requestIsParsed; - public Map data = new LinkedHashMap<>(); + public final Map data = new LinkedHashMap<>(); boolean rootParamsNodeIsGenerated = false; private RootParamNode rootParamNode = null; @@ -519,7 +519,7 @@ public String toString() { */ public static class RenderArgs { - public Map data = new HashMap<>(); // ThreadLocal access + public final Map data = new HashMap<>(); // ThreadLocal access public static final ThreadLocal current = new ThreadLocal<>(); public static RenderArgs current() { @@ -550,7 +550,7 @@ public String toString() { */ public static class RouteArgs { - public Map data = new HashMap<>(); // ThreadLocal access + public final Map data = new HashMap<>(); // ThreadLocal access public static final ThreadLocal current = new ThreadLocal<>(); public static RouteArgs current() { diff --git a/framework/src/play/plugins/PluginCollection.java b/framework/src/play/plugins/PluginCollection.java index 1cefe15153..f6d8b919bc 100644 --- a/framework/src/play/plugins/PluginCollection.java +++ b/framework/src/play/plugins/PluginCollection.java @@ -56,7 +56,7 @@ public class PluginCollection { /** * List that holds all loaded plugins, enabled or disabled */ - protected List allPlugins = new ArrayList<>(); + protected final List allPlugins = new ArrayList<>(); /** * Readonly copy of allPlugins - updated each time allPlugins is updated. Using this cached copy so we don't have to @@ -67,7 +67,7 @@ public class PluginCollection { /** * List of all enabled plugins */ - protected List enabledPlugins = new ArrayList<>(); + protected final List enabledPlugins = new ArrayList<>(); /** * Readonly copy of enabledPlugins - updated each time enabledPlugins is updated. Using this cached copy so we don't @@ -78,7 +78,7 @@ public class PluginCollection { /** * List of all enabled plugins with filters */ - protected List enabledPluginsWithFilters = new ArrayList<>(); + protected final List enabledPluginsWithFilters = new ArrayList<>(); /** * Readonly copy of enabledPluginsWithFilters - updated each time enabledPluginsWithFilters is updated. Using this diff --git a/framework/src/play/server/FileService.java b/framework/src/play/server/FileService.java index 1213e9ebb1..9b94575527 100644 --- a/framework/src/play/server/FileService.java +++ b/framework/src/play/server/FileService.java @@ -273,9 +273,9 @@ private static String makeRangeBodyHeader(String separator, String contentType, } private class ByteRange { - public long start; - public long end; - public byte[] header; + public final long start; + public final long end; + public final byte[] header; public long length() { return end - start + 1; diff --git a/framework/src/play/server/HttpServerPipelineFactory.java b/framework/src/play/server/HttpServerPipelineFactory.java index 69c2bb2cba..ca006c307c 100644 --- a/framework/src/play/server/HttpServerPipelineFactory.java +++ b/framework/src/play/server/HttpServerPipelineFactory.java @@ -14,9 +14,9 @@ public class HttpServerPipelineFactory implements ChannelPipelineFactory { - private String pipelineConfig = Play.configuration.getProperty("play.netty.pipeline", "play.server.FlashPolicyHandler,org.jboss.netty.handler.codec.http.HttpRequestDecoder,play.server.StreamChunkAggregator,org.jboss.netty.handler.codec.http.HttpResponseEncoder,org.jboss.netty.handler.stream.ChunkedWriteHandler,play.server.PlayHandler"); + protected static final Map classes = new HashMap<>(); - protected static Map classes = new HashMap<>(); + private final String pipelineConfig = Play.configuration.getProperty("play.netty.pipeline", "play.server.FlashPolicyHandler,org.jboss.netty.handler.codec.http.HttpRequestDecoder,play.server.StreamChunkAggregator,org.jboss.netty.handler.codec.http.HttpResponseEncoder,org.jboss.netty.handler.stream.ChunkedWriteHandler,play.server.PlayHandler"); @Override public ChannelPipeline getPipeline() throws Exception { diff --git a/framework/src/play/server/PlayHandler.java b/framework/src/play/server/PlayHandler.java index 989b3c48d8..95d881348e 100644 --- a/framework/src/play/server/PlayHandler.java +++ b/framework/src/play/server/PlayHandler.java @@ -76,7 +76,7 @@ public class PlayHandler extends SimpleChannelUpstreamHandler { /** * The Pipeline is given for a PlayHandler */ - public Map pipelines = new HashMap<>(); + public final Map pipelines = new HashMap<>(); private WebSocketServerHandshaker handshaker; @@ -965,8 +965,8 @@ public static void setContentLength(HttpMessage message, long contentLength) { static class LazyChunkedInput implements org.jboss.netty.handler.stream.ChunkedInput { + private final ConcurrentLinkedQueue nextChunks = new ConcurrentLinkedQueue<>(); private boolean closed = false; - private ConcurrentLinkedQueue nextChunks = new ConcurrentLinkedQueue<>(); @Override public boolean hasNextChunk() throws Exception { diff --git a/framework/src/play/server/ServletWrapper.java b/framework/src/play/server/ServletWrapper.java index 9a95315481..83bc9028f8 100644 --- a/framework/src/play/server/ServletWrapper.java +++ b/framework/src/play/server/ServletWrapper.java @@ -510,10 +510,10 @@ private void copyStream(HttpServletResponse servletResponse, InputStream is) thr public class ServletInvocation extends Invoker.DirectInvocation { - private Request request; - private Response response; - private HttpServletRequest httpServletRequest; - private HttpServletResponse httpServletResponse; + private final Request request; + private final Response response; + private final HttpServletRequest httpServletRequest; + private final HttpServletResponse httpServletResponse; public ServletInvocation(Request request, Response response, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) { this.httpServletRequest = httpServletRequest; diff --git a/framework/src/play/server/ssl/SslHttpServerContextFactory.java b/framework/src/play/server/ssl/SslHttpServerContextFactory.java index b4da404886..9146bd26c7 100644 --- a/framework/src/play/server/ssl/SslHttpServerContextFactory.java +++ b/framework/src/play/server/ssl/SslHttpServerContextFactory.java @@ -80,7 +80,7 @@ public static SSLContext getServerContext() { public static class PEMKeyManager extends X509ExtendedKeyManager { - static PEMKeyManager instance = new PEMKeyManager(); + static final PEMKeyManager instance = new PEMKeyManager(); PrivateKey key; X509Certificate[] chain; diff --git a/framework/src/play/server/ssl/SslHttpServerPipelineFactory.java b/framework/src/play/server/ssl/SslHttpServerPipelineFactory.java index 295d6643e0..f622a9295c 100644 --- a/framework/src/play/server/ssl/SslHttpServerPipelineFactory.java +++ b/framework/src/play/server/ssl/SslHttpServerPipelineFactory.java @@ -14,7 +14,7 @@ public class SslHttpServerPipelineFactory extends HttpServerPipelineFactory { - private String pipelineConfig = Play.configuration.getProperty("play.ssl.netty.pipeline", + private final String pipelineConfig = Play.configuration.getProperty("play.ssl.netty.pipeline", "play.server.FlashPolicyHandler,org.jboss.netty.handler.codec.http.HttpRequestDecoder,play.server.StreamChunkAggregator,org.jboss.netty.handler.codec.http.HttpResponseEncoder,org.jboss.netty.handler.stream.ChunkedWriteHandler,play.server.ssl.SslPlayHandler"); @Override diff --git a/framework/src/play/templates/BaseTemplate.java b/framework/src/play/templates/BaseTemplate.java index dae9a543c0..7b3e4fd0e0 100644 --- a/framework/src/play/templates/BaseTemplate.java +++ b/framework/src/play/templates/BaseTemplate.java @@ -18,12 +18,12 @@ public abstract class BaseTemplate extends Template { + public final Long timestamp = System.currentTimeMillis(); public String compiledSource; public Map linesMatrix = new HashMap<>(); public Set doBodyLines = new HashSet<>(); public Class compiledTemplate; public String compiledTemplateName; - public Long timestamp = System.currentTimeMillis(); public BaseTemplate(String name, String source) { this.name = name; @@ -97,7 +97,7 @@ void throwException(Throwable e) { public static final class RawData { - public String data; + public final String data; public RawData(Object val) { if (val == null) { diff --git a/framework/src/play/templates/GroovyTemplateCompiler.java b/framework/src/play/templates/GroovyTemplateCompiler.java index 41e9234beb..8e08348dbd 100644 --- a/framework/src/play/templates/GroovyTemplateCompiler.java +++ b/framework/src/play/templates/GroovyTemplateCompiler.java @@ -17,7 +17,7 @@ public class GroovyTemplateCompiler extends TemplateCompiler { - protected List extensionsClassnames = new ArrayList<>(); + protected final List extensionsClassnames = new ArrayList<>(); // [#714] The groovy-compiler complaints if a line is more than 65535 unicode units long.. // Have to split it if it is really that big diff --git a/framework/src/play/templates/TagContext.java b/framework/src/play/templates/TagContext.java index 4b2177aaf4..7793b6ab00 100644 --- a/framework/src/play/templates/TagContext.java +++ b/framework/src/play/templates/TagContext.java @@ -11,8 +11,8 @@ public class TagContext { private static final ThreadLocal> currentStack = new ThreadLocal<>(); - public String tagName; - public Map data = new HashMap<>(); + public final String tagName; + public final Map data = new HashMap<>(); public TagContext(String tagName) { this.tagName = tagName; diff --git a/framework/src/play/templates/TemplateCompiler.java b/framework/src/play/templates/TemplateCompiler.java index c8e6d7d2cd..be77c23ed7 100644 --- a/framework/src/play/templates/TemplateCompiler.java +++ b/framework/src/play/templates/TemplateCompiler.java @@ -28,12 +28,12 @@ public BaseTemplate compile(VirtualFile file) { return compile(new GroovyTemplate(file.relativePath(), file.contentAsString())); } - protected StringBuilder compiledSource = new StringBuilder(); + protected final StringBuilder compiledSource = new StringBuilder(); + protected final Stack tagsStack = new Stack<>(); protected BaseTemplate template; protected TemplateParser parser; protected boolean doNextScan = true; protected TemplateParser.Token state; - protected Stack tagsStack = new Stack<>(); protected int tagIndex; protected boolean skipLineBreak; protected int currentLine = 1; diff --git a/framework/src/play/templates/TemplateLoader.java b/framework/src/play/templates/TemplateLoader.java index 0982b25ad2..8a3c6b4582 100644 --- a/framework/src/play/templates/TemplateLoader.java +++ b/framework/src/play/templates/TemplateLoader.java @@ -17,12 +17,12 @@ public class TemplateLoader { - protected static Map templates = new HashMap<>(); + protected static final Map templates = new HashMap<>(); /** * See getUniqueNumberForTemplateFile() for more info */ - private static AtomicLong nextUniqueNumber = new AtomicLong(1000);// we start on 1000 - private static Map templateFile2UniqueNumber = Collections.synchronizedMap(new HashMap()); + private static final AtomicLong nextUniqueNumber = new AtomicLong(1000);// we start on 1000 + private static final Map templateFile2UniqueNumber = Collections.synchronizedMap(new HashMap()); /** * All loaded templates is cached in the templates-list using a key. This key is included as part of the classname diff --git a/framework/src/play/templates/TemplateParser.java b/framework/src/play/templates/TemplateParser.java index f5cf13298f..682dedb66b 100644 --- a/framework/src/play/templates/TemplateParser.java +++ b/framework/src/play/templates/TemplateParser.java @@ -5,7 +5,7 @@ */ public class TemplateParser { - private String pageSource; + private final String pageSource; private int nestedBracesCounter; // counts nested braces in current expression/tag public TemplateParser(String pageSource) { diff --git a/framework/src/play/test/Fixtures.java b/framework/src/play/test/Fixtures.java index e115c4b9b2..dfaee51de6 100644 --- a/framework/src/play/test/Fixtures.java +++ b/framework/src/play/test/Fixtures.java @@ -60,9 +60,9 @@ public class Fixtures { */ public static final String PROFILE_NAME = "Fixtures"; - static Pattern keyPattern = Pattern.compile("([^(]+)\\(([^)]+)\\)"); + static final Pattern keyPattern = Pattern.compile("([^(]+)\\(([^)]+)\\)"); // Allows people to clear the cache, so Fixture is not stateful - public static Map idCache = new HashMap<>(); + public static final Map idCache = new HashMap<>(); public static void executeSQL(String sqlScript) { for (CharSequence sql : new SQLSplitter(sqlScript)) { @@ -138,7 +138,7 @@ public static void deleteAll() { deleteDatabase(); } - static String[] dontDeleteTheseTables = new String[] { "play_evolutions" }; + static final String[] dontDeleteTheseTables = { "play_evolutions" }; /** * Flush the entire JDBC database diff --git a/framework/src/play/test/FunctionalTest.java b/framework/src/play/test/FunctionalTest.java index 330d5ff08e..53e3825f36 100644 --- a/framework/src/play/test/FunctionalTest.java +++ b/framework/src/play/test/FunctionalTest.java @@ -53,7 +53,7 @@ public abstract class FunctionalTest extends BaseTest { private static Map savedCookies; // cookies stored // between calls - private static Map renderArgs = new HashMap<>(); + private static final Map renderArgs = new HashMap<>(); @Before public void clearCookies() { @@ -626,7 +626,7 @@ protected static URL reverse() { public static class URL { - ActionDefinition actionDefinition; + final ActionDefinition actionDefinition; URL(ActionDefinition actionDefinition) { this.actionDefinition = actionDefinition; diff --git a/framework/src/play/test/Helpers.java b/framework/src/play/test/Helpers.java index 08361646c8..a1b6a5fee2 100644 --- a/framework/src/play/test/Helpers.java +++ b/framework/src/play/test/Helpers.java @@ -5,7 +5,7 @@ public class Helpers { - static Pattern pattern = Pattern.compile("^(\\w+)\\(\\s*(?:('(?:\\\\'|[^'])*'|[^.]+?)\\s*(?:,\\s*('(?:\\\\'|[^'])*'|[^.]+?)\\s*)?)?\\)$"); + static final Pattern pattern = Pattern.compile("^(\\w+)\\(\\s*(?:('(?:\\\\'|[^'])*'|[^.]+?)\\s*(?:,\\s*('(?:\\\\'|[^'])*'|[^.]+?)\\s*)?)?\\)$"); public static String[] seleniumCommand(String command) { Matcher matcher = pattern.matcher(command.trim()); diff --git a/framework/src/play/test/TestEngine.java b/framework/src/play/test/TestEngine.java index 2c0623ae62..f76bdcdb73 100644 --- a/framework/src/play/test/TestEngine.java +++ b/framework/src/play/test/TestEngine.java @@ -39,7 +39,7 @@ public int compare(Class aClass, Class bClass) { private static final ClassNameComparator classNameComparator = new ClassNameComparator(); - public static ExecutorService functionalTestsExecutor = Executors.newSingleThreadExecutor(); + public static final ExecutorService functionalTestsExecutor = Executors.newSingleThreadExecutor(); public static List allUnitTests() { List classes = new ArrayList<>(); @@ -197,9 +197,9 @@ public static TestResults run(String name) { // ~~~~~~ Run listener static class Listener extends RunListener { - TestResults results; + final TestResults results; + final String className; TestResult current; - String className; public Listener(String className, TestResults results) { this.results = results; diff --git a/framework/src/play/utils/Default.java b/framework/src/play/utils/Default.java index 74bab120f5..0942879f91 100644 --- a/framework/src/play/utils/Default.java +++ b/framework/src/play/utils/Default.java @@ -2,7 +2,7 @@ public class Default { - Object o; + final Object o; public Default(Object o) { this.o = o; diff --git a/framework/src/play/utils/Java.java b/framework/src/play/utils/Java.java index d718777d34..d46d935fa0 100644 --- a/framework/src/play/utils/Java.java +++ b/framework/src/play/utils/Java.java @@ -316,7 +316,7 @@ public static void findAllFields(Class clazz, Set found) { } /** cache */ - private static Map wrappers = new HashMap<>(); + private static final Map wrappers = new HashMap<>(); public static FieldWrapper getFieldWrapper(Field field) { if (wrappers.get(field) == null) { diff --git a/framework/src/play/utils/SmartFuture.java b/framework/src/play/utils/SmartFuture.java index bed603982a..a6e86246ba 100644 --- a/framework/src/play/utils/SmartFuture.java +++ b/framework/src/play/utils/SmartFuture.java @@ -42,7 +42,7 @@ public V get(long timeout, TimeUnit unit) throws InterruptedException, Execution // Callbacks - private List> callbacks = new ArrayList<>(); + private final List> callbacks = new ArrayList<>(); private boolean invoked = false; private V result = null; diff --git a/framework/src/play/utils/Utils.java b/framework/src/play/utils/Utils.java index fd2aefffb6..a5b0f7ba84 100644 --- a/framework/src/play/utils/Utils.java +++ b/framework/src/play/utils/Utils.java @@ -175,11 +175,10 @@ public static void kill(String pid) throws Exception { public static class AlternativeDateFormat { - Locale locale; - List formats = new ArrayList<>(); + final List formats = new ArrayList<>(); + final Locale locale; public AlternativeDateFormat(Locale locale, String... alternativeFormats) { - super(); this.locale = locale; setFormats(alternativeFormats); } diff --git a/framework/src/play/vfs/VirtualFile.java b/framework/src/play/vfs/VirtualFile.java index 8cb4096287..95d55084e6 100644 --- a/framework/src/play/vfs/VirtualFile.java +++ b/framework/src/play/vfs/VirtualFile.java @@ -30,7 +30,7 @@ */ public class VirtualFile { - File realFile; + final File realFile; VirtualFile(File file) { this.realFile = file; From 07e954e90af6292927617ee3c8f58e7bd1b09bad Mon Sep 17 00:00:00 2001 From: aleksandy Date: Sat, 23 Apr 2022 12:28:49 +0600 Subject: [PATCH 08/22] cleanup code * remove unused constant * simplify if expression --- .../src/play/classloading/ApplicationClassloaderState.java | 4 +--- framework/src/play/data/parsing/ApacheMultipartParser.java | 4 ---- 2 files changed, 1 insertion(+), 7 deletions(-) diff --git a/framework/src/play/classloading/ApplicationClassloaderState.java b/framework/src/play/classloading/ApplicationClassloaderState.java index 4b70f9991b..725ea9d7a7 100644 --- a/framework/src/play/classloading/ApplicationClassloaderState.java +++ b/framework/src/play/classloading/ApplicationClassloaderState.java @@ -24,9 +24,7 @@ public boolean equals(Object o) { ApplicationClassloaderState that = (ApplicationClassloaderState) o; - if (currentStateValue != that.currentStateValue) return false; - - return true; + return this.currentStateValue == that.currentStateValue; } @Override diff --git a/framework/src/play/data/parsing/ApacheMultipartParser.java b/framework/src/play/data/parsing/ApacheMultipartParser.java index f1800b14af..72e2bb49f7 100644 --- a/framework/src/play/data/parsing/ApacheMultipartParser.java +++ b/framework/src/play/data/parsing/ApacheMultipartParser.java @@ -108,10 +108,6 @@ public static class AutoFileItem implements FileItem { * HTTP. */ public static final String DEFAULT_CHARSET = "ISO-8859-1"; - /** - * Size of buffer to use when writing an item to disk. - */ - private static final int WRITE_BUFFER_SIZE = 2048; // ----------------------------------------------------------- Data members /** From 6171e0bce68e7fee3abec8409e19052e2399c280 Mon Sep 17 00:00:00 2001 From: aleksandy Date: Sat, 23 Apr 2022 12:32:53 +0600 Subject: [PATCH 09/22] use new api to create predefined maps --- .../classloading/ApplicationCompiler.java | 63 ++++++++++--------- .../db/c3p0/PlayConnectionCustomizer.java | 18 +++--- framework/src/play/libs/CronExpression.java | 50 +++++++-------- 3 files changed, 63 insertions(+), 68 deletions(-) diff --git a/framework/src/play/classloading/ApplicationCompiler.java b/framework/src/play/classloading/ApplicationCompiler.java index 11f6250eb6..f0ce32ef34 100644 --- a/framework/src/play/classloading/ApplicationCompiler.java +++ b/framework/src/play/classloading/ApplicationCompiler.java @@ -34,21 +34,21 @@ */ public class ApplicationCompiler { - Map packagesCache = new HashMap<>(); - ApplicationClasses applicationClasses; - Map settings; private static final String JAVA_SOURCE_DEFAULT_VERSION = "11"; - static final Map compatibleJavaVersions = new HashMap<>(); - static { - compatibleJavaVersions.put("11", CompilerOptions.VERSION_11); - compatibleJavaVersions.put("12", CompilerOptions.VERSION_12); - compatibleJavaVersions.put("13", CompilerOptions.VERSION_13); - compatibleJavaVersions.put("14", CompilerOptions.VERSION_14); - compatibleJavaVersions.put("15", CompilerOptions.VERSION_15); - compatibleJavaVersions.put("16", CompilerOptions.VERSION_16); - compatibleJavaVersions.put("17", CompilerOptions.VERSION_17); - compatibleJavaVersions.put("18", CompilerOptions.VERSION_18); - } + static final Map compatibleJavaVersions = Map.of( + "11", CompilerOptions.VERSION_11, + "12", CompilerOptions.VERSION_12, + "13", CompilerOptions.VERSION_13, + "14", CompilerOptions.VERSION_14, + "15", CompilerOptions.VERSION_15, + "16", CompilerOptions.VERSION_16, + "17", CompilerOptions.VERSION_17, + "18", CompilerOptions.VERSION_18 + ); + + final Map packagesCache = new HashMap<>(); + final ApplicationClasses applicationClasses; + final Map settings; /** * Try to guess the magic configuration options @@ -57,32 +57,33 @@ public class ApplicationCompiler { * The application classes container */ public ApplicationCompiler(ApplicationClasses applicationClasses) { - this.applicationClasses = applicationClasses; - this.settings = new HashMap<>(); - this.settings.put(CompilerOptions.OPTION_ReportMissingSerialVersion, CompilerOptions.IGNORE); - this.settings.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE); - this.settings.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE); - this.settings.put(CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.IGNORE); - this.settings.put(CompilerOptions.OPTION_ReportUnusedImport, CompilerOptions.IGNORE); - this.settings.put(CompilerOptions.OPTION_Encoding, "UTF-8"); - this.settings.put(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE); - final String runningJavaVersion = System.getProperty("java.version"); - if (Stream.of("1.5", "1.6", "1.7", "1.8", "9", "10").anyMatch(runningJavaVersion::startsWith)) { + if (Stream.of("1.5", "1.6", "1.7", "1.8", "9", "10").anyMatch(runningJavaVersion::startsWith)) { throw new CompilationException("JDK version prior to 11 are not supported to run the application"); } + final String configSourceVersion = Play.configuration.getProperty("java.source", JAVA_SOURCE_DEFAULT_VERSION); final String jdtVersion = compatibleJavaVersions.get(configSourceVersion); if (jdtVersion == null) { throw new CompilationException(String.format("Incompatible Java version specified (%s). Compatible versions are: %s", - configSourceVersion, compatibleJavaVersions.keySet())); + configSourceVersion, compatibleJavaVersions.keySet())); } - this.settings.put(CompilerOptions.OPTION_Source, jdtVersion); - this.settings.put(CompilerOptions.OPTION_TargetPlatform, jdtVersion); - this.settings.put(CompilerOptions.OPTION_PreserveUnusedLocal, CompilerOptions.PRESERVE); - this.settings.put(CompilerOptions.OPTION_Compliance, jdtVersion); - this.settings.put(CompilerOptions.OPTION_MethodParametersAttribute, CompilerOptions.GENERATE); + this.applicationClasses = applicationClasses; + this.settings = Map.ofEntries( + Map.entry(CompilerOptions.OPTION_ReportMissingSerialVersion, CompilerOptions.IGNORE), + Map.entry(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE), + Map.entry(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE), + Map.entry(CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.IGNORE), + Map.entry(CompilerOptions.OPTION_ReportUnusedImport, CompilerOptions.IGNORE), + Map.entry(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE), + Map.entry(CompilerOptions.OPTION_PreserveUnusedLocal, CompilerOptions.PRESERVE), + Map.entry(CompilerOptions.OPTION_MethodParametersAttribute, CompilerOptions.GENERATE), + Map.entry(CompilerOptions.OPTION_Encoding, "UTF-8"), + Map.entry(CompilerOptions.OPTION_Source, jdtVersion), + Map.entry(CompilerOptions.OPTION_TargetPlatform, jdtVersion), + Map.entry(CompilerOptions.OPTION_Compliance, jdtVersion) + ); } /** diff --git a/framework/src/play/db/c3p0/PlayConnectionCustomizer.java b/framework/src/play/db/c3p0/PlayConnectionCustomizer.java index 01c80700ed..b6e53cbc4b 100644 --- a/framework/src/play/db/c3p0/PlayConnectionCustomizer.java +++ b/framework/src/play/db/c3p0/PlayConnectionCustomizer.java @@ -7,21 +7,17 @@ import java.sql.Connection; import java.sql.SQLException; -import java.util.HashMap; import java.util.Map; public class PlayConnectionCustomizer implements ConnectionCustomizer { - public static Map isolationLevels; - - static { - isolationLevels = new HashMap<>(); - isolationLevels.put("NONE", Connection.TRANSACTION_NONE); - isolationLevels.put("READ_UNCOMMITTED", Connection.TRANSACTION_READ_UNCOMMITTED); - isolationLevels.put("READ_COMMITTED", Connection.TRANSACTION_READ_COMMITTED); - isolationLevels.put("REPEATABLE_READ", Connection.TRANSACTION_REPEATABLE_READ); - isolationLevels.put("SERIALIZABLE", Connection.TRANSACTION_SERIALIZABLE); - } + public static final Map isolationLevels = Map.of( + "NONE", Connection.TRANSACTION_NONE, + "READ_UNCOMMITTED", Connection.TRANSACTION_READ_UNCOMMITTED, + "READ_COMMITTED", Connection.TRANSACTION_READ_COMMITTED, + "REPEATABLE_READ", Connection.TRANSACTION_REPEATABLE_READ, + "SERIALIZABLE", Connection.TRANSACTION_SERIALIZABLE + ); @Override public void onAcquire(Connection c, String parentDataSourceIdentityToken) { diff --git a/framework/src/play/libs/CronExpression.java b/framework/src/play/libs/CronExpression.java index 09d9dcd5a2..6f97374888 100644 --- a/framework/src/play/libs/CronExpression.java +++ b/framework/src/play/libs/CronExpression.java @@ -4,7 +4,6 @@ import java.text.ParseException; import java.util.Calendar; import java.util.Date; -import java.util.HashMap; import java.util.Iterator; import java.util.Locale; import java.util.Map; @@ -176,31 +175,30 @@ public class CronExpression implements Serializable, Cloneable { protected static final int NO_SPEC_INT = 98; // '?' 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", 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); - } + protected static final Map monthMap = Map.ofEntries( + Map.entry("JAN", 0), + Map.entry("FEB", 1), + Map.entry("MAR", 2), + Map.entry("APR", 3), + Map.entry("MAY", 4), + Map.entry("JUN", 5), + Map.entry("JUL", 6), + Map.entry("AUG", 7), + Map.entry("SEP", 8), + Map.entry("OCT", 9), + Map.entry("NOV", 10), + Map.entry("DEC", 11) + ); + protected static final Map dayMap = Map.of( + "SUN", 1, + "MON", 2, + "TUE", 3, + "WED", 4, + "THU", 5, + "FRI", 6, + "SAT", 7 + ); + private String cronExpression = null; private TimeZone timeZone = null; protected transient TreeSet seconds; From 015d0ad16e569019bd2e485339094f6024ef3e1d Mon Sep 17 00:00:00 2001 From: aleksandy Date: Sat, 23 Apr 2022 12:48:22 +0600 Subject: [PATCH 10/22] remove redundant unboxing and nulls checks --- framework/src/play/libs/CronExpression.java | 32 +++++++-------------- 1 file changed, 10 insertions(+), 22 deletions(-) diff --git a/framework/src/play/libs/CronExpression.java b/framework/src/play/libs/CronExpression.java index 6f97374888..46cbc7a623 100644 --- a/framework/src/play/libs/CronExpression.java +++ b/framework/src/play/libs/CronExpression.java @@ -507,7 +507,7 @@ protected int storeExpressionVals(int pos, String s, int type) throws ParseExcep throw new ParseException("'?' can only be specfied for Day-of-Month or Day-of-Week.", i); } if (type == DAY_OF_WEEK && !lastdayOfMonth) { - int val = daysOfMonth.last().intValue(); + int val = daysOfMonth.last(); if (val == NO_SPEC_INT) { throw new ParseException("'?' can only be specfied for Day-of-Month -OR- Day-of-Week.", i); } @@ -967,23 +967,11 @@ protected int getNumericValue(String s, int i) { } protected int getMonthNumber(String s) { - Integer integer = monthMap.get(s); - - if (integer == null) { - return -1; - } - - return integer.intValue(); + return monthMap.getOrDefault(s, -1); } protected int getDayOfWeekNumber(String s) { - Integer integer = dayMap.get(s); - - if (integer == null) { - return -1; - } - - return integer.intValue(); + return dayMap.getOrDefault(s, -1); } // ////////////////////////////////////////////////////////////////////////// @@ -1124,7 +1112,7 @@ protected Date getTimeAfter(Date afterTime) { } } else if (nearestWeekday) { t = day; - day = daysOfMonth.first().intValue(); + day = daysOfMonth.first(); java.util.Calendar tcal = java.util.Calendar.getInstance(); tcal.set(Calendar.SECOND, 0); @@ -1154,14 +1142,14 @@ protected Date getTimeAfter(Date afterTime) { tcal.set(Calendar.MONTH, mon - 1); Date nTime = tcal.getTime(); if (nTime.before(afterTime)) { - day = daysOfMonth.first().intValue(); + day = daysOfMonth.first(); mon++; } - } else if (st != null && st.size() != 0) { + } else if (st.size() != 0) { t = day; - day = st.first().intValue(); + day = st.first(); } else { - day = daysOfMonth.first().intValue(); + day = daysOfMonth.first(); mon++; } @@ -1180,7 +1168,7 @@ protected Date getTimeAfter(Date afterTime) { // week rule if (lastdayOfWeek) { // are we looking for the last day of the month? - int dow = daysOfWeek.first().intValue(); // desired + int dow = daysOfWeek.first(); // desired // d-o-w int cDow = cl.get(Calendar.DAY_OF_WEEK); // current // d-o-w @@ -1225,7 +1213,7 @@ protected Date getTimeAfter(Date afterTime) { } else if (nthdayOfWeek != 0) { // are we looking for the Nth day in the month? - int dow = daysOfWeek.first().intValue(); // desired + int dow = daysOfWeek.first(); // desired // d-o-w int cDow = cl.get(Calendar.DAY_OF_WEEK); // current // d-o-w From bae4d8730c4f6ae164740740928851362a941562 Mon Sep 17 00:00:00 2001 From: aleksandy Date: Sat, 23 Apr 2022 12:55:07 +0600 Subject: [PATCH 11/22] remove duplicates --- .gitignore | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/.gitignore b/.gitignore index c71b4410aa..0ded2a2277 100644 --- a/.gitignore +++ b/.gitignore @@ -14,8 +14,6 @@ nbproject/private framework/tests-results framework/src/version framework/src/play/version -framework/src/play/version -framework/src/play/version framework/tests/test-application/db framework/play-*.jar framework/docs @@ -33,7 +31,6 @@ eclipse .project id framework/tests-tmp -framework/docs dist modules/bespin/lib/bespin.jar modules/ecss/lib/ecss.jar @@ -42,7 +39,6 @@ resources/catalog.xml resources/nbproject/private modules/gae/lib/gae.jar catalog.xml -modules/gae/lib/gae.jar play-*.jar modules/gae/bin modules/gwt/lib/play-gwt.jar @@ -51,7 +47,6 @@ test-result logs db *.pyc -test-result samples-and-tests/with-gwt/nbproject samples-and-tests/jobboard/db samples-and-tests/jobboard/tmp @@ -133,11 +128,7 @@ atlassian-ide-plugin.xml modules/* build.classes modules/crud/nbproject -nbproject -samples-and-tests/jobboard/attachments samples-and-tests/jobboard/logs -samples-and-tests/jobboard/test-result -samples-and-tests/jobboard/tmp samples-and-tests/validation/logs samples-and-tests/zencontact/precompiled !modules/docviewer @@ -148,4 +139,3 @@ samples-and-tests/zencontact/precompiled !modules/testrunner !framework/src/play/db !framework/test-src/play/db -*~ From 7b1340c93de5885c06e65aa6c27329b3985f0225 Mon Sep 17 00:00:00 2001 From: aleksandy Date: Sat, 23 Apr 2022 13:05:14 +0600 Subject: [PATCH 12/22] use standard charset directly --- framework/src/play/mvc/results/RenderBinary.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/framework/src/play/mvc/results/RenderBinary.java b/framework/src/play/mvc/results/RenderBinary.java index 559c3e504d..91d78b0e97 100644 --- a/framework/src/play/mvc/results/RenderBinary.java +++ b/framework/src/play/mvc/results/RenderBinary.java @@ -9,6 +9,7 @@ import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; +import java.nio.charset.StandardCharsets; import org.apache.commons.codec.net.URLCodec; import org.apache.commons.io.IOUtils; @@ -211,7 +212,7 @@ private static void copyInputStreamAndClose(InputStream is, OutputStream out) th } private boolean canAsciiEncode(String string) { - CharsetEncoder asciiEncoder = Charset.forName("US-ASCII").newEncoder(); + CharsetEncoder asciiEncoder = StandardCharsets.US_ASCII.newEncoder(); return asciiEncoder.canEncode(string); } From f959f5329e9a8fc48e95baa9701a92670d846698 Mon Sep 17 00:00:00 2001 From: aleksandy Date: Sat, 23 Apr 2022 13:06:22 +0600 Subject: [PATCH 13/22] remove unused private fields --- framework/src/play/server/PlayHandler.java | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/framework/src/play/server/PlayHandler.java b/framework/src/play/server/PlayHandler.java index 95d881348e..73f6e74df2 100644 --- a/framework/src/play/server/PlayHandler.java +++ b/framework/src/play/server/PlayHandler.java @@ -40,10 +40,7 @@ import java.io.*; 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.util.*; import java.util.concurrent.ConcurrentHashMap; @@ -69,10 +66,6 @@ public class PlayHandler extends SimpleChannelUpstreamHandler { private static final String signature = "Play! Framework;" + Play.version + ";" + Play.mode.name().toLowerCase(); private static final boolean exposePlayServer; - private static final String ACCEPT_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; - private static final Charset ASCII = Charset.forName("ASCII"); - private static final MessageDigest SHA_1; - /** * The Pipeline is given for a PlayHandler */ @@ -87,14 +80,6 @@ public class PlayHandler extends SimpleChannelUpstreamHandler { */ private static final Set allowedHttpMethodOverride; - static { - try { - SHA_1 = MessageDigest.getInstance("SHA1"); - } catch (NoSuchAlgorithmException e) { - throw new IllegalStateException("SHA-1 not supported on this platform", e); - } - } - static { exposePlayServer = !"false".equals(Play.configuration.getProperty("http.exposePlayServer")); allowedHttpMethodOverride = Stream.of(Play.configuration.getProperty("http.allowed.method.override", "").split(",")).collect(Collectors.toSet()); From fd8eaf0cea440e7392af185f360b9d681262106f Mon Sep 17 00:00:00 2001 From: aleksandy Date: Sun, 24 Apr 2022 11:06:46 +0600 Subject: [PATCH 14/22] use lambdas instead of anonymous class --- .../src/play/templates/GroovyTemplate.java | 7 +--- .../app/helpers/CheatSheetHelper.java | 41 ++++++------------- .../docviewer/app/helpers/LangMenuHelper.java | 7 +--- 3 files changed, 14 insertions(+), 41 deletions(-) diff --git a/framework/src/play/templates/GroovyTemplate.java b/framework/src/play/templates/GroovyTemplate.java index 7600aa1d79..73ea940110 100644 --- a/framework/src/play/templates/GroovyTemplate.java +++ b/framework/src/play/templates/GroovyTemplate.java @@ -156,12 +156,7 @@ public void compile() { Collection[] phases = (Collection[]) phasesF.get(compilationUnit); LinkedList output = new LinkedList<>(); phases[Phases.OUTPUT] = output; - output.add(new IGroovyClassOperation() { - @Override - public void call(GroovyClass gclass) { - groovyClassesForThisTemplate.add(gclass); - } - }); + output.add(groovyClassesForThisTemplate::add); compilationUnit.compile(); // ouf diff --git a/modules/docviewer/app/helpers/CheatSheetHelper.java b/modules/docviewer/app/helpers/CheatSheetHelper.java index 82df469eb5..f2675112b0 100644 --- a/modules/docviewer/app/helpers/CheatSheetHelper.java +++ b/modules/docviewer/app/helpers/CheatSheetHelper.java @@ -21,27 +21,18 @@ public static File[] getSheets(String category, String docLang) { } if (cheatSheetDir.exists() && cheatSheetDir.isDirectory()) { - File[] sheetFiles = cheatSheetDir.listFiles(new FileFilter() { - - public boolean accept(File pathname) { - return pathname.isFile() && pathname.getName().endsWith(".textile"); - } - }); + File[] sheetFiles = cheatSheetDir.listFiles(pathname -> pathname.isFile() && pathname.getName().endsWith(".textile")); // first letters of file name before "-" serves as sort index - Arrays.sort(sheetFiles, new Comparator() { - - public int compare(File f1, File f2) { - - String o1 = f1.getName(); - String o2 = f2.getName(); - - if (o1.contains("-") && o2.contains("-")) { - return o1.substring(0, o1.indexOf("-")) - .compareTo(o2.substring(0, o1.indexOf("-"))); - } else { - return o1.compareTo(o2); - } + Arrays.sort(sheetFiles, (f1, f2) -> { + String o1 = f1.getName(); + String o2 = f2.getName(); + + if (o1.contains("-") && o2.contains("-")) { + return o1.substring(0, o1.indexOf("-")) + .compareTo(o2.substring(0, o1.indexOf("-"))); + } else { + return o1.compareTo(o2); } }); @@ -73,18 +64,10 @@ public static String getCategoryTitle(String category) { public static Map listCategoriesAndTitles(String docLang) { String docLangDir = (docLang != null && (!"en".equalsIgnoreCase(docLang) && !docLang.matches("en-.*"))) ? "_" + docLang : ""; - File[] categories = new File(cheatSheetBaseDir + docLangDir).listFiles(new FileFilter() { - public boolean accept(File pathname) { - return pathname.isDirectory(); - } - }); + File[] categories = new File(cheatSheetBaseDir + docLangDir).listFiles(File::isDirectory); if(categories==null || categories.length<=0){ - categories = cheatSheetBaseDir.listFiles(new FileFilter() { - public boolean accept(File pathname) { - return pathname.isDirectory(); - } - }); + categories = cheatSheetBaseDir.listFiles(File::isDirectory); } Arrays.sort(categories); diff --git a/modules/docviewer/app/helpers/LangMenuHelper.java b/modules/docviewer/app/helpers/LangMenuHelper.java index 20871145bc..3a7527ac76 100644 --- a/modules/docviewer/app/helpers/LangMenuHelper.java +++ b/modules/docviewer/app/helpers/LangMenuHelper.java @@ -20,12 +20,7 @@ public static List getMenuList() { defaultLangMenu.key = "en"; defaultLangMenu.value = "English"; langMenuList.add(defaultLangMenu); - File[] dirs = baseDir.listFiles(new FileFilter() { - @Override - public boolean accept(File file) { - return file.isDirectory() && ptn.matcher(file.getName()).find(); - } - }); + File[] dirs = baseDir.listFiles(file -> file.isDirectory() && ptn.matcher(file.getName()).find()); for (final File dir : dirs) { Matcher m = ptn.matcher(dir.getName()); String langCd = ""; From d957a30ebd45133bc3badd8d18c4ad1dae7d12dc Mon Sep 17 00:00:00 2001 From: aleksandy Date: Sun, 24 Apr 2022 11:07:46 +0600 Subject: [PATCH 15/22] StringBuilder instead of StringBuffer --- framework/src/play/Play.java | 2 +- framework/src/play/i18n/Messages.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/framework/src/play/Play.java b/framework/src/play/Play.java index 5d14bfd1a6..1241fdac71 100644 --- a/framework/src/play/Play.java +++ b/framework/src/play/Play.java @@ -426,7 +426,7 @@ private static Properties readOneConfigurationFile(String filename) { for (Object key : propsFromFile.keySet()) { String value = propsFromFile.getProperty(key.toString()); Matcher matcher = pattern.matcher(value); - StringBuffer newValue = new StringBuffer(100); + StringBuilder newValue = new StringBuilder(100); while (matcher.find()) { String jp = matcher.group(1); String r; diff --git a/framework/src/play/i18n/Messages.java b/framework/src/play/i18n/Messages.java index 7123a6bda6..66d35b9b3d 100644 --- a/framework/src/play/i18n/Messages.java +++ b/framework/src/play/i18n/Messages.java @@ -125,7 +125,7 @@ public static String formatString(Locale locale, String value, Object... args) { String message = String.format(locale, value, coolStuff(value, args)); Matcher matcher = recursive.matcher(message); - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); while (matcher.find()) { matcher.appendReplacement(sb, get(matcher.group(1))); } From 729c5ffdf68f6d6df88449b275a3bb07c3f86c8b Mon Sep 17 00:00:00 2001 From: aleksandy Date: Sun, 24 Apr 2022 11:08:32 +0600 Subject: [PATCH 16/22] use primitives instead of wrapper class --- framework/src/play/libs/Time.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/framework/src/play/libs/Time.java b/framework/src/play/libs/Time.java index f6ebfc51db..6a21a14846 100644 --- a/framework/src/play/libs/Time.java +++ b/framework/src/play/libs/Time.java @@ -16,9 +16,9 @@ */ public class Time { private static final Pattern p = Pattern.compile("(([0-9]+?)((d|h|mi|min|mn|s)))+?"); - private static final Integer MINUTE = 60; - private static final Integer HOUR = 60 * MINUTE; - private static final Integer DAY = 24 * HOUR; + private static final int MINUTE = 60; + private static final int HOUR = 60 * MINUTE; + private static final int DAY = 24 * HOUR; /** * Parse a duration From 90e5f4a9e5bf005977d77ca76c969e9ad5197a10 Mon Sep 17 00:00:00 2001 From: aleksandy Date: Sun, 24 Apr 2022 15:10:23 +0600 Subject: [PATCH 17/22] use new java 9+ api --- .../classloading/ApplicationClassloader.java | 2 +- .../LocalvariablesNamesEnhancerJava7.java | 2 +- .../src/play/data/binding/types/DateBinder.java | 2 +- .../play/data/binding/types/DateTimeBinder.java | 2 +- .../play/data/binding/types/FileArrayBinder.java | 2 +- .../src/play/data/binding/types/FileBinder.java | 2 +- .../play/data/binding/types/LocalDateBinder.java | 2 +- .../data/binding/types/LocalDateTimeBinder.java | 2 +- .../play/data/binding/types/LocalTimeBinder.java | 2 +- .../data/binding/types/UploadArrayBinder.java | 2 +- .../play/data/binding/types/UploadBinder.java | 2 +- .../src/play/data/validation/Validation.java | 16 ++-------------- framework/src/play/db/jpa/Blob.java | 11 ++++------- framework/src/play/mvc/Http.java | 2 +- framework/src/play/mvc/Scope.java | 8 +------- framework/src/play/mvc/results/RenderJson.java | 7 ++----- framework/src/play/plugins/PluginCollection.java | 4 ++-- .../play/templates/GroovyTemplateCompiler.java | 2 +- framework/src/play/test/TestEngine.java | 12 ++++-------- framework/src/play/utils/Java.java | 10 +++------- 20 files changed, 31 insertions(+), 63 deletions(-) diff --git a/framework/src/play/classloading/ApplicationClassloader.java b/framework/src/play/classloading/ApplicationClassloader.java index 279c63a4c7..d1a76dc35f 100644 --- a/framework/src/play/classloading/ApplicationClassloader.java +++ b/framework/src/play/classloading/ApplicationClassloader.java @@ -446,7 +446,7 @@ public List getAllClasses() { } } - Collections.sort(result, Comparator.comparing(Class::getName)); + result.sort(Comparator.comparing(Class::getName)); } Map byNormalizedName = new HashMap<>(result.size()); diff --git a/framework/src/play/classloading/enhancers/LocalvariablesNamesEnhancerJava7.java b/framework/src/play/classloading/enhancers/LocalvariablesNamesEnhancerJava7.java index 6fd8929bec..df718a8cf3 100644 --- a/framework/src/play/classloading/enhancers/LocalvariablesNamesEnhancerJava7.java +++ b/framework/src/play/classloading/enhancers/LocalvariablesNamesEnhancerJava7.java @@ -56,7 +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, Comparator.comparing(o -> o._1)); + parameterNames.sort(Comparator.comparing(o -> o._1)); } List names = new ArrayList<>(); for (int i = 0; i < method.getParameterTypes().length + (Modifier.isStatic(method.getModifiers()) ? 0 : 1); i++) { diff --git a/framework/src/play/data/binding/types/DateBinder.java b/framework/src/play/data/binding/types/DateBinder.java index 2116a05a14..24d4509249 100644 --- a/framework/src/play/data/binding/types/DateBinder.java +++ b/framework/src/play/data/binding/types/DateBinder.java @@ -18,7 +18,7 @@ public class DateBinder implements TypeBinder { @Override public Date bind(String name, Annotation[] annotations, String value, Class actualClass, Type genericType) throws Exception { - if (value == null || value.trim().length() == 0) { + if (value == null || value.isBlank()) { return null; } diff --git a/framework/src/play/data/binding/types/DateTimeBinder.java b/framework/src/play/data/binding/types/DateTimeBinder.java index 5dacf56f85..0421745adf 100644 --- a/framework/src/play/data/binding/types/DateTimeBinder.java +++ b/framework/src/play/data/binding/types/DateTimeBinder.java @@ -16,7 +16,7 @@ public class DateTimeBinder implements TypeBinder { @Override public DateTime bind(String name, Annotation[] annotations, String value, Class actualClass, Type genericType) throws Exception { - if (value == null || value.trim().length() == 0) { + if (value == null || value.isBlank()) { return null; } return new DateTime(dateBinder.bind(name, annotations, value, actualClass, genericType)); diff --git a/framework/src/play/data/binding/types/FileArrayBinder.java b/framework/src/play/data/binding/types/FileArrayBinder.java index 8b31e37a3b..b85a8e4a2d 100644 --- a/framework/src/play/data/binding/types/FileArrayBinder.java +++ b/framework/src/play/data/binding/types/FileArrayBinder.java @@ -19,7 +19,7 @@ public class FileArrayBinder implements TypeBinder { @SuppressWarnings("unchecked") @Override public File[] bind(String name, Annotation[] annotations, String value, Class actualClass, Type genericType) { - if (value == null || value.trim().length() == 0) { + if (value == null || value.isBlank()) { return null; } Request req = Request.current(); diff --git a/framework/src/play/data/binding/types/FileBinder.java b/framework/src/play/data/binding/types/FileBinder.java index f3c198220a..3cad419f4b 100644 --- a/framework/src/play/data/binding/types/FileBinder.java +++ b/framework/src/play/data/binding/types/FileBinder.java @@ -17,7 +17,7 @@ public class FileBinder implements TypeBinder { @Override @SuppressWarnings("unchecked") public File bind(String name, Annotation[] annotations, String value, Class actualClass, Type genericType) { - if (value == null || value.trim().length() == 0) { + if (value == null || value.isBlank()) { return null; } Request req = Request.current(); diff --git a/framework/src/play/data/binding/types/LocalDateBinder.java b/framework/src/play/data/binding/types/LocalDateBinder.java index b620a4bb4a..b7a40e28bb 100644 --- a/framework/src/play/data/binding/types/LocalDateBinder.java +++ b/framework/src/play/data/binding/types/LocalDateBinder.java @@ -13,6 +13,6 @@ public class LocalDateBinder implements TypeBinder { @Override public LocalDate bind(String name, Annotation[] annotations, String value, Class actualClass, Type genericType) { - return value != null && !value.trim().isEmpty() ? LocalDate.parse(value) : null; + return value != null && !value.isBlank() ? LocalDate.parse(value) : null; } } diff --git a/framework/src/play/data/binding/types/LocalDateTimeBinder.java b/framework/src/play/data/binding/types/LocalDateTimeBinder.java index 9017d8a27a..d1704ce6ca 100644 --- a/framework/src/play/data/binding/types/LocalDateTimeBinder.java +++ b/framework/src/play/data/binding/types/LocalDateTimeBinder.java @@ -10,6 +10,6 @@ public class LocalDateTimeBinder implements TypeBinder { @Override public LocalDateTime bind(String name, Annotation[] annotations, String value, Class actualClass, Type genericType) { - return value != null && !value.trim().isEmpty() ? LocalDateTime.parse(value) : null; + return value != null && !value.isBlank() ? LocalDateTime.parse(value) : null; } } diff --git a/framework/src/play/data/binding/types/LocalTimeBinder.java b/framework/src/play/data/binding/types/LocalTimeBinder.java index d3caab52f9..86cb938ac6 100644 --- a/framework/src/play/data/binding/types/LocalTimeBinder.java +++ b/framework/src/play/data/binding/types/LocalTimeBinder.java @@ -13,6 +13,6 @@ public class LocalTimeBinder implements TypeBinder { @Override public LocalTime bind(String name, Annotation[] annotations, String value, Class actualClass, Type genericType) { - return value != null && !value.trim().isEmpty() ? LocalTime.parse(value) : null; + return value != null && !value.isBlank() ? LocalTime.parse(value) : null; } } diff --git a/framework/src/play/data/binding/types/UploadArrayBinder.java b/framework/src/play/data/binding/types/UploadArrayBinder.java index 7a87bc663a..f57bb9f5ed 100644 --- a/framework/src/play/data/binding/types/UploadArrayBinder.java +++ b/framework/src/play/data/binding/types/UploadArrayBinder.java @@ -19,7 +19,7 @@ public class UploadArrayBinder implements TypeBinder { @SuppressWarnings("unchecked") @Override public Upload[] bind(String name, Annotation[] annotations, String value, Class actualClass, Type genericType) { - if (value == null || value.trim().length() == 0) { + if (value == null || value.isBlank()) { return null; } Request req = Request.current(); diff --git a/framework/src/play/data/binding/types/UploadBinder.java b/framework/src/play/data/binding/types/UploadBinder.java index fcaee068f5..2fd855cdaa 100644 --- a/framework/src/play/data/binding/types/UploadBinder.java +++ b/framework/src/play/data/binding/types/UploadBinder.java @@ -18,7 +18,7 @@ public class UploadBinder implements TypeBinder { @Override @SuppressWarnings("unchecked") public Object bind(String name, Annotation[] annotations, String value, Class actualClass, Type genericType) { - if (value == null || value.trim().length() == 0) { + if (value == null || value.isBlank()) { return null; } try { diff --git a/framework/src/play/data/validation/Validation.java b/framework/src/play/data/validation/Validation.java index bb6366beb7..74e651047b 100644 --- a/framework/src/play/data/validation/Validation.java +++ b/framework/src/play/data/validation/Validation.java @@ -97,13 +97,7 @@ public static void insertError(int index, String field, String message, String.. public static void removeErrors(String field, String message) { Validation validation = current.get(); if (validation != null) { - Iterator it = validation.errors.iterator(); - while (it.hasNext()) { - Error error = it.next(); - if (error.key != null && error.key.equals(field) && error.message.equals(message)) { - it.remove(); - } - } + validation.errors.removeIf(error -> error.key != null && error.key.equals(field) && error.message.equals(message)); } } @@ -114,13 +108,7 @@ public static void removeErrors(String field, String message) { public static void removeErrors(String field) { Validation validation = current.get(); if (validation != null) { - Iterator it = validation.errors.iterator(); - while (it.hasNext()) { - Error error = it.next(); - if (error.key != null && error.key.equals(field)) { - it.remove(); - } - } + validation.errors.removeIf(error -> error.key != null && error.key.equals(field)); } } diff --git a/framework/src/play/db/jpa/Blob.java b/framework/src/play/db/jpa/Blob.java index a9ad9ab8bf..74bd42505f 100644 --- a/framework/src/play/db/jpa/Blob.java +++ b/framework/src/play/db/jpa/Blob.java @@ -8,6 +8,7 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; +import java.util.Objects; import org.hibernate.HibernateException; import org.hibernate.engine.spi.SharedSessionContractImplementor; @@ -95,17 +96,13 @@ public Class returnedClass() { return Blob.class; } - private static boolean equal(Object a, Object b) { - return a == b || (a != null && a.equals(b)); - } - @Override public boolean equals(Object o, Object o1) throws HibernateException { if(o instanceof Blob && o1 instanceof Blob) { - return equal(((Blob)o).UUID, ((Blob)o1).UUID) && - equal(((Blob)o).type, ((Blob)o1).type); + return Objects.equals(((Blob) o).UUID, ((Blob) o1).UUID) && + Objects.equals(((Blob)o).type, ((Blob)o1).type); } - return equal(o, o1); + return Objects.equals(o, o1); } @Override diff --git a/framework/src/play/mvc/Http.java b/framework/src/play/mvc/Http.java index b2004c07f5..5ec27af3b0 100644 --- a/framework/src/play/mvc/Http.java +++ b/framework/src/play/mvc/Http.java @@ -576,7 +576,7 @@ public List acceptLanguage() { } String acceptLanguage = headers.get("accept-language").value(); List languages = Arrays.asList(acceptLanguage.split(",")); - Collections.sort(languages, (lang1, lang2) -> { + languages.sort((lang1, lang2) -> { double q1 = 1.0; double q2 = 1.0; Matcher m1 = qpattern.matcher(lang1); diff --git a/framework/src/play/mvc/Scope.java b/framework/src/play/mvc/Scope.java index de11721d80..4e58f6c3b7 100644 --- a/framework/src/play/mvc/Scope.java +++ b/framework/src/play/mvc/Scope.java @@ -356,13 +356,7 @@ public void remove(String key) { public void removeStartWith(String prefix) { checkAndParse(); - Iterator> iterator = data.entrySet().iterator(); - while (iterator.hasNext()) { - Map.Entry entry = iterator.next(); - if (entry.getKey().startsWith(prefix)) { - iterator.remove(); - } - } + data.entrySet().removeIf(entry -> entry.getKey().startsWith(prefix)); // make sure rootsParamsNode is regenerated if needed rootParamsNodeIsGenerated = false; } diff --git a/framework/src/play/mvc/results/RenderJson.java b/framework/src/play/mvc/results/RenderJson.java index 57f8f4fccd..a0a92889fc 100644 --- a/framework/src/play/mvc/results/RenderJson.java +++ b/framework/src/play/mvc/results/RenderJson.java @@ -5,6 +5,7 @@ import com.google.gson.JsonSerializer; import java.lang.reflect.Method; import java.lang.reflect.Type; +import java.util.Objects; import play.exceptions.UnexpectedException; import play.mvc.Http.Request; @@ -47,11 +48,7 @@ public RenderJson(String jsonString) { public RenderJson(Object response, Gson gson) { this.response = response; - if (gson != null) { - json = gson.toJson(response); - } else { - json = GSON.toJson(response); - } + json = Objects.requireNonNullElse(gson, GSON).toJson(response); } @Override diff --git a/framework/src/play/plugins/PluginCollection.java b/framework/src/play/plugins/PluginCollection.java index f6d8b919bc..c5cd8ee885 100644 --- a/framework/src/play/plugins/PluginCollection.java +++ b/framework/src/play/plugins/PluginCollection.java @@ -94,7 +94,7 @@ public class PluginCollection { * @return Read only list of plugins */ protected List createReadonlyCopy(List list) { - return Collections.unmodifiableList(new ArrayList<>(list)); + return List.copyOf(list); } private static class LoadingPluginInfo implements Comparable { @@ -202,7 +202,7 @@ List loadPlayPluginDescriptors() { String playPluginsDescriptors = Play.configuration.getProperty("play.plugins.descriptor"); if (playPluginsDescriptors != null) { return Stream.of(playPluginsDescriptors.split(",")) - .map(playPluginsDescriptor -> fileToUrl(playPluginsDescriptor)) + .map(this::fileToUrl) .collect(toList()); } return Collections.list(Play.classloader.getResources(play_plugins_resourceName)); diff --git a/framework/src/play/templates/GroovyTemplateCompiler.java b/framework/src/play/templates/GroovyTemplateCompiler.java index 8e08348dbd..78bfdb9d17 100644 --- a/framework/src/play/templates/GroovyTemplateCompiler.java +++ b/framework/src/play/templates/GroovyTemplateCompiler.java @@ -79,7 +79,7 @@ protected String checkScalaCompatibility(String source) { originalNames.put(name, clazz.getName()); } } - Collections.sort(names, (o1, o2) -> o2.length() - o1.length()); + names.sort((o1, o2) -> o2.length() - o1.length()); // We're about to do many many String.replaceAll() so we do some // checking first diff --git a/framework/src/play/test/TestEngine.java b/framework/src/play/test/TestEngine.java index f76bdcdb73..173b0b6791 100644 --- a/framework/src/play/test/TestEngine.java +++ b/framework/src/play/test/TestEngine.java @@ -55,7 +55,7 @@ public static List allUnitTests() { } } } - Collections.sort(classes, classNameComparator); + classes.sort(classNameComparator); return classes; } @@ -63,13 +63,9 @@ public static List allFunctionalTests() { List classes = new ArrayList<>(); classes.addAll(Play.classloader.getAssignableClasses(FunctionalTest.class)); classes.addAll(Play.pluginCollection.getFunctionalTests()); - - for (ListIterator it = classes.listIterator(); it.hasNext();) { - if (Modifier.isAbstract(it.next().getModifiers())) { - it.remove(); - } - } - Collections.sort(classes, classNameComparator); + + classes.removeIf(aClass -> Modifier.isAbstract(aClass.getModifiers())); + classes.sort(classNameComparator); return classes; } diff --git a/framework/src/play/utils/Java.java b/framework/src/play/utils/Java.java index d46d935fa0..5fc7111f0e 100644 --- a/framework/src/play/utils/Java.java +++ b/framework/src/play/utils/Java.java @@ -18,6 +18,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; import java.util.concurrent.FutureTask; @@ -473,12 +474,7 @@ public boolean equals(Object o) { ClassAndAnnotation that = (ClassAndAnnotation) o; - if (annotation != null ? !annotation.equals(that.annotation) : that.annotation != null) - return false; - if (clazz != null ? !clazz.equals(that.clazz) : that.clazz != null) - return false; - - return true; + return Objects.equals(annotation, that.annotation) && Objects.equals(clazz, that.clazz); } @Override @@ -543,7 +539,7 @@ public List findAllAnnotatedMethods(Class clazz, Class methods, final Class annotationType) { try { final Method priority = annotationType.getMethod("priority"); - sort(methods, (m1, m2) -> { + methods.sort((m1, m2) -> { try { Integer priority1 = (Integer) priority.invoke(m1.getAnnotation(annotationType)); Integer priority2 = (Integer) priority.invoke(m2.getAnnotation(annotationType)); From 7d1c9fe7097c4b0900392d02a156f93f637d42dd Mon Sep 17 00:00:00 2001 From: aleksandy Date: Sun, 24 Apr 2022 18:15:19 +0600 Subject: [PATCH 18/22] make classes static --- framework/src/play/db/jpa/JPAPlugin.java | 2 +- framework/src/play/libs/ws/WSAsync.java | 4 ++-- framework/src/play/libs/ws/WSUrlFetch.java | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/framework/src/play/db/jpa/JPAPlugin.java b/framework/src/play/db/jpa/JPAPlugin.java index e8e08f0357..7a476ee7b6 100644 --- a/framework/src/play/db/jpa/JPAPlugin.java +++ b/framework/src/play/db/jpa/JPAPlugin.java @@ -309,7 +309,7 @@ public void afterInvocation() { } } - public class TransactionalFilter extends Filter { + public static class TransactionalFilter extends Filter { public TransactionalFilter(String name) { super(name); } diff --git a/framework/src/play/libs/ws/WSAsync.java b/framework/src/play/libs/ws/WSAsync.java index 74591e23e1..fdd3c68ca3 100644 --- a/framework/src/play/libs/ws/WSAsync.java +++ b/framework/src/play/libs/ws/WSAsync.java @@ -738,9 +738,9 @@ public WSRequest sign(WSRequest request, String method) return request; } - public class WSRequestAdapter implements HttpRequest { + public static class WSRequestAdapter implements HttpRequest { - private WSRequest request; + private final WSRequest request; private String method; public WSRequestAdapter(WSRequest request) { diff --git a/framework/src/play/libs/ws/WSUrlFetch.java b/framework/src/play/libs/ws/WSUrlFetch.java index 9403a8956b..433d1dad36 100644 --- a/framework/src/play/libs/ws/WSUrlFetch.java +++ b/framework/src/play/libs/ws/WSUrlFetch.java @@ -49,7 +49,7 @@ public play.libs.WS.WSRequest newRequest(String url, String encoding) { return new WSUrlfetchRequest(url, encoding); } - public class WSUrlfetchRequest extends WSRequest { + public static class WSUrlfetchRequest extends WSRequest { protected WSUrlfetchRequest(String url, String encoding) { super(url, encoding); From 4a0314a0ccee884e164f777f88ee9cc098e73697 Mon Sep 17 00:00:00 2001 From: aleksandy Date: Sun, 24 Apr 2022 18:51:57 +0600 Subject: [PATCH 19/22] remove duplicates and use immutable map --- framework/src/play/libs/I18N.java | 257 ++++++++++++++---------------- 1 file changed, 116 insertions(+), 141 deletions(-) diff --git a/framework/src/play/libs/I18N.java b/framework/src/play/libs/I18N.java index 79c1fc3f3f..c3db7c7524 100644 --- a/framework/src/play/libs/I18N.java +++ b/framework/src/play/libs/I18N.java @@ -1,6 +1,5 @@ package play.libs; -import java.util.HashMap; import java.util.Map; import org.apache.commons.lang.StringUtils; import play.Play; @@ -11,142 +10,121 @@ */ public class I18N { - static final Map symbols = new HashMap<>(); - - static { - symbols.put("ALL", "Lek"); - symbols.put("USD", "$"); - symbols.put("AFN", "؋"); - symbols.put("ARS", "$"); - symbols.put("AWG", "ƒ"); - symbols.put("AUD", "$"); - symbols.put("AZN", "ман"); - symbols.put("BSD", "$"); - symbols.put("BBD", "$"); - symbols.put("BYR", "p."); - symbols.put("EUR", "€"); - symbols.put("BZD", "BZ$"); - symbols.put("BMD", "$"); - symbols.put("BOB", "$b"); - symbols.put("BAM", "KM"); - symbols.put("BWP", "P"); - symbols.put("BGN", "лв"); - symbols.put("BRL", "R$"); - symbols.put("GBP", "£"); - symbols.put("BND", "$"); - symbols.put("KHR", "៛"); - symbols.put("CAD", "$"); - symbols.put("KYD", "$"); - symbols.put("CLP", "$"); - symbols.put("CNY", "¥"); - symbols.put("COP", "$"); - symbols.put("CRC", "₡"); - symbols.put("HRK", "kn"); - symbols.put("CUP", "₱"); - symbols.put("EUR", "€"); - symbols.put("CZK", "Kč"); - symbols.put("DKK", "kr"); - symbols.put("DOP", "RD$"); - symbols.put("XCD", "$"); - symbols.put("EGP", "£"); - symbols.put("SVC", "$"); - symbols.put("GBP", "£"); - symbols.put("EEK", "kr"); - symbols.put("EUR", "€"); - symbols.put("FKP", "£"); - symbols.put("FJD", "$"); - symbols.put("EUR", "€"); - symbols.put("GHC", "¢"); - symbols.put("GIP", "£"); - symbols.put("EUR", "€"); - symbols.put("GTQ", "Q"); - symbols.put("GGP", "£"); - symbols.put("GYD", "$"); - symbols.put("EUR", "€"); - symbols.put("HNL", "L"); - symbols.put("HKD", "$"); - symbols.put("HUF", "Ft"); - symbols.put("ISK", "kr"); - symbols.put("INR", ""); - symbols.put("IDR", "Rp"); - symbols.put("IRR", "﷼"); - symbols.put("EUR", "€"); - symbols.put("IMP", "£"); - symbols.put("ILS", "₪"); - symbols.put("EUR", "€"); - symbols.put("JMD", "J$"); - symbols.put("JPY", "¥"); - symbols.put("JEP", "£"); - symbols.put("KZT", "лв"); - symbols.put("KPW", "₩"); - symbols.put("KRW", "₩"); - symbols.put("KGS", "лв"); - symbols.put("LAK", "₭"); - symbols.put("LVL", "Ls"); - symbols.put("LBP", "£"); - symbols.put("LRD", "$"); - symbols.put("CHF", "CHF"); - symbols.put("LTL", "Lt"); - symbols.put("EUR", "€"); - symbols.put("MKD", "ден"); - symbols.put("MYR", "RM"); - symbols.put("EUR", "€"); - symbols.put("MUR", "₨"); - symbols.put("MXN", "$"); - symbols.put("MNT", "₮"); - symbols.put("MZN", "MT"); - symbols.put("NAD", "$"); - symbols.put("NPR", "₨"); - symbols.put("ANG", "ƒ"); - symbols.put("EUR", "€"); - symbols.put("NZD", "$"); - symbols.put("NIO", "C$"); - symbols.put("NGN", "₦"); - symbols.put("KPW", "₩"); - symbols.put("NOK", "kr"); - symbols.put("OMR", "﷼"); - symbols.put("PKR", "₨"); - symbols.put("PAB", "B/."); - symbols.put("PYG", "Gs"); - symbols.put("PEN", "S/."); - symbols.put("PHP", "Php"); - symbols.put("PLN", "zł"); - symbols.put("QAR", "﷼"); - symbols.put("RON", "lei"); - symbols.put("RUB", "руб."); - symbols.put("SHP", "£"); - symbols.put("SAR", "﷼"); - symbols.put("RSD", "Дин."); - symbols.put("SCR", "₨"); - symbols.put("SGD", "$"); - symbols.put("EUR", "€"); - symbols.put("SBD", "$"); - symbols.put("SOS", "S"); - symbols.put("ZAR", "R"); - symbols.put("KRW", "₩"); - symbols.put("EUR", "€"); - symbols.put("LKR", "₨"); - symbols.put("SEK", "kr"); - symbols.put("CHF", "CHF"); - symbols.put("SRD", "$"); - symbols.put("SYP", "£"); - symbols.put("TWD", "NT$"); - symbols.put("THB", "฿"); - symbols.put("TTD", "TT$"); - symbols.put("TRY", "TL"); - symbols.put("TRL", "₤"); - symbols.put("TVD", "$"); - symbols.put("UAH", "₴"); - symbols.put("GBP", "£"); - symbols.put("USD", "$"); - symbols.put("UYU", "$U"); - symbols.put("UZS", "лв"); - symbols.put("EUR", "€"); - symbols.put("VEF", "Bs"); - symbols.put("VND", "₫"); - symbols.put("YER", "﷼"); - symbols.put("ZWD", "Z$"); - } + static final Map symbols = Map.ofEntries( + Map.entry("ALL", "Lek"), + Map.entry("USD", "$"), + Map.entry("AFN", "؋"), + Map.entry("ARS", "$"), + Map.entry("AWG", "ƒ"), + Map.entry("AUD", "$"), + Map.entry("AZN", "ман"), + Map.entry("BSD", "$"), + Map.entry("BBD", "$"), + Map.entry("BYR", "p."), + Map.entry("EUR", "€"), + Map.entry("BZD", "BZ$"), + Map.entry("BMD", "$"), + Map.entry("BOB", "$b"), + Map.entry("BAM", "KM"), + Map.entry("BWP", "P"), + Map.entry("BGN", "лв"), + Map.entry("BRL", "R$"), + Map.entry("GBP", "£"), + Map.entry("BND", "$"), + Map.entry("KHR", "៛"), + Map.entry("CAD", "$"), + Map.entry("KYD", "$"), + Map.entry("CLP", "$"), + Map.entry("CNY", "¥"), + Map.entry("COP", "$"), + Map.entry("CRC", "₡"), + Map.entry("HRK", "kn"), + Map.entry("CUP", "₱"), + Map.entry("CZK", "Kč"), + Map.entry("DKK", "kr"), + Map.entry("DOP", "RD$"), + Map.entry("XCD", "$"), + Map.entry("EGP", "£"), + Map.entry("SVC", "$"), + Map.entry("EEK", "kr"), + Map.entry("FKP", "£"), + Map.entry("FJD", "$"), + Map.entry("GHC", "¢"), + Map.entry("GIP", "£"), + Map.entry("GTQ", "Q"), + Map.entry("GGP", "£"), + Map.entry("GYD", "$"), + Map.entry("HNL", "L"), + Map.entry("HKD", "$"), + Map.entry("HUF", "Ft"), + Map.entry("ISK", "kr"), + Map.entry("INR", ""), + Map.entry("IDR", "Rp"), + Map.entry("IRR", "﷼"), + Map.entry("IMP", "£"), + Map.entry("ILS", "₪"), + Map.entry("JMD", "J$"), + Map.entry("JPY", "¥"), + Map.entry("JEP", "£"), + Map.entry("KZT", "лв"), + Map.entry("KPW", "₩"), + Map.entry("KGS", "лв"), + Map.entry("LAK", "₭"), + Map.entry("LVL", "Ls"), + Map.entry("LBP", "£"), + Map.entry("LRD", "$"), + Map.entry("CHF", "CHF"), + Map.entry("LTL", "Lt"), + Map.entry("MKD", "ден"), + Map.entry("MYR", "RM"), + Map.entry("MUR", "₨"), + Map.entry("MXN", "$"), + Map.entry("MNT", "₮"), + Map.entry("MZN", "MT"), + Map.entry("NAD", "$"), + Map.entry("NPR", "₨"), + Map.entry("ANG", "ƒ"), + Map.entry("NZD", "$"), + Map.entry("NIO", "C$"), + Map.entry("NGN", "₦"), + Map.entry("NOK", "kr"), + Map.entry("OMR", "﷼"), + Map.entry("PKR", "₨"), + Map.entry("PAB", "B/."), + Map.entry("PYG", "Gs"), + Map.entry("PEN", "S/."), + Map.entry("PHP", "Php"), + Map.entry("PLN", "zł"), + Map.entry("QAR", "﷼"), + Map.entry("RON", "lei"), + Map.entry("RUB", "руб."), + Map.entry("SHP", "£"), + Map.entry("SAR", "﷼"), + Map.entry("RSD", "Дин."), + Map.entry("SCR", "₨"), + Map.entry("SGD", "$"), + Map.entry("SBD", "$"), + Map.entry("SOS", "S"), + Map.entry("ZAR", "R"), + Map.entry("KRW", "₩"), + Map.entry("LKR", "₨"), + Map.entry("SEK", "kr"), + Map.entry("SRD", "$"), + Map.entry("SYP", "£"), + Map.entry("TWD", "NT$"), + Map.entry("THB", "฿"), + Map.entry("TTD", "TT$"), + Map.entry("TRY", "TL"), + Map.entry("TRL", "₤"), + Map.entry("TVD", "$"), + Map.entry("UAH", "₴"), + Map.entry("UYU", "$U"), + Map.entry("UZS", "лв"), + Map.entry("VEF", "Bs"), + Map.entry("VND", "₫"), + Map.entry("YER", "﷼"), + Map.entry("ZWD", "Z$") + ); /** * Retrieve currency symbol for a currency @@ -154,10 +132,7 @@ public class I18N { * @return ($, €, ...) */ public static String getCurrencySymbol(String currency) { - if (symbols.containsKey(currency)) { - return symbols.get(currency); - } - return currency; + return symbols.getOrDefault(currency, currency); } public static String getDateFormat() { From 234ed399d9afb7c7db8bd635d6d866774c06f9c7 Mon Sep 17 00:00:00 2001 From: aleksandy Date: Sun, 24 Apr 2022 18:54:55 +0600 Subject: [PATCH 20/22] use constructors with argument instead of no-args+putAll() --- framework/src/play/classloading/ApplicationClassloader.java | 3 +-- framework/src/play/server/PlayHandler.java | 5 +---- framework/src/play/templates/FastTags.java | 6 ++---- framework/src/play/test/Fixtures.java | 3 +-- 4 files changed, 5 insertions(+), 12 deletions(-) diff --git a/framework/src/play/classloading/ApplicationClassloader.java b/framework/src/play/classloading/ApplicationClassloader.java index d1a76dc35f..edcfe86e8d 100644 --- a/framework/src/play/classloading/ApplicationClassloader.java +++ b/framework/src/play/classloading/ApplicationClassloader.java @@ -323,8 +323,7 @@ public void detectChanges() throws RestartNeededException { modifieds.add(applicationClass); } } - Set modifiedWithDependencies = new HashSet<>(); - modifiedWithDependencies.addAll(modifieds); + Set modifiedWithDependencies = new HashSet<>(modifieds); if (!modifieds.isEmpty()) { modifiedWithDependencies.addAll(Play.pluginCollection.onClassesChange(modifieds)); } diff --git a/framework/src/play/server/PlayHandler.java b/framework/src/play/server/PlayHandler.java index 73f6e74df2..5a1291e0b8 100644 --- a/framework/src/play/server/PlayHandler.java +++ b/framework/src/play/server/PlayHandler.java @@ -632,10 +632,7 @@ protected static Map getHeaders(HttpRequest nettyRequest) { for (String key : nettyRequest.headers().names()) { Http.Header hd = new Http.Header(); hd.name = key.toLowerCase(); - hd.values = new ArrayList<>(); - for (String next : nettyRequest.headers().getAll(key)) { - hd.values.add(next); - } + hd.values = new ArrayList<>(nettyRequest.headers().getAll(key)); headers.put(hd.name, hd); } diff --git a/framework/src/play/templates/FastTags.java b/framework/src/play/templates/FastTags.java index ebc5448302..70ae069da2 100644 --- a/framework/src/play/templates/FastTags.java +++ b/framework/src/play/templates/FastTags.java @@ -414,8 +414,7 @@ public static void _include(Map args, Closure body, PrintWriter out, Execu name = ct + name.substring(1); } BaseTemplate t = (BaseTemplate) TemplateLoader.load(name); - Map newArgs = new HashMap<>(); - newArgs.putAll(template.getBinding().getVariables()); + Map newArgs = new HashMap<>(template.getBinding().getVariables()); newArgs.put("_isInclude", true); t.internalRender(newArgs); } catch (TemplateNotFoundException e) { @@ -441,8 +440,7 @@ public static void _render(Map args, Closure body, PrintWriter out, Execut } args.remove("arg"); BaseTemplate t = (BaseTemplate) TemplateLoader.load(name); - Map newArgs = new HashMap<>(); - newArgs.putAll((Map) args); + Map newArgs = new HashMap<>((Map) args); newArgs.put("_isInclude", true); newArgs.put("out", out); t.internalRender(newArgs); diff --git a/framework/src/play/test/Fixtures.java b/framework/src/play/test/Fixtures.java index dfaee51de6..ceff21da2f 100644 --- a/framework/src/play/test/Fixtures.java +++ b/framework/src/play/test/Fixtures.java @@ -540,8 +540,7 @@ static Map resolveDependencies(Class type, Map fields = new HashSet<>(); - Map resolvedYml = new HashMap<>(); - resolvedYml.putAll(yml); + Map resolvedYml = new HashMap<>(yml); // Look up the super classes Class clazz = type; From caa9b07b0965621dd18b1a5bd9c60aa6d0c66709 Mon Sep 17 00:00:00 2001 From: aleksandy Date: Sun, 24 Apr 2022 23:51:51 +0600 Subject: [PATCH 21/22] use new api to create predefined map --- .../LocalvariablesNamesEnhancer.java | 66 +++++++++---------- 1 file changed, 32 insertions(+), 34 deletions(-) diff --git a/framework/src/play/classloading/enhancers/LocalvariablesNamesEnhancer.java b/framework/src/play/classloading/enhancers/LocalvariablesNamesEnhancer.java index fd69035410..17a26e408e 100644 --- a/framework/src/play/classloading/enhancers/LocalvariablesNamesEnhancer.java +++ b/framework/src/play/classloading/enhancers/LocalvariablesNamesEnhancer.java @@ -278,43 +278,41 @@ public static void setLocalVariablesStateAfterAwait(Stack> s } } - static final Map storeByCode = new HashMap<>(); - /* * Useful instructions */ - static { - storeByCode.put(CodeIterator.ASTORE_0, 0); - storeByCode.put(CodeIterator.ASTORE_1, 1); - storeByCode.put(CodeIterator.ASTORE_2, 2); - storeByCode.put(CodeIterator.ASTORE_3, 3); - storeByCode.put(CodeIterator.ASTORE, -2); - - storeByCode.put(CodeIterator.ISTORE_0, 0); - storeByCode.put(CodeIterator.ISTORE_1, 1); - storeByCode.put(CodeIterator.ISTORE_2, 2); - storeByCode.put(CodeIterator.ISTORE_3, 3); - storeByCode.put(CodeIterator.ISTORE, -2); - storeByCode.put(CodeIterator.IINC, -2); - - storeByCode.put(CodeIterator.LSTORE_0, 0); - storeByCode.put(CodeIterator.LSTORE_1, 1); - storeByCode.put(CodeIterator.LSTORE_2, 2); - storeByCode.put(CodeIterator.LSTORE_3, 3); - storeByCode.put(CodeIterator.LSTORE, -2); - - storeByCode.put(CodeIterator.FSTORE_0, 0); - storeByCode.put(CodeIterator.FSTORE_1, 1); - storeByCode.put(CodeIterator.FSTORE_2, 2); - storeByCode.put(CodeIterator.FSTORE_3, 3); - storeByCode.put(CodeIterator.FSTORE, -2); - - storeByCode.put(CodeIterator.DSTORE_0, 0); - storeByCode.put(CodeIterator.DSTORE_1, 1); - storeByCode.put(CodeIterator.DSTORE_2, 2); - storeByCode.put(CodeIterator.DSTORE_3, 3); - storeByCode.put(CodeIterator.DSTORE, -2); - } + static final Map storeByCode = Map.ofEntries( + Map.entry(CodeIterator.ASTORE_0, 0), + Map.entry(CodeIterator.ASTORE_1, 1), + Map.entry(CodeIterator.ASTORE_2, 2), + Map.entry(CodeIterator.ASTORE_3, 3), + Map.entry(CodeIterator.ASTORE, -2), + + Map.entry(CodeIterator.ISTORE_0, 0), + Map.entry(CodeIterator.ISTORE_1, 1), + Map.entry(CodeIterator.ISTORE_2, 2), + Map.entry(CodeIterator.ISTORE_3, 3), + Map.entry(CodeIterator.ISTORE, -2), + Map.entry(CodeIterator.IINC, -2), + + Map.entry(CodeIterator.LSTORE_0, 0), + Map.entry(CodeIterator.LSTORE_1, 1), + Map.entry(CodeIterator.LSTORE_2, 2), + Map.entry(CodeIterator.LSTORE_3, 3), + Map.entry(CodeIterator.LSTORE, -2), + + Map.entry(CodeIterator.FSTORE_0, 0), + Map.entry(CodeIterator.FSTORE_1, 1), + Map.entry(CodeIterator.FSTORE_2, 2), + Map.entry(CodeIterator.FSTORE_3, 3), + Map.entry(CodeIterator.FSTORE, -2), + + Map.entry(CodeIterator.DSTORE_0, 0), + Map.entry(CodeIterator.DSTORE_1, 1), + Map.entry(CodeIterator.DSTORE_2, 2), + Map.entry(CodeIterator.DSTORE_3, 3), + Map.entry(CodeIterator.DSTORE, -2) + ); /** * Debug utility. Display a byte code op as plain text. From b51bea090446677868f242998a8a175ca211e2f6 Mon Sep 17 00:00:00 2001 From: aleksandy Date: Tue, 5 Jul 2022 01:01:25 +0600 Subject: [PATCH 22/22] use new api to create predefined list --- .../enhancers/ContinuationEnhancer.java | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/framework/src/play/classloading/enhancers/ContinuationEnhancer.java b/framework/src/play/classloading/enhancers/ContinuationEnhancer.java index 0340b5faaa..456f28704e 100644 --- a/framework/src/play/classloading/enhancers/ContinuationEnhancer.java +++ b/framework/src/play/classloading/enhancers/ContinuationEnhancer.java @@ -15,16 +15,14 @@ public class ContinuationEnhancer extends Enhancer { - static final List continuationMethods = new ArrayList<>(); - - static { - continuationMethods.add("play.mvc.Controller.await(java.lang.String)"); - continuationMethods.add("play.mvc.Controller.await(int)"); - continuationMethods.add("play.mvc.Controller.await(java.util.concurrent.Future)"); - continuationMethods.add("play.mvc.WebSocketController.await(java.lang.String)"); - continuationMethods.add("play.mvc.WebSocketController.await(int)"); - continuationMethods.add("play.mvc.WebSocketController.await(java.util.concurrent.Future)"); - } + private static final List continuationMethods = List.of( + "play.mvc.Controller.await(java.lang.String)", + "play.mvc.Controller.await(int)", + "play.mvc.Controller.await(java.util.concurrent.Future)", + "play.mvc.WebSocketController.await(java.lang.String)", + "play.mvc.WebSocketController.await(int)", + "play.mvc.WebSocketController.await(java.util.concurrent.Future)" + ); public static boolean isEnhanced(String appClassName) { ApplicationClass appClass = Play.classes.getApplicationClass( appClassName);