+ Build history widget only showed the last day of builds.
+ (Due to JENKINS-20892, even with this fix at most 20 builds are shown.)
+ (issue 21159)
+
+ Random class loading error mostly known to affect static analysis plugins.
+ (issue 12124)
+
+ After restarting Jenkins, users known only from changelogs could be shown as First Last _first.last@some.org_, breaking mail delivery.
+ (issue 16332)
+
+ CLI build -s -v command caused 100% CPU usage on the master.
+ (issue 20965)
+
+ Slave started from Java Web Start can now install itself as a systemd service.
+
+ Split the “raw HTML” markup formatter out of core into a bundled plugin.
+
@@ -448,8 +667,11 @@ Upcoming changes
Ensuring /log/all shows only INFO and above messages, even if custom loggers display FINE or below.
(issue 18959)
- Added a new monitor that detects and fixse out-of-order builds records.
+ Added a new monitor that detects and fixes out-of-order builds records.
(issue 18289)
+
NPE from MatrixConfiguration.newBuild.
(issue 17728)
+
+ Identify the short name of an uploaded plugin from the manifest, so it does not matter what the filename was.
+ (issue 4543)
NPE configuring Copy Artifact with Maven jobs.
(issue 17402)
diff --git a/cli/pom.xml b/cli/pom.xml
index 70ebb80c95..ce3173d6e2 100644
--- a/cli/pom.xml
+++ b/cli/pom.xml
@@ -5,7 +5,7 @@
pomorg.jenkins-ci.main
- 1.542-SNAPSHOT
+ 1.554-SNAPSHOTcli
diff --git a/cli/src/main/java/hudson/cli/CLI.java b/cli/src/main/java/hudson/cli/CLI.java
index 6549c39d73..2ee12793cd 100644
--- a/cli/src/main/java/hudson/cli/CLI.java
+++ b/cli/src/main/java/hudson/cli/CLI.java
@@ -261,7 +261,7 @@ public class CLI {
/**
* If the server advertises CLI endpoint, returns its location.
*/
- private CliPort getCliTcpPort(String url) throws IOException {
+ protected CliPort getCliTcpPort(String url) throws IOException {
URL _url = new URL(url);
if (_url.getHost()==null || _url.getHost().length()==0) {
throw new IOException("Invalid URL: "+url);
diff --git a/cli/src/main/resources/hudson/cli/client/Messages_pt_BR.properties b/cli/src/main/resources/hudson/cli/client/Messages_pt_BR.properties
index 1131ec8d17..106ba7ce84 100644
--- a/cli/src/main/resources/hudson/cli/client/Messages_pt_BR.properties
+++ b/cli/src/main/resources/hudson/cli/client/Messages_pt_BR.properties
@@ -1,6 +1,6 @@
# The MIT License
#
-# Copyright (c) 2004-2010, Sun Microsystems, Inc., Reginaldo L. Russinholi, Cleiber Silva
+# Copyright (c) 2004-2010, Sun Microsystems, Inc., Reginaldo L. Russinholi, Cleiber Silva, Fernando Boaglio
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
@@ -21,21 +21,21 @@
# THE SOFTWARE.
# Version mismatch. This CLI cannot work with this Hudson server
-CLI.VersionMismatch=A vers\ufffdo n\ufffdo coincide. Esta CLI n\ufffdo pode funcionar com este servidor Hudson
-# Hudson CLI\n\
-# Usage: java -jar jenkins-cli.jar [-s URL] command [opts...] args...\n\
-# Options:\n\
+CLI.VersionMismatch=A vers\u00e3o n\u00e3o coincide. Esta CLI n\u00e3o pode funcionar com este servidor Hudson
+# Hudson CLI\n\
+# Usage: java -jar jenkins-cli.jar [-s URL] command [opts...] args...\n\
+# Options:\n\
# \ -s URL : specify the server URL (defaults to the JENKINS_URL env var)\n\
-# \n\
-# The available commands depend on the server. Run the 'help' command to\n\
+# \n\
+# The available commands depend on the server. Run the 'help' command to\n\
# see the list.
CLI.Usage=Jenkins CLI\n\
- Uso: java -jar jenkins-cli.jar [-s URL] comando [op\ufffd\ufffdes...] par\ufffdmetros...\n\
- Op\ufffd\ufffdes:\n\
- \ -s URL : a URL do servidor (por padr\ufffdo a vari\ufffdvel de ambiente JENKINS_URL \ufffd usada)\n\
+ Uso: java -jar jenkins-cli.jar [-s URL] comando [op\u00e7\u00f5es...] par\u00e2metros...\n\
+ Op\u00e7\u00f5es:\n\
+ \ -s URL : a URL do servidor (por padr\u00e3o a vari\u00e1vel de ambiente JENKINS_URL \u00e9 usada)\n\
\n\
- Os comandos dispon\ufffdveis dependem do servidor. Execute o comando 'help' para\n\
+ Os comandos dispon\u00edveis dependem do servidor. Execute o comando 'help' para\n\
ver a lista.
# Neither -s nor the JENKINS_URL env var is specified.
-CLI.NoURL=N\ufffdo foi especificado nem '-s' e nem a vari\ufffdvel de ambiente JENKINS_URL
+CLI.NoURL=N\u00e3o foi especificado nem '-s' e nem a vari\u00e1vel de ambiente JENKINS_URL
diff --git a/core/pom.xml b/core/pom.xml
index 99a01997b0..fbebee0786 100644
--- a/core/pom.xml
+++ b/core/pom.xml
@@ -29,7 +29,7 @@ THE SOFTWARE.
org.jenkins-ci.mainpom
- 1.542-SNAPSHOT
+ 1.554-SNAPSHOT../pom.xml
@@ -194,7 +194,7 @@ THE SOFTWARE.
org.jenkins-ciannotation-indexer
- 1.6
+ 1.7org.jenkins-ci
@@ -219,7 +219,7 @@ THE SOFTWARE.
org.jvnet.hudsonxstream
- 1.4.4-jenkins-4
+ 1.4.4-jenkins-5jfree
@@ -517,14 +517,9 @@ THE SOFTWARE.
1.9
- org.jenkins-ci
- jinterop-wmi
- 1.1
-
-
- org.jenkins-ci
- windows-remote-command
- 1.4
+ org.kohsuke.jinterop
+ j-interop
+ 2.0.6-kohsuke-1org.kohsuke.metainf-services
@@ -558,12 +553,6 @@ THE SOFTWARE.
provided
-
- org.kohsuke
- owasp-html-sanitizer
- r88
-
-
org.mindrotjbcrypt
@@ -583,7 +572,7 @@ THE SOFTWARE.
com.google.guavaguava
-
+
com.jcraftjzlib
@@ -640,7 +629,6 @@ THE SOFTWARE.
com.infradna.toolbridge-method-injector
- 1.9
@@ -787,7 +775,7 @@ THE SOFTWARE.
org.kohsuke.staplermaven-stapler-plugin
-
+ ${maven-stapler-plugin.version}/lib/.*
diff --git a/core/src/main/java/hudson/ClassicPluginStrategy.java b/core/src/main/java/hudson/ClassicPluginStrategy.java
index f60166f34e..8279fb8ca1 100644
--- a/core/src/main/java/hudson/ClassicPluginStrategy.java
+++ b/core/src/main/java/hudson/ClassicPluginStrategy.java
@@ -56,7 +56,6 @@ import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.lang.reflect.Field;
-import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
@@ -72,7 +71,6 @@ import java.util.logging.Level;
import java.util.logging.Logger;
public class ClassicPluginStrategy implements PluginStrategy {
- private final ClassLoaderReflectionToolkit clt = new ClassLoaderReflectionToolkit();
/**
* Filter for jar files.
@@ -272,7 +270,9 @@ public class ClassicPluginStrategy implements PluginStrategy {
new DetachedPlugin("ldap","1.467.*","1.0"),
new DetachedPlugin("pam-auth","1.467.*","1.0"),
new DetachedPlugin("mailer","1.493.*","1.2"),
- new DetachedPlugin("matrix-auth","1.535.*","1.0.2")
+ new DetachedPlugin("matrix-auth","1.535.*","1.0.2"),
+ new DetachedPlugin("windows-slaves","1.547.*","1.0"),
+ new DetachedPlugin("antisamy-markup-formatter","1.553.*","1.0")
);
/**
@@ -567,10 +567,10 @@ public class ClassicPluginStrategy implements PluginStrategy {
if (PluginManager.FAST_LOOKUP) {
for (PluginWrapper pw : getTransitiveDependencies()) {
try {
- Class c = clt.findLoadedClass(pw.classLoader,name);
+ Class> c = ClassLoaderReflectionToolkit._findLoadedClass(pw.classLoader, name);
if (c!=null) return c;
- return clt.findClass(pw.classLoader,name);
- } catch (InvocationTargetException e) {
+ return ClassLoaderReflectionToolkit._findClass(pw.classLoader, name);
+ } catch (ClassNotFoundException e) {
//not found. try next
}
}
@@ -594,15 +594,11 @@ public class ClassicPluginStrategy implements PluginStrategy {
HashSet result = new HashSet();
if (PluginManager.FAST_LOOKUP) {
- try {
for (PluginWrapper pw : getTransitiveDependencies()) {
- Enumeration urls = clt.findResources(pw.classLoader, name);
+ Enumeration urls = ClassLoaderReflectionToolkit._findResources(pw.classLoader, name);
while (urls != null && urls.hasMoreElements())
result.add(urls.nextElement());
}
- } catch (InvocationTargetException e) {
- throw new Error(e);
- }
} else {
for (Dependency dep : dependencies) {
PluginWrapper p = pluginManager.getPlugin(dep.shortName);
@@ -620,14 +616,10 @@ public class ClassicPluginStrategy implements PluginStrategy {
@Override
protected URL findResource(String name) {
if (PluginManager.FAST_LOOKUP) {
- try {
for (PluginWrapper pw : getTransitiveDependencies()) {
- URL url = clt.findResource(pw.classLoader,name);
+ URL url = ClassLoaderReflectionToolkit._findResource(pw.classLoader, name);
if (url!=null) return url;
}
- } catch (InvocationTargetException e) {
- throw new Error(e);
- }
} else {
for (Dependency dep : dependencies) {
PluginWrapper p = pluginManager.getPlugin(dep.shortName);
diff --git a/core/src/main/java/hudson/FilePath.java b/core/src/main/java/hudson/FilePath.java
index df548f5583..9fd3134740 100644
--- a/core/src/main/java/hudson/FilePath.java
+++ b/core/src/main/java/hudson/FilePath.java
@@ -1406,6 +1406,45 @@ public final class FilePath implements Serializable {
});
}
+ /**
+ * Returns the number of unallocated bytes in the partition of that file.
+ * @since 1.542
+ */
+ public long getFreeDiskSpace() throws IOException, InterruptedException {
+ return act(new FileCallable() {
+ private static final long serialVersionUID = 1L;
+ @Override public Long invoke(File f, VirtualChannel channel) throws IOException {
+ return f.getFreeSpace();
+ }
+ });
+ }
+
+ /**
+ * Returns the total number of bytes in the partition of that file.
+ * @since 1.542
+ */
+ public long getTotalDiskSpace() throws IOException, InterruptedException {
+ return act(new FileCallable() {
+ private static final long serialVersionUID = 1L;
+ @Override public Long invoke(File f, VirtualChannel channel) throws IOException {
+ return f.getTotalSpace();
+ }
+ });
+ }
+
+ /**
+ * Returns the number of usable bytes in the partition of that file.
+ * @since 1.542
+ */
+ public long getUsableDiskSpace() throws IOException, InterruptedException {
+ return act(new FileCallable() {
+ private static final long serialVersionUID = 1L;
+ @Override public Long invoke(File f, VirtualChannel channel) throws IOException {
+ return f.getUsableSpace();
+ }
+ });
+ }
+
/**
* Sets the file permission.
*
diff --git a/core/src/main/java/hudson/Functions.java b/core/src/main/java/hudson/Functions.java
index 5c5652ed7e..4899606ae4 100644
--- a/core/src/main/java/hudson/Functions.java
+++ b/core/src/main/java/hudson/Functions.java
@@ -44,6 +44,7 @@ import hudson.model.JobPropertyDescriptor;
import hudson.model.ModelObject;
import hudson.model.Node;
import hudson.model.PageDecorator;
+import hudson.model.PaneStatusProperties;
import hudson.model.ParameterDefinition;
import hudson.model.ParameterDefinition.ParameterDescriptor;
import hudson.model.Project;
@@ -149,9 +150,9 @@ import org.kohsuke.stapler.jelly.InternationalizedStringExpression.RawHtmlArgume
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
+import hudson.util.RunList;
import java.util.concurrent.atomic.AtomicLong;
import org.kohsuke.accmod.Restricted;
-import org.kohsuke.accmod.restrictions.DoNotUse;
import org.kohsuke.accmod.restrictions.NoExternalUse;
/**
@@ -445,13 +446,14 @@ public class Functions {
return formatter.format(r);
}
- @Restricted(DoNotUse.class)
+ @Restricted(NoExternalUse.class)
public static String[] printLogRecordHtml(LogRecord r, LogRecord prior) {
String[] oldParts = prior == null ? new String[4] : logRecordPreformat(prior);
String[] newParts = logRecordPreformat(r);
for (int i = 0; i < /* not 4 */3; i++) {
newParts[i] = "" + newParts[i] + "";
}
+ newParts[3] = Util.xmlEscape(newParts[3]);
return newParts;
}
/**
@@ -508,6 +510,15 @@ public class Functions {
return c.getValue();
}
+ private static final Pattern ICON_SIZE = Pattern.compile("\\d+x\\d+");
+ @Restricted(NoExternalUse.class)
+ public static String validateIconSize(String iconSize) throws SecurityException {
+ if (!ICON_SIZE.matcher(iconSize).matches()) {
+ throw new SecurityException("invalid iconSize");
+ }
+ return iconSize;
+ }
+
/**
* Gets the suffix to use for YUI JavaScript.
*/
@@ -580,6 +591,10 @@ public class Functions {
return false;
}
+ public static boolean isCollapsed(String paneId) {
+ return PaneStatusProperties.forCurrentUser().isCollapsed(paneId);
+ }
+
/**
* Finds the given object in the ancestor list and returns its URL.
* This is used to determine the "current" URL assigned to the given object,
@@ -1426,7 +1441,8 @@ public class Functions {
}
/**
- * Returns a sub-list if the given list is bigger than the specified 'maxSize'
+ * Returns a sub-list if the given list is bigger than the specified {@code maxSize}.
+ * Warning: do not call this with a {@link RunList}, or you will break lazy loading!
*/
public static List subList(List base, int maxSize) {
if(maxSize$1")
- .replaceAll("(\\w{10})(?=\\w{3})", "$1")
+ return plain.replaceAll("([\\p{Punct}&&[^;]]+\\w)", "$1")
+ .replaceAll("([^\\p{Punct}\\s-]{10})(?=[^\\p{Punct}\\s-]{3})", "$1")
;
}
diff --git a/core/src/main/java/hudson/Main.java b/core/src/main/java/hudson/Main.java
index 45067f932b..6a176b2397 100644
--- a/core/src/main/java/hudson/Main.java
+++ b/core/src/main/java/hudson/Main.java
@@ -37,7 +37,6 @@ import java.io.Writer;
import java.net.HttpRetryException;
import java.net.HttpURLConnection;
import java.net.URL;
-import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.nio.charset.Charset;
@@ -104,14 +103,14 @@ public class Main {
}
}
- String projectNameEnc = URLEncoder.encode(projectName,"UTF-8").replaceAll("\\+","%20");
+ URL jobURL = new URL(home + "job/" + Util.encode(projectName).replace("/", "/job/") + "/");
{// check if the job name is correct
- HttpURLConnection con = open(new URL(home+"job/"+projectNameEnc+"/acceptBuildResult"));
+ HttpURLConnection con = open(new URL(jobURL, "acceptBuildResult"));
if (auth != null) con.setRequestProperty("Authorization", auth);
con.connect();
if(con.getResponseCode()!=200) {
- System.err.println(projectName+" is not a valid job name on "+home+" ("+con.getResponseMessage()+")");
+ System.err.println(jobURL + " is not a valid external job (" + con.getResponseCode() + " " + con.getResponseMessage() + ")");
return -1;
}
}
@@ -156,11 +155,11 @@ public class Main {
w.write(""+ret+""+(System.currentTimeMillis()-start)+"");
w.close();
- String location = home+"job/"+projectNameEnc+"/postBuildResult";
+ URL location = new URL(jobURL, "postBuildResult");
while(true) {
try {
// start a remote connection
- HttpURLConnection con = open(new URL(location));
+ HttpURLConnection con = open(location);
if (auth != null) con.setRequestProperty("Authorization", auth);
if (crumbField != null && crumbValue != null) {
con.setRequestProperty(crumbField, crumbValue);
@@ -182,7 +181,7 @@ public class Main {
} catch (HttpRetryException e) {
if(e.getLocation()!=null) {
// retry with the new location
- location = e.getLocation();
+ location = new URL(e.getLocation());
continue;
}
// otherwise failed for reasons beyond us.
diff --git a/core/src/main/java/hudson/PluginManager.java b/core/src/main/java/hudson/PluginManager.java
index dc657a9a0b..ace1d44d41 100644
--- a/core/src/main/java/hudson/PluginManager.java
+++ b/core/src/main/java/hudson/PluginManager.java
@@ -82,7 +82,6 @@ import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
-import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
@@ -941,8 +940,6 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas
*/
private ConcurrentMap> generatedClasses = new ConcurrentHashMap>();
- private ClassLoaderReflectionToolkit clt = new ClassLoaderReflectionToolkit();
-
public UberClassLoader() {
super(PluginManager.class.getClassLoader());
}
@@ -963,11 +960,11 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas
if (FAST_LOOKUP) {
for (PluginWrapper p : activePlugins) {
try {
- Class c = clt.findLoadedClass(p.classLoader,name);
+ Class> c = ClassLoaderReflectionToolkit._findLoadedClass(p.classLoader, name);
if (c!=null) return c;
// calling findClass twice appears to cause LinkageError: duplicate class def
- return clt.findClass(p.classLoader,name);
- } catch (InvocationTargetException e) {
+ return ClassLoaderReflectionToolkit._findClass(p.classLoader, name);
+ } catch (ClassNotFoundException e) {
//not found. try next
}
}
@@ -987,15 +984,11 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas
@Override
protected URL findResource(String name) {
if (FAST_LOOKUP) {
- try {
for (PluginWrapper p : activePlugins) {
- URL url = clt.findResource(p.classLoader,name);
+ URL url = ClassLoaderReflectionToolkit._findResource(p.classLoader, name);
if(url!=null)
return url;
}
- } catch (InvocationTargetException e) {
- throw new Error(e);
- }
} else {
for (PluginWrapper p : activePlugins) {
URL url = p.classLoader.getResource(name);
@@ -1010,13 +1003,9 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas
protected Enumeration findResources(String name) throws IOException {
List resources = new ArrayList();
if (FAST_LOOKUP) {
- try {
for (PluginWrapper p : activePlugins) {
- resources.addAll(Collections.list(clt.findResources(p.classLoader, name)));
+ resources.addAll(Collections.list(ClassLoaderReflectionToolkit._findResources(p.classLoader, name)));
}
- } catch (InvocationTargetException e) {
- throw new Error(e);
- }
} else {
for (PluginWrapper p : activePlugins) {
resources.addAll(Collections.list(p.classLoader.getResources(name)));
diff --git a/core/src/main/java/hudson/PluginWrapper.java b/core/src/main/java/hudson/PluginWrapper.java
index 3245888194..870930f7de 100644
--- a/core/src/main/java/hudson/PluginWrapper.java
+++ b/core/src/main/java/hudson/PluginWrapper.java
@@ -45,6 +45,7 @@ import java.util.jar.Manifest;
import java.util.logging.Logger;
import static java.util.logging.Level.WARNING;
+import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.LogFactory;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
@@ -213,7 +214,7 @@ public class PluginWrapper implements Comparable, ModelObject {
}
public String getDisplayName() {
- return getLongName();
+ return StringUtils.removeStart(getLongName(), "Jenkins ");
}
public Api getApi() {
@@ -581,7 +582,7 @@ public class PluginWrapper implements Comparable, ModelObject {
backupPlugin.close();
}
} catch (IOException e) {
- LOGGER.log(WARNING, "Failed to get backup version ", e);
+ LOGGER.log(WARNING, "Failed to get backup version from " + backup, e);
return null;
}
} else {
diff --git a/core/src/main/java/hudson/XmlFile.java b/core/src/main/java/hudson/XmlFile.java
index 148578c469..00eae060e9 100644
--- a/core/src/main/java/hudson/XmlFile.java
+++ b/core/src/main/java/hudson/XmlFile.java
@@ -24,7 +24,7 @@
package hudson;
import com.thoughtworks.xstream.XStream;
-import com.thoughtworks.xstream.converters.ConversionException;
+import com.thoughtworks.xstream.XStreamException;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.StreamException;
@@ -140,9 +140,7 @@ public final class XmlFile {
InputStream in = new BufferedInputStream(new FileInputStream(file));
try {
return xs.fromXML(in);
- } catch(StreamException e) {
- throw new IOException("Unable to read "+file,e);
- } catch(ConversionException e) {
+ } catch (XStreamException e) {
throw new IOException("Unable to read "+file,e);
} catch(Error e) {// mostly reflection errors
throw new IOException("Unable to read "+file,e);
@@ -163,9 +161,7 @@ public final class XmlFile {
try {
// TODO: expose XStream the driver from XStream
return xs.unmarshal(DEFAULT_DRIVER.createReader(in), o);
- } catch (StreamException e) {
- throw new IOException("Unable to read "+file,e);
- } catch(ConversionException e) {
+ } catch (XStreamException e) {
throw new IOException("Unable to read "+file,e);
} catch(Error e) {// mostly reflection errors
throw new IOException("Unable to read "+file,e);
diff --git a/core/src/main/java/hudson/cli/CLICommand.java b/core/src/main/java/hudson/cli/CLICommand.java
index 980036567a..dc79a622de 100644
--- a/core/src/main/java/hudson/cli/CLICommand.java
+++ b/core/src/main/java/hudson/cli/CLICommand.java
@@ -189,6 +189,8 @@ public abstract class CLICommand implements ExtensionPoint, Cloneable {
* The default implementation uses args4j to parse command line arguments and call {@link #run()},
* but if that processing is undesirable, subtypes can directly override this method and leave {@link #run()}
* to an empty method.
+ * You would however then have to consider {@link CliAuthenticator} and {@link #getTransportAuthentication},
+ * so this is not really recommended.
*
* @param args
* Arguments to the sub command. For example, if the CLI is invoked like "java -jar cli.jar foo bar zot",
diff --git a/core/src/main/java/hudson/cli/ClientAuthenticationCache.java b/core/src/main/java/hudson/cli/ClientAuthenticationCache.java
index cd727e7ba4..6b8ef61d73 100644
--- a/core/src/main/java/hudson/cli/ClientAuthenticationCache.java
+++ b/core/src/main/java/hudson/cli/ClientAuthenticationCache.java
@@ -43,7 +43,11 @@ public class ClientAuthenticationCache implements Serializable {
store = (channel==null ? MasterComputer.localChannel : channel).call(new Callable() {
public FilePath call() throws IOException {
File home = new File(System.getProperty("user.home"));
- return new FilePath(new File(home, ".hudson/cli-credentials"));
+ File hudsonHome = new File(home, ".hudson");
+ if (hudsonHome.exists()) {
+ return new FilePath(new File(hudsonHome, "cli-credentials"));
+ }
+ return new FilePath(new File(home, ".jenkins/cli-credentials"));
}
});
if (store.exists()) {
diff --git a/core/src/main/java/hudson/cli/CopyJobCommand.java b/core/src/main/java/hudson/cli/CopyJobCommand.java
index a8049bdf28..8d1c86676c 100644
--- a/core/src/main/java/hudson/cli/CopyJobCommand.java
+++ b/core/src/main/java/hudson/cli/CopyJobCommand.java
@@ -75,7 +75,7 @@ public class CopyJobCommand extends CLICommand {
dst = dst.substring(i + 1);
}
- ig.copy(src,dst);
+ ig.copy(src,dst).save();
return 0;
}
}
diff --git a/core/src/main/java/hudson/cli/CreateJobCommand.java b/core/src/main/java/hudson/cli/CreateJobCommand.java
index db73c30b51..02dd6ae55e 100644
--- a/core/src/main/java/hudson/cli/CreateJobCommand.java
+++ b/core/src/main/java/hudson/cli/CreateJobCommand.java
@@ -72,6 +72,7 @@ public class CreateJobCommand extends CLICommand {
name = name.substring(i + 1);
}
+ Jenkins.checkGoodName(name);
ig.createProjectFromXML(name, stdin);
return 0;
}
diff --git a/core/src/main/java/hudson/cli/GroovyshCommand.java b/core/src/main/java/hudson/cli/GroovyshCommand.java
index 92a7d2731e..48babcb90d 100644
--- a/core/src/main/java/hudson/cli/GroovyshCommand.java
+++ b/core/src/main/java/hudson/cli/GroovyshCommand.java
@@ -34,14 +34,15 @@ import org.codehaus.groovy.tools.shell.Shell;
import org.codehaus.groovy.tools.shell.util.XmlCommandRegistrar;
import java.util.List;
-import java.util.Locale;
import java.io.PrintStream;
import java.io.InputStream;
import java.io.BufferedInputStream;
import java.io.PrintWriter;
+import java.util.ArrayList;
import jline.UnsupportedTerminal;
import jline.Terminal;
+import org.kohsuke.args4j.Argument;
/**
* Executes Groovy shell.
@@ -55,11 +56,12 @@ public class GroovyshCommand extends CLICommand {
return Messages.GroovyshCommand_ShortDescription();
}
+ @Argument(metaVar="ARGS") public List args = new ArrayList();
+
@Override
- public int main(List args, Locale locale, InputStream stdin, PrintStream stdout, PrintStream stderr) {
+ protected int run() {
// this allows the caller to manipulate the JVM state, so require the admin privilege.
Jenkins.getInstance().checkPermission(Jenkins.RUN_SCRIPTS);
- // TODO JENKINS-17929 this does not work
// this being remote means no jline capability is available
System.setProperty("jline.terminal", UnsupportedTerminal.class.getName());
@@ -122,7 +124,4 @@ public class GroovyshCommand extends CLICommand {
return shell;
}
- protected int run() {
- throw new UnsupportedOperationException();
- }
}
diff --git a/core/src/main/java/hudson/cli/SetBuildParameterCommand.java b/core/src/main/java/hudson/cli/SetBuildParameterCommand.java
index d2c976e5e7..5676bb5264 100644
--- a/core/src/main/java/hudson/cli/SetBuildParameterCommand.java
+++ b/core/src/main/java/hudson/cli/SetBuildParameterCommand.java
@@ -37,9 +37,7 @@ public class SetBuildParameterCommand extends CommandDuringBuild {
ParametersAction a = r.getAction(ParametersAction.class);
if (a!=null) {
- ParametersAction b = a.createUpdated(Collections.singleton(p));
- r.addAction(b);
- r.getActions().remove(a);
+ r.replaceAction(a.createUpdated(Collections.singleton(p)));
} else {
r.addAction(new ParametersAction(p));
}
diff --git a/core/src/main/java/hudson/diagnosis/ReverseProxySetupMonitor.java b/core/src/main/java/hudson/diagnosis/ReverseProxySetupMonitor.java
index 3fa520808c..46851d7b0a 100644
--- a/core/src/main/java/hudson/diagnosis/ReverseProxySetupMonitor.java
+++ b/core/src/main/java/hudson/diagnosis/ReverseProxySetupMonitor.java
@@ -25,12 +25,10 @@ package hudson.diagnosis;
import hudson.Extension;
import hudson.model.AdministrativeMonitor;
-import hudson.util.FormValidation;
import org.kohsuke.stapler.HttpRedirect;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.QueryParameter;
-import org.kohsuke.stapler.WebMethod;
import java.io.IOException;
@@ -54,12 +52,15 @@ public class ReverseProxySetupMonitor extends AdministrativeMonitor {
}
public HttpResponse doTest() {
- return new HttpRedirect("test-for-reverse-proxy-setup");
+ return new HttpRedirect("testForReverseProxySetup/a%2Fb/");
}
- @WebMethod(name="test-for-reverse-proxy-setup")
- public FormValidation doFoo() {
- return FormValidation.ok();
+ public void getTestForReverseProxySetup(String rest) {
+ if (rest.equals("a/b")) {
+ throw HttpResponses.ok();
+ } else {
+ throw HttpResponses.errorWithoutStack(404, "expected a/b but got " + rest);
+ }
}
/**
diff --git a/core/src/main/java/hudson/logging/LogRecorder.java b/core/src/main/java/hudson/logging/LogRecorder.java
index f780252af4..43b4cb4562 100644
--- a/core/src/main/java/hudson/logging/LogRecorder.java
+++ b/core/src/main/java/hudson/logging/LogRecorder.java
@@ -84,14 +84,38 @@ public class LogRecorder extends AbstractModelObject implements Saveable {
public final CopyOnWriteList targets = new CopyOnWriteList();
- private transient /*almost final*/ RingBufferLogHandler handler = new RingBufferLogHandler() {
+ @Restricted(NoExternalUse.class)
+ Target[] orderedTargets() {
+ // will contain targets ordered by reverse name length (place specific targets at the beginning)
+ Target[] ts = targets.toArray(new Target[]{});
+
+ Arrays.sort(ts, new Comparator() {
+ public int compare(Target left, Target right) {
+ return right.getName().length() - left.getName().length();
+ }
+ });
+
+ return ts;
+ }
+
+ @Restricted(NoExternalUse.class)
+ transient /*almost final*/ RingBufferLogHandler handler = new RingBufferLogHandler() {
@Override
public void publish(LogRecord record) {
- for (Target t : targets) {
- if(t.includes(record)) {
- super.publish(record);
- return;
+ for (Target t : orderedTargets()) {
+ Boolean match = t.matches(record);
+ if (match == null) {
+ // domain does not match, so continue looking
+ continue;
}
+
+ if (match.booleanValue()) {
+ // most specific logger matches, so publish
+ super.publish(record);
+ }
+ // most specific logger does not match, so don't publish
+ // allows reducing log level for more specific loggers
+ return;
}
}
};
@@ -123,6 +147,11 @@ public class LogRecorder extends AbstractModelObject implements Saveable {
return Level.parse(String.valueOf(level));
}
+ public String getName() {
+ return name;
+ }
+
+ @Deprecated
public boolean includes(LogRecord r) {
if(r.getLevel().intValue() < level)
return false; // below the threshold
@@ -136,6 +165,21 @@ public class LogRecorder extends AbstractModelObject implements Saveable {
return rest.startsWith(".") || rest.length()==0;
}
+ public Boolean matches(LogRecord r) {
+ boolean levelSufficient = r.getLevel().intValue() >= level;
+ if (name.length() == 0) {
+ return Boolean.valueOf(levelSufficient); // include if level matches
+ }
+ String logName = r.getLoggerName();
+ if(logName==null || !logName.startsWith(name))
+ return null; // not in the domain of this logger
+ String rest = logName.substring(name.length());
+ if (rest.startsWith(".") || rest.length()==0) {
+ return Boolean.valueOf(levelSufficient); // include if level matches
+ }
+ return null;
+ }
+
public Logger getLogger() {
if (logger == null) {
logger = Logger.getLogger(name);
@@ -299,7 +343,7 @@ public class LogRecorder extends AbstractModelObject implements Saveable {
* The file we save our configuration.
*/
private XmlFile getConfigFile() {
- return new XmlFile(XSTREAM, new File(Jenkins.getInstance().getRootDir(),"log/"+name+".xml"));
+ return new XmlFile(XSTREAM, new File(LogRecorderManager.configDir(), name + ".xml"));
}
/**
diff --git a/core/src/main/java/hudson/logging/LogRecorderManager.java b/core/src/main/java/hudson/logging/LogRecorderManager.java
index ab8337c701..d16ece6c2b 100644
--- a/core/src/main/java/hudson/logging/LogRecorderManager.java
+++ b/core/src/main/java/hudson/logging/LogRecorderManager.java
@@ -33,7 +33,6 @@ import hudson.model.RSS;
import hudson.util.CopyOnWriteMap;
import jenkins.model.JenkinsLocationConfiguration;
import jenkins.model.ModelObjectWithChildren;
-import jenkins.model.ModelObjectWithContextMenu;
import jenkins.model.ModelObjectWithContextMenu.ContextMenu;
import org.apache.commons.io.filefilter.WildcardFileFilter;
import org.kohsuke.stapler.QueryParameter;
@@ -52,7 +51,6 @@ import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.Map;
-import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
@@ -84,12 +82,16 @@ public class LogRecorderManager extends AbstractModelObject implements ModelObje
return logRecorders.get(token);
}
+ static File configDir() {
+ return new File(Jenkins.getInstance().getRootDir(), "log");
+ }
+
/**
* Loads the configuration from disk.
*/
public void load() throws IOException {
logRecorders.clear();
- File dir = new File(Jenkins.getInstance().getRootDir(), "log");
+ File dir = configDir();
File[] files = dir.listFiles((FileFilter)new WildcardFileFilter("*.xml"));
if(files==null) return;
for (File child : files) {
diff --git a/core/src/main/java/hudson/markup/EbayPolicy.java b/core/src/main/java/hudson/markup/EbayPolicy.java
deleted file mode 100644
index 75b43f7a79..0000000000
--- a/core/src/main/java/hudson/markup/EbayPolicy.java
+++ /dev/null
@@ -1,241 +0,0 @@
-// Copyright (c) 2011, Mike Samuel
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions
-// are met:
-//
-// Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// Redistributions in binary form must reproduce the above copyright
-// notice, this list of conditions and the following disclaimer in the
-// documentation and/or other materials provided with the distribution.
-// Neither the name of the OWASP nor the names of its contributors may
-// be used to endorse or promote products derived from this software
-// without specific prior written permission.
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
-// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
-// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
-// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
-// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
-// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
-// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
-// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-// POSSIBILITY OF SUCH DAMAGE.
-package hudson.markup;
-
-import com.google.common.base.Charsets;
-import com.google.common.base.Function;
-import com.google.common.base.Predicate;
-import com.google.common.base.Throwables;
-import com.google.common.io.CharStreams;
-import org.owasp.html.Handler;
-import org.owasp.html.HtmlPolicyBuilder;
-import org.owasp.html.HtmlSanitizer;
-import org.owasp.html.HtmlSanitizer.Policy;
-import org.owasp.html.HtmlStreamEventReceiver;
-import org.owasp.html.HtmlStreamRenderer;
-import org.owasp.html.PolicyFactory;
-
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.util.regex.Pattern;
-
-/**
- * Based on the
- * AntiSamy EBay example.
- *
- * eBay (http://www.ebay.com/) is the most popular online auction site in the
- * universe, as far as I can tell. It is a public site so anyone is allowed to
- * post listings with rich HTML content. It's not surprising that given the
- * attractiveness of eBay as a target that it has been subject to a few complex
- * XSS attacks. Listings are allowed to contain much more rich content than,
- * say, Slashdot- so it's attack surface is considerably larger. The following
- * tags appear to be accepted by eBay (they don't publish rules):
- * {@code },...
- *
- */
-public class EbayPolicy {
-
- // Some common regular expression definitions.
-
- // The 16 colors defined by the HTML Spec (also used by the CSS Spec)
- private static final Pattern COLOR_NAME = Pattern.compile(
- "(?:aqua|black|blue|fuchsia|gray|grey|green|lime|maroon|navy|olive|purple"
- + "|red|silver|teal|white|yellow)");
-
- // HTML/CSS Spec allows 3 or 6 digit hex to specify color
- private static final Pattern COLOR_CODE = Pattern.compile(
- "(?:#(?:[0-9a-fA-F]{3}(?:[0-9a-fA-F]{3})?))");
-
- private static final Pattern NUMBER_OR_PERCENT = Pattern.compile(
- "[0-9]+%?");
- private static final Pattern PARAGRAPH = Pattern.compile(
- "(?:[\\p{L}\\p{N},'\\.\\s\\-_\\(\\)]|&[0-9]{2};)*");
- private static final Pattern HTML_ID = Pattern.compile(
- "[a-zA-Z0-9\\:\\-_\\.]+");
- // force non-empty with a '+' at the end instead of '*'
- private static final Pattern HTML_TITLE = Pattern.compile(
- "[\\p{L}\\p{N}\\s\\-_',:\\[\\]!\\./\\\\\\(\\)&]*");
- private static final Pattern HTML_CLASS = Pattern.compile(
- "[a-zA-Z0-9\\s,\\-_]+");
-
- private static final Pattern ONSITE_URL = Pattern.compile(
- "(?:[\\p{L}\\p{N}\\\\\\.\\#@\\$%\\+&;\\-_~,\\?=/!]+|\\#(\\w)+)");
- private static final Pattern OFFSITE_URL = Pattern.compile(
- "\\s*(?:(?:ht|f)tps?://|mailto:)[\\p{L}\\p{N}]"
- + "[\\p{L}\\p{N}\\p{Zs}\\.\\#@\\$%\\+&;:\\-_~,\\?=/!\\(\\)]*\\s*");
-
- private static final Pattern NUMBER = Pattern.compile(
- "[+-]?(?:(?:[0-9]+(?:\\.[0-9]*)?)|\\.[0-9]+)");
-
- private static final Pattern NAME = Pattern.compile("[a-zA-Z0-9\\-_\\$]+");
-
- private static final Pattern ALIGN = Pattern.compile(
- "(?i)center|left|right|justify|char");
-
- private static final Pattern VALIGN = Pattern.compile(
- "(?i)baseline|bottom|middle|top");
-
- private static final Predicate COLOR_NAME_OR_COLOR_CODE
- = new Predicate() {
- public boolean apply(String s) {
- return COLOR_NAME.matcher(s).matches()
- || COLOR_CODE.matcher(s).matches();
- }
- };
-
- private static final Predicate ONSITE_OR_OFFSITE_URL
- = new Predicate() {
- public boolean apply(String s) {
- return ONSITE_URL.matcher(s).matches()
- || OFFSITE_URL.matcher(s).matches();
- }
- };
-
- private static final Pattern HISTORY_BACK = Pattern.compile(
- "(?:javascript:)?\\Qhistory.go(-1)\\E");
-
- private static final Pattern ONE_CHAR = Pattern.compile(
- ".?", Pattern.DOTALL);
-
-
- public static final PolicyFactory POLICY_DEFINITION;
-
- static {
- POLICY_DEFINITION = new HtmlPolicyBuilder()
- .allowAttributes("id").matching(HTML_ID).globally()
- .allowAttributes("class").matching(HTML_CLASS).globally()
- .allowAttributes("lang").matching(Pattern.compile("[a-zA-Z]{2,20}"))
- .globally()
- .allowAttributes("title").matching(HTML_TITLE).globally()
- .allowStyling()
- .allowAttributes("align").matching(ALIGN).onElements("p")
- .allowAttributes("for").matching(HTML_ID).onElements("label")
- .allowAttributes("color").matching(COLOR_NAME_OR_COLOR_CODE)
- .onElements("font")
- .allowAttributes("face")
- .matching(Pattern.compile("[\\w;, \\-]+"))
- .onElements("font")
- .allowAttributes("size").matching(NUMBER).onElements("font")
- .allowAttributes("href").matching(ONSITE_OR_OFFSITE_URL)
- .onElements("a")
- .allowStandardUrlProtocols()
- .allowAttributes("nohref").onElements("a")
- .allowAttributes("name").matching(NAME).onElements("a")
- .allowAttributes(
- "onfocus", "onblur", "onclick", "onmousedown", "onmouseup")
- .matching(HISTORY_BACK).onElements("a")
- .requireRelNofollowOnLinks()
- .allowAttributes("src").matching(ONSITE_OR_OFFSITE_URL)
- .onElements("img")
- .allowAttributes("name").matching(NAME)
- .onElements("img")
- .allowAttributes("alt").matching(PARAGRAPH)
- .onElements("img")
- .allowAttributes("border", "hspace", "vspace").matching(NUMBER)
- .onElements("img")
- .allowAttributes("border", "cellpadding", "cellspacing")
- .matching(NUMBER).onElements("table")
- .allowAttributes("bgcolor").matching(COLOR_NAME_OR_COLOR_CODE)
- .onElements("table")
- .allowAttributes("background").matching(ONSITE_URL)
- .onElements("table")
- .allowAttributes("align").matching(ALIGN)
- .onElements("table")
- .allowAttributes("noresize").matching(Pattern.compile("(?i)noresize"))
- .onElements("table")
- .allowAttributes("background").matching(ONSITE_URL)
- .onElements("td", "th", "tr")
- .allowAttributes("bgcolor").matching(COLOR_NAME_OR_COLOR_CODE)
- .onElements("td", "th")
- .allowAttributes("abbr").matching(PARAGRAPH)
- .onElements("td", "th")
- .allowAttributes("axis", "headers").matching(NAME)
- .onElements("td", "th")
- .allowAttributes("scope")
- .matching(Pattern.compile("(?i)(?:row|col)(?:group)?"))
- .onElements("td", "th")
- .allowAttributes("nowrap")
- .onElements("td", "th")
- .allowAttributes("height", "width").matching(NUMBER_OR_PERCENT)
- .onElements("table", "td", "th", "tr", "img")
- .allowAttributes("align").matching(ALIGN)
- .onElements("thead", "tbody", "tfoot", "img",
- "td", "th", "tr", "colgroup", "col")
- .allowAttributes("valign").matching(VALIGN)
- .onElements("thead", "tbody", "tfoot",
- "td", "th", "tr", "colgroup", "col")
- .allowAttributes("charoff").matching(NUMBER_OR_PERCENT)
- .onElements("td", "th", "tr", "colgroup", "col",
- "thead", "tbody", "tfoot")
- .allowAttributes("char").matching(ONE_CHAR)
- .onElements("td", "th", "tr", "colgroup", "col",
- "thead", "tbody", "tfoot")
- .allowAttributes("colspan", "rowspan").matching(NUMBER)
- .onElements("td", "th")
- .allowAttributes("span", "width").matching(NUMBER_OR_PERCENT)
- .onElements("colgroup", "col")
- .allowElements(
- "label", "noscript", "h1", "h2", "h3", "h4", "h5", "h6",
- "p", "i", "b", "u", "strong", "em", "small", "big", "pre", "code",
- "cite", "samp", "sub", "sup", "strike", "center", "blockquote",
- "hr", "br", "col", "font", "map", "span", "div", "img",
- "ul", "ol", "li", "dd", "dt", "dl", "tbody", "thead", "tfoot",
- "table", "td", "th", "tr", "colgroup", "fieldset", "legend")
- .toFactory();
- }
-
- public static void main(String[] args) throws IOException {
- if (args.length != 0) {
- System.err.println("Reads from STDIN and writes to STDOUT");
- System.exit(-1);
- }
- System.err.println("[Reading from STDIN]");
- // Fetch the HTML to sanitize.
- String html = CharStreams.toString(
- new InputStreamReader(System.in, Charsets.UTF_8));
- // Set up an output channel to receive the sanitized HTML.
- HtmlStreamRenderer renderer = HtmlStreamRenderer.create(
- System.out,
- // Receives notifications on a failure to write to the output.
- new Handler() {
- public void handle(IOException ex) {
- Throwables.propagate(ex); // System.out suppresses IOExceptions
- }
- },
- // Our HTML parser is very lenient, but this receives notifications on
- // truly bizarre inputs.
- new Handler() {
- public void handle(String x) {
- throw new AssertionError(x);
- }
- }
- );
- // Use the policy defined above to sanitize the HTML.
- HtmlSanitizer.sanitize(html, POLICY_DEFINITION.apply(renderer));
- }
-}
\ No newline at end of file
diff --git a/core/src/main/java/hudson/markup/EscapedMarkupFormatter.java b/core/src/main/java/hudson/markup/EscapedMarkupFormatter.java
new file mode 100644
index 0000000000..f106b5de2c
--- /dev/null
+++ b/core/src/main/java/hudson/markup/EscapedMarkupFormatter.java
@@ -0,0 +1,60 @@
+/*
+ * The MIT License
+ *
+ * Copyright 2011 Seiji Sogabe
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package hudson.markup;
+
+import hudson.Extension;
+import hudson.Util;
+import hudson.markup.MarkupFormatter;
+import hudson.markup.MarkupFormatterDescriptor;
+import java.io.IOException;
+import java.io.Writer;
+import org.kohsuke.stapler.DataBoundConstructor;
+
+/**
+ * @link MarkupFormatter} that treats the input as the escaped html.
+ *
+ * @author Seiji Sogabe
+ * @since 1.553
+ */
+public class EscapedMarkupFormatter extends MarkupFormatter {
+
+ @DataBoundConstructor
+ public EscapedMarkupFormatter() {
+ }
+
+ @Override
+ public void translate(String markup, Writer output) throws IOException {
+ output.write(Util.escape(markup));
+ }
+
+ @Extension
+ public static class DescriptorImpl extends MarkupFormatterDescriptor {
+
+ @Override
+ public String getDisplayName() {
+ return Messages.EscapedMarkupFormatter_DisplayName();
+ }
+ }
+
+}
diff --git a/core/src/main/java/hudson/markup/HtmlPolicyBuilder2.java b/core/src/main/java/hudson/markup/HtmlPolicyBuilder2.java
deleted file mode 100644
index 4f6ea5435e..0000000000
--- a/core/src/main/java/hudson/markup/HtmlPolicyBuilder2.java
+++ /dev/null
@@ -1,42 +0,0 @@
-package hudson.markup;
-
-import com.google.common.base.Predicate;
-import org.owasp.html.HtmlPolicyBuilder;
-
-import java.util.regex.Pattern;
-
-/**
- * {@link HtmlPolicyBuilder} with additional
- * functions to simplify transcoding policy definition
- * from OWASP AntiSamy policy files.
- *
- * @author Kohsuke Kawaguchi
- */
-class HtmlPolicyBuilder2 extends HtmlPolicyBuilder {
- public void tag(String names, Object... attributes) {
- String[] tags = names.split(",");
- for (int i=0; iOWASP AntiSamy MySpace Policy
- */
-public class MyspacePolicy {
- public static final PolicyFactory POLICY_DEFINITION;
-
- private static final Pattern ONSITE_URL = Pattern.compile(
- "(?:[\\p{L}\\p{N}\\\\\\.\\#@\\$%\\+&;\\-_~,\\?=/!]+|\\#(\\w)+)");
- private static final Pattern OFFSITE_URL = Pattern.compile(
- "\\s*(?:(?:ht|f)tps?://|mailto:)[\\p{L}\\p{N}]"
- + "[\\p{L}\\p{N}\\p{Zs}\\.\\#@\\$%\\+&;:\\-_~,\\?=/!\\(\\)]*\\s*");
-
- private static final Predicate ONSITE_OR_OFFSITE_URL
- = new Predicate() {
- public boolean apply(String s) {
- return ONSITE_URL.matcher(s).matches()
- || OFFSITE_URL.matcher(s).matches();
- }
- };
-
- static {
- POLICY_DEFINITION = new HtmlPolicyBuilder2() {{
- allowAttributes("id","class","lang","title",
- "alt","style","media","href","name","shape",
- "border","cellpadding","cellspacing","colspan","rowspan",
- "background","bgcolor","abbr","headers","charoff","char",
- "aixs","nowrap","width","height","align","valign","scope",
- "tabindex","disabled","readonly","accesskey","size",
- "autocomplete","rows","cols").globally();
-
- disallowElements(
- // I'm allowing iframe
- "script","noscript",/*"iframe",*/"frameset","frame");
-
- tag("label", "for");
- tag("form", "action",ONSITE_OR_OFFSITE_URL,
- "method");
- tag("button", "value", "type");
- tag("input", "maxlength","checked",
- "src",ONSITE_OR_OFFSITE_URL,
- "usemap",ONSITE_URL,
- "type","value");
- tag("select", "multiple");
- tag("option", "value","label","selected");
- tag("textarea");
- tag("h1,h2,h3,h4,h5,h6,p,i,b,u,strong,em,small,big,pre,code,cite,samp,sub,sup,strike,center,blockquote");
- tag("hr,br,col");
- tag("font", "color", "face", "size");
- tag("a", "nohref","rel");
- tag("style", "type");
- tag("span,div");
- tag("img", "src",ONSITE_OR_OFFSITE_URL,
- "hspace","vspace");
- tag("iframe", "src");
- tag("ul,ol,li,dd,dl,dt,thead,tbody,tfoot");
- tag("table", "noresize");
- tag("td,th,tr");
- tag("colgroup", "span");
- tag("col", "span");
- tag("fieldset,legend");
- allowStandardUrlProtocols();
- }}.toFactory();
- }
-
- public static void main(String[] args) throws IOException {
- // Fetch the HTML to sanitize.
- String html = "Google";
- // Set up an output channel to receive the sanitized HTML.
- HtmlStreamRenderer renderer = HtmlStreamRenderer.create(
- System.out,
- // Receives notifications on a failure to write to the output.
- new Handler() {
- public void handle(IOException ex) {
- Throwables.propagate(ex); // System.out suppresses IOExceptions
- }
- },
- // Our HTML parser is very lenient, but this receives notifications on
- // truly bizarre inputs.
- new Handler() {
- public void handle(String x) {
- throw new AssertionError(x);
- }
- }
- );
- // Use the policy defined above to sanitize the HTML.
- HtmlSanitizer.sanitize(html, POLICY_DEFINITION.apply(renderer));
- }
-}
diff --git a/core/src/main/java/hudson/markup/RawHtmlMarkupFormatter.java b/core/src/main/java/hudson/markup/RawHtmlMarkupFormatter.java
deleted file mode 100644
index 89b0eca43d..0000000000
--- a/core/src/main/java/hudson/markup/RawHtmlMarkupFormatter.java
+++ /dev/null
@@ -1,71 +0,0 @@
-package hudson.markup;
-
-import com.google.common.base.Throwables;
-import hudson.Extension;
-import org.kohsuke.stapler.DataBoundConstructor;
-import org.owasp.html.Handler;
-import org.owasp.html.HtmlSanitizer;
-import org.owasp.html.HtmlStreamRenderer;
-
-import java.io.IOException;
-import java.io.Writer;
-
-/**
- * {@link MarkupFormatter} that treats the input as the raw html.
- * This is the backward compatible behaviour.
- *
- * @author Kohsuke Kawaguchi
- */
-public class RawHtmlMarkupFormatter extends MarkupFormatter {
-
- final boolean disableSyntaxHighlighting;
-
- @DataBoundConstructor
- public RawHtmlMarkupFormatter(final boolean disableSyntaxHighlighting) {
- this.disableSyntaxHighlighting = disableSyntaxHighlighting;
- }
-
- public boolean isDisableSyntaxHighlighting() {
- return disableSyntaxHighlighting;
- }
-
- @Override
- public void translate(String markup, Writer output) throws IOException {
- HtmlStreamRenderer renderer = HtmlStreamRenderer.create(
- output,
- // Receives notifications on a failure to write to the output.
- new Handler() {
- public void handle(IOException ex) {
- Throwables.propagate(ex); // System.out suppresses IOExceptions
- }
- },
- // Our HTML parser is very lenient, but this receives notifications on
- // truly bizarre inputs.
- new Handler() {
- public void handle(String x) {
- throw new Error(x);
- }
- }
- );
- // Use the policy defined above to sanitize the HTML.
- HtmlSanitizer.sanitize(markup, MyspacePolicy.POLICY_DEFINITION.apply(renderer));
- }
-
- public String getCodeMirrorMode() {
- return disableSyntaxHighlighting ? null : "htmlmixed";
- }
-
- public String getCodeMirrorConfig() {
- return "mode:'text/html'";
- }
-
- @Extension
- public static class DescriptorImpl extends MarkupFormatterDescriptor {
- @Override
- public String getDisplayName() {
- return "Raw HTML";
- }
- }
-
- public static final MarkupFormatter INSTANCE = new RawHtmlMarkupFormatter(false);
-}
diff --git a/core/src/main/java/hudson/matrix/DefaultMatrixExecutionStrategyImpl.java b/core/src/main/java/hudson/matrix/DefaultMatrixExecutionStrategyImpl.java
index 6b19c6a39e..c874a35963 100644
--- a/core/src/main/java/hudson/matrix/DefaultMatrixExecutionStrategyImpl.java
+++ b/core/src/main/java/hudson/matrix/DefaultMatrixExecutionStrategyImpl.java
@@ -3,7 +3,6 @@ package hudson.matrix;
import groovy.lang.GroovyRuntimeException;
import hudson.AbortException;
import hudson.Extension;
-import hudson.Util;
import hudson.console.ModelHyperlinkNote;
import hudson.matrix.MatrixBuild.MatrixBuildExecution;
import hudson.matrix.listeners.MatrixBuildListener;
@@ -238,7 +237,7 @@ public class DefaultMatrixExecutionStrategyImpl extends MatrixExecutionStrategy
exec.getListener().getLogger().println(Messages.MatrixBuild_Triggering(ModelHyperlinkNote.encodeTo(c)));
// filter the parent actions for those that can be passed to the individual jobs.
- List childActions = Util.filter(build.getActions(), MatrixChildAction.class);
+ List childActions = build.getActions(MatrixChildAction.class);
c.scheduleBuild(childActions, new UpstreamCause((Run)build));
}
diff --git a/core/src/main/java/hudson/model/AbstractBuild.java b/core/src/main/java/hudson/model/AbstractBuild.java
index bbbc44ad62..eeeaf4e927 100644
--- a/core/src/main/java/hudson/model/AbstractBuild.java
+++ b/core/src/main/java/hudson/model/AbstractBuild.java
@@ -30,13 +30,13 @@ import hudson.EnvVars;
import hudson.FilePath;
import hudson.Functions;
import hudson.Launcher;
-import hudson.Util;
import hudson.console.AnnotatedLargeText;
import hudson.console.ExpandableDetailsNote;
import hudson.console.ModelHyperlinkNote;
import hudson.matrix.MatrixConfiguration;
import hudson.model.Fingerprint.BuildPtr;
import hudson.model.Fingerprint.RangeSet;
+import hudson.model.labels.LabelAtom;
import hudson.model.listeners.RunListener;
import hudson.model.listeners.SCMListener;
import hudson.scm.ChangeLogParser;
@@ -541,11 +541,30 @@ public abstract class AbstractBuild
,R extends Abs
for (Environment e : buildEnvironments)
e.buildEnvVars(env);
- for (EnvironmentContributingAction a : Util.filter(getActions(),EnvironmentContributingAction.class))
+ for (EnvironmentContributingAction a : getActions(EnvironmentContributingAction.class))
a.buildEnvVars(this,env);
EnvVars.resolve(env);
@@ -956,6 +975,7 @@ public abstract class AbstractBuild
,R extends Abs
return getTimestamp();
}
+ @SuppressWarnings("deprecation")
public List getPersistentActions(){
return super.getActions();
}
diff --git a/core/src/main/java/hudson/model/AbstractCIBase.java b/core/src/main/java/hudson/model/AbstractCIBase.java
index 69328fa4c9..19cc8cfbf7 100644
--- a/core/src/main/java/hudson/model/AbstractCIBase.java
+++ b/core/src/main/java/hudson/model/AbstractCIBase.java
@@ -54,6 +54,7 @@ public abstract class AbstractCIBase extends Node implements ItemGroup> implements Describable {
- public Descriptor getDescriptor() {
- return Jenkins.getInstance().getDescriptorOrDie(getClass());
- }
-}
+/*
+ * The MIT License
+ *
+ * Copyright (c) 2004-2009, Kohsuke Kawaguchi
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package hudson.model;
+
+import hudson.Extension;
+import jenkins.model.Jenkins;
+
+/**
+ * Partial default implementation of {@link Describable}.
+ *
+ * @author Kohsuke Kawaguchi
+ */
+public abstract class AbstractDescribableImpl> implements Describable {
+
+ /**
+ * By default looks for a nested class (conventionally named {@code DescriptorImpl}) implementing {@link Descriptor} and marked with {@link Extension}.
+ *
{@inheritDoc}
+ */
+ public Descriptor getDescriptor() {
+ return Jenkins.getInstance().getDescriptorOrDie(getClass());
+ }
+
+}
diff --git a/core/src/main/java/hudson/model/AbstractItem.java b/core/src/main/java/hudson/model/AbstractItem.java
index fd3b2693aa..aafb50025a 100644
--- a/core/src/main/java/hudson/model/AbstractItem.java
+++ b/core/src/main/java/hudson/model/AbstractItem.java
@@ -34,6 +34,7 @@ import hudson.cli.declarative.CLIMethod;
import hudson.cli.declarative.CLIResolver;
import hudson.model.listeners.ItemListener;
import hudson.model.listeners.SaveableListener;
+import hudson.remoting.Callable;
import hudson.security.AccessControlled;
import hudson.security.Permission;
import hudson.security.ACL;
@@ -42,6 +43,7 @@ import hudson.util.AlternativeUiTextProvider.Message;
import hudson.util.AtomicFileWriter;
import hudson.util.IOUtils;
import jenkins.model.Jenkins;
+import jenkins.model.Jenkins.MasterComputer;
import org.apache.tools.ant.taskdefs.Copy;
import org.apache.tools.ant.types.FileSet;
import org.kohsuke.stapler.WebMethod;
@@ -223,6 +225,7 @@ public abstract class AbstractItem extends Actionable implements Item, HttpDelet
+ " already exists");
String oldName = this.name;
+ String oldFullName = getFullName();
File oldRoot = this.getRootDir();
doSetName(newName);
@@ -293,8 +296,7 @@ public abstract class AbstractItem extends Actionable implements Item, HttpDelet
callOnRenamed(newName, parent, oldName);
- for (ItemListener l : ItemListener.all())
- l.onRenamed(this, oldName, newName);
+ ItemListener.fireLocationChange(this, oldFullName);
}
}
}
@@ -366,7 +368,7 @@ public abstract class AbstractItem extends Actionable implements Item, HttpDelet
/**
* Called right after when a {@link Item} is loaded from disk.
- * This is an opporunity to do a post load processing.
+ * This is an opportunity to do a post load processing.
*/
public void onLoad(ItemGroup extends Item> parent, String name) throws IOException {
this.parent = parent;
@@ -510,21 +512,23 @@ public abstract class AbstractItem extends Actionable implements Item, HttpDelet
checkPermission(DELETE);
performDelete();
- try {
- invokeOnDeleted();
- } catch (AbstractMethodError e) {
- // ignore
- }
+ // defer the notification to avoid the lock ordering problem. See JENKINS-19446.
+ MasterComputer.threadPoolForRemoting.submit(new java.util.concurrent.Callable() {
+ @Override
+ public Void call() throws Exception {
+ invokeOnDeleted();
+ Jenkins.getInstance().rebuildDependencyGraphAsync();
+ return null;
+ }
- Jenkins.getInstance().rebuildDependencyGraphAsync();
- }
-
- /**
- * A pointless function to work around what appears to be a HotSpot problem. See JENKINS-5756 and bug 6933067
- * on BugParade for more details.
- */
- private void invokeOnDeleted() throws IOException {
- getParent().onDeleted(this);
+ /**
+ * A pointless function to work around what appears to be a HotSpot problem. See JENKINS-5756 and bug 6933067
+ * on BugParade for more details.
+ */
+ private void invokeOnDeleted() throws IOException {
+ getParent().onDeleted(AbstractItem.this);
+ }
+ });
}
/**
@@ -585,17 +589,17 @@ public abstract class AbstractItem extends Actionable implements Item, HttpDelet
new StreamResult(out));
out.close();
} catch (TransformerException e) {
- throw new IOException("Failed to persist configuration.xml", e);
+ throw new IOException("Failed to persist config.xml", e);
}
// try to reflect the changes by reloading
new XmlFile(Items.XSTREAM, out.getTemporaryFile()).unmarshal(this);
- Items.updatingByXml.set(true);
- try {
- onLoad(getParent(), getRootDir().getName());
- } finally {
- Items.updatingByXml.set(false);
- }
+ Items.whileUpdatingByXml(new Callable() {
+ @Override public Void call() throws IOException {
+ onLoad(getParent(), getRootDir().getName());
+ return null;
+ }
+ });
Jenkins.getInstance().rebuildDependencyGraphAsync();
// if everything went well, commit this new version
diff --git a/core/src/main/java/hudson/model/AbstractProject.java b/core/src/main/java/hudson/model/AbstractProject.java
index 05a2af4f0d..7271a76e80 100644
--- a/core/src/main/java/hudson/model/AbstractProject.java
+++ b/core/src/main/java/hudson/model/AbstractProject.java
@@ -27,15 +27,16 @@
*/
package hudson.model;
-import com.infradna.tool.bridge_method_injector.WithBridgeMethods;
-import hudson.EnvVars;
-import hudson.ExtensionPoint;
-import hudson.Functions;
import antlr.ANTLRException;
+import com.infradna.tool.bridge_method_injector.WithBridgeMethods;
import hudson.AbortException;
import hudson.CopyOnWrite;
+import hudson.EnvVars;
+import hudson.Extension;
+import hudson.ExtensionPoint;
import hudson.FeedAdapter;
import hudson.FilePath;
+import hudson.Functions;
import hudson.Launcher;
import hudson.Util;
import hudson.cli.declarative.CLIMethod;
@@ -48,21 +49,23 @@ import hudson.model.Fingerprint.RangeSet;
import hudson.model.PermalinkProjectAction.Permalink;
import hudson.model.Queue.Executable;
import hudson.model.Queue.Task;
-import hudson.model.queue.QueueTaskFuture;
-import hudson.model.queue.ScheduleResult;
-import hudson.model.queue.SubTask;
import hudson.model.RunMap.Constructor;
import hudson.model.labels.LabelAtom;
import hudson.model.labels.LabelExpression;
import hudson.model.listeners.ItemListener;
import hudson.model.listeners.SCMPollListener;
import hudson.model.queue.CauseOfBlockage;
+import hudson.model.queue.QueueTaskFuture;
+import hudson.model.queue.ScheduleResult;
+import hudson.model.queue.SubTask;
import hudson.model.queue.SubTaskContributor;
import hudson.node_monitors.DiskSpaceMonitor;
import hudson.scm.ChangeLogSet;
import hudson.scm.ChangeLogSet.Entry;
import hudson.scm.NullSCM;
import hudson.scm.PollingResult;
+
+import static hudson.scm.PollingResult.*;
import hudson.scm.SCM;
import hudson.scm.SCMRevisionState;
import hudson.scm.SCMS;
@@ -85,38 +88,6 @@ import hudson.util.FormValidation;
import hudson.util.TimeUnit2;
import hudson.widgets.BuildHistoryWidget;
import hudson.widgets.HistoryWidget;
-import jenkins.model.Jenkins;
-import jenkins.model.JenkinsLocationConfiguration;
-import jenkins.model.ModelObjectWithChildren;
-import jenkins.model.Uptime;
-import jenkins.model.lazy.AbstractLazyLoadRunMap.Direction;
-import jenkins.scm.DefaultSCMCheckoutStrategyImpl;
-import jenkins.scm.SCMCheckoutStrategy;
-import jenkins.scm.SCMCheckoutStrategyDescriptor;
-import jenkins.util.TimeDuration;
-import net.sf.json.JSONObject;
-import org.acegisecurity.Authentication;
-import org.acegisecurity.context.SecurityContext;
-import org.acegisecurity.context.SecurityContextHolder;
-import org.jenkinsci.bytecode.AdaptField;
-import org.kohsuke.accmod.Restricted;
-import org.kohsuke.accmod.restrictions.NoExternalUse;
-import org.kohsuke.args4j.Argument;
-import org.kohsuke.args4j.CmdLineException;
-import org.kohsuke.stapler.Ancestor;
-import org.kohsuke.stapler.AncestorInPath;
-import org.kohsuke.stapler.ForwardToView;
-import org.kohsuke.stapler.HttpRedirect;
-import org.kohsuke.stapler.HttpResponse;
-import org.kohsuke.stapler.HttpResponses;
-import org.kohsuke.stapler.QueryParameter;
-import org.kohsuke.stapler.StaplerRequest;
-import org.kohsuke.stapler.StaplerResponse;
-import org.kohsuke.stapler.export.Exported;
-import org.kohsuke.stapler.interceptor.RequirePOST;
-
-import javax.annotation.Nonnull;
-import javax.servlet.ServletException;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
@@ -139,10 +110,40 @@ import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import java.util.logging.Level;
import java.util.logging.Logger;
-
-import static hudson.scm.PollingResult.*;
import javax.annotation.CheckForNull;
+import javax.annotation.Nonnull;
+import javax.servlet.ServletException;
import static javax.servlet.http.HttpServletResponse.*;
+import jenkins.model.Jenkins;
+import jenkins.model.JenkinsLocationConfiguration;
+import jenkins.model.ModelObjectWithChildren;
+import jenkins.model.Uptime;
+import jenkins.model.lazy.AbstractLazyLoadRunMap.Direction;
+import jenkins.scm.DefaultSCMCheckoutStrategyImpl;
+import jenkins.scm.SCMCheckoutStrategy;
+import jenkins.scm.SCMCheckoutStrategyDescriptor;
+import jenkins.util.TimeDuration;
+import net.sf.json.JSONObject;
+import org.acegisecurity.Authentication;
+import org.acegisecurity.context.SecurityContext;
+import org.acegisecurity.context.SecurityContextHolder;
+import org.jenkinsci.bytecode.AdaptField;
+import org.kohsuke.accmod.Restricted;
+import org.kohsuke.accmod.restrictions.DoNotUse;
+import org.kohsuke.accmod.restrictions.NoExternalUse;
+import org.kohsuke.args4j.Argument;
+import org.kohsuke.args4j.CmdLineException;
+import org.kohsuke.stapler.Ancestor;
+import org.kohsuke.stapler.AncestorInPath;
+import org.kohsuke.stapler.ForwardToView;
+import org.kohsuke.stapler.HttpRedirect;
+import org.kohsuke.stapler.HttpResponse;
+import org.kohsuke.stapler.HttpResponses;
+import org.kohsuke.stapler.QueryParameter;
+import org.kohsuke.stapler.StaplerRequest;
+import org.kohsuke.stapler.StaplerResponse;
+import org.kohsuke.stapler.export.Exported;
+import org.kohsuke.stapler.interceptor.RequirePOST;
/**
* Base implementation of {@link Job}s that build software.
@@ -326,8 +327,9 @@ public abstract class AbstractProject
,R extends A
}
this.builds = builds;
triggers().setOwner(this);
- for (Trigger t : triggers())
- t.start(this, Items.updatingByXml.get());
+ for (Trigger t : triggers()) {
+ t.start(this, Items.currentlyUpdatingByXml());
+ }
if(scm==null)
scm = new NullSCM(); // perhaps it was pointing to a plugin that no longer exists.
@@ -399,7 +401,7 @@ public abstract class AbstractProject
,R extends A
* If this project is configured to be always built on this node,
* return that {@link Node}. Otherwise null.
*/
- public Label getAssignedLabel() {
+ public @CheckForNull Label getAssignedLabel() {
if(canRoam)
return null;
@@ -776,13 +778,7 @@ public abstract class AbstractProject
,R extends A
}
public List getProminentActions() {
- List a = getActions();
- List pa = new Vector();
- for (Action action : a) {
- if(action instanceof ProminentProjectAction)
- pa.add((ProminentProjectAction) action);
- }
- return pa;
+ return getActions(ProminentProjectAction.class);
}
@Override
@@ -1103,7 +1099,10 @@ public abstract class AbstractProject
,R extends A
}
/**
- * Determines Class<R>.
+ * Type token for the corresponding build type.
+ * The build class must have two constructors:
+ * one taking this project type;
+ * and one taking this project type, then {@link File}.
*/
protected abstract Class getBuildClass();
@@ -1174,6 +1173,7 @@ public abstract class AbstractProject
,R extends A
*
* @see TransientProjectActionFactory
*/
+ @SuppressWarnings("deprecation")
@Override
public List getActions() {
// add all the transient actions, too
@@ -2026,7 +2026,14 @@ public abstract class AbstractProject
,R extends A
for (Publisher _t : Descriptor.newInstancesFromHeteroList(req, json, "publisher", Jenkins.getInstance().getExtensionList(BuildTrigger.DescriptorImpl.class))) {
BuildTrigger t = (BuildTrigger) _t;
- for (AbstractProject downstream : t.getChildProjects(this)) {
+ List childProjects;
+ SecurityContext orig = ACL.impersonate(ACL.SYSTEM);
+ try {
+ childProjects = t.getChildProjects(this);
+ } finally {
+ SecurityContextHolder.setContext(orig);
+ }
+ for (AbstractProject downstream : childProjects) {
downstream.checkPermission(BUILD);
}
}
@@ -2119,6 +2126,7 @@ public abstract class AbstractProject
,R extends A
makeDisabled(false);
return new HttpRedirect(".");
}
+
/**
* RSS feed for changes in this project.
@@ -2221,7 +2229,8 @@ public abstract class AbstractProject
,R extends A
return FormValidation.error(e,
Messages.AbstractProject_AssignedLabelString_InvalidBooleanExpression(e.getMessage()));
}
- Label l = Jenkins.getInstance().getLabel(value);
+ Jenkins j = Jenkins.getInstance();
+ Label l = j.getLabel(value);
if (l.isEmpty()) {
for (LabelAtom a : l.listAtoms()) {
if (a.isEmpty()) {
@@ -2232,7 +2241,7 @@ public abstract class AbstractProject
,R extends A
return FormValidation.warning(Messages.AbstractProject_AssignedLabelString_NoMatch());
}
if (project != null) {
- for (AbstractProject.LabelValidator v : Jenkins.getInstance()
+ for (AbstractProject.LabelValidator v : j
.getExtensionList(AbstractProject.LabelValidator.class)) {
FormValidation result = v.check(project, l);
if (!FormValidation.Kind.OK.equals(result.kind)) {
@@ -2240,7 +2249,9 @@ public abstract class AbstractProject
,R extends A
}
}
}
- return FormValidation.ok();
+ return FormValidation.okWithMarkup(Messages.AbstractProject_LabelLink(
+ j.getRootUrl(), l.getUrl(), l.getNodes().size() + l.getClouds().size()
+ ));
}
public FormValidation doCheckCustomWorkspace(@QueryParameter(value="customWorkspace.directory") String customWorkspace){
@@ -2415,4 +2426,14 @@ public abstract class AbstractProject
- * A new {@link Action} can be added by {@code getActions().add(...)}.
+ * A new {@link Action} can be added by {@link #addAction}.
+ *
+ *
If you are reading the list, rather than modifying it,
+ * use {@link #getAllActions} instead.
+ * This method by default returns only persistent actions
+ * (though some subclasses override it to return an extended unmodifiable list).
*
* @return
* may be empty but never null.
+ * @deprecated Normally outside code should not call this method any more.
+ * Use {@link #getAllActions}, or {@link #addAction}, or {@link #replaceAction}.
+ * May still be called for compatibility reasons from subclasses predating {@link TransientActionFactory}.
*/
- @Exported
+ @Deprecated
public List getActions() {
if(actions == null) {
synchronized (this) {
@@ -81,7 +82,27 @@ public abstract class Actionable extends AbstractModelObject implements ModelObj
}
/**
- * Gets all actions of a specified type that contributed to this build.
+ * Gets all actions, transient or persistent.
+ * {@link #getActions} is supplemented with anything contributed by {@link TransientActionFactory}.
+ * @return an unmodifiable, possible empty list
+ * @since 1.548
+ */
+ @Exported(name="actions")
+ public final List extends Action> getAllActions() {
+ List _actions = new ArrayList(getActions());
+ for (TransientActionFactory> taf : Jenkins.getInstance().getExtensionList(TransientActionFactory.class)) {
+ if (taf.type().isInstance(this)) {
+ _actions.addAll(createFor(taf));
+ }
+ }
+ return Collections.unmodifiableList(_actions);
+ }
+ private Collection extends Action> createFor(TransientActionFactory taf) {
+ return taf.createFor(taf.type().cast(this));
+ }
+
+ /**
+ * Gets all actions of a specified type that contributed to this object.
*
* @param type The type of action to return.
* @return
@@ -89,23 +110,39 @@ public abstract class Actionable extends AbstractModelObject implements ModelObj
* @see #getAction(Class)
*/
public List getActions(Class type) {
- List result = new Vector();
- for (Action a : getActions())
- if (type.isInstance(a))
- result.add(type.cast(a));
- return result;
+ return Util.filter(getAllActions(), type);
}
/**
* Adds a new action.
*
- * Short for getActions().add(a)
+ * The default implementation calls {@code getActions().add(a)}.
*/
public void addAction(Action a) {
if(a==null) throw new IllegalArgumentException();
getActions().add(a);
}
+ /**
+ * Add an action, replacing any existing action of the (exact) same class.
+ * @param a an action to add/replace
+ * @since 1.548
+ */
+ public void replaceAction(Action a) {
+ // CopyOnWriteArrayList does not support Iterator.remove, so need to do it this way:
+ List old = new ArrayList(1);
+ List current = getActions();
+ for (Action a2 : current) {
+ if (a2.getClass() == a.getClass()) {
+ old.add(a2);
+ }
+ }
+ current.removeAll(old);
+ addAction(a);
+ }
+
+ /** @deprecated No clear purpose, since subclasses may have overridden {@link #getActions}, and does not consider {@link TransientActionFactory}. */
+ @Deprecated
public Action getAction(int index) {
if(actions==null) return null;
return actions.get(index);
@@ -119,14 +156,14 @@ public abstract class Actionable extends AbstractModelObject implements ModelObj
* @see #getActions(Class)
*/
public T getAction(Class type) {
- for (Action a : getActions())
+ for (Action a : getAllActions())
if (type.isInstance(a))
return type.cast(a);
return null;
}
public Object getDynamic(String token, StaplerRequest req, StaplerResponse rsp) {
- for (Action a : getActions()) {
+ for (Action a : getAllActions()) {
if(a==null)
continue; // be defensive
String urlName = a.getUrlName();
diff --git a/core/src/main/java/hudson/model/AllView.java b/core/src/main/java/hudson/model/AllView.java
index 0bc73d3c58..de02320266 100644
--- a/core/src/main/java/hudson/model/AllView.java
+++ b/core/src/main/java/hudson/model/AllView.java
@@ -81,11 +81,6 @@ public class AllView extends View {
return ""; // there's no configuration page
}
- @Override
- public void onJobRenamed(Item item, String oldName, String newName) {
- // noop
- }
-
@Override
protected void submit(StaplerRequest req) throws IOException, ServletException, FormException {
// noop
diff --git a/core/src/main/java/hudson/model/AsyncPeriodicWork.java b/core/src/main/java/hudson/model/AsyncPeriodicWork.java
index f678e1425e..3960e61fa2 100644
--- a/core/src/main/java/hudson/model/AsyncPeriodicWork.java
+++ b/core/src/main/java/hudson/model/AsyncPeriodicWork.java
@@ -38,12 +38,12 @@ public abstract class AsyncPeriodicWork extends PeriodicWork {
public final void doRun() {
try {
if(thread!=null && thread.isAlive()) {
- logger.log(Level.INFO, name+" thread is still running. Execution aborted.");
+ logger.log(this.getNormalLoggingLevel(), name+" thread is still running. Execution aborted.");
return;
}
thread = new Thread(new Runnable() {
public void run() {
- logger.log(Level.INFO, "Started "+name);
+ logger.log(getNormalLoggingLevel(), "Started "+name);
long startTime = System.currentTimeMillis();
StreamTaskListener l = createListener();
@@ -59,13 +59,13 @@ public abstract class AsyncPeriodicWork extends PeriodicWork {
l.closeQuietly();
}
- logger.log(Level.INFO, "Finished "+name+". "+
+ logger.log(getNormalLoggingLevel(), "Finished "+name+". "+
(System.currentTimeMillis()-startTime)+" ms");
}
},name+" thread");
thread.start();
} catch (Throwable t) {
- logger.log(Level.SEVERE, name+" thread failed with error", t);
+ logger.log(this.getErrorLoggingLevel(), name+" thread failed with error", t);
}
}
@@ -83,7 +83,31 @@ public abstract class AsyncPeriodicWork extends PeriodicWork {
protected File getLogFile() {
return new File(Jenkins.getInstance().getRootDir(),name+".log");
}
-
+
+ /**
+ * Returns the logging level at which normal messages are displayed.
+ *
+ * @return
+ * The logging level as @Level.
+ *
+ * @since 1.551
+ */
+ protected Level getNormalLoggingLevel() {
+ return Level.INFO;
+ }
+
+ /**
+ * Returns the logging level at which error messages are displayed.
+ *
+ * @return
+ * The logging level as @Level.
+ *
+ * @since 1.551
+ */
+ protected Level getErrorLoggingLevel() {
+ return Level.SEVERE;
+ }
+
/**
* Executes the task.
*
diff --git a/core/src/main/java/hudson/model/AutoCompletionCandidates.java b/core/src/main/java/hudson/model/AutoCompletionCandidates.java
index 556ea22806..0373b552bb 100644
--- a/core/src/main/java/hudson/model/AutoCompletionCandidates.java
+++ b/core/src/main/java/hudson/model/AutoCompletionCandidates.java
@@ -91,7 +91,22 @@ public class AutoCompletionCandidates implements HttpResponse {
public static AutoCompletionCandidates ofJobNames(final Class type, final String value, @CheckForNull Item self, ItemGroup container) {
if (self==container)
container = self.getParent();
+ return ofJobNames(type, value, container);
+ }
+
+ /**
+ * Auto-completes possible job names.
+ *
+ * @param type
+ * Limit the auto-completion to the subtype of this type.
+ * @param value
+ * The value the user has typed in. Matched as a prefix.
+ * @param container
+ * The nearby contextual {@link ItemGroup} to resolve relative job names from.
+ * @since 1.553
+ */
+ public static AutoCompletionCandidates ofJobNames(final Class type, final String value, ItemGroup container) {
final AutoCompletionCandidates candidates = new AutoCompletionCandidates();
class Visitor extends ItemVisitor {
String prefix;
diff --git a/core/src/main/java/hudson/model/BooleanParameterDefinition.java b/core/src/main/java/hudson/model/BooleanParameterDefinition.java
old mode 100755
new mode 100644
diff --git a/core/src/main/java/hudson/model/BooleanParameterValue.java b/core/src/main/java/hudson/model/BooleanParameterValue.java
old mode 100755
new mode 100644
diff --git a/core/src/main/java/hudson/model/BuildTimelineWidget.java b/core/src/main/java/hudson/model/BuildTimelineWidget.java
index ca1e226893..9b8bc849b8 100644
--- a/core/src/main/java/hudson/model/BuildTimelineWidget.java
+++ b/core/src/main/java/hudson/model/BuildTimelineWidget.java
@@ -33,7 +33,7 @@ import java.io.IOException;
import java.util.Date;
/**
- * UI widget for showing the SMILE timeline control.
+ * UI widget for showing the SIMILE timeline control.
*
*
* Return this from your "getTimeline" method.
@@ -45,13 +45,15 @@ public class BuildTimelineWidget {
protected final RunList> builds;
public BuildTimelineWidget(RunList> builds) {
- this.builds = builds;
+ this.builds = builds.limit(20); // TODO instead render lazily
}
+ @Deprecated
public Run, ?> getFirstBuild() {
return builds.getFirstBuild();
}
+ @Deprecated
public Run, ?> getLastBuild() {
return builds.getLastBuild();
}
diff --git a/core/src/main/java/hudson/model/Cause.java b/core/src/main/java/hudson/model/Cause.java
index 8283cfa68c..44861804da 100644
--- a/core/src/main/java/hudson/model/Cause.java
+++ b/core/src/main/java/hudson/model/Cause.java
@@ -34,6 +34,7 @@ import jenkins.model.Jenkins;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
+import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import javax.annotation.CheckForNull;
@@ -412,10 +413,13 @@ public abstract class Cause {
@Override
public String getShortDescription() {
if(note != null) {
- return Messages.Cause_RemoteCause_ShortDescriptionWithNote(addr, note);
- } else {
- return Messages.Cause_RemoteCause_ShortDescription(addr);
+ try {
+ return Messages.Cause_RemoteCause_ShortDescriptionWithNote(addr, Jenkins.getInstance().getMarkupFormatter().translate(note));
+ } catch (IOException x) {
+ // ignore
+ }
}
+ return Messages.Cause_RemoteCause_ShortDescription(addr);
}
@Override
diff --git a/core/src/main/java/hudson/model/CauseAction.java b/core/src/main/java/hudson/model/CauseAction.java
index e823afdfed..1938f6f561 100644
--- a/core/src/main/java/hudson/model/CauseAction.java
+++ b/core/src/main/java/hudson/model/CauseAction.java
@@ -144,7 +144,7 @@ public class CauseAction implements FoldableAction, RunAction2 {
return;
}
// no CauseAction found, so add a copy of this one
- item.getActions().add(new CauseAction(this));
+ item.addAction(new CauseAction(this));
}
public static class ConverterImpl extends XStream2.PassthruConverter {
diff --git a/core/src/main/java/hudson/model/ChoiceParameterDefinition.java b/core/src/main/java/hudson/model/ChoiceParameterDefinition.java
old mode 100755
new mode 100644
diff --git a/core/src/main/java/hudson/model/Computer.java b/core/src/main/java/hudson/model/Computer.java
index 219373d5ff..43fa1c37c2 100644
--- a/core/src/main/java/hudson/model/Computer.java
+++ b/core/src/main/java/hudson/model/Computer.java
@@ -180,6 +180,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces
/**
* Returns the transient {@link Action}s associated with the computer.
*/
+ @SuppressWarnings("deprecation")
public List getActions() {
List result = new ArrayList();
result.addAll(super.getActions());
@@ -189,9 +190,10 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces
}
result.addAll(transientActions);
}
- return result;
+ return Collections.unmodifiableList(result);
}
+ @SuppressWarnings("deprecation")
@Override
public void addAction(Action a) {
if(a==null) throw new IllegalArgumentException();
@@ -1083,9 +1085,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces
checkPermission(DISCONNECT);
offlineMessage = Util.fixEmptyAndTrim(offlineMessage);
setTemporarilyOffline(!temporarilyOffline,
- OfflineCause.create(hudson.slaves.Messages._SlaveComputer_DisconnectedBy(
- Jenkins.getAuthentication().getName(),
- offlineMessage!=null ? " : " + offlineMessage : "")));
+ new OfflineCause.UserCause(User.current(), offlineMessage));
} else {
checkPermission(CONNECT);
setTemporarilyOffline(!temporarilyOffline,null);
@@ -1097,9 +1097,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces
checkPermission(DISCONNECT);
offlineMessage = Util.fixEmptyAndTrim(offlineMessage);
setTemporarilyOffline(true,
- OfflineCause.create(hudson.slaves.Messages._SlaveComputer_DisconnectedBy(
- Jenkins.getAuthentication().getName(),
- offlineMessage != null ? " : " + offlineMessage : "")));
+ new OfflineCause.UserCause(User.current(), offlineMessage));
return HttpResponses.redirectToDot();
}
diff --git a/core/src/main/java/hudson/model/Describable.java b/core/src/main/java/hudson/model/Describable.java
index d916ed3488..ae8103b3cf 100644
--- a/core/src/main/java/hudson/model/Describable.java
+++ b/core/src/main/java/hudson/model/Describable.java
@@ -34,8 +34,9 @@ public interface Describable> {
*
*
* {@link Descriptor} is a singleton for every concrete {@link Describable}
- * implementation, so if a.getClass()==b.getClass() then
- * a.getDescriptor()==b.getDescriptor() must hold.
+ * implementation, so if {@code a.getClass() == b.getClass()} then by default
+ * {@code a.getDescriptor() == b.getDescriptor()} as well.
+ * (In rare cases a single implementation class may be used for instances with distinct descriptors.)
*/
Descriptor getDescriptor();
}
diff --git a/core/src/main/java/hudson/model/Descriptor.java b/core/src/main/java/hudson/model/Descriptor.java
index e0cc80c5ea..1d36481101 100644
--- a/core/src/main/java/hudson/model/Descriptor.java
+++ b/core/src/main/java/hudson/model/Descriptor.java
@@ -967,7 +967,7 @@ public abstract class Descriptor> implements Saveable {
public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException, ServletException {
if (FormApply.isApply(req)) {
- FormApply.applyResponse("notificationBar.show(" + quote(getMessage())+ ",notificationBar.defaultOptions.ERROR)")
+ FormApply.applyResponse("notificationBar.show(" + quote(getMessage())+ ",notificationBar.ERROR)")
.generateResponse(req, rsp, node);
} else {
// for now, we can't really use the field name that caused the problem.
diff --git a/core/src/main/java/hudson/model/DirectoryBrowserSupport.java b/core/src/main/java/hudson/model/DirectoryBrowserSupport.java
index 5fd72727db..1dfd2b3a3b 100644
--- a/core/src/main/java/hudson/model/DirectoryBrowserSupport.java
+++ b/core/src/main/java/hudson/model/DirectoryBrowserSupport.java
@@ -25,13 +25,6 @@ package hudson.model;
import hudson.FilePath;
import hudson.Util;
-import jenkins.model.Jenkins;
-import org.kohsuke.stapler.StaplerRequest;
-import org.kohsuke.stapler.StaplerResponse;
-import org.kohsuke.stapler.HttpResponse;
-
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@@ -41,14 +34,23 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
+import java.util.HashMap;
import java.util.List;
import java.util.Locale;
+import java.util.Map;
import java.util.StringTokenizer;
-import java.util.logging.Logger;
import java.util.logging.Level;
+import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletResponse;
+import jenkins.model.Jenkins;
import jenkins.util.VirtualFile;
+import org.apache.commons.io.IOUtils;
+import org.kohsuke.stapler.HttpResponse;
+import org.kohsuke.stapler.StaplerRequest;
+import org.kohsuke.stapler.StaplerResponse;
/**
* Has convenience methods to serve file system.
@@ -351,7 +353,12 @@ public final class DirectoryBrowserSupport implements HttpResponse {
VirtualFile f = dir.child(n);
e.setTime(f.lastModified());
zos.putNextEntry(e);
- Util.copyStream(f.open(), zos);
+ InputStream in = f.open();
+ try {
+ Util.copyStream(in, zos);
+ } finally {
+ IOUtils.closeQuietly(in);
+ }
zos.closeEntry();
}
zos.close();
@@ -424,8 +431,9 @@ public final class DirectoryBrowserSupport implements HttpResponse {
private static final class FileComparator implements Comparator {
private Collator collator;
+ private final Map isDirCache = new HashMap();
- public FileComparator(Locale locale) {
+ FileComparator(Locale locale) {
this.collator = Collator.getInstance(locale);
}
@@ -437,9 +445,18 @@ public final class DirectoryBrowserSupport implements HttpResponse {
return this.collator.compare(lhs.getName(), rhs.getName());
}
+ private boolean isDirectory(VirtualFile f) throws IOException {
+ Boolean known = isDirCache.get(f);
+ if (known == null) {
+ known = f.isDirectory();
+ isDirCache.put(f, known);
+ }
+ return known;
+ }
+
private int dirRank(VirtualFile f) {
try {
- if(f.isDirectory()) return 0;
+ if(isDirectory(f)) return 0;
else return 1;
} catch (IOException ex) {
return 0;
diff --git a/core/src/main/java/hudson/model/Executor.java b/core/src/main/java/hudson/model/Executor.java
index 181bc017ab..8a460a4887 100644
--- a/core/src/main/java/hudson/model/Executor.java
+++ b/core/src/main/java/hudson/model/Executor.java
@@ -274,13 +274,13 @@ public class Executor extends Thread implements ModelObject {
}
/**
- * Returns the current {@link hudson.model.Queue.Task} this executor is running.
+ * Returns the current build this executor is running.
*
* @return
* null if the executor is idle.
*/
@Exported
- public Queue.Executable getCurrentExecutable() {
+ public @CheckForNull Queue.Executable getCurrentExecutable() {
return executable;
}
diff --git a/core/src/main/java/hudson/model/Fingerprint.java b/core/src/main/java/hudson/model/Fingerprint.java
index 9c0e6ee7cf..4ada1f6c9c 100644
--- a/core/src/main/java/hudson/model/Fingerprint.java
+++ b/core/src/main/java/hudson/model/Fingerprint.java
@@ -727,7 +727,7 @@ public class Fingerprint implements ModelObject, Saveable {
@Extension
public static final class ProjectRenameListener extends ItemListener {
@Override
- public void onRenamed(Item item, String oldName, String newName) {
+ public void onLocationChanged(Item item, String oldName, String newName) {
if (item instanceof AbstractProject) {
AbstractProject p = Jenkins.getInstance().getItemByFullName(newName, AbstractProject.class);
if (p != null) {
diff --git a/core/src/main/java/hudson/model/FreeStyleBuild.java b/core/src/main/java/hudson/model/FreeStyleBuild.java
index df091cd142..4941789ef2 100644
--- a/core/src/main/java/hudson/model/FreeStyleBuild.java
+++ b/core/src/main/java/hudson/model/FreeStyleBuild.java
@@ -23,9 +23,6 @@
*/
package hudson.model;
-import hudson.slaves.WorkspaceList;
-import hudson.slaves.WorkspaceList.Lease;
-
import java.io.IOException;
import java.io.File;
diff --git a/core/src/main/java/hudson/model/ItemGroup.java b/core/src/main/java/hudson/model/ItemGroup.java
index a87814eb9d..bc042c8925 100644
--- a/core/src/main/java/hudson/model/ItemGroup.java
+++ b/core/src/main/java/hudson/model/ItemGroup.java
@@ -23,6 +23,7 @@
*/
package hudson.model;
+import hudson.model.listeners.ItemListener;
import java.io.IOException;
import java.util.Collection;
import java.io.File;
@@ -76,6 +77,7 @@ public interface ItemGroup extends PersistenceRoot, ModelObject
/**
* Internal method. Called by {@link Item}s when they are renamed by users.
+ * This is not expected to call {@link ItemListener#onRenamed}, inconsistent with {@link #onDeleted}.
*/
void onRenamed(T item, String oldName, String newName) throws IOException;
diff --git a/core/src/main/java/hudson/model/ItemGroupMixIn.java b/core/src/main/java/hudson/model/ItemGroupMixIn.java
index a91405c3a4..0b975851b4 100644
--- a/core/src/main/java/hudson/model/ItemGroupMixIn.java
+++ b/core/src/main/java/hudson/model/ItemGroupMixIn.java
@@ -25,6 +25,7 @@ package hudson.model;
import hudson.Util;
import hudson.model.listeners.ItemListener;
+import hudson.remoting.Callable;
import hudson.security.AccessControlled;
import hudson.util.CopyOnWriteMap;
import hudson.util.Function1;
@@ -40,6 +41,8 @@ import java.io.FileFilter;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
+import java.util.logging.Level;
+import java.util.logging.Logger;
/**
* Defines a bunch of static methods to be used as a "mix-in" for {@link ItemGroup}
@@ -96,10 +99,16 @@ public abstract class ItemGroupMixIn {
CopyOnWriteMap.Tree configurations = new CopyOnWriteMap.Tree();
for (File subdir : subdirs) {
try {
- V item = (V) Items.load(parent,subdir);
+ // Try to retain the identity of an existing child object if we can.
+ V item = (V) parent.getItem(subdir.getName());
+ if (item == null) {
+ item = (V) Items.load(parent,subdir);
+ } else {
+ item.onLoad(parent, subdir.getName());
+ }
configurations.put(key.call(item), item);
} catch (IOException e) {
- e.printStackTrace(); // TODO: logging
+ Logger.getLogger(ItemGroupMixIn.class.getName()).log(Level.WARNING, "could not load " + subdir, e);
}
}
@@ -204,12 +213,12 @@ public abstract class ItemGroupMixIn {
Util.copyFile(Items.getConfigFile(src).getFile(),Items.getConfigFile(result).getFile());
// reload from the new config
- Items.updatingByXml.set(true);
- try {
- result = (T)Items.load(parent,result.getRootDir());
- } finally {
- Items.updatingByXml.set(false);
- }
+ final File rootDir = result.getRootDir();
+ result = Items.whileUpdatingByXml(new Callable() {
+ @Override public T call() throws IOException {
+ return (T) Items.load(parent, rootDir);
+ }
+ });
result.onCopiedFrom(src);
add(result);
@@ -229,18 +238,17 @@ public abstract class ItemGroupMixIn {
// place it as config.xml
File configXml = Items.getConfigFile(getRootDirFor(name)).getFile();
- configXml.getParentFile().mkdirs();
+ final File dir = configXml.getParentFile();
+ dir.mkdirs();
try {
IOUtils.copy(xml,configXml);
// load it
- TopLevelItem result;
- Items.updatingByXml.set(true);
- try {
- result = (TopLevelItem)Items.load(parent,configXml.getParentFile());
- } finally {
- Items.updatingByXml.set(false);
- }
+ TopLevelItem result = Items.whileUpdatingByXml(new Callable() {
+ @Override public TopLevelItem call() throws IOException {
+ return (TopLevelItem) Items.load(parent, dir);
+ }
+ });
add(result);
ItemListener.fireOnCreated(result);
@@ -249,7 +257,7 @@ public abstract class ItemGroupMixIn {
return result;
} catch (IOException e) {
// if anything fails, delete the config file to avoid further confusion
- Util.deleteRecursive(configXml.getParentFile());
+ Util.deleteRecursive(dir);
throw e;
}
}
diff --git a/core/src/main/java/hudson/model/Items.java b/core/src/main/java/hudson/model/Items.java
index 5ca561beaa..9b0993dfb2 100644
--- a/core/src/main/java/hudson/model/Items.java
+++ b/core/src/main/java/hudson/model/Items.java
@@ -30,6 +30,8 @@ import hudson.matrix.MatrixProject;
import hudson.matrix.MatrixConfiguration;
import hudson.XmlFile;
import hudson.matrix.Axis;
+import hudson.model.listeners.ItemListener;
+import hudson.remoting.Callable;
import hudson.triggers.Trigger;
import hudson.util.DescriptorList;
import hudson.util.EditDistance;
@@ -41,6 +43,8 @@ import java.io.File;
import java.io.IOException;
import java.util.*;
import javax.annotation.CheckForNull;
+import jenkins.model.DirectlyModifiableTopLevelItemGroup;
+import org.apache.commons.io.FileUtils;
/**
* Convenience methods related to {@link Item}.
@@ -61,12 +65,41 @@ public class Items {
* @see Trigger#start
* @since 1.482
*/
- static final ThreadLocal updatingByXml = new ThreadLocal() {
+ private static final ThreadLocal updatingByXml = new ThreadLocal() {
@Override protected Boolean initialValue() {
return false;
}
};
+ /**
+ * Runs a block while making {@link #currentlyUpdatingByXml} be temporarily true.
+ * Use this when you are creating or changing an item.
+ * @param a return value type (may be {@link Void})
+ * @param an error type (may be {@link Error})
+ * @param callable a block, typically running {@link #load} or {@link Item#onLoad}
+ * @return whatever {@code callable} returned
+ * @throws T anything {@code callable} throws
+ * @since 1.546
+ */
+ public static V whileUpdatingByXml(Callable callable) throws T {
+ updatingByXml.set(true);
+ try {
+ return callable.call();
+ } finally {
+ updatingByXml.set(false);
+ }
+ }
+
+ /**
+ * Checks whether we are in the middle of creating or configuring an item via XML.
+ * Used to determine the {@code newInstance} parameter for {@link Trigger#start}.
+ * @return true if {@link #whileUpdatingByXml} is currently being called, false for example when merely starting Jenkins or reloading from disk
+ * @since 1.546
+ */
+ public static boolean currentlyUpdatingByXml() {
+ return updatingByXml.get();
+ }
+
/**
* Returns all the registered {@link TopLevelItemDescriptor}s.
*/
@@ -149,8 +182,8 @@ public class Items {
}
/**
- * Compute the relative name of list of items after a rename occurred. Used to manage job references as names in
- * plugins to support {@link hudson.model.listeners.ItemListener#onRenamed(hudson.model.Item, String, String)}.
+ * Computes the relative name of list of items after a rename or move occurred.
+ * Used to manage job references as names in plugins to support {@link hudson.model.listeners.ItemListener#onLocationChanged}.
*
* In a hierarchical context, when a plugin has a reference to a job as ../foo/bar this method will
* handle the relative path as "foo" is renamed to "zot" to compute ../zot/bar
@@ -170,8 +203,11 @@ public class Items {
String canonicalName = getCanonicalName(context, relativeName);
if (canonicalName.equals(oldFullName) || canonicalName.startsWith(oldFullName+'/')) {
String newCanonicalName = newFullName + canonicalName.substring(oldFullName.length());
- // relative name points to the renamed item, let's compute the new relative name
- newValue.add( computeRelativeNameAfterRenaming(canonicalName, newCanonicalName, relativeName) );
+ if (relativeName.startsWith("/")) {
+ newValue.add("/" + newCanonicalName);
+ } else {
+ newValue.add(getRelativeNameFrom(newCanonicalName, context.getFullName()));
+ }
} else {
newValue.add(relativeName);
}
@@ -179,39 +215,56 @@ public class Items {
return StringUtils.join(newValue, ",");
}
- /**
- * Compute the relative name of an Item after renaming
- */
- private static String computeRelativeNameAfterRenaming(String oldFullName, String newFullName, String relativeName) {
-
- String[] a = oldFullName.split("/");
- String[] n = newFullName.split("/");
- assert a.length == n.length;
- String[] r = relativeName.split("/");
-
- int j = a.length-1;
- for(int i=r.length-1;i>=0;i--) {
- String part = r[i];
- if (part.equals("") && i==0) {
- continue;
- }
- if (part.equals(".")) {
- continue;
- }
- if (part.equals("..")) {
- j--;
- continue;
- }
- if (part.equals(a[j])) {
- r[i] = n[j];
- j--;
+ // Had difficulty adapting the version in Functions to use no live items, so rewrote it:
+ static String getRelativeNameFrom(String itemFullName, String groupFullName) {
+ String[] itemFullNameA = itemFullName.isEmpty() ? new String[0] : itemFullName.split("/");
+ String[] groupFullNameA = groupFullName.isEmpty() ? new String[0] : groupFullName.split("/");
+ for (int i = 0; ; i++) {
+ if (i == itemFullNameA.length) {
+ if (i == groupFullNameA.length) {
+ // itemFullName and groupFullName are identical
+ return ".";
+ } else {
+ // itemFullName is an ancestor of groupFullName; insert ../ for rest of groupFullName
+ StringBuilder b = new StringBuilder();
+ for (int j = 0; j < groupFullNameA.length - itemFullNameA.length; j++) {
+ if (j > 0) {
+ b.append('/');
+ }
+ b.append("..");
+ }
+ return b.toString();
+ }
+ } else if (i == groupFullNameA.length) {
+ // groupFullName is an ancestor of itemFullName; insert rest of itemFullName
+ StringBuilder b = new StringBuilder();
+ for (int j = i; j < itemFullNameA.length; j++) {
+ if (j > i) {
+ b.append('/');
+ }
+ b.append(itemFullNameA[j]);
+ }
+ return b.toString();
+ } else if (itemFullNameA[i].equals(groupFullNameA[i])) {
+ // identical up to this point
continue;
+ } else {
+ // first mismatch; insert ../ for rest of groupFullName, then rest of itemFullName
+ StringBuilder b = new StringBuilder();
+ for (int j = i; j < groupFullNameA.length; j++) {
+ if (j > i) {
+ b.append('/');
+ }
+ b.append("..");
+ }
+ for (int j = i; j < itemFullNameA.length; j++) {
+ b.append('/').append(itemFullNameA[j]);
+ }
+ return b.toString();
}
}
- return StringUtils.join(r, '/');
}
-
/**
* Loads a {@link Item} from a config file.
*
@@ -300,6 +353,42 @@ public class Items {
return Jenkins.getInstance().getItem(nearest, context, type);
}
+ /**
+ * Moves an item between folders (or top level).
+ * Fires all relevant events but does not verify that the item’s directory is not currently being used in some way (for example by a running build).
+ * Does not check any permissions.
+ * @param item some item (job or folder)
+ * @param destination the destination of the move (a folder or {@link Jenkins}); not the current parent (or you could just call {@link AbstractItem#renameTo})
+ * @return the new item (usually the same object as {@code item})
+ * @throws IOException if the move fails, or some subsequent step fails (directory might have already been moved)
+ * @throws IllegalArgumentException if the move would really be a rename, or the destination cannot accept the item, or the destination already has an item of that name
+ * @since 1.548
+ */
+ public static I move(I item, DirectlyModifiableTopLevelItemGroup destination) throws IOException, IllegalArgumentException {
+ DirectlyModifiableTopLevelItemGroup oldParent = (DirectlyModifiableTopLevelItemGroup) item.getParent();
+ if (oldParent == destination) {
+ throw new IllegalArgumentException();
+ }
+ // TODO verify that destination is to not equal to, or inside, item
+ if (!destination.canAdd(item)) {
+ throw new IllegalArgumentException();
+ }
+ String name = item.getName();
+ if (destination.getItem(name) != null) {
+ throw new IllegalArgumentException(name + " already exists");
+ }
+ String oldFullName = item.getFullName();
+ // TODO AbstractItem.renameTo has a more baroque implementation; factor it out into a utility method perhaps?
+ File destDir = destination.getRootDirFor(item);
+ FileUtils.forceMkdir(destDir.getParentFile());
+ FileUtils.moveDirectory(item.getRootDir(), destDir);
+ oldParent.remove(item);
+ I newItem = destination.add(item, name);
+ newItem.onLoad(destination, name);
+ ItemListener.fireLocationChange(newItem, oldFullName);
+ return newItem;
+ }
+
/**
* Used to load/save job configuration.
*
diff --git a/core/src/main/java/hudson/model/Job.java b/core/src/main/java/hudson/model/Job.java
index aef474184a..87590f8f9a 100644
--- a/core/src/main/java/hudson/model/Job.java
+++ b/core/src/main/java/hudson/model/Job.java
@@ -54,6 +54,7 @@ import hudson.util.DescribableList;
import hudson.util.FormApply;
import hudson.util.Graph;
import hudson.util.ProcessTree;
+import hudson.util.QuotedStringTokenizer;
import hudson.util.RunList;
import hudson.util.ShiftedCategoryAxis;
import hudson.util.StackedAreaRenderer2;
@@ -357,10 +358,12 @@ public abstract class Job, RunT extends Run, RunT extends Run, RunT extends Run, RunT extends Run {
@@ -1269,7 +1273,7 @@ public abstract class Job, RunT extends Run data = new DataSetBuilder();
- for (Run r : getBuilds()) {
+ for (Run r : getNewBuilds()) {
if (r.isBuilding())
continue;
data.add(((double) r.getDuration()) / (1000 * 60), "min",
@@ -1345,6 +1349,16 @@ public abstract class Job, RunT extends Run getDefaultColumns() {
return ListViewColumn.createDefaultInitialColumnList();
}
+
+ @Restricted(NoExternalUse.class)
+ @Extension public static final class Listener extends ItemListener {
+ @Override public void onLocationChanged(Item item, String oldFullName, String newFullName) {
+ for (Item g : Jenkins.getInstance().getAllItems()) {
+ if (g instanceof ViewGroup) {
+ ViewGroup vg = (ViewGroup) g;
+ for (View v : vg.getViews()) {
+ if (v instanceof ListView) {
+ ListView lv = (ListView) v;
+ synchronized (lv) {
+ Set oldJobNames = new HashSet(lv.jobNames);
+ lv.jobNames.clear();
+ for (String oldName : oldJobNames) {
+ lv.jobNames.add(Items.computeRelativeNamesAfterRenaming(oldFullName, newFullName, oldName, vg.getItemGroup()));
+ }
+ if (!oldJobNames.equals(lv.jobNames)) {
+ try {
+ g.save();
+ } catch (IOException x) {
+ Logger.getLogger(ListView.class.getName()).log(Level.WARNING, null, x);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ @Override public void onDeleted(Item item) {
+ for (Item g : Jenkins.getInstance().getAllItems()) {
+ if (g instanceof ViewGroup) {
+ ViewGroup vg = (ViewGroup) g;
+ for (View v : vg.getViews()) {
+ if (v instanceof ListView) {
+ ListView lv = (ListView) v;
+ synchronized (lv) {
+ if (lv.jobNames.remove(item.getRelativeNameFrom(vg.getItemGroup()))) {
+ try {
+ g.save();
+ } catch (IOException x) {
+ Logger.getLogger(ListView.class.getName()).log(Level.WARNING, null, x);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
}
diff --git a/core/src/main/java/hudson/model/ModifiableViewGroup.java b/core/src/main/java/hudson/model/ModifiableViewGroup.java
new file mode 100644
index 0000000000..6a2542af38
--- /dev/null
+++ b/core/src/main/java/hudson/model/ModifiableViewGroup.java
@@ -0,0 +1,42 @@
+/*
+ * The MIT License
+ *
+ * Copyright (c) 2013 Red Hat, Inc.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package hudson.model;
+
+import java.io.IOException;
+
+import javax.annotation.Nonnull;
+
+/**
+ * {@link ViewGroup} that can be modified.
+ *
+ * @author ogondza
+ * @since 1.545
+ */
+public interface ModifiableViewGroup extends ViewGroup {
+
+ /**
+ * Add new {@link View} to this {@link ViewGroup}.
+ */
+ public void addView(@Nonnull View view) throws IOException;
+}
diff --git a/core/src/main/java/hudson/model/MyView.java b/core/src/main/java/hudson/model/MyView.java
index f10c2540eb..2cac72e38b 100644
--- a/core/src/main/java/hudson/model/MyView.java
+++ b/core/src/main/java/hudson/model/MyView.java
@@ -86,11 +86,6 @@ public class MyView extends View {
return ""; // there's no configuration page
}
- @Override
- public void onJobRenamed(Item item, String oldName, String newName) {
- // noop
- }
-
@Override
protected void submit(StaplerRequest req) throws IOException, ServletException, FormException {
// noop
diff --git a/core/src/main/java/hudson/model/MyViewsProperty.java b/core/src/main/java/hudson/model/MyViewsProperty.java
index 3f65ba8d3b..a7a40014e8 100644
--- a/core/src/main/java/hudson/model/MyViewsProperty.java
+++ b/core/src/main/java/hudson/model/MyViewsProperty.java
@@ -58,7 +58,7 @@ import org.kohsuke.stapler.StaplerResponse;
*
* @author Tom Huybrechts
*/
-public class MyViewsProperty extends UserProperty implements ViewGroup, Action, StaplerFallback {
+public class MyViewsProperty extends UserProperty implements ModifiableViewGroup, Action, StaplerFallback {
private String primaryViewName;
/**
@@ -136,6 +136,7 @@ public class MyViewsProperty extends UserProperty implements ViewGroup, Action,
viewGroupMixIn.onViewRenamed(view,oldName,newName);
}
+ @Override
public void addView(View view) throws IOException {
viewGroupMixIn.addView(view);
}
diff --git a/core/src/main/java/hudson/model/Node.java b/core/src/main/java/hudson/model/Node.java
index f542b78411..d92f684208 100644
--- a/core/src/main/java/hudson/model/Node.java
+++ b/core/src/main/java/hudson/model/Node.java
@@ -371,7 +371,7 @@ public abstract class Node extends AbstractModelObject implements Reconfigurable
* null if this node is not connected hence the path is not available
*/
// TODO: should this be modified now that getWorkspace is moved from AbstractProject to AbstractBuild?
- public abstract FilePath getWorkspaceFor(TopLevelItem item);
+ public abstract @CheckForNull FilePath getWorkspaceFor(TopLevelItem item);
/**
* Gets the root directory of this node.
@@ -384,7 +384,7 @@ public abstract class Node extends AbstractModelObject implements Reconfigurable
* null if the node is offline and hence the {@link FilePath}
* object is not available.
*/
- public abstract FilePath getRootPath();
+ public abstract @CheckForNull FilePath getRootPath();
/**
* Gets the {@link FilePath} on this node.
diff --git a/core/src/main/java/hudson/model/PaneStatusProperties.java b/core/src/main/java/hudson/model/PaneStatusProperties.java
new file mode 100644
index 0000000000..9f8be77227
--- /dev/null
+++ b/core/src/main/java/hudson/model/PaneStatusProperties.java
@@ -0,0 +1,98 @@
+package hudson.model;
+
+import static java.lang.String.format;
+import hudson.Extension;
+import hudson.util.PersistedList;
+
+import java.io.IOException;
+
+import javax.servlet.http.HttpSession;
+
+import org.kohsuke.stapler.Stapler;
+
+public class PaneStatusProperties extends UserProperty implements Saveable {
+
+ private final PersistedList collapsed = new PersistedList(this);
+
+ private static final PaneStatusProperties FALLBACK = new PaneStatusPropertiesSessionFallback();
+
+ public boolean isCollapsed(String paneId) {
+ return collapsed.contains(paneId);
+ }
+
+ /**
+ * @param paneId panel name
+ * @return the actual state of panel
+ */
+ public boolean toggleCollapsed(String paneId) throws IOException {
+ if (collapsed.contains(paneId)) {
+ collapsed.remove(paneId);
+ return false;
+ } else {
+ collapsed.add(paneId);
+ return true;
+ }
+ }
+
+ public void save() throws IOException {
+ user.save();
+ }
+
+ private Object readResolve() {
+ collapsed.setOwner(this);
+ return this;
+ }
+
+ @Extension
+ public static class DescriptorImpl extends UserPropertyDescriptor {
+
+ @Override
+ public UserProperty newInstance(User user) {
+ return new PaneStatusProperties();
+ }
+
+ @Override
+ public String getDisplayName() {
+ return null;
+ }
+
+ @Override
+ public boolean isEnabled() {
+ return false;
+ }
+
+ }
+
+ private static class PaneStatusPropertiesSessionFallback extends PaneStatusProperties {
+
+ private final String attribute = "jenkins_pane_%s_collapsed";
+
+ @Override
+ public boolean isCollapsed(String paneId) {
+ final HttpSession session = Stapler.getCurrentRequest().getSession();
+ return session.getAttribute(format(attribute, paneId)) != null;
+ }
+
+ @Override
+ public boolean toggleCollapsed(String paneId) {
+ final HttpSession session = Stapler.getCurrentRequest().getSession();
+ final String property = format(attribute, paneId);
+ final Object collapsed = session.getAttribute(property);
+ if (collapsed == null) {
+ session.setAttribute(property, true);
+ return true;
+ }
+ session.removeAttribute(property);
+ return false;
+ }
+ }
+
+ public static PaneStatusProperties forCurrentUser() {
+ final User current = User.current();
+ if (current == null) {
+ return FALLBACK;
+ }
+ return current.getProperty(PaneStatusProperties.class);
+ }
+
+}
diff --git a/core/src/main/java/hudson/model/PasswordParameterDefinition.java b/core/src/main/java/hudson/model/PasswordParameterDefinition.java
index 6c3388cd5e..ce93144a56 100644
--- a/core/src/main/java/hudson/model/PasswordParameterDefinition.java
+++ b/core/src/main/java/hudson/model/PasswordParameterDefinition.java
@@ -28,6 +28,8 @@ import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.DataBoundConstructor;
import hudson.Extension;
import hudson.util.Secret;
+import org.kohsuke.accmod.Restricted;
+import org.kohsuke.accmod.restrictions.DoNotUse;
/**
* Parameter whose value is a {@link Secret} and is hidden from the UI.
@@ -76,6 +78,11 @@ public class PasswordParameterDefinition extends SimpleParameterDefinition {
return Secret.toString(defaultValue);
}
+ @Restricted(DoNotUse.class) // used from Jelly
+ public Secret getDefaultValueAsSecret() {
+ return defaultValue;
+ }
+
// kept for backward compatibility
public void setDefaultValue(String defaultValue) {
this.defaultValue = Secret.fromString(defaultValue);
diff --git a/core/src/main/java/hudson/model/ProxyView.java b/core/src/main/java/hudson/model/ProxyView.java
index 3c3c3c3f63..183abd566d 100644
--- a/core/src/main/java/hudson/model/ProxyView.java
+++ b/core/src/main/java/hudson/model/ProxyView.java
@@ -89,13 +89,6 @@ public class ProxyView extends View implements StaplerFallback {
return getProxiedView().contains(item);
}
- @Override
- public void onJobRenamed(Item item, String oldName, String newName) {
- if (oldName.equals(proxiedViewName)) {
- proxiedViewName = newName;
- }
- }
-
@Override
protected void submit(StaplerRequest req) throws IOException, ServletException, FormException {
String proxiedViewName = req.getSubmittedForm().getString("proxiedViewName");
diff --git a/core/src/main/java/hudson/model/Queue.java b/core/src/main/java/hudson/model/Queue.java
index 1280d702b4..c14bbe316c 100644
--- a/core/src/main/java/hudson/model/Queue.java
+++ b/core/src/main/java/hudson/model/Queue.java
@@ -116,6 +116,7 @@ import org.kohsuke.stapler.export.ExportedBean;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.basic.AbstractSingleValueConverter;
+import javax.annotation.CheckForNull;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.interceptor.RequirePOST;
@@ -448,12 +449,9 @@ public class Queue extends ResourceController implements Saveable {
/**
* Schedule a new build for this project.
- *
- * @return true if the project is actually added to the queue.
- * false if the queue contained it and therefore the add()
- * was noop
+ * @see #schedule(Task, int)
*/
- public WaitingItem schedule(AbstractProject p) {
+ public @CheckForNull WaitingItem schedule(AbstractProject p) {
return schedule(p, p.getQuietPeriod());
}
@@ -539,7 +537,7 @@ public class Queue extends ResourceController implements Saveable {
shouldScheduleItem |= action.shouldSchedule(actions);
}
for (QueueAction action: Util.filter(actions,QueueAction.class)) {
- shouldScheduleItem |= action.shouldSchedule(item.getActions());
+ shouldScheduleItem |= action.shouldSchedule((new ArrayList(item.getAllActions())));
}
if(!shouldScheduleItem) {
duplicatesInQueue.add(item);
@@ -603,7 +601,7 @@ public class Queue extends ResourceController implements Saveable {
return schedule(p, quietPeriod)!=null;
}
- public synchronized WaitingItem schedule(Task p, int quietPeriod) {
+ public synchronized @CheckForNull WaitingItem schedule(Task p, int quietPeriod) {
return schedule(p, quietPeriod, new Action[0]);
}
@@ -618,7 +616,7 @@ public class Queue extends ResourceController implements Saveable {
/**
* Convenience wrapper method around {@link #schedule(Task, int, List)}
*/
- public synchronized WaitingItem schedule(Task p, int quietPeriod, Action... actions) {
+ public synchronized @CheckForNull WaitingItem schedule(Task p, int quietPeriod, Action... actions) {
return schedule2(p, quietPeriod, actions).getCreateItem();
}
@@ -853,8 +851,9 @@ public class Queue extends ResourceController implements Saveable {
return bi;
for (Item item : waitingList) {
- if (item.task == t)
+ if (item.task.equals(t)) {
return item;
+ }
}
return null;
}
@@ -870,8 +869,9 @@ public class Queue extends ResourceController implements Saveable {
result.addAll(buildables.getAll(t));
result.addAll(pendings.getAll(t));
for (Item item : waitingList) {
- if (item.task == t)
+ if (item.task.equals(t)) {
result.add(item);
+ }
}
return result;
}
@@ -892,8 +892,9 @@ public class Queue extends ResourceController implements Saveable {
if (blockedProjects.containsKey(t) || buildables.containsKey(t) || pendings.containsKey(t))
return true;
for (Item item : waitingList) {
- if (item.task == t)
+ if (item.task.equals(t)) {
return true;
+ }
}
return false;
}
@@ -1417,7 +1418,7 @@ public class Queue extends ResourceController implements Saveable {
}
protected Item(Item item) {
- this(item.task, item.getActions(), item.id, item.future, item.inQueueSince);
+ this(item.task, new ArrayList(item.getAllActions()), item.id, item.future, item.inQueueSince);
}
/**
@@ -1453,13 +1454,10 @@ public class Queue extends ResourceController implements Saveable {
@Exported
public String getParams() {
StringBuilder s = new StringBuilder();
- for(Action action : getActions()) {
- if(action instanceof ParametersAction) {
- ParametersAction pa = (ParametersAction)action;
- for (ParameterValue p : pa.getParameters()) {
- s.append('\n').append(p.getShortDescription());
- }
- }
+ for (ParametersAction pa : getActions(ParametersAction.class)) {
+ for (ParameterValue p : pa.getParameters()) {
+ s.append('\n').append(p.getShortDescription());
+ }
}
return s.toString();
}
@@ -2003,7 +2001,7 @@ public class Queue extends ResourceController implements Saveable {
private class ItemList extends ArrayList {
public T get(Task task) {
for (T item: this) {
- if (item.task == task) {
+ if (item.task.equals(task)) {
return item;
}
}
@@ -2013,7 +2011,7 @@ public class Queue extends ResourceController implements Saveable {
public List getAll(Task task) {
List result = new ArrayList();
for (T item: this) {
- if (item.task == task) {
+ if (item.task.equals(task)) {
result.add(item);
}
}
@@ -2028,7 +2026,7 @@ public class Queue extends ResourceController implements Saveable {
Iterator it = iterator();
while (it.hasNext()) {
T t = it.next();
- if (t.task == task) {
+ if (t.task.equals(task)) {
it.remove();
return t;
}
@@ -2037,7 +2035,7 @@ public class Queue extends ResourceController implements Saveable {
}
public void put(Task task, T item) {
- assert item.task == task;
+ assert item.task.equals(task);
add(item);
}
diff --git a/core/src/main/java/hudson/model/Run.java b/core/src/main/java/hudson/model/Run.java
index 3c29d7524a..b8540ebfea 100644
--- a/core/src/main/java/hudson/model/Run.java
+++ b/core/src/main/java/hudson/model/Run.java
@@ -55,6 +55,7 @@ import hudson.tasks.test.AbstractTestResultAction;
import hudson.util.FlushProofOutputStream;
import hudson.util.FormApply;
import hudson.util.LogTaskListener;
+import hudson.util.ProcessTree;
import hudson.util.XStream2;
import java.io.BufferedReader;
@@ -210,7 +211,7 @@ public abstract class Run ,RunT extends Run,RunT extends Run,RunT extends Run getTransientActions() {
List actions = new ArrayList();
for (TransientBuildActionFactory factory: TransientBuildActionFactory.all()) {
@@ -442,21 +445,11 @@ public abstract class Run ,RunT extends Run getBadgeActions() {
- List r = null;
- for (Action a : getActions()) {
- if(a instanceof BuildBadgeAction) {
- if(r==null)
- r = new ArrayList();
- r.add((BuildBadgeAction)a);
- }
- }
+ List r = getActions(BuildBadgeAction.class);
if(isKeepLog()) {
- if(r==null)
- r = new ArrayList();
r.add(new KeepLogBuildBadge());
}
- if(r==null) return Collections.emptyList();
- else return r;
+ return r;
}
/**
@@ -1252,7 +1245,7 @@ public abstract class Run ,RunT extends Run,RunT extends Run,RunT extends Run,RunT extends Run,RunT extends Run> extends AbstractLazyLoadRunMap
final SimpleDateFormat formatter = Run.ID_FORMATTER.get();
return new FilenameFilter() {
- public boolean accept(File dir, String name) {
- // JENKINS-1461 sometimes create bogus data directories with impossible dates, such as year 0, April 31st,
- // or August 0th. Date object doesn't roundtrip those, so we eventually fail to load this data.
- // Don't even bother trying.
- if (!isCorrectDate(name)) {
- LOGGER.log(FINE, "Skipping {0}", new File(dir,name));
+ @Override public boolean accept(File dir, String name) {
+ if (name.startsWith("0000")) {
+ // JENKINS-1461 sometimes create bogus data directories with impossible dates, such as year 0, April 31st,
+ // or August 0th. Date object doesn't roundtrip those, so we eventually fail to load this data.
+ // Don't even bother trying.
return false;
}
- return !name.startsWith("0000") && new File(dir,name).isDirectory();
- }
-
- private boolean isCorrectDate(String name) {
try {
- if(formatter.format(formatter.parse(name)).equals(name))
+ if (formatter.format(formatter.parse(name)).equals(name)) {
return true;
+ }
} catch (ParseException e) {
// fall through
}
+ LOGGER.log(FINE, "Skipping {0} in {1}", new Object[] {name, dir});
return false;
}
};
diff --git a/core/src/main/java/hudson/model/Slave.java b/core/src/main/java/hudson/model/Slave.java
index 46b4849596..5e9204f0a0 100644
--- a/core/src/main/java/hudson/model/Slave.java
+++ b/core/src/main/java/hudson/model/Slave.java
@@ -57,6 +57,7 @@ import java.util.Set;
import javax.servlet.ServletException;
import hudson.util.TimeUnit2;
+import javax.annotation.CheckForNull;
import jenkins.model.Jenkins;
import jenkins.slaves.WorkspaceLocator;
@@ -284,7 +285,7 @@ public abstract class Slave extends Node implements Serializable {
* @return
* null if not connected.
*/
- public FilePath getWorkspaceRoot() {
+ public @CheckForNull FilePath getWorkspaceRoot() {
FilePath r = getRootPath();
if(r==null) return null;
return r.child(WORKSPACE_ROOT);
diff --git a/core/src/main/java/hudson/model/TransientBuildActionFactory.java b/core/src/main/java/hudson/model/TransientBuildActionFactory.java
index ec3adf99ba..414c584b3a 100644
--- a/core/src/main/java/hudson/model/TransientBuildActionFactory.java
+++ b/core/src/main/java/hudson/model/TransientBuildActionFactory.java
@@ -6,6 +6,7 @@ import hudson.ExtensionPoint;
import jenkins.model.Jenkins;
import java.util.Collection;
import java.util.Collections;
+import jenkins.model.TransientActionFactory;
/**
* Extension point for inserting transient {@link Action}s into {@link Run}s.
@@ -15,8 +16,9 @@ import java.util.Collections;
* @author Lucie Votypkova
* @since 1.458
* @see Action
+ * @deprecated Does not contribute to {@link Run#getActions}. Use {@link TransientActionFactory} instead.
*/
-
+@Deprecated
public abstract class TransientBuildActionFactory implements ExtensionPoint {
/**
* Creates actions for the given build.
diff --git a/core/src/main/java/hudson/model/TransientComputerActionFactory.java b/core/src/main/java/hudson/model/TransientComputerActionFactory.java
index ee724ce044..cf4d490eb1 100644
--- a/core/src/main/java/hudson/model/TransientComputerActionFactory.java
+++ b/core/src/main/java/hudson/model/TransientComputerActionFactory.java
@@ -30,6 +30,7 @@ import jenkins.model.Jenkins;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
+import jenkins.model.TransientActionFactory;
/**
* Extension point for inserting transient {@link hudson.model.Action}s to {@link hudson.model.Computer}s.
@@ -39,6 +40,7 @@ import java.util.List;
* @author Stephen Connolly
* @since 1.405
* @see hudson.model.Action
+ * @see TransientActionFactory
*/
public abstract class TransientComputerActionFactory implements ExtensionPoint {
/**
diff --git a/core/src/main/java/hudson/model/TransientProjectActionFactory.java b/core/src/main/java/hudson/model/TransientProjectActionFactory.java
index 9588d83fe9..ebae7d2323 100644
--- a/core/src/main/java/hudson/model/TransientProjectActionFactory.java
+++ b/core/src/main/java/hudson/model/TransientProjectActionFactory.java
@@ -30,6 +30,7 @@ import hudson.tasks.BuildStep;
import jenkins.model.Jenkins;
import java.util.Collection;
+import jenkins.model.TransientActionFactory;
/**
* Extension point for inserting transient {@link Action}s into {@link AbstractProject}s.
@@ -50,6 +51,7 @@ import java.util.Collection;
* @author Kohsuke Kawaguchi
* @since 1.327
* @see Action
+ * @see TransientActionFactory
*/
public abstract class TransientProjectActionFactory implements ExtensionPoint {
/**
diff --git a/core/src/main/java/hudson/model/TreeView.java b/core/src/main/java/hudson/model/TreeView.java
index bf16d3d0fa..c97f892b46 100644
--- a/core/src/main/java/hudson/model/TreeView.java
+++ b/core/src/main/java/hudson/model/TreeView.java
@@ -119,14 +119,7 @@ public class TreeView extends View implements ViewGroup {
return null;
}
- @Override
- public synchronized void onJobRenamed(Item item, String oldName, String newName) {
- if(jobNames.remove(oldName) && newName!=null)
- jobNames.add(newName);
- // forward to children
- for (View v : views)
- v.onJobRenamed(item,oldName,newName);
- }
+ // TODO listen for changes that might affect jobNames
protected void submit(StaplerRequest req) throws IOException, ServletException, FormException {
}
diff --git a/core/src/main/java/hudson/model/UpdateSite.java b/core/src/main/java/hudson/model/UpdateSite.java
index 470ecaccab..8966234e6c 100644
--- a/core/src/main/java/hudson/model/UpdateSite.java
+++ b/core/src/main/java/hudson/model/UpdateSite.java
@@ -40,6 +40,7 @@ import jenkins.model.Jenkins;
import jenkins.util.JSONSignatureValidator;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
+import org.apache.commons.lang.StringUtils;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.StaplerRequest;
@@ -637,8 +638,12 @@ public class UpdateSite {
}
public String getDisplayName() {
- if(title!=null) return title;
- return name;
+ String displayName;
+ if(title!=null)
+ displayName = title;
+ else
+ displayName = name;
+ return StringUtils.removeStart(displayName, "Jenkins ");
}
/**
diff --git a/core/src/main/java/hudson/model/UsageStatistics.java b/core/src/main/java/hudson/model/UsageStatistics.java
index f350b06ee9..e7b77a42ca 100644
--- a/core/src/main/java/hudson/model/UsageStatistics.java
+++ b/core/src/main/java/hudson/model/UsageStatistics.java
@@ -156,7 +156,7 @@ public class UsageStatistics extends PageDecorator {
o.put("plugins",plugins);
JSONObject jobs = new JSONObject();
- List items = j.getItems();
+ List items = j.getAllItems(TopLevelItem.class);
for (TopLevelItemDescriptor d : Items.all()) {
int cnt=0;
for (TopLevelItem item : items) {
diff --git a/core/src/main/java/hudson/model/User.java b/core/src/main/java/hudson/model/User.java
index 94b6369975..3d9cdbb5b5 100644
--- a/core/src/main/java/hudson/model/User.java
+++ b/core/src/main/java/hudson/model/User.java
@@ -24,6 +24,7 @@
*/
package hudson.model;
+import com.google.common.base.Predicate;
import com.infradna.tool.bridge_method_injector.WithBridgeMethods;
import hudson.*;
import hudson.model.Descriptor.FormException;
@@ -349,9 +350,13 @@ public class User extends AbstractModelObject implements AccessControlled, Descr
if (LOGGER.isLoggable(Level.FINE) && !fullName.equals(prev.getFullName())) {
LOGGER.log(Level.FINE, "mismatch on fullName (‘" + fullName + "’ vs. ‘" + prev.getFullName() + "’) for ‘" + id + "’", new Throwable());
}
- }
- if (LOGGER.isLoggable(Level.FINE) && id.equals(fullName) && fullName.matches(".+ _\\S+@\\S+_")) {
- LOGGER.log(Level.FINE, "[JENKINS-16332] Suspicious fullName being stored: " + fullName, new Throwable());
+ } else if (!id.equals(fullName) && !getConfigFileFor(id).exists()) {
+ // JENKINS-16332: since the fullName may not be recoverable from the id, and various code may store the id only, we must save the fullName
+ try {
+ u.save();
+ } catch (IOException x) {
+ LOGGER.log(Level.WARNING, null, x);
+ }
}
}
return u;
@@ -432,30 +437,33 @@ public class User extends AbstractModelObject implements AccessControlled, Descr
return getFullName();
}
+ /** true if {@link AbstractBuild#hasParticipant} or {@link hudson.model.Cause.UserIdCause} */
+ private boolean relatedTo(AbstractBuild,?> b) {
+ if (b.hasParticipant(this)) {
+ return true;
+ }
+ for (Cause cause : b.getCauses()) {
+ if (cause instanceof Cause.UserIdCause) {
+ String userId = ((Cause.UserIdCause) cause).getUserId();
+ if (userId != null && userId.equals(getId())) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
/**
* Gets the list of {@link Build}s that include changes by this user,
* by the timestamp order.
- *
- * TODO: do we need some index for this?
*/
@WithBridgeMethods(List.class)
public RunList getBuilds() {
- List r = new ArrayList();
- for (AbstractProject,?> p : Jenkins.getInstance().getAllItems(AbstractProject.class))
- for (AbstractBuild,?> b : p.getBuilds().newBuilds()){
- if(b.hasParticipant(this))
- r.add(b);
- else {
- //append builds that were run by this user
- Cause.UserIdCause cause = b.getCause(Cause.UserIdCause.class);
- if (cause != null) {
- String userId = cause.getUserId();
- if (userId != null && this.getId() != null && userId.equals(this.getId()))
- r.add(b);
- }
- }
+ return new RunList>(Jenkins.getInstance().getAllItems(Job.class)).filter(new Predicate>() {
+ @Override public boolean apply(Run,?> r) {
+ return r instanceof AbstractBuild && relatedTo((AbstractBuild,?>) r);
}
- return RunList.fromRuns(r);
+ });
}
/**
@@ -573,21 +581,18 @@ public class User extends AbstractModelObject implements AccessControlled, Descr
}
public void doRssAll(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
- rss(req, rsp, " all builds", RunList.fromRuns(getBuilds()), Run.FEED_ADAPTER);
+ rss(req, rsp, " all builds", getBuilds(), Run.FEED_ADAPTER);
}
public void doRssFailed(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
- rss(req, rsp, " regression builds", RunList.fromRuns(getBuilds()).regressionOnly(), Run.FEED_ADAPTER);
+ rss(req, rsp, " regression builds", getBuilds().regressionOnly(), Run.FEED_ADAPTER);
}
public void doRssLatest(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
final List lastBuilds = new ArrayList();
- for (final TopLevelItem item : Jenkins.getInstance().getItems()) {
- if (!(item instanceof Job)) continue;
- for (Run r = ((Job) item).getLastBuild(); r != null; r = r.getPreviousBuild()) {
- if (!(r instanceof AbstractBuild)) continue;
- final AbstractBuild b = (AbstractBuild) r;
- if (b.hasParticipant(this)) {
+ for (AbstractProject,?> p : Jenkins.getInstance().getAllItems(AbstractProject.class)) {
+ for (AbstractBuild,?> b = p.getLastBuild(); b != null; b = b.getPreviousBuild()) {
+ if (relatedTo(b)) {
lastBuilds.add(b);
break;
}
@@ -668,6 +673,7 @@ public class User extends AbstractModelObject implements AccessControlled, Descr
r.add(n);
}
}
+ Collections.sort(r, String.CASE_INSENSITIVE_ORDER);
return r;
}
diff --git a/core/src/main/java/hudson/model/View.java b/core/src/main/java/hudson/model/View.java
index 1b0e1b982c..f27cd63547 100644
--- a/core/src/main/java/hudson/model/View.java
+++ b/core/src/main/java/hudson/model/View.java
@@ -114,7 +114,7 @@ import org.kohsuke.accmod.restrictions.NoExternalUse;
* This is an extension point in Hudson, allowing different kind of
* rendering to be added as plugins.
*
- *
Note for implementors
+ *
Note for implementers
*
*
* {@link View} subtypes need the newViewDetail.jelly page,
@@ -436,22 +436,21 @@ public abstract class View extends AbstractModelObject implements AccessControll
}
for (Computer c : computers) {
- Node n = c.getNode();
- if (n != null) {
- if (labels.contains(null) && n.getMode() == Mode.NORMAL || !isDisjoint(n.getAssignedLabels(), labels)) {
- result.add(c);
- }
- }
+ if (isRelevant(labels, c)) result.add(c);
}
return result;
}
- private boolean isDisjoint(Collection c1, Collection c2) {
- for (Object o : c1)
- if (c2.contains(o))
- return false;
- return true;
+ private boolean isRelevant(Collection