Merge branch 'master' into SCM-Job

This commit is contained in:
Jesse Glick committed 2014-06-05 14:57:06 -04:00
commit 4e24f702af
36 files changed
+712 -303

No files matched your search

+19 -6
View File
@@ -54,6 +54,19 @@ Upcoming changes</a>
<!-- Record your changes in the trunk here. -->
<div id="trunk" style="display:none"><!--=TRUNK-BEGIN=-->
<ul class=image>
<li class=bug>
Fixed <code>NullPointerException</code> caused by the uninitialized <code>ProcessStarter</code> environment in build wrappers
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-20559">issue 20559</a>)
<li class=rfe>
API changes allowing to create nested launchers (<code>DecoratedLauncher</code>)
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-19454">issue 19454</a>)
</ul>
</div><!--=TRUNK-END=-->
<!-- these changes are controlled by the release process. DO NOT MODIFY -->
<div id="rc" style="display:none;"><!--=BEGIN=-->
<h3><a name=v1.567>What's new in 1.567</a> <!--=DATE=--></h3>
<ul class=image>
<li class="bug">
Fixed a reference counting bug in the remoting layer.
@@ -82,6 +95,10 @@ Upcoming changes</a>
<li class="bug">
Process the items hierarchy when displaying the Show Poll Thread Count option
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-22934">issue 22934</a>)
<li class="bug">
Compressed output was turned on even before Access Denied errors were shown for disallowed Remote API requests, yielding a confusing error.
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-17374">issue 17374</a>)
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-18116">issue 18116</a>)
<li class="bug">
Properly close input streams in <code>FileParameterValue</code>
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-22693">issue 22693</a>)
@@ -113,11 +130,8 @@ Upcoming changes</a>
Added an option to archive artifacts only when the build is successful
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-22699">issue 22699</a>)
</ul>
</div><!--=TRUNK-END=-->
<!-- these changes are controlled by the release process. DO NOT MODIFY -->
<div id="rc" style="display:none;"><!--=BEGIN=-->
<h3><a name=v1.566>What's new in 1.566</a> <!--=DATE=--></h3>
</div><!--=END=-->
<h3><a name=v1.566>What's new in 1.566</a> (2014/06/01)</h3>
<ul class=image>
<li class="rfe">
Configurable case sensitivity mode for user IDs.
@@ -132,7 +146,6 @@ Upcoming changes</a>
Jenkins cannot restart Windows service
(<a href="https://issues.jenkins-ci.org/browse/JENKINS-22685">issue 22685</a>)
</ul>
</div><!--=END=-->
<h3><a name=v1.565>What's new in 1.565</a> (2014/05/26)</h3>
<ul class=image>
<li class="bug">
+1 -1
View File
@@ -5,7 +5,7 @@
<parent>
<artifactId>pom</artifactId>
<groupId>org.jenkins-ci.main</groupId>
<version>1.567-SNAPSHOT</version>
<version>1.568-SNAPSHOT</version>
</parent>
<artifactId>cli</artifactId>
+1 -1
View File
@@ -29,7 +29,7 @@ THE SOFTWARE.
<parent>
<groupId>org.jenkins-ci.main</groupId>
<artifactId>pom</artifactId>
<version>1.567-SNAPSHOT</version>
<version>1.568-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
+88 -1
View File
@@ -300,8 +300,13 @@ public abstract class Launcher {
return this;
}
/**
* Gets a list of environment variables to be set.
* Returns an empty array if envs field has not been initialized.
* @return If initialized, returns a copy of internal envs array. Otherwise - a new empty array.
*/
public String[] envs() {
return envs.clone();
return envs != null ? envs.clone() : new String[0];
}
/**
@@ -972,6 +977,88 @@ public abstract class Launcher {
}
}
}
/**
* A launcher which delegates to a provided inner launcher.
* Allows subclasses to only implement methods they want to override.
* Originally, this launcher has been implemented in
* <a href="https://wiki.jenkins-ci.org/display/JENKINS/Custom+Tools+Plugin">
* Custom Tools Plugin</a>.
*
* @author rcampbell
* @author Oleg Nenashev, Synopsys Inc.
* @since TODO: define version
*/
public static class DecoratedLauncher extends Launcher {
private Launcher inner = null;
public DecoratedLauncher(Launcher inner) {
super(inner);
this.inner = inner;
}
@Override
public Proc launch(ProcStarter starter) throws IOException {
return inner.launch(starter);
}
@Override
public Channel launchChannel(String[] cmd, OutputStream out,
FilePath workDir, Map<String, String> envVars) throws IOException,
InterruptedException {
return inner.launchChannel(cmd, out, workDir, envVars);
}
@Override
public void kill(Map<String, String> modelEnvVars) throws IOException,
InterruptedException {
inner.kill(modelEnvVars);
}
@Override
public boolean isUnix() {
return inner.isUnix();
}
@Override
public Proc launch(String[] cmd, boolean[] mask, String[] env, InputStream in, OutputStream out, FilePath workDir) throws IOException {
return inner.launch(cmd, mask, env, in, out, workDir);
}
@Override
public Computer getComputer() {
return inner.getComputer();
}
@Override
public TaskListener getListener() {
return inner.getListener();
}
@Override
public String toString() {
return super.toString() + "; decorates " + inner.toString();
}
@Override
public VirtualChannel getChannel() {
return inner.getChannel();
}
@Override
public Proc launch(String[] cmd, String[] env, InputStream in, OutputStream out, FilePath workDir) throws IOException {
return inner.launch(cmd, env, in, out, workDir);
}
/**
* Gets nested launcher.
* @return Inner launcher
*/
public Launcher getInner() {
return inner;
}
}
public static class IOTriplet implements Serializable {
InputStream stdout,stderr;
+122 -66
View File
@@ -73,6 +73,9 @@ import hudson.util.jna.Kernel32Utils;
import static hudson.util.jna.GNUCLibrary.LIBC;
import java.security.DigestInputStream;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.apache.commons.codec.digest.DigestUtils;
/**
@@ -94,7 +97,8 @@ public class Util {
* Creates a filtered sublist.
* @since 1.176
*/
public static <T> List<T> filter( Iterable<?> base, Class<T> type ) {
@Nonnull
public static <T> List<T> filter( @Nonnull Iterable<?> base, @Nonnull Class<T> type ) {
List<T> r = new ArrayList<T>();
for (Object i : base) {
if(type.isInstance(i))
@@ -106,7 +110,8 @@ public class Util {
/**
* Creates a filtered sublist.
*/
public static <T> List<T> filter( List<?> base, Class<T> type ) {
@Nonnull
public static <T> List<T> filter( @Nonnull List<?> base, @Nonnull Class<T> type ) {
return filter((Iterable)base,type);
}
@@ -122,7 +127,8 @@ public class Util {
* Unlike shell, undefined variables are left as-is (this behavior is the same as Ant.)
*
*/
public static String replaceMacro(String s, Map<String,String> properties) {
@Nullable
public static String replaceMacro( @CheckForNull String s, @Nonnull Map<String,String> properties) {
return replaceMacro(s,new VariableResolver.ByMap<String>(properties));
}
@@ -132,7 +138,8 @@ public class Util {
* <p>
* Unlike shell, undefined variables are left as-is (this behavior is the same as Ant.)
*/
public static String replaceMacro(String s, VariableResolver<String> resolver) {
@Nullable
public static String replaceMacro(@CheckForNull String s, @Nonnull VariableResolver<String> resolver) {
if (s == null) {
return null;
}
@@ -165,11 +172,13 @@ public class Util {
/**
* Loads the contents of a file into a string.
*/
public static String loadFile(File logfile) throws IOException {
@Nonnull
public static String loadFile(@Nonnull File logfile) throws IOException {
return loadFile(logfile, Charset.defaultCharset());
}
public static String loadFile(File logfile,Charset charset) throws IOException {
@Nonnull
public static String loadFile(@Nonnull File logfile, @Nonnull Charset charset) throws IOException {
if(!logfile.exists())
return "";
@@ -195,7 +204,7 @@ public class Util {
* @throws IOException
* if the operation fails.
*/
public static void deleteContentsRecursive(File file) throws IOException {
public static void deleteContentsRecursive(@Nonnull File file) throws IOException {
File[] files = file.listFiles();
if(files==null)
return; // the directory didn't exist in the first place
@@ -208,7 +217,7 @@ public class Util {
* @param f a file to delete
* @throws IOException if it exists but could not be successfully deleted
*/
public static void deleteFile(File f) throws IOException {
public static void deleteFile(@Nonnull File f) throws IOException {
if (!f.delete()) {
if(!f.exists())
// we are trying to delete a file that no longer exists, so this is not an error
@@ -259,7 +268,7 @@ public class Util {
/**
* Makes the given file writable by any means possible.
*/
private static void makeWritable(File f) {
private static void makeWritable(@Nonnull File f) {
if (f.setWritable(true)) {
return;
}
@@ -287,7 +296,7 @@ public class Util {
}
public static void deleteRecursive(File dir) throws IOException {
public static void deleteRecursive(@Nonnull File dir) throws IOException {
if(!isSymlink(dir))
deleteContentsRecursive(dir);
try {
@@ -321,7 +330,7 @@ public class Util {
* Checks if the given file represents a symlink.
*/
//Taken from http://svn.apache.org/viewvc/maven/shared/trunk/file-management/src/main/java/org/apache/maven/shared/model/fileset/util/FileSetManager.java?view=markup
public static boolean isSymlink(File file) throws IOException {
public static boolean isSymlink(@Nonnull File file) throws IOException {
Boolean r = isSymlinkJava7(file);
if (r != null) {
return r;
@@ -350,7 +359,7 @@ public class Util {
}
@SuppressWarnings("NP_BOOLEAN_RETURN_NULL")
private static Boolean isSymlinkJava7(File file) throws IOException {
private static Boolean isSymlinkJava7(@Nonnull File file) throws IOException {
try {
Object path = File.class.getMethod("toPath").invoke(file);
return (Boolean) Class.forName("java.nio.file.Files").getMethod("isSymbolicLink", Class.forName("java.nio.file.Path")).invoke(null, path);
@@ -379,13 +388,14 @@ public class Util {
* On Windows, error messages for IOException aren't very helpful.
* This method generates additional user-friendly error message to the listener
*/
public static void displayIOException( IOException e, TaskListener listener ) {
public static void displayIOException(@Nonnull IOException e, @Nonnull TaskListener listener ) {
String msg = getWin32ErrorMessage(e);
if(msg!=null)
listener.getLogger().println(msg);
}
public static String getWin32ErrorMessage(IOException e) {
@CheckForNull
public static String getWin32ErrorMessage(@Nonnull IOException e) {
return getWin32ErrorMessage((Throwable)e);
}
@@ -395,6 +405,7 @@ public class Util {
* @return
* null if there seems to be no error code or if the platform is not Win32.
*/
@CheckForNull
public static String getWin32ErrorMessage(Throwable e) {
String msg = e.getMessage();
if(msg!=null) {
@@ -420,6 +431,7 @@ public class Util {
* @return
* null if no such message is available.
*/
@CheckForNull
public static String getWin32ErrorMessage(int n) {
try {
ResourceBundle rb = ResourceBundle.getBundle("/hudson/win32errors");
@@ -433,6 +445,7 @@ public class Util {
/**
* Guesses the current host name.
*/
@Nonnull
public static String getHostName() {
try {
return InetAddress.getLocalHost().getHostName();
@@ -441,21 +454,21 @@ public class Util {
}
}
public static void copyStream(InputStream in,OutputStream out) throws IOException {
public static void copyStream(@Nonnull InputStream in,@Nonnull OutputStream out) throws IOException {
byte[] buf = new byte[8192];
int len;
while((len=in.read(buf))>=0)
out.write(buf,0,len);
}
public static void copyStream(Reader in, Writer out) throws IOException {
public static void copyStream(@Nonnull Reader in, @Nonnull Writer out) throws IOException {
char[] buf = new char[8192];
int len;
while((len=in.read(buf))>0)
out.write(buf,0,len);
}
public static void copyStreamAndClose(InputStream in,OutputStream out) throws IOException {
public static void copyStreamAndClose(@Nonnull InputStream in, @Nonnull OutputStream out) throws IOException {
try {
copyStream(in,out);
} finally {
@@ -464,7 +477,7 @@ public class Util {
}
}
public static void copyStreamAndClose(Reader in,Writer out) throws IOException {
public static void copyStreamAndClose(@Nonnull Reader in, @Nonnull Writer out) throws IOException {
try {
copyStream(in,out);
} finally {
@@ -483,18 +496,21 @@ public class Util {
* @since 1.145
* @see QuotedStringTokenizer
*/
public static String[] tokenize(String s,String delimiter) {
@Nonnull
public static String[] tokenize(@Nonnull String s, @CheckForNull String delimiter) {
return QuotedStringTokenizer.tokenize(s,delimiter);
}
public static String[] tokenize(String s) {
@Nonnull
public static String[] tokenize(@Nonnull String s) {
return tokenize(s," \t\n\r\f");
}
/**
* Converts the map format of the environment variables to the K=V format in the array.
*/
public static String[] mapToEnv(Map<String,String> m) {
@Nonnull
public static String[] mapToEnv(@Nonnull Map<String,String> m) {
String[] r = new String[m.size()];
int idx=0;
@@ -504,7 +520,7 @@ public class Util {
return r;
}
public static int min(int x, int... values) {
public static int min(int x, @Nonnull int... values) {
for (int i : values) {
if(i<x)
x=i;
@@ -512,11 +528,13 @@ public class Util {
return x;
}
public static String nullify(String v) {
@CheckForNull
public static String nullify(@CheckForNull String v) {
return fixEmpty(v);
}
public static String removeTrailingSlash(String s) {
@Nonnull
public static String removeTrailingSlash(@Nonnull String s) {
if(s.endsWith("/")) return s.substring(0,s.length()-1);
else return s;
}
@@ -531,7 +549,8 @@ public class Util {
* case subject was null and subject + suffix otherwise.
* @since 1.505
*/
public static String ensureEndsWith(String subject, String suffix) {
@Nullable
public static String ensureEndsWith(@CheckForNull String subject, @CheckForNull String suffix) {
if (subject == null) return null;
@@ -549,7 +568,8 @@ public class Util {
* 32-char wide string
* @see DigestUtils#md5Hex(InputStream)
*/
public static String getDigestOf(InputStream source) throws IOException {
@Nonnull
public static String getDigestOf(@Nonnull InputStream source) throws IOException {
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
@@ -574,7 +594,8 @@ public class Util {
*/
}
public static String getDigestOf(String text) {
@Nonnull
public static String getDigestOf(@Nonnull String text) {
try {
return getDigestOf(new ByteArrayInputStream(text.getBytes("UTF-8")));
} catch (IOException e) {
@@ -589,7 +610,8 @@ public class Util {
* @throws IOException in case reading fails
* @since 1.525
*/
public static String getDigestOf(File file) throws IOException {
@Nonnull
public static String getDigestOf(@Nonnull File file) throws IOException {
InputStream is = new FileInputStream(file);
try {
return getDigestOf(new BufferedInputStream(is));
@@ -602,7 +624,8 @@ public class Util {
* Converts a string into 128-bit AES key.
* @since 1.308
*/
public static SecretKey toAes128Key(String s) {
@Nonnull
public static SecretKey toAes128Key(@Nonnull String s) {
try {
// turn secretKey into 256 bit hash
MessageDigest digest = MessageDigest.getInstance("SHA-256");
@@ -618,7 +641,8 @@ public class Util {
}
}
public static String toHexString(byte[] data, int start, int len) {
@Nonnull
public static String toHexString(@Nonnull byte[] data, int start, int len) {
StringBuilder buf = new StringBuilder();
for( int i=0; i<len; i++ ) {
int b = data[start+i]&0xFF;
@@ -628,11 +652,13 @@ public class Util {
return buf.toString();
}
public static String toHexString(byte[] bytes) {
@Nonnull
public static String toHexString(@Nonnull byte[] bytes) {
return toHexString(bytes,0,bytes.length);
}
public static byte[] fromHexString(String data) {
@Nonnull
public static byte[] fromHexString(@Nonnull String data) {
byte[] r = new byte[data.length() / 2];
for (int i = 0; i < data.length(); i += 2)
r[i / 2] = (byte) Integer.parseInt(data.substring(i, i + 2), 16);
@@ -646,6 +672,7 @@ public class Util {
* @param duration
* number of milliseconds.
*/
@Nonnull
public static String getTimeSpanString(long duration) {
// Break the duration up in to units.
long years = duration / ONE_YEAR_MS;
@@ -692,10 +719,11 @@ public class Util {
* So 13 minutes and 43 seconds returns just "13 minutes", but 3 minutes
* and 43 seconds is "3 minutes 43 seconds".
*/
@Nonnull
private static String makeTimeSpanString(long bigUnit,
String bigLabel,
@Nonnull String bigLabel,
long smallUnit,
String smallLabel) {
@Nonnull String smallLabel) {
String text = bigLabel;
if (bigUnit < 10)
text += ' ' + smallLabel;
@@ -707,6 +735,7 @@ public class Util {
* Get a human readable string representing strings like "xxx days ago",
* which should be used to point to the occurrence of an event in the past.
*/
@Nonnull
public static String getPastTimeString(long duration) {
return Messages.Util_pastTime(getTimeSpanString(duration));
}
@@ -720,7 +749,8 @@ public class Util {
* See {@link Messages#Util_year(Object)} for an example.
* Deprecated since 2009-06-24, remove method after 2009-12-24.
*/
public static String combine(long n, String suffix) {
@Nonnull
public static String combine(long n, @Nonnull String suffix) {
String s = Long.toString(n)+' '+suffix;
if(n!=1)
// Just adding an 's' won't work in most natural languages, even English has exception to the rule (e.g. copy/copies).
@@ -731,7 +761,8 @@ public class Util {
/**
* Create a sub-list by only picking up instances of the specified type.
*/
public static <T> List<T> createSubList( Collection<?> source, Class<T> type ) {
@Nonnull
public static <T> List<T> createSubList(@Nonnull Collection<?> source, @Nonnull Class<T> type ) {
List<T> r = new ArrayList<T>();
for (Object item : source) {
if(type.isInstance(item))
@@ -749,7 +780,8 @@ public class Util {
* {@link #rawEncode(String)} should generally be used instead, though be careful to pass only
* a single path component to that method (it will encode /, but this method does not).
*/
public static String encode(String s) {
@Nonnull
public static String encode(@Nonnull String s) {
try {
boolean escaped = false;
@@ -806,7 +838,8 @@ public class Util {
* single path component used in constructing a URL.
* Method name inspired by PHP's rawurlencode.
*/
public static String rawEncode(String s) {
@Nonnull
public static String rawEncode(@Nonnull String s) {
boolean escaped = false;
StringBuilder out = null;
CharsetEncoder enc = null;
@@ -855,7 +888,8 @@ public class Util {
/**
* Escapes HTML unsafe characters like &lt;, &amp; to the respective character entities.
*/
public static String escape(String text) {
@Nonnull
public static String escape(@Nonnull String text) {
if (text==null) return null;
StringBuilder buf = new StringBuilder(text.length()+64);
for( int i=0; i<text.length(); i++ ) {
@@ -888,7 +922,8 @@ public class Util {
return buf.toString();
}
public static String xmlEscape(String text) {
@Nonnull
public static String xmlEscape(@Nonnull String text) {
StringBuilder buf = new StringBuilder(text.length()+64);
for( int i=0; i<text.length(); i++ ) {
char ch = text.charAt(i);
@@ -906,14 +941,14 @@ public class Util {
/**
* Creates an empty file.
*/
public static void touch(File file) throws IOException {
public static void touch(@Nonnull File file) throws IOException {
new FileOutputStream(file).close();
}
/**
* Copies a single file by using Ant.
*/
public static void copyFile(File src, File dst) throws BuildException {
public static void copyFile(@Nonnull File src, @Nonnull File dst) throws BuildException {
Copy cp = new Copy();
cp.setProject(new org.apache.tools.ant.Project());
cp.setTofile(dst);
@@ -925,7 +960,8 @@ public class Util {
/**
* Convert null to "".
*/
public static String fixNull(String s) {
@Nonnull
public static String fixNull(@CheckForNull String s) {
if(s==null) return "";
else return s;
}
@@ -933,7 +969,8 @@ public class Util {
/**
* Convert empty string to null.
*/
public static String fixEmpty(String s) {
@CheckForNull
public static String fixEmpty(@CheckForNull String s) {
if(s==null || s.length()==0) return null;
return s;
}
@@ -943,31 +980,37 @@ public class Util {
*
* @since 1.154
*/
public static String fixEmptyAndTrim(String s) {
@CheckForNull
public static String fixEmptyAndTrim(@CheckForNull String s) {
if(s==null) return null;
return fixEmpty(s.trim());
}
public static <T> List<T> fixNull(List<T> l) {
@Nonnull
public static <T> List<T> fixNull(@CheckForNull List<T> l) {
return l!=null ? l : Collections.<T>emptyList();
}
public static <T> Set<T> fixNull(Set<T> l) {
@Nonnull
public static <T> Set<T> fixNull(@CheckForNull Set<T> l) {
return l!=null ? l : Collections.<T>emptySet();
}
public static <T> Collection<T> fixNull(Collection<T> l) {
@Nonnull
public static <T> Collection<T> fixNull(@CheckForNull Collection<T> l) {
return l!=null ? l : Collections.<T>emptySet();
}
public static <T> Iterable<T> fixNull(Iterable<T> l) {
@Nonnull
public static <T> Iterable<T> fixNull(@CheckForNull Iterable<T> l) {
return l!=null ? l : Collections.<T>emptySet();
}
/**
* Cuts all the leading path portion and get just the file name.
*/
public static String getFileName(String filePath) {
@Nonnull
public static String getFileName(@Nonnull String filePath) {
int idx = filePath.lastIndexOf('\\');
if(idx>=0)
return getFileName(filePath.substring(idx+1));
@@ -980,7 +1023,8 @@ public class Util {
/**
* Concatenate multiple strings by inserting a separator.
*/
public static String join(Collection<?> strings, String separator) {
@Nonnull
public static String join(@Nonnull Collection<?> strings, @Nonnull String separator) {
StringBuilder buf = new StringBuilder();
boolean first=true;
for (Object s : strings) {
@@ -994,7 +1038,8 @@ public class Util {
/**
* Combines all the given collections into a single list.
*/
public static <T> List<T> join(Collection<? extends T>... items) {
@Nonnull
public static <T> List<T> join(@Nonnull Collection<? extends T>... items) {
int size = 0;
for (Collection<? extends T> item : items)
size += item.size();
@@ -1021,7 +1066,8 @@ public class Util {
* Can be null.
* @since 1.172
*/
public static FileSet createFileSet(File baseDir, String includes, String excludes) {
@Nonnull
public static FileSet createFileSet(@Nonnull File baseDir, @Nonnull String includes, @CheckForNull String excludes) {
FileSet fs = new FileSet();
fs.setDir(baseDir);
fs.setProject(new Project());
@@ -1043,7 +1089,8 @@ public class Util {
return fs;
}
public static FileSet createFileSet(File baseDir, String includes) {
@Nonnull
public static FileSet createFileSet(@Nonnull File baseDir, @Nonnull String includes) {
return createFileSet(baseDir,includes,null);
}
@@ -1059,7 +1106,8 @@ public class Util {
* @param symlinkPath
* Where to create a symlink in (relative to {@code baseDir})
*/
public static void createSymlink(File baseDir, String targetPath, String symlinkPath, TaskListener listener) throws InterruptedException {
public static void createSymlink(@Nonnull File baseDir, @Nonnull String targetPath,
@Nonnull String symlinkPath, @Nonnull TaskListener listener) throws InterruptedException {
try {
if (createSymlinkJava7(baseDir, targetPath, symlinkPath)) {
return;
@@ -1131,7 +1179,7 @@ public class Util {
}
}
private static boolean createSymlinkJava7(File baseDir, String targetPath, String symlinkPath) throws IOException {
private static boolean createSymlinkJava7(@Nonnull File baseDir, @Nonnull String targetPath, @Nonnull String symlinkPath) throws IOException {
try {
Object path = File.class.getMethod("toPath").invoke(new File(baseDir, symlinkPath));
Object target = Class.forName("java.nio.file.Paths").getMethod("get", String.class, String[].class).invoke(null, targetPath, new String[0]);
@@ -1201,7 +1249,8 @@ public class Util {
* @return null
* if the specified file is not a symlink.
*/
public static File resolveSymlinkToFile(File link) throws InterruptedException, IOException {
@CheckForNull
public static File resolveSymlinkToFile(@Nonnull File link) throws InterruptedException, IOException {
String target = resolveSymlink(link);
if (target==null) return null;
@@ -1221,7 +1270,8 @@ public class Util {
* If the symlink is relative, the returned string is that relative representation.
* The relative path is meant to be resolved from the location of the symlink.
*/
public static String resolveSymlink(File link) throws InterruptedException, IOException {
@CheckForNull
public static String resolveSymlink(@Nonnull File link) throws InterruptedException, IOException {
try { // Java 7
Object path = File.class.getMethod("toPath").invoke(link);
return Class.forName("java.nio.file.Files").getMethod("readSymbolicLink", Class.forName("java.nio.file.Path")).invoke(null, path).toString();
@@ -1306,7 +1356,8 @@ public class Util {
* Wraps with the error icon and the CSS class to render error message.
* @since 1.173
*/
public static String wrapToErrorSpan(String s) {
@Nonnull
public static String wrapToErrorSpan(@Nonnull String s) {
s = "<span class=error style='display:inline-block'>"+s+"</span>";
return s;
}
@@ -1319,7 +1370,8 @@ public class Util {
* @param defaultNumber number to return if the string can not be parsed
* @return returns the parsed string; otherwise the default number
*/
public static Number tryParseNumber(String numberStr, Number defaultNumber) {
@CheckForNull
public static Number tryParseNumber(@CheckForNull String numberStr, @CheckForNull Number defaultNumber) {
if ((numberStr == null) || (numberStr.length() == 0)) {
return defaultNumber;
}
@@ -1334,7 +1386,7 @@ public class Util {
* Checks if the public method defined on the base type with the given arguments
* are overridden in the given derived type.
*/
public static boolean isOverridden(Class base, Class derived, String methodName, Class... types) {
public static boolean isOverridden(@Nonnull Class base, @Nonnull Class derived, @Nonnull String methodName, @Nonnull Class... types) {
try {
return !base.getMethod(methodName, types).equals(
derived.getMethod(methodName,types));
@@ -1349,7 +1401,8 @@ public class Util {
* @param ext
* For example, ".zip"
*/
public static File changeExtension(File dst, String ext) {
@Nonnull
public static File changeExtension(@Nonnull File dst, @Nonnull String ext) {
String p = dst.getPath();
int pos = p.lastIndexOf('.');
if (pos<0) return new File(p+ext);
@@ -1358,8 +1411,10 @@ public class Util {
/**
* Null-safe String intern method.
* @return A canonical representation for the string object. Null for null input strings
*/
public static String intern(String s) {
@Nullable
public static String intern(@CheckForNull String s) {
return s==null ? s : s.intern();
}
@@ -1370,7 +1425,7 @@ public class Util {
* implementing this by ourselves allow it to be more lenient about
* escaping of URI.
*/
public static boolean isAbsoluteUri(String uri) {
public static boolean isAbsoluteUri(@Nonnull String uri) {
int idx = uri.indexOf(':');
if (idx<0) return false; // no ':'. can't be absolute
@@ -1382,7 +1437,7 @@ public class Util {
* Works like {@link String#indexOf(int)} but 'not found' is returned as s.length(), not -1.
* This enables more straight-forward comparison.
*/
private static int _indexOf(String s, char ch) {
private static int _indexOf(@Nonnull String s, char ch) {
int idx = s.indexOf(ch);
if (idx<0) return s.length();
return idx;
@@ -1392,7 +1447,8 @@ public class Util {
* Loads a key/value pair string as {@link Properties}
* @since 1.392
*/
public static Properties loadProperties(String properties) throws IOException {
@Nonnull
public static Properties loadProperties(@Nonnull String properties) throws IOException {
Properties p = new Properties();
p.load(new StringReader(properties));
return p;
@@ -122,6 +122,9 @@ public class InstallToolCommand extends CLICommand {
throw new AbortException(b.getFullDisplayName()+" is not building");
Node node = exec.getOwner().getNode();
if (node == null) {
throw new AbortException("The node " + exec.getOwner().getDisplayName() + " has been deleted");
}
t = t.translate(node, EnvVars.getRemote(checkChannel()), new StreamTaskListener(stderr));
stdout.println(t.getHome());
@@ -84,9 +84,11 @@ import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import org.kohsuke.stapler.interceptor.RequirePOST;
import static java.util.logging.Level.WARNING;
import jenkins.model.lazy.BuildReference;
import jenkins.model.lazy.LazyBuildMixIn;
@@ -435,9 +437,20 @@ public abstract class AbstractBuild<P extends AbstractProject<P,R>,R extends Abs
/**
* Returns the current {@link Node} on which we are building.
* @return Returns the current {@link Node}
* @throws IllegalStateException if that cannot be determined
*/
protected final Node getCurrentNode() {
return Executor.currentExecutor().getOwner().getNode();
protected final @Nonnull Node getCurrentNode() throws IllegalStateException {
Executor exec = Executor.currentExecutor();
if (exec == null) {
throw new IllegalStateException("not being called from an executor thread");
}
Computer c = exec.getOwner();
Node node = c.getNode();
if (node == null) {
throw new IllegalStateException("no longer a configured node for " + c.getName());
}
return node;
}
public Launcher getLauncher() {
@@ -456,7 +469,7 @@ public abstract class AbstractBuild<P extends AbstractProject<P,R>,R extends Abs
* @param wsl
* Passed in for the convenience. The returned path must be registered to this object.
*/
protected Lease decideWorkspace(Node n, WorkspaceList wsl) throws InterruptedException, IOException {
protected Lease decideWorkspace(@Nonnull Node n, WorkspaceList wsl) throws InterruptedException, IOException {
String customWorkspace = getProject().getCustomWorkspace();
if (customWorkspace != null) {
// we allow custom workspaces to be concurrently used between jobs.
@@ -466,8 +479,9 @@ public abstract class AbstractBuild<P extends AbstractProject<P,R>,R extends Abs
return wsl.allocate(n.getWorkspaceFor((TopLevelItem)getProject()), getBuild());
}
public Result run(BuildListener listener) throws Exception {
Node node = getCurrentNode();
public Result run(@Nonnull BuildListener listener) throws Exception {
final Node node = getCurrentNode();
assert builtOn==null;
builtOn = node.getNodeName();
hudsonVersion = Jenkins.VERSION;
@@ -555,8 +569,10 @@ public abstract class AbstractBuild<P extends AbstractProject<P,R>,R extends Abs
* @param listener
* Always non-null. Connected to the main build output.
*/
protected Launcher createLauncher(BuildListener listener) throws IOException, InterruptedException {
Launcher l = getCurrentNode().createLauncher(listener);
@Nonnull
protected Launcher createLauncher(@Nonnull BuildListener listener) throws IOException, InterruptedException {
final Node currentNode = getCurrentNode();
Launcher l = currentNode.createLauncher(listener);
if (project instanceof BuildableItemWithBuildWrappers) {
BuildableItemWithBuildWrappers biwbw = (BuildableItemWithBuildWrappers) project;
@@ -580,7 +596,7 @@ public abstract class AbstractBuild<P extends AbstractProject<P,R>,R extends Abs
}
}
for (NodeProperty nodeProperty: Computer.currentComputer().getNode().getNodeProperties()) {
for (NodeProperty nodeProperty: currentNode.getNodeProperties()) {
Environment environment = nodeProperty.setUp(AbstractBuild.this, l, listener);
if (environment != null) {
buildEnvironments.add(environment);
@@ -165,9 +165,10 @@ public abstract class AbstractCIBase extends Node implements ItemGroup<TopLevelI
synchronized(updateComputerLock) {// just so that we don't have two code updating computer list at the same time
Map<String,Computer> byName = new HashMap<String,Computer>();
for (Computer c : computers.values()) {
if(c.getNode()==null)
Node node = c.getNode();
if (node == null)
continue; // this computer is gone
byName.put(c.getNode().getNodeName(),c);
byName.put(node.getNodeName(),c);
}
Set<Computer> old = new HashSet<Computer>(computers.values());
+17 -8
View File
@@ -154,16 +154,21 @@ public class Api extends AbstractModelObject {
throw new IOException("Failed to do XPath/wrapper handling. Turn on FINER logging to view XML.",e);
}
if (isSimpleOutput(result) && !permit(req)) {
// simple output prohibited
rsp.sendError(HttpURLConnection.HTTP_FORBIDDEN, "primitive XPath result sets forbidden; implement jenkins.security.SecureRequester");
return;
}
// switch to gzipped output
OutputStream o = rsp.getCompressedOutputStream(req);
try {
if (result instanceof CharacterData || result instanceof String || result instanceof Number || result instanceof Boolean) {
if (permit(req)) {
rsp.setContentType("text/plain;charset=UTF-8");
String text = result instanceof CharacterData ? ((CharacterData) result).getText() : result.toString();
o.write(text.getBytes("UTF-8"));
} else {
rsp.sendError(HttpURLConnection.HTTP_FORBIDDEN, "primitive XPath result sets forbidden; implement jenkins.security.SecureRequester");
}
if (isSimpleOutput(result)) {
// simple output allowed
rsp.setContentType("text/plain;charset=UTF-8");
String text = result instanceof CharacterData ? ((CharacterData) result).getText() : result.toString();
o.write(text.getBytes("UTF-8"));
return;
}
@@ -175,6 +180,10 @@ public class Api extends AbstractModelObject {
}
}
private boolean isSimpleOutput(Object result) {
return result instanceof CharacterData || result instanceof String || result instanceof Number || result instanceof Boolean;
}
/**
* Generate schema.
*/
+5 -4
View File
@@ -42,6 +42,7 @@ import java.util.logging.Logger;
import java.util.logging.Level;
import static hudson.model.Result.FAILURE;
import javax.annotation.Nonnull;
/**
* A build of a {@link Project}.
@@ -135,7 +136,7 @@ public abstract class Build <P extends Project<P,B>,B extends Build<P,B>>
deprecated class here.
*/
protected Result doRun(BuildListener listener) throws Exception {
protected Result doRun(@Nonnull BuildListener listener) throws Exception {
if(!preBuild(listener,project.getBuilders()))
return FAILURE;
if(!preBuild(listener,project.getPublishersList()))
@@ -178,7 +179,7 @@ public abstract class Build <P extends Project<P,B>,B extends Build<P,B>>
return r;
}
public void post2(BuildListener listener) throws IOException, InterruptedException {
public void post2(@Nonnull BuildListener listener) throws IOException, InterruptedException {
if (!performAllBuildSteps(listener, project.getPublishersList(), true))
setResult(FAILURE);
if (!performAllBuildSteps(listener, project.getProperties(), true))
@@ -186,14 +187,14 @@ public abstract class Build <P extends Project<P,B>,B extends Build<P,B>>
}
@Override
public void cleanUp(BuildListener listener) throws Exception {
public void cleanUp(@Nonnull BuildListener listener) throws Exception {
// at this point it's too late to mark the build as a failure, so ignore return value.
performAllBuildSteps(listener, project.getPublishersList(), false);
performAllBuildSteps(listener, project.getProperties(), false);
super.cleanUp(listener);
}
private boolean build(BuildListener listener, Collection<Builder> steps) throws IOException, InterruptedException {
private boolean build(@Nonnull BuildListener listener, @Nonnull Collection<Builder> steps) throws IOException, InterruptedException {
for( BuildStep bs : steps ) {
if(!perform(bs,listener)) {
LOGGER.log(Level.FINE, "{0} : {1} failed", new Object[] {Build.this, bs});
+14 -4
View File
@@ -204,7 +204,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces
/**
* This is where the log from the remote agent goes.
*
* The method also creates a log directory if required.
* @see #relocateOldLogs()
*/
protected File getLogFile() {
@@ -1196,7 +1196,11 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces
// read
checkPermission(EXTENDED_READ);
rsp.setContentType("application/xml");
Jenkins.XSTREAM2.toXMLUTF8(getNode(), rsp.getOutputStream());
Node node = getNode();
if (node == null) {
throw HttpResponses.notFound();
}
Jenkins.XSTREAM2.toXMLUTF8(node, rsp.getOutputStream());
return;
}
if (req.getMethod().equals("POST")) {
@@ -1218,7 +1222,8 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces
// replace the old Node object by the new one
synchronized (app) {
List<Node> nodes = new ArrayList<Node>(app.getNodes());
int i = nodes.indexOf(getNode());
Node node = getNode();
int i = (node != null) ? nodes.indexOf(node) : -1;
if(i<0) {
throw new IOException("This slave appears to be removed while you were editing the configuration");
}
@@ -1348,7 +1353,12 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces
if (m.matches()) {
File newLocation = new File(dir, "logs/slaves/" + m.group(1) + "/slave.log" + Util.fixNull(m.group(2)));
newLocation.getParentFile().mkdirs();
f.renameTo(newLocation);
boolean relocationSuccessfull=f.renameTo(newLocation);
if (relocationSuccessfull) { // The operation will fail if mkdir fails
LOGGER.log(Level.INFO, "Relocated log file {0} to {1}",new Object[] {f.getPath(),newLocation.getPath()});
} else {
LOGGER.log(Level.WARNING, "Cannot relocate log file {0} to {1}",new Object[] {f.getPath(),newLocation.getPath()});
}
} else {
assert false;
}
@@ -59,6 +59,7 @@ import java.util.logging.Logger;
import static hudson.model.queue.Executables.*;
import static java.util.logging.Level.*;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
/**
@@ -70,7 +71,7 @@ import javax.annotation.CheckForNull;
*/
@ExportedBean
public class Executor extends Thread implements ModelObject {
protected final Computer owner;
protected final @Nonnull Computer owner;
private final Queue queue;
private long startTime;
@@ -111,7 +112,7 @@ public class Executor extends Thread implements ModelObject {
*/
private final List<CauseOfInterruption> causes = new Vector<CauseOfInterruption>();
public Executor(Computer owner, int n) {
public Executor(@Nonnull Computer owner, int n) {
super("Executor #"+n+" for "+owner.getDisplayName());
this.owner = owner;
this.queue = Jenkins.getInstance().getQueue();
@@ -534,7 +535,7 @@ public class Executor extends Thread implements ModelObject {
return e!=null && Tasks.getOwnerTaskOf(getParentOf(e)).hasAbortPermission();
}
public Computer getOwner() {
public @Nonnull Computer getOwner() {
return owner;
}
+1 -1
View File
@@ -202,7 +202,7 @@ public abstract class Node extends AbstractModelObject implements Reconfigurable
// At startup, we need to restore any previously in-effect temp offline cause.
// We wait until the computer is started rather than getting the data to it sooner
// so that the normal computer start up processing works as expected.
if (node.temporaryOfflineCause != null && node.temporaryOfflineCause != c.getOfflineCause()) {
if (node!= null && node.temporaryOfflineCause != null && node.temporaryOfflineCause != c.getOfflineCause()) {
c.setTemporarilyOffline(true, node.temporaryOfflineCause);
}
}
@@ -283,6 +283,7 @@ public class Queue extends ResourceController implements Saveable {
return workUnit == null && !executor.getOwner().isOffline() && executor.getOwner().isAcceptingTasks();
}
@CheckForNull
public Node getNode() {
return executor.getOwner().getNode();
}
@@ -739,6 +740,8 @@ public class Queue extends ResourceController implements Saveable {
private void _getBuildableItems(Computer c, ItemList<BuildableItem> col, List<BuildableItem> result) {
Node node = c.getNode();
if (node == null) // Deleted computers cannot take build items...
return;
for (BuildableItem p : col.values()) {
if (node.canTake(p) == null)
result.add(p);
+149 -126
View File
@@ -111,6 +111,7 @@ import jenkins.model.lazy.BuildReference;
import jenkins.util.VirtualFile;
import jenkins.util.io.OnMaster;
import net.sf.json.JSONObject;
import org.acegisecurity.AccessDeniedException;
import org.acegisecurity.Authentication;
import org.apache.commons.io.IOUtils;
import org.apache.commons.jelly.XMLOutput;
@@ -136,7 +137,7 @@ import org.kohsuke.stapler.interceptor.RequirePOST;
public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,RunT>>
extends Actionable implements ExtensionPoint, Comparable<RunT>, AccessControlled, PersistenceRoot, DescriptorByNameOwner, OnMaster {
protected transient final JobT project;
protected transient final @Nonnull JobT project;
/**
* Build number.
@@ -278,8 +279,9 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
/**
* Creates a new {@link Run}.
* @param job Owner job
*/
protected Run(JobT job) throws IOException {
protected Run(@Nonnull JobT job) throws IOException {
this(job, new GregorianCalendar());
this.number = project.assignBuildNumber();
LOGGER.log(FINER, "new {0} @{1}", new Object[] {this, hashCode()});
@@ -289,11 +291,11 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
* Constructor for creating a {@link Run} object in
* an arbitrary state.
*/
protected Run(JobT job, Calendar timestamp) {
protected Run(@Nonnull JobT job, @Nonnull Calendar timestamp) {
this(job,timestamp.getTimeInMillis());
}
protected Run(JobT job, long timestamp) {
protected Run(@Nonnull JobT job, long timestamp) {
this.project = job;
this.timestamp = timestamp;
this.state = State.NOT_STARTED;
@@ -303,7 +305,7 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
/**
* Loads a run from a log file.
*/
protected Run(JobT project, File buildDir) throws IOException {
protected Run(@Nonnull JobT project, @Nonnull File buildDir) throws IOException {
this(project, parseTimestampFromBuildDir(buildDir));
this.previousBuildInProgress = _this(); // loaded builds are always completed
reload();
@@ -357,8 +359,13 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
public List<Action> getTransientActions() {
List<Action> actions = new ArrayList<Action>();
for (TransientBuildActionFactory factory: TransientBuildActionFactory.all()) {
actions.addAll(factory.createFor(this));
assert !actions.contains(null) : "null action added by " + factory;
for (Action created : factory.createFor(this)) {
if (created == null) {
LOGGER.log(WARNING, "null action added by {0}", factory);
continue;
}
actions.add(created);
}
}
return Collections.unmodifiableList(actions);
}
@@ -369,7 +376,7 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
*/
@SuppressWarnings("deprecation")
@Override
public void addAction(Action a) {
public void addAction(@Nonnull Action a) {
super.addAction(a);
if (a instanceof RunAction2) {
((RunAction2) a).onAttached(this);
@@ -384,7 +391,8 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
}
}
/*package*/ static long parseTimestampFromBuildDir(File buildDir) throws IOException, InvalidDirectoryNameException {
/*package*/ static long parseTimestampFromBuildDir(@Nonnull File buildDir)
throws IOException, InvalidDirectoryNameException {
try {
if(Util.isSymlink(buildDir)) {
// "Util.resolveSymlink(file)" resolves NTFS symlinks.
@@ -406,16 +414,16 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
/**
* Obtains 'this' in a more type safe signature.
*/
*/
@SuppressWarnings({"unchecked"})
protected RunT _this() {
protected @Nonnull RunT _this() {
return (RunT)this;
}
/**
* Ordering based on build numbers.
*/
public int compareTo(RunT that) {
public int compareTo(@Nonnull RunT that) {
return this.number - that.number;
}
@@ -432,7 +440,7 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
return result;
}
public void setResult(Result r) {
public void setResult(@Nonnull Result r) {
// state can change only when we are building
assert state==State.BUILDING : state;
@@ -446,7 +454,7 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
/**
* Gets the subset of {@link #getActions()} that consists of {@link BuildBadgeAction}s.
*/
public List<BuildBadgeAction> getBadgeActions() {
public @Nonnull List<BuildBadgeAction> getBadgeActions() {
List<BuildBadgeAction> r = getActions(BuildBadgeAction.class);
if(isKeepLog()) {
r.add(new KeepLogBuildBadge());
@@ -508,7 +516,7 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
* Otherwise null.
* @since 1.433
*/
public Executor getOneOffExecutor() {
public @CheckForNull Executor getOneOffExecutor() {
for( Computer c : Jenkins.getInstance().getComputers() ) {
for (Executor e : c.getOneOffExecutors()) {
if(e.getCurrentExecutable()==this)
@@ -522,14 +530,14 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
* Gets the charset in which the log file is written.
* @return never null.
* @since 1.257
*/
public final Charset getCharset() {
*/
public final @Nonnull Charset getCharset() {
if(charset==null) return Charset.defaultCharset();
return Charset.forName(charset);
}
/**
* Returns the {@link Cause}s that tirggered a build.
* Returns the {@link Cause}s that triggered a build.
*
* <p>
* If a build sits in the queue for a long time, multiple build requests made during this period
@@ -539,7 +547,7 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
* can be empty but never null. read-only.
* @since 1.321
*/
public List<Cause> getCauses() {
public @Nonnull List<Cause> getCauses() {
CauseAction a = getAction(CauseAction.class);
if (a==null) return Collections.emptyList();
return Collections.unmodifiableList(a.getCauses());
@@ -549,8 +557,8 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
* Returns a {@link Cause} of a particular type.
*
* @since 1.362
*/
public <T extends Cause> T getCause(Class<T> type) {
*/
public @CheckForNull <T extends Cause> T getCause(Class<T> type) {
for (Cause c : getCauses())
if (type.isInstance(c))
return type.cast(c);
@@ -570,8 +578,8 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
/**
* If {@link #isKeepLog()} returns true, returns a short, human-readable
* sentence that explains why it's being kept.
*/
public String getWhyKeepLog() {
*/
public @CheckForNull String getWhyKeepLog() {
if(keepLog)
return Messages.Run_MarkedExplicitly();
return null; // not marked at all
@@ -579,8 +587,8 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
/**
* The project this build is for.
*/
public JobT getParent() {
*/
public @Nonnull JobT getParent() {
return project;
}
@@ -588,9 +596,9 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
* When the build is scheduled.
*
* @see #getStartTimeInMillis()
*/
*/
@Exported
public Calendar getTimestamp() {
public @Nonnull Calendar getTimestamp() {
GregorianCalendar c = new GregorianCalendar();
c.setTimeInMillis(timestamp);
return c;
@@ -598,8 +606,8 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
/**
* Same as {@link #getTimestamp()} but in a different type.
*/
public final Date getTime() {
*/
public final @Nonnull Date getTime() {
return new Date(timestamp);
}
@@ -632,8 +640,8 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
/**
* Returns the length-limited description.
* @return The length-limited description.
*/
public String getTruncatedDescription() {
*/
public @Nonnull String getTruncatedDescription() {
final int maxDescrLength = 100;
if (description == null || description.length() < maxDescrLength) {
return description;
@@ -684,7 +692,7 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
* @return
* string like "3 minutes" "1 day" etc.
*/
public String getTimestampString() {
public @Nonnull String getTimestampString() {
long duration = new GregorianCalendar().getTimeInMillis()-timestamp;
return Util.getPastTimeString(duration);
}
@@ -692,14 +700,14 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
/**
* Returns the timestamp formatted in xs:dateTime.
*/
public String getTimestampString2() {
public @Nonnull String getTimestampString2() {
return Util.XS_DATETIME_FORMATTER.format(new Date(timestamp));
}
/**
* Gets the string that says how long the build took to run.
*/
public String getDurationString() {
public @Nonnull String getDurationString() {
if(isBuilding())
return Messages.Run_InProgressDuration(
Util.getTimeSpanString(System.currentTimeMillis()-timestamp));
@@ -717,7 +725,7 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
/**
* Gets the icon color for display.
*/
public BallColor getIconColor() {
public @Nonnull BallColor getIconColor() {
if(!isBuilding()) {
// already built
return getResult().color;
@@ -776,10 +784,11 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
/**
* Called by {@link RunMap} to obtain a reference to this run.
* @return Reference to the build. Never null
* @see jenkins.model.lazy.LazyBuildMixIn.RunMixIn#createReference
* @since 1.556
*/
protected BuildReference<RunT> createReference() {
*/
protected @Nonnull BuildReference<RunT> createReference() {
return new BuildReference<RunT>(getId(), _this());
}
@@ -798,15 +807,15 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
/**
* @see jenkins.model.lazy.LazyBuildMixIn.RunMixIn#getPreviousBuild
*/
public RunT getPreviousBuild() {
*/
public @CheckForNull RunT getPreviousBuild() {
return previousBuild;
}
/**
* Gets the most recent {@linkplain #isBuilding() completed} build excluding 'this' Run itself.
*/
public final RunT getPreviousCompletedBuild() {
*/
public final @CheckForNull RunT getPreviousCompletedBuild() {
RunT r=getPreviousBuild();
while (r!=null && r.isBuilding())
r=r.getPreviousBuild();
@@ -820,8 +829,8 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
* <p>
* We basically follow the existing skip list, and wherever we find a non-optimal pointer, we remember them
* in 'fixUp' and update them later.
*/
public final RunT getPreviousBuildInProgress() {
*/
public final @CheckForNull RunT getPreviousBuildInProgress() {
if(previousBuildInProgress==this) return null; // the most common case
List<RunT> fixUp = new ArrayList<RunT>();
@@ -856,8 +865,8 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
/**
* Returns the last build that was actually built - i.e., skipping any with Result.NOT_BUILT
*/
public RunT getPreviousBuiltBuild() {
*/
public @CheckForNull RunT getPreviousBuiltBuild() {
RunT r=getPreviousBuild();
// in certain situations (aborted m2 builds) r.getResult() can still be null, although it should theoretically never happen
while( r!=null && (r.getResult() == null || r.getResult()==Result.NOT_BUILT) )
@@ -867,8 +876,8 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
/**
* Returns the last build that didn't fail before this build.
*/
public RunT getPreviousNotFailedBuild() {
*/
public @CheckForNull RunT getPreviousNotFailedBuild() {
RunT r=getPreviousBuild();
while( r!=null && r.getResult()==Result.FAILURE )
r=r.getPreviousBuild();
@@ -877,8 +886,8 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
/**
* Returns the last failed build before this build.
*/
public RunT getPreviousFailedBuild() {
*/
public @CheckForNull RunT getPreviousFailedBuild() {
RunT r=getPreviousBuild();
while( r!=null && r.getResult()!=Result.FAILURE )
r=r.getPreviousBuild();
@@ -889,7 +898,7 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
* Returns the last successful build before this build.
* @since 1.383
*/
public RunT getPreviousSuccessfulBuild() {
public @CheckForNull RunT getPreviousSuccessfulBuild() {
RunT r=getPreviousBuild();
while( r!=null && r.getResult()!=Result.SUCCESS )
r=r.getPreviousBuild();
@@ -905,8 +914,8 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
* May be smaller than 'numberOfBuilds' or even empty
* if not enough builds satisfying the threshold have been found. Never null.
* @since 1.383
*/
public List<RunT> getPreviousBuildsOverThreshold(int numberOfBuilds, Result threshold) {
*/
public @Nonnull List<RunT> getPreviousBuildsOverThreshold(int numberOfBuilds, @Nonnull Result threshold) {
List<RunT> builds = new ArrayList<RunT>(numberOfBuilds);
RunT r = getPreviousBuild();
@@ -923,8 +932,8 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
/**
* @see jenkins.model.lazy.LazyBuildMixIn.RunMixIn#getNextBuild
*/
public RunT getNextBuild() {
*/
public @CheckForNull RunT getNextBuild() {
return nextBuild;
}
@@ -936,7 +945,7 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
*/
// I really messed this up. I'm hoping to fix this some time
// it shouldn't have trailing '/', and instead it should have leading '/'
public String getUrl() {
public @Nonnull String getUrl() {
// RUN may be accessed using permalinks, as "/lastSuccessful" or other, so try to retrieve this base URL
// looking for "this" in the current request ancestors
@@ -962,11 +971,11 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
* This method is only intended for the remote API clients who cannot resolve relative references.
*/
@Exported(visibility=2,name="url")
public final String getAbsoluteUrl() {
public final @Nonnull String getAbsoluteUrl() {
return project.getAbsoluteUrl()+getNumber()+'/';
}
public final String getSearchUrl() {
public final @Nonnull String getSearchUrl() {
return getNumber()+"/";
}
@@ -974,29 +983,31 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
* Unique ID of this build.
*/
@Exported
public String getId() {
public @Nonnull String getId() {
return ID_FORMATTER.get().format(new Date(timestamp));
}
/**
* Get the date formatter used to convert the directory name in to a timestamp
* Get the date formatter used to convert the directory name in to a timestamp.
* This is nasty exposure of private data, but needed all the time the directory
* containing the build is used as it's timestamp.
*/
public static DateFormat getIDFormatter() {
public static @Nonnull DateFormat getIDFormatter() {
return ID_FORMATTER.get();
}
public Descriptor getDescriptorByName(String className) {
@Override
public @CheckForNull Descriptor getDescriptorByName(String className) {
return Jenkins.getInstance().getDescriptorByName(className);
}
/**
* Root directory of this {@link Run} on the master.
*
* Get the root directory of this {@link Run} on the master.
* Files related to this {@link Run} should be stored below this directory.
* @return Root directory of this {@link Run} on the master. Never null
*/
public File getRootDir() {
@Override
public @Nonnull File getRootDir() {
return new File(project.getBuildDir(),getId());
}
@@ -1053,19 +1064,21 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
/**
* Gets the artifacts (relative to {@link #getArtifactsDir()}.
*/
@Exported
public List<Artifact> getArtifacts() {
* @return The list can be empty but never null
*/
@Exported
public @Nonnull List<Artifact> getArtifacts() {
return getArtifactsUpTo(Integer.MAX_VALUE);
}
/**
* Gets the first N artifacts.
*/
public List<Artifact> getArtifactsUpTo(int n) {
* @return The list can be empty but never null
*/
public @Nonnull List<Artifact> getArtifactsUpTo(int artifactsNumber) {
ArtifactList r = new ArtifactList();
try {
addArtifacts(getArtifactManager().root(), "", "", r, null, n);
addArtifacts(getArtifactManager().root(), "", "", r, null, artifactsNumber);
} catch (IOException x) {
LOGGER.log(Level.WARNING, null, x);
}
@@ -1074,16 +1087,17 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
}
/**
* Returns true if this run has any artifacts.
*
* <p>
* Check if the {@link Run} contains artifacts.
* The strange method name is so that we can access it from EL.
* @return true if this run has any artifacts
*/
public boolean getHasArtifacts() {
return !getArtifactsUpTo(1).isEmpty();
}
private int addArtifacts(VirtualFile dir, String path, String pathHref, ArtifactList r, Artifact parent, int upTo) throws IOException {
private int addArtifacts(@Nonnull VirtualFile dir,
@Nonnull String path, @Nonnull String pathHref,
@Nonnull ArtifactList r, @Nonnull Artifact parent, int upTo) throws IOException {
VirtualFile[] kids = dir.list();
Arrays.sort(kids);
@@ -1267,7 +1281,7 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
* @deprecated May not be meaningful with custom artifact managers. Use {@link ArtifactManager#root} plus {@link VirtualFile#child} with {@link #relativePath} instead.
*/
@Deprecated
public File getFile() {
public @Nonnull File getFile() {
return new File(getArtifactsDir(),relativePath);
}
@@ -1308,8 +1322,9 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
/**
* Returns the log file.
*/
public File getLogFile() {
* @return The file may reference both uncompressed or compressed logs
*/
public @Nonnull File getLogFile() {
File rawF = new File(getRootDir(), "log");
if (rawF.isFile()) {
return rawF;
@@ -1327,13 +1342,14 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
* It will use a gzip-compressed log file (log.gz) if that exists.
*
* @throws IOException
* @return an input stream from the log file, or null if none exists
* @return An input stream from the log file.
* If the log file does not exist, the error message will be returned to the output.
* @since 1.349
*/
public InputStream getLogInputStream() throws IOException {
public @Nonnull InputStream getLogInputStream() throws IOException {
File logFile = getLogFile();
if (logFile != null && logFile.exists() ) {
if (logFile.exists() ) {
// Checking if a ".gz" file was return
FileInputStream fis = new FileInputStream(logFile);
if (logFile.getName().endsWith(".gz")) {
@@ -1346,8 +1362,8 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
String message = "No such file: " + logFile;
return new ByteArrayInputStream(charset != null ? message.getBytes(charset) : message.getBytes());
}
public Reader getLogReader() throws IOException {
public @Nonnull Reader getLogReader() throws IOException {
if (charset==null) return new InputStreamReader(getLogInputStream());
else return new InputStreamReader(getLogInputStream(),charset);
}
@@ -1357,7 +1373,7 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
*
* @since 1.349
*/
public void writeLogTo(long offset, XMLOutput out) throws IOException {
public void writeLogTo(long offset, @Nonnull XMLOutput out) throws IOException {
try {
getLogText().writeHtmlTo(offset,out.asWriter());
} catch (IOException e) {
@@ -1378,8 +1394,10 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
*
* If someone is still writing to the log, this method will not return until the whole log
* file gets written out.
* <p/>
* The method does not close the {@link OutputStream}.
*/
public void writeWholeLogTo(OutputStream out) throws IOException, InterruptedException {
public void writeWholeLogTo(@Nonnull OutputStream out) throws IOException, InterruptedException {
long pos = 0;
AnnotatedLargeText logText;
logText = getLogText();
@@ -1396,13 +1414,14 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
/**
* Used to URL-bind {@link AnnotatedLargeText}.
*/
public AnnotatedLargeText getLogText() {
* @return A {@link Run} log with annotations
*/
public @Nonnull AnnotatedLargeText getLogText() {
return new AnnotatedLargeText(getLogFile(),getCharset(),!isLogUpdated(),this);
}
@Override
protected SearchIndexBuilder makeSearchIndex() {
protected @Nonnull SearchIndexBuilder makeSearchIndex() {
SearchIndexBuilder builder = super.makeSearchIndex()
.add("console")
.add("changes");
@@ -1413,18 +1432,21 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
return builder;
}
public Api getApi() {
public @Nonnull Api getApi() {
return new Api(this);
}
public void checkPermission(Permission p) {
@Override
public void checkPermission(@Nonnull Permission p) {
getACL().checkPermission(p);
}
public boolean hasPermission(Permission p) {
@Override
public boolean hasPermission(@Nonnull Permission p) {
return getACL().hasPermission(p);
}
@Override
public ACL getACL() {
// for now, don't maintain ACL per run, and do it at project level
return getParent().getACL();
@@ -1495,14 +1517,14 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
/**
* @see CheckPoint#report()
*/
/*package*/ static void reportCheckpoint(CheckPoint id) {
/*package*/ static void reportCheckpoint(@Nonnull CheckPoint id) {
RunnerStack.INSTANCE.peek().checkpoints.report(id);
}
/**
* @see CheckPoint#block()
*/
/*package*/ static void waitForCheckpoint(CheckPoint id, @CheckForNull BuildListener listener, @CheckForNull String waiter) throws InterruptedException {
/*package*/ static void waitForCheckpoint(@Nonnull CheckPoint id, @CheckForNull BuildListener listener, @CheckForNull String waiter) throws InterruptedException {
while(true) {
Run b = RunnerStack.INSTANCE.peek().getBuild().getPreviousBuildInProgress();
if(b==null) return; // no pending earlier build
@@ -1543,12 +1565,12 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
private boolean allDone;
protected synchronized void report(CheckPoint identifier) {
protected synchronized void report(@Nonnull CheckPoint identifier) {
checkpoints.add(identifier);
notifyAll();
}
protected synchronized boolean waitForCheckPoint(CheckPoint identifier, @CheckForNull BuildListener listener, @CheckForNull String waiter) throws InterruptedException {
protected synchronized boolean waitForCheckPoint(@Nonnull CheckPoint identifier, @CheckForNull BuildListener listener, @CheckForNull String waiter) throws InterruptedException {
final Thread t = Thread.currentThread();
final String oldName = t.getName();
t.setName(oldName + " : waiting for " + identifier + " on " + getFullDisplayName() + " from " + waiter);
@@ -1586,7 +1608,7 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
* @throws Exception
* exception will be recorded and the build will be considered a failure.
*/
public abstract Result run( BuildListener listener ) throws Exception, RunnerAbortedException;
public abstract @Nonnull Result run(@Nonnull BuildListener listener ) throws Exception, RunnerAbortedException;
/**
* Performs the post-build action.
@@ -1598,7 +1620,7 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
* even if the build is successful, this build still won't be picked up
* by {@link Job#getLastSuccessfulBuild()}.
*/
public abstract void post( BuildListener listener ) throws Exception;
public abstract void post(@Nonnull BuildListener listener ) throws Exception;
/**
* Performs final clean up action.
@@ -1612,11 +1634,11 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
*/
public abstract void cleanUp(@Nonnull BuildListener listener) throws Exception;
public RunT getBuild() {
public @Nonnull RunT getBuild() {
return _this();
}
public JobT getProject() {
public @Nonnull JobT getProject() {
return _this().getParent();
}
@@ -1626,7 +1648,7 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
*
* @since 1.473
*/
public Map<Object,Object> getAttributes() {
public @Nonnull Map<Object,Object> getAttributes() {
return attributes;
}
}
@@ -1644,11 +1666,11 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
* @deprecated as of 1.467
* Use {@link #execute(RunExecution)}
*/
protected final void run(Runner job) {
protected final void run(@Nonnull Runner job) {
execute(job);
}
protected final void execute(RunExecution job) {
protected final void execute(@Nonnull RunExecution job) {
if(result!=null)
return; // already built.
@@ -1792,7 +1814,7 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
* @throws InterruptedException probably not thrown
* @since 1.530
*/
public final void updateSymlinks(TaskListener listener) throws InterruptedException {
public final void updateSymlinks(@Nonnull TaskListener listener) throws InterruptedException {
Util.createSymlink(getParent().getBuildDir(), getId(), String.valueOf(getNumber()), listener);
createSymlink(listener, "lastSuccessful", PermalinkProjectAction.Permalink.LAST_SUCCESSFUL_BUILD);
createSymlink(listener, "lastStable", PermalinkProjectAction.Permalink.LAST_STABLE_BUILD);
@@ -1804,7 +1826,7 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
* builds, but now those are done in {@link PeepholePermalink}. So here, we simply create symlinks that
* resolves to the symlink created by {@link PeepholePermalink}.
*/
private void createSymlink(TaskListener listener, String name, PermalinkProjectAction.Permalink target) throws InterruptedException {
private void createSymlink(@Nonnull TaskListener listener, @Nonnull String name, @Nonnull PermalinkProjectAction.Permalink target) throws InterruptedException {
File buildDir = getParent().getBuildDir();
File rootDir = getParent().getRootDir();
String targetDir;
@@ -1819,7 +1841,7 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
/**
* Handles a fatal build problem (exception) that occurred during the build.
*/
private void handleFatalBuildProblem(BuildListener listener, Throwable e) {
private void handleFatalBuildProblem(@Nonnull BuildListener listener, @Nonnull Throwable e) {
if(listener!=null) {
LOGGER.log(FINE, getDisplayName()+" failed to build",e);
@@ -1881,19 +1903,19 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
SaveableListener.fireOnChange(this, getDataFile());
}
private XmlFile getDataFile() {
private @Nonnull XmlFile getDataFile() {
return new XmlFile(XSTREAM,new File(getRootDir(),"build.xml"));
}
/**
* Gets the log of the build as a string.
*
* @return Returns the log or an empty string if it has not been found
* @deprecated since 2007-11-11.
* Use {@link #getLog(int)} instead as it avoids loading
* the whole log into memory unnecessarily.
*/
@Deprecated
public String getLog() throws IOException {
public @Nonnull String getLog() throws IOException {
return Util.loadFile(getLogFile(),getCharset());
}
@@ -1906,7 +1928,7 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
* @return A list of log lines. Will have no more than maxLines elements.
* @throws IOException If there is a problem reading the log file.
*/
public List<String> getLog(int maxLines) throws IOException {
public @Nonnull List<String> getLog(int maxLines) throws IOException {
int lineCount = 0;
List<String> logLines = new LinkedList<String>();
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(getLogFile()),getCharset()));
@@ -1938,7 +1960,7 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
rsp.sendRedirect2(req.getContextPath()+"/images/48x48/"+getBuildStatusUrl());
}
public String getBuildStatusUrl() {
public @Nonnull String getBuildStatusUrl() {
return getIconColor().getImage();
}
@@ -1959,7 +1981,7 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
* Gets an object which represents the single line summary of the status of this build
* (especially in comparison with the previous build.)
*/
public Summary getBuildStatusSummary() {
public @Nonnull Summary getBuildStatusSummary() {
if (isBuilding()) {
return new Summary(false, Messages.Run_Summary_Unknown());
}
@@ -2002,7 +2024,7 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
* @param worseOverride override the 'worse' parameter to this value.
* May be null in which case 'worse' is calculated based on the number of failed tests.
*/
private Summary determineDetailedUnstableSummary(Boolean worseOverride) {
private @Nonnull Summary determineDetailedUnstableSummary(Boolean worseOverride) {
if(((Run)this) instanceof AbstractBuild) {
AbstractTestResultAction trN = ((AbstractBuild)(Run)this).getTestResultAction();
Run prev = getPreviousBuild();
@@ -2035,8 +2057,9 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
/**
* Serves the artifacts.
* @throws AccessDeniedException Access denied
*/
public DirectoryBrowserSupport doArtifact() {
public @Nonnull DirectoryBrowserSupport doArtifact() {
if(Functions.isArtifactsPermissionEnabled()) {
checkPermission(ARTIFACTS);
}
@@ -2231,7 +2254,7 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
* Builds up the environment variable map that's sufficient to identify a process
* as ours. This is used to kill run-away processes via {@link ProcessTree#killAll(Map)}.
*/
public final EnvVars getCharacteristicEnvVars() {
public @Nonnull final EnvVars getCharacteristicEnvVars() {
EnvVars env = getParent().getCharacteristicEnvVars();
env.put("BUILD_NUMBER",String.valueOf(number));
env.put("BUILD_ID",getId());
@@ -2239,11 +2262,11 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
return env;
}
public String getExternalizableId() {
public @Nonnull String getExternalizableId() {
return project.getFullName() + "#" + getNumber();
}
public static Run<?,?> fromExternalizableId(String id) {
public @Nonnull static Run<?,?> fromExternalizableId(String id) {
int hash = id.lastIndexOf('#');
if (hash <= 0) {
throw new IllegalArgumentException("Invalid id");
@@ -2272,7 +2295,7 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
}
@RequirePOST
public HttpResponse doConfigSubmit( StaplerRequest req ) throws IOException, ServletException, FormException {
public @Nonnull HttpResponse doConfigSubmit( StaplerRequest req ) throws IOException, ServletException, FormException {
checkPermission(UPDATE);
BulkChange bc = new BulkChange(this);
try {
@@ -2308,7 +2331,7 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
* Sort by date. Newer ones first.
*/
public static final Comparator<Run> ORDER_BY_DATE = new Comparator<Run>() {
public int compare(Run lhs, Run rhs) {
public int compare(@Nonnull Run lhs, @Nonnull Run rhs) {
long lt = lhs.getTimeInMillis();
long rt = rhs.getTimeInMillis();
if(lt>rt) return -1;
@@ -2341,10 +2364,10 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
* {@link BuildBadgeAction} that shows the logs are being kept.
*/
public final class KeepLogBuildBadge implements BuildBadgeAction {
public String getIconFileName() { return null; }
public String getDisplayName() { return null; }
public String getUrlName() { return null; }
public String getWhyKeepLog() { return Run.this.getWhyKeepLog(); }
public @CheckForNull String getIconFileName() { return null; }
public @CheckForNull String getDisplayName() { return null; }
public @CheckForNull String getUrlName() { return null; }
public @CheckForNull String getWhyKeepLog() { return Run.this.getWhyKeepLog(); }
}
public static final PermissionGroup PERMISSIONS = new PermissionGroup(Run.class,Messages._Run_Permissions_Title());
@@ -2384,8 +2407,8 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
@Override
public Object getDynamic(String token, StaplerRequest req, StaplerResponse rsp) {
Object result = super.getDynamic(token, req, rsp);
if (result == null){
Object returnedResult = super.getDynamic(token, req, rsp);
if (returnedResult == null){
//check transient actions too
for(Action action: getTransientActions()){
String urlName = action.getUrlName();
@@ -2399,9 +2422,9 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
// Next/Previous Build links on an action page (like /job/Abc/123/testReport)
// will also point to same action (/job/Abc/124/testReport), but other builds
// may not have the action.. tell browsers to redirect up to the build page.
result = new RedirectUp();
returnedResult = new RedirectUp();
}
return result;
return returnedResult;
}
public static class RedirectUp {
@@ -26,6 +26,7 @@ package hudson.node_monitors;
import hudson.Extension;
import hudson.FilePath;
import hudson.model.Computer;
import hudson.model.Node;
import hudson.remoting.Callable;
import jenkins.model.Jenkins;
import hudson.node_monitors.DiskSpaceMonitorDescriptor.DiskSpace;
@@ -66,7 +67,10 @@ public class DiskSpaceMonitor extends AbstractDiskSpaceMonitor {
@Override
protected Callable<DiskSpace, IOException> createCallable(Computer c) {
FilePath p = c.getNode().getRootPath();
Node node = c.getNode();
if (node == null) return null;
FilePath p = node.getRootPath();
if(p==null) return null;
return p.asCallableWith(new GetUsableSpace());
@@ -27,6 +27,7 @@ import hudson.Extension;
import hudson.FilePath;
import hudson.FilePath.FileCallable;
import hudson.model.Computer;
import hudson.model.Node;
import hudson.remoting.Callable;
import jenkins.model.Jenkins;
import hudson.node_monitors.DiskSpaceMonitorDescriptor.DiskSpace;
@@ -67,7 +68,10 @@ public class TemporarySpaceMonitor extends AbstractDiskSpaceMonitor {
@Override
protected Callable<DiskSpace,IOException> createCallable(Computer c) {
FilePath p = c.getNode().getRootPath();
Node node = c.getNode();
if (node == null) return null;
FilePath p = node.getRootPath();
if(p==null) return null;
return p.asCallableWith(new GetTempSpace());
+6 -5
View File
@@ -23,6 +23,7 @@
*/
package hudson.security;
import javax.annotation.Nonnull;
import jenkins.security.NonSerializableSecurityContext;
import jenkins.model.Jenkins;
import org.acegisecurity.AccessDeniedException;
@@ -48,7 +49,7 @@ public abstract class ACL {
* @throws AccessDeniedException
* if the user doesn't have the permission.
*/
public final void checkPermission(Permission p) {
public final void checkPermission(@Nonnull Permission p) {
Authentication a = Jenkins.getAuthentication();
if(!hasPermission(a,p))
throw new AccessDeniedException2(a,p);
@@ -60,7 +61,7 @@ public abstract class ACL {
* @return false
* if the user doesn't have the permission.
*/
public final boolean hasPermission(Permission p) {
public final boolean hasPermission(@Nonnull Permission p) {
return hasPermission(Jenkins.getAuthentication(),p);
}
@@ -71,7 +72,7 @@ public abstract class ACL {
* Note that {@link #SYSTEM} can be passed in as the authentication parameter,
* in which case you should probably just assume it has every permission.
*/
public abstract boolean hasPermission(Authentication a, Permission permission);
public abstract boolean hasPermission(@Nonnull Authentication a, @Nonnull Permission permission);
//
// Sid constants
@@ -124,7 +125,7 @@ public abstract class ACL {
* because the same {@link SecurityContext} object is reused for all the concurrent requests from the same session.
* @since 1.462
*/
public static SecurityContext impersonate(Authentication auth) {
public static @Nonnull SecurityContext impersonate(@Nonnull Authentication auth) {
SecurityContext old = SecurityContextHolder.getContext();
SecurityContextHolder.setContext(new NonSerializableSecurityContext(auth));
return old;
@@ -136,7 +137,7 @@ public abstract class ACL {
* @param body an action to run with this alternate authentication in effect
* @since 1.509
*/
public static void impersonate(Authentication auth, Runnable body) {
public static void impersonate(@Nonnull Authentication auth, @Nonnull Runnable body) {
SecurityContext old = impersonate(auth);
try {
body.run();
@@ -23,6 +23,7 @@
*/
package hudson.security;
import javax.annotation.Nonnull;
import org.acegisecurity.AccessDeniedException;
/**
@@ -36,16 +37,16 @@ public interface AccessControlled {
*
* @return never null.
*/
ACL getACL();
@Nonnull ACL getACL();
/**
* Convenient short-cut for {@code getACL().checkPermission(permission)}
*/
void checkPermission(Permission permission) throws AccessDeniedException;
void checkPermission(@Nonnull Permission permission) throws AccessDeniedException;
/**
* Convenient short-cut for {@code getACL().hasPermission(permission)}
*/
boolean hasPermission(Permission permission);
boolean hasPermission(@Nonnull Permission permission);
}
@@ -33,6 +33,7 @@ import hudson.util.DescriptorList;
import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import javax.annotation.Nonnull;
import jenkins.model.Jenkins;
import net.sf.json.JSONObject;
@@ -68,18 +69,18 @@ public abstract class AuthorizationStrategy extends AbstractDescribableImpl<Auth
* <p>
* IOW, this ACL will have the ultimate say on the access control.
*/
public abstract ACL getRootACL();
public abstract @Nonnull ACL getRootACL();
/**
* @deprecated since 1.277
* Override {@link #getACL(Job)} instead.
*/
@Deprecated
public ACL getACL(AbstractProject<?,?> project) {
public @Nonnull ACL getACL(@Nonnull AbstractProject<?,?> project) {
return getACL((Job)project);
}
public ACL getACL(Job<?,?> project) {
public @Nonnull ACL getACL(@Nonnull Job<?,?> project) {
return getRootACL();
}
@@ -93,7 +94,7 @@ public abstract class AuthorizationStrategy extends AbstractDescribableImpl<Auth
*
* @since 1.220
*/
public ACL getACL(final View item) {
public @Nonnull ACL getACL(final @Nonnull View item) {
return new ACL() {
@Override
public boolean hasPermission(Authentication a, Permission permission) {
@@ -118,7 +119,7 @@ public abstract class AuthorizationStrategy extends AbstractDescribableImpl<Auth
*
* @since 1.220
*/
public ACL getACL(AbstractItem item) {
public @Nonnull ACL getACL(@Nonnull AbstractItem item) {
return getRootACL();
}
@@ -131,7 +132,7 @@ public abstract class AuthorizationStrategy extends AbstractDescribableImpl<Auth
*
* @since 1.221
*/
public ACL getACL(User user) {
public @Nonnull ACL getACL(@Nonnull User user) {
return getRootACL();
}
@@ -144,7 +145,7 @@ public abstract class AuthorizationStrategy extends AbstractDescribableImpl<Auth
*
* @since 1.220
*/
public ACL getACL(Computer computer) {
public @Nonnull ACL getACL(@Nonnull Computer computer) {
return getACL(computer.getNode());
}
@@ -157,11 +158,11 @@ public abstract class AuthorizationStrategy extends AbstractDescribableImpl<Auth
*
* @since 1.252
*/
public ACL getACL(Cloud cloud) {
public @Nonnull ACL getACL(@Nonnull Cloud cloud) {
return getRootACL();
}
public ACL getACL(Node node) {
public @Nonnull ACL getACL(@Nonnull Node node) {
return getRootACL();
}
@@ -179,12 +180,12 @@ public abstract class AuthorizationStrategy extends AbstractDescribableImpl<Auth
* @return
* never null.
*/
public abstract Collection<String> getGroups();
public abstract @Nonnull Collection<String> getGroups();
/**
* Returns all the registered {@link AuthorizationStrategy} descriptors.
*/
public static DescriptorExtensionList<AuthorizationStrategy,Descriptor<AuthorizationStrategy>> all() {
public static @Nonnull DescriptorExtensionList<AuthorizationStrategy,Descriptor<AuthorizationStrategy>> all() {
return Jenkins.getInstance().<AuthorizationStrategy,Descriptor<AuthorizationStrategy>>getDescriptorList(AuthorizationStrategy.class);
}
@@ -214,15 +215,17 @@ public abstract class AuthorizationStrategy extends AbstractDescribableImpl<Auth
}
@Override
public ACL getRootACL() {
public @Nonnull ACL getRootACL() {
return UNSECURED_ACL;
}
public Collection<String> getGroups() {
@Override
public @Nonnull Collection<String> getGroups() {
return Collections.emptySet();
}
private static final ACL UNSECURED_ACL = new ACL() {
@Override
public boolean hasPermission(Authentication a, Permission permission) {
return true;
}
@@ -230,12 +233,13 @@ public abstract class AuthorizationStrategy extends AbstractDescribableImpl<Auth
@Extension
public static final class DescriptorImpl extends Descriptor<AuthorizationStrategy> {
@Override
public String getDisplayName() {
return Messages.AuthorizationStrategy_DisplayName();
}
@Override
public AuthorizationStrategy newInstance(StaplerRequest req, JSONObject formData) throws FormException {
public @Nonnull AuthorizationStrategy newInstance(StaplerRequest req, JSONObject formData) throws FormException {
return UNSECURED;
}
@@ -34,6 +34,7 @@ import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import org.jvnet.localizer.Localizable;
@@ -58,14 +59,14 @@ public final class Permission {
*/
// break eclipse compilation
//Override
public int compare(Permission one, Permission two) {
public int compare(@Nonnull Permission one, @Nonnull Permission two) {
return one.getId().compareTo(two.getId());
}
};
public final Class owner;
public final @Nonnull Class owner;
public final PermissionGroup group;
public final @Nonnull PermissionGroup group;
/**
* Human readable ID of the permission.
@@ -76,7 +77,7 @@ public final class Permission {
* <p>
* The expected naming convention is something like "BrowseWorkspace".
*/
public final String name;
public final @Nonnull String name;
/**
* Human-readable description of this permission.
@@ -86,7 +87,7 @@ public final class Permission {
* <p>
* If null, there will be no description text.
*/
public final Localizable description;
public final @CheckForNull Localizable description;
/**
* Bundled {@link Permission} that also implies this permission.
@@ -101,7 +102,7 @@ public final class Permission {
* such broad permission bundle is good enough, and those few
* that need finer control can do so.
*/
public final Permission impliedBy;
public final @CheckForNull Permission impliedBy;
/**
* Whether this permission is available for use.
@@ -118,7 +119,7 @@ public final class Permission {
/**
* Scopes that this permission is directly contained by.
*/
private final Set<PermissionScope> scopes;
private final @Nonnull Set<PermissionScope> scopes;
/**
* Defines a new permission.
@@ -144,7 +145,9 @@ public final class Permission {
* @param impliedBy
* See {@link #impliedBy}.
*/
public Permission(PermissionGroup group, String name, Localizable description, Permission impliedBy, boolean enable, PermissionScope[] scopes) {
public Permission(@Nonnull PermissionGroup group, @Nonnull String name,
@CheckForNull Localizable description, @CheckForNull Permission impliedBy, boolean enable,
@Nonnull PermissionScope[] scopes) {
if(!JSONUtils.isJavaIdentifier(name))
throw new IllegalArgumentException(name+" is not a Java identifier");
this.owner = group.owner;
@@ -159,7 +162,8 @@ public final class Permission {
ALL.add(this);
}
public Permission(PermissionGroup group, String name, Localizable description, Permission impliedBy, PermissionScope scope) {
public Permission(@Nonnull PermissionGroup group, @Nonnull String name,
@CheckForNull Localizable description, @CheckForNull Permission impliedBy, @Nonnull PermissionScope scope) {
this(group,name,description,impliedBy,true,new PermissionScope[]{scope});
assert scope!=null;
}
@@ -168,7 +172,7 @@ public final class Permission {
* @deprecated as of 1.421
* Use {@link #Permission(PermissionGroup, String, Localizable, Permission, boolean, PermissionScope[])}
*/
public Permission(PermissionGroup group, String name, Localizable description, Permission impliedBy, boolean enable) {
public Permission(@Nonnull PermissionGroup group, @Nonnull String name, @CheckForNull Localizable description, @CheckForNull Permission impliedBy, boolean enable) {
this(group,name,description,impliedBy,enable,new PermissionScope[]{PermissionScope.JENKINS});
}
@@ -176,7 +180,7 @@ public final class Permission {
* @deprecated as of 1.421
* Use {@link #Permission(PermissionGroup, String, Localizable, Permission, PermissionScope)}
*/
public Permission(PermissionGroup group, String name, Localizable description, Permission impliedBy) {
public Permission(@Nonnull PermissionGroup group, @Nonnull String name, @CheckForNull Localizable description, @CheckForNull Permission impliedBy) {
this(group, name, description, impliedBy, PermissionScope.JENKINS);
}
@@ -184,18 +188,18 @@ public final class Permission {
* @deprecated since 1.257.
* Use {@link #Permission(PermissionGroup, String, Localizable, Permission)}
*/
public Permission(PermissionGroup group, String name, Permission impliedBy) {
public Permission(@Nonnull PermissionGroup group, @Nonnull String name, @CheckForNull Permission impliedBy) {
this(group,name,null,impliedBy);
}
private Permission(PermissionGroup group, String name) {
private Permission(@Nonnull PermissionGroup group, @Nonnull String name) {
this(group,name,null,null);
}
/**
* Checks if this permission is contained in the specified scope, (either directly or indirectly.)
*/
public boolean isContainedBy(PermissionScope s) {
public boolean isContainedBy(@Nonnull PermissionScope s) {
for (PermissionScope c : scopes) {
if (c.isContainedBy(s))
return true;
@@ -210,10 +214,10 @@ public final class Permission {
*
* <p>
* This string representation is suitable for persistence.
*
* @return ID with the following format: <i>permissionClass.permissionName</i>
* @see #fromId(String)
*/
public String getId() {
public @Nonnull String getId() {
return owner.getName()+'.'+name;
}
@@ -224,7 +228,7 @@ public final class Permission {
* null if the conversion failed.
* @see #getId()
*/
public static @CheckForNull Permission fromId(String id) {
public static @CheckForNull Permission fromId(@Nonnull String id) {
int idx = id.lastIndexOf('.');
if(idx<0) return null;
@@ -257,7 +261,7 @@ public final class Permission {
* @return
* always non-null. Read-only.
*/
public static List<Permission> getAll() {
public static @Nonnull List<Permission> getAll() {
return ALL_VIEW;
}
@@ -29,6 +29,7 @@ import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import java.io.IOException;
import javax.annotation.CheckForNull;
/**
* Partial implementation of {@link Computer} to be used in conjunction with
@@ -42,6 +43,7 @@ public class AbstractCloudComputer<T extends AbstractCloudSlave> extends SlaveCo
super(slave);
}
@CheckForNull
@Override
public T getNode() {
return (T) super.getNode();
@@ -54,7 +56,10 @@ public class AbstractCloudComputer<T extends AbstractCloudSlave> extends SlaveCo
public HttpResponse doDoDelete() throws IOException {
checkPermission(DELETE);
try {
getNode().terminate();
T node = getNode();
if (node != null) { // No need to terminate nodes again
node.terminate();
}
return new HttpRedirect("..");
} catch (InterruptedException e) {
return HttpResponses.error(500,e);
@@ -23,10 +23,12 @@
*/
package hudson.slaves;
import hudson.model.Node;
import java.io.IOException;
import java.util.logging.Logger;
import static hudson.util.TimeUnit2.*;
import java.util.logging.Level;
import static java.util.logging.Level.*;
/**
@@ -43,13 +45,15 @@ public class CloudRetentionStrategy extends RetentionStrategy<AbstractCloudCompu
this.idleMinutes = idleMinutes;
}
@Override
public synchronized long check(AbstractCloudComputer c) {
if (c.isIdle() && !disabled) {
AbstractCloudSlave computerNode = c.getNode();
if (c.isIdle() && !disabled && computerNode != null) {
final long idleMilliseconds = System.currentTimeMillis() - c.getIdleStartMilliseconds();
if (idleMilliseconds > MINUTES.toMillis(idleMinutes)) {
LOGGER.info("Disconnecting "+c.getName());
LOGGER.log(Level.INFO, "Disconnecting {0}",c.getName());
try {
c.getNode().terminate();
computerNode.terminate();
} catch (InterruptedException e) {
LOGGER.log(WARNING,"Failed to terminate "+c.getName(),e);
} catch (IOException e) {
@@ -23,10 +23,12 @@
*/
package hudson.slaves;
import hudson.AbortException;
import hudson.EnvVars;
import hudson.Util;
import hudson.Extension;
import hudson.model.Descriptor;
import hudson.model.Slave;
import jenkins.model.Jenkins;
import hudson.model.TaskListener;
import hudson.remoting.Channel;
@@ -87,6 +89,11 @@ public class CommandLauncher extends ComputerLauncher {
EnvVars _cookie = null;
Process _proc = null;
try {
Slave node = computer.getNode();
if (node == null) {
throw new AbortException("Cannot launch commands on deleted nodes");
}
listener.getLogger().println(hudson.model.Messages.Slave_Launching(getTimestamp()));
if(getCommand().trim().length()==0) {
listener.getLogger().println(Messages.CommandLauncher_NoLaunchCommand());
@@ -96,8 +103,8 @@ public class CommandLauncher extends ComputerLauncher {
ProcessBuilder pb = new ProcessBuilder(Util.tokenize(getCommand()));
final EnvVars cookie = _cookie = EnvVars.createCookie();
pb.environment().putAll(cookie);
pb.environment().put("WORKSPACE", computer.getNode().getRemoteFS()); //path for local slave log
pb.environment().putAll(cookie);
pb.environment().put("WORKSPACE", node.getRemoteFS()); //path for local slave log
{// system defined variables
String rootUrl = Jenkins.getInstance().getRootUrl();
@@ -24,6 +24,7 @@
package hudson.slaves;
import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.model.Node;
import hudson.model.EnvironmentSpecific;
import hudson.model.TaskListener;
@@ -44,5 +45,5 @@ public interface NodeSpecific<T extends NodeSpecific<T>> {
/**
* Returns a specialized copy of T for functioning in the given node.
*/
T forNode(Node node, TaskListener log) throws IOException, InterruptedException;
T forNode(@NonNull Node node, TaskListener log) throws IOException, InterruptedException;
}
@@ -193,6 +193,7 @@ public abstract class RetentionStrategy<T extends Computer> extends AbstractDesc
return idleDelay;
}
@Override
public synchronized long check(SlaveComputer c) {
if (c.isOffline() && c.isLaunchSupported()) {
final HashMap<Computer, Integer> availableComputers = new HashMap<Computer, Integer>();
@@ -211,7 +212,8 @@ public abstract class RetentionStrategy<T extends Computer> extends AbstractDesc
// assume the answer is no until we can find such an executor
boolean needExecutor = true;
for (Computer o : Collections.unmodifiableSet(availableComputers.keySet())) {
if (o.getNode().canTake(item) == null) {
Node otherNode = o.getNode();
if (otherNode != null && otherNode.canTake(item) == null) {
needExecutor = false;
final int availableExecutors = availableComputers.remove(o);
if (availableExecutors > 1) {
@@ -224,7 +226,8 @@ public abstract class RetentionStrategy<T extends Computer> extends AbstractDesc
}
// this 'item' cannot be built by any of the existing idle nodes, but it can be built by 'c'
if (needExecutor && c.getNode().canTake(item) == null) {
Node checkedNode = c.getNode();
if (needExecutor && checkedNode != null && checkedNode.canTake(item) == null) {
demandMilliseconds = System.currentTimeMillis() - item.buildableStartMilliseconds;
needComputer = demandMilliseconds > inDemandDelay * 1000 * 60 /*MINS->MILLIS*/;
break;
@@ -251,6 +254,7 @@ public abstract class RetentionStrategy<T extends Computer> extends AbstractDesc
@Extension
public static class DescriptorImpl extends Descriptor<RetentionStrategy<?>> {
@Override
public String getDisplayName() {
return Messages.RetentionStrategy_Demand_displayName();
}
@@ -78,8 +78,11 @@ import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import javax.annotation.CheckForNull;
import jenkins.model.Jenkins;
import static hudson.slaves.SlaveComputer.LogHolder.*;
/**
* {@link Computer} for {@link Slave}s.
*
@@ -168,6 +171,7 @@ public class SlaveComputer extends Computer {
return isUnix;
}
@CheckForNull
@Override
public Slave getNode() {
Node node = super.getNode();
@@ -418,7 +422,7 @@ public class SlaveComputer extends Computer {
}
/**
* Sets up the connection through an exsting channel.
* Sets up the connection through an existing channel.
*
* @since 1.444
*/
@@ -454,10 +458,15 @@ public class SlaveComputer extends Computer {
String defaultCharsetName = channel.call(new DetectDefaultCharset());
String remoteFs = getNode().getRemoteFS();
Slave node = getNode();
if (node == null) { // Node has been disabled/removed during the connection
throw new IOException("Node "+nodeName+" has been deleted during the channel setup");
}
String remoteFs = node.getRemoteFS();
if(_isUnix && !remoteFs.contains("/") && remoteFs.contains("\\"))
log.println("WARNING: "+remoteFs+" looks suspiciously like Windows path. Maybe you meant "+remoteFs.replace('\\','/')+"?");
FilePath root = new FilePath(channel,getNode().getRemoteFS());
FilePath root = new FilePath(channel,remoteFs);
// reference counting problem is known to happen, such as JENKINS-9017, and so as a preventive measure
// we pin the base classloader so that it'll never get GCed. When this classloader gets released,
@@ -247,11 +247,9 @@ public class BuildTrigger extends Recorder implements DependencyDeclarer {
logger.println(Messages.BuildTrigger_Disabled(ModelHyperlinkNote.encodeTo(p)));
continue;
}
// this is not completely accurate, as a new build might be triggered
// between these calls
boolean scheduled = p.scheduleBuild(p.getQuietPeriod(), new UpstreamCause((Run)build), buildActions.toArray(new Action[buildActions.size()]));
if (Jenkins.getInstance().getItemByFullName(p.getFullName()) == p) {
String name = ModelHyperlinkNote.encodeTo(p) + " #" + p.getNextBuildNumber();
String name = ModelHyperlinkNote.encodeTo(p);
if (scheduled) {
logger.println(Messages.BuildTrigger_Triggering(name));
} else {
@@ -41,6 +41,7 @@ import java.util.List;
import com.thoughtworks.xstream.annotations.XStreamSerializable;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import jenkins.model.Jenkins;
/**
@@ -163,7 +164,7 @@ public abstract class ToolInstallation extends AbstractDescribableImpl<ToolInsta
* @see EnvironmentSpecific
* @since 1.460
*/
public ToolInstallation translate(Node node, EnvVars envs, TaskListener listener) throws IOException, InterruptedException {
public ToolInstallation translate(@Nonnull Node node, EnvVars envs, TaskListener listener) throws IOException, InterruptedException {
ToolInstallation t = this;
if (t instanceof NodeSpecific) {
NodeSpecific n = (NodeSpecific) t;
@@ -210,10 +210,11 @@ public abstract class PeepholePermalink extends Permalink implements Predicate<R
public void onDeleted(Run run) {
Job<?, ?> j = run.getParent();
for (PeepholePermalink pp : Util.filter(j.getPermalinks(), PeepholePermalink.class)) {
if (pp.apply(run)) {
if (pp.resolve(j)==run) {
pp.updateCache(j,pp.find(run.getPreviousBuild()));
}
if (pp.resolve(j)==run) {
Run<?,?> r = pp.find(run.getPreviousBuild());
if (LOGGER.isLoggable(Level.FINE))
LOGGER.fine("Updating "+pp.getPermalinkFile(j).getName()+" permalink from deleted "+run.getNumber()+" to "+(r == null ? -1 : r.getNumber()));
pp.updateCache(j,r);
}
}
}
@@ -227,8 +228,11 @@ public abstract class PeepholePermalink extends Permalink implements Predicate<R
for (PeepholePermalink pp : Util.filter(j.getPermalinks(), PeepholePermalink.class)) {
if (pp.apply(run)) {
Run<?, ?> cur = pp.resolve(j);
if (cur==null || cur.getNumber()<run.getNumber())
if (cur==null || cur.getNumber()<run.getNumber()) {
if (LOGGER.isLoggable(Level.FINE))
LOGGER.fine("Updating "+pp.getPermalinkFile(j).getName()+" permalink to completed "+run.getNumber());
pp.updateCache(j,run);
}
}
}
}
+6
View File
@@ -1,3 +1,9 @@
jenkins (1.566) unstable; urgency=low
* See http://jenkins-ci.org/changelog for more details.
-- Kohsuke Kawaguchi <kk@kohsuke.org> Mon, 02 Jun 2014 08:18:10 -0700
jenkins (1.565) unstable; urgency=low
* See http://jenkins-ci.org/changelog for more details.
+4 -4
View File
@@ -11,7 +11,7 @@
<groupId>org.jenkins-ci.plugins</groupId>
<artifactId>plugin</artifactId>
<name>Jenkins plugin POM</name>
<version>1.567-SNAPSHOT</version>
<version>1.568-SNAPSHOT</version>
<packaging>pom</packaging>
<!--
@@ -39,19 +39,19 @@
<groupId>org.jenkins-ci.main</groupId>
<artifactId>jenkins-war</artifactId>
<type>war</type>
<version>1.567-SNAPSHOT</version>
<version>1.568-SNAPSHOT</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jenkins-ci.main</groupId>
<artifactId>jenkins-core</artifactId>
<version>1.567-SNAPSHOT</version>
<version>1.568-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jenkins-ci.main</groupId>
<artifactId>jenkins-test-harness</artifactId>
<version>1.567-SNAPSHOT</version>
<version>1.568-SNAPSHOT</version>
<scope>test</scope>
</dependency>
<!--
+1 -1
View File
@@ -33,7 +33,7 @@ THE SOFTWARE.
<groupId>org.jenkins-ci.main</groupId>
<artifactId>pom</artifactId>
<version>1.567-SNAPSHOT</version>
<version>1.568-SNAPSHOT</version>
<packaging>pom</packaging>
<name>Jenkins main module</name>
+3 -3
View File
@@ -29,7 +29,7 @@ THE SOFTWARE.
<parent>
<artifactId>pom</artifactId>
<groupId>org.jenkins-ci.main</groupId>
<version>1.567-SNAPSHOT</version>
<version>1.568-SNAPSHOT</version>
</parent>
<groupId>org.jenkins-ci.main</groupId>
<artifactId>jenkins-test-harness</artifactId>
@@ -103,9 +103,9 @@ THE SOFTWARE.
<version>6.1.26</version>
</dependency>
<dependency>
<groupId>org.jvnet.hudson</groupId>
<groupId>org.jenkins-ci</groupId>
<artifactId>test-annotations</artifactId>
<version>1.0</version>
<version>1.1</version>
<scope>compile</scope>
<!-- in this module we need this as a compile scope, whereas in the parent it's test -->
</dependency>
@@ -0,0 +1,129 @@
/*
* The MIT License
*
* Copyright 2013 Oleg Nenashev <nenashev@synopsys.com>, Synopsys 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;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.BuildListener;
import hudson.model.FreeStyleProject;
import hudson.model.Run;
import hudson.tasks.BuildWrapper;
import hudson.tasks.BuildWrapperDescriptor;
import java.io.IOException;
import org.jvnet.hudson.test.Bug;
import hudson.Launcher.DecoratedLauncher;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;
/**
* Contains tests for {@link ProcStarter} class.
* @author Oleg Nenashev <nenashev@synopsys.com>, Synopsys Inc.
* @since TODO: define a version
*/
public class ProcStarterTest {
@Rule
public JenkinsRule rule = new JenkinsRule();
@Test
@Bug(20559)
public void testNonInitializedEnvsNPE() throws Exception {
// Create nodes and other test stuff
rule.hudson.setNumExecutors(0);
rule.createSlave();
// Create a job with test build wrappers
FreeStyleProject project = rule.createFreeStyleProject();
project.getBuildWrappersList().add(new DecoratedWrapper());
project.getBuildWrappersList().add(new EchoWrapper());
// Run the build. If NPE occurs, the test will fail
rule.buildAndAssertSuccess(project);
}
/**
* A stub descriptor for {@link BuildWrapper}s.
*/
public abstract static class TestWrapperDescriptor extends BuildWrapperDescriptor {
@Override
public boolean isApplicable(AbstractProject<?, ?> ap) {
return true;
}
@Override
public String getDisplayName() {
return "testStub";
}
}
/**
* A wrapper, which contains a nested launch.
*/
public static class EchoWrapper extends BuildWrapper {
@Override
public Environment setUp(AbstractBuild build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException {
Launcher.ProcStarter starter = launcher.launch().cmds("echo", "Hello");
starter.start();
starter.join();
return new Environment() {
};
}
@Extension
public static class DescriptorImpl extends TestWrapperDescriptor {
}
};
/**
* A wrapper, which decorates launchers.
*/
public static class DecoratedWrapper extends BuildWrapper {
@Override
public Launcher decorateLauncher(AbstractBuild build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException, Run.RunnerAbortedException {
final BuildListener l = listener;
return new DecoratedLauncher(launcher) {
@Override
public Proc launch(Launcher.ProcStarter starter) throws IOException {
String[] envs = starter.envs(); // Finally, call envs()
l.getLogger().println("[DecoratedWrapper]: Number of environment variables is "+envs.length); // Fail on null
return super.launch(starter);
}
};
}
@Override
public Environment setUp(AbstractBuild build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException {
return new Environment() {
};
}
@Extension
public static class DescriptorImpl extends TestWrapperDescriptor {
}
};
}
+1 -1
View File
@@ -28,7 +28,7 @@ THE SOFTWARE.
<parent>
<groupId>org.jenkins-ci.main</groupId>
<artifactId>pom</artifactId>
<version>1.567-SNAPSHOT</version>
<version>1.568-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>