提交 f1c2e85f 编写于 作者: D Daniel Beck

Merge branch 'master' into unbundle-maven-plugin

......@@ -289,7 +289,7 @@ public class ClassicPluginStrategy implements PluginStrategy {
protected ClassLoader createClassLoader(List<File> paths, ClassLoader parent, Attributes atts) throws IOException {
if (atts != null) {
String usePluginFirstClassLoader = atts.getValue( "PluginFirstClassLoader" );
if (Boolean.valueOf( usePluginFirstClassLoader )) {
if (Boolean.parseBoolean( usePluginFirstClassLoader )) {
PluginFirstClassLoader classLoader = new PluginFirstClassLoader();
classLoader.setParentFirst( false );
classLoader.setParent( parent );
......
......@@ -47,7 +47,7 @@ public class DependencyRunner implements Runnable {
ProjectRunnable runnable;
List<AbstractProject> polledProjects = new ArrayList<AbstractProject>();
List<AbstractProject> polledProjects = new ArrayList<>();
public DependencyRunner(ProjectRunnable runnable) {
this.runnable = runnable;
......@@ -56,7 +56,7 @@ public class DependencyRunner implements Runnable {
public void run() {
SecurityContext oldContext = ACL.impersonate(ACL.SYSTEM);
try {
Set<AbstractProject> topLevelProjects = new HashSet<AbstractProject>();
Set<AbstractProject> topLevelProjects = new HashSet<>();
// Get all top-level projects
LOGGER.fine("assembling top level projects");
for (AbstractProject p : Jenkins.get().allItems(AbstractProject.class))
......
......@@ -951,7 +951,7 @@ public class Functions {
@Restricted(DoNotUse.class)
@RestrictedSince("2.12")
public static List<NodePropertyDescriptor> getNodePropertyDescriptors(Class<? extends Node> clazz) {
List<NodePropertyDescriptor> result = new ArrayList<NodePropertyDescriptor>();
List<NodePropertyDescriptor> result = new ArrayList<>();
Collection<NodePropertyDescriptor> list = (Collection) Jenkins.get().getDescriptorList(NodeProperty.class);
for (NodePropertyDescriptor npd : list) {
if (npd.isApplicable(clazz)) {
......@@ -967,7 +967,7 @@ public class Functions {
* @since 1.520
*/
public static List<NodePropertyDescriptor> getGlobalNodePropertyDescriptors() {
List<NodePropertyDescriptor> result = new ArrayList<NodePropertyDescriptor>();
List<NodePropertyDescriptor> result = new ArrayList<>();
Collection<NodePropertyDescriptor> list = (Collection) Jenkins.get().getDescriptorList(NodeProperty.class);
for (NodePropertyDescriptor npd : list) {
if (npd.isApplicableAsGlobal()) {
......@@ -996,7 +996,7 @@ public class Functions {
*/
public static Collection<Descriptor> getSortedDescriptorsForGlobalConfig(Predicate<GlobalConfigurationCategory> predicate) {
ExtensionList<Descriptor> exts = ExtensionList.lookup(Descriptor.class);
List<Tag> r = new ArrayList<Tag>(exts.size());
List<Tag> r = new ArrayList<>(exts.size());
for (ExtensionComponent<Descriptor> c : exts.getComponents()) {
Descriptor d = c.getInstance();
......@@ -1008,7 +1008,7 @@ public class Functions {
}
Collections.sort(r);
List<Descriptor> answer = new ArrayList<Descriptor>(r.size());
List<Descriptor> answer = new ArrayList<>(r.size());
for (Tag d : r) answer.add(d.d);
return DescriptorVisibilityFilter.apply(Jenkins.get(),answer);
......@@ -1059,8 +1059,8 @@ public class Functions {
}
public int compareTo(Tag that) {
int r = Double.compare(this.ordinal, that.ordinal);
if (r!=0) return -r; // descending for ordinal
int r = Double.compare(that.ordinal, this.ordinal);
if (r!=0) return r; // descending for ordinal by reversing the order for compare
return this.hierarchy.compareTo(that.hierarchy);
}
}
......@@ -1090,7 +1090,7 @@ public class Functions {
* Computes the relative path from the current page to the given item.
*/
public static String getRelativeLinkTo(Item p) {
Map<Object,String> ancestors = new HashMap<Object,String>();
Map<Object,String> ancestors = new HashMap<>();
View view=null;
StaplerRequest request = Stapler.getCurrentRequest();
......@@ -1166,7 +1166,7 @@ public class Functions {
String separationString = useDisplayName ? " » " : "/";
// first list up all the parents
Map<ItemGroup,Integer> parents = new HashMap<ItemGroup,Integer>();
Map<ItemGroup,Integer> parents = new HashMap<>();
int depth=0;
while (g!=null) {
parents.put(g, depth++);
......@@ -1233,7 +1233,7 @@ public class Functions {
}
public static Map<Thread,StackTraceElement[]> dumpAllThreads() {
Map<Thread,StackTraceElement[]> sorted = new TreeMap<Thread,StackTraceElement[]>(new ThreadSorter());
Map<Thread,StackTraceElement[]> sorted = new TreeMap<>(new ThreadSorter());
sorted.putAll(Thread.getAllStackTraces());
return sorted;
}
......@@ -1251,7 +1251,7 @@ public class Functions {
// Common code for sorting Threads/ThreadInfos by ThreadGroup
private static class ThreadSorterBase {
protected Map<Long,String> map = new HashMap<Long,String>();
protected Map<Long,String> map = new HashMap<>();
private ThreadSorterBase() {
ThreadGroup tg = Thread.currentThread().getThreadGroup();
......@@ -1475,7 +1475,7 @@ public class Functions {
return Messages.Functions_NoExceptionDetails();
}
StringBuilder s = new StringBuilder();
doPrintStackTrace(s, t, null, "", new HashSet<Throwable>());
doPrintStackTrace(s, t, null, "", new HashSet<>());
return s.toString();
}
private static void doPrintStackTrace(@Nonnull StringBuilder s, @Nonnull Throwable t, @CheckForNull Throwable higher, @Nonnull String prefix, @Nonnull Set<Throwable> encountered) {
......@@ -1840,7 +1840,7 @@ public class Functions {
public List<String> getLoggerNames() {
while (true) {
try {
List<String> r = new ArrayList<String>();
List<String> r = new ArrayList<>();
Enumeration<String> e = LogManager.getLogManager().getLoggerNames();
while (e.hasMoreElements())
r.add(e.nextElement());
......@@ -1933,7 +1933,7 @@ public class Functions {
}
public static List<String> getRequestHeaders(String name) {
List<String> r = new ArrayList<String>();
List<String> r = new ArrayList<>();
Enumeration e = Stapler.getCurrentRequest().getHeaders(name);
while (e.hasMoreElements()) {
r.add(e.nextElement().toString());
......@@ -1949,7 +1949,7 @@ public class Functions {
}
public static ArrayList<CLICommand> getCLICommands() {
ArrayList<CLICommand> all = new ArrayList<CLICommand>(CLICommand.all());
ArrayList<CLICommand> all = new ArrayList<>(CLICommand.all());
Collections.sort(all, new Comparator<CLICommand>() {
public int compare(CLICommand cliCommand, CLICommand cliCommand1) {
return cliCommand.getName().compareTo(cliCommand1.getName());
......
......@@ -50,7 +50,7 @@ public class PluginFirstClassLoader
super(null, false);
}
private List<URL> urls = new ArrayList<URL>();
private List<URL> urls = new ArrayList<>();
public void addPathFiles( Collection<File> paths )
throws IOException
......
......@@ -2131,7 +2131,7 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas
* Stores {@link Plugin} instances.
*/
/*package*/ static final class PluginInstanceStore {
final Map<PluginWrapper,Plugin> store = new ConcurrentHashMap<PluginWrapper,Plugin>();
final Map<PluginWrapper,Plugin> store = new ConcurrentHashMap<>();
}
/**
......@@ -2174,7 +2174,7 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas
@Extension @Symbol("pluginUpdate")
public static final class PluginUpdateMonitor extends AdministrativeMonitor {
private Map<String, PluginUpdateInfo> pluginsToBeUpdated = new HashMap<String, PluginManager.PluginUpdateMonitor.PluginUpdateInfo>();
private Map<String, PluginUpdateInfo> pluginsToBeUpdated = new HashMap<>();
/**
* Convenience method to ease access to this monitor, this allows other plugins to register required updates.
......
......@@ -905,10 +905,10 @@ public class Util {
}
byte[] bytes = new String(new int[] { codePoint }, 0, 1).getBytes(StandardCharsets.UTF_8);
for(int j=0;j<bytes.length;j++) {
for (byte aByte : bytes) {
out.append('%');
out.append(toDigit((bytes[j] >> 4) & 0xF));
out.append(toDigit(bytes[j] & 0xF));
out.append(toDigit((aByte >> 4) & 0xF));
out.append(toDigit(aByte & 0xF));
}
if(Character.charCount(codePoint) > 1) {
......
......@@ -294,7 +294,7 @@ public class OldDataMonitor extends AdministrativeMonitor {
*/
@Restricted(NoExternalUse.class)
public Iterator<VersionNumber> getVersionList() {
TreeSet<VersionNumber> set = new TreeSet<VersionNumber>();
TreeSet<VersionNumber> set = new TreeSet<>();
for (VersionRange vr : data.values()) {
if (vr.max != null) {
set.add(vr.max);
......@@ -364,7 +364,7 @@ public class OldDataMonitor extends AdministrativeMonitor {
* does occur: just means the user will be prompted to discard less than they should have been (and
* would see the warning again after next restart).
*/
List<SaveableReference> removed = new ArrayList<SaveableReference>();
List<SaveableReference> removed = new ArrayList<>();
for (Map.Entry<SaveableReference,VersionRange> entry : data.entrySet()) {
if (matchingPredicate.apply(entry)) {
Saveable s = entry.getKey().get();
......
......@@ -262,7 +262,7 @@ public class LogRecorder extends AbstractModelObject implements Saveable {
private static final class SetLevel extends MasterToSlaveCallable<Void,Error> {
/** known loggers (kept per agent), to avoid GC */
@SuppressWarnings("MismatchedQueryAndUpdateOfCollection") private static final Set<Logger> loggers = new HashSet<Logger>();
@SuppressWarnings("MismatchedQueryAndUpdateOfCollection") private static final Set<Logger> loggers = new HashSet<>();
private final String name;
private final Level level;
SetLevel(String name, Level level) {
......@@ -421,8 +421,9 @@ public class LogRecorder extends AbstractModelObject implements Saveable {
* @since 1.519
*/
public Map<Computer,List<LogRecord>> getSlaveLogRecords() {
Map<Computer,List<LogRecord>> result = new TreeMap<Computer,List<LogRecord>>(new Comparator<Computer>() {
Map<Computer,List<LogRecord>> result = new TreeMap<>(new Comparator<Computer>() {
final Collator COLL = Collator.getInstance();
public int compare(Computer c1, Computer c2) {
return COLL.compare(c1.getDisplayName(), c2.getDisplayName());
}
......@@ -431,7 +432,7 @@ public class LogRecorder extends AbstractModelObject implements Saveable {
if (c.getName().length() == 0) {
continue; // master
}
List<LogRecord> recs = new ArrayList<LogRecord>();
List<LogRecord> recs = new ArrayList<>();
try {
for (LogRecord rec : c.getLogRecords()) {
for (Target t : targets) {
......
......@@ -93,7 +93,7 @@ public abstract class AbstractCIBase extends Node implements ItemGroup<TopLevelI
* Package-protected, but accessed API
* ============================================================================================================== */
/*package*/ final CopyOnWriteArraySet<String> disabledAdministrativeMonitors = new CopyOnWriteArraySet<String>();
/*package*/ final CopyOnWriteArraySet<String> disabledAdministrativeMonitors = new CopyOnWriteArraySet<>();
@Restricted(NoExternalUse.class)
public CopyOnWriteArraySet<String> getDisabledAdministrativeMonitors(){
......@@ -192,11 +192,11 @@ public abstract class AbstractCIBase extends Node implements ItemGroup<TopLevelI
*/
protected void updateComputerList(final boolean automaticSlaveLaunch) {
final Map<Node,Computer> computers = getComputerMap();
final Set<Computer> old = new HashSet<Computer>(computers.size());
final Set<Computer> old = new HashSet<>(computers.size());
Queue.withLock(new Runnable() {
@Override
public void run() {
Map<String,Computer> byName = new HashMap<String,Computer>();
Map<String,Computer> byName = new HashMap<>();
for (Computer c : computers.values()) {
old.add(c);
Node node = c.getNode();
......
......@@ -981,7 +981,7 @@ public abstract class AbstractItem extends Actionable implements Item, HttpDelet
/**
* Replaceable pronoun of that points to a job. Defaults to "Job"/"Project" depending on the context.
*/
public static final Message<AbstractItem> PRONOUN = new Message<AbstractItem>();
public static final Message<AbstractItem> PRONOUN = new Message<>();
/**
* Replaceable noun for describing the kind of task that this item represents. Defaults to "Build".
......
......@@ -232,7 +232,7 @@ public abstract class AbstractProject<P extends AbstractProject<P,R>,R extends A
* List of all {@link Trigger}s for this project.
*/
@AdaptField(was=List.class)
protected volatile DescribableList<Trigger<?>,TriggerDescriptor> triggers = new DescribableList<Trigger<?>,TriggerDescriptor>(this);
protected volatile DescribableList<Trigger<?>,TriggerDescriptor> triggers = new DescribableList<>(this);
private static final AtomicReferenceFieldUpdater<AbstractProject,DescribableList> triggersUpdater
= AtomicReferenceFieldUpdater.newUpdater(AbstractProject.class,DescribableList.class,"triggers");
......@@ -244,7 +244,7 @@ public abstract class AbstractProject<P extends AbstractProject<P,R>,R extends A
* come and go as configuration change, so it's kept separate.
*/
@CopyOnWrite
protected transient volatile List<Action> transientActions = new Vector<Action>();
protected transient volatile List<Action> transientActions = new Vector<>();
private boolean concurrentBuild;
......@@ -260,9 +260,8 @@ public abstract class AbstractProject<P extends AbstractProject<P,R>,R extends A
buildMixIn = createBuildMixIn();
builds = buildMixIn.getRunMap();
final Jenkins j = Jenkins.get();
final List<Node> nodes = j != null ? j.getNodes() : null;
if(nodes!=null && !nodes.isEmpty()) {
Jenkins j = Jenkins.getInstanceOrNull();
if (j != null && !j.getNodes().isEmpty()) {
// if a new job is configured with Hudson that already has agent nodes
// make it roamable by default
canRoam = true;
......@@ -320,7 +319,7 @@ public abstract class AbstractProject<P extends AbstractProject<P,R>,R extends A
scm = new NullSCM(); // perhaps it was pointing to a plugin that no longer exists.
if(transientActions==null)
transientActions = new Vector<Action>(); // happens when loaded from disk
transientActions = new Vector<>(); // happens when loaded from disk
updateTransientActions();
}
......@@ -731,7 +730,7 @@ public abstract class AbstractProject<P extends AbstractProject<P,R>,R extends A
}
protected List<Action> createTransientActions() {
Vector<Action> ta = new Vector<Action>();
Vector<Action> ta = new Vector<>();
for (JobProperty<? super P> p : Util.fixNull(properties))
ta.addAll(p.getJobActions((P)this));
......@@ -817,7 +816,7 @@ public abstract class AbstractProject<P extends AbstractProject<P,R>,R extends A
*/
@WithBridgeMethods(Future.class)
public QueueTaskFuture<R> scheduleBuild2(int quietPeriod, Cause c, Collection<? extends Action> actions) {
List<Action> queueActions = new ArrayList<Action>(actions);
List<Action> queueActions = new ArrayList<>(actions);
if (c != null) {
queueActions.add(new CauseAction(c));
}
......@@ -987,7 +986,7 @@ public abstract class AbstractProject<P extends AbstractProject<P,R>,R extends A
@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);
......@@ -1127,7 +1126,7 @@ public abstract class AbstractProject<P extends AbstractProject<P,R>,R extends A
}
public List<SubTask> getSubTasks() {
List<SubTask> r = new ArrayList<SubTask>();
List<SubTask> r = new ArrayList<>();
r.add(this);
for (SubTaskContributor euc : SubTaskContributor.all())
r.addAll(euc.forProject(this));
......@@ -1173,7 +1172,7 @@ public abstract class AbstractProject<P extends AbstractProject<P,R>,R extends A
*/
public ResourceList getResourceList() {
final Set<ResourceActivity> resourceActivities = getResourceActivities();
final List<ResourceList> resourceLists = new ArrayList<ResourceList>(1 + resourceActivities.size());
final List<ResourceList> resourceLists = new ArrayList<>(1 + resourceActivities.size());
for (ResourceActivity activity : resourceActivities) {
if (activity != this && activity != null) {
// defensive infinite recursion and null check
......@@ -1605,7 +1604,7 @@ public abstract class AbstractProject<P extends AbstractProject<P,R>,R extends A
* @return A List of upstream projects that has a {@link BuildTrigger} to this project.
*/
public final List<AbstractProject> getBuildTriggerUpstreamProjects() {
ArrayList<AbstractProject> result = new ArrayList<AbstractProject>();
ArrayList<AbstractProject> result = new ArrayList<>();
for (AbstractProject<?,?> ap : getUpstreamProjects()) {
BuildTrigger buildTrigger = ap.getPublishersList().get(BuildTrigger.class);
if (buildTrigger != null)
......@@ -1642,7 +1641,7 @@ public abstract class AbstractProject<P extends AbstractProject<P,R>,R extends A
* numbers of that project.
*/
public SortedMap<Integer, RangeSet> getRelationship(AbstractProject that) {
TreeMap<Integer,RangeSet> r = new TreeMap<Integer,RangeSet>(REVERSE_INTEGER_COMPARATOR);
TreeMap<Integer,RangeSet> r = new TreeMap<>(REVERSE_INTEGER_COMPARATOR);
checkAndRecord(that, r, this.getBuilds());
// checkAndRecord(that, r, that.getBuilds());
......@@ -1815,7 +1814,7 @@ public abstract class AbstractProject<P extends AbstractProject<P,R>,R extends A
throws FormException, ServletException {
JSONObject data = req.getSubmittedForm();
List<T> r = new Vector<T>();
List<T> r = new Vector<>();
for (Descriptor<T> d : descriptors) {
String safeName = d.getJsonSafeClassName();
if (req.getParameter(safeName) != null) {
......@@ -2016,7 +2015,7 @@ public abstract class AbstractProject<P extends AbstractProject<P,R>,R extends A
}
List<String> getSeeds() {
ArrayList<String> terms = new ArrayList<String>();
ArrayList<String> terms = new ArrayList<>();
boolean trailingQuote = source.endsWith("\"");
boolean leadingQuote = source.startsWith("\"");
boolean trailingSpace = source.endsWith(" ");
......@@ -2082,7 +2081,7 @@ public abstract class AbstractProject<P extends AbstractProject<P,R>,R extends A
* @deprecated Use {@link ParameterizedJobMixIn#BUILD_NOW_TEXT}.
*/
@Deprecated
public static final Message<AbstractProject> BUILD_NOW_TEXT = new Message<AbstractProject>();
public static final Message<AbstractProject> BUILD_NOW_TEXT = new Message<>();
/**
* Used for CLI binding.
......
......@@ -65,7 +65,7 @@ public class BooleanParameterDefinition extends SimpleParameterDefinition {
}
public ParameterValue createValue(String value) {
return new BooleanParameterValue(getName(),Boolean.valueOf(value),getDescription());
return new BooleanParameterValue(getName(),Boolean.parseBoolean(value),getDescription());
}
@Override
......
......@@ -181,7 +181,7 @@ public final class DirectoryBrowserSupport implements HttpResponse {
}
String path = getPath(req);
if(path.replace('\\','/').indexOf("/../")!=-1) {
if(path.replace('\\', '/').contains("/../")) {
// don't serve anything other than files in the artifacts dir
rsp.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
......@@ -413,7 +413,7 @@ public final class DirectoryBrowserSupport implements HttpResponse {
* from a string like "/foo/bar/zot".
*/
private List<Path> buildParentPath(String pathList, int restSize) {
List<Path> r = new ArrayList<Path>();
List<Path> r = new ArrayList<>();
StringTokenizer tokens = new StringTokenizer(pathList, "/");
int total = tokens.countTokens();
int current=1;
......@@ -669,7 +669,7 @@ public final class DirectoryBrowserSupport implements HttpResponse {
* (this mechanism is used to skip empty intermediate directory.)
*/
private static List<List<Path>> buildChildPaths(VirtualFile cur, Locale locale) throws IOException {
List<List<Path>> r = new ArrayList<List<Path>>();
List<List<Path>> r = new ArrayList<>();
VirtualFile[] files = cur.list();
Arrays.sort(files,new FileComparator(locale));
......@@ -680,12 +680,12 @@ public final class DirectoryBrowserSupport implements HttpResponse {
r.add(Collections.singletonList(p));
} else {
// find all empty intermediate directory
List<Path> l = new ArrayList<Path>();
List<Path> l = new ArrayList<>();
l.add(p);
String relPath = Util.rawEncode(f.getName());
while(true) {
// files that don't start with '.' qualify for 'meaningful files', nor SCM related files
List<VirtualFile> sub = new ArrayList<VirtualFile>();
List<VirtualFile> sub = new ArrayList<>();
for (VirtualFile vf : f.list()) {
String name = vf.getName();
if (!name.startsWith(".") && !name.equals("CVS") && !name.equals(".svn")) {
......@@ -714,7 +714,7 @@ public final class DirectoryBrowserSupport implements HttpResponse {
Collection<String> files = baseDir.list(pattern, null, /* TODO what is the user expectation? */true);
if (!files.isEmpty()) {
List<List<Path>> r = new ArrayList<List<Path>>(files.size());
List<List<Path>> r = new ArrayList<>(files.size());
for (String match : files) {
List<Path> file = buildPathList(baseDir, baseDir.child(match), baseRef);
r.add(file);
......@@ -729,7 +729,7 @@ public final class DirectoryBrowserSupport implements HttpResponse {
* Builds a path list from the current workspace directory down to the specified file path.
*/
private static List<Path> buildPathList(VirtualFile baseDir, VirtualFile filePath, String baseRef) throws IOException {
List<Path> pathList = new ArrayList<Path>();
List<Path> pathList = new ArrayList<>();
StringBuilder href = new StringBuilder(baseRef);
buildPathList(baseDir, filePath, pathList, href);
......
......@@ -282,7 +282,7 @@ public abstract class Node extends AbstractModelObject implements Reconfigurable
* Return the possibly empty tag cloud for the labels of this node.
*/
public TagCloud<LabelAtom> getLabelCloud() {
return new TagCloud<LabelAtom>(getAssignedLabels(),new WeightFunction<LabelAtom>() {
return new TagCloud<>(getAssignedLabels(), new WeightFunction<LabelAtom>() {
public float weight(LabelAtom item) {
return item.getTiedJobCount();
}
......@@ -313,7 +313,7 @@ public abstract class Node extends AbstractModelObject implements Reconfigurable
* @return HashSet<Label>.
*/
private HashSet<LabelAtom> getDynamicLabels() {
HashSet<LabelAtom> result = new HashSet<LabelAtom>();
HashSet<LabelAtom> result = new HashSet<>();
for (LabelFinder labeler : LabelFinder.all()) {
// Filter out any bad(null) results from plugins
// for compatibility reasons, findLabels may return LabelExpression and not atom.
......@@ -526,7 +526,7 @@ public abstract class Node extends AbstractModelObject implements Reconfigurable
}
try {
DescribableList<NodeProperty<?>, NodePropertyDescriptor> tmp = new DescribableList<NodeProperty<?>, NodePropertyDescriptor>(Saveable.NOOP,getNodeProperties().toList());
DescribableList<NodeProperty<?>, NodePropertyDescriptor> tmp = new DescribableList<>(Saveable.NOOP, getNodeProperties().toList());
tmp.rebuild(req, jsonForProperties, NodeProperty.all());
return tmp.toList();
} catch (FormException e) {
......
......@@ -2871,7 +2871,7 @@ public class Queue extends ResourceController implements Saveable {
private final WeakReference<Queue> queue;
MaintainTask(Queue queue) {
this.queue = new WeakReference<Queue>(queue);
this.queue = new WeakReference<>(queue);
}
private void periodic() {
......@@ -2902,7 +2902,7 @@ public class Queue extends ResourceController implements Saveable {
}
public List<T> getAll(Task task) {
List<T> result = new ArrayList<T>();
List<T> result = new ArrayList<>();
for (T item: this) {
if (item.task.equals(task)) {
result.add(item);
......@@ -2949,7 +2949,7 @@ public class Queue extends ResourceController implements Saveable {
justification = "It will invoke the inherited clear() method according to Java semantics. "
+ "FindBugs recommends suppressing warnings in such case")
public void cancelAll() {
for (T t : new ArrayList<T>(this))
for (T t : new ArrayList<>(this))
t.cancel(Queue.this);
clear();
}
......@@ -2963,10 +2963,10 @@ public class Queue extends ResourceController implements Saveable {
public Snapshot(Set<WaitingItem> waitingList, List<BlockedItem> blockedProjects, List<BuildableItem> buildables,
List<BuildableItem> pendings) {
this.waitingList = new LinkedHashSet<WaitingItem>(waitingList);
this.blockedProjects = new ArrayList<BlockedItem>(blockedProjects);
this.buildables = new ArrayList<BuildableItem>(buildables);
this.pendings = new ArrayList<BuildableItem>(pendings);
this.waitingList = new LinkedHashSet<>(waitingList);
this.blockedProjects = new ArrayList<>(blockedProjects);
this.buildables = new ArrayList<>(buildables);
this.pendings = new ArrayList<>(pendings);
}
@Override
......
......@@ -156,7 +156,7 @@ public final class RunMap<R extends Run<?,R>> extends AbstractLazyLoadRunMap<R>
@Deprecated
public static final Comparator<Comparable> COMPARATOR = new Comparator<Comparable>() {
public int compare(Comparable o1, Comparable o2) {
return -o1.compareTo(o2);
return o2.compareTo(o1);
}
};
......
......@@ -1482,7 +1482,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas
* Tests the internet connectivity.
*/
public final class ConnectionCheckJob extends UpdateCenterJob {
private final Vector<String> statuses= new Vector<String>();
private final Vector<String> statuses= new Vector<>();
final Map<String, ConnectionStatus> connectionStates = new ConcurrentHashMap<>();
......
......@@ -741,7 +741,7 @@ public abstract class SCM implements Describable<SCM>, ExtensionPoint {
if(project==null) return all();
final Descriptor pd = Jenkins.get().getDescriptor((Class) project.getClass());
List<SCMDescriptor<?>> r = new ArrayList<SCMDescriptor<?>>();
List<SCMDescriptor<?>> r = new ArrayList<>();
for (SCMDescriptor<?> scmDescriptor : all()) {
if(!scmDescriptor.isApplicable(project)) continue;
......
......@@ -194,7 +194,7 @@ public class Search implements StaplerProxy {
@ExportedBean
public static class Result {
@Exported
public List<Item> suggestions = new ArrayList<Item>();
public List<Item> suggestions = new ArrayList<>();
}
@ExportedBean(defaultVisibility=999)
......@@ -310,7 +310,7 @@ public class Search implements StaplerProxy {
}
}
List<Tag> buf = new ArrayList<Tag>();
List<Tag> buf = new ArrayList<>();
List<SuggestedItem> items = find(Mode.SUGGEST, index, tokenList, searchContext);
// sort them
......@@ -372,9 +372,9 @@ public class Search implements StaplerProxy {
List<SuggestedItem>[] paths = new List[tokens.length()+1]; // we won't use [0].
for(int i=1;i<=tokens.length();i++)
paths[i] = new ArrayList<SuggestedItem>();
paths[i] = new ArrayList<>();
List<SearchItem> items = new ArrayList<SearchItem>(); // items found in 1 step
List<SearchItem> items = new ArrayList<>(); // items found in 1 step
LOGGER.log(Level.FINE, "tokens={0}", tokens);
......
......@@ -552,7 +552,7 @@ public class HudsonPrivateSecurityRealm extends AbstractPasswordBasedSecurityRea
* All users who can login to the system.
*/
public List<User> getAllUsers() {
List<User> r = new ArrayList<User>();
List<User> r = new ArrayList<>();
for (User u : User.getAll()) {
if(u.getProperty(Details.class)!=null)
r.add(u);
......@@ -587,7 +587,7 @@ public class HudsonPrivateSecurityRealm extends AbstractPasswordBasedSecurityRea
* Keys are field names (e.g. {@code password2}), values are the messages.
*/
// TODO i18n?
public HashMap<String, String> errors = new HashMap<String, String>();
public HashMap<String, String> errors = new HashMap<>();
public SignupInfo() {
}
......
......@@ -82,7 +82,7 @@ public abstract class DelegatingComputerLauncher extends ComputerLauncher {
*/
public List<Descriptor<ComputerLauncher>> applicableDescriptors(@CheckForNull Slave it,
@Nonnull Slave.SlaveDescriptor itDescriptor) {
List<Descriptor<ComputerLauncher>> r = new ArrayList<Descriptor<ComputerLauncher>>();
List<Descriptor<ComputerLauncher>> r = new ArrayList<>();
for (Descriptor<ComputerLauncher> d : itDescriptor.computerLauncherDescriptors(it)) {
if (DelegatingComputerLauncher.class.isAssignableFrom(d.getKlass().toJavaClass())) continue;
r.add(d);
......@@ -98,7 +98,7 @@ public abstract class DelegatingComputerLauncher extends ComputerLauncher {
@Restricted(DoNotUse.class)
@RestrictedSince("2.12")
public List<Descriptor<ComputerLauncher>> getApplicableDescriptors() {
List<Descriptor<ComputerLauncher>> r = new ArrayList<Descriptor<ComputerLauncher>>();
List<Descriptor<ComputerLauncher>> r = new ArrayList<>();
for (Descriptor<ComputerLauncher> d :
Jenkins.get().getDescriptorList(ComputerLauncher.class)) {
if (DelegatingComputerLauncher.class.isAssignableFrom(d.getKlass().toJavaClass())) continue;
......
......@@ -67,7 +67,7 @@ public class BatchFile extends CommandInterpreter {
@CheckForNull
public final Integer getUnstableReturn() {
return new Integer(0).equals(unstableReturn) ? null : unstableReturn;
return Integer.valueOf(0).equals(unstableReturn) ? null : unstableReturn;
}
@DataBoundSetter
......
......@@ -106,7 +106,7 @@ public class Shell extends CommandInterpreter {
@CheckForNull
public final Integer getUnstableReturn() {
return new Integer(0).equals(unstableReturn) ? null : unstableReturn;
return Integer.valueOf(0).equals(unstableReturn) ? null : unstableReturn;
}
@DataBoundSetter
......
......@@ -285,7 +285,7 @@ public class SCMTrigger extends Trigger<Item> {
// originally List<SCMedItem> but known to be used only for logging, in which case the instances are not actually cast to SCMedItem anyway
public List<SCMTriggerItem> getItemsBeingPolled() {
List<SCMTriggerItem> r = new ArrayList<SCMTriggerItem>();
List<SCMTriggerItem> r = new ArrayList<>();
for (Runner i : getRunners())
r.add(i.getTarget());
return r;
......@@ -467,7 +467,7 @@ public class SCMTrigger extends Trigger<Item> {
}
public AnnotatedLargeText getPollingLogText() {
return new AnnotatedLargeText<BuildAction>(getPollingLogFile(), Charset.defaultCharset(), true, this);
return new AnnotatedLargeText<>(getPollingLogFile(), Charset.defaultCharset(), true, this);
}
/**
......@@ -509,7 +509,7 @@ public class SCMTrigger extends Trigger<Item> {
}
public String getDisplayName() {
Set<SCMDescriptor<?>> descriptors = new HashSet<SCMDescriptor<?>>();
Set<SCMDescriptor<?>> descriptors = new HashSet<>();
for (SCM scm : job().getSCMs()) {
descriptors.add(scm.getDescriptor());
}
......@@ -529,7 +529,7 @@ public class SCMTrigger extends Trigger<Item> {
* @since 1.350
*/
public void writeLogTo(XMLOutput out) throws IOException {
new AnnotatedLargeText<SCMAction>(getLogFile(),Charset.defaultCharset(),true,this).writeHtmlTo(0,out.asWriter());
new AnnotatedLargeText<>(getLogFile(), Charset.defaultCharset(), true, this).writeHtmlTo(0,out.asWriter());
}
}
......
......@@ -124,6 +124,7 @@ public abstract class ProcessTree implements Iterable<OSProcess>, IProcessTree,
/**
* Gets the process given a specific ID, or null if no such process exists.
*/
@CheckForNull
public final OSProcess get(int pid) {
return processes.get(pid);
}
......@@ -131,6 +132,7 @@ public abstract class ProcessTree implements Iterable<OSProcess>, IProcessTree,
/**
* Lists all the processes in the system.
*/
@Nonnull
public final Iterator<OSProcess> iterator() {
return processes.values().iterator();
}
......@@ -140,7 +142,8 @@ public abstract class ProcessTree implements Iterable<OSProcess>, IProcessTree,
* or null if it fails (for example, maybe the snapshot is taken after
* this process has already finished.)
*/
public abstract OSProcess get(Process proc);
@CheckForNull
public abstract OSProcess get(@Nonnull Process proc);
/**
* Kills all the processes that have matching environment variables.
......@@ -154,9 +157,15 @@ public abstract class ProcessTree implements Iterable<OSProcess>, IProcessTree,
* them all. This is suitable for locating daemon processes
* that cannot be tracked by the regular ancestor/descendant relationship.
*/
public abstract void killAll(Map<String, String> modelEnvVars) throws InterruptedException;
public abstract void killAll(@Nonnull Map<String, String> modelEnvVars) throws InterruptedException;
private final long softKillWaitSeconds = Integer.getInteger("SoftKillWaitSeconds", 2 * 60); // by default processes get at most 2 minutes to respond to SIGTERM (JENKINS-17116)
/**
* The time to wait between sending Ctrl+C and killing the process. (JENKINS-17116)
*
* The default is 5 seconds. Careful! There are other timers in the system that may
* interfere with this value here, e.g. in org.jenkinsci.plugins.workflow.cps.CpsThread.stop
*/
private final long softKillWaitSeconds = Integer.getInteger("SoftKillWaitSeconds", 5);
/**
* Convenience method that does {@link #killAll(Map)} and {@link OSProcess#killRecursively()}.
......@@ -165,10 +174,14 @@ public abstract class ProcessTree implements Iterable<OSProcess>, IProcessTree,
*
* Either of the parameter can be null.
*/
public void killAll(Process proc, Map<String, String> modelEnvVars) throws InterruptedException {
public void killAll(@CheckForNull Process proc, @CheckForNull Map<String, String> modelEnvVars) throws InterruptedException {
LOGGER.fine("killAll: process="+proc+" and envs="+modelEnvVars);
OSProcess p = get(proc);
if(p!=null) p.killRecursively();
if (proc != null) {
OSProcess p = get(proc);
if (p != null) p.killRecursively();
}
if(modelEnvVars!=null)
killAll(modelEnvVars);
}
......@@ -176,6 +189,7 @@ public abstract class ProcessTree implements Iterable<OSProcess>, IProcessTree,
/**
* Obtains the list of killers.
*/
@Nonnull
/*package*/ final List<ProcessKiller> getKillers() throws InterruptedException {
if (killers==null)
try {
......@@ -219,6 +233,7 @@ public abstract class ProcessTree implements Iterable<OSProcess>, IProcessTree,
* there's no guarantee that we are getting a consistent snapshot
* of the whole system state.
*/
@CheckForNull
public abstract OSProcess getParent();
/*package*/ final ProcessTree getTree() {
......@@ -228,8 +243,9 @@ public abstract class ProcessTree implements Iterable<OSProcess>, IProcessTree,
/**
* Immediate child processes.
*/
@Nonnull
public final List<OSProcess> getChildren() {
List<OSProcess> r = new ArrayList<OSProcess>();
List<OSProcess> r = new ArrayList<>();
for (OSProcess p : ProcessTree.this)
if(p.getParent()==this)
r.add(p);
......@@ -297,6 +313,7 @@ public abstract class ProcessTree implements Iterable<OSProcess>, IProcessTree,
* On Windows, where the OS models command-line arguments as a single string, this method
* computes the approximated tokenization.
*/
@Nonnull
public abstract List<String> getArguments();
/**
......@@ -306,6 +323,7 @@ public abstract class ProcessTree implements Iterable<OSProcess>, IProcessTree,
* empty map if failed (for example because the process is already dead,
* or the permission was denied.)
*/
@Nonnull
public abstract EnvVars getEnvironmentVariables();
/**
......@@ -462,8 +480,9 @@ public abstract class ProcessTree implements Iterable<OSProcess>, IProcessTree,
* Empty process list as a default value if the platform doesn't support it.
*/
/*package*/ static final ProcessTree DEFAULT = new Local() {
public OSProcess get(final Process proc) {
public OSProcess get(@Nonnull final Process proc) {
return new OSProcess(-1) {
@CheckForNull
public OSProcess getParent() {
return null;
}
......@@ -480,17 +499,19 @@ public abstract class ProcessTree implements Iterable<OSProcess>, IProcessTree,
killByKiller();
}
@Nonnull
public List<String> getArguments() {
return Collections.emptyList();
}
@Nonnull
public EnvVars getEnvironmentVariables() {
return new EnvVars();
}
};
}
public void killAll(Map<String, String> modelEnvVars) {
public void killAll(@Nonnull Map<String, String> modelEnvVars) {
// no-op
}
};
......@@ -506,6 +527,7 @@ public abstract class ProcessTree implements Iterable<OSProcess>, IProcessTree,
this.p = p;
}
@CheckForNull
@Override
public OSProcess getParent() {
// Windows process doesn't have parent/child relationship
......@@ -564,6 +586,7 @@ public abstract class ProcessTree implements Iterable<OSProcess>, IProcessTree,
} while (System.nanoTime() < deadline);
}
@Nonnull
@Override
public synchronized List<String> getArguments() {
if(args==null) {
......@@ -572,6 +595,7 @@ public abstract class ProcessTree implements Iterable<OSProcess>, IProcessTree,
return args;
}
@Nonnull
@Override
public synchronized EnvVars getEnvironmentVariables() {
try {
......@@ -581,7 +605,7 @@ public abstract class ProcessTree implements Iterable<OSProcess>, IProcessTree,
LOGGER.log(FINEST, "Failed to get the environment variables of process with pid=" + p.getPid(), e);
}
}
return null;
return env;
}
private synchronized EnvVars getEnvironmentVariables2() throws WindowsOSProcessException {
......@@ -639,13 +663,14 @@ public abstract class ProcessTree implements Iterable<OSProcess>, IProcessTree,
}
}
@CheckForNull
@Override
public OSProcess get(Process proc) {
public OSProcess get(@Nonnull Process proc) {
return get(new WinProcess(proc).getPid());
}
@Override
public void killAll(Map<String, String> modelEnvVars) throws InterruptedException {
public void killAll(@Nonnull Map<String, String> modelEnvVars) throws InterruptedException {
for( OSProcess p : this) {
if(p.getPid()<10)
continue; // ignore system processes like "idle process"
......@@ -696,13 +721,14 @@ public abstract class ProcessTree implements Iterable<OSProcess>, IProcessTree,
public Unix(boolean vetoersExist) {
super(vetoersExist);
}
@CheckForNull
@Override
public OSProcess get(Process proc) {
public OSProcess get(@Nonnull Process proc) {
return get(UnixReflection.pid(proc));
}
public void killAll(Map<String, String> modelEnvVars) throws InterruptedException {
public void killAll(@Nonnull Map<String, String> modelEnvVars) throws InterruptedException {
for (OSProcess p : this)
if(p.hasMatchingEnvVars(modelEnvVars))
p.killRecursively();
......@@ -824,6 +850,7 @@ public abstract class ProcessTree implements Iterable<OSProcess>, IProcessTree,
* empty list if failed (for example because the process is already dead,
* or the permission was denied.)
*/
@Nonnull
public abstract List<String> getArguments();
}
......@@ -946,14 +973,16 @@ public abstract class ProcessTree implements Iterable<OSProcess>, IProcessTree,
throw new IOException("Failed to parse PPID from /proc/"+pid+"/status");
}
@CheckForNull
public OSProcess getParent() {
return get(ppid);
}
@Nonnull
public synchronized List<String> getArguments() {
if(arguments!=null)
return arguments;
arguments = new ArrayList<String>();
arguments = new ArrayList<>();
try {
byte[] cmdline = readFileToByteArray(getFile("cmdline"));
int pos=0;
......@@ -972,6 +1001,7 @@ public abstract class ProcessTree implements Iterable<OSProcess>, IProcessTree,
return arguments;
}
@Nonnull
public synchronized EnvVars getEnvironmentVariables() {
if(envVars !=null)
return envVars;
......@@ -1175,15 +1205,17 @@ public abstract class ProcessTree implements Iterable<OSProcess>, IProcessTree,
}
}
@CheckForNull
public OSProcess getParent() {
return get(ppid);
}
@Nonnull
public synchronized List<String> getArguments() {
if (arguments != null)
return arguments;
arguments = new ArrayList<String>(argc);
arguments = new ArrayList<>(argc);
if (argc == 0) {
return arguments;
}
......@@ -1225,6 +1257,7 @@ public abstract class ProcessTree implements Iterable<OSProcess>, IProcessTree,
return arguments;
}
@Nonnull
public synchronized EnvVars getEnvironmentVariables() {
if(envVars != null)
return envVars;
......@@ -1462,15 +1495,17 @@ public abstract class ProcessTree implements Iterable<OSProcess>, IProcessTree,
}
@CheckForNull
public OSProcess getParent() {
return get(ppid);
}
@Nonnull
public synchronized List<String> getArguments() {
if(arguments!=null)
return arguments;
arguments = new ArrayList<String>(argc);
arguments = new ArrayList<>(argc);
if (argc == 0) {
return arguments;
}
......@@ -1501,6 +1536,7 @@ public abstract class ProcessTree implements Iterable<OSProcess>, IProcessTree,
return arguments;
}
@Nonnull
public synchronized EnvVars getEnvironmentVariables() {
if(envVars !=null)
return envVars;
......@@ -1656,10 +1692,12 @@ public abstract class ProcessTree implements Iterable<OSProcess>, IProcessTree,
this.ppid = ppid;
}
@CheckForNull
public OSProcess getParent() {
return get(ppid);
}
@Nonnull
public synchronized EnvVars getEnvironmentVariables() {
if(envVars !=null)
return envVars;
......@@ -1667,6 +1705,7 @@ public abstract class ProcessTree implements Iterable<OSProcess>, IProcessTree,
return envVars;
}
@Nonnull
public List<String> getArguments() {
if(arguments !=null)
return arguments;
......@@ -1678,7 +1717,7 @@ public abstract class ProcessTree implements Iterable<OSProcess>, IProcessTree,
try {
// allocate them first, so that the parse error wil result in empty data
// and avoid retry.
arguments = new ArrayList<String>();
arguments = new ArrayList<>();
envVars = new EnvVars();
IntByReference intByRef = new IntByReference();
......@@ -1847,13 +1886,14 @@ public abstract class ProcessTree implements Iterable<OSProcess>, IProcessTree,
processes.put(e.getKey(),new RemoteProcess(e.getValue(),ch));
}
@CheckForNull
@Override
public OSProcess get(Process proc) {
public OSProcess get(@Nonnull Process proc) {
return null;
}
@Override
public void killAll(Map<String, String> modelEnvVars) throws InterruptedException {
public void killAll(@Nonnull Map<String, String> modelEnvVars) throws InterruptedException {
proxy.killAll(modelEnvVars);
}
......@@ -1871,6 +1911,7 @@ public abstract class ProcessTree implements Iterable<OSProcess>, IProcessTree,
this.proxy = ch.export(IOSProcess.class,proxy);
}
@CheckForNull
public OSProcess getParent() {
IOSProcess p = proxy.getParent();
if (p==null) return null;
......@@ -1885,10 +1926,12 @@ public abstract class ProcessTree implements Iterable<OSProcess>, IProcessTree,
proxy.killRecursively();
}
@Nonnull
public List<String> getArguments() {
return proxy.getArguments();
}
@Nonnull
public EnvVars getEnvironmentVariables() {
return proxy.getEnvironmentVariables();
}
......
......@@ -3,6 +3,8 @@ package hudson.util;
import hudson.EnvVars;
import hudson.util.ProcessTree.ProcessCallable;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import java.io.IOException;
import java.lang.reflect.Proxy;
import java.util.List;
......@@ -17,15 +19,18 @@ import java.util.Map;
*/
public class ProcessTreeRemoting {
public interface IProcessTree {
void killAll(Map<String, String> modelEnvVars) throws InterruptedException;
void killAll(@Nonnull Map<String, String> modelEnvVars) throws InterruptedException;
}
public interface IOSProcess {
int getPid();
@CheckForNull
IOSProcess getParent();
void kill() throws InterruptedException;
void killRecursively() throws InterruptedException;
@Nonnull
List<String> getArguments();
@Nonnull
EnvVars getEnvironmentVariables();
<T> T act(ProcessCallable<T> callable) throws IOException, InterruptedException;
}
......
......@@ -47,9 +47,9 @@ import java.util.logging.Logger;
class DefaultRuntimeSpringConfiguration implements RuntimeSpringConfiguration {
private static final Logger LOGGER = Logger.getLogger(DefaultRuntimeSpringConfiguration.class.getName());
private StaticWebApplicationContext context;
private Map<String,BeanConfiguration> beanConfigs = new HashMap<String,BeanConfiguration>();
private Map<String,BeanDefinition> beanDefinitions = new HashMap<String,BeanDefinition>();
private List<String> beanNames = new ArrayList<String>();
private Map<String,BeanConfiguration> beanConfigs = new HashMap<>();
private Map<String,BeanDefinition> beanDefinitions = new HashMap<>();
private List<String> beanNames = new ArrayList<>();
public DefaultRuntimeSpringConfiguration() {
super();
......
......@@ -285,7 +285,7 @@ public class HistoryWidget<O extends ModelObject,T> extends Widget {
return null;
}
try {
return new Long(paramVal);
return Long.valueOf(paramVal);
} catch (NumberFormatException nfe) {
return null;
}
......
......@@ -31,7 +31,7 @@ public class Configuration {
public static boolean getBooleanConfigParameter(String name, boolean defaultValue) {
String value = getStringConfigParameter(name,null);
return (value==null)?defaultValue:Boolean.valueOf(value);
return (value==null)?defaultValue:Boolean.parseBoolean(value);
}
public static String getStringConfigParameter(String name, String defaultValue) {
......
......@@ -316,6 +316,9 @@ public class Jenkins extends AbstractCIBase implements DirectlyModifiableTopLeve
ModelObjectWithContextMenu, ModelObjectWithChildren, OnMaster {
private transient final Queue queue;
// flag indicating if we have loaded the jenkins configuration or not yet.
private transient volatile boolean configLoaded = false;
/**
* Stores various objects scoped to {@link Jenkins}.
*/
......@@ -2093,6 +2096,7 @@ public class Jenkins extends AbstractCIBase implements DirectlyModifiableTopLeve
* Returns all {@link Node}s in the system, excluding {@link Jenkins} instance itself which
* represents the master.
*/
@Nonnull
public List<Node> getNodes() {
return nodes.getNodes();
}
......@@ -3080,14 +3084,13 @@ public class Jenkins extends AbstractCIBase implements DirectlyModifiableTopLeve
// load from disk
cfg.unmarshal(Jenkins.this);
}
configLoaded = true;
try {
checkRawBuildsDir(buildsDir);
setBuildsAndWorkspacesDir();
} catch (InvalidBuildsDir invalidBuildsDir) {
throw new IOException(invalidBuildsDir);
}
}
private void setBuildsAndWorkspacesDir() throws IOException, InvalidBuildsDir {
......@@ -3288,13 +3291,31 @@ public class Jenkins extends AbstractCIBase implements DirectlyModifiableTopLeve
* Save the settings to a file.
*/
public synchronized void save() throws IOException {
if(BulkChange.contains(this)) return;
if (initLevel == InitMilestone.COMPLETED) {
InitMilestone currentMilestone = initLevel;
if (!configLoaded) {
// someone is trying to save the config before all extensions are loaded (and possibly after as the task
// may run in parallel with other tasks. OMG...!!! this is generally very bad and can lead to dataloss
LOGGER.log(Level.SEVERE,
"An attempt to save Jenkins'' global configuration before it has been loaded has been "
+ "made during milestone " + currentMilestone
+ ". This is indicative of a bug in the caller and may lead to full or partial loss of "
+ "configuration.",
new IllegalStateException("call trace"));
// at this point we may want to terminate but the save may be called from a different thread and we
// can not call System.halt() because we could be running in a container :(
// for now just deny the save (the data will be replaced when we do load anyway
throw new IllegalStateException("An attempt to save the global configuration was made before it was loaded");
}
if(BulkChange.contains(this)) {
return;
}
if (currentMilestone == InitMilestone.COMPLETED) {
LOGGER.log(FINE, "setting version {0} to {1}", new Object[] {version, VERSION});
version = VERSION;
} else {
LOGGER.log(FINE, "refusing to set version {0} to {1} during {2}", new Object[] {version, VERSION, initLevel});
LOGGER.log(FINE, "refusing to set version {0} to {1} during {2}", new Object[] {version, VERSION, currentMilestone});
}
getConfigFile().write(this);
......
......@@ -15,5 +15,5 @@ import org.kohsuke.accmod.restrictions.NoExternalUse;
@Extension(ordinal = 1000) @Symbol("frameOptions")
public class FrameOptionsPageDecorator extends PageDecorator {
@Restricted(NoExternalUse.class)
public static boolean enabled = Boolean.valueOf(SystemProperties.getString(FrameOptionsPageDecorator.class.getName() + ".enabled", "true"));
public static boolean enabled = Boolean.parseBoolean(SystemProperties.getString(FrameOptionsPageDecorator.class.getName() + ".enabled", "true"));
}
......@@ -365,9 +365,9 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener {
if (classpath != null) {
Path actualClasspath = classpath.concatSystemClasspath("ignore");
String[] pathElements = actualClasspath.list();
for (int i = 0; i < pathElements.length; ++i) {
for (String pathElement : pathElements) {
try {
addPathElement(pathElements[i]);
addPathElement(pathElement);
} catch (BuildException e) {
// ignore path elements which are invalid
// relative to the project
......
......@@ -403,7 +403,7 @@ public class XStreamDOM {
private static class Pending {
final String tagName;
List<XStreamDOM> children;
List<String> attributes = new ArrayList<String>();
List<String> attributes = new ArrayList<>();
String value;
private Pending(String tagName) {
......@@ -412,7 +412,7 @@ public class XStreamDOM {
void addChild(XStreamDOM dom) {
if (children==null)
children = new ArrayList<XStreamDOM>();
children = new ArrayList<>();
children.add(dom);
}
......@@ -421,7 +421,7 @@ public class XStreamDOM {
}
}
private final Stack<Pending> pendings = new Stack<Pending>();
private final Stack<Pending> pendings = new Stack<>();
public WriterImpl() {
pendings.push(new Pending(null)); // to get the final result
......@@ -522,7 +522,7 @@ public class XStreamDOM {
List<XStreamDOM> children = null;
String value = null;
if (r.hasMoreChildren()) {
children = new ArrayList<XStreamDOM>();
children = new ArrayList<>();
while (r.hasMoreChildren()) {
children.add(unmarshal(r, context));
}
......
......@@ -138,6 +138,6 @@ public class EnvVarsTest {
OverrideOrderCalculator calc = new OverrideOrderCalculator(env, overrides);
List<String> order = calc.getOrderedVariableNames();
assertEquals(Arrays.asList("B", "A", "C"), order.subList(0, 3));
assertEquals(Sets.newHashSet("E", "D"), new HashSet<String>(order.subList(3, order.size())));
assertEquals(Sets.newHashSet("E", "D"), new HashSet<>(order.subList(3, order.size())));
}
}
......@@ -132,7 +132,7 @@ public class FilePathTest {
}
private List<Future<Integer>> whenFileIsCopied100TimesConcurrently(final File file) throws InterruptedException {
List<Callable<Integer>> r = new ArrayList<Callable<Integer>>();
List<Callable<Integer>> r = new ArrayList<>();
for (int i=0; i<100; i++) {
r.add(new Callable<Integer>() {
public Integer call() throws Exception {
......@@ -371,36 +371,36 @@ public class FilePathTest {
@Test public void list() throws Exception {
File baseDir = temp.getRoot();
final Set<FilePath> expected = new HashSet<FilePath>();
final Set<FilePath> expected = new HashSet<>();
expected.add(createFilePath(baseDir, "top", "sub", "app.log"));
expected.add(createFilePath(baseDir, "top", "sub", "trace.log"));
expected.add(createFilePath(baseDir, "top", "db", "db.log"));
expected.add(createFilePath(baseDir, "top", "db", "trace.log"));
final FilePath[] result = new FilePath(baseDir).list("**");
assertEquals(expected, new HashSet<FilePath>(Arrays.asList(result)));
assertEquals(expected, new HashSet<>(Arrays.asList(result)));
}
@Test public void listWithExcludes() throws Exception {
File baseDir = temp.getRoot();
final Set<FilePath> expected = new HashSet<FilePath>();
final Set<FilePath> expected = new HashSet<>();
expected.add(createFilePath(baseDir, "top", "sub", "app.log"));
createFilePath(baseDir, "top", "sub", "trace.log");
expected.add(createFilePath(baseDir, "top", "db", "db.log"));
createFilePath(baseDir, "top", "db", "trace.log");
final FilePath[] result = new FilePath(baseDir).list("**", "**/trace.log");
assertEquals(expected, new HashSet<FilePath>(Arrays.asList(result)));
assertEquals(expected, new HashSet<>(Arrays.asList(result)));
}
@Test public void listWithDefaultExcludes() throws Exception {
File baseDir = temp.getRoot();
final Set<FilePath> expected = new HashSet<FilePath>();
final Set<FilePath> expected = new HashSet<>();
expected.add(createFilePath(baseDir, "top", "sub", "backup~"));
expected.add(createFilePath(baseDir, "top", "CVS", "somefile,v"));
expected.add(createFilePath(baseDir, "top", ".git", "config"));
// none of the files are included by default (default includes true)
assertEquals(0, new FilePath(baseDir).list("**", "").length);
final FilePath[] result = new FilePath(baseDir).list("**", "", false);
assertEquals(expected, new HashSet<FilePath>(Arrays.asList(result)));
assertEquals(expected, new HashSet<>(Arrays.asList(result)));
}
@Issue("JENKINS-11073")
......
......@@ -62,7 +62,7 @@ public class UtilTest {
@Test
public void testReplaceMacro() {
Map<String,String> m = new HashMap<String,String>();
Map<String,String> m = new HashMap<>();
m.put("A","a");
m.put("A.B","a-b");
m.put("AA","aa");
......
......@@ -178,11 +178,11 @@ public class ListJobsCommandTest {
@Override
protected boolean matchesSafely(ByteArrayOutputStream item) {
final HashSet<String> jobs = new HashSet<String>(
final HashSet<String> jobs = new HashSet<>(
Arrays.asList(item.toString().split(System.getProperty("line.separator")))
);
return new HashSet<String>(Arrays.asList(expected)).equals(jobs);
return new HashSet<>(Arrays.asList(expected)).equals(jobs);
}
@Override
......
......@@ -54,7 +54,7 @@ public class ActionableTest {
}
static class ActionableOverride extends Actionable {
ArrayList<Action> specialActions = new ArrayList<Action>();
ArrayList<Action> specialActions = new ArrayList<>();
@Override
public String getDisplayName() {
......
......@@ -112,7 +112,7 @@ public class ParametersActionTest {
assertEquals(2, vars.size());
parametersAction.createVariableResolver(build);
LinkedList<BuildWrapper> wrappers = new LinkedList<BuildWrapper>();
LinkedList<BuildWrapper> wrappers = new LinkedList<>();
parametersAction.createBuildWrappers(build, wrappers);
assertEquals(0, wrappers.size());
......
......@@ -46,7 +46,7 @@ public class ViewTest {
TopLevelItem item2 = Mockito.mock(TopLevelItem.class);
Mockito.when(item2.getSearchUrl()).thenReturn(url2);
Mockito.when(item2.getDisplayName()).thenReturn(displayName2);
Collection<TopLevelItem> items = new ArrayList<TopLevelItem>();
Collection<TopLevelItem> items = new ArrayList<>();
items.add(item1);
items.add(item2);
......@@ -62,7 +62,7 @@ public class ViewTest {
SearchIndex index = sib.make();
// now make sure we can fetch item1 from the index
List<SearchItem> result = new ArrayList<SearchItem>();
List<SearchItem> result = new ArrayList<>();
index.find(displayName1, result);
assertEquals(1, result.size());
SearchItem actual = result.get(0);
......
......@@ -29,7 +29,7 @@ public class CronTabDayOfWeekLocaleTest {
@Parameters
public static Collection<Object[]> parameters() {
final Locale[] locales = Locale.getAvailableLocales();
final Collection<Object[]> parameters = new ArrayList<Object[]>();
final Collection<Object[]> parameters = new ArrayList<>();
for (final Locale locale : locales) {
final Calendar cal = Calendar.getInstance(locale);
if (GregorianCalendar.class.equals(cal.getClass())) {
......
......@@ -20,7 +20,7 @@ import java.util.GregorianCalendar;
public class CronTabEventualityTest {
@Parameterized.Parameters
public static Collection<Object[]> parameters() {
Collection<Object[]> parameters = new ArrayList<Object[]>();
Collection<Object[]> parameters = new ArrayList<>();
parameters.add(new Object[]{"zero", Hash.zero()});
parameters.add(new Object[]{"seed1", Hash.from("seed1")});
parameters.add(new Object[]{"seed2", Hash.from("seed2")});
......
......@@ -272,7 +272,7 @@ public class CronTabTest {
@Test public void repeatedHash() throws Exception {
CronTabList tabs = CronTabList.create("H * * * *\nH * * * *", Hash.from("seed"));
List<Integer> times = new ArrayList<Integer>();
List<Integer> times = new ArrayList<>();
for (int i = 0; i < 60; i++) {
if (tabs.check(new GregorianCalendar(2013, 3, 3, 11, i, 0))) {
times.add(i);
......@@ -306,7 +306,7 @@ public class CronTabTest {
@Issue("JENKINS-9283")
@Test public void testTimezone() throws Exception {
CronTabList tabs = CronTabList.create("TZ=Australia/Sydney\nH * * * *\nH * * * *", Hash.from("seed"));
List<Integer> times = new ArrayList<Integer>();
List<Integer> times = new ArrayList<>();
for (int i = 0; i < 60; i++) {
GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
calendar.set(2013, Calendar.APRIL, 3, 11, i, 0);
......
......@@ -93,7 +93,7 @@ public class SearchTest {
SuggestedItem suggestedHit = new SuggestedItem(searchItemHit);
SuggestedItem suggestedNoHit = new SuggestedItem(searchItemNoHit);
ArrayList<SuggestedItem> list = new ArrayList<SuggestedItem>();
ArrayList<SuggestedItem> list = new ArrayList<>();
list.add(suggestedNoHit);
list.add(suggestedHit); // make sure the hit is the second item
......
......@@ -27,7 +27,7 @@ public class ChannelPingerTest {
@Mock private Channel mockChannel;
private Map<String, String> savedSystemProperties = new HashMap<String, String>();
private Map<String, String> savedSystemProperties = new HashMap<>();
@Before
public void setUp() throws Exception {
......
......@@ -200,9 +200,9 @@ public class ArgumentListBuilderTest {
@Test
public void addKeyValuePairsFromPropertyString() throws IOException {
final Map<String, String> map = new HashMap<String, String>();
final Map<String, String> map = new HashMap<>();
map.put("PATH", "C:\\Windows");
final VariableResolver<String> resolver = new VariableResolver.ByMap<String>(map);
final VariableResolver<String> resolver = new VariableResolver.ByMap<>(map);
final String properties = "my.path=$PATH";
......@@ -217,7 +217,7 @@ public class ArgumentListBuilderTest {
@Test
public void numberOfBackslashesInPropertiesShouldBePreservedAfterMacroExpansion() throws IOException {
final Map<String, String> map = new HashMap<String, String>();
final Map<String, String> map = new HashMap<>();
map.put("ONE", "one\\backslash");
map.put("TWO", "two\\\\backslashes");
map.put("FOUR", "four\\\\\\\\backslashes");
......@@ -230,7 +230,7 @@ public class ArgumentListBuilderTest {
;
final String args = new ArgumentListBuilder()
.addKeyValuePairsFromPropertyString("", properties, new VariableResolver.ByMap<String>(map))
.addKeyValuePairsFromPropertyString("", properties, new VariableResolver.ByMap<>(map))
.toString()
;
......
......@@ -45,7 +45,7 @@ public class ConsistentHashTest {
*/
@Test
public void basic() {
ConsistentHash<String> hash = new ConsistentHash<String>();
ConsistentHash<String> hash = new ConsistentHash<>();
hash.add("data1");
hash.add("data2");
hash.add("data3");
......@@ -60,7 +60,7 @@ public class ConsistentHashTest {
// list them up
Iterator<String> itr = hash.list(Integer.MIN_VALUE).iterator();
Set<String> all = new HashSet<String>();
Set<String> all = new HashSet<>();
String z = itr.next();
all.add(z);
assertEquals(z,x);
......@@ -75,7 +75,7 @@ public class ConsistentHashTest {
*/
@Test
public void unevenDistribution() {
ConsistentHash<String> hash = new ConsistentHash<String>();
ConsistentHash<String> hash = new ConsistentHash<>();
hash.add("even",10);
hash.add("odd",100);
......@@ -97,12 +97,12 @@ public class ConsistentHashTest {
*/
@Test
public void removal() {
ConsistentHash<Integer> hash = new ConsistentHash<Integer>();
ConsistentHash<Integer> hash = new ConsistentHash<>();
for( int i=0; i<10; i++ )
hash.add(i);
// what was the mapping before the mutation?
Map<Integer,Integer> before = new HashMap<Integer, Integer>();
Map<Integer,Integer> before = new HashMap<>();
Random r = new Random(0);
for(int i=0; i<1000; i++) {
int q = r.nextInt();
......@@ -121,7 +121,7 @@ public class ConsistentHashTest {
@Test
public void emptyBehavior() {
ConsistentHash<String> hash = new ConsistentHash<String>();
ConsistentHash<String> hash = new ConsistentHash<>();
assertEquals(0, hash.countAllPoints());
assertFalse(hash.list(0).iterator().hasNext());
assertNull(hash.lookup(0));
......@@ -130,7 +130,7 @@ public class ConsistentHashTest {
@Test
public void countAllPoints() {
ConsistentHash<String> hash = new ConsistentHash<String>();
ConsistentHash<String> hash = new ConsistentHash<>();
assertEquals(0, hash.countAllPoints());
hash.add("foo", 10);
assertEquals(10, hash.countAllPoints());
......@@ -142,7 +142,7 @@ public class ConsistentHashTest {
@Test
public void defaultReplicationIsOneHundred() {
ConsistentHash<String> hash = new ConsistentHash<String>();
ConsistentHash<String> hash = new ConsistentHash<>();
assertEquals(0, hash.countAllPoints());
hash.add("foo");
assertEquals(100, hash.countAllPoints());
......@@ -150,7 +150,7 @@ public class ConsistentHashTest {
@Test
public void setCustomDefaultReplication() {
ConsistentHash<String> hash = new ConsistentHash<String>((ConsistentHash.Hash<String>) ConsistentHash.DEFAULT_HASH, 7);
ConsistentHash<String> hash = new ConsistentHash<>((ConsistentHash.Hash<String>) ConsistentHash.DEFAULT_HASH, 7);
assertEquals(0, hash.countAllPoints());
hash.add("foo");
assertEquals(7, hash.countAllPoints());
......@@ -166,7 +166,7 @@ public class ConsistentHashTest {
};
try {
ConsistentHash<String> hash = new ConsistentHash<String>(hashFunction);
ConsistentHash<String> hash = new ConsistentHash<>(hashFunction);
hash.add("foo");
fail("Didn't use custom hash function");
} catch (RuntimeException e) {
......@@ -179,14 +179,14 @@ public class ConsistentHashTest {
*/
@Test
public void speed() {
Map<String,Integer> data = new Hash<String, Integer>();
Map<String,Integer> data = new Hash<>();
for (int i = 0; i < 1000; i++)
data.put("node" + i,100);
data.put("tail",100);
long start = System.currentTimeMillis();
for (int j=0; j<10; j++) {
ConsistentHash<String> b = new ConsistentHash<String>();
ConsistentHash<String> b = new ConsistentHash<>();
b.addAll(data);
}
......
......@@ -35,8 +35,8 @@ import org.junit.Test;
*/
public class CopyOnWriteMapTest {
public static final class HashData {
CopyOnWriteMap.Hash<String,String> map1 = new CopyOnWriteMap.Hash<String,String>();
HashMap<String,String> map2 = new HashMap<String,String>();
CopyOnWriteMap.Hash<String,String> map1 = new CopyOnWriteMap.Hash<>();
HashMap<String,String> map2 = new HashMap<>();
}
/**
......@@ -71,12 +71,12 @@ public class CopyOnWriteMapTest {
CopyOnWriteMap.Tree<String,String> map1;
TreeMap<String,String> map2;
TreeData() {
map1 = new CopyOnWriteMap.Tree<String,String>();
map2 = new TreeMap<String,String>();
map1 = new CopyOnWriteMap.Tree<>();
map2 = new TreeMap<>();
}
TreeData(Comparator<String> comparator) {
map1 = new CopyOnWriteMap.Tree<String,String>(comparator);
map2 = new TreeMap<String,String>(comparator);
map1 = new CopyOnWriteMap.Tree<>(comparator);
map2 = new TreeMap<>(comparator);
}
}
......@@ -115,8 +115,8 @@ public class CopyOnWriteMapTest {
}
@Test public void equalsHashCodeToString() throws Exception {
Map<String,Integer> m1 = new TreeMap<String,Integer>();
Map<String,Integer> m2 = new CopyOnWriteMap.Tree<String,Integer>();
Map<String,Integer> m1 = new TreeMap<>();
Map<String,Integer> m2 = new CopyOnWriteMap.Tree<>();
m1.put("foo", 5);
m1.put("bar", 7);
m2.put("foo", 5);
......
......@@ -32,7 +32,7 @@ public class CyclicGraphDetectorTest {
}
Set<String> nodes() {
Set<String> nodes = new LinkedHashSet<String>();
Set<String> nodes = new LinkedHashSet<>();
for (Edge e : this) {
nodes.add(e.src);
nodes.add(e.dst);
......@@ -41,7 +41,7 @@ public class CyclicGraphDetectorTest {
}
Set<String> edges(String from) {
Set<String> edges = new LinkedHashSet<String>();
Set<String> edges = new LinkedHashSet<>();
for (Edge e : this) {
if (e.src.equals(from))
edges.add(e.dst);
......
......@@ -21,7 +21,7 @@ public class PackedMapTest {
@Test
public void basic() {
Map<String,String> o = new TreeMap<String, String>();
Map<String,String> o = new TreeMap<>();
o.put("a","b");
o.put("c","d");
......
......@@ -58,7 +58,7 @@ public class RunListTest {
when(r1.getTimeInMillis()).thenReturn(200L);
when(r2.getTimeInMillis()).thenReturn(300L);
ArrayList<Run> list = new ArrayList<Run>();
ArrayList<Run> list = new ArrayList<>();
list.add(r2);
list.add(r1);
......
......@@ -271,7 +271,7 @@ public class XStream2Test {
}
public static class Foo2 {
ConcurrentHashMap<String,String> m = new ConcurrentHashMap<String,String>();
ConcurrentHashMap<String,String> m = new ConcurrentHashMap<>();
}
@Issue("SECURITY-105")
......
......@@ -73,7 +73,7 @@ public class AbstractLazyLoadRunMapTest {
return new FakeMap(getDir()) {
@Override
protected BuildReference<Build> createReference(Build r) {
return new BuildReference<Build>(Integer.toString(r.n), /* pretend referent expired */ null);
return new BuildReference<>(Integer.toString(r.n), /* pretend referent expired */ null);
}
};
}
......
......@@ -36,7 +36,7 @@ import java.util.Arrays;
* @author Kohsuke Kawaguchi
*/
public class SortedListTest {
SortedList<String> l = new SortedList<String>(new ArrayList<String>(Arrays.asList("B","D","F")));
SortedList<String> l = new SortedList<>(new ArrayList<>(Arrays.asList("B", "D", "F")));
@Test
public void testCeil() {
......@@ -106,7 +106,7 @@ public class SortedListTest {
@Test
public void testClone() {
final int originalSize = l.size();
SortedList<String> l2 = new SortedList<String>(l);
SortedList<String> l2 = new SortedList<>(l);
assertEquals(originalSize, l2.size());
assertEquals(originalSize, l.size());
for (int i = 0; i < originalSize; i++) {
......
......@@ -24,6 +24,6 @@ public class ConfidentialStoreRule extends ExternalResource {
}
static {
ConfidentialStore.TEST = new ThreadLocal<ConfidentialStore>();
ConfidentialStore.TEST = new ThreadLocal<>();
}
}
......@@ -124,7 +124,7 @@ public class XStreamDOMTest {
public static class Name_That_Gets_Escaped {}
public static class DomInMap {
Map<String,XStreamDOM> values = new HashMap<String, XStreamDOM>();
Map<String,XStreamDOM> values = new HashMap<>();
}
@Test
......
......@@ -45,24 +45,24 @@ public class PluginTest {
@Issue({"SECURITY-131", "SECURITY-155", "SECURITY-705"})
@Test public void doDynamic() throws Exception {
((TestPluginManager) r.jenkins.pluginManager).installDetachedPlugin("credentials");
r.createWebClient().goTo("plugin/credentials/images/24x24/credentials.png", "image/png");
r.createWebClient().goTo("plugin/credentials/images/../images/24x24/credentials.png", "image/png"); // collapsed somewhere before it winds up in restOfPath
r.createWebClient().assertFails("plugin/credentials/images/%2E%2E/images/24x24/credentials.png", HttpServletResponse.SC_INTERNAL_SERVER_ERROR); // IAE from TokenList.<init>
r.createWebClient().assertFails("plugin/credentials/images/%252E%252E/images/24x24/credentials.png", HttpServletResponse.SC_BAD_REQUEST); // SECURITY-131
r.createWebClient().assertFails("plugin/credentials/images/%25252E%25252E/images/24x24/credentials.png", HttpServletResponse.SC_BAD_REQUEST); // just checking
((TestPluginManager) r.jenkins.pluginManager).installDetachedPlugin("matrix-auth");
r.createWebClient().goTo("plugin/matrix-auth/images/user-disabled.png", "image/png");
r.createWebClient().goTo("plugin/matrix-auth/images/../images/user-disabled.png", "image/png"); // collapsed somewhere before it winds up in restOfPath
r.createWebClient().assertFails("plugin/matrix-auth/images/%2E%2E/images/user-disabled.png", HttpServletResponse.SC_INTERNAL_SERVER_ERROR); // IAE from TokenList.<init>
r.createWebClient().assertFails("plugin/matrix-auth/images/%252E%252E/images/user-disabled.png", HttpServletResponse.SC_BAD_REQUEST); // SECURITY-131
r.createWebClient().assertFails("plugin/matrix-auth/images/%25252E%25252E/images/user-disabled.png", HttpServletResponse.SC_BAD_REQUEST); // just checking
// SECURITY-705:
r.createWebClient().assertFails("plugin/credentials/images/..%2fWEB-INF/licenses.xml", HttpServletResponse.SC_BAD_REQUEST);
r.createWebClient().assertFails("plugin/credentials/./credentials.jpi", /* Path collapsed to simply `credentials.jpi` before entering */ HttpServletResponse.SC_NOT_FOUND);
r.createWebClient().assertFails("plugin/credentials/images/%2e%2e%2fWEB-INF/licenses.xml", HttpServletResponse.SC_BAD_REQUEST);
r.createWebClient().assertFails("plugin/credentials/images/%2e.%2fWEB-INF/licenses.xml", HttpServletResponse.SC_BAD_REQUEST);
r.createWebClient().assertFails("plugin/credentials/images/..%2f..%2f..%2f" + r.jenkins.getRootDir().getName() + "%2fsecrets%2fmaster.key", HttpServletResponse.SC_BAD_REQUEST);
r.createWebClient().assertFails("plugin/credentials/" + r.jenkins.getRootDir() + "/secrets/master.key", /* ./ prepended anyway */ HttpServletResponse.SC_NOT_FOUND);
r.createWebClient().assertFails("plugin/matrix-auth/images/..%2fWEB-INF/licenses.xml", HttpServletResponse.SC_BAD_REQUEST);
r.createWebClient().assertFails("plugin/matrix-auth/./matrix-auth.jpi", /* Path collapsed to simply `credentials.jpi` before entering */ HttpServletResponse.SC_NOT_FOUND);
r.createWebClient().assertFails("plugin/matrix-auth/images/%2e%2e%2fWEB-INF/licenses.xml", HttpServletResponse.SC_BAD_REQUEST);
r.createWebClient().assertFails("plugin/matrix-auth/images/%2e.%2fWEB-INF/licenses.xml", HttpServletResponse.SC_BAD_REQUEST);
r.createWebClient().assertFails("plugin/matrix-auth/images/..%2f..%2f..%2f" + r.jenkins.getRootDir().getName() + "%2fsecrets%2fmaster.key", HttpServletResponse.SC_BAD_REQUEST);
r.createWebClient().assertFails("plugin/matrix-auth/" + r.jenkins.getRootDir() + "/secrets/master.key", /* ./ prepended anyway */ HttpServletResponse.SC_NOT_FOUND);
// SECURITY-155:
r.createWebClient().assertFails("plugin/credentials/WEB-INF/licenses.xml", HttpServletResponse.SC_BAD_REQUEST);
r.createWebClient().assertFails("plugin/credentials/META-INF/MANIFEST.MF", HttpServletResponse.SC_BAD_REQUEST);
r.createWebClient().assertFails("plugin/credentials/web-inf/licenses.xml", HttpServletResponse.SC_BAD_REQUEST);
r.createWebClient().assertFails("plugin/credentials/meta-inf/manifest.mf", HttpServletResponse.SC_BAD_REQUEST);
r.createWebClient().assertFails("plugin/matrix-auth/WEB-INF/licenses.xml", HttpServletResponse.SC_BAD_REQUEST);
r.createWebClient().assertFails("plugin/matrix-auth/META-INF/MANIFEST.MF", HttpServletResponse.SC_BAD_REQUEST);
r.createWebClient().assertFails("plugin/matrix-auth/web-inf/licenses.xml", HttpServletResponse.SC_BAD_REQUEST);
r.createWebClient().assertFails("plugin/matrix-auth/meta-inf/manifest.mf", HttpServletResponse.SC_BAD_REQUEST);
}
@Ignore("TODO observed to fail in CI with 404 due to external UC issues")
......@@ -76,6 +76,6 @@ public class PluginTest {
for (Future<UpdateCenter.UpdateCenterJob> job : pluginInstalled) {
job.get();
}
r.createWebClient().assertFails("plugin/credentials/.timestamp2", HttpServletResponse.SC_BAD_REQUEST);
r.createWebClient().assertFails("plugin/matrix-auth/.timestamp2", HttpServletResponse.SC_BAD_REQUEST);
}
}
......@@ -72,7 +72,7 @@ public class UsageStatisticsTest {
*/
@Test
public void roundtrip() throws Exception {
((TestPluginManager) j.jenkins.pluginManager).installDetachedPlugin("credentials");
((TestPluginManager) j.jenkins.pluginManager).installDetachedPlugin("matrix-auth");
j.createOnlineSlave();
warmUpNodeMonitorCache();
......@@ -116,7 +116,7 @@ public class UsageStatisticsTest {
assertThat("No duplicates", reported.contains(name), is(false));
reported.add(name);
}
assertThat(reported, hasItem("credentials"));
assertThat(reported, hasItem("matrix-auth"));
// Compare content to watch out for backwards compatibility
compareWithFile("jobs.json", sortJobTypes((JSONObject) o.get("jobs")));
......
......@@ -35,35 +35,41 @@ public class ProcessTreeKillerTest {
@Rule
public JenkinsRule j = new JenkinsRule();
private Process process;
@After
public void tearDown() throws Exception {
ProcessTree.vetoersExist = null;
if (null != process)
process.destroy();
}
}
@Test
public void manualAbortProcess() throws Exception {
ProcessTree.enabled = true;
FreeStyleProject project = j.createFreeStyleProject();
public void manualAbortProcess() throws Exception {
ProcessTree.enabled = true;
FreeStyleProject project = j.createFreeStyleProject();
// this contains a maven project with a single test that sleeps 5s.
project.setScm(new ExtractResourceSCM(getClass().getResource(
"ProcessTreeKiller-test-project.jar")));
project.getBuildersList().add(new Maven("install", "maven"));
// this contains a maven project with a single test that sleeps 5s.
project.setScm(new ExtractResourceSCM(getClass().getResource(
"ProcessTreeKiller-test-project.jar")));
project.getBuildersList().add(new Maven("install", "maven"));
// build the project, wait until tests are running, then cancel.
project.scheduleBuild2(0).waitForStart();
// build the project, wait until tests are running, then cancel.
project.scheduleBuild2(0).waitForStart();
FreeStyleBuild b = project.getLastBuild();
b.doStop();
Thread.sleep(1000);
Thread.sleep(1000);
// will fail (at least on windows) if test process is still running
b.getWorkspace().deleteRecursive();
}
// will fail (at least on windows) if test process is still running
b.getWorkspace().deleteRecursive();
}
@Test
public void killNullProcess() throws Exception {
ProcessTree.enabled = true;
ProcessTree.get().killAll(null, null);
}
@Test
@Issue("JENKINS-22641")
......@@ -85,7 +91,6 @@ public class ProcessTreeKillerTest {
@Test
public void doNotKillProcessWithCookie() throws Exception {
Assume.assumeFalse("This test does not involve windows", Functions.isWindows());
ProcessTree.enabled = true;
SpawnBuilder spawner = new SpawnBuilder();
......@@ -100,6 +105,7 @@ public class ProcessTreeKillerTest {
assertTrue("Process should be dead", !spawner.proc.isAlive());
}
}
public static final class SpawnBuilder extends TestBuilder {
private Proc proc;
......@@ -107,11 +113,14 @@ public class ProcessTreeKillerTest {
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
EnvVars envvars = build.getEnvironment(listener);
envvars.addLine("BUILD_ID=dontKillMe");
proc = launcher.launch().envs(envvars).cmds("nohup", "sleep", "100000").start();
final String[] cmd = Functions.isWindows()
? new String[]{"ping", "-n", "100000", "localhost"}
: new String[]{"nohup", "sleep", "100000"};
proc = launcher.launch().envs(envvars).cmds(cmd).start();
return true;
}
}
@Test
@Issue("JENKINS-9104")
public void considersKillingVetos() throws Exception {
......@@ -140,35 +149,35 @@ public class ProcessTreeKillerTest {
// Means the process is still running
}
}
@Test
@Issue("JENKINS-9104")
public void considersKillingVetosOnSlave() throws Exception {
// on some platforms where we fail to list any processes, this test will
// just not work
assumeTrue(ProcessTree.get() != ProcessTree.DEFAULT);
// Define a process we (shouldn't) kill
ProcessBuilder pb = new ProcessBuilder();
pb.environment().put("cookie", "testKeepDaemonsAlive");
if (File.pathSeparatorChar == ';') {
pb.command("cmd");
} else {
pb.command("sleep", "5m");
}
// Create an agent so we can tell it to kill the process
Slave s = j.createSlave();
s.toComputer().connect(false).get();
// Start the process
process = pb.start();
// Call killall (somewhat roundabout though) to (not) kill it
StringWriter out = new StringWriter();
s.createLauncher(new StreamTaskListener(out)).kill(ImmutableMap.of("cookie", "testKeepDaemonsAlive"));
try {
process.exitValue();
fail("Process should have been excluded from the killing");
......
......@@ -63,13 +63,11 @@ public class I18nTest {
@Issue("JENKINS-35270")
@Test
public void test_baseName_plugin() throws Exception {
((TestPluginManager) jenkinsRule.jenkins.pluginManager).installDetachedPlugin("credentials");
((TestPluginManager) jenkinsRule.jenkins.pluginManager).installDetachedPlugin("ssh-credentials");
((TestPluginManager) jenkinsRule.jenkins.pluginManager).installDetachedPlugin("ssh-slaves");
JSONObject response = jenkinsRule.getJSON("i18n/resourceBundle?baseName=hudson.plugins.sshslaves.Messages").getJSONObject();
((TestPluginManager) jenkinsRule.jenkins.pluginManager).installDetachedPlugin("matrix-auth");
JSONObject response = jenkinsRule.getJSON("i18n/resourceBundle?baseName=org.jenkinsci.plugins.matrixauth.Messages").getJSONObject();
Assert.assertEquals(response.toString(), "ok", response.getString("status"));
JSONObject data = response.getJSONObject("data");
Assert.assertEquals("The launch timeout must be a number.", data.getString("SSHConnector.LaunchTimeoutMustBeANumber"));
Assert.assertEquals("Matrix-based security", data.getString("GlobalMatrixAuthorizationStrategy.DisplayName"));
}
@Test
......
......@@ -294,24 +294,6 @@ THE SOFTWARE.
<!--
Detached plugins and their dependencies - detached plugins that used to be bundled plugins
-->
<artifactItem>
<groupId>org.jenkins-ci.plugins</groupId>
<artifactId>ssh-slaves</artifactId>
<version>1.15</version>
<type>hpi</type>
</artifactItem>
<artifactItem>
<groupId>org.jenkins-ci.plugins</groupId>
<artifactId>credentials</artifactId>
<version>2.1.2</version>
<type>hpi</type>
</artifactItem>
<artifactItem>
<groupId>org.jenkins-ci.plugins</groupId>
<artifactId>ssh-credentials</artifactId>
<version>1.10</version>
<type>hpi</type>
</artifactItem>
<artifactItem>
<groupId>org.jenkins-ci.plugins</groupId>
<artifactId>cvs</artifactId>
......@@ -330,12 +312,6 @@ THE SOFTWARE.
<version>1.1</version>
<type>hpi</type>
</artifactItem>
<artifactItem>
<groupId>org.jenkins-ci.plugins</groupId>
<artifactId>translation</artifactId>
<version>1.10</version>
<type>hpi</type>
</artifactItem>
<artifactItem>
<groupId>org.jenkins-ci.plugins</groupId>
<artifactId>external-monitor-job</artifactId>
......@@ -393,7 +369,7 @@ THE SOFTWARE.
<artifactItem>
<groupId>org.jenkins-ci.plugins</groupId>
<artifactId>script-security</artifactId>
<version>1.63</version>
<version>1.65</version>
<type>hpi</type>
</artifactItem>
<artifactItem>
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册