Return-Path: X-Original-To: apmail-struts-commits-archive@minotaur.apache.org Delivered-To: apmail-struts-commits-archive@minotaur.apache.org Received: from mail.apache.org (hermes.apache.org [140.211.11.3]) by minotaur.apache.org (Postfix) with SMTP id A2A17184AF for ; Mon, 15 Jun 2015 17:38:04 +0000 (UTC) Received: (qmail 59085 invoked by uid 500); 15 Jun 2015 17:38:03 -0000 Delivered-To: apmail-struts-commits-archive@struts.apache.org Received: (qmail 58955 invoked by uid 500); 15 Jun 2015 17:38:03 -0000 Mailing-List: contact commits-help@struts.apache.org; run by ezmlm Precedence: bulk List-Help: List-Unsubscribe: List-Post: List-Id: Reply-To: dev@struts.apache.org Delivered-To: mailing list commits@struts.apache.org Received: (qmail 58748 invoked by uid 99); 15 Jun 2015 17:38:03 -0000 Received: from git1-us-west.apache.org (HELO git1-us-west.apache.org) (140.211.11.23) by apache.org (qpsmtpd/0.29) with ESMTP; Mon, 15 Jun 2015 17:38:03 +0000 Received: by git1-us-west.apache.org (ASF Mail Server at git1-us-west.apache.org, from userid 33) id E407EE17FD; Mon, 15 Jun 2015 17:38:02 +0000 (UTC) Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit From: jogep@apache.org To: commits@struts.apache.org Date: Mon, 15 Jun 2015 17:38:05 -0000 Message-Id: <841ac35aa323474fbe18e9b37d6d4e5f@git.apache.org> In-Reply-To: References: X-Mailer: ASF-Git Admin Mailer Subject: [4/9] struts git commit: Minor code improvements's in the xwork-core module http://git-wip-us.apache.org/repos/asf/struts/blob/2e9df577/xwork-core/src/main/java/com/opensymphony/xwork2/util/finder/DefaultClassFinder.java ---------------------------------------------------------------------- diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/util/finder/DefaultClassFinder.java b/xwork-core/src/main/java/com/opensymphony/xwork2/util/finder/DefaultClassFinder.java index 80f205a..b703639 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/util/finder/DefaultClassFinder.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/util/finder/DefaultClassFinder.java @@ -19,9 +19,9 @@ import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.FileManager; import com.opensymphony.xwork2.FileManagerFactory; import com.opensymphony.xwork2.XWorkException; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; import org.apache.commons.lang3.StringUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.objectweb.asm.AnnotationVisitor; import org.objectweb.asm.ClassReader; import org.objectweb.asm.FieldVisitor; @@ -38,26 +38,17 @@ import java.lang.reflect.Method; import java.net.JarURLConnection; import java.net.URL; import java.net.URLDecoder; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; +import java.util.*; import java.util.jar.JarEntry; import java.util.jar.JarInputStream; public class DefaultClassFinder implements ClassFinder { private static final Logger LOG = LogManager.getLogger(DefaultClassFinder.class); - private final Map> annotated = new HashMap>(); - private final Map classInfos = new LinkedHashMap(); + private final Map> annotated = new HashMap<>(); + private final Map classInfos = new LinkedHashMap<>(); - private final List classesNotLoaded = new ArrayList(); + private final List classesNotLoaded = new ArrayList<>(); private boolean extractBaseInterfaces; private ClassLoaderInterface classLoaderInterface; @@ -68,7 +59,7 @@ public class DefaultClassFinder implements ClassFinder { this.extractBaseInterfaces = extractBaseInterfaces; this.fileManager = ActionContext.getContext().getInstance(FileManagerFactory.class).getFileManager(); - List classNames = new ArrayList(); + List classNames = new ArrayList<>(); for (URL location : urls) { try { if (protocols.contains(location.getProtocol())) { @@ -105,8 +96,8 @@ public class DefaultClassFinder implements ClassFinder { public DefaultClassFinder(List classes){ this.classLoaderInterface = null; - List infos = new ArrayList(); - List packages = new ArrayList(); + List infos = new ArrayList<>(); + List packages = new ArrayList<>(); for (Class clazz : classes) { Package aPackage = clazz.getPackage(); @@ -154,7 +145,7 @@ public class DefaultClassFinder implements ClassFinder { public List findAnnotatedPackages(Class annotation) { classesNotLoaded.clear(); - List packages = new ArrayList(); + List packages = new ArrayList<>(); List infos = getAnnotationInfos(annotation.getName()); for (Info info : infos) { if (info instanceof PackageInfo) { @@ -175,7 +166,7 @@ public class DefaultClassFinder implements ClassFinder { public List findAnnotatedClasses(Class annotation) { classesNotLoaded.clear(); - List classes = new ArrayList(); + List classes = new ArrayList<>(); List infos = getAnnotationInfos(annotation.getName()); for (Info info : infos) { if (info instanceof ClassInfo) { @@ -197,8 +188,8 @@ public class DefaultClassFinder implements ClassFinder { public List findAnnotatedMethods(Class annotation) { classesNotLoaded.clear(); - List seen = new ArrayList(); - List methods = new ArrayList(); + List seen = new ArrayList<>(); + List methods = new ArrayList<>(); List infos = getAnnotationInfos(annotation.getName()); for (Info info : infos) { if (info instanceof MethodInfo && !"".equals(info.getName())) { @@ -227,8 +218,8 @@ public class DefaultClassFinder implements ClassFinder { public List findAnnotatedConstructors(Class annotation) { classesNotLoaded.clear(); - List seen = new ArrayList(); - List constructors = new ArrayList(); + List seen = new ArrayList<>(); + List constructors = new ArrayList<>(); List infos = getAnnotationInfos(annotation.getName()); for (Info info : infos) { if (info instanceof MethodInfo && "".equals(info.getName())) { @@ -257,15 +248,17 @@ public class DefaultClassFinder implements ClassFinder { public List findAnnotatedFields(Class annotation) { classesNotLoaded.clear(); - List seen = new ArrayList(); - List fields = new ArrayList(); + List seen = new ArrayList<>(); + List fields = new ArrayList<>(); List infos = getAnnotationInfos(annotation.getName()); for (Info info : infos) { if (info instanceof FieldInfo) { FieldInfo fieldInfo = (FieldInfo) info; ClassInfo classInfo = fieldInfo.getDeclaringClass(); - if (seen.contains(classInfo)) continue; + if (seen.contains(classInfo)) { + continue; + } seen.add(classInfo); @@ -287,7 +280,7 @@ public class DefaultClassFinder implements ClassFinder { public List findClassesInPackage(String packageName, boolean recursive) { classesNotLoaded.clear(); - List classes = new ArrayList(); + List classes = new ArrayList<>(); for (ClassInfo classInfo : classInfos.values()) { try { if (recursive && classInfo.getPackageName().startsWith(packageName)){ @@ -305,7 +298,7 @@ public class DefaultClassFinder implements ClassFinder { public List findClasses(Test test) { classesNotLoaded.clear(); - List classes = new ArrayList(); + List classes = new ArrayList<>(); for (ClassInfo classInfo : classInfos.values()) { try { if (test.test(classInfo)) { @@ -321,7 +314,7 @@ public class DefaultClassFinder implements ClassFinder { public List findClasses() { classesNotLoaded.clear(); - List classes = new ArrayList(); + List classes = new ArrayList<>(); for (ClassInfo classInfo : classInfos.values()) { try { classes.add(classInfo.get()); @@ -334,7 +327,7 @@ public class DefaultClassFinder implements ClassFinder { } private static List getURLs(ClassLoaderInterface classLoader, String[] dirNames) { - List urls = new ArrayList(); + List urls = new ArrayList<>(); for (String dirName : dirNames) { try { Enumeration classLoaderURLs = classLoader.getResources(dirName); @@ -351,7 +344,7 @@ public class DefaultClassFinder implements ClassFinder { } private List file(URL location) { - List classNames = new ArrayList(); + List classNames = new ArrayList<>(); File dir = new File(URLDecoder.decode(location.getPath())); if ("META-INF".equals(dir.getName())) { dir = dir.getParentFile(); // Scrape "META-INF" off @@ -394,7 +387,7 @@ public class DefaultClassFinder implements ClassFinder { } private List jar(JarInputStream jarStream) throws IOException { - List classNames = new ArrayList(); + List classNames = new ArrayList<>(); JarEntry entry; while ((entry = jarStream.getNextJarEntry()) != null) { @@ -444,7 +437,7 @@ public class DefaultClassFinder implements ClassFinder { private List getAnnotationInfos(String name) { List infos = annotated.get(name); if (infos == null) { - infos = new ArrayList(); + infos = new ArrayList<>(); annotated.put(name, infos); } return infos; http://git-wip-us.apache.org/repos/asf/struts/blob/2e9df577/xwork-core/src/main/java/com/opensymphony/xwork2/util/finder/ResourceFinder.java ---------------------------------------------------------------------- diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/util/finder/ResourceFinder.java b/xwork-core/src/main/java/com/opensymphony/xwork2/util/finder/ResourceFinder.java index 8e8d2a6..e07503d 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/util/finder/ResourceFinder.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/util/finder/ResourceFinder.java @@ -15,30 +15,16 @@ */ package com.opensymphony.xwork2.util.finder; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; import org.apache.commons.lang3.StringUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import java.io.BufferedInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; -import java.net.HttpURLConnection; -import java.net.JarURLConnection; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLConnection; -import java.net.URLDecoder; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; -import java.util.Vector; +import java.net.*; +import java.util.*; import java.util.jar.JarEntry; import java.util.jar.JarFile; @@ -52,7 +38,7 @@ public class ResourceFinder { private final URL[] urls; private final String path; private final ClassLoaderInterface classLoaderInterface; - private final List resourcesNotLoaded = new ArrayList(); + private final List resourcesNotLoaded = new ArrayList<>(); public ResourceFinder(URL... urls) { this(null, new ClassLoaderInterfaceDelegate(Thread.currentThread().getContextClassLoader()), urls); @@ -71,9 +57,8 @@ public class ResourceFinder { } public ResourceFinder(String path, ClassLoaderInterface classLoaderInterface, URL... urls) { - if (path == null){ - path = ""; - } else if (path.length() > 0 && !path.endsWith("/")) { + path = StringUtils.trimToEmpty(path); + if (!StringUtils.endsWith(path, "/")) { path += "/"; } this.path = path; @@ -131,7 +116,7 @@ public class ResourceFinder { String fullUri = path + uri; Enumeration resources = getResources(fullUri); - List list = new ArrayList(); + List list = new ArrayList<>(); while (resources.hasMoreElements()) { URL url = resources.nextElement(); list.add(url); @@ -175,7 +160,7 @@ public class ResourceFinder { public List findAllStrings(String uri) throws IOException { String fulluri = path + uri; - List strings = new ArrayList(); + List strings = new ArrayList<>(); Enumeration resources = getResources(fulluri); while (resources.hasMoreElements()) { @@ -199,7 +184,7 @@ public class ResourceFinder { resourcesNotLoaded.clear(); String fulluri = path + uri; - List strings = new ArrayList(); + List strings = new ArrayList<>(); Enumeration resources = getResources(fulluri); while (resources.hasMoreElements()) { @@ -239,7 +224,7 @@ public class ResourceFinder { * @throws IOException if any of the urls cannot be read */ public Map mapAllStrings(String uri) throws IOException { - Map strings = new HashMap(); + Map strings = new HashMap<>(); Map resourcesMap = getResourcesMap(uri); for (Map.Entry entry : resourcesMap.entrySet()) { String name = entry.getKey(); @@ -277,7 +262,7 @@ public class ResourceFinder { */ public Map mapAvailableStrings(String uri) throws IOException { resourcesNotLoaded.clear(); - Map strings = new HashMap(); + Map strings = new HashMap<>(); Map resourcesMap = getResourcesMap(uri); for (Map.Entry entry : resourcesMap.entrySet()) { String name = entry.getKey(); @@ -324,7 +309,7 @@ public class ResourceFinder { * @throws ClassNotFoundException */ public List findAllClasses(String uri) throws IOException, ClassNotFoundException { - List classes = new ArrayList(); + List classes = new ArrayList<>(); List strings = findAllStrings(uri); for (String className : strings) { Class clazz = classLoaderInterface.loadClass(className); @@ -346,7 +331,7 @@ public class ResourceFinder { */ public List findAvailableClasses(String uri) throws IOException { resourcesNotLoaded.clear(); - List classes = new ArrayList(); + List classes = new ArrayList<>(); List strings = findAvailableStrings(uri); for (String className : strings) { try { @@ -383,7 +368,7 @@ public class ResourceFinder { * @throws ClassNotFoundException */ public Map mapAllClasses(String uri) throws IOException, ClassNotFoundException { - Map classes = new HashMap(); + Map classes = new HashMap<>(); Map map = mapAllStrings(uri); for (Map.Entry entry : map.entrySet()) { String string = entry.getKey(); @@ -419,7 +404,7 @@ public class ResourceFinder { */ public Map mapAvailableClasses(String uri) throws IOException { resourcesNotLoaded.clear(); - Map classes = new HashMap(); + Map classes = new HashMap<>(); Map map = mapAvailableStrings(uri); for (Map.Entry entry : map.entrySet()) { String string = entry.getKey(); @@ -496,7 +481,7 @@ public class ResourceFinder { * @throws ClassCastException if the class found is not assignable to the specified superclass or interface */ public List findAllImplementations(Class interfase) throws IOException, ClassNotFoundException { - List implementations = new ArrayList(); + List implementations = new ArrayList<>(); List strings = findAllStrings(interfase.getName()); for (String className : strings) { Class impl = classLoaderInterface.loadClass(className); @@ -533,7 +518,7 @@ public class ResourceFinder { */ public List findAvailableImplementations(Class interfase) throws IOException { resourcesNotLoaded.clear(); - List implementations = new ArrayList(); + List implementations = new ArrayList<>(); List strings = findAvailableStrings(interfase.getName()); for (String className : strings) { try { @@ -576,7 +561,7 @@ public class ResourceFinder { * @throws ClassCastException if the class found is not assignable to the specified superclass or interface */ public Map mapAllImplementations(Class interfase) throws IOException, ClassNotFoundException { - Map implementations = new HashMap(); + Map implementations = new HashMap<>(); Map map = mapAllStrings(interfase.getName()); for (Map.Entry entry : map.entrySet()) { String string = entry.getKey(); @@ -615,7 +600,7 @@ public class ResourceFinder { */ public Map mapAvailableImplementations(Class interfase) throws IOException { resourcesNotLoaded.clear(); - Map implementations = new HashMap(); + Map implementations = new HashMap<>(); Map map = mapAvailableStrings(interfase.getName()); for (Map.Entry entry : map.entrySet()) { String string = entry.getKey(); @@ -686,7 +671,7 @@ public class ResourceFinder { public List findAllProperties(String uri) throws IOException { String fulluri = path + uri; - List properties = new ArrayList(); + List properties = new ArrayList<>(); Enumeration resources = getResources(fulluri); while (resources.hasMoreElements()) { @@ -720,7 +705,7 @@ public class ResourceFinder { resourcesNotLoaded.clear(); String fulluri = path + uri; - List properties = new ArrayList(); + List properties = new ArrayList<>(); Enumeration resources = getResources(fulluri); while (resources.hasMoreElements()) { @@ -757,7 +742,7 @@ public class ResourceFinder { * @throws IOException if the URL cannot be read or is not in properties file format */ public Map mapAllProperties(String uri) throws IOException { - Map propertiesMap = new HashMap(); + Map propertiesMap = new HashMap<>(); Map map = getResourcesMap(uri); for (Map.Entry entry : map.entrySet()) { String string = entry.getKey(); @@ -792,7 +777,7 @@ public class ResourceFinder { */ public Map mapAvailableProperties(String uri) throws IOException { resourcesNotLoaded.clear(); - Map propertiesMap = new HashMap(); + Map propertiesMap = new HashMap<>(); Map map = getResourcesMap(uri); for (Map.Entry entry : map.entrySet()) { String string = entry.getKey(); @@ -816,7 +801,7 @@ public class ResourceFinder { public Map getResourcesMap(String uri) throws IOException { String basePath = path + uri; - Map resources = new HashMap(); + Map resources = new HashMap<>(); if (!basePath.endsWith("/")) { basePath += "/"; } @@ -827,13 +812,9 @@ public class ResourceFinder { try { if ("jar".equals(location.getProtocol())) { - readJarEntries(location, basePath, resources); - } else if ("file".equals(location.getProtocol())) { - readDirectoryEntries(location, resources); - } } catch (Exception e) { LOG.debug("Got exception loading resources for {}", uri, e); @@ -849,7 +830,7 @@ public class ResourceFinder { public Set findPackages(String uri) throws IOException { String basePath = path + uri; - Set resources = new HashSet(); + Set resources = new HashSet<>(); if (!basePath.endsWith("/")) { basePath += "/"; } @@ -860,13 +841,9 @@ public class ResourceFinder { try { if ("jar".equals(location.getProtocol())) { - readJarDirectoryEntries(location, basePath, resources); - } else if ("file".equals(location.getProtocol())) { - readSubDirectories(new File(location.toURI()), uri, resources); - } } catch (Exception e) { LOG.debug("Got exception search for subpackages for {}", uri, e); @@ -886,18 +863,18 @@ public class ResourceFinder { basePath += "/"; } Enumeration urls = getResources(basePath); - Map> result = new HashMap>(); + Map> result = new HashMap<>(); while (urls.hasMoreElements()) { URL location = urls.nextElement(); try { if ("jar".equals(location.getProtocol())) { - Set resources = new HashSet(); + Set resources = new HashSet<>(); readJarDirectoryEntries(location, basePath, resources); result.put(location, convertPathsToPackages(resources)); } else if ("file".equals(location.getProtocol())) { - Set resources = new HashSet(); + Set resources = new HashSet<>(); readSubDirectories(new File(location.toURI()), uri, resources); result.put(location, convertPathsToPackages(resources)); } @@ -910,9 +887,9 @@ public class ResourceFinder { } private Set convertPathsToPackages(Set resources) { - Set packageNames = new HashSet(resources.size()); + Set packageNames = new HashSet<>(resources.size()); for(String resource : resources) { - packageNames.add(StringUtils.chomp(StringUtils.replace(resource, "/", "."), ".")); + packageNames.add(StringUtils.removeEnd(StringUtils.replace(resource, "/", "."), ".")); } return packageNames; @@ -941,7 +918,7 @@ public class ResourceFinder { for (File file : files) { if (file.isDirectory()) { String name = file.getName(); - String subName = StringUtils.chomp(basePath, "/") + "/" + name; + String subName = StringUtils.removeEnd(basePath, "/") + "/" + name; resources.add(subName); readSubDirectories(file, subName, resources); } @@ -951,7 +928,7 @@ public class ResourceFinder { private static void readJarEntries(URL location, String basePath, Map resources) throws IOException { JarURLConnection conn = (JarURLConnection) location.openConnection(); - JarFile jarfile = null; + JarFile jarfile; jarfile = conn.getJarFile(); Enumeration entries = jarfile.entries(); @@ -977,7 +954,7 @@ public class ResourceFinder { //read directories in the jar that start with the basePath private static void readJarDirectoryEntries(URL location, String basePath, Set resources) throws IOException { JarURLConnection conn = (JarURLConnection) location.openConnection(); - JarFile jarfile = null; + JarFile jarfile; jarfile = conn.getJarFile(); Enumeration entries = jarfile.entries(); @@ -1058,7 +1035,7 @@ public class ResourceFinder { if (currentUrl == null) { continue; } - JarFile jarFile = null; + JarFile jarFile; try { String protocol = currentUrl.getProtocol(); if ("jar".equals(protocol)) { @@ -1147,10 +1124,8 @@ public class ResourceFinder { return resourceURL; } } - } catch (MalformedURLException e) { + } catch (IOException | SecurityException e) { // Keep iterating through the URL list - } catch (IOException e) { - } catch (SecurityException e) { } } return null; http://git-wip-us.apache.org/repos/asf/struts/blob/2e9df577/xwork-core/src/main/java/com/opensymphony/xwork2/util/finder/UrlSet.java ---------------------------------------------------------------------- diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/util/finder/UrlSet.java b/xwork-core/src/main/java/com/opensymphony/xwork2/util/finder/UrlSet.java index f5de6fd..34e0937 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/util/finder/UrlSet.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/util/finder/UrlSet.java @@ -15,24 +15,16 @@ */ package com.opensymphony.xwork2.util.finder; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; +import java.util.*; /** * Use with ClassFinder to filter the Urls to be scanned, example: @@ -57,7 +49,7 @@ public class UrlSet { private Set protocols; private UrlSet() { - this.urls = new HashMap(); + this.urls = new HashMap<>(); } public UrlSet(ClassLoaderInterface classLoader) throws IOException { @@ -92,21 +84,19 @@ public class UrlSet { try { this.urls.put(location.toExternalForm(), location); } catch (Exception e) { - if (LOG.isWarnEnabled()) { - LOG.warn("Cannot translate url to external form!", e); - } + LOG.warn("Cannot translate url to external form!", e); } } } public UrlSet include(UrlSet urlSet){ - Map urls = new HashMap(this.urls); + Map urls = new HashMap<>(this.urls); urls.putAll(urlSet.urls); return new UrlSet(urls); } public UrlSet exclude(UrlSet urlSet) { - Map urls = new HashMap(this.urls); + Map urls = new HashMap<>(this.urls); Map parentUrls = urlSet.urls; for (String url : parentUrls.keySet()) { urls.remove(url); @@ -148,9 +138,7 @@ public class UrlSet { public UrlSet excludeJavaHome() throws MalformedURLException { String path = System.getProperty("java.home"); if (path != null) { - File java = new File(path); - if (path.matches("/System/Library/Frameworks/JavaVM.framework/Versions/[^/]+/Home")){ java = java.getParentFile(); } @@ -173,7 +161,7 @@ public class UrlSet { } public UrlSet matching(String pattern) { - Map urls = new HashMap(); + Map urls = new HashMap<>(); for (Map.Entry entry : this.urls.entrySet()) { String url = entry.getKey(); if (url.matches(pattern)){ @@ -198,7 +186,7 @@ public class UrlSet { URL normalizedUrl = normalizer.normalizeToFileProtocol(warUrl); URL finalUrl = ObjectUtils.defaultIfNull(normalizedUrl, warUrl); - Map newUrls = new HashMap(this.urls); + Map newUrls = new HashMap<>(this.urls); if ("jar".equals(finalUrl.getProtocol()) || "file".equals(finalUrl.getProtocol())) { newUrls.put(finalUrl.toExternalForm(), finalUrl); } @@ -211,7 +199,7 @@ public class UrlSet { public UrlSet relative(File file) throws MalformedURLException { String urlPath = file.toURI().toURL().toExternalForm(); - Map urls = new HashMap(); + Map urls = new HashMap<>(); for (Map.Entry entry : this.urls.entrySet()) { String url = entry.getKey(); if (url.startsWith(urlPath) || url.startsWith("jar:"+urlPath)){ @@ -222,11 +210,11 @@ public class UrlSet { } public List getUrls() { - return new ArrayList(urls.values()); + return new ArrayList<>(urls.values()); } private List getUrls(ClassLoaderInterface classLoader) throws IOException { - List list = new ArrayList(); + List list = new ArrayList<>(); //find jars ArrayList urls = Collections.list(classLoader.getResources("META-INF")); @@ -253,7 +241,7 @@ public class UrlSet { return getUrls(classLoader); } - List list = new ArrayList(); + List list = new ArrayList<>(); //find jars ArrayList urls = Collections.list(classLoader.getResources("META-INF")); http://git-wip-us.apache.org/repos/asf/struts/blob/2e9df577/xwork-core/src/main/java/com/opensymphony/xwork2/util/fs/DefaultFileManager.java ---------------------------------------------------------------------- diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/util/fs/DefaultFileManager.java b/xwork-core/src/main/java/com/opensymphony/xwork2/util/fs/DefaultFileManager.java index 42d2a38..86fda9b 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/util/fs/DefaultFileManager.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/util/fs/DefaultFileManager.java @@ -16,18 +16,14 @@ package com.opensymphony.xwork2.util.fs; import com.opensymphony.xwork2.FileManager; -import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; +import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -90,9 +86,7 @@ public class DefaultFileManager implements FileManager { public void monitorFile(URL fileUrl) { String fileName = fileUrl.toString(); Revision revision; - if (LOG.isDebugEnabled()) { - LOG.debug("Creating revision for URL: " + fileName); - } + LOG.debug("Creating revision for URL: {}", fileName); if (isJarURL(fileUrl)) { revision = JarEntryRevision.build(fileUrl, this); } else { http://git-wip-us.apache.org/repos/asf/struts/blob/2e9df577/xwork-core/src/main/java/com/opensymphony/xwork2/util/fs/DefaultFileManagerFactory.java ---------------------------------------------------------------------- diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/util/fs/DefaultFileManagerFactory.java b/xwork-core/src/main/java/com/opensymphony/xwork2/util/fs/DefaultFileManagerFactory.java index 7c872f3..c19385f 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/util/fs/DefaultFileManagerFactory.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/util/fs/DefaultFileManagerFactory.java @@ -5,8 +5,8 @@ import com.opensymphony.xwork2.FileManagerFactory; import com.opensymphony.xwork2.XWorkConstants; import com.opensymphony.xwork2.inject.Container; import com.opensymphony.xwork2.inject.Inject; -import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import java.util.HashSet; import java.util.Set; @@ -52,8 +52,8 @@ public class DefaultFileManagerFactory implements FileManagerFactory { private FileManager lookupFileManager() { Set names = container.getInstanceNames(FileManager.class); LOG.debug("Found following implementations of FileManager interface: {}", names); - Set internals = new HashSet(); - Set users = new HashSet(); + Set internals = new HashSet<>(); + Set users = new HashSet<>(); for (String fmName : names) { FileManager fm = container.getInstance(FileManager.class, fmName); if (fm.internal()) { http://git-wip-us.apache.org/repos/asf/struts/blob/2e9df577/xwork-core/src/main/java/com/opensymphony/xwork2/util/location/LocatableProperties.java ---------------------------------------------------------------------- diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/util/location/LocatableProperties.java b/xwork-core/src/main/java/com/opensymphony/xwork2/util/location/LocatableProperties.java index 9b41eb1..8df44f3 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/util/location/LocatableProperties.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/util/location/LocatableProperties.java @@ -28,7 +28,7 @@ public class LocatableProperties extends Properties implements Locatable { public LocatableProperties(Location loc) { super(); this.location = loc; - this.propLocations = new HashMap(); + this.propLocations = new HashMap<>(); } @Override @@ -48,7 +48,7 @@ public class LocatableProperties extends Properties implements Locatable { String convertCommentsToString(List lines) { StringBuilder sb = new StringBuilder(); - if (lines != null && lines.size() > 0) { + if (lines != null && !lines.isEmpty()) { for (String line : lines) { sb.append(line).append('\n'); } http://git-wip-us.apache.org/repos/asf/struts/blob/2e9df577/xwork-core/src/main/java/com/opensymphony/xwork2/util/location/LocationImpl.java ---------------------------------------------------------------------- diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/util/location/LocationImpl.java b/xwork-core/src/main/java/com/opensymphony/xwork2/util/location/LocationImpl.java index 3a1974f..ca101ca 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/util/location/LocationImpl.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/util/location/LocationImpl.java @@ -15,6 +15,8 @@ */ package com.opensymphony.xwork2.util.location; +import org.apache.commons.lang3.StringUtils; + import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; @@ -53,7 +55,7 @@ public class LocationImpl implements Location, Serializable { * @param column the column number (starts at 1) */ public LocationImpl(String description, String uri, int line, int column) { - if (uri == null || uri.length() == 0) { + if (StringUtils.isEmpty(uri)) { this.uri = null; this.line = -1; this.column = -1; @@ -62,11 +64,7 @@ public class LocationImpl implements Location, Serializable { this.line = line; this.column = column; } - - if (description != null && description.length() == 0) { - description = null; - } - this.description = description; + this.description = StringUtils.trimToNull(description); } /** @@ -147,7 +145,7 @@ public class LocationImpl implements Location, Serializable { * @param padding The amount of lines before and after the error to include */ public List getSnippet(int padding) { - List snippet = new ArrayList(); + List snippet = new ArrayList<>(); if (getLineNumber() > 0) { try { InputStream in = new URL(getURI()).openStream(); http://git-wip-us.apache.org/repos/asf/struts/blob/2e9df577/xwork-core/src/main/java/com/opensymphony/xwork2/util/location/LocationUtils.java ---------------------------------------------------------------------- diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/util/location/LocationUtils.java b/xwork-core/src/main/java/com/opensymphony/xwork2/util/location/LocationUtils.java index fd2c55d..892d3c7 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/util/location/LocationUtils.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/util/location/LocationUtils.java @@ -36,8 +36,8 @@ public class LocationUtils { * The string representation of an unknown location: "[unknown location]". */ public static final String UNKNOWN_STRING = "[unknown location]"; - - private static List> finders = new ArrayList>(); + + private static List> finders = new ArrayList<>(); /** * An finder or object locations @@ -182,7 +182,7 @@ public class LocationUtils { synchronized(LocationFinder.class) { // Update a clone of the current finder list to avoid breaking // any iteration occuring in another thread. - List> newFinders = new ArrayList>(finders); + List> newFinders = new ArrayList<>(finders); newFinders.add(new WeakReference(finder)); finders = newFinders; } @@ -259,7 +259,7 @@ public class LocationUtils { // This finder was garbage collected: update finders synchronized(LocationFinder.class) { // Update a clone of the current list to avoid breaking current iterations - List> newFinders = new ArrayList>(finders); + List> newFinders = new ArrayList<>(finders); newFinders.remove(ref); finders = newFinders; } http://git-wip-us.apache.org/repos/asf/struts/blob/2e9df577/xwork-core/src/main/java/com/opensymphony/xwork2/util/profiling/ObjectProfiler.java ---------------------------------------------------------------------- diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/util/profiling/ObjectProfiler.java b/xwork-core/src/main/java/com/opensymphony/xwork2/util/profiling/ObjectProfiler.java index d374a2c..7438113 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/util/profiling/ObjectProfiler.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/util/profiling/ObjectProfiler.java @@ -34,13 +34,12 @@ import java.lang.reflect.Proxy; /** * @author Scott Farquhar */ -public class ObjectProfiler -{ +public class ObjectProfiler { /** * Given a class, and an interface that it implements, return a proxied version of the class that implements * the interface. - *

