Merge commit '32b4bfb3a23bd186f4f9486185c031c7f406b858' of git://github.com/jenkinsci/jenkins

This commit is contained in:
Daniel Beck committed 2019-04-08 17:16:39 +02:00
commit 0207fbc6c7
281 files changed
+1308 -983

No files matched your search

@@ -141,7 +141,7 @@ public abstract class AbstractMarkupText {
public List<MarkupText.SubText> findTokens(Pattern pattern) {
String text = getText();
Matcher m = pattern.matcher(text);
List<SubText> r = new ArrayList<SubText>();
List<SubText> r = new ArrayList<>();
while(m.find()) {
int idx = m.start();
+1 -1
View File
@@ -132,7 +132,7 @@ public class BulkChange implements Closeable {
/**
* {@link BulkChange}s that are effective currently.
*/
private static final ThreadLocal<BulkChange> INSCOPE = new ThreadLocal<BulkChange>();
private static final ThreadLocal<BulkChange> INSCOPE = new ThreadLocal<>();
/**
* Gets the {@link BulkChange} instance currently in scope for the current thread.
@@ -192,7 +192,7 @@ public class ClassicPluginStrategy implements PluginStrategy {
// TODO: define a mechanism to hide classes
// String export = manifest.getMainAttributes().getValue("Export");
List<File> paths = new ArrayList<File>();
List<File> 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<PluginWrapper.Dependency> dependencies = new ArrayList<PluginWrapper.Dependency>();
List<PluginWrapper.Dependency> optionalDependencies = new ArrayList<PluginWrapper.Dependency>();
List<PluginWrapper.Dependency> dependencies = new ArrayList<>();
List<PluginWrapper.Dependency> 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>(t));
r.add(new ExtensionComponent<>(t));
}
}
@@ -578,7 +578,7 @@ public class ClassicPluginStrategy implements PluginStrategy {
CyclicGraphDetector<PluginWrapper> cgd = new CyclicGraphDetector<PluginWrapper>() {
@Override
protected List<PluginWrapper> getEdges(PluginWrapper pw) {
List<PluginWrapper> dep = new ArrayList<PluginWrapper>();
List<PluginWrapper> 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<URL> findResources(String name) throws IOException {
HashSet<URL> result = new HashSet<URL>();
HashSet<URL> result = new HashSet<>();
if (PluginManager.FAST_LOOKUP) {
for (PluginWrapper pw : getTransitiveDependencies()) {
+1 -1
View File
@@ -32,7 +32,7 @@ public class DNSMultiCast implements Closeable {
try {
jmdns = JmDNS.create();
Map<String,String> props = new HashMap<String, String>();
Map<String,String> props = new HashMap<>();
String rootURL = jenkins.getRootUrl();
if (rootURL==null) return null;
@@ -76,7 +76,7 @@ public class DescriptorExtensionList<T extends Describable<T>, D extends Descrip
if (describableType == (Class) Publisher.class) {
return (DescriptorExtensionList) new Publisher.DescriptorExtensionListImpl(jenkins);
}
return new DescriptorExtensionList<T,D>(jenkins,describableType);
return new DescriptorExtensionList<>(jenkins, describableType);
}
/**
@@ -199,7 +199,7 @@ public class DescriptorExtensionList<T extends Describable<T>, D extends Descrip
}
private List<ExtensionComponent<D>> _load(Iterable<ExtensionComponent<Descriptor>> set) {
List<ExtensionComponent<D>> r = new ArrayList<ExtensionComponent<D>>();
List<ExtensionComponent<D>> r = new ArrayList<>();
for( ExtensionComponent<Descriptor> c : set ) {
Descriptor d = c.getInstance();
try {
+5 -5
View File
@@ -200,7 +200,7 @@ public class EnvVars extends TreeMap<String,String> {
}
public void clear() {
referredVariables = new TreeSet<String>(comparator);
referredVariables = new TreeSet<>(comparator);
}
public String resolve(String name) {
@@ -288,8 +288,8 @@ public class EnvVars extends TreeMap<String,String> {
* Scan all variables and list all referring variables.
*/
public void scan() {
refereeSetMap = new TreeMap<String, Set<String>>(comparator);
List<String> extendingVariableNames = new ArrayList<String>();
refereeSetMap = new TreeMap<>(comparator);
List<String> extendingVariableNames = new ArrayList<>();
TraceResolver resolver = new TraceResolver(comparator);
@@ -327,10 +327,10 @@ public class EnvVars extends TreeMap<String,String> {
// When A refers B, the last appearance of B always comes after
// the last appearance of A.
List<String> reversedDuplicatedOrder = new ArrayList<String>(sorter.getSorted());
List<String> reversedDuplicatedOrder = new ArrayList<>(sorter.getSorted());
Collections.reverse(reversedDuplicatedOrder);
orderedVariableNames = new ArrayList<String>(overrides.size());
orderedVariableNames = new ArrayList<>(overrides.size());
for(String key: reversedDuplicatedOrder) {
if(overrides.containsKey(key) && !orderedVariableNames.contains(key)) {
orderedVariableNames.add(key);
@@ -168,5 +168,5 @@ final class ExpressionFactory2 implements ExpressionFactory {
*
* @see Functions#getCurrentJellyContext()
*/
protected static final ThreadLocal<JellyContext> CURRENT_CONTEXT = new ThreadLocal<JellyContext>();
protected static final ThreadLocal<JellyContext> CURRENT_CONTEXT = new ThreadLocal<>();
}
@@ -95,9 +95,7 @@ public class ExtensionComponent<T> implements Comparable<ExtensionComponent<T>>
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);
}
}
+8 -8
View File
@@ -86,7 +86,7 @@ public class ExtensionList<T> extends AbstractList<T> implements OnMaster {
@CopyOnWrite
private volatile List<ExtensionComponent<T>> extensions;
private final List<ExtensionListListener> listeners = new CopyOnWriteArrayList<ExtensionListListener>();
private final List<ExtensionListListener> listeners = new CopyOnWriteArrayList<>();
/**
* Place to store manually registered instances with the per-Hudson scope.
@@ -104,7 +104,7 @@ public class ExtensionList<T> extends AbstractList<T> implements OnMaster {
}
protected ExtensionList(Jenkins jenkins, Class<T> extensionType) {
this(jenkins,extensionType,new CopyOnWriteArrayList<ExtensionComponent<T>>());
this(jenkins,extensionType, new CopyOnWriteArrayList<>());
}
/**
@@ -237,7 +237,7 @@ public class ExtensionList<T> extends AbstractList<T> implements OnMaster {
private synchronized boolean removeSync(Object o) {
boolean removed = removeComponent(legacyInstances, o);
if(extensions!=null) {
List<ExtensionComponent<T>> r = new ArrayList<ExtensionComponent<T>>(extensions);
List<ExtensionComponent<T>> r = new ArrayList<>(extensions);
removed |= removeComponent(r,o);
extensions = sort(r);
}
@@ -279,11 +279,11 @@ public class ExtensionList<T> extends AbstractList<T> implements OnMaster {
}
private synchronized boolean addSync(T t) {
legacyInstances.add(new ExtensionComponent<T>(t));
legacyInstances.add(new ExtensionComponent<>(t));
// if we've already filled extensions, add it
if(extensions!=null) {
List<ExtensionComponent<T>> r = new ArrayList<ExtensionComponent<T>>(extensions);
r.add(new ExtensionComponent<T>(t));
List<ExtensionComponent<T>> r = new ArrayList<>(extensions);
r.add(new ExtensionComponent<>(t));
extensions = sort(r);
}
return true;
@@ -395,7 +395,7 @@ public class ExtensionList<T> extends AbstractList<T> implements OnMaster {
* The implementation should copy a list, do a sort, and return the new instance.
*/
protected List<ExtensionComponent<T>> sort(List<ExtensionComponent<T>> r) {
r = new ArrayList<ExtensionComponent<T>>(r);
r = new ArrayList<>(r);
Collections.sort(r);
return r;
}
@@ -412,7 +412,7 @@ public class ExtensionList<T> extends AbstractList<T> implements OnMaster {
@SuppressWarnings({"unchecked", "rawtypes"})
public static <T> ExtensionList<T> create(Jenkins jenkins, Class<T> type) {
if(type.getAnnotation(LegacyInstancesAreScopedToHudson.class)!=null)
return new ExtensionList<T>(jenkins,type);
return new ExtensionList<>(jenkins, type);
else {
return new ExtensionList(jenkins, type, staticLegacyInstances.computeIfAbsent(type, key -> new CopyOnWriteArrayList()));
}
+4 -4
View File
@@ -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<String> tokens = new ArrayList<String>();
List<String> 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<T,IOException> wrapper = new FileCallableWrapper<T>(callable, cl);
DelegatingCallable<T,IOException> 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 <T> Future<T> actAsync(final FileCallable<T> callable) throws IOException, InterruptedException {
try {
DelegatingCallable<T,IOException> wrapper = new FileCallableWrapper<T>(callable);
DelegatingCallable<T,IOException> 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<FilePath> r = new ArrayList<FilePath>(children.length);
ArrayList<FilePath> r = new ArrayList<>(children.length);
for (File child : children)
r.add(new FilePath(child));
+3 -3
View File
@@ -465,7 +465,7 @@ public class Functions {
}
public static Map getSystemProperties() {
return new TreeMap<Object,Object>(System.getProperties());
return new TreeMap<>(System.getProperties());
}
/**
@@ -479,7 +479,7 @@ public class Functions {
}
public static Map getEnvVars() {
return new TreeMap<String,String>(EnvVars.masterEnvVars);
return new TreeMap<>(EnvVars.masterEnvVars);
}
public static boolean isWindows() {
@@ -544,7 +544,7 @@ public class Functions {
* @since 1.525
*/
public static <T> Iterable<T> reverse(Collection<T> collection) {
List<T> list = new ArrayList<T>(collection);
List<T> list = new ArrayList<>(collection);
Collections.reverse(list);
return list;
}
+3 -3
View File
@@ -197,14 +197,14 @@ public abstract class Launcher {
}
public ProcStarter cmds(File program, String... args) {
commands = new ArrayList<String>(args.length+1);
commands = new ArrayList<>(args.length + 1);
commands.add(program.getPath());
commands.addAll(Arrays.asList(args));
return this;
}
public ProcStarter cmds(List<String> args) {
commands = new ArrayList<String>(args);
commands = new ArrayList<>(args);
return this;
}
@@ -774,7 +774,7 @@ public abstract class Launcher {
*/
protected final void maskedPrintCommandLine(@Nonnull List<String> 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;
}
+1 -1
View File
@@ -32,7 +32,7 @@ import java.util.concurrent.ConcurrentHashMap;
* @author Kohsuke Kawaguchi
*/
public class Lookup {
private final ConcurrentHashMap<Class,Object> data = new ConcurrentHashMap<Class,Object>();
private final ConcurrentHashMap<Class,Object> data = new ConcurrentHashMap<>();
public <T> T get(Class<T> type) {
return type.cast(data.get(type));
+3 -3
View File
@@ -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<String> cmd = new ArrayList<String>();
for( int i=1; i<args.length; i++ )
cmd.add(args[i]);
List<String> 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)));
+1 -1
View File
@@ -45,7 +45,7 @@ public class MarkupText extends AbstractMarkupText {
/**
* Added mark up tags.
*/
private final List<Tag> tags = new ArrayList<Tag>();
private final List<Tag> tags = new ArrayList<>();
/**
* Represents one mark up inserted into text.
+1 -1
View File
@@ -60,7 +60,7 @@ public final class PermalinkList extends ArrayList<Permalink> {
* Finds the closest name match by its ID.
*/
public Permalink findNearest(String id) {
List<String> ids = new ArrayList<String>();
List<String> ids = new ArrayList<>();
for (Permalink p : this)
ids.add(p.getId());
String nearest = EditDistance.findNearest(id, ids);
+16 -19
View File
@@ -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<PluginWrapper> activePlugins = new CopyOnWriteArrayList<PluginWrapper>();
protected final List<PluginWrapper> activePlugins = new CopyOnWriteArrayList<>();
protected final List<FailedPlugin> failedPlugins = new ArrayList<FailedPlugin>();
protected final List<FailedPlugin> 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<String,File> inspectedShortNames = new HashMap<String,File>();
final Map<String,File> 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<PluginWrapper> cgd = new CyclicGraphDetector<PluginWrapper>() {
@Override
protected List<PluginWrapper> getEdges(PluginWrapper p) {
List<PluginWrapper> next = new ArrayList<PluginWrapper>();
List<PluginWrapper> 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<PluginWrapper> getPlugins(Class<? extends Plugin> pluginSuperclass) {
List<PluginWrapper> result = new ArrayList<PluginWrapper>();
List<PluginWrapper> 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 <T> Collection<Class<? extends T>> discover( Class<T> spi ) {
Set<Class<? extends T>> result = new HashSet<Class<? extends T>>();
Set<Class<? extends T>> 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<Future<UpdateCenter.UpdateCenterJob>> prevalidateConfig(InputStream configXml) throws IOException {
Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);
List<Future<UpdateCenter.UpdateCenterJob>> jobs = new ArrayList<Future<UpdateCenter.UpdateCenterJob>>();
List<Future<UpdateCenter.UpdateCenterJob>> 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<String,VersionNumber> 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<String,VersionNumber> parseRequestedPlugins(InputStream configXml) throws IOException {
final Map<String,VersionNumber> requestedPlugins = new TreeMap<String,VersionNumber>();
final Map<String,VersionNumber> 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<String, WeakReference<Class>> generatedClasses = new ConcurrentHashMap<String, WeakReference<Class>>();
private ConcurrentMap<String, WeakReference<Class>> generatedClasses = new ConcurrentHashMap<>();
/** Cache of loaded, or known to be unloadable, classes. */
private final Map<String,Class<?>> loaded = new HashMap<String,Class<?>>();
private final Map<String,Class<?>> loaded = new HashMap<>();
public UberClassLoader() {
super(PluginManager.class.getClassLoader());
}
public void addNamedClass(String className, Class c) {
generatedClasses.put(className,new WeakReference<Class>(c));
generatedClasses.put(className, new WeakReference<>(c));
}
@Override
@@ -2071,7 +2068,7 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas
@Override
protected Enumeration<URL> findResources(String name) throws IOException {
List<URL> resources = new ArrayList<URL>();
List<URL> resources = new ArrayList<>();
if (FAST_LOOKUP) {
for (PluginWrapper p : activePlugins) {
resources.addAll(Collections.list(ClassLoaderReflectionToolkit._findResources(p.classLoader, name)));
@@ -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 {
+4 -4
View File
@@ -114,7 +114,7 @@ public class Util {
*/
@Nonnull
public static <T> List<T> filter( @Nonnull Iterable<?> base, @Nonnull Class<T> type ) {
List<T> r = new ArrayList<T>();
List<T> 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<String,String> properties) {
return replaceMacro(s,new VariableResolver.ByMap<String>(properties));
return replaceMacro(s, new VariableResolver.ByMap<>(properties));
}
/**
@@ -783,7 +783,7 @@ public class Util {
*/
@Nonnull
public static <T> List<T> createSubList(@Nonnull Collection<?> source, @Nonnull Class<T> type ) {
List<T> r = new ArrayList<T>();
List<T> 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<? extends T> item : items)
size += item.size();
List<T> r = new ArrayList<T>(size);
List<T> r = new ArrayList<>(size);
for (Collection<? extends T> item : items)
r.addAll(item);
return r;
@@ -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<CLICommand> CURRENT_COMMAND = new ThreadLocal<CLICommand>();
private static final ThreadLocal<CLICommand> CURRENT_COMMAND = new ThreadLocal<>();
/*package*/ static CLICommand setCurrent(CLICommand cmd) {
CLICommand old = getCurrent();
@@ -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;
}
@@ -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<String> sources = new ArrayList<String>();
public List<String> 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
@@ -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<T> 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<T> 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<T> 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<T> caw = new ConsoleAnnotationOutputStream<>(
w, createAnnotator(Stapler.getCurrentRequest()), context, charset);
@@ -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<T> 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
@@ -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.)
* <p>Implementations which are {@link Serializable} may be sent to an agent JVM for processing.
* In particular, this happens under <a href="https://jenkins.io/jep/210">JEP-210</a>.
* 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
@@ -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.
*
* <p>
* 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
* <a href="https://jenkins.io/security/advisory/2017-02-01/#persisted-cross-site-scripting-vulnerability-in-console-notes">SECURITY-382</a>
* 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.
*
* <h2>Behaviour, JavaScript, and CSS</h2>
* <p>
* {@link ConsoleNote} can have associated {@code script.js} and {@code style.css} (put them
@@ -192,18 +203,15 @@ public abstract class ConsoleNote<T> implements Serializable, Describable<Consol
ByteArrayOutputStream buf2 = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(new Base64OutputStream(buf2,true,-1,null));
try {
try (DataOutputStream dos = new DataOutputStream(new Base64OutputStream(buf2, true, -1, null))) {
buf2.write(PREAMBLE);
if (JenkinsJVM.isJenkinsJVM()) { // else we are in another JVM and cannot sign; result will be ignored unless INSECURE
byte[] mac = MAC.mac(buf.toByteArray());
dos.writeInt(- mac.length); // negative to differentiate from older form
dos.writeInt(-mac.length); // negative to differentiate from older form
dos.write(mac);
}
dos.writeInt(buf.size());
buf.writeTo(dos);
} finally {
dos.close();
}
buf2.write(POSTAMBLE);
return buf2;
@@ -239,6 +247,9 @@ public abstract class ConsoleNote<T> implements Serializable, Describable<Consol
mac = new byte[macSz];
decoded.readFully(mac);
sz = decoded.readInt();
if (sz < 0) {
throw new IOException("Corrupt stream");
}
} else {
mac = null;
sz = - macSz;
@@ -251,12 +262,12 @@ public abstract class ConsoleNote<T> implements Serializable, Describable<Consol
if (!Arrays.equals(postamble,POSTAMBLE))
return null; // not a valid postamble
if (mac == null) {
if (!INSECURE) {
if (!INSECURE) {
if (mac == null) {
throw new IOException("Refusing to deserialize unsigned note from an old log.");
} else if (!MAC.checkMac(buf, mac)) {
throw new IOException("MAC mismatch");
}
} else if (!MAC.checkMac(buf, mac)) {
throw new IOException("MAC mismatch");
}
Jenkins jenkins = Jenkins.getInstance();
@@ -337,7 +348,7 @@ public abstract class ConsoleNote<T> implements Serializable, Describable<Consol
* @since 1.350
*/
public static List<String> removeNotes(Collection<String> logLines) {
List<String> r = new ArrayList<String>(logLines.size());
List<String> r = new ArrayList<>(logLines.size());
for (String l : logLines)
r.add(removeNotes(l));
return r;
@@ -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<MemoryPoolMXBean> pools = new ArrayList<MemoryPoolMXBean>();
private final List<MemoryPoolMXBean> pools = new ArrayList<>();
/**
* Trend of the memory usage, after GCs.
@@ -55,7 +55,7 @@ public class NullIdDescriptorMonitor extends AdministrativeMonitor {
return Messages.NullIdDescriptorMonitor_DisplayName();
}
private final List<Descriptor> problems = new ArrayList<Descriptor>();
private final List<Descriptor> problems = new ArrayList<>();
@Override
public boolean isActivated() {
@@ -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<SaveableReference,VersionRange> data = new ConcurrentHashMap<SaveableReference,VersionRange>();
private ConcurrentMap<SaveableReference,VersionRange> data = new ConcurrentHashMap<>();
/**
* Gets instance of the monitor.
@@ -106,7 +106,7 @@ public class OldDataMonitor extends AdministrativeMonitor {
}
public Map<Saveable,VersionRange> getData() {
Map<Saveable,VersionRange> r = new HashMap<Saveable,VersionRange>();
Map<Saveable,VersionRange> r = new HashMap<>();
for (Map.Entry<SaveableReference,VersionRange> entry : this.data.entrySet()) {
Saveable s = entry.getKey().get();
if (s != null) {
@@ -45,7 +45,7 @@ public class InitStrategy {
* and when that happens, Jenkins will ignore all but the first one in the list.
*/
public List<File> listPluginArchives(PluginManager pm) throws IOException {
List<File> r = new ArrayList<File>();
List<File> 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
@@ -32,7 +32,7 @@ import static java.util.logging.Level.WARNING;
abstract class TaskMethodFinder<T extends Annotation> extends TaskBuilder {
private static final Logger LOGGER = Logger.getLogger(TaskMethodFinder.class.getName());
protected final ClassLoader cl;
private final Set<Method> discovered = new HashSet<Method>();
private final Set<Method> discovered = new HashSet<>();
private final Class<T> type;
private final Class<? extends Enum> milestoneType;
@@ -52,7 +52,7 @@ abstract class TaskMethodFinder<T extends Annotation> extends TaskBuilder {
protected abstract boolean fatalOf(T i);
public Collection<Task> discoverTasks(Reactor session) throws IOException {
List<Task> result = new ArrayList<Task>();
List<Task> 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<T extends Annotation> extends TaskBuilder {
}
private Collection<Milestone> toMilestones(String[] tokens, Milestone m) {
List<Milestone> r = new ArrayList<Milestone>();
List<Milestone> r = new ArrayList<>();
for (String s : tokens) {
try {
r.add((Milestone)Enum.valueOf(milestoneType,s));
@@ -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()));
}
@@ -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();
}
}
@@ -75,7 +75,7 @@ import org.kohsuke.accmod.restrictions.NoExternalUse;
public class LogRecorder extends AbstractModelObject implements Saveable {
private volatile String name;
public final CopyOnWriteList<Target> targets = new CopyOnWriteList<Target>();
public final CopyOnWriteList<Target> targets = new CopyOnWriteList<>();
private final static TargetComparator TARGET_COMPARATOR = new TargetComparator();
@Restricted(NoExternalUse.class)
@@ -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<String,LogRecorder> logRecorders = new CopyOnWriteMap.Tree<String,LogRecorder>();
public transient final Map<String,LogRecorder> 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<LogRecord> filtered = new ArrayList<LogRecord>();
List<LogRecord> filtered = new ArrayList<>();
for (LogRecord r : logs) {
if(r.getLevel().intValue() >= threshold.intValue())
filtered.add(r);
@@ -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<Handler>(target);
this.target = new WeakReference<>(target);
}
public void publish(LogRecord record) {
@@ -465,7 +465,7 @@ public abstract class AbstractBuild<P extends AbstractProject<P,R>,R extends Abs
listener.getLogger().print(Messages.AbstractBuild_BuildingOnMaster());
} else {
listener.getLogger().print(Messages.AbstractBuild_BuildingRemotely(ModelHyperlinkNote.encodeTo("/computer/" + builtOn, node.getDisplayName())));
Set<LabelAtom> assignedLabels = new HashSet<LabelAtom>(node.getAssignedLabels());
Set<LabelAtom> assignedLabels = new HashSet<>(node.getAssignedLabels());
assignedLabels.remove(node.getSelfLabel());
if (!assignedLabels.isEmpty()) {
boolean first = true;
@@ -536,7 +536,7 @@ public abstract class AbstractBuild<P extends AbstractProject<P,R>,R extends Abs
l = bw.decorateLauncher(AbstractBuild.this,l,listener);
}
buildEnvironments = new ArrayList<Environment>();
buildEnvironments = new ArrayList<>();
for (RunListener rl: RunListener.all()) {
Environment environment = rl.setUpEnvironment(AbstractBuild.this, l, listener);
@@ -583,7 +583,7 @@ public abstract class AbstractBuild<P extends AbstractProject<P,R>,R extends Abs
}
build.scm = scm.createChangeLogParser();
build.changeSet = new WeakReference<ChangeLogSet<? extends Entry>>(build.calcChangeSet());
build.changeSet = new WeakReference<>(build.calcChangeSet());
for (SCMListener l : SCMListener.all())
try {
@@ -635,7 +635,7 @@ public abstract class AbstractBuild<P extends AbstractProject<P,R>,R extends Abs
post2(listener);
} finally {
// update the culprit list
HashSet<String> r = new HashSet<String>();
HashSet<String> r = new HashSet<>();
for (User u : getCulprits())
r.add(u.getId());
culprits = ImmutableSortedSet.copyOf(r);
@@ -694,10 +694,7 @@ public abstract class AbstractBuild<P extends AbstractProject<P,R>,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<P extends AbstractProject<P,R>,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<P extends AbstractProject<P,R>,R extends Abs
if (cs==null)
cs = ChangeLogSet.createEmpty(this);
changeSet = new WeakReference<ChangeLogSet<? extends Entry>>(cs);
changeSet = new WeakReference<>(cs);
return cs;
}
@@ -859,9 +853,7 @@ public abstract class AbstractBuild<P extends AbstractProject<P,R>,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<P extends AbstractProject<P,R>,R extends Abs
public EnvironmentList getEnvironments() {
Executor e = Executor.currentExecutor();
if (e!=null && e.getCurrentExecutable()==this) {
if (buildEnvironments==null) buildEnvironments = new ArrayList<Environment>();
if (buildEnvironments==null) buildEnvironments = new ArrayList<>();
return new EnvironmentList(buildEnvironments);
}
@@ -936,7 +928,7 @@ public abstract class AbstractBuild<P extends AbstractProject<P,R>,R extends Abs
* @since 1.378
*/
public Set<String> getSensitiveBuildVariables() {
Set<String> s = new HashSet<String>();
Set<String> s = new HashSet<>();
ParametersAction parameters = getAction(ParametersAction.class);
if (parameters != null) {
@@ -973,7 +965,7 @@ public abstract class AbstractBuild<P extends AbstractProject<P,R>,R extends Abs
* The returned map is mutable so that subtypes can put more values.
*/
public Map<String,String> getBuildVariables() {
Map<String,String> r = new HashMap<String, String>();
Map<String,String> r = new HashMap<>();
ParametersAction parameters = getAction(ParametersAction.class);
if (parameters!=null) {
@@ -1000,7 +992,7 @@ public abstract class AbstractBuild<P extends AbstractProject<P,R>,R extends Abs
* Creates {@link VariableResolver} backed by {@link #getBuildVariables()}.
*/
public final VariableResolver<String> getBuildVariableResolver() {
return new VariableResolver.ByMap<String>(getBuildVariables());
return new VariableResolver.ByMap<>(getBuildVariables());
}
/**
@@ -1173,7 +1165,7 @@ public abstract class AbstractBuild<P extends AbstractProject<P,R>,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<AbstractProject,RangeSet> getDownstreamBuilds() {
Map<AbstractProject,RangeSet> r = new HashMap<AbstractProject,RangeSet>();
Map<AbstractProject,RangeSet> r = new HashMap<>();
for (AbstractProject p : getParent().getDownstreamProjects()) {
if (p.isFingerprintConfigured())
r.put(p,getDownstreamRelationship(p));
@@ -1200,7 +1192,7 @@ public abstract class AbstractBuild<P extends AbstractProject<P,R>,R extends Abs
}
private Map<AbstractProject, Integer> _getUpstreamBuilds(Collection<AbstractProject> projects) {
Map<AbstractProject,Integer> r = new HashMap<AbstractProject,Integer>();
Map<AbstractProject,Integer> r = new HashMap<>();
for (AbstractProject p : projects) {
int n = getUpstreamRelationship(p);
if (n>=0)
@@ -1222,7 +1214,7 @@ public abstract class AbstractBuild<P extends AbstractProject<P,R>,R extends Abs
Map<AbstractProject,Integer> ndep = n.getDependencies(true);
Map<AbstractProject,Integer> odep = o.getDependencies(true);
Map<AbstractProject,DependencyChange> r = new HashMap<AbstractProject,DependencyChange>();
Map<AbstractProject,DependencyChange> r = new HashMap<>();
for (Map.Entry<AbstractProject,Integer> entry : odep.entrySet()) {
AbstractProject p = entry.getKey();
@@ -1274,7 +1266,7 @@ public abstract class AbstractBuild<P extends AbstractProject<P,R>,R extends Abs
* of IDs, but due to log rotations, some builds may be already unavailable.
*/
public List<AbstractBuild> getBuilds() {
List<AbstractBuild> r = new ArrayList<AbstractBuild>();
List<AbstractBuild> r = new ArrayList<>();
AbstractBuild<?,?> b = project.getNearestBuild(fromId);
if (b!=null && b.getNumber()==fromId)
@@ -822,7 +822,7 @@ public abstract class AbstractProject<P extends AbstractProject<P,R>,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]));
}
/**
@@ -78,7 +78,7 @@ public abstract class Actionable extends AbstractModelObject implements ModelObj
if (actions == null) {
synchronized (this) {
if (actions == null) {
actions = new CopyOnWriteArrayList<Action>();
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<Action> old = new ArrayList<Action>(1);
List<Action> old = new ArrayList<>(1);
List<Action> 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<Action> old = new ArrayList<Action>();
List<Action> old = new ArrayList<>();
List<Action> 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<Action> old = new ArrayList<Action>();
List<Action> old = new ArrayList<>();
List<Action> current = getActions();
boolean found = false;
for (Action a1 : current) {
@@ -126,9 +126,7 @@ public abstract class AperiodicWork extends SafeTimerTask implements ExtensionPo
private final Set<AperiodicWork> registered = new HashSet<>();
AperiodicWorkExtensionListListener(ExtensionList<AperiodicWork> initiallyRegistered) {
for (AperiodicWork p : initiallyRegistered) {
registered.add(p);
}
registered.addAll(initiallyRegistered);
}
@Override
@@ -48,7 +48,7 @@ import org.apache.commons.lang.StringUtils;
* @author Kohsuke Kawaguchi
*/
public class AutoCompletionCandidates implements HttpResponse {
private final List<String> values = new ArrayList<String>();
private final List<String> values = new ArrayList<>();
public AutoCompletionCandidates add(String v) {
values.add(v);
+1 -1
View File
@@ -147,7 +147,7 @@ public abstract class Build <P extends Project<P,B>,B extends Build<P,B>>
Result r = null;
try {
List<BuildWrapper> wrappers = new ArrayList<BuildWrapper>(project.getBuildWrappers().values());
List<BuildWrapper> wrappers = new ArrayList<>(project.getBuildWrappers().values());
ParametersAction parameters = getAction(ParametersAction.class);
if (parameters != null)
+4 -4
View File
@@ -175,8 +175,8 @@ public abstract class Cause {
upstreamBuild = up.getNumber();
upstreamProject = up.getParent().getFullName();
upstreamUrl = up.getParent().getUrl();
upstreamCauses = new ArrayList<Cause>();
Set<String> traversed = new HashSet<String>();
upstreamCauses = new ArrayList<>();
Set<String> 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<Cause> cs = new ArrayList<Cause>();
List<Cause> 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<Cause>();
if (uc.upstreamCauses == null) uc.upstreamCauses = new ArrayList<>();
uc.upstreamCauses.add(uc.upstreamCause);
uc.upstreamCause = null;
OldDataMonitor.report(context, "1.288");
@@ -45,7 +45,7 @@ public class ChoiceParameterDefinition extends SimpleParameterDefinition {
public ChoiceParameterDefinition(String name, String[] choices, String description) {
super(name, description);
this.choices = new ArrayList<String>(Arrays.asList(choices));
this.choices = new ArrayList<>(Arrays.asList(choices));
defaultValue = null;
}
+12 -13
View File
@@ -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<Executor> executors = new CopyOnWriteArrayList<Executor>();
private final CopyOnWriteArrayList<Executor> executors = new CopyOnWriteArrayList<>();
// TODO:
private final CopyOnWriteArrayList<OneOffExecutor> oneOffExecutors = new CopyOnWriteArrayList<OneOffExecutor>();
private final CopyOnWriteArrayList<OneOffExecutor> 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<TerminationRequest> terminatedBy = Collections.synchronizedList(new ArrayList
<TerminationRequest>());
private transient final List<TerminationRequest> 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<TerminationRequest> getTerminatedBy() {
return new ArrayList<TerminationRequest>(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<Action> getActions() {
List<Action> result = new ArrayList<Action>();
List<Action> 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<Computer> getLogText() {
checkPermission(CONNECT);
return new AnnotatedLargeText<Computer>(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<Integer> availableNumbers = new HashSet<Integer>();
Set<Integer> 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<Executor> getExecutors() {
return new ArrayList<Executor>(executors);
return new ArrayList<>(executors);
}
/**
@@ -974,7 +973,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces
@Exported
@StaplerDispatchable
public List<OneOffExecutor> getOneOffExecutors() {
return new ArrayList<OneOffExecutor>(oneOffExecutors);
return new ArrayList<>(oneOffExecutors);
}
/**
@@ -998,7 +997,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces
@Restricted(NoExternalUse.class)
public List<DisplayExecutor> getDisplayExecutors() {
// The size may change while we are populating, but let's start with a reasonable guess to minimize resizing
List<DisplayExecutor> result = new ArrayList<DisplayExecutor>(executors.size()+oneOffExecutors.size());
List<DisplayExecutor> 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<String/*monitor name*/,Object> getMonitorData() {
Map<String,Object> r = new HashMap<String, Object>();
Map<String,Object> 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<String> call() throws IOException {
List<String> names = new ArrayList<String>();
List<String> names = new ArrayList<>();
Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
while (nis.hasMoreElements()) {
@@ -37,7 +37,7 @@ public abstract class ComputerPanelBox implements ExtensionPoint{
* List of all the registered {@link ComputerPanelBox}s.
*/
public static List<ComputerPanelBox> all(Computer computer) {
List<ComputerPanelBox> boxs = new ArrayList<ComputerPanelBox>();
List<ComputerPanelBox> boxs = new ArrayList<>();
for(ComputerPanelBox box: ExtensionList.lookup(ComputerPanelBox.class)){
box.setComputer(computer);
boxs.add(box);
@@ -85,7 +85,7 @@ public final class ComputerSet extends AbstractModelObject implements Describabl
};
private static final DescribableList<NodeMonitor,Descriptor<NodeMonitor>> monitors
= new DescribableList<NodeMonitor, Descriptor<NodeMonitor>>(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<Descriptor<NodeMonitor>,NodeMonitor> getNonIgnoredMonitors() {
Map<Descriptor<NodeMonitor>,NodeMonitor> r = new HashMap<Descriptor<NodeMonitor>, NodeMonitor>();
Map<Descriptor<NodeMonitor>,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<String> getComputerNames() {
final ArrayList<String> names = new ArrayList<String>();
final ArrayList<String> 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<NodeMonitor,Descriptor<NodeMonitor>> r
= new DescribableList<NodeMonitor, Descriptor<NodeMonitor>>(Saveable.NOOP);
= new DescribableList<>(Saveable.NOOP);
// load persisted monitors
XmlFile xf = getConfigFile();
if(xf.exists()) {
DescribableList<NodeMonitor,Descriptor<NodeMonitor>> persisted =
(DescribableList<NodeMonitor,Descriptor<NodeMonitor>>) xf.read();
List<NodeMonitor> sanitized = new ArrayList<NodeMonitor>();
List<NodeMonitor> sanitized = new ArrayList<>();
for (NodeMonitor nm : persisted) {
try {
nm.getDescriptor();
@@ -70,8 +70,8 @@ import java.util.Stack;
*/
public class DependencyGraph implements Comparator<AbstractProject> {
private Map<AbstractProject, List<DependencyGroup>> forward = new HashMap<AbstractProject, List<DependencyGroup>>();
private Map<AbstractProject, List<DependencyGroup>> backward = new HashMap<AbstractProject, List<DependencyGroup>>();
private Map<AbstractProject, List<DependencyGroup>> forward = new HashMap<>();
private Map<AbstractProject, List<DependencyGroup>> backward = new HashMap<>();
private transient Map<Class<?>, Object> computationalData;
@@ -90,7 +90,7 @@ public class DependencyGraph implements Comparator<AbstractProject> {
// 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<Class<?>, 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<AbstractProject> {
DirectedGraph<AbstractProject> g = new DirectedGraph<AbstractProject>() {
@Override
protected Collection<AbstractProject> nodes() {
final Set<AbstractProject> nodes = new HashSet<AbstractProject>();
final Set<AbstractProject> nodes = new HashSet<>();
nodes.addAll(forward.keySet());
nodes.addAll(backward.keySet());
return nodes;
@@ -127,8 +127,8 @@ public class DependencyGraph implements Comparator<AbstractProject> {
List<SCC<AbstractProject>> sccs = g.getStronglyConnectedComponents();
final Map<AbstractProject,Integer> topoOrder = new HashMap<AbstractProject,Integer>();
topologicallySorted = new ArrayList<AbstractProject<?,?>>();
final Map<AbstractProject,Integer> topoOrder = new HashMap<>();
topologicallySorted = new ArrayList<>();
int idx=0;
for (SCC<AbstractProject> scc : sccs) {
for (AbstractProject n : scc) {
@@ -196,7 +196,7 @@ public class DependencyGraph implements Comparator<AbstractProject> {
private List<AbstractProject> get(Map<AbstractProject, List<DependencyGroup>> map, AbstractProject src, boolean up) {
List<DependencyGroup> v = map.get(src);
if(v==null) return Collections.emptyList();
List<AbstractProject> result = new ArrayList<AbstractProject>(v.size());
List<AbstractProject> 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<AbstractProject> {
* where the length is greater than 1.
*/
public boolean hasIndirectDependencies(AbstractProject src, AbstractProject dst) {
Set<AbstractProject> visited = new HashSet<AbstractProject>();
Stack<AbstractProject> queue = new Stack<AbstractProject>();
Set<AbstractProject> visited = new HashSet<>();
Stack<AbstractProject> queue = new Stack<>();
queue.addAll(getDownstream(src));
queue.remove(dst);
@@ -316,8 +316,8 @@ public class DependencyGraph implements Comparator<AbstractProject> {
}
private Set<AbstractProject> getTransitive(Map<AbstractProject, List<DependencyGroup>> direction, AbstractProject src, boolean up) {
Set<AbstractProject> visited = new HashSet<AbstractProject>();
Stack<AbstractProject> queue = new Stack<AbstractProject>();
Set<AbstractProject> visited = new HashSet<>();
Stack<AbstractProject> queue = new Stack<>();
queue.add(src);
@@ -334,11 +334,7 @@ public class DependencyGraph implements Comparator<AbstractProject> {
}
private void add(Map<AbstractProject, List<DependencyGroup>> map, AbstractProject key, Dependency dep) {
List<DependencyGroup> set = map.get(key);
if(set==null) {
set = new ArrayList<DependencyGroup>();
map.put(key,set);
}
List<DependencyGroup> 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<AbstractProject> {
private Map<AbstractProject, List<DependencyGroup>> finalize(Map<AbstractProject, List<DependencyGroup>> m) {
for (Entry<AbstractProject, List<DependencyGroup>> 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<AbstractProject> {
* Collect multiple dependencies between the same two projects.
*/
private static class DependencyGroup {
private Set<Dependency> group = new LinkedHashSet<Dependency>();
private Set<Dependency> group = new LinkedHashSet<>();
DependencyGroup(Dependency first) {
this.upstream = first.getUpstreamProject();
@@ -137,7 +137,7 @@ public abstract class Descriptor<T extends Describable<T>> implements Saveable,
*/
public transient final Class<? extends T> clazz;
private transient final Map<String,CheckMethod> checkMethods = new ConcurrentHashMap<String,CheckMethod>(2);
private transient final Map<String,CheckMethod> 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<T extends Describable<T>> implements Saveable,
*
* @see #getHelpFile(String)
*/
private transient final Map<String,HelpRedirect> helpRedirect = new HashMap<String,HelpRedirect>(2);
private transient final Map<String,HelpRedirect> helpRedirect = new HashMap<>(2);
private static class HelpRedirect {
private final Class<? extends Describable> owner;
@@ -416,7 +416,7 @@ public abstract class Descriptor<T extends Describable<T>> 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<String> depends = buildFillDependencies(method, new ArrayList<String>());
List<String> depends = buildFillDependencies(method, new ArrayList<>());
if (!depends.isEmpty())
attributes.put("fillDependsOn",Util.join(depends," "));
@@ -506,7 +506,7 @@ public abstract class Descriptor<T extends Describable<T>> implements Saveable,
* Given the class, list up its {@link PropertyType}s from its public fields/getters.
*/
private Map<String, PropertyType> buildPropertyTypes(Class<?> clazz) {
Map<String, PropertyType> r = new HashMap<String, PropertyType>();
Map<String, PropertyType> r = new HashMap<>();
for (Field f : clazz.getFields())
r.put(f.getName(),new PropertyType(f));
@@ -855,7 +855,7 @@ public abstract class Descriptor<T extends Describable<T>> implements Saveable,
}
protected List<String> getPossibleViewNames(String baseName) {
List<String> names = new ArrayList<String>();
List<String> 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<T extends Describable<T>> implements Saveable,
}
public static <T> List<T> toList( T... values ) {
return new ArrayList<T>(Arrays.asList(values));
return new ArrayList<>(Arrays.asList(values));
}
public static <T extends Describable<T>>
Map<Descriptor<T>,T> toMap(Iterable<T> describables) {
Map<Descriptor<T>,T> m = new LinkedHashMap<Descriptor<T>,T>();
Map<Descriptor<T>,T> m = new LinkedHashMap<>();
for (T d : describables) {
Descriptor<T> descriptor;
try {
@@ -1025,7 +1025,7 @@ public abstract class Descriptor<T extends Describable<T>> implements Saveable,
List<T> newInstancesFromHeteroList(StaplerRequest req, Object formData,
Collection<? extends Descriptor<T>> descriptors) throws FormException {
List<T> items = new ArrayList<T>();
List<T> items = new ArrayList<>();
if (formData!=null) {
for (Object o : JSONArray.fromObject(formData)) {
@@ -65,7 +65,7 @@ public abstract class DescriptorVisibilityFilter implements ExtensionPoint {
public static <T extends Descriptor> List<T> apply(Object context, Iterable<T> source) {
ExtensionList<DescriptorVisibilityFilter> filters = all();
List<T> r = new ArrayList<T>();
List<T> 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 <T extends Descriptor> List<T> applyType(Class<?> contextClass, Iterable<T> source) {
ExtensionList<DescriptorVisibilityFilter> filters = all();
List<T> r = new ArrayList<T>();
List<T> r = new ArrayList<>();
OUTER:
for (T d : source) {
@@ -309,7 +309,7 @@ public class DownloadService extends PageDecorator {
* URLs to download from.
*/
public List<String> getUrls() {
List<String> updateSites = new ArrayList<String>();
List<String> updateSites = new ArrayList<>();
for (UpdateSite site : Jenkins.getActiveInstance().getUpdateCenter().getSiteList()) {
String siteUrl = site.getUrl();
int baseUrlEnd = siteUrl.indexOf("update-center.json");
@@ -139,7 +139,7 @@ public class Executor extends Thread implements ModelObject {
* Cause of interruption. Access needs to be synchronized.
*/
@GuardedBy("lock")
private final List<CauseOfInterruption> causes = new Vector<CauseOfInterruption>();
private final List<CauseOfInterruption> 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<CauseOfInterruption>(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<Executor> IMPERSONATION = new ThreadLocal<Executor>();
private static final ThreadLocal<Executor> IMPERSONATION = new ThreadLocal<>();
private static final Logger LOGGER = Logger.getLogger(Executor.class.getName());
}
@@ -349,7 +349,7 @@ public class Fingerprint implements ModelObject, Saveable {
private final List<Range> ranges;
public RangeSet() {
this(new ArrayList<Range>());
this(new ArrayList<>());
}
private RangeSet(List<Range> data) {
@@ -417,7 +417,7 @@ public class Fingerprint implements ModelObject, Saveable {
*/
@Exported
public synchronized List<Range> getRanges() {
return new ArrayList<Range>(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<Range> intersection = new ArrayList<Range>();
List<Range> intersection = new ArrayList<>();
int lhs=0,rhs=0;
while(lhs<this.ranges.size() && rhs<that.ranges.size()) {
@@ -561,7 +561,7 @@ public class Fingerprint implements ModelObject, Saveable {
*/
public synchronized boolean removeAll(RangeSet that) {
boolean modified = false;
List<Range> sub = new ArrayList<Range>();
List<Range> sub = new ArrayList<>();
int lhs=0,rhs=0;
while(lhs<this.ranges.size() && rhs<that.ranges.size()) {
@@ -866,9 +866,9 @@ public class Fingerprint implements ModelObject, Saveable {
/**
* Range of builds that use this file keyed by a job full name.
*/
private Hashtable<String,RangeSet> usages = new Hashtable<String,RangeSet>();
private Hashtable<String,RangeSet> usages = new Hashtable<>();
PersistedList<FingerprintFacet> facets = new PersistedList<FingerprintFacet>(this);
PersistedList<FingerprintFacet> 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<String> getJobs() {
List<String> r = new ArrayList<String>();
List<String> 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<RangeItem> _getUsages() {
List<RangeItem> r = new ArrayList<RangeItem>();
List<RangeItem> r = new ArrayList<>();
final Jenkins instance = Jenkins.getInstance();
for (Entry<String, RangeSet> 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<String,RangeSet>();
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<String,RangeSet> e : new Hashtable<String,RangeSet>(usages).entrySet()) {// copy because we mutate
for (Entry<String,RangeSet> 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<FingerprintFacet> getFacets() {
if (transientFacets==null) {
List<FingerprintFacet> transientFacets = new ArrayList<FingerprintFacet>();
List<FingerprintFacet> 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<FingerprintFacet> getSortedFacets() {
List<FingerprintFacet> r = new ArrayList<FingerprintFacet>(getFacets());
Collections.sort(r,new Comparator<FingerprintFacet>() {
List<FingerprintFacet> r = new ArrayList<>(getFacets());
r.sort(new Comparator<FingerprintFacet>() {
public int compare(FingerprintFacet o1, FingerprintFacet o2) {
long a = o1.getTimestamp();
long b = o2.getTimestamp();
if (a<b) return -1;
if (a==b) return 0;
if (a < b) return -1;
if (a == b) return 0;
return 1;
}
});
@@ -1230,7 +1230,7 @@ public class Fingerprint implements ModelObject, Saveable {
* Returns the actions contributed from {@link #getFacets()}
*/
public @Nonnull List<Action> getActions() {
List<Action> r = new ArrayList<Action>();
List<Action> 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<FingerprintFacet>(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<String,RangeSet>(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 + "]";
}
/**
@@ -62,7 +62,7 @@ public class HealthReport implements Serializable, Comparable<HealthReport> {
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<String, String> iconIMGToClassMap = new HashMap<String, String>();
private static final Map<String, String> iconIMGToClassMap = new HashMap<>();
static {
iconIMGToClassMap.put(HEALTH_OVER_80_IMG, HEALTH_OVER_80);
iconIMGToClassMap.put(HEALTH_61_TO_80_IMG, HEALTH_61_TO_80);
@@ -107,7 +107,7 @@ public abstract class ItemGroupMixIn {
return child.isDirectory();
}
});
CopyOnWriteMap.Tree<K,V> configurations = new CopyOnWriteMap.Tree<K,V>();
CopyOnWriteMap.Tree<K,V> 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 {
+8 -8
View File
@@ -69,7 +69,7 @@ public class Items {
* Use {@link #all()} for read access and {@link Extension} for registration.
*/
@Deprecated
public static final List<TopLevelItemDescriptor> LIST = (List)new DescriptorList<TopLevelItem>(TopLevelItem.class);
public static final List<TopLevelItemDescriptor> 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<TopLevelItemDescriptor> all(Authentication a, ItemGroup c) {
List<TopLevelItemDescriptor> result = new ArrayList<TopLevelItemDescriptor>();
List<TopLevelItemDescriptor> result = new ArrayList<>();
ACL acl;
if (c instanceof AccessControlled) {
acl = ((AccessControlled) c).getACL();
@@ -224,7 +224,7 @@ public class Items {
public static <T extends Item> List<T> fromNameList(ItemGroup context, @Nonnull String list, @Nonnull Class<T> type) {
final Jenkins jenkins = Jenkins.getInstance();
List<T> r = new ArrayList<T>();
List<T> 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<String> name = new Stack<String>();
Stack<String> name = new Stack<>();
for (int i=0; i<c.length;i++) {
if (i==0 && c[i].equals("")) continue;
name.push(c[i]);
@@ -294,7 +294,7 @@ public class Items {
public static String computeRelativeNamesAfterRenaming(String oldFullName, String newFullName, String relativeNames, ItemGroup context) {
StringTokenizer tokens = new StringTokenizer(relativeNames,",");
List<String> newValue = new ArrayList<String>();
List<String> 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 <T extends Item> List<T> getAllItems(final ItemGroup root, Class<T> type) {
List<T> r = new ArrayList<T>();
List<T> r = new ArrayList<>();
getAllItems(root, type, r);
return r;
}
private static <T extends Item> void getAllItems(final ItemGroup root, Class<T> type, List<T> r) {
List<Item> items = new ArrayList<Item>(((ItemGroup<?>) root).getItems());
List<Item> 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)) {
+1 -3
View File
@@ -163,9 +163,7 @@ public final class JDK extends ToolInstallation implements NodeSpecific<JDK>, 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;
}
}
+13 -13
View File
@@ -175,7 +175,7 @@ public abstract class Job<JobT extends Job<JobT, RunT>, RunT extends Run<JobT, R
* List of properties configured for this project.
*/
// this should have been DescribableList but now it's too late
protected CopyOnWriteList<JobProperty<? super JobT>> properties = new CopyOnWriteList<JobProperty<? super JobT>>();
protected CopyOnWriteList<JobProperty<? super JobT>> properties = new CopyOnWriteList<>();
@Restricted(NoExternalUse.class)
public transient RunIdMigrator runIdMigrator;
@@ -232,7 +232,7 @@ public abstract class Job<JobT extends Job<JobT, RunT>, RunT extends Run<JobT, R
}
if (properties == null) // didn't exist < 1.72
properties = new CopyOnWriteList<JobProperty<? super JobT>>();
properties = new CopyOnWriteList<>();
for (JobProperty p : properties)
p.setOwner(this);
@@ -595,14 +595,14 @@ public abstract class Job<JobT extends Job<JobT, RunT>, RunT extends Run<JobT, R
* @see JobProperty#getJobOverrides
*/
public Collection<?> getOverrides() {
List<Object> r = new ArrayList<Object>();
List<Object> r = new ArrayList<>();
for (JobProperty<? super JobT> p : properties)
r.addAll(p.getJobOverrides());
return r;
}
public List<Widget> getWidgets() {
ArrayList<Widget> r = new ArrayList<Widget>();
ArrayList<Widget> r = new ArrayList<>();
r.add(createHistoryWidget());
return r;
}
@@ -741,7 +741,7 @@ public abstract class Job<JobT extends Job<JobT, RunT>, RunT extends Run<JobT, R
* Obtains all the {@link Run}s whose build numbers matches the given {@link RangeSet}.
*/
public synchronized List<RunT> getBuilds(RangeSet rs) {
List<RunT> builds = new LinkedList<RunT>();
List<RunT> builds = new LinkedList<>();
for (Range r : rs.getRanges()) {
for (RunT b = getNearestBuild(r.start); b!=null && b.getNumber()<r.end; b=b.getNextBuild()) {
@@ -997,7 +997,7 @@ public abstract class Job<JobT extends Job<JobT, RunT>, RunT extends Run<JobT, R
*/
public List<RunT> getLastBuildsOverThreshold(int numberOfBuilds, Result threshold) {
List<RunT> result = new ArrayList<RunT>(numberOfBuilds);
List<RunT> result = new ArrayList<>(numberOfBuilds);
RunT r = getLastBuild();
while (r != null && result.size() < numberOfBuilds) {
@@ -1021,7 +1021,7 @@ public abstract class Job<JobT extends Job<JobT, RunT>, RunT extends Run<JobT, R
*/
@SuppressWarnings("unchecked")
protected List<RunT> getEstimatedDurationCandidates() {
List<RunT> candidates = new ArrayList<RunT>(3);
List<RunT> candidates = new ArrayList<>(3);
RunT lastSuccessful = getLastSuccessfulBuild();
int lastSuccessfulNumber = -1;
if (lastSuccessful != null) {
@@ -1031,7 +1031,7 @@ public abstract class Job<JobT extends Job<JobT, RunT>, RunT extends Run<JobT, R
int i = 0;
RunT r = getLastBuild();
List<RunT> fallbackCandidates = new ArrayList<RunT>(3);
List<RunT> 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<JobT extends Job<JobT, RunT>, RunT extends Run<JobT, R
}
}
List<FeedItem> entries = new ArrayList<FeedItem>();
List<FeedItem> entries = new ArrayList<>();
String scmDisplayName = "";
if (this instanceof SCMTriggerItem) {
SCMTriggerItem scmItem = (SCMTriggerItem) this;
@@ -1199,7 +1199,7 @@ public abstract class Job<JobT extends Job<JobT, RunT>, RunT extends Run<JobT, R
@Exported(name = "healthReport")
public List<HealthReport> getBuildHealthReports() {
List<HealthReport> reports = new ArrayList<HealthReport>();
List<HealthReport> reports = new ArrayList<>();
RunT lastBuild = getLastBuild();
if (lastBuild != null && lastBuild.isBuilding()) {
@@ -1241,7 +1241,7 @@ public abstract class Job<JobT extends Job<JobT, RunT>, RunT extends Run<JobT, R
// store the cache
cachedBuildHealthReportsBuildNumber = lastBuild.getNumber();
cachedBuildHealthReports = new ArrayList<HealthReport>(reports);
cachedBuildHealthReports = new ArrayList<>(reports);
}
return reports;
@@ -1332,7 +1332,7 @@ public abstract class Job<JobT extends Job<JobT, RunT>, RunT extends Run<JobT, R
logRotator = null;
DescribableList<JobProperty<?>, JobPropertyDescriptor> t = new DescribableList<JobProperty<?>, JobPropertyDescriptor>(NOOP,getAllProperties());
DescribableList<JobProperty<?>, 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<JobT extends Job<JobT, RunT>, RunT extends Run<JobT, R
}
DataSetBuilder<String, ChartLabel> data = new DataSetBuilder<String, ChartLabel>();
DataSetBuilder<String, ChartLabel> data = new DataSetBuilder<>();
for (Run r : getNewBuilds()) {
if (r.isBuilding())
continue;
@@ -99,7 +99,7 @@ public abstract class JobPropertyDescriptor extends Descriptor<JobProperty<?>> {
* Gets the {@link JobPropertyDescriptor}s applicable for a given job type.
*/
public static List<JobPropertyDescriptor> getPropertyDescriptors(Class<? extends Job> clazz) {
List<JobPropertyDescriptor> r = new ArrayList<JobPropertyDescriptor>();
List<JobPropertyDescriptor> r = new ArrayList<>();
for (JobPropertyDescriptor p : all())
if(p.isApplicable(clazz))
r.add(p);
+5 -5
View File
@@ -241,7 +241,7 @@ public abstract class Label extends Actionable implements Comparable<Label>, Mod
@Exported
public Set<Cloud> getClouds() {
if(clouds==null) {
Set<Cloud> r = new HashSet<Cloud>();
Set<Cloud> r = new HashSet<>();
Jenkins h = Jenkins.getInstance();
for (Cloud c : h.clouds) {
if(c.canProvision(this))
@@ -381,12 +381,12 @@ public abstract class Label extends Actionable implements Comparable<Label>, Mod
*/
@Exported
public List<AbstractProject> getTiedJobs() {
List<AbstractProject> r = new ArrayList<AbstractProject>();
List<AbstractProject> r = new ArrayList<>();
for (AbstractProject<?,?> p : Jenkins.getInstance().allItems(AbstractProject.class)) {
if(p instanceof TopLevelItem && this.equals(p.getAssignedLabel()))
r.add(p);
}
Collections.sort(r, Items.BY_FULL_NAME);
r.sort(Items.BY_FULL_NAME);
return r;
}
@@ -417,7 +417,7 @@ public abstract class Label extends Actionable implements Comparable<Label>, Mod
}
}
if (topLevelItem instanceof ItemGroup) {
Stack<ItemGroup> q = new Stack<ItemGroup>();
Stack<ItemGroup> q = new Stack<>();
q.push((ItemGroup) topLevelItem);
while (!q.isEmpty()) {
@@ -480,7 +480,7 @@ public abstract class Label extends Actionable implements Comparable<Label>, Mod
* @since 1.420
*/
public Set<LabelAtom> listAtoms() {
Set<LabelAtom> r = new HashSet<LabelAtom>();
Set<LabelAtom> r = new HashSet<>();
accept(ATOM_COLLECTOR,r);
return r;
}
+13 -13
View File
@@ -77,7 +77,7 @@ public class ListView extends View implements DirectlyModifiableView {
* List of job names. This is what gets serialized.
*/
@GuardedBy("this")
/*package*/ /*almost-final*/ SortedSet<String> jobNames = new TreeSet<String>(CaseInsensitiveComparator.INSTANCE);
/*package*/ /*almost-final*/ SortedSet<String> jobNames = new TreeSet<>(CaseInsensitiveComparator.INSTANCE);
private DescribableList<ViewJobFilter, Descriptor<ViewJobFilter>> jobFilters;
@@ -135,7 +135,7 @@ public class ListView extends View implements DirectlyModifiableView {
}
synchronized(this) {
if (jobNames == null) {
jobNames = new TreeSet<String>(CaseInsensitiveComparator.INSTANCE);
jobNames = new TreeSet<>(CaseInsensitiveComparator.INSTANCE);
}
}
initColumns();
@@ -145,14 +145,14 @@ public class ListView extends View implements DirectlyModifiableView {
protected void initColumns() {
if (columns == null)
columns = new DescribableList<ListViewColumn, Descriptor<ListViewColumn>>(this,
columns = new DescribableList<>(this,
ListViewColumn.createDefaultInitialColumnList(getClass())
);
}
protected void initJobFilters() {
if (jobFilters == null)
jobFilters = new DescribableList<ViewJobFilter, Descriptor<ViewJobFilter>>(this);
jobFilters = new DescribableList<>(this);
}
/**
@@ -196,14 +196,14 @@ public class ListView extends View implements DirectlyModifiableView {
*/
private List<TopLevelItem> getItems(boolean recurse) {
SortedSet<String> names;
List<TopLevelItem> items = new ArrayList<TopLevelItem>();
List<TopLevelItem> items = new ArrayList<>();
synchronized (this) {
names = new TreeSet<String>(jobNames);
names = new TreeSet<>(jobNames);
}
ItemGroup<? extends TopLevelItem> parent = getOwner().getItemGroup();
List<TopLevelItem> parentItems = new ArrayList<TopLevelItem>(parent.getItems());
List<TopLevelItem> parentItems = new ArrayList<>(parent.getItems());
includeItems(parent, parentItems, names);
Boolean statusFilter = this.statusFilter; // capture the value to isolate us from concurrent update
@@ -223,13 +223,13 @@ public class ListView extends View implements DirectlyModifiableView {
// check the filters
Iterable<ViewJobFilter> jobFilters = getJobFilters();
List<TopLevelItem> allItems = new ArrayList<TopLevelItem>(parentItems);
if (recurse) allItems = expand(allItems, new ArrayList<TopLevelItem>());
List<TopLevelItem> allItems = new ArrayList<>(parentItems);
if (recurse) allItems = expand(allItems, new ArrayList<>());
for (ViewJobFilter jobFilter: jobFilters) {
items = jobFilter.filter(items, allItems, this);
}
// for sanity, trim off duplicates
items = new ArrayList<TopLevelItem>(new LinkedHashSet<TopLevelItem>(items));
items = new ArrayList<>(new LinkedHashSet<>(items));
return items;
}
@@ -459,12 +459,12 @@ public class ListView extends View implements DirectlyModifiableView {
setIncludeRegex(req.getParameter("useincluderegex") != null ? req.getParameter("includeRegex") : null);
if (columns == null) {
columns = new DescribableList<ListViewColumn,Descriptor<ListViewColumn>>(this);
columns = new DescribableList<>(this);
}
columns.rebuildHetero(req, json, ListViewColumn.all(), "columns");
if (jobFilters == null) {
jobFilters = new DescribableList<ViewJobFilter,Descriptor<ViewJobFilter>>(this);
jobFilters = new DescribableList<>(this);
}
jobFilters.rebuildHetero(req, json, ViewJobFilter.all(), "jobFilters");
@@ -545,7 +545,7 @@ public class ListView extends View implements DirectlyModifiableView {
private void renameViewItem(String oldFullName, String newFullName, ViewGroup vg, ListView lv) {
boolean needsSave;
synchronized (lv) {
Set<String> oldJobNames = new HashSet<String>(lv.jobNames);
Set<String> oldJobNames = new HashSet<>(lv.jobNames);
lv.jobNames.clear();
for (String oldName : oldJobNames) {
lv.jobNames.add(Items.computeRelativeNamesAfterRenaming(oldFullName, newFullName, oldName, vg.getItemGroup()));
@@ -79,9 +79,9 @@ public abstract class LoadBalancer implements ExtensionPoint {
@Override
public Mapping map(Task task, MappingWorksheet ws) {
// build consistent hash for each work chunk
List<ConsistentHash<ExecutorChunk>> hashes = new ArrayList<ConsistentHash<ExecutorChunk>>(ws.works.size());
List<ConsistentHash<ExecutorChunk>> hashes = new ArrayList<>(ws.works.size());
for (int i=0; i<ws.works.size(); i++) {
ConsistentHash<ExecutorChunk> hash = new ConsistentHash<ExecutorChunk>(new Hash<ExecutorChunk>() {
ConsistentHash<ExecutorChunk> hash = new ConsistentHash<>(new Hash<ExecutorChunk>() {
public String hash(ExecutorChunk node) {
return node.getName();
}
@@ -201,7 +201,7 @@ public class MultiStageTimeSeries implements Serializable {
public TrendChart(TimeScale timeScale, MultiStageTimeSeries... series) {
this.timeScale = timeScale;
this.series = new ArrayList<MultiStageTimeSeries>(Arrays.asList(series));
this.series = new ArrayList<>(Arrays.asList(series));
this.dataset = createDataset();
}
+1 -1
View File
@@ -75,7 +75,7 @@ public class MyView extends View {
@Override
public Collection<TopLevelItem> getItems() {
List<TopLevelItem> items = new ArrayList<TopLevelItem>();
List<TopLevelItem> items = new ArrayList<>();
for (TopLevelItem item : getOwner().getItemGroup().getItems()) {
if (item.hasPermission(Item.CONFIGURE)) {
items.add(item);
@@ -73,7 +73,7 @@ public class MyViewsProperty extends UserProperty implements ModifiableViewGroup
/**
* Always hold at least one view.
*/
private CopyOnWriteArrayList<View> views = new CopyOnWriteArrayList<View>();
private CopyOnWriteArrayList<View> views = new CopyOnWriteArrayList<>();
private transient ViewGroupMixIn viewGroupMixIn;
@@ -91,7 +91,7 @@ public class MyViewsProperty extends UserProperty implements ModifiableViewGroup
public Object readResolve() {
if (views == null)
// this shouldn't happen, but an error in 1.319 meant the last view could be deleted
views = new CopyOnWriteArrayList<View>();
views = new CopyOnWriteArrayList<>();
if (views.isEmpty()) {
// preserve the non-empty invariant
@@ -108,7 +108,7 @@ public abstract class PageDecorator extends Descriptor<PageDecorator> implements
* Use {@link #all()} for read access, and use {@link Extension} for registration.
*/
@Deprecated
public static final List<PageDecorator> ALL = (List)new DescriptorList<PageDecorator>(PageDecorator.class);
public static final List<PageDecorator> ALL = (List) new DescriptorList<>(PageDecorator.class);
/**
* Returns all the registered {@link PageDecorator} descriptors.
@@ -13,7 +13,7 @@ import org.kohsuke.stapler.Stapler;
public class PaneStatusProperties extends UserProperty implements Saveable {
private final PersistedList<String> collapsed = new PersistedList<String>(this);
private final PersistedList<String> collapsed = new PersistedList<>(this);
private static final PaneStatusProperties FALLBACK = new PaneStatusPropertiesSessionFallback();
@@ -232,7 +232,7 @@ public abstract class ParameterDefinition implements
* Use {@link #all()} for read access, and {@link Extension} for registration.
*/
@Deprecated
public static final DescriptorList<ParameterDefinition> LIST = new DescriptorList<ParameterDefinition>(ParameterDefinition.class);
public static final DescriptorList<ParameterDefinition> LIST = new DescriptorList<>(ParameterDefinition.class);
public abstract static class ParameterDescriptor extends
Descriptor<ParameterDefinition> {
@@ -222,11 +222,11 @@ public class ParametersAction implements RunAction2, Iterable<ParameterValue>, Q
return !parameters.isEmpty();
} else {
// I don't think we need multiple ParametersActions, but let's be defensive
Set<ParameterValue> params = new HashSet<ParameterValue>();
Set<ParameterValue> params = new HashSet<>();
for (ParametersAction other: others) {
params.addAll(other.parameters);
}
return !params.equals(new HashSet<ParameterValue>(this.parameters));
return !params.equals(new HashSet<>(this.parameters));
}
}
@@ -324,7 +324,7 @@ public class ParametersAction implements RunAction2, Iterable<ParameterValue>, Q
return parameters;
}
List<ParameterValue> filteredParameters = new ArrayList<ParameterValue>();
List<ParameterValue> filteredParameters = new ArrayList<>();
for (ParameterValue v : this.parameters) {
if (this.parameterDefinitionNames.contains(v.getName()) || isSafeParameter(v.getName())) {
@@ -138,7 +138,7 @@ public class ParametersDefinitionProperty extends OptionalJobProperty<Job<?, ?>>
delay=new TimeDuration(TimeUnit.MILLISECONDS.convert(getJob().getQuietPeriod(), TimeUnit.SECONDS));
List<ParameterValue> values = new ArrayList<ParameterValue>();
List<ParameterValue> values = new ArrayList<>();
JSONObject formData = req.getSubmittedForm();
JSONArray a = JSONArray.fromObject(formData.get("parameter"));
@@ -177,7 +177,7 @@ public class ParametersDefinitionProperty extends OptionalJobProperty<Job<?, ?>>
}
public void buildWithParameters(StaplerRequest req, StaplerResponse rsp, @CheckForNull TimeDuration delay) throws IOException, ServletException {
List<ParameterValue> values = new ArrayList<ParameterValue>();
List<ParameterValue> values = new ArrayList<>();
for (ParameterDefinition d: parameterDefinitions) {
ParameterValue value = d.createValue(req);
if (value != null) {
@@ -96,16 +96,11 @@ public class PasswordParameterDefinition extends SimpleParameterDefinition {
this.defaultValue = Secret.fromString(defaultValue);
}
@Extension @Symbol({"password","nonStoredPasswordParam"})
@Extension @Symbol({"password"})
public final static class ParameterDescriptorImpl extends ParameterDescriptor {
@Override
public String getDisplayName() {
return Messages.PasswordParameterDefinition_DisplayName();
}
@Override
public String getHelpFile() {
return "/help/parameter/string.html";
}
}
}
@@ -129,9 +129,7 @@ public abstract class PeriodicWork extends SafeTimerTask implements ExtensionPoi
private final Set<PeriodicWork> registered = new HashSet<>();
PeriodicWorkExtensionListListener(ExtensionList<PeriodicWork> initiallyRegistered) {
for (PeriodicWork p : initiallyRegistered) {
registered.add(p);
}
registered.addAll(initiallyRegistered);
}
@Override
@@ -91,7 +91,7 @@ public interface PermalinkProjectAction extends Action {
/**
* List of {@link Permalink}s that are built into Jenkins.
*/
public static final List<Permalink> BUILTIN = new CopyOnWriteArrayList<Permalink>();
public static final List<Permalink> BUILTIN = new CopyOnWriteArrayList<>();
public static final Permalink LAST_BUILD = new Permalink() {
public String getDisplayName() {
+1 -1
View File
@@ -157,7 +157,7 @@ public abstract class Project<P extends Project<P,B>,B extends Build<P,B>>
@Override
protected Set<ResourceActivity> getResourceActivities() {
final Set<ResourceActivity> activities = new HashSet<ResourceActivity>();
final Set<ResourceActivity> activities = new HashSet<>();
activities.addAll(super.getResourceActivities());
activities.addAll(Util.filter(getBuildersList(),ResourceActivity.class));
+30 -32
View File
@@ -96,6 +96,7 @@ import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.Callable;
@@ -184,7 +185,7 @@ public class Queue extends ResourceController implements Saveable {
* This consists of {@link Item}s that cannot be run yet
* because its time has not yet come.
*/
private final Set<WaitingItem> waitingList = new TreeSet<WaitingItem>();
private final Set<WaitingItem> waitingList = new TreeSet<>();
/**
* {@link Task}s that can be built immediately
@@ -193,20 +194,20 @@ public class Queue extends ResourceController implements Saveable {
* blocked via {@link QueueTaskDispatcher#canRun(Item)},
* or otherwise blocked by {@link Task#isBuildBlocked()}.
*/
private final ItemList<BlockedItem> blockedProjects = new ItemList<BlockedItem>();
private final ItemList<BlockedItem> blockedProjects = new ItemList<>();
/**
* {@link Task}s that can be built immediately
* that are waiting for available {@link Executor}.
* This list is sorted in such a way that earlier items are built earlier.
*/
private final ItemList<BuildableItem> buildables = new ItemList<BuildableItem>();
private final ItemList<BuildableItem> buildables = new ItemList<>();
/**
* {@link Task}s that are being handed over to the executor, but execution
* has not started yet.
*/
private final ItemList<BuildableItem> pendings = new ItemList<BuildableItem>();
private final ItemList<BuildableItem> pendings = new ItemList<>();
private transient volatile Snapshot snapshot = new Snapshot(waitingList, blockedProjects, buildables, pendings);
@@ -319,7 +320,7 @@ public class Queue extends ResourceController implements Saveable {
private volatile transient QueueSorter sorter;
private transient final AtmostOneTaskExecutor<Void> maintainerThread = new AtmostOneTaskExecutor<Void>(new Callable<Void>() {
private transient final AtmostOneTaskExecutor<Void> maintainerThread = new AtmostOneTaskExecutor<>(new Callable<Void>() {
@Override
public Void call() throws Exception {
maintain();
@@ -365,7 +366,7 @@ public class Queue extends ResourceController implements Saveable {
*/
static class State {
public long counter;
public List<Item> items = new ArrayList<Item>();
public List<Item> items = new ArrayList<>();
}
/**
@@ -495,7 +496,7 @@ public class Queue extends ResourceController implements Saveable {
Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);
lock.lock();
try { try {
for (WaitingItem i : new ArrayList<WaitingItem>(
for (WaitingItem i : new ArrayList<>(
waitingList)) // copy the list as we'll modify it in the loop
i.cancel(this);
blockedProjects.cancelAll();
@@ -579,11 +580,8 @@ public class Queue extends ResourceController implements Saveable {
*/
public @Nonnull ScheduleResult schedule2(Task p, int quietPeriod, List<Action> actions) {
// remove nulls
actions = new ArrayList<Action>(actions);
for (Iterator<Action> itr = actions.iterator(); itr.hasNext();) {
Action a = itr.next();
if (a==null) itr.remove();
}
actions = new ArrayList<>(actions);
actions.removeIf(Objects::isNull);
lock.lock();
try { try {
@@ -617,14 +615,14 @@ public class Queue extends ResourceController implements Saveable {
due.add(Calendar.SECOND, quietPeriod);
// Do we already have this task in the queue? Because if so, we won't schedule a new one.
List<Item> duplicatesInQueue = new ArrayList<Item>();
List<Item> duplicatesInQueue = new ArrayList<>();
for (Item item : liveGetItems(p)) {
boolean shouldScheduleItem = false;
for (QueueAction action : item.getActions(QueueAction.class)) {
shouldScheduleItem |= action.shouldSchedule(actions);
}
for (QueueAction action : Util.filter(actions, QueueAction.class)) {
shouldScheduleItem |= action.shouldSchedule((new ArrayList<Action>(item.getAllActions())));
shouldScheduleItem |= action.shouldSchedule((new ArrayList<>(item.getAllActions())));
}
if (!shouldScheduleItem) {
duplicatesInQueue.add(item);
@@ -787,7 +785,7 @@ public class Queue extends ResourceController implements Saveable {
@Exported(inline=true)
public Item[] getItems() {
Snapshot s = this.snapshot;
List<Item> r = new ArrayList<Item>();
List<Item> r = new ArrayList<>();
for(WaitingItem p : s.waitingList) {
r = checkPermissionsAndAddToList(r, p);
@@ -826,7 +824,7 @@ public class Queue extends ResourceController implements Saveable {
@Exported(inline=true)
public StubItem[] getDiscoverableItems() {
Snapshot s = this.snapshot;
List<StubItem> r = new ArrayList<StubItem>();
List<StubItem> r = new ArrayList<>();
for(WaitingItem p : s.waitingList) {
r = filterDiscoverableItemListBasedOnPermissions(r, p);
@@ -904,7 +902,7 @@ public class Queue extends ResourceController implements Saveable {
*/
public List<BuildableItem> getBuildableItems(Computer c) {
Snapshot snapshot = this.snapshot;
List<BuildableItem> result = new ArrayList<BuildableItem>();
List<BuildableItem> result = new ArrayList<>();
_getBuildableItems(c, snapshot.buildables, result);
_getBuildableItems(c, snapshot.pendings, result);
return result;
@@ -925,7 +923,7 @@ public class Queue extends ResourceController implements Saveable {
*/
public List<BuildableItem> getBuildableItems() {
Snapshot snapshot = this.snapshot;
ArrayList<BuildableItem> r = new ArrayList<BuildableItem>(snapshot.buildables);
ArrayList<BuildableItem> r = new ArrayList<>(snapshot.buildables);
r.addAll(snapshot.pendings);
return r;
}
@@ -934,14 +932,14 @@ public class Queue extends ResourceController implements Saveable {
* Gets the snapshot of all {@link BuildableItem}s.
*/
public List<BuildableItem> getPendingItems() {
return new ArrayList<BuildableItem>(snapshot.pendings);
return new ArrayList<>(snapshot.pendings);
}
/**
* Gets the snapshot of all {@link BlockedItem}s.
*/
protected List<BlockedItem> getBlockedItems() {
return new ArrayList<BlockedItem>(snapshot.blockedProjects);
return new ArrayList<>(snapshot.blockedProjects);
}
/**
@@ -969,7 +967,7 @@ public class Queue extends ResourceController implements Saveable {
*/
public List<Item> getUnblockedItems() {
Snapshot snapshot = this.snapshot;
List<Item> queuedNotBlocked = new ArrayList<Item>();
List<Item> queuedNotBlocked = new ArrayList<>();
queuedNotBlocked.addAll(snapshot.waitingList);
queuedNotBlocked.addAll(snapshot.buildables);
queuedNotBlocked.addAll(snapshot.pendings);
@@ -984,7 +982,7 @@ public class Queue extends ResourceController implements Saveable {
*/
public Set<Task> getUnblockedTasks() {
List<Item> items = getUnblockedItems();
Set<Task> unblockedTasks = new HashSet<Task>(items.size());
Set<Task> unblockedTasks = new HashSet<>(items.size());
for (Queue.Item t : items)
unblockedTasks.add(t.task);
return unblockedTasks;
@@ -1089,7 +1087,7 @@ public class Queue extends ResourceController implements Saveable {
private List<Item> liveGetItems(Task t) {
lock.lock();
try {
List<Item> result = new ArrayList<Item>();
List<Item> result = new ArrayList<>();
result.addAll(blockedProjects.getAll(t));
result.addAll(buildables.getAll(t));
// Do not include pendings—we have already finalized WorkUnitContext.actions.
@@ -1117,7 +1115,7 @@ public class Queue extends ResourceController implements Saveable {
*/
public List<Item> getItems(Task t) {
Snapshot snapshot = this.snapshot;
List<Item> result = new ArrayList<Item>();
List<Item> result = new ArrayList<>();
for (Item item : snapshot.blockedProjects) {
if (item.task.equals(t)) {
result.add(item);
@@ -1356,7 +1354,7 @@ public class Queue extends ResourceController implements Saveable {
final Jenkins jenkins = Jenkins.getInstanceOrNull();
// TODO confirm safe to assume non-null and use getInstance()
final Queue queue = jenkins == null ? null : jenkins.getQueue();
return queue == null ? callable : new LockedJUCCallable<V>(callable);
return queue == null ? callable : new LockedJUCCallable<>(callable);
}
@Override
@@ -1466,10 +1464,10 @@ public class Queue extends ResourceController implements Saveable {
LOGGER.log(Level.FINE, "Queue maintenance started on {0} with {1}", new Object[] {this, snapshot});
// The executors that are currently waiting for a job to run.
Map<Executor, JobOffer> parked = new HashMap<Executor, JobOffer>();
Map<Executor, JobOffer> parked = new HashMap<>();
{// update parked (and identify any pending items whose executor has disappeared)
List<BuildableItem> lostPendings = new ArrayList<BuildableItem>(pendings);
List<BuildableItem> lostPendings = new ArrayList<>(pendings);
for (Computer c : jenkins.getComputers()) {
for (Executor e : c.getAllExecutors()) {
if (e.isInterrupted()) {
@@ -1514,7 +1512,7 @@ public class Queue extends ResourceController implements Saveable {
if (s != null) {
s.sortBlockedItems(blockedItems);
} else {
Collections.sort(blockedItems, QueueSorter.DEFAULT_BLOCKED_ITEM_COMPARATOR);
blockedItems.sort(QueueSorter.DEFAULT_BLOCKED_ITEM_COMPARATOR);
}
for (BlockedItem p : blockedItems) {
String taskDisplayName = LOGGER.isLoggable(Level.FINEST) ? p.task.getFullDisplayName() : null;
@@ -1584,7 +1582,7 @@ public class Queue extends ResourceController implements Saveable {
updateSnapshot();
// allocate buildable jobs to executors
for (BuildableItem p : new ArrayList<BuildableItem>(
for (BuildableItem p : new ArrayList<>(
buildables)) {// copy as we'll mutate the list in the loop
// one last check to make sure this build is not blocked.
CauseOfBlockage causeOfBlockage = getCauseOfBlockageForItem(p);
@@ -1721,7 +1719,7 @@ public class Queue extends ResourceController implements Saveable {
}
}
Map<Node, Integer> hashSource = new HashMap<Node, Integer>(h.getNodes().size());
Map<Node, Integer> hashSource = new HashMap<>(h.getNodes().size());
// Even if master is configured with zero executors, we may need to run a flyweight task like MatrixProject on it.
hashSource.put(h, Math.max(h.getNumExecutors() * 100, 1));
@@ -1730,7 +1728,7 @@ public class Queue extends ResourceController implements Saveable {
hashSource.put(n, n.getNumExecutors() * 100);
}
ConsistentHash<Node> hash = new ConsistentHash<Node>(NODE_HASH);
ConsistentHash<Node> hash = new ConsistentHash<>(NODE_HASH);
hash.addAll(hashSource);
String fullDisplayName = p.task.getFullDisplayName();
@@ -2222,7 +2220,7 @@ public class Queue extends ResourceController implements Saveable {
@SuppressWarnings("deprecation") // JENKINS-51584
protected Item(Item item) {
// do not use item.getAllActions() here as this will persist actions from a TransientActionFactory
this(item.task, new ArrayList<Action>(item.getActions()), item.id, item.future, item.inQueueSince);
this(item.task, new ArrayList<>(item.getActions()), item.id, item.future, item.inQueueSince);
}
/**
@@ -42,7 +42,7 @@ public class ResourceController {
/**
* {@link ResourceList}s that are used by activities that are in progress.
*/
private final Set<ResourceActivity> inProgress = new CopyOnWriteArraySet<ResourceActivity>();
private final Set<ResourceActivity> inProgress = new CopyOnWriteArraySet<>();
/**
* View of {@link #inProgress} that exposes its {@link ResourceList}.
@@ -52,7 +52,7 @@ public final class ResourceList {
/**
* All resources (R/W.)
*/
private final Set<Resource> all = new HashSet<Resource>();
private final Set<Resource> all = new HashSet<>();
/**
* Write accesses. Values are the # of write counts that this list uses.
@@ -60,7 +60,7 @@ public final class ResourceList {
* The values are mostly supposed to be 1, but when {@link ResourceController}
* uses a list to keep track of the union of all the activities, it can get larger.
*/
private final Map<Resource,Integer> write = new HashMap<Resource,Integer>();
private final Map<Resource,Integer> write = new HashMap<>();
private static final Integer MAX_INT = Integer.MAX_VALUE;
/**
@@ -143,7 +143,7 @@ public final class ResourceList {
@Override
public String toString() {
Map<Resource,String> m = new HashMap<Resource,String>();
Map<Resource,String> m = new HashMap<>();
for (Resource r : all)
m.put(r,"R");
for (Entry<Resource,Integer> e : write.entrySet())
+1 -1
View File
@@ -155,7 +155,7 @@ public final class Result implements Serializable, CustomExportedBean {
}
private static @Nonnull List<String> getNames() {
List<String> l = new ArrayList<String>();
List<String> l = new ArrayList<>();
for (Result r : all)
l.add(r.name);
return l;
+13 -13
View File
@@ -381,7 +381,7 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
*/
@Deprecated
public List<Action> getTransientActions() {
List<Action> actions = new ArrayList<Action>();
List<Action> actions = new ArrayList<>();
for (TransientBuildActionFactory factory: TransientBuildActionFactory.all()) {
for (Action created : factory.createFor(this)) {
if (created == null) {
@@ -821,7 +821,7 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
* @since 1.556
*/
protected @Nonnull BuildReference<RunT> createReference() {
return new BuildReference<RunT>(getId(), _this());
return new BuildReference<>(getId(), _this());
}
/**
@@ -865,7 +865,7 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
public final @CheckForNull RunT getPreviousBuildInProgress() {
if(previousBuildInProgress==this) return null; // the most common case
List<RunT> fixUp = new ArrayList<RunT>();
List<RunT> fixUp = new ArrayList<>();
RunT r = _this(); // 'r' is the source of the pointer (so that we can add it to fix up if we find that the target of the pointer is inefficient.)
RunT answer;
while (true) {
@@ -948,7 +948,7 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
* @since 1.383
*/
public @Nonnull List<RunT> getPreviousBuildsOverThreshold(int numberOfBuilds, @Nonnull Result threshold) {
List<RunT> builds = new ArrayList<RunT>(numberOfBuilds);
List<RunT> builds = new ArrayList<>(numberOfBuilds);
RunT r = getPreviousBuild();
while (r != null && builds.size() < numberOfBuilds) {
@@ -1216,7 +1216,7 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
* Map of Artifact to treeNodeId of parent node in tree view.
* Contains Artifact objects for directories and files (the ArrayList contains only files).
*/
private LinkedHashMap<Artifact,String> tree = new LinkedHashMap<Artifact,String>();
private LinkedHashMap<Artifact,String> tree = new LinkedHashMap<>();
void updateFrom(SerializableArtifactList clone) {
Map<String, Artifact> artifacts = new HashMap<>(); // need to share objects between tree and list, since computeDisplayName mutates displayPath
@@ -1256,7 +1256,7 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
int depth=0;
do {
collision = false;
Map<String,Integer/*index*/> names = new HashMap<String,Integer>();
Map<String,Integer/*index*/> names = new HashMap<>();
for (int i = 0; i < tokens.length; i++) {
String[] token = tokens[i];
String displayName = combineLast(token,len[i]);
@@ -1429,7 +1429,9 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
/**
* Returns the log file.
* @return The file may reference both uncompressed or compressed logs
*/
* @deprecated Assumes file-based storage of the log, which is not necessarily the case for Pipelines after JEP-210. Use other methods giving various kinds of streams such as {@link Run#getLogReader()}, {@link Run#getLogInputStream()}, or {@link Run#getLogText()}.
*/
@Deprecated
public @Nonnull File getLogFile() {
File rawF = new File(getRootDir(), "log");
if (rawF.isFile()) {
@@ -1658,7 +1660,7 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
* Stages of the builds that this runner has completed. This is used for concurrent {@link RunExecution}s to
* coordinate and serialize their executions where necessary.
*/
private final Set<CheckPoint> checkpoints = new HashSet<CheckPoint>();
private final Set<CheckPoint> checkpoints = new HashSet<>();
private boolean allDone;
@@ -1697,7 +1699,7 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
private final CheckpointSet checkpoints = new CheckpointSet();
private final Map<Object,Object> attributes = new HashMap<Object, Object>();
private final Map<Object,Object> attributes = new HashMap<>();
/**
* Performs the main build and returns the status code.
@@ -2098,7 +2100,7 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
private String convertBytesToString(List<Byte> bytes) {
Collections.reverse(bytes);
Byte[] byteArray = bytes.toArray(new Byte[bytes.size()]);
Byte[] byteArray = bytes.toArray(new Byte[0]);
return new String(ArrayUtils.toPrimitive(byteArray), getCharset());
}
@@ -2335,9 +2337,7 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
LOGGER.log(WARNING, "deprecated call to Run.getEnvVars\n\tat {0}", new Throwable().getStackTrace()[1]);
try {
return getEnvironment(new LogTaskListener(LOGGER, Level.INFO));
} catch (IOException e) {
return new EnvVars();
} catch (InterruptedException e) {
} catch (IOException | InterruptedException e) {
return new EnvVars();
}
}
+1 -5
View File
@@ -227,11 +227,7 @@ public final class RunMap<R extends Run<?,R>> extends AbstractLazyLoadRunMap<R>
LOGGER.log(FINEST, "Loaded " + b.getFullDisplayName() + " in " + Thread.currentThread().getName(), new ThisIsHowItsLoaded());
}
return b;
} catch (IOException e) {
LOGGER.log(Level.WARNING, "could not load " + d, e);
} catch (InstantiationError e) {
LOGGER.log(Level.WARNING, "could not load " + d, e);
} catch (Exception e) {
} catch (Exception | InstantiationError e) {
LOGGER.log(Level.WARNING, "could not load " + d, e);
}
}
@@ -38,12 +38,11 @@ import javax.annotation.CheckForNull;
* @since 1.319
*/
final class RunnerStack {
private final Map<Executor,Stack<RunExecution>> stack = new WeakHashMap<Executor,Stack<RunExecution>>();
private final Map<Executor,Stack<RunExecution>> stack = new WeakHashMap<>();
synchronized void push(RunExecution r) {
Executor e = Executor.currentExecutor();
Stack<RunExecution> s = stack.get(e);
if(s==null) stack.put(e,s=new Stack<RunExecution>());
Stack<RunExecution> s = stack.computeIfAbsent(e, k -> new Stack<>());
s.push(r);
}
+1 -1
View File
@@ -636,7 +636,7 @@ public abstract class Slave extends Node implements Serializable {
@SuppressWarnings("unchecked") // used by Jelly EL only
@Restricted(NoExternalUse.class) // used by Jelly EL only
public final List<NodePropertyDescriptor> nodePropertyDescriptors(@CheckForNull Slave it) {
List<NodePropertyDescriptor> result = new ArrayList<NodePropertyDescriptor>();
List<NodePropertyDescriptor> result = new ArrayList<>();
Collection<NodePropertyDescriptor> list =
(Collection) Jenkins.getInstance().getDescriptorList(NodeProperty.class);
for (NodePropertyDescriptor npd : it == null
@@ -97,7 +97,7 @@ public abstract class TaskThread extends Thread {
*/
protected final void associateWith(TaskAction action) {
action.workerThread = this;
action.log = new WeakReference<AnnotatedLargeText>(log);
action.log = new WeakReference<>(log);
}
/**
@@ -188,7 +188,7 @@ public abstract class TaskThread extends Thread {
return new ListenerAndText(
new StreamTaskListener(log),
new AnnotatedLargeText<TaskAction>(log,Charset.defaultCharset(),false,context)
new AnnotatedLargeText<>(log, Charset.defaultCharset(), false, context)
);
}
@@ -198,7 +198,7 @@ public abstract class TaskThread extends Thread {
public static ListenerAndText forFile(File f, TaskAction context) throws IOException {
return new ListenerAndText(
new StreamTaskListener(f),
new AnnotatedLargeText<TaskAction>(f,Charset.defaultCharset(),false,context)
new AnnotatedLargeText<>(f, Charset.defaultCharset(), false, context)
);
}
}
@@ -64,7 +64,7 @@ public abstract class TransientComputerActionFactory implements ExtensionPoint {
* Creates {@link Action}s for a node, using all registered {@link TransientComputerActionFactory}s.
*/
public static List<Action> createAllFor(Computer target) {
List<Action> result = new ArrayList<Action>();
List<Action> result = new ArrayList<>();
for (TransientComputerActionFactory f: all()) {
result.addAll(f.createFor(target));
}
@@ -31,7 +31,7 @@ public abstract class TransientViewActionFactory implements ExtensionPoint {
* Creates {@link Action}s for a view, using all registered {@link TransientViewActionFactory}s.
*/
public static List<Action> createAllFor(View v) {
List<Action> result = new ArrayList<Action>();
List<Action> result = new ArrayList<>();
for (TransientViewActionFactory f: all()) {
result.addAll(f.createFor(v));
}
@@ -62,12 +62,12 @@ public class TreeView extends View implements ViewGroup {
* List of job names. This is what gets serialized.
*/
private final Set<String> jobNames
= new TreeSet<String>(CaseInsensitiveComparator.INSTANCE);
= new TreeSet<>(CaseInsensitiveComparator.INSTANCE);
/**
* Nested views.
*/
private final CopyOnWriteArrayList<View> views = new CopyOnWriteArrayList<View>();
private final CopyOnWriteArrayList<View> views = new CopyOnWriteArrayList<>();
@DataBoundConstructor
public TreeView(String name) {
@@ -189,18 +189,18 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas
/**
* List of created {@link UpdateCenterJob}s. Access needs to be synchronized.
*/
private final Vector<UpdateCenterJob> jobs = new Vector<UpdateCenterJob>();
private final Vector<UpdateCenterJob> jobs = new Vector<>();
/**
* {@link UpdateSite}s from which we've already installed a plugin at least once.
* This is used to skip network tests.
*/
private final Set<UpdateSite> sourcesUsed = new HashSet<UpdateSite>();
private final Set<UpdateSite> sourcesUsed = new HashSet<>();
/**
* List of {@link UpdateSite}s to be used.
*/
private final PersistedList<UpdateSite> sites = new PersistedList<UpdateSite>(this);
private final PersistedList<UpdateSite> sites = new PersistedList<>(this);
/**
* Update center configuration data
@@ -338,7 +338,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas
@StaplerDispatchable
public List<UpdateCenterJob> getJobs() {
synchronized (jobs) {
return new ArrayList<UpdateCenterJob>(jobs);
return new ArrayList<>(jobs);
}
}
@@ -918,7 +918,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas
@Exported
public List<Plugin> getAvailables() {
Map<String,Plugin> pluginMap = new LinkedHashMap<String, Plugin>();
Map<String,Plugin> pluginMap = new LinkedHashMap<>();
for (UpdateSite site : sites) {
for (Plugin plugin: site.getAvailables()) {
final Plugin existing = pluginMap.get(plugin.name);
@@ -935,7 +935,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas
}
}
return new ArrayList<Plugin>(pluginMap.values());
return new ArrayList<>(pluginMap.values());
}
/**
@@ -943,7 +943,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas
* A plugin with multiple categories will appear multiple times in the list.
*/
public PluginEntry[] getCategorizedAvailables() {
TreeSet<PluginEntry> entries = new TreeSet<PluginEntry>();
TreeSet<PluginEntry> entries = new TreeSet<>();
for (Plugin p : getAvailables()) {
if (p.categories==null || p.categories.length==0)
entries.add(new PluginEntry(p, getCategoryDisplayName(null)));
@@ -951,7 +951,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas
for (String c : p.categories)
entries.add(new PluginEntry(p, getCategoryDisplayName(c)));
}
return entries.toArray(new PluginEntry[entries.size()]);
return entries.toArray(new PluginEntry[0]);
}
private static String getCategoryDisplayName(String category) {
@@ -966,7 +966,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas
}
public List<Plugin> getUpdates() {
Map<String,Plugin> pluginMap = new LinkedHashMap<String, Plugin>();
Map<String,Plugin> pluginMap = new LinkedHashMap<>();
for (UpdateSite site : sites) {
for (Plugin plugin: site.getUpdates()) {
final Plugin existing = pluginMap.get(plugin.name);
@@ -983,7 +983,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas
}
}
return new ArrayList<Plugin>(pluginMap.values());
return new ArrayList<>(pluginMap.values());
}
/**
@@ -997,7 +997,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas
*
*/
public List<FormValidation> updateAllSites() throws InterruptedException, ExecutionException {
List <Future<FormValidation>> futures = new ArrayList<Future<FormValidation>>();
List <Future<FormValidation>> futures = new ArrayList<>();
for (UpdateSite site : getSites()) {
Future<FormValidation> future = site.updateDirectly(DownloadService.signatureCheck);
if (future != null) {
@@ -1005,7 +1005,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas
}
}
List<FormValidation> results = new ArrayList<FormValidation>();
List<FormValidation> results = new ArrayList<>();
for (Future<FormValidation> f : futures) {
results.add(f.get());
}
@@ -335,11 +335,7 @@ public class UpdateSite {
if(df.exists()) {
try {
return JSONObject.fromObject(df.read());
} catch (JSONException e) {
LOGGER.log(Level.SEVERE,"Failed to parse "+df,e);
df.delete(); // if we keep this file, it will cause repeated failures
return null;
} catch (IOException e) {
} catch (JSONException | IOException e) {
LOGGER.log(Level.SEVERE,"Failed to parse "+df,e);
df.delete(); // if we keep this file, it will cause repeated failures
return null;
@@ -355,7 +351,7 @@ public class UpdateSite {
*/
@Exported
public List<Plugin> getAvailables() {
List<Plugin> r = new ArrayList<Plugin>();
List<Plugin> r = new ArrayList<>();
Data data = getData();
if(data==null) return Collections.emptyList();
for (Plugin p : data.plugins.values()) {
@@ -415,7 +411,7 @@ public class UpdateSite {
Data data = getData();
if(data==null) return Collections.emptyList(); // fail to determine
List<Plugin> r = new ArrayList<Plugin>();
List<Plugin> r = new ArrayList<>();
for (PluginWrapper pw : Jenkins.getInstance().getPluginManager().getPlugins()) {
Plugin p = pw.getUpdateInfo();
if(p!=null) r.add(p);
@@ -515,13 +511,13 @@ public class UpdateSite {
/**
* Plugins in the repository, keyed by their artifact IDs.
*/
public final Map<String,Plugin> plugins = new TreeMap<String,Plugin>(String.CASE_INSENSITIVE_ORDER);
public final Map<String,Plugin> plugins = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
/**
* List of warnings (mostly security) published with the update site.
*
* @since 2.40
*/
private final Set<Warning> warnings = new HashSet<Warning>();
private final Set<Warning> warnings = new HashSet<>();
/**
* If this is non-null, Jenkins is going to check the connectivity to this URL to make sure
@@ -1073,7 +1069,7 @@ public class UpdateSite {
*/
@Exported
public List<Plugin> getNeededDependencies() {
List<Plugin> deps = new ArrayList<Plugin>();
List<Plugin> deps = new ArrayList<>();
for(Map.Entry<String,String> e : dependencies.entrySet()) {
VersionNumber requiredVersion = e.getValue() != null ? new VersionNumber(e.getValue()) : null;
@@ -130,7 +130,7 @@ public class UsageStatistics extends PageDecorator implements PersistentDescript
o.put("servletContainer", j.servletContext.getServerInfo());
o.put("version", Jenkins.VERSION);
List<JSONObject> nodes = new ArrayList<JSONObject>();
List<JSONObject> nodes = new ArrayList<>();
for( Computer c : j.getComputers() ) {
JSONObject n = new JSONObject();
if(c.getNode()==j) {
@@ -146,7 +146,7 @@ public class UsageStatistics extends PageDecorator implements PersistentDescript
}
o.put("nodes",nodes);
List<JSONObject> plugins = new ArrayList<JSONObject>();
List<JSONObject> plugins = new ArrayList<>();
for( PluginWrapper pw : j.getPluginManager().getPlugins() ) {
if(!pw.isActive()) continue; // treat disabled plugins as if they are uninstalled
JSONObject p = new JSONObject();
@@ -40,5 +40,5 @@ public class UserProperties {
* Use {@link UserProperty#all()} for read access and {@link Extension} for auto-registration.
*/
@Deprecated
public static final List<UserPropertyDescriptor> LIST = (List)new DescriptorList<UserProperty>(UserProperty.class);
public static final List<UserPropertyDescriptor> LIST = (List) new DescriptorList<>(UserProperty.class);
}
+14 -14
View File
@@ -206,7 +206,7 @@ public abstract class View extends AbstractModelObject implements AccessControll
public Collection<TopLevelItem> getAllItems() {
if (this instanceof ViewGroup) {
final Collection<TopLevelItem> items = new LinkedHashSet<TopLevelItem>(getItems());
final Collection<TopLevelItem> items = new LinkedHashSet<>(getItems());
for(View view: ((ViewGroup) this).getViews()) {
items.addAll(view.getAllItems());
@@ -318,7 +318,7 @@ public abstract class View extends AbstractModelObject implements AccessControll
* on this label.
*/
public List<ViewPropertyDescriptor> getApplicablePropertyDescriptors() {
List<ViewPropertyDescriptor> r = new ArrayList<ViewPropertyDescriptor>();
List<ViewPropertyDescriptor> r = new ArrayList<>();
for (ViewPropertyDescriptor pd : ViewProperty.all()) {
if (pd.isEnabledFor(this))
r.add(pd);
@@ -428,9 +428,9 @@ public abstract class View extends AbstractModelObject implements AccessControll
return Arrays.asList(computers);
}
List<Computer> result = new ArrayList<Computer>();
List<Computer> result = new ArrayList<>();
HashSet<Label> labels = new HashSet<Label>();
HashSet<Label> labels = new HashSet<>();
for (Item item : getItems()) {
if (item instanceof AbstractProject<?, ?>) {
labels.addAll(((AbstractProject<?, ?>) item).getRelevantLabels());
@@ -725,7 +725,7 @@ public abstract class View extends AbstractModelObject implements AccessControll
}
private Map<User,UserInfo> getUserInfo(Collection<? extends Item> items) {
Map<User,UserInfo> users = new HashMap<User,UserInfo>();
Map<User,UserInfo> users = new HashMap<>();
for (Item item : items) {
for (Job<?, ?> job : item.getAllJobs()) {
RunList<? extends Run<?, ?>> runs = job.getBuilds();
@@ -754,7 +754,7 @@ public abstract class View extends AbstractModelObject implements AccessControll
}
private List<UserInfo> toList(Map<User,UserInfo> users) {
ArrayList<UserInfo> list = new ArrayList<UserInfo>();
ArrayList<UserInfo> list = new ArrayList<>();
list.addAll(users.values());
Collections.sort(list);
return Collections.unmodifiableList(list);
@@ -799,8 +799,8 @@ public abstract class View extends AbstractModelObject implements AccessControll
private final Collection<TopLevelItem> items;
private final User unknown;
private final Map<User,UserInfo> users = new HashMap<User,UserInfo>();
private final Set<User> modified = new HashSet<User>();
private final Map<User,UserInfo> users = new HashMap<>();
private final Set<User> modified = new HashSet<>();
private final String iconSize;
public final ModelObject parent;
@@ -1085,7 +1085,7 @@ public abstract class View extends AbstractModelObject implements AccessControll
}
for (TopLevelItemDescriptor descriptor : DescriptorVisibilityFilter.apply(getOwner().getItemGroup(), Items.all(Jenkins.getAuthentication(), getOwner().getItemGroup()))) {
ItemCategory ic = ItemCategory.getCategory(descriptor);
Map<String, Serializable> metadata = new HashMap<String, Serializable>();
Map<String, Serializable> metadata = new HashMap<>();
// Information about Item.
metadata.put("class", descriptor.getId());
@@ -1109,7 +1109,7 @@ public abstract class View extends AbstractModelObject implements AccessControll
if (category != null) {
category.getItems().add(metadata);
} else {
List<Map<String, Serializable>> temp = new ArrayList<Map<String, Serializable>>();
List<Map<String, Serializable>> temp = new ArrayList<>();
temp.add(metadata);
category = new Category(ic.getId(), ic.getDisplayName(), ic.getDescription(), ic.getOrder(), ic.getMinToShow(), temp);
categories.getItems().add(category);
@@ -1140,7 +1140,7 @@ public abstract class View extends AbstractModelObject implements AccessControll
}
public void doRssLatest( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
List<Run> lastBuilds = new ArrayList<Run>();
List<Run> lastBuilds = new ArrayList<>();
for (TopLevelItem item : getItems()) {
if (item instanceof Job) {
Job job = (Job) item;
@@ -1241,7 +1241,7 @@ public abstract class View extends AbstractModelObject implements AccessControll
* Use {@link #all()} for read access, and use {@link Extension} for registration.
*/
@Deprecated
public static final DescriptorList<View> LIST = new DescriptorList<View>(View.class);
public static final DescriptorList<View> LIST = new DescriptorList<>(View.class);
/**
* Returns all the registered {@link ViewDescriptor}s.
@@ -1259,7 +1259,7 @@ public abstract class View extends AbstractModelObject implements AccessControll
*/
@Nonnull
public static List<ViewDescriptor> allInstantiable() {
List<ViewDescriptor> r = new ArrayList<ViewDescriptor>();
List<ViewDescriptor> r = new ArrayList<>();
StaplerRequest request = Stapler.getCurrentRequest();
if (request == null) {
throw new IllegalStateException("This method can only be invoked from a stapler request");
@@ -1403,7 +1403,7 @@ public abstract class View extends AbstractModelObject implements AccessControll
* "Job" in "New Job". When a view is used in a context that restricts the child type,
* It might be useful to override this.
*/
public static final Message<View> NEW_PRONOUN = new Message<View>();
public static final Message<View> NEW_PRONOUN = new Message<>();
private final static Logger LOGGER = Logger.getLogger(View.class.getName());
}
@@ -146,12 +146,12 @@ public abstract class ViewGroupMixIn {
@Exported
public Collection<View> getViews() {
List<View> orig = views();
List<View> copy = new ArrayList<View>(orig.size());
List<View> copy = new ArrayList<>(orig.size());
for (View v : orig) {
if (v.hasPermission(View.READ))
copy.add(v);
}
Collections.sort(copy, View.SORTER);
copy.sort(View.SORTER);
return copy;
}
+3 -3
View File
@@ -60,7 +60,7 @@ public abstract class ViewJob<JobT extends ViewJob<JobT,RunT>, RunT extends Run<
/**
* All {@link Run}s. Copy-on-write semantics.
*/
protected transient /*almost final*/ RunMap<RunT> runs = new RunMap<RunT>();
protected transient /*almost final*/ RunMap<RunT> runs = new RunMap<>();
private transient boolean notLoaded = true;
@@ -105,7 +105,7 @@ public abstract class ViewJob<JobT extends ViewJob<JobT,RunT>, RunT extends Run<
// if none is loaded yet, do so immediately.
synchronized(this) {
if(runs==null)
runs = new RunMap<RunT>();
runs = new RunMap<>();
if(notLoaded) {
notLoaded = false;
_reload();
@@ -177,7 +177,7 @@ public abstract class ViewJob<JobT extends ViewJob<JobT,RunT>, RunT extends Run<
* This is a set, so no {@link ExternalJob}s are scheduled twice, yet
* it's order is predictable, avoiding starvation.
*/
final Set<ViewJob> reloadQueue = new LinkedHashSet<ViewJob>();
final Set<ViewJob> reloadQueue = new LinkedHashSet<>();
private ReloadThread() {
setName("ViewJob reload thread");
@@ -65,7 +65,7 @@ public class WorkspaceCleanupThread extends AsyncPeriodicWork {
LOGGER.fine("Disabled. Skipping execution");
return;
}
List<Node> nodes = new ArrayList<Node>();
List<Node> nodes = new ArrayList<>();
Jenkins j = Jenkins.getInstance();
nodes.add(j);
nodes.addAll(j.getNodes());
@@ -82,10 +82,7 @@ public class WorkspaceCleanupThread extends AsyncPeriodicWork {
boolean check;
try {
check = shouldBeDeleted(item, ws, node);
} catch (IOException x) {
Functions.printStackTrace(x, listener.error("Failed to check " + node.getDisplayName()));
continue;
} catch (InterruptedException x) {
} catch (IOException | InterruptedException x) {
Functions.printStackTrace(x, listener.error("Failed to check " + node.getDisplayName()));
continue;
}
@@ -94,9 +91,7 @@ public class WorkspaceCleanupThread extends AsyncPeriodicWork {
try {
ws.deleteRecursive();
WorkspaceList.tempDir(ws).deleteRecursive();
} catch (IOException x) {
Functions.printStackTrace(x, listener.error("Failed to delete " + ws + " on " + node.getDisplayName()));
} catch (InterruptedException x) {
} catch (IOException | InterruptedException x) {
Functions.printStackTrace(x, listener.error("Failed to delete " + ws + " on " + node.getDisplayName()));
}
}
@@ -66,10 +66,10 @@ import javax.annotation.Nullable;
*/
public class LabelAtom extends Label implements Saveable {
private DescribableList<LabelAtomProperty,LabelAtomPropertyDescriptor> properties =
new DescribableList<LabelAtomProperty,LabelAtomPropertyDescriptor>(this);
new DescribableList<>(this);
@CopyOnWrite
protected transient volatile List<Action> transientActions = new Vector<Action>();
protected transient volatile List<Action> transientActions = new Vector<>();
private String description;
@@ -100,7 +100,7 @@ public class LabelAtom extends Label implements Saveable {
@Override
public List<Action> getActions() {
// add all the transient actions, too
List<Action> actions = new Vector<Action>(super.getActions());
List<Action> actions = new Vector<>(super.getActions());
actions.addAll(transientActions);
// return the read only list to cause a failure on plugins who try to add an action here
return Collections.unmodifiableList(actions);
@@ -109,7 +109,7 @@ public class LabelAtom extends Label implements Saveable {
// TODO implement addAction, addOrReplaceAction, removeAction, removeActions, replaceActions
protected void updateTransientActions() {
Vector<Action> ta = new Vector<Action>();
Vector<Action> ta = new Vector<>();
for (LabelAtomProperty p : properties)
ta.addAll(p.getActions(this));
@@ -236,7 +236,7 @@ public class LabelAtom extends Label implements Saveable {
}
public static LabelAtom findNearest(String name) {
List<String> candidates = new ArrayList<String>();
List<String> candidates = new ArrayList<>();
for (LabelAtom a : Jenkins.getInstance().getLabelAtoms()) {
candidates.add(a.getName());
}
@@ -130,7 +130,7 @@ public abstract class SCMListener implements ExtensionPoint {
if (j == null) { // TODO use !Functions.isExtensionsAvailable() once JENKINS-33377
return Collections.emptySet();
}
List<SCMListener> r = new ArrayList<SCMListener>(j.getExtensionList(SCMListener.class));
List<SCMListener> r = new ArrayList<>(j.getExtensionList(SCMListener.class));
for (SCMListener l : j.getSCMListeners()) {
r.add(l);
}
@@ -15,7 +15,7 @@ import java.util.List;
public abstract class AbstractQueueSorterImpl extends QueueSorter implements Comparator<BuildableItem> {
@Override
public void sortBuildableItems(List<BuildableItem> buildables) {
Collections.sort(buildables,this); // sort is ascending order
buildables.sort(this); // sort is ascending order
}
/**
@@ -32,7 +32,7 @@ public class BackFiller extends LoadPredictor {
@Override
public Iterable<FutureLoad> predict(MappingWorksheet plan, Computer computer, long start, long end) {
TimeRange timeRange = new TimeRange(start, end - start);
List<FutureLoad> loads = new ArrayList<FutureLoad>();
List<FutureLoad> loads = new ArrayList<>();
for (BuildableItem bi : Jenkins.getInstance().getQueue().getBuildableItems()) {
TentativePlan tp = bi.getAction(TentativePlan.class);
@@ -94,7 +94,7 @@ public class BackFiller extends LoadPredictor {
recursion = true;
try {
// pretend for now that all executors are available and decide some assignment that's executable.
List<PseudoExecutorSlot> slots = new ArrayList<PseudoExecutorSlot>();
List<PseudoExecutorSlot> slots = new ArrayList<>();
for (Computer c : Jenkins.getInstance().getComputers()) {
if (c.isOffline()) continue;
for (Executor e : c.getExecutors()) {
@@ -109,7 +109,7 @@ public class BackFiller extends LoadPredictor {
if (m==null) return null;
// figure out how many executors we need on each computer?
Map<Computer,Integer> footprint = new HashMap<Computer, Integer>();
Map<Computer,Integer> footprint = new HashMap<>();
for (Entry<WorkChunk, ExecutorChunk> e : m.toMap().entrySet()) {
Computer c = e.getValue().computer;
Integer v = footprint.get(c);
@@ -47,14 +47,14 @@ public final class FutureImpl extends AsyncFutureImpl<Executable> implements Que
/**
* If the computation has started, set to {@link Executor}s that are running the build.
*/
private final Set<Executor> executors = new HashSet<Executor>();
private final Set<Executor> executors = new HashSet<>();
/**
* {@link Future} that completes when the task started running.
*
* In contrast, {@link FutureImpl} will complete when the task finishes.
*/
/*package*/ final AsyncFutureImpl<Executable> start = new AsyncFutureImpl<Executable>();
/*package*/ final AsyncFutureImpl<Executable> start = new AsyncFutureImpl<>();
public FutureImpl(Task task) {
this.task = task;
@@ -75,10 +75,7 @@ class Latch {
try {
onCriteriaMet();
} catch (Error e) {
abort(e);
throw e;
} catch (RuntimeException e) {
} catch (Error | RuntimeException e) {
abort(e);
throw e;
}
Loaded 100 of 281 files, more files were not shown because too many files have changed in this diff. Show more