diff --git a/core/src/main/java/hudson/AbstractMarkupText.java b/core/src/main/java/hudson/AbstractMarkupText.java index 1e78b3e10c..2398f6f744 100644 --- a/core/src/main/java/hudson/AbstractMarkupText.java +++ b/core/src/main/java/hudson/AbstractMarkupText.java @@ -141,7 +141,7 @@ public abstract class AbstractMarkupText { public List findTokens(Pattern pattern) { String text = getText(); Matcher m = pattern.matcher(text); - List r = new ArrayList(); + List r = new ArrayList<>(); while(m.find()) { int idx = m.start(); diff --git a/core/src/main/java/hudson/BulkChange.java b/core/src/main/java/hudson/BulkChange.java index 28b9fde426..e65fa4d3ac 100644 --- a/core/src/main/java/hudson/BulkChange.java +++ b/core/src/main/java/hudson/BulkChange.java @@ -132,7 +132,7 @@ public class BulkChange implements Closeable { /** * {@link BulkChange}s that are effective currently. */ - private static final ThreadLocal INSCOPE = new ThreadLocal(); + private static final ThreadLocal INSCOPE = new ThreadLocal<>(); /** * Gets the {@link BulkChange} instance currently in scope for the current thread. diff --git a/core/src/main/java/hudson/ClassicPluginStrategy.java b/core/src/main/java/hudson/ClassicPluginStrategy.java index fdd2e88dd1..1d93d3fb24 100644 --- a/core/src/main/java/hudson/ClassicPluginStrategy.java +++ b/core/src/main/java/hudson/ClassicPluginStrategy.java @@ -192,7 +192,7 @@ public class ClassicPluginStrategy implements PluginStrategy { // TODO: define a mechanism to hide classes // String export = manifest.getMainAttributes().getValue("Export"); - List paths = new ArrayList(); + List paths = new ArrayList<>(); if (isLinked) { parseClassPath(manifest, archive, paths, "Libraries", ","); parseClassPath(manifest, archive, paths, "Class-Path", " +"); // backward compatibility @@ -218,8 +218,8 @@ public class ClassicPluginStrategy implements PluginStrategy { } // compute dependencies - List dependencies = new ArrayList(); - List optionalDependencies = new ArrayList(); + List dependencies = new ArrayList<>(); + List optionalDependencies = new ArrayList<>(); String v = atts.getValue("Plugin-Dependencies"); if (v != null) { for (String s : v.split(",")) { @@ -336,7 +336,7 @@ public class ClassicPluginStrategy implements PluginStrategy { } catch (AbstractMethodError e) { // backward compatibility for (T t : finder.findExtensions(type, hudson)) - r.add(new ExtensionComponent(t)); + r.add(new ExtensionComponent<>(t)); } } @@ -578,7 +578,7 @@ public class ClassicPluginStrategy implements PluginStrategy { CyclicGraphDetector cgd = new CyclicGraphDetector() { @Override protected List getEdges(PluginWrapper pw) { - List dep = new ArrayList(); + List dep = new ArrayList<>(); for (Dependency d : pw.getDependencies()) { PluginWrapper p = pluginManager.getPlugin(d.shortName); if (p!=null && p.isActive()) @@ -644,7 +644,7 @@ public class ClassicPluginStrategy implements PluginStrategy { @SuppressFBWarnings(value = "DMI_COLLECTION_OF_URLS", justification = "Should not produce network overheads since the URL is local. JENKINS-53793 is a follow-up") protected Enumeration findResources(String name) throws IOException { - HashSet result = new HashSet(); + HashSet result = new HashSet<>(); if (PluginManager.FAST_LOOKUP) { for (PluginWrapper pw : getTransitiveDependencies()) { diff --git a/core/src/main/java/hudson/DNSMultiCast.java b/core/src/main/java/hudson/DNSMultiCast.java index aa71b2e23b..fcb3fe33bb 100644 --- a/core/src/main/java/hudson/DNSMultiCast.java +++ b/core/src/main/java/hudson/DNSMultiCast.java @@ -32,7 +32,7 @@ public class DNSMultiCast implements Closeable { try { jmdns = JmDNS.create(); - Map props = new HashMap(); + Map props = new HashMap<>(); String rootURL = jenkins.getRootUrl(); if (rootURL==null) return null; diff --git a/core/src/main/java/hudson/DescriptorExtensionList.java b/core/src/main/java/hudson/DescriptorExtensionList.java index 8452227e5e..5e9d35f7ec 100644 --- a/core/src/main/java/hudson/DescriptorExtensionList.java +++ b/core/src/main/java/hudson/DescriptorExtensionList.java @@ -76,7 +76,7 @@ public class DescriptorExtensionList, D extends Descrip if (describableType == (Class) Publisher.class) { return (DescriptorExtensionList) new Publisher.DescriptorExtensionListImpl(jenkins); } - return new DescriptorExtensionList(jenkins,describableType); + return new DescriptorExtensionList<>(jenkins, describableType); } /** @@ -199,7 +199,7 @@ public class DescriptorExtensionList, D extends Descrip } private List> _load(Iterable> set) { - List> r = new ArrayList>(); + List> r = new ArrayList<>(); for( ExtensionComponent c : set ) { Descriptor d = c.getInstance(); try { diff --git a/core/src/main/java/hudson/EnvVars.java b/core/src/main/java/hudson/EnvVars.java index 6d2f451071..8caaebf312 100644 --- a/core/src/main/java/hudson/EnvVars.java +++ b/core/src/main/java/hudson/EnvVars.java @@ -200,7 +200,7 @@ public class EnvVars extends TreeMap { } public void clear() { - referredVariables = new TreeSet(comparator); + referredVariables = new TreeSet<>(comparator); } public String resolve(String name) { @@ -288,8 +288,8 @@ public class EnvVars extends TreeMap { * Scan all variables and list all referring variables. */ public void scan() { - refereeSetMap = new TreeMap>(comparator); - List extendingVariableNames = new ArrayList(); + refereeSetMap = new TreeMap<>(comparator); + List extendingVariableNames = new ArrayList<>(); TraceResolver resolver = new TraceResolver(comparator); @@ -327,10 +327,10 @@ public class EnvVars extends TreeMap { // When A refers B, the last appearance of B always comes after // the last appearance of A. - List reversedDuplicatedOrder = new ArrayList(sorter.getSorted()); + List reversedDuplicatedOrder = new ArrayList<>(sorter.getSorted()); Collections.reverse(reversedDuplicatedOrder); - orderedVariableNames = new ArrayList(overrides.size()); + orderedVariableNames = new ArrayList<>(overrides.size()); for(String key: reversedDuplicatedOrder) { if(overrides.containsKey(key) && !orderedVariableNames.contains(key)) { orderedVariableNames.add(key); diff --git a/core/src/main/java/hudson/ExpressionFactory2.java b/core/src/main/java/hudson/ExpressionFactory2.java index 277858c933..c8704fccfd 100644 --- a/core/src/main/java/hudson/ExpressionFactory2.java +++ b/core/src/main/java/hudson/ExpressionFactory2.java @@ -168,5 +168,5 @@ final class ExpressionFactory2 implements ExpressionFactory { * * @see Functions#getCurrentJellyContext() */ - protected static final ThreadLocal CURRENT_CONTEXT = new ThreadLocal(); + protected static final ThreadLocal CURRENT_CONTEXT = new ThreadLocal<>(); } diff --git a/core/src/main/java/hudson/ExtensionComponent.java b/core/src/main/java/hudson/ExtensionComponent.java index 136d52f81a..98e03969f3 100644 --- a/core/src/main/java/hudson/ExtensionComponent.java +++ b/core/src/main/java/hudson/ExtensionComponent.java @@ -95,9 +95,7 @@ public class ExtensionComponent implements Comparable> if (this.instance instanceof Descriptor && that.instance instanceof Descriptor) { try { return Util.fixNull(((Descriptor)this.instance).getDisplayName()).compareTo(Util.fixNull(((Descriptor)that.instance).getDisplayName())); - } catch (RuntimeException x) { - LOG.log(Level.WARNING, null, x); - } catch (LinkageError x) { + } catch (RuntimeException | LinkageError x) { LOG.log(Level.WARNING, null, x); } } diff --git a/core/src/main/java/hudson/ExtensionList.java b/core/src/main/java/hudson/ExtensionList.java index b4d32bd06d..0417f1674c 100644 --- a/core/src/main/java/hudson/ExtensionList.java +++ b/core/src/main/java/hudson/ExtensionList.java @@ -86,7 +86,7 @@ public class ExtensionList extends AbstractList implements OnMaster { @CopyOnWrite private volatile List> extensions; - private final List listeners = new CopyOnWriteArrayList(); + private final List listeners = new CopyOnWriteArrayList<>(); /** * Place to store manually registered instances with the per-Hudson scope. @@ -104,7 +104,7 @@ public class ExtensionList extends AbstractList implements OnMaster { } protected ExtensionList(Jenkins jenkins, Class extensionType) { - this(jenkins,extensionType,new CopyOnWriteArrayList>()); + this(jenkins,extensionType, new CopyOnWriteArrayList<>()); } /** @@ -237,7 +237,7 @@ public class ExtensionList extends AbstractList implements OnMaster { private synchronized boolean removeSync(Object o) { boolean removed = removeComponent(legacyInstances, o); if(extensions!=null) { - List> r = new ArrayList>(extensions); + List> r = new ArrayList<>(extensions); removed |= removeComponent(r,o); extensions = sort(r); } @@ -279,11 +279,11 @@ public class ExtensionList extends AbstractList implements OnMaster { } private synchronized boolean addSync(T t) { - legacyInstances.add(new ExtensionComponent(t)); + legacyInstances.add(new ExtensionComponent<>(t)); // if we've already filled extensions, add it if(extensions!=null) { - List> r = new ArrayList>(extensions); - r.add(new ExtensionComponent(t)); + List> r = new ArrayList<>(extensions); + r.add(new ExtensionComponent<>(t)); extensions = sort(r); } return true; @@ -395,7 +395,7 @@ public class ExtensionList extends AbstractList implements OnMaster { * The implementation should copy a list, do a sort, and return the new instance. */ protected List> sort(List> r) { - r = new ArrayList>(r); + r = new ArrayList<>(r); Collections.sort(r); return r; } @@ -412,7 +412,7 @@ public class ExtensionList extends AbstractList implements OnMaster { @SuppressWarnings({"unchecked", "rawtypes"}) public static ExtensionList create(Jenkins jenkins, Class type) { if(type.getAnnotation(LegacyInstancesAreScopedToHudson.class)!=null) - return new ExtensionList(jenkins,type); + return new ExtensionList<>(jenkins, type); else { return new ExtensionList(jenkins, type, staticLegacyInstances.computeIfAbsent(type, key -> new CopyOnWriteArrayList())); } diff --git a/core/src/main/java/hudson/FilePath.java b/core/src/main/java/hudson/FilePath.java index 66d2ea9aae..13311e72b5 100644 --- a/core/src/main/java/hudson/FilePath.java +++ b/core/src/main/java/hudson/FilePath.java @@ -325,7 +325,7 @@ public final class FilePath implements Serializable { } boolean isAbsolute = buf.length() > 0; // Split remaining path into tokens, trimming any duplicate or trailing separators - List tokens = new ArrayList(); + List tokens = new ArrayList<>(); int s = 0, end = path.length(); for (int i = 0; i < end; i++) { char c = path.charAt(i); @@ -1061,7 +1061,7 @@ public final class FilePath implements Serializable { if(channel!=null) { // run this on a remote system try { - DelegatingCallable wrapper = new FileCallableWrapper(callable, cl); + DelegatingCallable wrapper = new FileCallableWrapper<>(callable, cl); for (FileCallableWrapperFactory factory : ExtensionList.lookup(FileCallableWrapperFactory.class)) { wrapper = factory.wrap(wrapper); } @@ -1136,7 +1136,7 @@ public final class FilePath implements Serializable { */ public Future actAsync(final FileCallable callable) throws IOException, InterruptedException { try { - DelegatingCallable wrapper = new FileCallableWrapper(callable); + DelegatingCallable wrapper = new FileCallableWrapper<>(callable); for (FileCallableWrapperFactory factory : ExtensionList.lookup(FileCallableWrapperFactory.class)) { wrapper = factory.wrap(wrapper); } @@ -1839,7 +1839,7 @@ public final class FilePath implements Serializable { return Collections.emptyList(); } - ArrayList r = new ArrayList(children.length); + ArrayList r = new ArrayList<>(children.length); for (File child : children) r.add(new FilePath(child)); diff --git a/core/src/main/java/hudson/Functions.java b/core/src/main/java/hudson/Functions.java index 118a1f70fa..76fdf2f813 100644 --- a/core/src/main/java/hudson/Functions.java +++ b/core/src/main/java/hudson/Functions.java @@ -465,7 +465,7 @@ public class Functions { } public static Map getSystemProperties() { - return new TreeMap(System.getProperties()); + return new TreeMap<>(System.getProperties()); } /** @@ -479,7 +479,7 @@ public class Functions { } public static Map getEnvVars() { - return new TreeMap(EnvVars.masterEnvVars); + return new TreeMap<>(EnvVars.masterEnvVars); } public static boolean isWindows() { @@ -544,7 +544,7 @@ public class Functions { * @since 1.525 */ public static Iterable reverse(Collection collection) { - List list = new ArrayList(collection); + List list = new ArrayList<>(collection); Collections.reverse(list); return list; } diff --git a/core/src/main/java/hudson/Launcher.java b/core/src/main/java/hudson/Launcher.java index f0f18b4f81..c6e39a27d3 100644 --- a/core/src/main/java/hudson/Launcher.java +++ b/core/src/main/java/hudson/Launcher.java @@ -197,14 +197,14 @@ public abstract class Launcher { } public ProcStarter cmds(File program, String... args) { - commands = new ArrayList(args.length+1); + commands = new ArrayList<>(args.length + 1); commands.add(program.getPath()); commands.addAll(Arrays.asList(args)); return this; } public ProcStarter cmds(List args) { - commands = new ArrayList(args); + commands = new ArrayList<>(args); return this; } @@ -774,7 +774,7 @@ public abstract class Launcher { */ protected final void maskedPrintCommandLine(@Nonnull List cmd, @CheckForNull boolean[] mask, @CheckForNull FilePath workDir) { if(mask==null) { - printCommandLine(cmd.toArray(new String[cmd.size()]),workDir); + printCommandLine(cmd.toArray(new String[0]),workDir); return; } diff --git a/core/src/main/java/hudson/Lookup.java b/core/src/main/java/hudson/Lookup.java index 090f3eb284..b0b40ba891 100644 --- a/core/src/main/java/hudson/Lookup.java +++ b/core/src/main/java/hudson/Lookup.java @@ -32,7 +32,7 @@ import java.util.concurrent.ConcurrentHashMap; * @author Kohsuke Kawaguchi */ public class Lookup { - private final ConcurrentHashMap data = new ConcurrentHashMap(); + private final ConcurrentHashMap data = new ConcurrentHashMap<>(); public T get(Class type) { return type.cast(data.get(type)); diff --git a/core/src/main/java/hudson/Main.java b/core/src/main/java/hudson/Main.java index c4aa942755..14ae9ee38f 100644 --- a/core/src/main/java/hudson/Main.java +++ b/core/src/main/java/hudson/Main.java @@ -42,6 +42,7 @@ import java.net.HttpRetryException; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.nio.charset.Charset; @@ -152,9 +153,8 @@ public class Main { // run the command long start = System.currentTimeMillis(); - List cmd = new ArrayList(); - for( int i=1; i cmd = new ArrayList<>(); + cmd.addAll(Arrays.asList(args).subList(1, args.length)); Proc proc = new Proc.LocalProc(cmd.toArray(new String[0]),(String[])null,System.in, new DualOutputStream(System.out,new EncodingStream(os))); diff --git a/core/src/main/java/hudson/MarkupText.java b/core/src/main/java/hudson/MarkupText.java index 12a9b3b848..107c8fbdfc 100644 --- a/core/src/main/java/hudson/MarkupText.java +++ b/core/src/main/java/hudson/MarkupText.java @@ -45,7 +45,7 @@ public class MarkupText extends AbstractMarkupText { /** * Added mark up tags. */ - private final List tags = new ArrayList(); + private final List tags = new ArrayList<>(); /** * Represents one mark up inserted into text. diff --git a/core/src/main/java/hudson/PermalinkList.java b/core/src/main/java/hudson/PermalinkList.java index 0c4a3085a6..caffd8baf0 100644 --- a/core/src/main/java/hudson/PermalinkList.java +++ b/core/src/main/java/hudson/PermalinkList.java @@ -60,7 +60,7 @@ public final class PermalinkList extends ArrayList { * Finds the closest name match by its ID. */ public Permalink findNearest(String id) { - List ids = new ArrayList(); + List ids = new ArrayList<>(); for (Permalink p : this) ids.add(p.getId()); String nearest = EditDistance.findNearest(id, ids); diff --git a/core/src/main/java/hudson/PluginManager.java b/core/src/main/java/hudson/PluginManager.java index c26ca2439d..62c21991b3 100644 --- a/core/src/main/java/hudson/PluginManager.java +++ b/core/src/main/java/hudson/PluginManager.java @@ -284,9 +284,9 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas /** * All active plugins, topologically sorted so that when X depends on Y, Y appears in the list before X does. */ - protected final List activePlugins = new CopyOnWriteArrayList(); + protected final List activePlugins = new CopyOnWriteArrayList<>(); - protected final List failedPlugins = new ArrayList(); + protected final List failedPlugins = new ArrayList<>(); /** * Plug-in root directory. @@ -422,7 +422,7 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas // once we've listed plugins, we can fill in the reactor with plugin-specific initialization tasks TaskGraphBuilder g = new TaskGraphBuilder(); - final Map inspectedShortNames = new HashMap(); + final Map inspectedShortNames = new HashMap<>(); for( final File arc : archives ) { g.followedBy().notFatal().attains(PLUGINS_LISTED).add("Inspecting plugin " + arc, new Executable() { @@ -465,7 +465,7 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas CyclicGraphDetector cgd = new CyclicGraphDetector() { @Override protected List getEdges(PluginWrapper p) { - List next = new ArrayList(); + List next = new ArrayList<>(); addTo(p.getDependencies(), next); addTo(p.getOptionalDependencies(), next); return next; @@ -537,7 +537,7 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas TaskGraphBuilder g = new TaskGraphBuilder(); // schedule execution of loading plugins - for (final PluginWrapper p : activePlugins.toArray(new PluginWrapper[activePlugins.size()])) { + for (final PluginWrapper p : activePlugins.toArray(new PluginWrapper[0])) { g.followedBy().notFatal().attains(PLUGINS_PREPARED).add(String.format("Loading plugin %s v%s (%s)", p.getLongName(), p.getVersion(), p.getShortName()), new Executable() { public void run(Reactor session) throws Exception { try { @@ -560,7 +560,7 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas } // schedule execution of initializing plugins - for (final PluginWrapper p : activePlugins.toArray(new PluginWrapper[activePlugins.size()])) { + for (final PluginWrapper p : activePlugins.toArray(new PluginWrapper[0])) { g.followedBy().notFatal().attains(PLUGINS_STARTED).add("Initializing plugin " + p.getShortName(), new Executable() { public void run(Reactor session) throws Exception { if (!activePlugins.contains(p)) { @@ -1241,7 +1241,7 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas * @return The list of plugins implementing the specified class. */ public List getPlugins(Class pluginSuperclass) { - List result = new ArrayList(); + List result = new ArrayList<>(); for (PluginWrapper p : getPlugins()) { if(pluginSuperclass.isInstance(p.getPlugin())) result.add(p); @@ -1264,7 +1264,7 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas */ @Deprecated public Collection> discover( Class spi ) { - Set> result = new HashSet>(); + Set> result = new HashSet<>(); for (PluginWrapper p : activePlugins) { Service.load(spi, p.classLoader, result); @@ -1770,12 +1770,9 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas protected String identifyPluginShortName(File t) { try { - JarFile j = new JarFile(t); - try { + try (JarFile j = new JarFile(t)) { String name = j.getManifest().getMainAttributes().getValue("Short-Name"); - if (name!=null) return name; - } finally { - j.close(); + if (name != null) return name; } } catch (IOException e) { LOGGER.log(WARNING, "Failed to identify the short name from "+t,e); @@ -1807,7 +1804,7 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas */ public List> prevalidateConfig(InputStream configXml) throws IOException { Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER); - List> jobs = new ArrayList>(); + List> jobs = new ArrayList<>(); UpdateCenter uc = Jenkins.getInstance().getUpdateCenter(); // TODO call uc.updateAllSites() when available? perhaps not, since we should not block on network here for (Map.Entry requestedPlugin : parseRequestedPlugins(configXml).entrySet()) { @@ -1901,7 +1898,7 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas * Parses configuration XML files and picks up references to XML files. */ public Map parseRequestedPlugins(InputStream configXml) throws IOException { - final Map requestedPlugins = new TreeMap(); + final Map requestedPlugins = new TreeMap<>(); try { SAXParserFactory.newInstance().newSAXParser().parse(configXml, new DefaultHandler() { @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { @@ -1981,16 +1978,16 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas * Make generated types visible. * Keyed by the generated class name. */ - private ConcurrentMap> generatedClasses = new ConcurrentHashMap>(); + private ConcurrentMap> generatedClasses = new ConcurrentHashMap<>(); /** Cache of loaded, or known to be unloadable, classes. */ - private final Map> loaded = new HashMap>(); + private final Map> loaded = new HashMap<>(); public UberClassLoader() { super(PluginManager.class.getClassLoader()); } public void addNamedClass(String className, Class c) { - generatedClasses.put(className,new WeakReference(c)); + generatedClasses.put(className, new WeakReference<>(c)); } @Override @@ -2071,7 +2068,7 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas @Override protected Enumeration findResources(String name) throws IOException { - List resources = new ArrayList(); + List resources = new ArrayList<>(); if (FAST_LOOKUP) { for (PluginWrapper p : activePlugins) { resources.addAll(Collections.list(ClassLoaderReflectionToolkit._findResources(p.classLoader, name))); diff --git a/core/src/main/java/hudson/TcpSlaveAgentListener.java b/core/src/main/java/hudson/TcpSlaveAgentListener.java index bd2b8a1581..62f66b5471 100644 --- a/core/src/main/java/hudson/TcpSlaveAgentListener.java +++ b/core/src/main/java/hudson/TcpSlaveAgentListener.java @@ -33,6 +33,7 @@ import java.security.interfaces.RSAPublicKey; import javax.annotation.Nullable; import hudson.model.AperiodicWork; +import hudson.util.VersionNumber; import jenkins.model.Jenkins; import jenkins.model.identity.InstanceIdentityProvider; import jenkins.security.stapler.StaplerAccessibleType; @@ -153,6 +154,14 @@ public final class TcpSlaveAgentListener extends Thread { return StringUtils.join(Jenkins.getInstance().getAgentProtocols(), ", "); } + /** + * Gets Remoting minimum supported version to prevent unsupported agents from connecting + * @since 2.171 + */ + public VersionNumber getRemotingMinimumVersion() { + return RemotingVersionInfo.getMinimumSupportedVersion(); + } + @Override public void run() { try { @@ -293,8 +302,7 @@ public final class TcpSlaveAgentListener extends Thread { private void respondHello(String header, Socket s) throws IOException { try { Writer o = new OutputStreamWriter(s.getOutputStream(), StandardCharsets.UTF_8); - - //TODO: expose version about minimum supported Remoting version (JENKINS-48766) + if (header.startsWith("GET / ")) { o.write("HTTP/1.0 200 OK\r\n"); o.write("Content-Type: text/plain;charset=UTF-8\r\n"); @@ -304,7 +312,7 @@ public final class TcpSlaveAgentListener extends Thread { o.write("Jenkins-Session: " + Jenkins.SESSION_HASH + "\r\n"); o.write("Client: " + s.getInetAddress().getHostAddress() + "\r\n"); o.write("Server: " + s.getLocalAddress().getHostAddress() + "\r\n"); - o.write("Remoting-Minimum-Version: " + RemotingVersionInfo.getMinimumSupportedVersion() + "\r\n"); + o.write("Remoting-Minimum-Version: " + getRemotingMinimumVersion() + "\r\n"); o.flush(); s.shutdownOutput(); } else { diff --git a/core/src/main/java/hudson/Util.java b/core/src/main/java/hudson/Util.java index 9699df02c8..dc3de475bf 100644 --- a/core/src/main/java/hudson/Util.java +++ b/core/src/main/java/hudson/Util.java @@ -114,7 +114,7 @@ public class Util { */ @Nonnull public static List filter( @Nonnull Iterable base, @Nonnull Class type ) { - List r = new ArrayList(); + List r = new ArrayList<>(); for (Object i : base) { if(type.isInstance(i)) r.add(type.cast(i)); @@ -144,7 +144,7 @@ public class Util { */ @Nullable public static String replaceMacro( @CheckForNull String s, @Nonnull Map properties) { - return replaceMacro(s,new VariableResolver.ByMap(properties)); + return replaceMacro(s, new VariableResolver.ByMap<>(properties)); } /** @@ -783,7 +783,7 @@ public class Util { */ @Nonnull public static List createSubList(@Nonnull Collection source, @Nonnull Class type ) { - List r = new ArrayList(); + List r = new ArrayList<>(); for (Object item : source) { if(type.isInstance(item)) r.add(type.cast(item)); @@ -1117,7 +1117,7 @@ public class Util { int size = 0; for (Collection item : items) size += item.size(); - List r = new ArrayList(size); + List r = new ArrayList<>(size); for (Collection item : items) r.addAll(item); return r; diff --git a/core/src/main/java/hudson/cli/CLICommand.java b/core/src/main/java/hudson/cli/CLICommand.java index 738c738a63..e9c8f5765f 100644 --- a/core/src/main/java/hudson/cli/CLICommand.java +++ b/core/src/main/java/hudson/cli/CLICommand.java @@ -243,7 +243,7 @@ public abstract class CLICommand implements ExtensionPoint, Cloneable { if (!(this instanceof HelpCommand || this instanceof WhoAmICommand)) Jenkins.getActiveInstance().checkPermission(Jenkins.READ); - p.parseArgument(args.toArray(new String[args.size()])); + p.parseArgument(args.toArray(new String[0])); if (!(this instanceof HelpCommand || this instanceof WhoAmICommand)) Jenkins.getActiveInstance().checkPermission(Jenkins.READ); LOGGER.log(Level.FINE, "Invoking CLI command {0}, with {1} arguments, as user {2}.", @@ -530,7 +530,7 @@ public abstract class CLICommand implements ExtensionPoint, Cloneable { private static final Logger LOGGER = Logger.getLogger(CLICommand.class.getName()); - private static final ThreadLocal CURRENT_COMMAND = new ThreadLocal(); + private static final ThreadLocal CURRENT_COMMAND = new ThreadLocal<>(); /*package*/ static CLICommand setCurrent(CLICommand cmd) { CLICommand old = getCurrent(); diff --git a/core/src/main/java/hudson/cli/GroovyCommand.java b/core/src/main/java/hudson/cli/GroovyCommand.java index ea05dca912..f87ba80abc 100644 --- a/core/src/main/java/hudson/cli/GroovyCommand.java +++ b/core/src/main/java/hudson/cli/GroovyCommand.java @@ -68,7 +68,7 @@ public class GroovyCommand extends CLICommand { binding.setProperty("stderr",stderr); GroovyShell groovy = new GroovyShell(Jenkins.getActiveInstance().getPluginManager().uberClassLoader, binding); - groovy.run(loadScript(),"RemoteClass",remaining.toArray(new String[remaining.size()])); + groovy.run(loadScript(),"RemoteClass",remaining.toArray(new String[0])); return 0; } diff --git a/core/src/main/java/hudson/cli/InstallPluginCommand.java b/core/src/main/java/hudson/cli/InstallPluginCommand.java index 2bbabe09c6..5279a7fd3a 100644 --- a/core/src/main/java/hudson/cli/InstallPluginCommand.java +++ b/core/src/main/java/hudson/cli/InstallPluginCommand.java @@ -63,7 +63,7 @@ public class InstallPluginCommand extends CLICommand { "and the plugin will be installed from the update center. If the short name includes a minimum version number " + "(like ‘findbugs:1.4’), and there are multiple update centers publishing different versions, the update centers " + "will be searched in order for the first one publishing a version that is at least the specified version.") - public List sources = new ArrayList(); + public List sources = new ArrayList<>(); @Option(name="-name",usage="If specified, the plugin will be installed as this short name (whereas normally the name is inferred from the source name automatically).") public String name; // TODO better to parse out Short-Name from the manifest and deprecate this option diff --git a/core/src/main/java/hudson/console/AnnotatedLargeText.java b/core/src/main/java/hudson/console/AnnotatedLargeText.java index 2cd2988ede..f29430b1b2 100644 --- a/core/src/main/java/hudson/console/AnnotatedLargeText.java +++ b/core/src/main/java/hudson/console/AnnotatedLargeText.java @@ -54,6 +54,7 @@ import com.jcraft.jzlib.GZIPInputStream; import com.jcraft.jzlib.GZIPOutputStream; import static java.lang.Math.abs; +import javax.annotation.CheckReturnValue; import org.jenkinsci.remoting.util.AnonymousClassWarnings; /** @@ -139,6 +140,7 @@ public class AnnotatedLargeText extends LargeText { return ConsoleAnnotator.initial(context); } + @CheckReturnValue @Override public long writeLogTo(long start, Writer w) throws IOException { if (isHtml()) @@ -151,6 +153,7 @@ public class AnnotatedLargeText extends LargeText { * Strips annotations using a {@link PlainTextConsoleOutputStream}. * {@inheritDoc} */ + @CheckReturnValue @Override public long writeLogTo(long start, OutputStream out) throws IOException { return super.writeLogTo(start, new PlainTextConsoleOutputStream(out)); @@ -160,10 +163,12 @@ public class AnnotatedLargeText extends LargeText { * Calls {@link LargeText#writeLogTo(long, OutputStream)} without stripping annotations as {@link #writeLogTo(long, OutputStream)} would. * @since 1.577 */ + @CheckReturnValue public long writeRawLogTo(long start, OutputStream out) throws IOException { return super.writeLogTo(start, out); } + @CheckReturnValue public long writeHtmlTo(long start, Writer w) throws IOException { ConsoleAnnotationOutputStream caw = new ConsoleAnnotationOutputStream<>( w, createAnnotator(Stapler.getCurrentRequest()), context, charset); diff --git a/core/src/main/java/hudson/console/ConsoleAnnotationOutputStream.java b/core/src/main/java/hudson/console/ConsoleAnnotationOutputStream.java index f3a22c875c..5c731a17dd 100644 --- a/core/src/main/java/hudson/console/ConsoleAnnotationOutputStream.java +++ b/core/src/main/java/hudson/console/ConsoleAnnotationOutputStream.java @@ -24,9 +24,6 @@ package hudson.console; import hudson.MarkupText; -import org.apache.commons.io.output.ProxyWriter; -import org.kohsuke.stapler.framework.io.WriterOutputStream; - import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.IOException; @@ -38,6 +35,9 @@ import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; +import org.apache.commons.io.output.ProxyWriter; +import org.apache.commons.lang.StringEscapeUtils; +import org.kohsuke.stapler.framework.io.WriterOutputStream; /** * Used to convert plain text console output (as byte sequence) + embedded annotations into HTML (as char sequence), @@ -119,11 +119,9 @@ public class ConsoleAnnotationOutputStream extends LineTransformationOutputSt } }); } - } catch (IOException e) { + } catch (IOException | ClassNotFoundException e) { // if we failed to resurrect an annotation, ignore it. - LOGGER.log(Level.FINE,"Failed to resurrect annotation",e); - } catch (ClassNotFoundException e) { - LOGGER.log(Level.FINE,"Failed to resurrect annotation",e); + LOGGER.log(Level.FINE, "Failed to resurrect annotation from \"" + StringEscapeUtils.escapeJava(new String(in, next, rest)) + "\"", e); } int bytesUsed = rest - b.available(); // bytes consumed by annotations diff --git a/core/src/main/java/hudson/console/ConsoleLogFilter.java b/core/src/main/java/hudson/console/ConsoleLogFilter.java index ec1b0c0592..99fe50eca3 100644 --- a/core/src/main/java/hudson/console/ConsoleLogFilter.java +++ b/core/src/main/java/hudson/console/ConsoleLogFilter.java @@ -36,6 +36,8 @@ import hudson.util.ArgumentListBuilder; import javax.annotation.Nonnull; import java.io.IOException; import java.io.OutputStream; +import java.io.Serializable; +import jenkins.util.JenkinsJVM; /** * A hook to allow filtering of information that is written to the console log. @@ -43,6 +45,10 @@ import java.io.OutputStream; * direct access to the underlying {@link OutputStream} so it's possible to suppress * data, which isn't possible from the other interfaces. * ({@link ArgumentListBuilder#add(String, boolean)} is a simpler way to suppress a single password.) + *

Implementations which are {@link Serializable} may be sent to an agent JVM for processing. + * In particular, this happens under JEP-210. + * In this case, the implementation should not assume that {@link JenkinsJVM#isJenkinsJVM}, + * and if generating {@link ConsoleNote}s will need to encode them on the master side first. * @author dty * @since 1.383 * @see BuildWrapper#decorateLogger diff --git a/core/src/main/java/hudson/console/ConsoleNote.java b/core/src/main/java/hudson/console/ConsoleNote.java index b4f67cf3d6..2b646cab4b 100644 --- a/core/src/main/java/hudson/console/ConsoleNote.java +++ b/core/src/main/java/hudson/console/ConsoleNote.java @@ -110,6 +110,17 @@ import org.kohsuke.accmod.restrictions.NoExternalUse; * is also important, although {@link ConsoleNote}s that failed to deserialize will be simply ignored, so the * worst thing that can happen is that you just lose some notes. * + *

+ * Note that {@link #encode}, {@link #encodeTo(OutputStream)}, and {@link #encodeTo(Writer)} + * should be called on the Jenkins master. + * If called from an agent JVM, a signature will be missing and so as per + * SECURITY-382 + * the console note will be ignored. + * This may happen, in particular, if the note was generated by a {@link ConsoleLogFilter} sent to the agent. + * Alternative solutions include using a {@link ConsoleAnnotatorFactory} where practical; + * or generating the encoded form of the note on the master side and sending it to the agent, + * for example by saving that form as instance fields in a {@link ConsoleLogFilter} implementation. + * *

Behaviour, JavaScript, and CSS

*

* {@link ConsoleNote} can have associated {@code script.js} and {@code style.css} (put them @@ -192,18 +203,15 @@ public abstract class ConsoleNote implements Serializable, Describable implements Serializable, Describable implements Serializable, Describable implements Serializable, Describable removeNotes(Collection logLines) { - List r = new ArrayList(logLines.size()); + List r = new ArrayList<>(logLines.size()); for (String l : logLines) r.add(removeNotes(l)); return r; diff --git a/core/src/main/java/hudson/diagnosis/MemoryUsageMonitor.java b/core/src/main/java/hudson/diagnosis/MemoryUsageMonitor.java index 1ba648eb38..eba9991aff 100644 --- a/core/src/main/java/hudson/diagnosis/MemoryUsageMonitor.java +++ b/core/src/main/java/hudson/diagnosis/MemoryUsageMonitor.java @@ -53,7 +53,7 @@ public final class MemoryUsageMonitor extends PeriodicWork { * A memory group is conceptually a set of memory pools. */ public final class MemoryGroup { - private final List pools = new ArrayList(); + private final List pools = new ArrayList<>(); /** * Trend of the memory usage, after GCs. diff --git a/core/src/main/java/hudson/diagnosis/NullIdDescriptorMonitor.java b/core/src/main/java/hudson/diagnosis/NullIdDescriptorMonitor.java index 8b3778262e..27a5685f1d 100644 --- a/core/src/main/java/hudson/diagnosis/NullIdDescriptorMonitor.java +++ b/core/src/main/java/hudson/diagnosis/NullIdDescriptorMonitor.java @@ -55,7 +55,7 @@ public class NullIdDescriptorMonitor extends AdministrativeMonitor { return Messages.NullIdDescriptorMonitor_DisplayName(); } - private final List problems = new ArrayList(); + private final List problems = new ArrayList<>(); @Override public boolean isActivated() { diff --git a/core/src/main/java/hudson/diagnosis/OldDataMonitor.java b/core/src/main/java/hudson/diagnosis/OldDataMonitor.java index 7fc185737c..c4317b4816 100644 --- a/core/src/main/java/hudson/diagnosis/OldDataMonitor.java +++ b/core/src/main/java/hudson/diagnosis/OldDataMonitor.java @@ -78,7 +78,7 @@ import org.kohsuke.stapler.interceptor.RequirePOST; public class OldDataMonitor extends AdministrativeMonitor { private static final Logger LOGGER = Logger.getLogger(OldDataMonitor.class.getName()); - private ConcurrentMap data = new ConcurrentHashMap(); + private ConcurrentMap data = new ConcurrentHashMap<>(); /** * Gets instance of the monitor. @@ -106,7 +106,7 @@ public class OldDataMonitor extends AdministrativeMonitor { } public Map getData() { - Map r = new HashMap(); + Map r = new HashMap<>(); for (Map.Entry entry : this.data.entrySet()) { Saveable s = entry.getKey().get(); if (s != null) { diff --git a/core/src/main/java/hudson/init/InitStrategy.java b/core/src/main/java/hudson/init/InitStrategy.java index 9d7d287c43..c6c5795e54 100644 --- a/core/src/main/java/hudson/init/InitStrategy.java +++ b/core/src/main/java/hudson/init/InitStrategy.java @@ -45,7 +45,7 @@ public class InitStrategy { * and when that happens, Jenkins will ignore all but the first one in the list. */ public List listPluginArchives(PluginManager pm) throws IOException { - List r = new ArrayList(); + List r = new ArrayList<>(); // the ordering makes sure that during the debugging we get proper precedence among duplicates. // for example, while doing "mvn jpi:run" or "mvn hpi:run" on a plugin that's bundled with Jenkins, we want to the diff --git a/core/src/main/java/hudson/init/TaskMethodFinder.java b/core/src/main/java/hudson/init/TaskMethodFinder.java index 0e09bfe267..bbd60a61bf 100644 --- a/core/src/main/java/hudson/init/TaskMethodFinder.java +++ b/core/src/main/java/hudson/init/TaskMethodFinder.java @@ -32,7 +32,7 @@ import static java.util.logging.Level.WARNING; abstract class TaskMethodFinder extends TaskBuilder { private static final Logger LOGGER = Logger.getLogger(TaskMethodFinder.class.getName()); protected final ClassLoader cl; - private final Set discovered = new HashSet(); + private final Set discovered = new HashSet<>(); private final Class type; private final Class milestoneType; @@ -52,7 +52,7 @@ abstract class TaskMethodFinder extends TaskBuilder { protected abstract boolean fatalOf(T i); public Collection discoverTasks(Reactor session) throws IOException { - List result = new ArrayList(); + List result = new ArrayList<>(); for (Method e : Index.list(type, cl, Method.class)) { if (filter(e)) continue; // already reported once @@ -180,7 +180,7 @@ abstract class TaskMethodFinder extends TaskBuilder { } private Collection toMilestones(String[] tokens, Milestone m) { - List r = new ArrayList(); + List r = new ArrayList<>(); for (String s : tokens) { try { r.add((Milestone)Enum.valueOf(milestoneType,s)); diff --git a/core/src/main/java/hudson/lifecycle/UnixLifecycle.java b/core/src/main/java/hudson/lifecycle/UnixLifecycle.java index 1af9c13155..a17c898ab3 100644 --- a/core/src/main/java/hudson/lifecycle/UnixLifecycle.java +++ b/core/src/main/java/hudson/lifecycle/UnixLifecycle.java @@ -56,11 +56,8 @@ public class UnixLifecycle extends Lifecycle { // if we are running as daemon, don't fork into background one more time during restart args.remove("--daemon"); - } catch (UnsupportedOperationException e) { - // can't restart - failedToObtainArgs = e; - } catch (LinkageError e) { - // see HUDSON-3875 + } catch (UnsupportedOperationException | LinkageError e) { + // can't restart / see HUDSON-3875 failedToObtainArgs = e; } } @@ -86,7 +83,7 @@ public class UnixLifecycle extends Lifecycle { // exec to self String exe = args.get(0); - LIBC.execvp(exe, new StringArray(args.toArray(new String[args.size()]))); + LIBC.execvp(exe, new StringArray(args.toArray(new String[0]))); throw new IOException("Failed to exec '"+exe+"' "+LIBC.strerror(Native.getLastError())); } diff --git a/core/src/main/java/hudson/lifecycle/WindowsInstallerLink.java b/core/src/main/java/hudson/lifecycle/WindowsInstallerLink.java index 64bd857be7..414d39b4e6 100644 --- a/core/src/main/java/hudson/lifecycle/WindowsInstallerLink.java +++ b/core/src/main/java/hudson/lifecycle/WindowsInstallerLink.java @@ -215,9 +215,7 @@ public class WindowsInstallerLink extends ManagementLink { int r = runElevated( new File(installationDir, "jenkins.exe"), "start", task, installationDir); task.getLogger().println(r==0?"Successfully started":"start service failed. Exit code="+r); - } catch (IOException e) { - e.printStackTrace(); - } catch (InterruptedException e) { + } catch (IOException | InterruptedException e) { e.printStackTrace(); } } diff --git a/core/src/main/java/hudson/logging/LogRecorder.java b/core/src/main/java/hudson/logging/LogRecorder.java index 0ca0d57196..85de032387 100644 --- a/core/src/main/java/hudson/logging/LogRecorder.java +++ b/core/src/main/java/hudson/logging/LogRecorder.java @@ -75,7 +75,7 @@ import org.kohsuke.accmod.restrictions.NoExternalUse; public class LogRecorder extends AbstractModelObject implements Saveable { private volatile String name; - public final CopyOnWriteList targets = new CopyOnWriteList(); + public final CopyOnWriteList targets = new CopyOnWriteList<>(); private final static TargetComparator TARGET_COMPARATOR = new TargetComparator(); @Restricted(NoExternalUse.class) diff --git a/core/src/main/java/hudson/logging/LogRecorderManager.java b/core/src/main/java/hudson/logging/LogRecorderManager.java index 78c24c2a2e..a572900a55 100644 --- a/core/src/main/java/hudson/logging/LogRecorderManager.java +++ b/core/src/main/java/hudson/logging/LogRecorderManager.java @@ -68,7 +68,7 @@ public class LogRecorderManager extends AbstractModelObject implements ModelObje /** * {@link LogRecorder}s keyed by their {@linkplain LogRecorder#name name}. */ - public transient final Map logRecorders = new CopyOnWriteMap.Tree(); + public transient final Map logRecorders = new CopyOnWriteMap.Tree<>(); public String getDisplayName() { return Messages.LogRecorderManager_DisplayName(); @@ -160,7 +160,7 @@ public class LogRecorderManager extends AbstractModelObject implements ModelObje String level = req.getParameter("level"); if(level!=null) { Level threshold = Level.parse(level); - List filtered = new ArrayList(); + List filtered = new ArrayList<>(); for (LogRecord r : logs) { if(r.getLevel().intValue() >= threshold.intValue()) filtered.add(r); diff --git a/core/src/main/java/hudson/logging/WeakLogHandler.java b/core/src/main/java/hudson/logging/WeakLogHandler.java index 339c50ef64..9a51f279de 100644 --- a/core/src/main/java/hudson/logging/WeakLogHandler.java +++ b/core/src/main/java/hudson/logging/WeakLogHandler.java @@ -44,7 +44,7 @@ public final class WeakLogHandler extends Handler { public WeakLogHandler(Handler target, Logger logger) { this.logger = logger; logger.addHandler(this); - this.target = new WeakReference(target); + this.target = new WeakReference<>(target); } public void publish(LogRecord record) { diff --git a/core/src/main/java/hudson/model/AbstractBuild.java b/core/src/main/java/hudson/model/AbstractBuild.java index 2268f3dd99..3c2c1b4412 100644 --- a/core/src/main/java/hudson/model/AbstractBuild.java +++ b/core/src/main/java/hudson/model/AbstractBuild.java @@ -465,7 +465,7 @@ public abstract class AbstractBuild

,R extends Abs listener.getLogger().print(Messages.AbstractBuild_BuildingOnMaster()); } else { listener.getLogger().print(Messages.AbstractBuild_BuildingRemotely(ModelHyperlinkNote.encodeTo("/computer/" + builtOn, node.getDisplayName()))); - Set assignedLabels = new HashSet(node.getAssignedLabels()); + Set assignedLabels = new HashSet<>(node.getAssignedLabels()); assignedLabels.remove(node.getSelfLabel()); if (!assignedLabels.isEmpty()) { boolean first = true; @@ -536,7 +536,7 @@ public abstract class AbstractBuild

,R extends Abs l = bw.decorateLauncher(AbstractBuild.this,l,listener); } - buildEnvironments = new ArrayList(); + buildEnvironments = new ArrayList<>(); for (RunListener rl: RunListener.all()) { Environment environment = rl.setUpEnvironment(AbstractBuild.this, l, listener); @@ -583,7 +583,7 @@ public abstract class AbstractBuild

,R extends Abs } build.scm = scm.createChangeLogParser(); - build.changeSet = new WeakReference>(build.calcChangeSet()); + build.changeSet = new WeakReference<>(build.calcChangeSet()); for (SCMListener l : SCMListener.all()) try { @@ -635,7 +635,7 @@ public abstract class AbstractBuild

,R extends Abs post2(listener); } finally { // update the culprit list - HashSet r = new HashSet(); + HashSet r = new HashSet<>(); for (User u : getCulprits()) r.add(u.getId()); culprits = ImmutableSortedSet.copyOf(r); @@ -694,10 +694,7 @@ public abstract class AbstractBuild

,R extends Abs setResult(Result.FAILURE); } } - } catch (Exception e) { - reportError(bs, e, listener, phase); - r = false; - } catch (LinkageError e) { + } catch (Exception | LinkageError e) { reportError(bs, e, listener, phase); r = false; } @@ -742,10 +739,7 @@ public abstract class AbstractBuild

,R extends Abs try { canContinue = mon.perform(bs, AbstractBuild.this, launcher, listener); - } catch (RequestAbortedException ex) { - // Channel is closed, do not continue - reportBrokenChannel(listener); - } catch (ChannelClosedException ex) { + } catch (RequestAbortedException | ChannelClosedException ex) { // Channel is closed, do not continue reportBrokenChannel(listener); } catch (RuntimeException ex) { @@ -834,7 +828,7 @@ public abstract class AbstractBuild

,R extends Abs if (cs==null) cs = ChangeLogSet.createEmpty(this); - changeSet = new WeakReference>(cs); + changeSet = new WeakReference<>(cs); return cs; } @@ -859,9 +853,7 @@ public abstract class AbstractBuild

,R extends Abs try { return scm.parse(this,changelogFile); - } catch (IOException e) { - LOGGER.log(WARNING, "Failed to parse "+changelogFile,e); - } catch (SAXException e) { + } catch (IOException | SAXException e) { LOGGER.log(WARNING, "Failed to parse "+changelogFile,e); } return ChangeLogSet.createEmpty(this); @@ -903,7 +895,7 @@ public abstract class AbstractBuild

,R extends Abs public EnvironmentList getEnvironments() { Executor e = Executor.currentExecutor(); if (e!=null && e.getCurrentExecutable()==this) { - if (buildEnvironments==null) buildEnvironments = new ArrayList(); + if (buildEnvironments==null) buildEnvironments = new ArrayList<>(); return new EnvironmentList(buildEnvironments); } @@ -936,7 +928,7 @@ public abstract class AbstractBuild

,R extends Abs * @since 1.378 */ public Set getSensitiveBuildVariables() { - Set s = new HashSet(); + Set s = new HashSet<>(); ParametersAction parameters = getAction(ParametersAction.class); if (parameters != null) { @@ -973,7 +965,7 @@ public abstract class AbstractBuild

,R extends Abs * The returned map is mutable so that subtypes can put more values. */ public Map getBuildVariables() { - Map r = new HashMap(); + Map r = new HashMap<>(); ParametersAction parameters = getAction(ParametersAction.class); if (parameters!=null) { @@ -1000,7 +992,7 @@ public abstract class AbstractBuild

,R extends Abs * Creates {@link VariableResolver} backed by {@link #getBuildVariables()}. */ public final VariableResolver getBuildVariableResolver() { - return new VariableResolver.ByMap(getBuildVariables()); + return new VariableResolver.ByMap<>(getBuildVariables()); } /** @@ -1173,7 +1165,7 @@ public abstract class AbstractBuild

,R extends Abs * of builds (which can be empty if no build uses the artifact from this build or downstream is not {@link AbstractProject#isFingerprintConfigured}.) */ public Map getDownstreamBuilds() { - Map r = new HashMap(); + Map r = new HashMap<>(); for (AbstractProject p : getParent().getDownstreamProjects()) { if (p.isFingerprintConfigured()) r.put(p,getDownstreamRelationship(p)); @@ -1200,7 +1192,7 @@ public abstract class AbstractBuild

,R extends Abs } private Map _getUpstreamBuilds(Collection projects) { - Map r = new HashMap(); + Map r = new HashMap<>(); for (AbstractProject p : projects) { int n = getUpstreamRelationship(p); if (n>=0) @@ -1222,7 +1214,7 @@ public abstract class AbstractBuild

,R extends Abs Map ndep = n.getDependencies(true); Map odep = o.getDependencies(true); - Map r = new HashMap(); + Map r = new HashMap<>(); for (Map.Entry entry : odep.entrySet()) { AbstractProject p = entry.getKey(); @@ -1274,7 +1266,7 @@ public abstract class AbstractBuild

,R extends Abs * of IDs, but due to log rotations, some builds may be already unavailable. */ public List getBuilds() { - List r = new ArrayList(); + List r = new ArrayList<>(); AbstractBuild b = project.getNearestBuild(fromId); if (b!=null && b.getNumber()==fromId) diff --git a/core/src/main/java/hudson/model/AbstractProject.java b/core/src/main/java/hudson/model/AbstractProject.java index 2f91394f20..f86aed606d 100644 --- a/core/src/main/java/hudson/model/AbstractProject.java +++ b/core/src/main/java/hudson/model/AbstractProject.java @@ -822,7 +822,7 @@ public abstract class AbstractProject

,R extends A if (c != null) { queueActions.add(new CauseAction(c)); } - return scheduleBuild2(quietPeriod, queueActions.toArray(new Action[queueActions.size()])); + return scheduleBuild2(quietPeriod, queueActions.toArray(new Action[0])); } /** diff --git a/core/src/main/java/hudson/model/Actionable.java b/core/src/main/java/hudson/model/Actionable.java index 96eeda813a..496c2de286 100644 --- a/core/src/main/java/hudson/model/Actionable.java +++ b/core/src/main/java/hudson/model/Actionable.java @@ -78,7 +78,7 @@ public abstract class Actionable extends AbstractModelObject implements ModelObj if (actions == null) { synchronized (this) { if (actions == null) { - actions = new CopyOnWriteArrayList(); + actions = new CopyOnWriteArrayList<>(); } } } @@ -196,7 +196,7 @@ public abstract class Actionable extends AbstractModelObject implements ModelObj throw new IllegalArgumentException("Action must be non-null"); } // CopyOnWriteArrayList does not support Iterator.remove, so need to do it this way: - List old = new ArrayList(1); + List old = new ArrayList<>(1); List current = getActions(); boolean found = false; for (Action a2 : current) { @@ -255,7 +255,7 @@ public abstract class Actionable extends AbstractModelObject implements ModelObj throw new IllegalArgumentException("Action type must be non-null"); } // CopyOnWriteArrayList does not support Iterator.remove, so need to do it this way: - List old = new ArrayList(); + List old = new ArrayList<>(); List current = getActions(); for (Action a : current) { if (clazz.isInstance(a)) { @@ -290,7 +290,7 @@ public abstract class Actionable extends AbstractModelObject implements ModelObj throw new IllegalArgumentException("Action must be non-null"); } // CopyOnWriteArrayList does not support Iterator.remove, so need to do it this way: - List old = new ArrayList(); + List old = new ArrayList<>(); List current = getActions(); boolean found = false; for (Action a1 : current) { diff --git a/core/src/main/java/hudson/model/AperiodicWork.java b/core/src/main/java/hudson/model/AperiodicWork.java index 3c5385c077..dad7bbe573 100644 --- a/core/src/main/java/hudson/model/AperiodicWork.java +++ b/core/src/main/java/hudson/model/AperiodicWork.java @@ -126,9 +126,7 @@ public abstract class AperiodicWork extends SafeTimerTask implements ExtensionPo private final Set registered = new HashSet<>(); AperiodicWorkExtensionListListener(ExtensionList initiallyRegistered) { - for (AperiodicWork p : initiallyRegistered) { - registered.add(p); - } + registered.addAll(initiallyRegistered); } @Override diff --git a/core/src/main/java/hudson/model/AutoCompletionCandidates.java b/core/src/main/java/hudson/model/AutoCompletionCandidates.java index 29ce16f4ca..e8e64b8e48 100644 --- a/core/src/main/java/hudson/model/AutoCompletionCandidates.java +++ b/core/src/main/java/hudson/model/AutoCompletionCandidates.java @@ -48,7 +48,7 @@ import org.apache.commons.lang.StringUtils; * @author Kohsuke Kawaguchi */ public class AutoCompletionCandidates implements HttpResponse { - private final List values = new ArrayList(); + private final List values = new ArrayList<>(); public AutoCompletionCandidates add(String v) { values.add(v); diff --git a/core/src/main/java/hudson/model/Build.java b/core/src/main/java/hudson/model/Build.java index 15aed23050..00f9c21d4e 100644 --- a/core/src/main/java/hudson/model/Build.java +++ b/core/src/main/java/hudson/model/Build.java @@ -147,7 +147,7 @@ public abstract class Build

,B extends Build> Result r = null; try { - List wrappers = new ArrayList(project.getBuildWrappers().values()); + List wrappers = new ArrayList<>(project.getBuildWrappers().values()); ParametersAction parameters = getAction(ParametersAction.class); if (parameters != null) diff --git a/core/src/main/java/hudson/model/Cause.java b/core/src/main/java/hudson/model/Cause.java index d05cd867b5..4758f17dd0 100644 --- a/core/src/main/java/hudson/model/Cause.java +++ b/core/src/main/java/hudson/model/Cause.java @@ -175,8 +175,8 @@ public abstract class Cause { upstreamBuild = up.getNumber(); upstreamProject = up.getParent().getFullName(); upstreamUrl = up.getParent().getUrl(); - upstreamCauses = new ArrayList(); - Set traversed = new HashSet(); + upstreamCauses = new ArrayList<>(); + Set traversed = new HashSet<>(); for (Cause c : up.getCauses()) { upstreamCauses.add(trim(c, MAX_DEPTH, traversed)); } @@ -234,7 +234,7 @@ public abstract class Cause { return c; } UpstreamCause uc = (UpstreamCause) c; - List cs = new ArrayList(); + List cs = new ArrayList<>(); if (depth > 0) { if (traversed.add(uc.upstreamUrl + uc.upstreamBuild)) { for (Cause c2 : uc.upstreamCauses) { @@ -333,7 +333,7 @@ public abstract class Cause { public ConverterImpl(XStream2 xstream) { super(xstream); } @Override protected void callback(UpstreamCause uc, UnmarshallingContext context) { if (uc.upstreamCause != null) { - if (uc.upstreamCauses == null) uc.upstreamCauses = new ArrayList(); + if (uc.upstreamCauses == null) uc.upstreamCauses = new ArrayList<>(); uc.upstreamCauses.add(uc.upstreamCause); uc.upstreamCause = null; OldDataMonitor.report(context, "1.288"); diff --git a/core/src/main/java/hudson/model/ChoiceParameterDefinition.java b/core/src/main/java/hudson/model/ChoiceParameterDefinition.java index 9ea1415362..ffe11cb3fd 100644 --- a/core/src/main/java/hudson/model/ChoiceParameterDefinition.java +++ b/core/src/main/java/hudson/model/ChoiceParameterDefinition.java @@ -45,7 +45,7 @@ public class ChoiceParameterDefinition extends SimpleParameterDefinition { public ChoiceParameterDefinition(String name, String[] choices, String description) { super(name, description); - this.choices = new ArrayList(Arrays.asList(choices)); + this.choices = new ArrayList<>(Arrays.asList(choices)); defaultValue = null; } diff --git a/core/src/main/java/hudson/model/Computer.java b/core/src/main/java/hudson/model/Computer.java index e4c3a661b8..dacf3d8fa1 100644 --- a/core/src/main/java/hudson/model/Computer.java +++ b/core/src/main/java/hudson/model/Computer.java @@ -150,9 +150,9 @@ import static javax.servlet.http.HttpServletResponse.*; @ExportedBean public /*transient*/ abstract class Computer extends Actionable implements AccessControlled, ExecutorListener, DescriptorByNameOwner { - private final CopyOnWriteArrayList executors = new CopyOnWriteArrayList(); + private final CopyOnWriteArrayList executors = new CopyOnWriteArrayList<>(); // TODO: - private final CopyOnWriteArrayList oneOffExecutors = new CopyOnWriteArrayList(); + private final CopyOnWriteArrayList oneOffExecutors = new CopyOnWriteArrayList<>(); private int numExecutors; @@ -198,8 +198,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces * @since 1.607 * @see Executor#resetWorkUnit(String) */ - private transient final List terminatedBy = Collections.synchronizedList(new ArrayList - ()); + private transient final List terminatedBy = Collections.synchronizedList(new ArrayList<>()); /** * This method captures the information of a request to terminate a computer instance. Method is public as @@ -241,7 +240,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces * @since 1.607 */ public List getTerminatedBy() { - return new ArrayList(terminatedBy); + return new ArrayList<>(terminatedBy); } public Computer(Node node) { @@ -260,7 +259,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces */ @SuppressWarnings("deprecation") public List getActions() { - List result = new ArrayList(); + List result = new ArrayList<>(); result.addAll(super.getActions()); synchronized (this) { if (transientActions == null) { @@ -327,7 +326,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces */ public AnnotatedLargeText getLogText() { checkPermission(CONNECT); - return new AnnotatedLargeText(getLogFile(), Charset.defaultCharset(), false, this); + return new AnnotatedLargeText<>(getLogFile(), Charset.defaultCharset(), false, this); } public ACL getACL() { @@ -910,7 +909,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces if (Jenkins.getInstanceOrNull() == null) { return; } - Set availableNumbers = new HashSet(); + Set availableNumbers = new HashSet<>(); for (int i = 0; i < numExecutors; i++) availableNumbers.add(i); @@ -965,7 +964,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces @Exported @StaplerDispatchable public List getExecutors() { - return new ArrayList(executors); + return new ArrayList<>(executors); } /** @@ -974,7 +973,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces @Exported @StaplerDispatchable public List getOneOffExecutors() { - return new ArrayList(oneOffExecutors); + return new ArrayList<>(oneOffExecutors); } /** @@ -998,7 +997,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces @Restricted(NoExternalUse.class) public List getDisplayExecutors() { // The size may change while we are populating, but let's start with a reasonable guess to minimize resizing - List result = new ArrayList(executors.size()+oneOffExecutors.size()); + List result = new ArrayList<>(executors.size() + oneOffExecutors.size()); int index = 0; for (Executor e: executors) { if (e.isDisplayCell()) { @@ -1153,7 +1152,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces */ @Exported(inline=true) public Map getMonitorData() { - Map r = new HashMap(); + Map r = new HashMap<>(); if (hasPermission(CONNECT)) { for (NodeMonitor monitor : NodeMonitor.getAll()) r.put(monitor.getClass().getName(), monitor.data(this)); @@ -1324,7 +1323,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces private static final Logger LOGGER = Logger.getLogger(ListPossibleNames.class.getName()); public List call() throws IOException { - List names = new ArrayList(); + List names = new ArrayList<>(); Enumeration nis = NetworkInterface.getNetworkInterfaces(); while (nis.hasMoreElements()) { diff --git a/core/src/main/java/hudson/model/ComputerPanelBox.java b/core/src/main/java/hudson/model/ComputerPanelBox.java index 94ee1aaa3c..d5e7e45cba 100644 --- a/core/src/main/java/hudson/model/ComputerPanelBox.java +++ b/core/src/main/java/hudson/model/ComputerPanelBox.java @@ -37,7 +37,7 @@ public abstract class ComputerPanelBox implements ExtensionPoint{ * List of all the registered {@link ComputerPanelBox}s. */ public static List all(Computer computer) { - List boxs = new ArrayList(); + List boxs = new ArrayList<>(); for(ComputerPanelBox box: ExtensionList.lookup(ComputerPanelBox.class)){ box.setComputer(computer); boxs.add(box); diff --git a/core/src/main/java/hudson/model/ComputerSet.java b/core/src/main/java/hudson/model/ComputerSet.java index 5dbadb9219..1b618d0d50 100644 --- a/core/src/main/java/hudson/model/ComputerSet.java +++ b/core/src/main/java/hudson/model/ComputerSet.java @@ -85,7 +85,7 @@ public final class ComputerSet extends AbstractModelObject implements Describabl }; private static final DescribableList> monitors - = new DescribableList>(MONITORS_OWNER); + = new DescribableList<>(MONITORS_OWNER); @Exported public String getDisplayName() { @@ -129,7 +129,7 @@ public final class ComputerSet extends AbstractModelObject implements Describabl * Returns a subset pf {@link #getMonitors()} that are {@linkplain NodeMonitor#isIgnored() not ignored}. */ public static Map,NodeMonitor> getNonIgnoredMonitors() { - Map,NodeMonitor> r = new HashMap, NodeMonitor>(); + Map,NodeMonitor> r = new HashMap<>(); for (NodeMonitor m : monitors) { if(!m.isIgnored()) r.put(m.getDescriptor(),m); @@ -421,7 +421,7 @@ public final class ComputerSet extends AbstractModelObject implements Describabl */ @Nonnull public static List getComputerNames() { - final ArrayList names = new ArrayList(); + final ArrayList names = new ArrayList<>(); for (Computer c : Jenkins.getInstance().getComputers()) { if (!c.getName().isEmpty()) { names.add(c.getName()); @@ -435,14 +435,14 @@ public final class ComputerSet extends AbstractModelObject implements Describabl static { try { DescribableList> r - = new DescribableList>(Saveable.NOOP); + = new DescribableList<>(Saveable.NOOP); // load persisted monitors XmlFile xf = getConfigFile(); if(xf.exists()) { DescribableList> persisted = (DescribableList>) xf.read(); - List sanitized = new ArrayList(); + List sanitized = new ArrayList<>(); for (NodeMonitor nm : persisted) { try { nm.getDescriptor(); diff --git a/core/src/main/java/hudson/model/DependencyGraph.java b/core/src/main/java/hudson/model/DependencyGraph.java index 6c7469a302..076b25dee8 100644 --- a/core/src/main/java/hudson/model/DependencyGraph.java +++ b/core/src/main/java/hudson/model/DependencyGraph.java @@ -70,8 +70,8 @@ import java.util.Stack; */ public class DependencyGraph implements Comparator { - private Map> forward = new HashMap>(); - private Map> backward = new HashMap>(); + private Map> forward = new HashMap<>(); + private Map> backward = new HashMap<>(); private transient Map, Object> computationalData; @@ -90,7 +90,7 @@ public class DependencyGraph implements Comparator { // Set full privileges while computing to avoid missing any projects the current user cannot see. SecurityContext saveCtx = ACL.impersonate(ACL.SYSTEM); try { - this.computationalData = new HashMap, Object>(); + this.computationalData = new HashMap<>(); for( AbstractProject p : Jenkins.getInstance().allItems(AbstractProject.class) ) p.buildDependencyGraph(this); @@ -113,7 +113,7 @@ public class DependencyGraph implements Comparator { DirectedGraph g = new DirectedGraph() { @Override protected Collection nodes() { - final Set nodes = new HashSet(); + final Set nodes = new HashSet<>(); nodes.addAll(forward.keySet()); nodes.addAll(backward.keySet()); return nodes; @@ -127,8 +127,8 @@ public class DependencyGraph implements Comparator { List> sccs = g.getStronglyConnectedComponents(); - final Map topoOrder = new HashMap(); - topologicallySorted = new ArrayList>(); + final Map topoOrder = new HashMap<>(); + topologicallySorted = new ArrayList<>(); int idx=0; for (SCC scc : sccs) { for (AbstractProject n : scc) { @@ -196,7 +196,7 @@ public class DependencyGraph implements Comparator { private List get(Map> map, AbstractProject src, boolean up) { List v = map.get(src); if(v==null) return Collections.emptyList(); - List result = new ArrayList(v.size()); + List result = new ArrayList<>(v.size()); for (DependencyGroup d : v) result.add(up ? d.getUpstreamProject() : d.getDownstreamProject()); return result; } @@ -284,8 +284,8 @@ public class DependencyGraph implements Comparator { * where the length is greater than 1. */ public boolean hasIndirectDependencies(AbstractProject src, AbstractProject dst) { - Set visited = new HashSet(); - Stack queue = new Stack(); + Set visited = new HashSet<>(); + Stack queue = new Stack<>(); queue.addAll(getDownstream(src)); queue.remove(dst); @@ -316,8 +316,8 @@ public class DependencyGraph implements Comparator { } private Set getTransitive(Map> direction, AbstractProject src, boolean up) { - Set visited = new HashSet(); - Stack queue = new Stack(); + Set visited = new HashSet<>(); + Stack queue = new Stack<>(); queue.add(src); @@ -334,11 +334,7 @@ public class DependencyGraph implements Comparator { } private void add(Map> map, AbstractProject key, Dependency dep) { - List set = map.get(key); - if(set==null) { - set = new ArrayList(); - map.put(key,set); - } + List set = map.computeIfAbsent(key, k -> new ArrayList<>()); for (DependencyGroup d : set) { // Check for existing edge that connects the same two projects: if (d.getUpstreamProject() == dep.getUpstreamProject() && d.getDownstreamProject() == dep.getDownstreamProject()) { @@ -352,7 +348,7 @@ public class DependencyGraph implements Comparator { private Map> finalize(Map> m) { for (Entry> e : m.entrySet()) { - Collections.sort( e.getValue(), NAME_COMPARATOR ); + e.getValue().sort(NAME_COMPARATOR); e.setValue( Collections.unmodifiableList(e.getValue()) ); } return Collections.unmodifiableMap(m); @@ -457,7 +453,7 @@ public class DependencyGraph implements Comparator { * Collect multiple dependencies between the same two projects. */ private static class DependencyGroup { - private Set group = new LinkedHashSet(); + private Set group = new LinkedHashSet<>(); DependencyGroup(Dependency first) { this.upstream = first.getUpstreamProject(); diff --git a/core/src/main/java/hudson/model/Descriptor.java b/core/src/main/java/hudson/model/Descriptor.java index 3d941cd058..b00b60e4fb 100644 --- a/core/src/main/java/hudson/model/Descriptor.java +++ b/core/src/main/java/hudson/model/Descriptor.java @@ -137,7 +137,7 @@ public abstract class Descriptor> implements Saveable, */ public transient final Class clazz; - private transient final Map checkMethods = new ConcurrentHashMap(2); + private transient final Map checkMethods = new ConcurrentHashMap<>(2); /** * Lazily computed list of properties on {@link #clazz} and on the descriptor itself. @@ -233,7 +233,7 @@ public abstract class Descriptor> implements Saveable, * * @see #getHelpFile(String) */ - private transient final Map helpRedirect = new HashMap(2); + private transient final Map helpRedirect = new HashMap<>(2); private static class HelpRedirect { private final Class owner; @@ -416,7 +416,7 @@ public abstract class Descriptor> implements Saveable, throw new IllegalStateException(String.format("%s doesn't have the %s method for filling a drop-down list", getClass(), methodName)); // build query parameter line by figuring out what should be submitted - List depends = buildFillDependencies(method, new ArrayList()); + List depends = buildFillDependencies(method, new ArrayList<>()); if (!depends.isEmpty()) attributes.put("fillDependsOn",Util.join(depends," ")); @@ -506,7 +506,7 @@ public abstract class Descriptor> implements Saveable, * Given the class, list up its {@link PropertyType}s from its public fields/getters. */ private Map buildPropertyTypes(Class clazz) { - Map r = new HashMap(); + Map r = new HashMap<>(); for (Field f : clazz.getFields()) r.put(f.getName(),new PropertyType(f)); @@ -855,7 +855,7 @@ public abstract class Descriptor> implements Saveable, } protected List getPossibleViewNames(String baseName) { - List names = new ArrayList(); + List names = new ArrayList<>(); for (Facet f : WebApp.get(Jenkins.getInstance().servletContext).facets) { if (f instanceof JellyCompatibleFacet) { JellyCompatibleFacet jcf = (JellyCompatibleFacet) f; @@ -981,12 +981,12 @@ public abstract class Descriptor> implements Saveable, } public static List toList( T... values ) { - return new ArrayList(Arrays.asList(values)); + return new ArrayList<>(Arrays.asList(values)); } public static > Map,T> toMap(Iterable describables) { - Map,T> m = new LinkedHashMap,T>(); + Map,T> m = new LinkedHashMap<>(); for (T d : describables) { Descriptor descriptor; try { @@ -1025,7 +1025,7 @@ public abstract class Descriptor> implements Saveable, List newInstancesFromHeteroList(StaplerRequest req, Object formData, Collection> descriptors) throws FormException { - List items = new ArrayList(); + List items = new ArrayList<>(); if (formData!=null) { for (Object o : JSONArray.fromObject(formData)) { diff --git a/core/src/main/java/hudson/model/DescriptorVisibilityFilter.java b/core/src/main/java/hudson/model/DescriptorVisibilityFilter.java index e449569500..ef099a64dc 100644 --- a/core/src/main/java/hudson/model/DescriptorVisibilityFilter.java +++ b/core/src/main/java/hudson/model/DescriptorVisibilityFilter.java @@ -65,7 +65,7 @@ public abstract class DescriptorVisibilityFilter implements ExtensionPoint { public static List apply(Object context, Iterable source) { ExtensionList filters = all(); - List r = new ArrayList(); + List r = new ArrayList<>(); Class contextClass = context == null ? null : context.getClass(); if (source == null) { @@ -110,7 +110,7 @@ public abstract class DescriptorVisibilityFilter implements ExtensionPoint { public static List applyType(Class contextClass, Iterable source) { ExtensionList filters = all(); - List r = new ArrayList(); + List r = new ArrayList<>(); OUTER: for (T d : source) { diff --git a/core/src/main/java/hudson/model/DownloadService.java b/core/src/main/java/hudson/model/DownloadService.java index 125d58a394..1b0c4088fb 100644 --- a/core/src/main/java/hudson/model/DownloadService.java +++ b/core/src/main/java/hudson/model/DownloadService.java @@ -309,7 +309,7 @@ public class DownloadService extends PageDecorator { * URLs to download from. */ public List getUrls() { - List updateSites = new ArrayList(); + List updateSites = new ArrayList<>(); for (UpdateSite site : Jenkins.getActiveInstance().getUpdateCenter().getSiteList()) { String siteUrl = site.getUrl(); int baseUrlEnd = siteUrl.indexOf("update-center.json"); diff --git a/core/src/main/java/hudson/model/Executor.java b/core/src/main/java/hudson/model/Executor.java index 5f90ad1bfc..b466779e1a 100644 --- a/core/src/main/java/hudson/model/Executor.java +++ b/core/src/main/java/hudson/model/Executor.java @@ -139,7 +139,7 @@ public class Executor extends Thread implements ModelObject { * Cause of interruption. Access needs to be synchronized. */ @GuardedBy("lock") - private final List causes = new Vector(); + private final List causes = new Vector<>(); public Executor(@Nonnull Computer owner, int n) { super("Executor #"+n+" for "+owner.getDisplayName()); @@ -271,7 +271,7 @@ public class Executor extends Thread implements ModelObject { lock.writeLock().lock(); try { if (causes.isEmpty()) return; - r = new ArrayList(causes); + r = new ArrayList<>(causes); causes.clear(); } finally { lock.writeLock().unlock(); @@ -961,7 +961,7 @@ public class Executor extends Thread implements ModelObject { * Mechanism to allow threads (in particular the channel request handling threads) to * run on behalf of {@link Executor}. */ - private static final ThreadLocal IMPERSONATION = new ThreadLocal(); + private static final ThreadLocal IMPERSONATION = new ThreadLocal<>(); private static final Logger LOGGER = Logger.getLogger(Executor.class.getName()); } diff --git a/core/src/main/java/hudson/model/Fingerprint.java b/core/src/main/java/hudson/model/Fingerprint.java index cb33903bd1..37e46769c3 100644 --- a/core/src/main/java/hudson/model/Fingerprint.java +++ b/core/src/main/java/hudson/model/Fingerprint.java @@ -349,7 +349,7 @@ public class Fingerprint implements ModelObject, Saveable { private final List ranges; public RangeSet() { - this(new ArrayList()); + this(new ArrayList<>()); } private RangeSet(List data) { @@ -417,7 +417,7 @@ public class Fingerprint implements ModelObject, Saveable { */ @Exported public synchronized List getRanges() { - return new ArrayList(ranges); + return new ArrayList<>(ranges); } /** @@ -515,7 +515,7 @@ public class Fingerprint implements ModelObject, Saveable { * @return true if this range set was modified as a result. */ public synchronized boolean retainAll(RangeSet that) { - List intersection = new ArrayList(); + List intersection = new ArrayList<>(); int lhs=0,rhs=0; while(lhs sub = new ArrayList(); + List sub = new ArrayList<>(); int lhs=0,rhs=0; while(lhs usages = new Hashtable(); + private Hashtable usages = new Hashtable<>(); - PersistedList facets = new PersistedList(this); + PersistedList facets = new PersistedList<>(this); /** * Lazily computed immutable {@link FingerprintFacet}s created from {@link TransientFingerprintFacetFactory}. @@ -967,7 +967,7 @@ public class Fingerprint implements ModelObject, Saveable { * Gets the sorted list of job names where this jar is used. */ public @Nonnull List getJobs() { - List r = new ArrayList(); + List r = new ArrayList<>(); r.addAll(usages.keySet()); Collections.sort(r); return r; @@ -993,7 +993,7 @@ public class Fingerprint implements ModelObject, Saveable { // this is for remote API @Exported(name="usage") public @Nonnull List _getUsages() { - List r = new ArrayList(); + List r = new ArrayList<>(); final Jenkins instance = Jenkins.getInstance(); for (Entry e : usages.entrySet()) { final String itemName = e.getKey(); @@ -1032,7 +1032,7 @@ public class Fingerprint implements ModelObject, Saveable { // JENKINS-49588 protected Object readResolve() { if (usages == null) { - usages = new Hashtable(); + usages = new Hashtable<>(); } return this; } @@ -1087,7 +1087,7 @@ public class Fingerprint implements ModelObject, Saveable { public synchronized boolean trim() throws IOException { boolean modified = false; - for (Entry e : new Hashtable(usages).entrySet()) {// copy because we mutate + for (Entry e : new Hashtable<>(usages).entrySet()) {// copy because we mutate Job j = Jenkins.getInstance().getItemByFullName(e.getKey(),Job.class); if(j==null) {// no such job any more. recycle the record modified = true; @@ -1158,7 +1158,7 @@ public class Fingerprint implements ModelObject, Saveable { */ public @Nonnull Collection getFacets() { if (transientFacets==null) { - List transientFacets = new ArrayList(); + List transientFacets = new ArrayList<>(); for (TransientFingerprintFacetFactory fff : TransientFingerprintFacetFactory.all()) { fff.createFor(this,transientFacets); } @@ -1199,13 +1199,13 @@ public class Fingerprint implements ModelObject, Saveable { * @return Sorted list of {@link FingerprintFacet}s */ public @Nonnull Collection getSortedFacets() { - List r = new ArrayList(getFacets()); - Collections.sort(r,new Comparator() { + List r = new ArrayList<>(getFacets()); + r.sort(new Comparator() { public int compare(FingerprintFacet o1, FingerprintFacet o2) { long a = o1.getTimestamp(); long b = o2.getTimestamp(); - if (a getActions() { - List r = new ArrayList(); + List r = new ArrayList<>(); for (FingerprintFacet ff : getFacets()) ff.createActions(r); return Collections.unmodifiableList(r); @@ -1381,7 +1381,7 @@ public class Fingerprint implements ModelObject, Saveable { if(logger.isLoggable(Level.FINE)) logger.fine("Loading fingerprint "+file+" took "+(System.currentTimeMillis()-start)+"ms"); if (f.facets==null) - f.facets = new PersistedList(f); + f.facets = new PersistedList<>(f); for (FingerprintFacet facet : f.facets) facet._setOwner(f); return f; @@ -1420,7 +1420,7 @@ public class Fingerprint implements ModelObject, Saveable { } @Override public String toString() { - return "Fingerprint[original=" + original + ",hash=" + getHashString() + ",fileName=" + fileName + ",timestamp=" + DATE_CONVERTER.toString(timestamp) + ",usages=" + ((usages == null) ? "null" : new TreeMap(getUsages())) + ",facets=" + facets + "]"; + return "Fingerprint[original=" + original + ",hash=" + getHashString() + ",fileName=" + fileName + ",timestamp=" + DATE_CONVERTER.toString(timestamp) + ",usages=" + ((usages == null) ? "null" : new TreeMap<>(getUsages())) + ",facets=" + facets + "]"; } /** diff --git a/core/src/main/java/hudson/model/HealthReport.java b/core/src/main/java/hudson/model/HealthReport.java index ddcc1f9dec..7b67538272 100644 --- a/core/src/main/java/hudson/model/HealthReport.java +++ b/core/src/main/java/hudson/model/HealthReport.java @@ -62,7 +62,7 @@ public class HealthReport implements Serializable, Comparable { private static final String HEALTH_0_TO_20_IMG = "health-00to19.png"; private static final String HEALTH_UNKNOWN_IMG = "empty.png"; - private static final Map iconIMGToClassMap = new HashMap(); + private static final Map iconIMGToClassMap = new HashMap<>(); static { iconIMGToClassMap.put(HEALTH_OVER_80_IMG, HEALTH_OVER_80); iconIMGToClassMap.put(HEALTH_61_TO_80_IMG, HEALTH_61_TO_80); diff --git a/core/src/main/java/hudson/model/ItemGroupMixIn.java b/core/src/main/java/hudson/model/ItemGroupMixIn.java index 195d4d8c0c..b5cf8251f1 100644 --- a/core/src/main/java/hudson/model/ItemGroupMixIn.java +++ b/core/src/main/java/hudson/model/ItemGroupMixIn.java @@ -107,7 +107,7 @@ public abstract class ItemGroupMixIn { return child.isDirectory(); } }); - CopyOnWriteMap.Tree configurations = new CopyOnWriteMap.Tree(); + CopyOnWriteMap.Tree configurations = new CopyOnWriteMap.Tree<>(); for (File subdir : subdirs) { try { // Try to retain the identity of an existing child object if we can. @@ -290,16 +290,10 @@ public abstract class ItemGroupMixIn { Jenkins.getInstance().rebuildDependencyGraphAsync(); return result; - } catch (TransformerException e) { + } catch (TransformerException | SAXException e) { success = false; throw new IOException("Failed to persist config.xml", e); - } catch (SAXException e) { - success = false; - throw new IOException("Failed to persist config.xml", e); - } catch (IOException e) { - success = false; - throw e; - } catch (RuntimeException e) { + } catch (IOException | RuntimeException e) { success = false; throw e; } finally { diff --git a/core/src/main/java/hudson/model/Items.java b/core/src/main/java/hudson/model/Items.java index d0a26238a3..fb812e7a65 100644 --- a/core/src/main/java/hudson/model/Items.java +++ b/core/src/main/java/hudson/model/Items.java @@ -69,7 +69,7 @@ public class Items { * Use {@link #all()} for read access and {@link Extension} for registration. */ @Deprecated - public static final List LIST = (List)new DescriptorList(TopLevelItem.class); + public static final List LIST = (List) new DescriptorList<>(TopLevelItem.class); /** * Used to behave differently when loading posted configuration as opposed to persisted configuration. @@ -173,7 +173,7 @@ public class Items { * @since 1.607 */ public static List all(Authentication a, ItemGroup c) { - List result = new ArrayList(); + List result = new ArrayList<>(); ACL acl; if (c instanceof AccessControlled) { acl = ((AccessControlled) c).getACL(); @@ -224,7 +224,7 @@ public class Items { public static List fromNameList(ItemGroup context, @Nonnull String list, @Nonnull Class type) { final Jenkins jenkins = Jenkins.getInstance(); - List r = new ArrayList(); + List r = new ArrayList<>(); if (jenkins == null) { return r; } @@ -250,7 +250,7 @@ public class Items { String[] c = context.getFullName().split("/"); String[] p = path.split("/"); - Stack name = new Stack(); + Stack name = new Stack<>(); for (int i=0; i newValue = new ArrayList(); + List newValue = new ArrayList<>(); while(tokens.hasMoreTokens()) { String relativeName = tokens.nextToken().trim(); String canonicalName = getCanonicalName(context, relativeName); @@ -400,14 +400,14 @@ public class Items { * @since 1.512 */ public static List getAllItems(final ItemGroup root, Class type) { - List r = new ArrayList(); + List r = new ArrayList<>(); getAllItems(root, type, r); return r; } private static void getAllItems(final ItemGroup root, Class type, List r) { - List items = new ArrayList(((ItemGroup) root).getItems()); + List items = new ArrayList<>(((ItemGroup) root).getItems()); // because we add items depth first, we can use the quicker BY_NAME comparison - Collections.sort(items, BY_NAME); + items.sort(BY_NAME); for (Item i : items) { if (type.isInstance(i)) { if (i.hasPermission(Item.READ)) { diff --git a/core/src/main/java/hudson/model/JDK.java b/core/src/main/java/hudson/model/JDK.java index 043a5f392f..b7181ab45b 100644 --- a/core/src/main/java/hudson/model/JDK.java +++ b/core/src/main/java/hudson/model/JDK.java @@ -163,9 +163,7 @@ public final class JDK extends ToolInstallation implements NodeSpecific, En TaskListener listener = new StreamTaskListener(new NullStream()); Launcher launcher = n.createLauncher(listener); return launcher.launch().cmds("java","-fullversion").stdout(listener).join()==0; - } catch (IOException e) { - return false; - } catch (InterruptedException e) { + } catch (IOException | InterruptedException e) { return false; } } diff --git a/core/src/main/java/hudson/model/Job.java b/core/src/main/java/hudson/model/Job.java index 047e90a85f..820c85e8ae 100644 --- a/core/src/main/java/hudson/model/Job.java +++ b/core/src/main/java/hudson/model/Job.java @@ -175,7 +175,7 @@ public abstract class Job, RunT extends Run> properties = new CopyOnWriteList>(); + protected CopyOnWriteList> properties = new CopyOnWriteList<>(); @Restricted(NoExternalUse.class) public transient RunIdMigrator runIdMigrator; @@ -232,7 +232,7 @@ public abstract class Job, RunT extends Run>(); + properties = new CopyOnWriteList<>(); for (JobProperty p : properties) p.setOwner(this); @@ -595,14 +595,14 @@ public abstract class Job, RunT extends Run getOverrides() { - List r = new ArrayList(); + List r = new ArrayList<>(); for (JobProperty p : properties) r.addAll(p.getJobOverrides()); return r; } public List getWidgets() { - ArrayList r = new ArrayList(); + ArrayList r = new ArrayList<>(); r.add(createHistoryWidget()); return r; } @@ -741,7 +741,7 @@ public abstract class Job, RunT extends Run getBuilds(RangeSet rs) { - List builds = new LinkedList(); + List builds = new LinkedList<>(); for (Range r : rs.getRanges()) { for (RunT b = getNearestBuild(r.start); b!=null && b.getNumber(), RunT extends Run getLastBuildsOverThreshold(int numberOfBuilds, Result threshold) { - List result = new ArrayList(numberOfBuilds); + List result = new ArrayList<>(numberOfBuilds); RunT r = getLastBuild(); while (r != null && result.size() < numberOfBuilds) { @@ -1021,7 +1021,7 @@ public abstract class Job, RunT extends Run getEstimatedDurationCandidates() { - List candidates = new ArrayList(3); + List candidates = new ArrayList<>(3); RunT lastSuccessful = getLastSuccessfulBuild(); int lastSuccessfulNumber = -1; if (lastSuccessful != null) { @@ -1031,7 +1031,7 @@ public abstract class Job, RunT extends Run fallbackCandidates = new ArrayList(3); + List fallbackCandidates = new ArrayList<>(3); while (r != null && candidates.size() < 3 && i < 6) { if (!r.isBuilding() && r.getResult() != null && r.getNumber() != lastSuccessfulNumber) { Result result = r.getResult(); @@ -1103,7 +1103,7 @@ public abstract class Job, RunT extends Run entries = new ArrayList(); + List entries = new ArrayList<>(); String scmDisplayName = ""; if (this instanceof SCMTriggerItem) { SCMTriggerItem scmItem = (SCMTriggerItem) this; @@ -1199,7 +1199,7 @@ public abstract class Job, RunT extends Run getBuildHealthReports() { - List reports = new ArrayList(); + List reports = new ArrayList<>(); RunT lastBuild = getLastBuild(); if (lastBuild != null && lastBuild.isBuilding()) { @@ -1241,7 +1241,7 @@ public abstract class Job, RunT extends Run(reports); + cachedBuildHealthReports = new ArrayList<>(reports); } return reports; @@ -1332,7 +1332,7 @@ public abstract class Job, RunT extends Run, JobPropertyDescriptor> t = new DescribableList, JobPropertyDescriptor>(NOOP,getAllProperties()); + DescribableList, JobPropertyDescriptor> t = new DescribableList<>(NOOP, getAllProperties()); JSONObject jsonProperties = json.optJSONObject("properties"); if (jsonProperties != null) { t.rebuild(req,jsonProperties,JobPropertyDescriptor.getPropertyDescriptors(Job.this.getClass())); @@ -1469,7 +1469,7 @@ public abstract class Job, RunT extends Run data = new DataSetBuilder(); + DataSetBuilder data = new DataSetBuilder<>(); for (Run r : getNewBuilds()) { if (r.isBuilding()) continue; diff --git a/core/src/main/java/hudson/model/JobPropertyDescriptor.java b/core/src/main/java/hudson/model/JobPropertyDescriptor.java index 6955dff091..1a90cedf85 100644 --- a/core/src/main/java/hudson/model/JobPropertyDescriptor.java +++ b/core/src/main/java/hudson/model/JobPropertyDescriptor.java @@ -99,7 +99,7 @@ public abstract class JobPropertyDescriptor extends Descriptor> { * Gets the {@link JobPropertyDescriptor}s applicable for a given job type. */ public static List getPropertyDescriptors(Class clazz) { - List r = new ArrayList(); + List r = new ArrayList<>(); for (JobPropertyDescriptor p : all()) if(p.isApplicable(clazz)) r.add(p); diff --git a/core/src/main/java/hudson/model/Label.java b/core/src/main/java/hudson/model/Label.java index 049d0f89fc..0cb65eea38 100644 --- a/core/src/main/java/hudson/model/Label.java +++ b/core/src/main/java/hudson/model/Label.java @@ -241,7 +241,7 @@ public abstract class Label extends Actionable implements Comparable