+ *

* The usual use of this is to profile methods from Factory objects: *

      * public PersistenceManager getPersistenceManager()
@@ -54,28 +53,25 @@ public class ObjectProfiler
      *   return ObjectProfiler.getProfiledObject(PersistenceManager.class, new DefaultPersistenceManager());
      * }
      * 
- *

+ *

* A side effect of this is that you will no longer be able to downcast to DefaultPersistenceManager. This is probably a *good* thing. * - * @param interfaceClazz The interface to implement. - * @param o The object to proxy - * @return A proxied object, or the input object if the interfaceClazz wasn't an interface. + * @param interfaceClazz The interface to implement. + * @param o The object to proxy + * @return A proxied object, or the input object if the interfaceClazz wasn't an interface. */ - public static Object getProfiledObject(Class interfaceClazz, Object o) - { + public static Object getProfiledObject(Class interfaceClazz, Object o) { //if we are not active - then do nothing - if (!UtilTimerStack.isActive()) + if (!UtilTimerStack.isActive()) { return o; + } //this should always be true - you shouldn't be passing something that isn't an interface - if (interfaceClazz.isInterface()) - { + if (interfaceClazz.isInterface()) { InvocationHandler timerHandler = new TimerInvocationHandler(o); return Proxy.newProxyInstance(interfaceClazz.getClassLoader(), new Class[]{interfaceClazz}, timerHandler); - } - else - { + } else { return o; } } @@ -84,34 +80,27 @@ public class ObjectProfiler * A profiled call {@link Method#invoke(java.lang.Object, java.lang.Object[])}. If {@link UtilTimerStack#isActive() } * returns false, then no profiling is performed. */ - public static Object profiledInvoke(Method target, Object value, Object[] args) throws IllegalAccessException, InvocationTargetException - { + public static Object profiledInvoke(Method target, Object value, Object[] args) throws IllegalAccessException, InvocationTargetException { //if we are not active - then do nothing - if (!UtilTimerStack.isActive()) + if (!UtilTimerStack.isActive()) { return target.invoke(value, args); + } String logLine = new String(getTrimmedClassName(target) + "." + target.getName() + "()"); UtilTimerStack.push(logLine); - try - { + try { Object returnValue = target.invoke(value, args); //if the return value is an interface then we should also proxy it! - if (returnValue != null && target.getReturnType().isInterface()) - { -// System.out.println("Return type " + returnValue.getClass().getName() + " is being proxied " + target.getReturnType().getName() + " " + logLine); + if (returnValue != null && target.getReturnType().isInterface()) { InvocationHandler timerHandler = new TimerInvocationHandler(returnValue); return Proxy.newProxyInstance(returnValue.getClass().getClassLoader(), new Class[]{target.getReturnType()}, timerHandler); - } - else - { + } else { return returnValue; } - } - finally - { + } finally { UtilTimerStack.pop(logLine); } } @@ -119,27 +108,24 @@ public class ObjectProfiler /** * Given a method, get the Method name, with no package information. */ - public static String getTrimmedClassName(Method method) - { + public static String getTrimmedClassName(Method method) { String classname = method.getDeclaringClass().getName(); return classname.substring(classname.lastIndexOf('.') + 1); } } -class TimerInvocationHandler implements InvocationHandler -{ +class TimerInvocationHandler implements InvocationHandler { protected Object target; - public TimerInvocationHandler(Object target) - { - if (target == null) + public TimerInvocationHandler(Object target) { + if (target == null) { throw new IllegalArgumentException("Target Object passed to timer cannot be null"); + } this.target = target; } - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable - { + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return ObjectProfiler.profiledInvoke(method, target, args); } http://git-wip-us.apache.org/repos/asf/struts/blob/2e9df577/xwork-core/src/main/java/com/opensymphony/xwork2/util/profiling/ProfilingTimerBean.java ---------------------------------------------------------------------- diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/util/profiling/ProfilingTimerBean.java b/xwork-core/src/main/java/com/opensymphony/xwork2/util/profiling/ProfilingTimerBean.java index 35baaa4..a475c62 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/util/profiling/ProfilingTimerBean.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/util/profiling/ProfilingTimerBean.java @@ -34,14 +34,13 @@ import java.util.List; * * @author Mike Cannon-Brookes * @author Scott Farquhar - * * @version $Date$ $Id$ */ public class ProfilingTimerBean implements java.io.Serializable { - - private static final long serialVersionUID = -6180672043920208784L; - - List children = new ArrayList(); + + private static final long serialVersionUID = -6180672043920208784L; + + List children = new ArrayList<>(); ProfilingTimerBean parent = null; String resource; @@ -49,41 +48,34 @@ public class ProfilingTimerBean implements java.io.Serializable { long startTime; long totalTime; - public ProfilingTimerBean(String resource) - { + public ProfilingTimerBean(String resource) { this.resource = resource; } - protected void addParent(ProfilingTimerBean parent) - { + protected void addParent(ProfilingTimerBean parent) { this.parent = parent; } - public ProfilingTimerBean getParent() - { + public ProfilingTimerBean getParent() { return parent; } - public void addChild(ProfilingTimerBean child) - { + public void addChild(ProfilingTimerBean child) { children.add(child); child.addParent(this); } - public void setStartTime() - { + public void setStartTime() { this.startTime = System.currentTimeMillis(); } - public void setEndTime() - { + public void setEndTime() { this.totalTime = System.currentTimeMillis() - startTime; } - public String getResource() - { + public String getResource() { return resource; } @@ -91,16 +83,13 @@ public class ProfilingTimerBean implements java.io.Serializable { * Get a formatted string representing all the methods that took longer than a specified time. */ - public String getPrintable(long minTime) - { + public String getPrintable(long minTime) { return getPrintable("", minTime); } - protected String getPrintable(String indent, long minTime) - { + protected String getPrintable(String indent, long minTime) { //only print the value if we are larger or equal to the min time. - if (totalTime >= minTime) - { + if (totalTime >= minTime) { StringBuilder buffer = new StringBuilder(); buffer.append(indent); buffer.append("[" + totalTime + "ms] - " + resource); @@ -111,8 +100,7 @@ public class ProfilingTimerBean implements java.io.Serializable { } return buffer.toString(); - } - else + } else return ""; } } http://git-wip-us.apache.org/repos/asf/struts/blob/2e9df577/xwork-core/src/main/java/com/opensymphony/xwork2/util/profiling/UtilTimerStack.java ---------------------------------------------------------------------- diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/util/profiling/UtilTimerStack.java b/xwork-core/src/main/java/com/opensymphony/xwork2/util/profiling/UtilTimerStack.java index d9bbf27..7fb7ae2 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/util/profiling/UtilTimerStack.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/util/profiling/UtilTimerStack.java @@ -26,204 +26,204 @@ */ package com.opensymphony.xwork2.util.profiling; -import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; /** * A timer stack. - * - *

- * + *

+ *

+ *

* - * + *

* Struts2 profiling aspects involves the following :- *

    - *
  • ActionContextCleanUp
  • - *
  • FreemarkerPageFilter
  • - *
  • DispatcherFilter
  • - *
      - *
    • Dispatcher
    • - *
        - *
      • creation of DefaultActionProxy
      • - *
          - *
        • creation of DefaultActionInvocation
        • - *
            - *
          • creation of Action
          • - *
          - *
        - *
      • execution of DefaultActionProxy
      • - *
          - *
        • invocation of DefaultActionInvocation
        • - *
            - *
          • invocation of Interceptors
          • - *
          • invocation of Action
          • - *
          • invocation of PreResultListener
          • - *
          • invocation of Result
          • - *
          - *
        - *
      - *
    + *
  • ActionContextCleanUp
  • + *
  • FreemarkerPageFilter
  • + *
  • DispatcherFilter
  • + *
      + *
    • Dispatcher
    • + *
        + *
      • creation of DefaultActionProxy
      • + *
          + *
        • creation of DefaultActionInvocation
        • + *
            + *
          • creation of Action
          • *
          - * + *
        + *
      • execution of DefaultActionProxy
      • + *
          + *
        • invocation of DefaultActionInvocation
        • + *
            + *
          • invocation of Interceptors
          • + *
          • invocation of Action
          • + *
          • invocation of PreResultListener
          • + *
          • invocation of Result
          • + *
          + *
        + *
      + *
    + *
+ *

* - * - * + *

+ *

* - * + *

* XWork2 profiling aspects involves the following :- *

    - *
      - *
    • creation of DefaultActionProxy
    • - *
        - *
      • creation of DefaultActionInvocation
      • - *
          - *
        • creation of Action
        • - *
        - *
      - *
    • execution of DefaultActionProxy
    • - *
        - *
      • invocation of DefaultActionInvocation
      • - *
          - *
        • invocation of Interceptors
        • - *
        • invocation of Action
        • - *
        • invocation of PreResultListener
        • - *
        • invocation of Result
        • - *
        - *
      - *
    + *
      + *
    • creation of DefaultActionProxy
    • + *
        + *
      • creation of DefaultActionInvocation
      • + *
          + *
        • creation of Action
        • *
        - * + *
      + *
    • execution of DefaultActionProxy
    • + *
        + *
      • invocation of DefaultActionInvocation
      • + *
          + *
        • invocation of Interceptors
        • + *
        • invocation of Action
        • + *
        • invocation of PreResultListener
        • + *
        • invocation of Result
        • + *
        + *
      + *
    + *
+ *

* - * - * + *

+ *

* - * - * Activating / Deactivating of the profiling feature could be done through:- - * + *

+ * Activating / Deactivating of the profiling feature could be done through:- + *

* - * *

- * + *

+ *

* System properties:-

*

  * 
- * 
+ *
  *  -Dxwork.profile.activate=true
- *  
- *  
+ *
+ * 
  * 
- * + *

* - * - * This could be done in the container startup script eg. CATALINA_OPTS in catalina.sh - * (tomcat) or using "java -Dxwork.profile.activate=true -jar start.jar" (jetty) - * + *

+ * This could be done in the container startup script eg. CATALINA_OPTS in catalina.sh + * (tomcat) or using "java -Dxwork.profile.activate=true -jar start.jar" (jetty) + *

* - * + *

*

* Code :-

*

  * 
- *   
+ *
  *  UtilTimerStack.setActivate(true);
- *    
- *  
+ *
+ * 
  * 
- * - * - * + *

+ *

+ *

* - * - * This could be done in a static block, in a Spring bean with lazy-init="false", - * in a Servlet with init-on-startup as some numeric value, in a Filter or + *

+ * This could be done in a static block, in a Spring bean with lazy-init="false", + * in a Servlet with init-on-startup as some numeric value, in a Filter or * Listener's init method etc. - * + *

* - * *

- * Parameter:- - * + *

+ * Parameter:- + *

*

  * 
- * 
- * <action ... >  
+ *
+ * <action ... >
  *  ...
  *  <interceptor-ref name="profiling">
  *      <param name="profilingKey">profiling</param>
  *  </interceptor-ref>
  *  ...
  * </action>
- * 
- * or 
- * 
+ *
+ * or
+ *
  * <action .... >
  * ...
  *  <interceptor-ref name="profiling" />
  * ...
  * </action>
- * 
+ *
  * through url
- * 
+ *
  * http://host:port/context/namespace/someAction.action?profiling=true
- * 
+ *
  * through code
- * 
+ *
  * ActionContext.getContext().getParameters().put("profiling", "true);
- * 
+ *
  * 
  * 
- * - * + *

+ *

* - * - * To use profiling activation through parameter, one will need to pass in through - * the 'profiling' parameter (which is the default) and could be changed through - * the param tag in the interceptor-ref. - * + *

+ * To use profiling activation through parameter, one will need to pass in through + * the 'profiling' parameter (which is the default) and could be changed through + * the param tag in the interceptor-ref. + *

* - * + *

*

* Warning:

* - * + *

* Profiling activation through a parameter requires the following: - * + *

*

    - *
  • Profiling interceptor in interceptor stack
  • - *
  • dev mode on (struts.devMode=true in struts.properties) + *
  • Profiling interceptor in interceptor stack
  • + *
  • dev mode on (struts.devMode=true in struts.properties) *
- * + *

* - * *

- * + *

+ *

* - * + *

* One could filter out the profile logging by having a System property as follows. With this - * 'xwork.profile.mintime' property, one could only log profile information when its execution time - * exceed those specified in 'xwork.profile.mintime' system property. If no such property is specified, + * 'xwork.profile.mintime' property, one could only log profile information when its execution time + * exceed those specified in 'xwork.profile.mintime' system property. If no such property is specified, * it will be assumed to be 0, hence all profile information will be logged. - * + *

* - * + *

*

  * 
- * 
+ *
  *  -Dxwork.profile.mintime=10000
- * 
+ *
  * 
  * 
- * + *

* - * - * One could extend the profiling feature provided by Struts2 in their web application as well. - * + *

+ * One could extend the profiling feature provided by Struts2 in their web application as well. + *

* - * + *

*

  * 
- * 
+ *
  *    String logMessage = "Log message";
  *    UtilTimerStack.push(logMessage);
  *    try {
@@ -232,43 +232,42 @@ import org.apache.logging.log4j.LogManager;
  *    finally {
  *        UtilTimerStack.pop(logMessage); // this needs to be the same text as above
  *    }
- *    
- *    
+ *
+ * 
  * 
- * - * or - * + *

+ * or + *

*

  * 
- * 
- *   String result = UtilTimerStack.profile("purchaseItem: ", 
+ *
+ *   String result = UtilTimerStack.profile("purchaseItem: ",
  *       new UtilTimerStack.ProfilingBlock() {
  *            public String doProfiling() {
  *               // do some code
  *               return "Ok";
  *            }
  *       });
- *       
- *       
+ *
+ * 
  * 
- * - * + *

+ *

* - * - * Profiled result is logged using commons-logging under the logger named + *

+ * Profiled result is logged using commons-logging under the logger named * 'com.opensymphony.xwork2.util.profiling.UtilTimerStack'. Depending on the underlying logging implementation - * say if it is Log4j, one could direct the log to appear in a different file, being emailed to someone or have + * say if it is Log4j, one could direct the log to appear in a different file, being emailed to someone or have * it stored in the db. - * + *

* - * + * * @version $Date$ $Id$ */ -public class UtilTimerStack -{ +public class UtilTimerStack { // A reference to the current ProfilingTimerBean - protected static ThreadLocal current = new ThreadLocal(); + protected static ThreadLocal current = new ThreadLocal<>(); /** * System property that controls whether this timer should be used or not. Set to "true" activates @@ -281,7 +280,7 @@ public class UtilTimerStack * created. */ public static final String MIN_TIME = "xwork.profile.mintime"; - + private static final Logger LOG = LogManager.getLogger(UtilTimerStack.class); /** @@ -294,15 +293,15 @@ public class UtilTimerStack } /** - * Create and start a performance profiling with the name given. Deal with + * Create and start a performance profiling with the name given. Deal with * profile hierarchy automatically, so caller don't have to be concern about it. - * + * * @param name profile name */ - public static void push(String name) - { - if (!isActive()) + public static void push(String name) { + if (!isActive()) { return; + } //create a new timer and start it ProfilingTimerBean newTimer = new ProfilingTimerBean(name); @@ -310,8 +309,7 @@ public class UtilTimerStack //if there is a current timer - add the new timer as a child of it ProfilingTimerBean currentTimer = (ProfilingTimerBean) current.get(); - if (currentTimer != null) - { + if (currentTimer != null) { currentTimer.addChild(newTimer); } @@ -322,116 +320,96 @@ public class UtilTimerStack /** * End a preformance profiling with the name given. Deal with * profile hierarchy automatically, so caller don't have to be concern about it. - * + * * @param name profile name */ - public static void pop(String name) - { - if (!isActive()) + public static void pop(String name) { + if (!isActive()) { return; + } - ProfilingTimerBean currentTimer = (ProfilingTimerBean) current.get(); + ProfilingTimerBean currentTimer = current.get(); //if the timers are matched up with each other (ie push("a"); pop("a")); - if (currentTimer != null && name != null && name.equals(currentTimer.getResource())) - { + if (currentTimer != null && name != null && name.equals(currentTimer.getResource())) { currentTimer.setEndTime(); ProfilingTimerBean parent = currentTimer.getParent(); //if we are the root timer, then print out the times - if (parent == null) - { + if (parent == null) { printTimes(currentTimer); current.set(null); //for those servers that use thread pooling - } - else - { + } else { current.set(parent); } - } - else - { + } else { //if timers are not matched up, then print what we have, and then print warning. - if (currentTimer != null) - { + if (currentTimer != null) { printTimes(currentTimer); current.set(null); //prevent printing multiple times - if (LOG.isWarnEnabled()) { - LOG.warn("Unmatched Timer. Was expecting " + currentTimer.getResource() + ", instead got " + name); - } + LOG.warn("Unmatched Timer. Was expecting {}, instead got {}", currentTimer.getResource(), name); } } - - } /** * Do a log (at INFO level) of the time taken for this particular profiling. - * + * * @param currentTimer profiling timer bean */ - private static void printTimes(ProfilingTimerBean currentTimer) - { - if (LOG.isInfoEnabled()) { - LOG.info(currentTimer.getPrintable(getMinTime())); - } + private static void printTimes(ProfilingTimerBean currentTimer) { + LOG.info(currentTimer.getPrintable(getMinTime())); } /** * Get the min time for this profiling, it searches for a System property * 'xwork.profile.mintime' and default to 0. - * + * * @return long */ - private static long getMinTime() - { - try - { + private static long getMinTime() { + try { return Long.parseLong(System.getProperty(MIN_TIME, "0")); - } - catch (NumberFormatException e) - { - return -1; + } catch (NumberFormatException e) { + return -1; } } /** * Determine if profiling is being activated, by searching for a system property * 'xwork.profile.activate', default to false (profiling is off). - * + * * @return true, if active, false otherwise. */ - public static boolean isActive() - { + public static boolean isActive() { return active; } /** * Turn profiling on or off. - * + * * @param active */ - public static void setActive(boolean active) - { - if (active) + public static void setActive(boolean active) { + if (active) { System.setProperty(ACTIVATE_PROPERTY, "true"); - else - System.clearProperty(ACTIVATE_PROPERTY); - - UtilTimerStack.active = active; + } else { + System.clearProperty(ACTIVATE_PROPERTY); + } + UtilTimerStack.active = active; } /** - * A convenience method that allows block of code subjected to profiling to be executed - * and avoid the need of coding boiler code that does pushing (UtilTimeBean.push(...)) and + * A convenience method that allows block of code subjected to profiling to be executed + * and avoid the need of coding boiler code that does pushing (UtilTimeBean.push(...)) and * poping (UtilTimerBean.pop(...)) in a try ... finally ... block. - * *

- * + *

+ *

* Example of usage: *

      * 	 // we need a returning result
-     *   String result = UtilTimerStack.profile("purchaseItem: ", 
+     *   String result = UtilTimerStack.profile("purchaseItem: ",
      *       new UtilTimerStack.ProfilingBlock() {
      *            public String doProfiling() {
      *               getMyService().purchaseItem(....)
@@ -442,7 +420,7 @@ public class UtilTimerStack
      * or
      * 
      *   // we don't need a returning result
-     *   UtilTimerStack.profile("purchaseItem: ", 
+     *   UtilTimerStack.profile("purchaseItem: ",
      *       new UtilTimerStack.ProfilingBlock() {
      *            public String doProfiling() {
      *               getMyService().purchaseItem(....)
@@ -450,40 +428,38 @@ public class UtilTimerStack
      *            }
      *       });
      * 
- * - * @param any return value if there's one. - * @param name profile name + * + * @param any return value if there's one. + * @param name profile name * @param block code block subjected to profiling * @return T * @throws Exception */ public static T profile(String name, ProfilingBlock block) throws Exception { - UtilTimerStack.push(name); - try { - return block.doProfiling(); - } - finally { - UtilTimerStack.pop(name); - } + UtilTimerStack.push(name); + try { + return block.doProfiling(); + } finally { + UtilTimerStack.pop(name); + } } - + /** * A callback interface where code subjected to profile is to be executed. This eliminates the need * of coding boiler code that does pushing (UtilTimerBean.push(...)) and poping (UtilTimerBean.pop(...)) * in a try ... finally ... block. - * - * @version $Date$ $Id$ - * + * * @param + * @version $Date$ $Id$ */ public static interface ProfilingBlock { - - /** - * Method that execute the code subjected to profiling. - * - * @return profiles Type - * @throws Exception - */ - T doProfiling() throws Exception; + + /** + * Method that execute the code subjected to profiling. + * + * @return profiles Type + * @throws Exception + */ + T doProfiling() throws Exception; } } http://git-wip-us.apache.org/repos/asf/struts/blob/2e9df577/xwork-core/src/main/java/com/opensymphony/xwork2/util/reflection/ReflectionContextState.java ---------------------------------------------------------------------- diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/util/reflection/ReflectionContextState.java b/xwork-core/src/main/java/com/opensymphony/xwork2/util/reflection/ReflectionContextState.java index 60fd456..9de464b 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/util/reflection/ReflectionContextState.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/util/reflection/ReflectionContextState.java @@ -29,11 +29,14 @@ import java.util.Map; */ public class ReflectionContextState { + private static final String GETTING_BY_KEY_PROPERTY = "xwork.getting.by.key.property"; + private static final String SET_MAP_KEY = "set.map.key"; + public static final String CURRENT_PROPERTY_PATH="current.property.path"; public static final String FULL_PROPERTY_PATH="current.property.path"; - private static final String GETTING_BY_KEY_PROPERTY="xwork.getting.by.key.property"; - - private static final String SET_MAP_KEY="set.map.key"; + public static final String CREATE_NULL_OBJECTS = "xwork.NullHandler.createNullObjects"; + public static final String DENY_METHOD_EXECUTION = "xwork.MethodAccessor.denyMethodExecution"; + public static final String DENY_INDEXED_ACCESS_EXECUTION = "xwork.IndexedPropertyAccessor.denyMethodExecution"; public static boolean isCreatingNullObjects(Map context) { //TODO @@ -126,7 +129,7 @@ public class ReflectionContextState { public static void setSetMap(Map context, Map setMap, String path) { Map> mapOfSetMaps=(Map)context.get(SET_MAP_KEY); if (mapOfSetMaps==null) { - mapOfSetMaps=new HashMap>(); + mapOfSetMaps = new HashMap<>(); context.put(SET_MAP_KEY, mapOfSetMaps); } mapOfSetMaps.put(path, setMap); @@ -157,7 +160,6 @@ public class ReflectionContextState { } - public static void clear(Map context) { if (context != null) { context.put(XWorkConverter.LAST_BEAN_CLASS_ACCESSED,null); @@ -168,12 +170,4 @@ public class ReflectionContextState { } } - - - public static final String CREATE_NULL_OBJECTS = "xwork.NullHandler.createNullObjects"; - public static final String DENY_METHOD_EXECUTION = "xwork.MethodAccessor.denyMethodExecution"; - public static final String DENY_INDEXED_ACCESS_EXECUTION = "xwork.IndexedPropertyAccessor.denyMethodExecution"; - - - } http://git-wip-us.apache.org/repos/asf/struts/blob/2e9df577/xwork-core/src/main/java/com/opensymphony/xwork2/validator/AnnotationActionValidatorManager.java ---------------------------------------------------------------------- diff --git a/xwork-core/src/main/java/com/opensymphony/xwork2/validator/AnnotationActionValidatorManager.java b/xwork-core/src/main/java/com/opensymphony/xwork2/validator/AnnotationActionValidatorManager.java index b1c475d..e98f8ee 100644 --- a/xwork-core/src/main/java/com/opensymphony/xwork2/validator/AnnotationActionValidatorManager.java +++ b/xwork-core/src/main/java/com/opensymphony/xwork2/validator/AnnotationActionValidatorManager.java @@ -16,32 +16,19 @@ package com.opensymphony.xwork2.validator; -import com.opensymphony.xwork2.ActionContext; -import com.opensymphony.xwork2.ActionInvocation; -import com.opensymphony.xwork2.ActionProxy; -import com.opensymphony.xwork2.FileManager; -import com.opensymphony.xwork2.FileManagerFactory; -import com.opensymphony.xwork2.XWorkConstants; +import com.opensymphony.xwork2.*; import com.opensymphony.xwork2.config.entities.ActionConfig; import com.opensymphony.xwork2.inject.Inject; import com.opensymphony.xwork2.util.ClassLoaderUtil; import com.opensymphony.xwork2.util.ValueStack; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; -import com.opensymphony.xwork2.validator.validators.VisitorFieldValidator; import org.apache.commons.lang3.StringUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import java.io.IOException; import java.io.InputStream; import java.net.URL; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeSet; +import java.util.*; /** * AnnotationActionValidatorManager is the entry point into XWork's annotations-based validator framework. @@ -108,7 +95,7 @@ public class AnnotationActionValidatorManager implements ActionValidatorManager ValueStack stack = ActionContext.getContext().getValueStack(); // create clean instances of the validators for the caller's use - ArrayList validators = new ArrayList(cfgs.size()); + ArrayList validators = new ArrayList<>(cfgs.size()); for (ValidatorConfig cfg : cfgs) { if (method == null || method.equals(cfg.getParams().get("methodName"))) { Validator validator = validatorFactory.getValidator( @@ -145,9 +132,7 @@ public class AnnotationActionValidatorManager implements ActionValidatorManager try { validator.setValidatorContext(validatorContext); - if (LOG.isDebugEnabled()) { - LOG.debug("Running validator: " + validator + " for object " + object + " and method " + method); - } + LOG.debug("Running validator: {} for object {} and method {}", validator, object, method); FieldValidator fValidator = null; String fullFieldName = null; @@ -157,10 +142,7 @@ public class AnnotationActionValidatorManager implements ActionValidatorManager fullFieldName = fValidator.getValidatorContext().getFullFieldName(fValidator.getFieldName()); if ((shortcircuitedFields != null) && shortcircuitedFields.contains(fullFieldName)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Short-circuited, skipping"); - } - + LOG.debug("Short-circuited, skipping"); continue; } } @@ -174,14 +156,14 @@ public class AnnotationActionValidatorManager implements ActionValidatorManager Collection fieldErrors = validatorContext.getFieldErrors().get(fullFieldName); if (fieldErrors != null) { - errs = new ArrayList(fieldErrors); + errs = new ArrayList<>(fieldErrors); } } } else if (validatorContext.hasActionErrors()) { Collection actionErrors = validatorContext.getActionErrors(); if (actionErrors != null) { - errs = new ArrayList(actionErrors); + errs = new ArrayList<>(actionErrors); } } @@ -192,9 +174,7 @@ public class AnnotationActionValidatorManager implements ActionValidatorManager Collection errCol = validatorContext.getFieldErrors().get(fullFieldName); if ((errCol != null) && !errCol.equals(errs)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Short-circuiting on field validation"); - } + LOG.debug("Short-circuiting on field validation"); if (shortcircuitedFields == null) { shortcircuitedFields = new TreeSet(); @@ -207,10 +187,7 @@ public class AnnotationActionValidatorManager implements ActionValidatorManager Collection errCol = validatorContext.getActionErrors(); if ((errCol != null) && !errCol.equals(errs)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Short-circuiting"); - } - + LOG.debug("Short-circuiting"); break; } } @@ -276,11 +253,11 @@ public class AnnotationActionValidatorManager implements ActionValidatorManager String fileName = aClass.getName().replace('.', '/') + VALIDATION_CONFIG_SUFFIX; - List result = new ArrayList(loadFile(fileName, aClass, checkFile)); + List result = new ArrayList<>(loadFile(fileName, aClass, checkFile)); AnnotationValidationConfigurationBuilder builder = new AnnotationValidationConfigurationBuilder(validatorFactory); - List annotationResult = new ArrayList(builder.buildAnnotationClassValidatorConfigs(aClass)); + List annotationResult = new ArrayList<>(builder.buildAnnotationClassValidatorConfigs(aClass)); result.addAll(annotationResult); @@ -331,10 +308,10 @@ public class AnnotationActionValidatorManager implements ActionValidatorManager * @return a list of validator configs for the given class and context. */ private List buildValidatorConfigs(Class clazz, String context, boolean checkFile, Set checked) { - List validatorConfigs = new ArrayList(); + List validatorConfigs = new ArrayList<>(); if (checked == null) { - checked = new TreeSet(); + checked = new TreeSet<>(); } else if (checked.contains(clazz.getName())) { return validatorConfigs; } @@ -385,24 +362,12 @@ public class AnnotationActionValidatorManager implements ActionValidatorManager URL fileUrl = ClassLoaderUtil.getResource(fileName, clazz); if ((checkFile && fileManager.fileNeedsReloading(fileUrl)) || !validatorFileCache.containsKey(fileName)) { - InputStream is = null; - - try { - is = fileManager.loadFile(fileUrl); - + try (InputStream is = fileManager.loadFile(fileUrl)) { if (is != null) { - retList = new ArrayList(validatorFileParser.parseActionValidatorConfigs(validatorFactory, is, fileName)); - } - } catch (Exception e) { - LOG.error("Caught exception while loading file " + fileName, e); - } finally { - if (is != null) { - try { - is.close(); - } catch (IOException e) { - LOG.error("Unable to close input stream for " + fileName, e); - } + retList = new ArrayList<>(validatorFileParser.parseActionValidatorConfigs(validatorFactory, is, fileName)); } + } catch (IOException e) { + LOG.error("Caught exception while loading file {}", fileName, e); } validatorFileCache.put(fileName, retList);