diff --git a/cli/src/main/java/hudson/cli/CLI.java b/cli/src/main/java/hudson/cli/CLI.java index 862847df96731df8c3c5aa6ebf62d2696322375e..a6a33c6f800e96e6286d5ac8628b2ecbe5be0a0f 100644 --- a/cli/src/main/java/hudson/cli/CLI.java +++ b/cli/src/main/java/hudson/cli/CLI.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.cli; import static java.util.logging.Level.FINE; @@ -80,9 +81,10 @@ public class CLI { * @throws NotTalkingToJenkinsException when connection is not made to Jenkins service. */ /*package*/ static void verifyJenkinsConnection(URLConnection c) throws IOException { - if (c.getHeaderField("X-Hudson")==null && c.getHeaderField("X-Jenkins")==null) + if (c.getHeaderField("X-Hudson") == null && c.getHeaderField("X-Jenkins") == null) throw new NotTalkingToJenkinsException(c); } + /*package*/ static final class NotTalkingToJenkinsException extends IOException { NotTalkingToJenkinsException(String s) { super(s); @@ -106,14 +108,15 @@ public class CLI { } } - private enum Mode {HTTP, SSH, WEB_SOCKET} + private enum Mode { HTTP, SSH, WEB_SOCKET } + public static int _main(String[] _args) throws Exception { List args = Arrays.asList(_args); PrivateKeyProvider provider = new PrivateKeyProvider(); String url = System.getenv("JENKINS_URL"); - if (url==null) + if (url == null) url = System.getenv("HUDSON_URL"); boolean noKeyAuth = false; @@ -130,10 +133,10 @@ public class CLI { boolean strictHostKey = false; - while(!args.isEmpty()) { + while (!args.isEmpty()) { String head = args.get(0); if (head.equals("-version")) { - System.out.println("Version: "+computeVersion()); + System.out.println("Version: " + computeVersion()); return 0; } if (head.equals("-http")) { @@ -167,9 +170,9 @@ public class CLI { printUsage("-remoting mode is no longer supported"); return -1; } - if(head.equals("-s") && args.size()>=2) { + if (head.equals("-s") && args.size() >= 2) { url = args.get(1); - args = args.subList(2,args.size()); + args = args.subList(2, args.size()); continue; } if (head.equals("-noCertificateCheck")) { @@ -185,15 +188,15 @@ public class CLI { return true; } }); - args = args.subList(1,args.size()); + args = args.subList(1, args.size()); continue; } if (head.equals("-noKeyAuth")) { noKeyAuth = true; - args = args.subList(1,args.size()); + args = args.subList(1, args.size()); continue; } - if(head.equals("-i") && args.size()>=2) { + if (head.equals("-i") && args.size() >= 2) { File f = getFileFromArguments(args); if (!f.exists()) { printUsage(Messages.CLI_NoSuchFileExists(f)); @@ -202,7 +205,7 @@ public class CLI { provider.readFrom(f); - args = args.subList(2,args.size()); + args = args.subList(2, args.size()); continue; } if (head.equals("-strictHostKey")) { @@ -239,7 +242,7 @@ public class CLI { break; } - if(url==null) { + if (url == null) { printUsage(Messages.CLI_NoURL()); return -1; } @@ -263,7 +266,7 @@ public class CLI { url += '/'; } - if(args.isEmpty()) + if (args.isEmpty()) args = Collections.singletonList("help"); // default to help if (mode == null) { @@ -338,6 +341,7 @@ public class CLI { @Override public void onOpen(Session session, EndpointConfig config) {} } + class Authenticator extends ClientEndpointConfig.Configurator { @Override public void beforeRequest(Map> headers) { @@ -346,6 +350,7 @@ public class CLI { } } } + ClientManager client = ClientManager.createClient(JdkClientContainer.class.getName()); // ~ ContainerProvider.getWebSocketContainer() client.getProperties().put(ClientProperties.REDIRECT_ENABLED, true); // https://tyrus-project.github.io/documentation/1.13.1/index/tyrus-proprietary-config.html#d0e1775 Session session = client.connectToServer(new CLIEndpoint(), ClientEndpointConfig.Builder.create().configurator(new Authenticator()).build(), URI.create(url.replaceFirst("^http", "ws") + "cli/ws")); @@ -354,6 +359,7 @@ public class CLI { public void send(byte[] data) throws IOException { session.getBasicRemote().sendBinary(ByteBuffer.wrap(data)); } + @Override public void close() throws IOException { session.close(); @@ -479,7 +485,7 @@ public class CLI { Properties props = new Properties(); try { InputStream is = CLI.class.getResourceAsStream("/jenkins/cli/jenkins-cli-version.properties"); - if(is!=null) { + if (is != null) { try { props.load(is); } finally { @@ -489,7 +495,7 @@ public class CLI { } catch (IOException e) { e.printStackTrace(); // if the version properties is missing, that's OK. } - return props.getProperty("version","?"); + return props.getProperty("version", "?"); } /** @@ -520,7 +526,7 @@ public class CLI { } private static void printUsage(String msg) { - if(msg!=null) System.out.println(msg); + if (msg != null) System.out.println(msg); System.err.println(usage()); } diff --git a/cli/src/main/java/hudson/cli/CLIConnectionFactory.java b/cli/src/main/java/hudson/cli/CLIConnectionFactory.java index 0553dd215de57930ed6df21945e6e19daed76651..9b4295b07cb343acbd15b0543ca8f5fcaf503237 100644 --- a/cli/src/main/java/hudson/cli/CLIConnectionFactory.java +++ b/cli/src/main/java/hudson/cli/CLIConnectionFactory.java @@ -5,7 +5,7 @@ import java.util.Base64; /** * Fluent-API to instantiate {@link CLI}. - * + * * @author Kohsuke Kawaguchi */ public class CLIConnectionFactory { @@ -26,7 +26,7 @@ public class CLIConnectionFactory { * Currently unused. */ public CLIConnectionFactory basicAuth(String username, String password) { - return basicAuth(username+':'+password); + return basicAuth(username + ':' + password); } /** diff --git a/cli/src/main/java/hudson/cli/DiagnosedStreamCorruptionException.java b/cli/src/main/java/hudson/cli/DiagnosedStreamCorruptionException.java index 4708b425dbb77a715910ac28c67ec84aca79db0f..a701cb3033474dffb19110c339cfce734b811615 100644 --- a/cli/src/main/java/hudson/cli/DiagnosedStreamCorruptionException.java +++ b/cli/src/main/java/hudson/cli/DiagnosedStreamCorruptionException.java @@ -41,14 +41,14 @@ class DiagnosedStreamCorruptionException extends StreamCorruptedException { buf.append(super.toString()).append("\n"); buf.append("Read back: ").append(HexDump.toHex(readBack)).append('\n'); buf.append("Read ahead: ").append(HexDump.toHex(readAhead)); - if (diagnoseFailure!=null) { + if (diagnoseFailure != null) { StringWriter w = new StringWriter(); PrintWriter p = new PrintWriter(w); diagnoseFailure.printStackTrace(p); p.flush(); buf.append("\nDiagnosis problem:\n "); - buf.append(w.toString().trim().replace("\n","\n ")); + buf.append(w.toString().trim().replace("\n", "\n ")); } return buf.toString(); } diff --git a/cli/src/main/java/hudson/cli/FlightRecorderInputStream.java b/cli/src/main/java/hudson/cli/FlightRecorderInputStream.java index 4dc9700e9371edc1795cbc1db36b6d0c9de3d9ef..5a1167c4fdc5d15709c466dfd2698d7f4a18a683 100644 --- a/cli/src/main/java/hudson/cli/FlightRecorderInputStream.java +++ b/cli/src/main/java/hudson/cli/FlightRecorderInputStream.java @@ -52,13 +52,13 @@ class FlightRecorderInputStream extends InputStream { final ByteArrayOutputStream readAhead = new ByteArrayOutputStream(); final IOException[] error = new IOException[1]; - Thread diagnosisThread = new Thread(diagnosisName+" stream corruption diagnosis thread") { + Thread diagnosisThread = new Thread(diagnosisName + " stream corruption diagnosis thread") { @Override public void run() { int b; try { // not all InputStream will look for the thread interrupt flag, so check that explicitly to be defensive - while (!Thread.interrupted() && (b=source.read())!=-1) { + while (!Thread.interrupted() && (b = source.read()) != -1) { readAhead.write(b); } } catch (IOException e) { @@ -81,14 +81,14 @@ class FlightRecorderInputStream extends InputStream { if (diagnosisThread.isAlive()) diagnosisThread.interrupt(); // if it's not dead, kill - return new DiagnosedStreamCorruptionException(problem,diagnosisProblem,getRecord(),readAhead.toByteArray()); + return new DiagnosedStreamCorruptionException(problem, diagnosisProblem, getRecord(), readAhead.toByteArray()); } @Override public int read() throws IOException { int i = source.read(); - if (i>=0) + if (i >= 0) recorder.write(i); return i; } @@ -96,8 +96,8 @@ class FlightRecorderInputStream extends InputStream { @Override public int read(@NonNull byte[] b, int off, int len) throws IOException { len = source.read(b, off, len); - if (len>0) - recorder.write(b,off,len); + if (len > 0) + recorder.write(b, off, len); return len; } @@ -106,8 +106,8 @@ class FlightRecorderInputStream extends InputStream { */ @Override public long skip(long n) throws IOException { - byte[] buf = new byte[(int)Math.min(n,64*1024)]; - return read(buf,0,buf.length); + byte[] buf = new byte[(int) Math.min(n, 64 * 1024)]; + return read(buf, 0, buf.length); } @Override @@ -157,7 +157,7 @@ class FlightRecorderInputStream extends InputStream { System.arraycopy(data, 0, ret, capacity - pos, pos); return ret; } - + /** @author @roadrunner2 */ @Override public synchronized void write(@NonNull byte[] buf, int off, int len) { // no point in trying to copy more than capacity; this also simplifies logic below diff --git a/cli/src/main/java/hudson/cli/FullDuplexHttpStream.java b/cli/src/main/java/hudson/cli/FullDuplexHttpStream.java index fec9d7d3b9d3c93af2528688ca9cb667cdb76d16..ae8917ab3aa6d54b5464ea12c92fa670d12935bc 100644 --- a/cli/src/main/java/hudson/cli/FullDuplexHttpStream.java +++ b/cli/src/main/java/hudson/cli/FullDuplexHttpStream.java @@ -18,7 +18,7 @@ import java.util.logging.Logger; */ public class FullDuplexHttpStream { private final URL base; - + private final OutputStream output; private final InputStream input; @@ -65,7 +65,7 @@ public class FullDuplexHttpStream { con.setDoOutput(true); // request POST to avoid caching con.setRequestMethod("POST"); con.addRequestProperty("Session", uuid.toString()); - con.addRequestProperty("Side","download"); + con.addRequestProperty("Side", "download"); if (authorization != null) { con.addRequestProperty("Authorization", authorization); } @@ -83,11 +83,11 @@ public class FullDuplexHttpStream { con.setDoOutput(true); // request POST con.setRequestMethod("POST"); con.setChunkedStreamingMode(0); - con.setRequestProperty("Content-type","application/octet-stream"); + con.setRequestProperty("Content-type", "application/octet-stream"); con.addRequestProperty("Session", uuid.toString()); - con.addRequestProperty("Side","upload"); + con.addRequestProperty("Side", "upload"); if (authorization != null) { - con.addRequestProperty ("Authorization", authorization); + con.addRequestProperty("Authorization", authorization); } output = con.getOutputStream(); LOGGER.fine("established upload side"); @@ -118,5 +118,5 @@ public class FullDuplexHttpStream { static final int BLOCK_SIZE = 1024; static final Logger LOGGER = Logger.getLogger(FullDuplexHttpStream.class.getName()); - + } diff --git a/cli/src/main/java/hudson/cli/HexDump.java b/cli/src/main/java/hudson/cli/HexDump.java index ad37158bc16d0e7939a34831bd7628120eb61207..0132f47f130da592aa86aec139a7fdf74c761742 100644 --- a/cli/src/main/java/hudson/cli/HexDump.java +++ b/cli/src/main/java/hudson/cli/HexDump.java @@ -9,13 +9,14 @@ class HexDump { private static final String CODE = "0123456789abcdef"; public static String toHex(byte[] buf) { - return toHex(buf,0,buf.length); + return toHex(buf, 0, buf.length); } + public static String toHex(byte[] buf, int start, int len) { - StringBuilder r = new StringBuilder(len*2); + StringBuilder r = new StringBuilder(len * 2); boolean inText = false; - for (int i=0; i= 0x20 && b <= 0x7e) { if (!inText) { inText = true; @@ -28,8 +29,8 @@ class HexDump { inText = false; } r.append("0x"); - r.append(CODE.charAt((b>>4)&15)); - r.append(CODE.charAt(b&15)); + r.append(CODE.charAt((b >> 4) & 15)); + r.append(CODE.charAt(b & 15)); if (i < len - 1) { if (b == 10) { r.append('\n'); diff --git a/cli/src/main/java/hudson/cli/PlainCLIProtocol.java b/cli/src/main/java/hudson/cli/PlainCLIProtocol.java index 0c14433d101966161a54afa88fc03d3bdfd8baef..ac1f9dbfe10bbf856e9486ab2adee8652d42a0c0 100644 --- a/cli/src/main/java/hudson/cli/PlainCLIProtocol.java +++ b/cli/src/main/java/hudson/cli/PlainCLIProtocol.java @@ -233,10 +233,12 @@ class PlainCLIProtocol { public void write(int b) throws IOException { send(op, new byte[] {(byte) b}); } + @Override public void write(@NonNull byte[] b, int off, int len) throws IOException { send(op, b, off, len); } + @Override public void write(@NonNull byte[] b) throws IOException { send(op, b); diff --git a/cli/src/main/java/hudson/cli/PrivateKeyProvider.java b/cli/src/main/java/hudson/cli/PrivateKeyProvider.java index f283053f9cb59939f6c650a50e608ad006153618..64c84fc2074de668f4b6846036d22b7a840754f2 100644 --- a/cli/src/main/java/hudson/cli/PrivateKeyProvider.java +++ b/cli/src/main/java/hudson/cli/PrivateKeyProvider.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.cli; import static java.util.logging.Level.FINE; @@ -110,15 +111,15 @@ public class PrivateKeyProvider { privateKeys.add(loadKey(keyFile, password)); } - private static boolean isPemEncrypted(File f) throws IOException{ + private static boolean isPemEncrypted(File f) throws IOException { //simple check if the file is encrypted return readPemFile(f).contains("4,ENCRYPTED"); } - private static String askForPasswd(String filePath){ + private static String askForPasswd(String filePath) { Console cons = System.console(); String passwd = null; - if (cons != null){ + if (cons != null) { char[] p = cons.readPassword("%s", "Enter passphrase for " + filePath + ":"); passwd = String.valueOf(p); } @@ -129,7 +130,7 @@ public class PrivateKeyProvider { return loadKey(readPemFile(f), passwd); } - private static String readPemFile(File f) throws IOException{ + private static String readPemFile(File f) throws IOException { try (InputStream is = Files.newInputStream(f.toPath()); DataInputStream dis = new DataInputStream(is)) { byte[] bytes = new byte[(int) f.length()]; diff --git a/cli/src/main/java/hudson/cli/SSHCLI.java b/cli/src/main/java/hudson/cli/SSHCLI.java index d9fa4911df84c52f8f12c2fcba007c31f96c6e19..5badd296fbf0e3b0d384782c704828f22e3ad62b 100644 --- a/cli/src/main/java/hudson/cli/SSHCLI.java +++ b/cli/src/main/java/hudson/cli/SSHCLI.java @@ -85,7 +85,7 @@ class SSHCLI { command.append(' '); } - try(SshClient client = SshClient.setUpDefaultClient()) { + try (SshClient client = SshClient.setUpDefaultClient()) { KnownHostsServerKeyVerifier verifier = new DefaultKnownHostsServerKeyVerifier(new ServerKeyVerifier() { @Override @@ -116,7 +116,7 @@ class SSHCLI { Set waitMask = channel.waitFor(Collections.singletonList(ClientChannelEvent.CLOSED), 0L); - if(waitMask.contains(ClientChannelEvent.TIMEOUT)) { + if (waitMask.contains(ClientChannelEvent.TIMEOUT)) { throw new SocketTimeoutException("Failed to retrieve command result in time: " + command); } diff --git a/cli/src/main/java/hudson/util/QuotedStringTokenizer.java b/cli/src/main/java/hudson/util/QuotedStringTokenizer.java index 6b8a6f43f7811d1e4964a721a414ed3123451a07..6f77b758bc1f301a8d34975ce75a8bc2647fd088 100644 --- a/cli/src/main/java/hudson/util/QuotedStringTokenizer.java +++ b/cli/src/main/java/hudson/util/QuotedStringTokenizer.java @@ -33,6 +33,7 @@ // See the License for the specific language governing permissions and // limitations under the License. // ======================================================================== + package hudson.util; import java.util.ArrayList; @@ -55,24 +56,24 @@ import java.util.StringTokenizer; public class QuotedStringTokenizer extends StringTokenizer { - private static final String __delim=" \t\n\r"; + private static final String __delim = " \t\n\r"; private String _string; private String _delim = __delim; - private boolean _returnQuotes=false; - private boolean _returnDelimiters=false; + private boolean _returnQuotes = false; + private boolean _returnDelimiters = false; private StringBuilder _token; - private boolean _hasToken=false; - private int _i=0; - private int _lastStart=0; - private boolean _double=true; - private boolean _single=true; + private boolean _hasToken = false; + private int _i = 0; + private int _lastStart = 0; + private boolean _double = true; + private boolean _single = true; public static String[] tokenize(String str) { return new QuotedStringTokenizer(str).toArray(); } public static String[] tokenize(String str, String delimiters) { - return new QuotedStringTokenizer(str,delimiters).toArray(); + return new QuotedStringTokenizer(str, delimiters).toArray(); } /* ------------------------------------------------------------ */ @@ -94,17 +95,17 @@ public class QuotedStringTokenizer boolean returnQuotes) { super(""); - _string=str; - if (delim!=null) - _delim=delim; - _returnDelimiters=returnDelimiters; - _returnQuotes=returnQuotes; + _string = str; + if (delim != null) + _delim = delim; + _returnDelimiters = returnDelimiters; + _returnQuotes = returnQuotes; - if (_delim.indexOf('\'')>=0 || - _delim.indexOf('"')>=0) - throw new Error("Can't use quotes as delimiters: "+_delim); + if (_delim.indexOf('\'') >= 0 || + _delim.indexOf('"') >= 0) + throw new Error("Can't use quotes as delimiters: " + _delim); - _token=new StringBuilder(_string.length()>1024?512:_string.length()/2); + _token = new StringBuilder(_string.length() > 1024 ? 512 : _string.length() / 2); } /* ------------------------------------------------------------ */ @@ -112,25 +113,25 @@ public class QuotedStringTokenizer String delim, boolean returnDelimiters) { - this(str,delim,returnDelimiters,false); + this(str, delim, returnDelimiters, false); } /* ------------------------------------------------------------ */ public QuotedStringTokenizer(String str, String delim) { - this(str,delim,false,false); + this(str, delim, false, false); } /* ------------------------------------------------------------ */ public QuotedStringTokenizer(String str) { - this(str,null,false,false); + this(str, null, false, false); } public String[] toArray() { List r = new ArrayList<>(); - while(hasMoreTokens()) + while (hasMoreTokens()) r.add(nextToken()); return r.toArray(new String[r.size()]); } @@ -144,75 +145,75 @@ public class QuotedStringTokenizer if (_hasToken) return true; - _lastStart=_i; + _lastStart = _i; - int state=0; - boolean escape=false; - while (_i<_string.length()) + int state = 0; + boolean escape = false; + while (_i < _string.length()) { - char c=_string.charAt(_i++); + char c = _string.charAt(_i++); switch (state) { case 0: // Start - if(_delim.indexOf(c)>=0) + if (_delim.indexOf(c) >= 0) { if (_returnDelimiters) { _token.append(c); - return _hasToken=true; + return _hasToken = true; } } - else if (c=='\'' && _single) + else if (c == '\'' && _single) { if (_returnQuotes) _token.append(c); - state=2; + state = 2; } - else if (c=='\"' && _double) + else if (c == '\"' && _double) { if (_returnQuotes) _token.append(c); - state=3; + state = 3; } else { _token.append(c); - _hasToken=true; - state=1; + _hasToken = true; + state = 1; } continue; case 1: // Token - _hasToken=true; + _hasToken = true; if (escape) { - escape=false; - if(ESCAPABLE_CHARS.indexOf(c)<0) + escape = false; + if (ESCAPABLE_CHARS.indexOf(c) < 0) _token.append('\\'); _token.append(c); } - else if(_delim.indexOf(c)>=0) + else if (_delim.indexOf(c) >= 0) { if (_returnDelimiters) _i--; return _hasToken; } - else if (c=='\'' && _single) + else if (c == '\'' && _single) { if (_returnQuotes) _token.append(c); - state=2; + state = 2; } - else if (c=='\"' && _double) + else if (c == '\"' && _double) { if (_returnQuotes) _token.append(c); - state=3; + state = 3; } - else if (c=='\\') + else if (c == '\\') { - escape=true; + escape = true; } else _token.append(c); @@ -220,25 +221,25 @@ public class QuotedStringTokenizer case 2: // Single Quote - _hasToken=true; + _hasToken = true; if (escape) { - escape=false; - if(ESCAPABLE_CHARS.indexOf(c)<0) + escape = false; + if (ESCAPABLE_CHARS.indexOf(c) < 0) _token.append('\\'); _token.append(c); } - else if (c=='\'') + else if (c == '\'') { if (_returnQuotes) _token.append(c); - state=1; + state = 1; } - else if (c=='\\') + else if (c == '\\') { if (_returnQuotes) _token.append(c); - escape=true; + escape = true; } else _token.append(c); @@ -246,25 +247,25 @@ public class QuotedStringTokenizer case 3: // Double Quote - _hasToken=true; + _hasToken = true; if (escape) { - escape=false; - if(ESCAPABLE_CHARS.indexOf(c)<0) + escape = false; + if (ESCAPABLE_CHARS.indexOf(c) < 0) _token.append('\\'); _token.append(c); } - else if (c=='\"') + else if (c == '\"') { if (_returnQuotes) _token.append(c); - state=1; + state = 1; } - else if (c=='\\') + else if (c == '\\') { if (_returnQuotes) _token.append(c); - escape=true; + escape = true; } else _token.append(c); @@ -283,11 +284,11 @@ public class QuotedStringTokenizer public String nextToken() throws NoSuchElementException { - if (!hasMoreTokens() || _token==null) + if (!hasMoreTokens() || _token == null) throw new NoSuchElementException(); - String t=_token.toString(); + String t = _token.toString(); _token.setLength(0); - _hasToken=false; + _hasToken = false; return t; } @@ -296,10 +297,10 @@ public class QuotedStringTokenizer public String nextToken(String delim) throws NoSuchElementException { - _delim=delim; - _i=_lastStart; + _delim = delim; + _i = _lastStart; _token.setLength(0); - _hasToken=false; + _hasToken = false; return nextToken(); } @@ -338,19 +339,19 @@ public class QuotedStringTokenizer */ public static String quote(String s, String delim) { - if (s==null) + if (s == null) return null; - if (s.length()==0) + if (s.length() == 0) return "\"\""; - for (int i=0;i=0) + if (c == '\\' || c == '"' || c == '\'' || Character.isWhitespace(c) || delim.indexOf(c) >= 0) { - StringBuffer b=new StringBuffer(s.length()+8); - quote(b,s); + StringBuffer b = new StringBuffer(s.length() + 8); + quote(b, s); return b.toString(); } } @@ -368,13 +369,13 @@ public class QuotedStringTokenizer */ public static String quote(String s) { - if (s==null) + if (s == null) return null; - if (s.length()==0) + if (s.length() == 0) return "\"\""; - StringBuffer b=new StringBuffer(s.length()+8); - quote(b,s); + StringBuffer b = new StringBuffer(s.length() + 8); + quote(b, s); return b.toString(); } @@ -388,13 +389,13 @@ public class QuotedStringTokenizer */ public static void quote(StringBuffer buf, String s) { - synchronized(buf) + synchronized (buf) { buf.append('"'); - for (int i=0;i= '0' && b <= '9') return (byte) (b - '0'); if (b >= 'a' && b <= 'f') return (byte) (b - 'a' + 10); @@ -546,7 +547,7 @@ public class QuotedStringTokenizer * * Others, like, say, \W will be left alone instead of becoming just W. * This is important to keep Hudson behave on Windows, which uses '\' as - * the directory separator. + * the directory separator. */ private static final String ESCAPABLE_CHARS = "\\\"' "; } diff --git a/cli/src/test/java/hudson/cli/HexDumpTest.java b/cli/src/test/java/hudson/cli/HexDumpTest.java index 52b6c2e631f41f77fde9e192e4e7e685b992a923..9e15de1453cbc385cc461e981442f2724978f014 100644 --- a/cli/src/test/java/hudson/cli/HexDumpTest.java +++ b/cli/src/test/java/hudson/cli/HexDumpTest.java @@ -24,9 +24,9 @@ public class HexDumpTest { static Stream testToHex1Sources() { return Stream.of( arguments("'fooBar'", new byte[] {'f', 'o', 'o', 'B', 'a', 'r'}), - arguments("0xc3", new byte[] {(byte)'Ã'}), - arguments("0xac '100'", new byte[] {(byte)'€', '1', '0', '0'}), - arguments("'1' 0xf7 '2'", new byte[] {'1', (byte)'÷', '2'}), + arguments("0xc3", new byte[] {(byte) 'Ã'}), + arguments("0xac '100'", new byte[] {(byte) '€', '1', '0', '0'}), + arguments("'1' 0xf7 '2'", new byte[] {'1', (byte) '÷', '2'}), arguments("'foo' 0x0a\n'Bar'", new byte[] {'f', 'o', 'o', '\n', 'B', 'a', 'r'}) ); } @@ -41,9 +41,9 @@ public class HexDumpTest { static Stream testToHex2Sources() { return Stream.of( arguments("'ooBa'", new byte[] {'f', 'o', 'o', 'B', 'a', 'r'}, 1, 4), - arguments("0xc3", new byte[] {(byte)'Ã'}, 0, 1), - arguments("0xac '10'", new byte[] {(byte)'€', '1', '0', '0'}, 0, 3), - arguments("0xf7 '2'", new byte[] {'1', (byte)'÷', '2'}, 1, 2), + arguments("0xc3", new byte[] {(byte) 'Ã'}, 0, 1), + arguments("0xac '10'", new byte[] {(byte) '€', '1', '0', '0'}, 0, 3), + arguments("0xf7 '2'", new byte[] {'1', (byte) '÷', '2'}, 1, 2), arguments("'Bar'", new byte[] {'f', 'o', 'o', '\n', 'B', 'a', 'r'}, 4, 3), arguments("", new byte[] {'f', 'o', 'o', 'B', 'a', 'r'}, 0, 0) ); diff --git a/cli/src/test/java/hudson/cli/PlainCLIProtocolTest.java b/cli/src/test/java/hudson/cli/PlainCLIProtocolTest.java index 3eb29728fd71b9d893be752162468a5f0addcb95..71b0368111c45f5179c01a04901f7b9d3c266006 100644 --- a/cli/src/test/java/hudson/cli/PlainCLIProtocolTest.java +++ b/cli/src/test/java/hudson/cli/PlainCLIProtocolTest.java @@ -42,27 +42,34 @@ public class PlainCLIProtocolTest { class Client extends PlainCLIProtocol.ClientSide { int code = -1; final ByteArrayOutputStream stdout = new ByteArrayOutputStream(); + Client() throws IOException { super(new PlainCLIProtocol.FramedOutput(upload)); } + @Override protected synchronized void onExit(int code) { this.code = code; notifyAll(); } + @Override protected void onStdout(byte[] chunk) throws IOException { stdout.write(chunk); } + @Override protected void onStderr(byte[] chunk) throws IOException {} + @Override protected void handleClose() {} + void send() throws IOException { sendArg("command"); sendStart(); streamStdin().write("hello".getBytes()); } + void newop() throws IOException { DataOutputStream dos = new DataOutputStream(upload); dos.writeInt(0); @@ -70,26 +77,33 @@ public class PlainCLIProtocolTest { dos.flush(); } } + class Server extends PlainCLIProtocol.ServerSide { String arg; boolean started; final ByteArrayOutputStream stdin = new ByteArrayOutputStream(); + Server() throws IOException { super(new PlainCLIProtocol.FramedOutput(download)); } + @Override protected void onArg(String text) { arg = text; } + @Override protected void onLocale(String text) {} + @Override protected void onEncoding(String text) {} + @Override protected synchronized void onStart() { started = true; notifyAll(); } + @Override protected void onStdin(byte[] chunk) throws IOException { /* To inject a race condition: @@ -101,14 +115,18 @@ public class PlainCLIProtocolTest { */ stdin.write(chunk); } + @Override protected void onEndStdin() throws IOException {} + @Override protected void handleClose() {} + void send() throws IOException { streamStdout().write("goodbye".getBytes()); sendExit(2); } + void newop() throws IOException { DataOutputStream dos = new DataOutputStream(download); dos.writeInt(0); @@ -116,6 +134,7 @@ public class PlainCLIProtocolTest { dos.flush(); } } + Client client = new Client(); Server server = new Server(); new PlainCLIProtocol.FramedReader(client, new PipedInputStream(download)).start(); diff --git a/cli/src/test/java/hudson/util/QuotedStringTokenizerTest.java b/cli/src/test/java/hudson/util/QuotedStringTokenizerTest.java index 9af792ca7b2fb2e39abf5b0ac12afd9854a21d17..e5c546d11c3eecd6daafea27b5740032cd2c144b 100644 --- a/cli/src/test/java/hudson/util/QuotedStringTokenizerTest.java +++ b/cli/src/test/java/hudson/util/QuotedStringTokenizerTest.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.util; import static org.junit.jupiter.api.Assertions.assertArrayEquals; @@ -38,19 +39,19 @@ public class QuotedStringTokenizerTest { @Test public void test1() { check("foo bar", - "foo","bar"); + "foo", "bar"); } @Test public void test2() { check("foo \"bar zot\"", - "foo","bar zot"); + "foo", "bar zot"); } @Test public void test3() { check("foo bar=\"quote zot\"", - "foo","bar=quote zot"); + "foo", "bar=quote zot"); } @Test @@ -68,7 +69,7 @@ public class QuotedStringTokenizerTest { @Test public void test6() { check("foo\\\\ bar", - "foo\\","bar"); + "foo\\", "bar"); } // see http://www.nabble.com/Error-parsing-%22-in-msbuild-task-to20535754.html diff --git a/core/src/main/java/hudson/AbortException.java b/core/src/main/java/hudson/AbortException.java index b68276e8eec12409624d20932aa3c7c58f30391c..d3d58122c87eece0423250c1cdf41513be2045ff 100644 --- a/core/src/main/java/hudson/AbortException.java +++ b/core/src/main/java/hudson/AbortException.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson; import java.io.IOException; diff --git a/core/src/main/java/hudson/AboutJenkins.java b/core/src/main/java/hudson/AboutJenkins.java index 04847d28853e010cfbc9549b71a30f4d0e8ba3cc..56f463da1db1ecdbbd4e42196664cfe3cad54323 100644 --- a/core/src/main/java/hudson/AboutJenkins.java +++ b/core/src/main/java/hudson/AboutJenkins.java @@ -11,7 +11,7 @@ import org.kohsuke.accmod.restrictions.NoExternalUse; /** * Show "About Jenkins" link. - * + * * @author Kohsuke Kawaguchi */ @Extension @Symbol("about") diff --git a/core/src/main/java/hudson/AbstractMarkupText.java b/core/src/main/java/hudson/AbstractMarkupText.java index 59e65e9bcba02976185430845f6fa526cece5727..b13eeaad3edd024edb3fd5b7451541d21daa7b40 100644 --- a/core/src/main/java/hudson/AbstractMarkupText.java +++ b/core/src/main/java/hudson/AbstractMarkupText.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson; import hudson.MarkupText.SubText; @@ -74,15 +75,15 @@ public abstract class AbstractMarkupText { * For example, if the text was "abc", then {@code addMarkup(1,2,"","")} * would generate {@code "abc"} */ - public abstract void addMarkup( int startPos, int endPos, String startTag, String endTag ); + public abstract void addMarkup(int startPos, int endPos, String startTag, String endTag); /** * Inserts an A tag that surrounds the given position. * * @since 1.349 */ - public void addHyperlink( int startPos, int endPos, String url ) { - addMarkup(startPos,endPos,"",""); + public void addHyperlink(int startPos, int endPos, String url) { + addMarkup(startPos, endPos, "", ""); } /** @@ -91,22 +92,22 @@ public abstract class AbstractMarkupText { * * @since 1.395 */ - public void addHyperlinkLowKey( int startPos, int endPos, String url ) { - addMarkup(startPos,endPos,"",""); + public void addHyperlinkLowKey(int startPos, int endPos, String url) { + addMarkup(startPos, endPos, "", ""); } /** * Hides the given text. */ - public void hide( int startPos, int endPos ) { - addMarkup(startPos,endPos,"",""); + public void hide(int startPos, int endPos) { + addMarkup(startPos, endPos, "", ""); } /** * Adds a start tag and end tag around the entire text */ public final void wrapBy(String startTag, String endTag) { - addMarkup(0,length(),startTag,endTag); + addMarkup(0, length(), startTag, endTag); } /** @@ -118,7 +119,7 @@ public abstract class AbstractMarkupText { String text = getText(); Matcher m = pattern.matcher(text); - if(m.find()) + if (m.find()) return createSubText(m); return null; @@ -142,17 +143,17 @@ public abstract class AbstractMarkupText { Matcher m = pattern.matcher(text); List r = new ArrayList<>(); - while(m.find()) { + while (m.find()) { int idx = m.start(); - if(idx>0) { - char ch = text.charAt(idx-1); - if(Character.isLetter(ch) || Character.isDigit(ch)) + if (idx > 0) { + char ch = text.charAt(idx - 1); + if (Character.isLetter(ch) || Character.isDigit(ch)) continue; // not at a word boundary } idx = m.end(); - if(idx paths, ClassLoader parent) throws IOException { - return createClassLoader( paths, parent, null ); + return createClassLoader(paths, parent, null); } /** @@ -322,7 +323,7 @@ public class ClassicPluginStrategy implements PluginStrategy { */ private ClassLoader getBaseClassLoader(Attributes atts, ClassLoader base) { String masked = atts.getValue("Mask-Classes"); - if(masked!=null) + if (masked != null) base = new MaskingClassLoader(base, masked.trim().split("[ \t\r\n]+")); return base; } @@ -335,7 +336,7 @@ public class ClassicPluginStrategy implements PluginStrategy { public List> findComponents(Class type, Hudson hudson) { List finders; - if (type==ExtensionFinder.class) { + if (type == ExtensionFinder.class) { // Avoid infinite recursion of using ExtensionFinders to find ExtensionFinders finders = Collections.singletonList(new ExtensionFinder.Sezpoz()); } else { @@ -346,7 +347,7 @@ public class ClassicPluginStrategy implements PluginStrategy { * See ExtensionFinder#scout(Class, Hudson) for the dead lock issue and what this does. */ if (LOGGER.isLoggable(Level.FINER)) - LOGGER.log(Level.FINER, "Scout-loading ExtensionList: "+type, new Throwable()); + LOGGER.log(Level.FINER, "Scout-loading ExtensionList: " + type, new Throwable()); for (ExtensionFinder finder : finders) { finder.scout(type, hudson); } @@ -364,7 +365,7 @@ public class ClassicPluginStrategy implements PluginStrategy { List> filtered = new ArrayList<>(); for (ExtensionComponent e : r) { - if (ExtensionFilter.isAllowed(type,e)) + if (ExtensionFilter.isAllowed(type, e)) filtered.add(e); } @@ -379,21 +380,21 @@ public class ClassicPluginStrategy implements PluginStrategy { Thread.currentThread().setContextClassLoader(wrapper.classLoader); try { String className = wrapper.getPluginClass(); - if(className==null) { + if (className == null) { // use the default dummy instance wrapper.setPlugin(new DummyImpl()); } else { try { Class clazz = wrapper.classLoader.loadClass(className); Object o = clazz.getDeclaredConstructor().newInstance(); - if(!(o instanceof Plugin)) { - throw new IOException(className+" doesn't extend from hudson.Plugin"); + if (!(o instanceof Plugin)) { + throw new IOException(className + " doesn't extend from hudson.Plugin"); } wrapper.setPlugin((Plugin) o); } catch (LinkageError | ClassNotFoundException e) { - throw new IOException("Unable to load " + className + " from " + wrapper.getShortName(),e); + throw new IOException("Unable to load " + className + " from " + wrapper.getShortName(), e); } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) { - throw new IOException("Unable to create instance of " + className + " from " + wrapper.getShortName(),e); + throw new IOException("Unable to create instance of " + className + " from " + wrapper.getShortName(), e); } } @@ -402,9 +403,9 @@ public class ClassicPluginStrategy implements PluginStrategy { Plugin plugin = wrapper.getPluginOrFail(); plugin.setServletContext(pluginManager.context); startPlugin(wrapper); - } catch(Throwable t) { + } catch (Throwable t) { // gracefully handle any error in plugin. - throw new IOException("Failed to initialize",t); + throw new IOException("Failed to initialize", t); } } finally { Thread.currentThread().setContextClassLoader(old); @@ -428,14 +429,14 @@ public class ClassicPluginStrategy implements PluginStrategy { { for (; classLoader != null; classLoader = classLoader.getParent()) { if (classLoader instanceof DependencyClassLoader) { - return (DependencyClassLoader)classLoader; + return (DependencyClassLoader) classLoader; } if (classLoader instanceof AntClassLoader) { // AntClassLoaders hold parents not only as AntClassLoader#getParent() // but also as AntClassLoader#getConfiguredParent() DependencyClassLoader ret = findAncestorDependencyClassLoader( - ((AntClassLoader)classLoader).getConfiguredParent() + ((AntClassLoader) classLoader).getConfiguredParent() ); if (ret != null) { return ret; @@ -448,29 +449,29 @@ public class ClassicPluginStrategy implements PluginStrategy { @SuppressFBWarnings(value = "PATH_TRAVERSAL_IN", justification = "Administrator action installing a plugin, which could do far worse.") private static File resolve(File base, String relative) { File rel = new File(relative); - if(rel.isAbsolute()) + if (rel.isAbsolute()) return rel; else - return new File(base.getParentFile(),relative); + return new File(base.getParentFile(), relative); } private static void parseClassPath(Manifest manifest, File archive, List paths, String attributeName, String separator) throws IOException { String classPath = manifest.getMainAttributes().getValue(attributeName); - if(classPath==null) return; // attribute not found + if (classPath == null) return; // attribute not found for (String s : classPath.split(separator)) { File file = resolve(archive, s); - if(file.getName().contains("*")) { + if (file.getName().contains("*")) { // handle wildcard FileSet fs = new FileSet(); File dir = file.getParentFile(); fs.setDir(dir); fs.setIncludes(file.getName()); - for( String included : fs.getDirectoryScanner(new Project()).getIncludedFiles() ) { - paths.add(new File(dir,included)); + for (String included : fs.getDirectoryScanner(new Project()).getIncludedFiles()) { + paths.add(new File(dir, included)); } } else { - if(!file.exists()) - throw new IOException("No such file: "+file); + if (!file.exists()) + throw new IOException("No such file: " + file); paths.add(file); } } @@ -483,8 +484,8 @@ public class ClassicPluginStrategy implements PluginStrategy { Util.createDirectories(Util.fileToPath(destDir)); // timestamp check - File explodeTime = new File(destDir,".timestamp2"); - if(explodeTime.exists() && explodeTime.lastModified()==archive.lastModified()) + File explodeTime = new File(destDir, ".timestamp2"); + if (explodeTime.exists() && explodeTime.lastModified() == archive.lastModified()) return; // no need to expand // delete the contents so that old files won't interfere with new files @@ -495,7 +496,7 @@ public class ClassicPluginStrategy implements PluginStrategy { unzipExceptClasses(archive, destDir, prj); createClassJarFromWebInfClasses(archive, destDir, prj); } catch (BuildException x) { - throw new IOException("Failed to expand " + archive,x); + throw new IOException("Failed to expand " + archive, x); } try { @@ -530,7 +531,7 @@ public class ClassicPluginStrategy implements PluginStrategy { try (ZipOutputStream wrappedZOut = new ZipOutputStream(NullOutputStream.NULL_OUTPUT_STREAM) { @Override public void putNextEntry(ZipEntry ze) throws IOException { - ze.setTime(dirTime+1999); // roundup + ze.setTime(dirTime + 1999); // roundup super.putNextEntry(ze); } }) { @@ -544,7 +545,7 @@ public class ClassicPluginStrategy implements PluginStrategy { int mode, ZipExtraField[] extra) throws IOException { // use wrappedZOut instead of zOut - super.zipDir(dir,wrappedZOut,vPath,mode,extra); + super.zipDir(dir, wrappedZOut, vPath, mode, extra); } }; z.setProject(prj); @@ -617,7 +618,7 @@ public class ClassicPluginStrategy implements PluginStrategy { List dep = new ArrayList<>(); for (Dependency d : pw.getDependencies()) { PluginWrapper p = pluginManager.getPlugin(d.shortName); - if (p!=null && p.isActive()) + if (p != null && p.isActive()) dep.add(p); } return dep; @@ -627,7 +628,7 @@ public class ClassicPluginStrategy implements PluginStrategy { try { for (Dependency d : dependencies) { PluginWrapper p = pluginManager.getPlugin(d.shortName); - if (p!=null && p.isActive()) + if (p != null && p.isActive()) cgd.run(Collections.singleton(p)); } } catch (CycleDetectedException e) { @@ -654,7 +655,7 @@ public class ClassicPluginStrategy implements PluginStrategy { } else { for (Dependency dep : dependencies) { PluginWrapper p = pluginManager.getPlugin(dep.shortName); - if(p!=null) { + if (p != null) { try { return p.classLoader.loadClass(name); } catch (ClassNotFoundException ignored) { @@ -682,7 +683,7 @@ public class ClassicPluginStrategy implements PluginStrategy { } else { for (Dependency dep : dependencies) { PluginWrapper p = pluginManager.getPlugin(dep.shortName); - if (p!=null) { + if (p != null) { Enumeration urls = p.classLoader.getResources(name); while (urls != null && urls.hasMoreElements()) result.add(urls.nextElement()); @@ -698,14 +699,14 @@ public class ClassicPluginStrategy implements PluginStrategy { if (PluginManager.FAST_LOOKUP) { for (PluginWrapper pw : getTransitiveDependencies()) { URL url = ClassLoaderReflectionToolkit._findResource(pw.classLoader, name); - if (url!=null) return url; + if (url != null) return url; } } else { for (Dependency dep : dependencies) { PluginWrapper p = pluginManager.getPlugin(dep.shortName); - if(p!=null) { + if (p != null) { URL url = p.classLoader.getResource(name); - if (url!=null) + if (url != null) return url; } } diff --git a/core/src/main/java/hudson/CloseProofOutputStream.java b/core/src/main/java/hudson/CloseProofOutputStream.java index 5a9090e79cc40f0cf5832b7ddc21de79dcfc0fc0..0fc4aee48a5ce5ce9f47a7023817f353cf6a0f1e 100644 --- a/core/src/main/java/hudson/CloseProofOutputStream.java +++ b/core/src/main/java/hudson/CloseProofOutputStream.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson; import hudson.util.DelegatingOutputStream; diff --git a/core/src/main/java/hudson/CopyOnWrite.java b/core/src/main/java/hudson/CopyOnWrite.java index a36dbaf4e9f9154c3d9d7da53a55634747e3675c..04e737964a80135433ad111835fde6e5a97d5b9b 100644 --- a/core/src/main/java/hudson/CopyOnWrite.java +++ b/core/src/main/java/hudson/CopyOnWrite.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson; import static java.lang.annotation.ElementType.FIELD; diff --git a/core/src/main/java/hudson/DependencyRunner.java b/core/src/main/java/hudson/DependencyRunner.java index 914be79ffa6f7accb6e46a313c0c3052014f1b32..b7db91fb9416470d6570a39ab755d7a80f96199c 100644 --- a/core/src/main/java/hudson/DependencyRunner.java +++ b/core/src/main/java/hudson/DependencyRunner.java @@ -1,19 +1,19 @@ /* * The MIT License - * + * * Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi, * Brian Westrich, Jean-Baptiste Quenot - * + * * 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 @@ -22,6 +22,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson; import hudson.model.AbstractProject; @@ -41,7 +42,7 @@ import jenkins.model.Jenkins; public class DependencyRunner implements Runnable { private static final Logger LOGGER = Logger.getLogger(DependencyRunner.class.getName()); - + ProjectRunnable runnable; List polledProjects = new ArrayList<>(); @@ -72,11 +73,11 @@ public class DependencyRunner implements Runnable { } private void populate(Collection projectList) { - for (AbstractProject p : projectList) { + for (AbstractProject p : projectList) { if (polledProjects.contains(p)) { // Project will be readded at the queue, so that we always use // the longest path - LOGGER.fine("removing project " + p.getName() + " for re-add"); + LOGGER.fine("removing project " + p.getName() + " for re-add"); polledProjects.remove(p); } diff --git a/core/src/main/java/hudson/DescriptorExtensionList.java b/core/src/main/java/hudson/DescriptorExtensionList.java index 25f11917065092b21098cba36a6915a20b5d3c62..7c9fbbddccacc7860ac12208ceb5c948eb422390 100644 --- a/core/src/main/java/hudson/DescriptorExtensionList.java +++ b/core/src/main/java/hudson/DescriptorExtensionList.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson; import edu.umd.cs.findbugs.annotations.CheckForNull; @@ -71,8 +72,8 @@ public class DescriptorExtensionList, D extends Descrip * Creates a new instance. */ @SuppressWarnings({"unchecked", "rawtypes"}) - public static ,D extends Descriptor> - DescriptorExtensionList createDescriptorList(Jenkins jenkins, Class describableType) { + public static , D extends Descriptor> + DescriptorExtensionList createDescriptorList(Jenkins jenkins, Class describableType) { if (describableType == Publisher.class) { return (DescriptorExtensionList) new Publisher.DescriptorExtensionListImpl(jenkins); } @@ -84,9 +85,9 @@ public class DescriptorExtensionList, D extends Descrip * Use {@link #create(Jenkins, Class)} */ @Deprecated - public static ,D extends Descriptor> - DescriptorExtensionList createDescriptorList(Hudson hudson, Class describableType) { - return (DescriptorExtensionList)createDescriptorList((Jenkins)hudson,describableType); + public static , D extends Descriptor> + DescriptorExtensionList createDescriptorList(Hudson hudson, Class describableType) { + return (DescriptorExtensionList) createDescriptorList((Jenkins) hudson, describableType); } /** @@ -100,11 +101,11 @@ public class DescriptorExtensionList, D extends Descrip */ @Deprecated protected DescriptorExtensionList(Hudson hudson, Class describableType) { - this((Jenkins)hudson,describableType); + this((Jenkins) hudson, describableType); } protected DescriptorExtensionList(Jenkins jenkins, Class describableType) { - super(jenkins, (Class)Descriptor.class, (CopyOnWriteArrayList)getLegacyDescriptors(describableType)); + super(jenkins, (Class) Descriptor.class, (CopyOnWriteArrayList) getLegacyDescriptors(describableType)); this.describableType = describableType; } @@ -117,7 +118,7 @@ public class DescriptorExtensionList, D extends Descrip */ @Deprecated public D find(String fqcn) { - return Descriptor.find(this,fqcn); + return Descriptor.find(this, fqcn); } /** @@ -126,7 +127,7 @@ public class DescriptorExtensionList, D extends Descrip */ public D find(Class type) { for (D d : this) - if (d.clazz==type) + if (d.clazz == type) return d; return null; } @@ -141,10 +142,10 @@ public class DescriptorExtensionList, D extends Descrip */ @CheckForNull public T newInstanceFromRadioList(JSONObject config) throws FormException { - if(config.isNullObject()) + if (config.isNullObject()) return null; // none was selected int idx = config.getInt("value"); - return get(idx).newInstance(Stapler.getCurrentRequest(),config); + return get(idx).newInstance(Stapler.getCurrentRequest(), config); } /** @@ -171,7 +172,7 @@ public class DescriptorExtensionList, D extends Descrip */ public @CheckForNull D findByName(String id) { for (D d : this) - if(d.getId().equals(id)) + if (d.getId().equals(id)) return d; return null; } @@ -219,11 +220,11 @@ public class DescriptorExtensionList, D extends Descrip private List> _load(Iterable> set) { List> r = new ArrayList<>(); - for( ExtensionComponent c : set ) { + for (ExtensionComponent c : set) { Descriptor d = c.getInstance(); try { - if(d.getT()==describableType) - r.add((ExtensionComponent)c); + if (d.getT() == describableType) + r.add((ExtensionComponent) c); } catch (IllegalStateException e) { LOGGER.log(Level.SEVERE, d.getClass() + " doesn't extend Descriptor with a type parameter", e); // skip this one } @@ -253,8 +254,8 @@ public class DescriptorExtensionList, D extends Descrip return new Iterable() { @Override public Iterator iterator() { - return new AdaptedIterator,Descriptor>( - new FlattenIterator,CopyOnWriteArrayList>>(legacyDescriptors.values()) { + return new AdaptedIterator, Descriptor>( + new FlattenIterator, CopyOnWriteArrayList>>(legacyDescriptors.values()) { @Override protected Iterator> expand(CopyOnWriteArrayList> v) { return v.iterator(); diff --git a/core/src/main/java/hudson/EnvVars.java b/core/src/main/java/hudson/EnvVars.java index 673396061a6c32934676b7c908dd725cad926ca6..cce69ede9ee849f5df65504e2bd4892b7017417e 100644 --- a/core/src/main/java/hudson/EnvVars.java +++ b/core/src/main/java/hudson/EnvVars.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Red Hat, Inc. - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson; import edu.umd.cs.findbugs.annotations.CheckForNull; @@ -71,7 +72,7 @@ import jenkins.security.MasterToSlaveCallable; * * @author Kohsuke Kawaguchi */ -public class EnvVars extends TreeMap { +public class EnvVars extends TreeMap { private static final long serialVersionUID = 4320331661987259022L; private static Logger LOGGER = Logger.getLogger(EnvVars.class.getName()); /** @@ -84,7 +85,7 @@ public class EnvVars extends TreeMap { * So this property remembers that information. */ private Platform platform; - + /** * Gets the platform for which these env vars targeted. * @since 2.144 @@ -102,11 +103,12 @@ public class EnvVars extends TreeMap { public void setPlatform(@NonNull Platform platform) { this.platform = platform; } + public EnvVars() { super(String.CASE_INSENSITIVE_ORDER); } - public EnvVars(@NonNull Map m) { + public EnvVars(@NonNull Map m) { this(); putAll(m); @@ -121,7 +123,7 @@ public class EnvVars extends TreeMap { @SuppressWarnings("CopyConstructorMissesField") // does not set #platform, see its Javadoc public EnvVars(@NonNull EnvVars m) { // this constructor is so that in future we can get rid of the downcasting. - this((Map)m); + this((Map) m); } /** @@ -129,10 +131,10 @@ public class EnvVars extends TreeMap { */ public EnvVars(String... keyValuePairs) { this(); - if(keyValuePairs.length%2!=0) + if (keyValuePairs.length % 2 != 0) throw new IllegalArgumentException(Arrays.asList(keyValuePairs).toString()); - for( int i=0; i { * Handles {@code PATH+XYZ} notation. */ public void override(String key, String value) { - if(value==null || value.length()==0) { + if (value == null || value.length() == 0) { remove(key); return; } int idx = key.indexOf('+'); - if(idx>0) { - String realKey = key.substring(0,idx); + if (idx > 0) { + String realKey = key.substring(0, idx); String v = get(realKey); - if(v==null) v=value; + if (v == null) v = value; else { // we might be handling environment variables for a agent that can have different path separator // than the controller, so the following is an attempt to get it right. // it's still more error prone that I'd like. - char ch = platform==null ? File.pathSeparatorChar : platform.pathSeparator; - v=value+ch+v; + char ch = platform == null ? File.pathSeparatorChar : platform.pathSeparator; + v = value + ch + v; } - put(realKey,v); + put(realKey, v); return; } - put(key,value); + put(key, value); } /** @@ -171,18 +173,18 @@ public class EnvVars extends TreeMap { * See {@link #override(String, String)}. * @return this */ - public EnvVars overrideAll(Map all) { + public EnvVars overrideAll(Map all) { for (Map.Entry e : all.entrySet()) { - override(e.getKey(),e.getValue()); + override(e.getKey(), e.getValue()); } return this; } /** * Calculates the order to override variables. - * + * * Sort variables with topological sort with their reference graph. - * + * * This is package accessible for testing purpose. */ static class OverrideOrderCalculator { @@ -192,31 +194,31 @@ public class EnvVars extends TreeMap { private static class TraceResolver implements VariableResolver { private final Comparator comparator; public Set referredVariables; - + TraceResolver(Comparator comparator) { this.comparator = comparator; clear(); } - + public void clear() { referredVariables = new TreeSet<>(comparator); } - + @Override public String resolve(String name) { referredVariables.add(name); return ""; } } - + private static class VariableReferenceSorter extends CyclicGraphDetector { // map from a variable to a set of variables that variable refers. private final Map> refereeSetMap; - + VariableReferenceSorter(Map> refereeSetMap) { this.refereeSetMap = refereeSetMap; } - + @Override protected Iterable getEdges(String n) { // return variables referred from the variable. @@ -229,32 +231,32 @@ public class EnvVars extends TreeMap { } private final Comparator comparator; - + @NonNull private final EnvVars target; @NonNull - private final Map overrides; - + private final Map overrides; + private Map> refereeSetMap; private List orderedVariableNames; - - OverrideOrderCalculator(@NonNull EnvVars target, @NonNull Map overrides) { + + OverrideOrderCalculator(@NonNull EnvVars target, @NonNull Map overrides) { comparator = target.comparator(); this.target = target; this.overrides = overrides; scan(); } - + public List getOrderedVariableNames() { return orderedVariableNames; } - + // Cut the reference to the variable in a cycle. private void cutCycleAt(String referee, List cycle) { // cycle contains variables in referrer-to-referee order. // This should not be negative, for the first and last one is same. int refererIndex = cycle.lastIndexOf(referee) - 1; - + assert refererIndex >= 0; String referrer = cycle.get(refererIndex); boolean removed = refereeSetMap.get(referrer).remove(referee); @@ -262,7 +264,7 @@ public class EnvVars extends TreeMap { LOGGER.warning(String.format("Cyclic reference detected: %s", String.join(" -> ", cycle))); LOGGER.warning(String.format("Cut the reference %s -> %s", referrer, referee)); } - + // Cut the variable reference in a cycle. private void cutCycle(List cycle) { // if an existing variable is contained in that cycle, @@ -273,27 +275,27 @@ public class EnvVars extends TreeMap { // PATH1=/usr/local/bin:${PATH} // PATH=/opt/something/bin:${PATH1} // then consider reference PATH1 -> PATH can be ignored. - for (String referee: cycle) { + for (String referee : cycle) { if (target.containsKey(referee)) { cutCycleAt(referee, cycle); return; } } - + // if not, cut the reference to the first one. cutCycleAt(cycle.get(0), cycle); } - + /** * Scan all variables and list all referring variables. */ public void scan() { refereeSetMap = new TreeMap<>(comparator); List extendingVariableNames = new ArrayList<>(); - + TraceResolver resolver = new TraceResolver(comparator); - - for (Map.Entry entry: overrides.entrySet()) { + + for (Map.Entry entry : overrides.entrySet()) { if (entry.getKey().indexOf('+') > 0) { // XYZ+AAA variables should be always processed in last. extendingVariableNames.add(entry.getKey()); @@ -301,20 +303,20 @@ public class EnvVars extends TreeMap { } resolver.clear(); Util.replaceMacro(entry.getValue(), resolver); - + // Variables directly referred from the current scanning variable. Set refereeSet = resolver.referredVariables; // Ignore self reference. refereeSet.remove(entry.getKey()); refereeSetMap.put(entry.getKey(), refereeSet); } - + VariableReferenceSorter sorter; - while(true) { + while (true) { sorter = new VariableReferenceSorter(refereeSetMap); try { sorter.run(refereeSetMap.keySet()); - } catch(CycleDetectedException e) { + } catch (CycleDetectedException e) { // cyclic reference found. // cut the cycle and retry. @SuppressWarnings("unchecked") @@ -324,15 +326,15 @@ public class EnvVars extends TreeMap { } break; } - + // When A refers B, the last appearance of B always comes after // the last appearance of A. List reversedDuplicatedOrder = new ArrayList<>(sorter.getSorted()); Collections.reverse(reversedDuplicatedOrder); - + orderedVariableNames = new ArrayList<>(overrides.size()); - for(String key: reversedDuplicatedOrder) { - if(overrides.containsKey(key) && !orderedVariableNames.contains(key)) { + for (String key : reversedDuplicatedOrder) { + if (overrides.containsKey(key) && !orderedVariableNames.contains(key)) { orderedVariableNames.add(key); } } @@ -340,14 +342,14 @@ public class EnvVars extends TreeMap { orderedVariableNames.addAll(extendingVariableNames); } } - + /** * Overrides all values in the map by the given map. Expressions in values will be expanded. * See {@link #override(String, String)}. * @return {@code this} */ - public EnvVars overrideExpandingAll(@NonNull Map all) { + public EnvVars overrideExpandingAll(@NonNull Map all) { for (String key : new OverrideOrderCalculator(this, all).getOrderedVariableNames()) { override(key, expand(all.get(key))); } @@ -357,11 +359,11 @@ public class EnvVars extends TreeMap { /** * Resolves environment variables against each other. */ - public static void resolve(Map env) { - for (Map.Entry entry: env.entrySet()) { - entry.setValue(Util.replaceMacro(entry.getValue(), env)); - } - } + public static void resolve(Map env) { + for (Map.Entry entry : env.entrySet()) { + entry.setValue(Util.replaceMacro(entry.getValue(), env)); + } + } /** * Convenience message @@ -369,14 +371,14 @@ public class EnvVars extends TreeMap { **/ public String get(String key, String defaultValue) { String v = get(key); - if (v==null) v=defaultValue; + if (v == null) v = defaultValue; return v; } @Override public String put(String key, String value) { - if (value==null) throw new IllegalArgumentException("Null value not allowed as an environment variable: "+key); - return super.put(key,value); + if (value == null) throw new IllegalArgumentException("Null value not allowed as an environment variable: " + key); + return super.put(key, value); } /** @@ -384,8 +386,8 @@ public class EnvVars extends TreeMap { * @since 1.556 */ public void putIfNotNull(String key, String value) { - if (value!=null) - put(key,value); + if (value != null) + put(key, value); } /** @@ -396,14 +398,14 @@ public class EnvVars extends TreeMap { map.forEach(this::putIfNotNull); } - + /** * Takes a string that looks like "a=b" and adds that to this map. */ public void addLine(String line) { int sep = line.indexOf('='); - if(sep > 0) { - put(line.substring(0,sep),line.substring(sep+1)); + if (sep > 0) { + put(line.substring(0, sep), line.substring(sep + 1)); } } @@ -431,16 +433,17 @@ public class EnvVars extends TreeMap { * A fresh copy that can be owned and modified by the caller. */ public static EnvVars getRemote(VirtualChannel channel) throws IOException, InterruptedException { - if(channel==null) - return new EnvVars("N/A","N/A"); + if (channel == null) + return new EnvVars("N/A", "N/A"); return channel.call(new GetEnvVars()); } - private static final class GetEnvVars extends MasterToSlaveCallable { + private static final class GetEnvVars extends MasterToSlaveCallable { @Override public EnvVars call() { return new EnvVars(EnvVars.masterEnvVars); } + private static final long serialVersionUID = 1L; } @@ -456,12 +459,12 @@ public class EnvVars extends TreeMap { * If you access this field from agents, then this is the environment * variable of the agent. */ - public static final Map masterEnvVars = initMaster(); + public static final Map masterEnvVars = initMaster(); private static EnvVars initMaster() { EnvVars vars = new EnvVars(System.getenv()); vars.platform = Platform.current(); - if(Main.isUnitTest || Main.isDevelopmentMode) + if (Main.isUnitTest || Main.isDevelopmentMode) // if unit test is launched with maven debug switch, // we need to prevent forked Maven processes from seeing it, or else // they'll hang diff --git a/core/src/main/java/hudson/ExpressionFactory2.java b/core/src/main/java/hudson/ExpressionFactory2.java index e71202f4552b1e969ede165a1f47304e5e4a2a22..7fcec22e76047b2ce2ab9af2212e1aa7ac69b081 100644 --- a/core/src/main/java/hudson/ExpressionFactory2.java +++ b/core/src/main/java/hudson/ExpressionFactory2.java @@ -72,14 +72,14 @@ final class ExpressionFactory2 implements ExpressionFactory { public Object evaluate(JellyContext context) { try { CURRENT_CONTEXT.set(context); - JexlContext jexlContext = new JellyJexlContext( context ); + JexlContext jexlContext = new JellyJexlContext(context); return expression.evaluate(jexlContext); } catch (AccessDeniedException e) { // let the security exception pass through throw e; } catch (Exception e) { StaplerRequest currentRequest = Stapler.getCurrentRequest(); - LOGGER.log(Level.WARNING,"Caught exception evaluating: " + expression + " in " + (currentRequest != null ? currentRequest.getOriginalRequestURI() : "?") + ". Reason: " + e, e); + LOGGER.log(Level.WARNING, "Caught exception evaluating: " + expression + " in " + (currentRequest != null ? currentRequest.getOriginalRequestURI() : "?") + ". Reason: " + e, e); return null; } finally { CURRENT_CONTEXT.set(null); @@ -93,13 +93,13 @@ final class ExpressionFactory2 implements ExpressionFactory { private Map vars; JellyJexlContext(JellyContext context) { - this.vars = new JellyMap( context ); + this.vars = new JellyMap(context); } @Override public void setVars(Map vars) { this.vars.clear(); - this.vars.putAll( vars ); + this.vars.putAll(vars); } @Override @@ -119,7 +119,7 @@ final class ExpressionFactory2 implements ExpressionFactory { @Override public Object get(Object key) { - return context.getVariable( (String) key ); + return context.getVariable((String) key); } @Override diff --git a/core/src/main/java/hudson/Extension.java b/core/src/main/java/hudson/Extension.java index 0bcffcefbe29438775a93fbd7ffb475cdfbb0bfa..b240e37f87db14fe0df1cf1745ccedd15b0ecd86 100644 --- a/core/src/main/java/hudson/Extension.java +++ b/core/src/main/java/hudson/Extension.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson; import static java.lang.annotation.ElementType.FIELD; diff --git a/core/src/main/java/hudson/ExtensionComponent.java b/core/src/main/java/hudson/ExtensionComponent.java index e80eb8edc1d632522df15030022fdfb1209586ea..4ef48d08008d0cd7a74b9063d41fe7b6860f7584 100644 --- a/core/src/main/java/hudson/ExtensionComponent.java +++ b/core/src/main/java/hudson/ExtensionComponent.java @@ -50,11 +50,11 @@ public class ExtensionComponent implements Comparable> } public ExtensionComponent(T instance, Extension annotation) { - this(instance,annotation.ordinal()); + this(instance, annotation.ordinal()); } public ExtensionComponent(T instance) { - this(instance,0); + this(instance, 0); } /** @@ -79,7 +79,7 @@ public class ExtensionComponent implements Comparable> * For example, {@code component.isDescriptorOf(Builder.class)} */ public boolean isDescriptorOf(Class c) { - return instance instanceof Descriptor && ((Descriptor)instance).isSubTypeOf(c); + return instance instanceof Descriptor && ((Descriptor) instance).isSubTypeOf(c); } /** diff --git a/core/src/main/java/hudson/ExtensionFinder.java b/core/src/main/java/hudson/ExtensionFinder.java index 10ca19bef5016b7424e6c99f78375d03b1a61750..19c60bc9b9757396259acc3568ac6f717c41a3e0 100644 --- a/core/src/main/java/hudson/ExtensionFinder.java +++ b/core/src/main/java/hudson/ExtensionFinder.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson; import com.google.inject.AbstractModule; @@ -98,7 +99,7 @@ public abstract class ExtensionFinder implements ExtensionPoint { */ public boolean isRefreshable() { try { - return getClass().getMethod("refresh").getDeclaringClass()!=ExtensionFinder.class; + return getClass().getMethod("refresh").getDeclaringClass() != ExtensionFinder.class; } catch (NoSuchMethodException e) { return false; } @@ -153,7 +154,7 @@ public abstract class ExtensionFinder implements ExtensionPoint { } /** - * Performs class initializations without creating instances. + * Performs class initializations without creating instances. * * If two threads try to initialize classes in the opposite order, a dead lock will ensue, * and we can get into a similar situation with {@link ExtensionFinder}s. @@ -227,7 +228,7 @@ public abstract class ExtensionFinder implements ExtensionPoint { protected abstract boolean isOptional(T annotation); } - + /** * Discovers components via sezpoz but instantiates them by using Guice. */ @@ -246,15 +247,15 @@ public abstract class ExtensionFinder implements ExtensionPoint { * Sezpoz index we are currently using in {@link #container} (and its ancestors.) * Needed to compute delta. */ - private List> sezpozIndex; + private List> sezpozIndex; - private final Map annotations = new HashMap<>(); + private final Map annotations = new HashMap<>(); private final Sezpoz moduleFinder = new Sezpoz(); /** * Map from {@link GuiceExtensionAnnotation#annotationType} to {@link GuiceExtensionAnnotation} */ - private Map,GuiceExtensionAnnotation> extensionAnnotations = new HashMap<>(); + private Map, GuiceExtensionAnnotation> extensionAnnotations = new HashMap<>(); public GuiceFinder() { refreshExtensionAnnotations(); @@ -280,14 +281,14 @@ public abstract class ExtensionFinder implements ExtensionPoint { container = Guice.createInjector(modules); sezpozIndex = extensions.getLoadedIndex(); } catch (Throwable e) { - LOGGER.log(Level.SEVERE, "Failed to create Guice container from all the plugins",e); + LOGGER.log(Level.SEVERE, "Failed to create Guice container from all the plugins", e); // failing to load all bindings are disastrous, so recover by creating minimum that works // by just including the core container = Guice.createInjector(new SezpozModule(loadSezpozIndices(Jenkins.class.getClassLoader()))); } // expose Injector via lookup mechanism for interop with non-Guice clients - Jenkins.get().lookup.set(Injector.class,new ProxyInjector() { + Jenkins.get().lookup.set(Injector.class, new ProxyInjector() { @Override protected Injector resolve() { return getContainer(); @@ -298,12 +299,12 @@ public abstract class ExtensionFinder implements ExtensionPoint { private void refreshExtensionAnnotations() { for (ExtensionComponent ec : moduleFinder.find(GuiceExtensionAnnotation.class, Hudson.getInstance())) { GuiceExtensionAnnotation gea = ec.getInstance(); - extensionAnnotations.put(gea.annotationType,gea); + extensionAnnotations.put(gea.annotationType, gea); } } private List> loadSezpozIndices(ClassLoader classLoader) { - List> indices = new ArrayList<>(); + List> indices = new ArrayList<>(); for (GuiceExtensionAnnotation gea : extensionAnnotations.values()) { for (IndexItem indexItem : Index.load(gea.annotationType, Object.class, classLoader)) { indices.add(indexItem); @@ -330,7 +331,7 @@ public abstract class ExtensionFinder implements ExtensionPoint { // figure out newly discovered sezpoz components List> delta = new ArrayList<>(); for (Class annotationType : extensionAnnotations.keySet()) { - delta.addAll(Sezpoz.listDelta(annotationType,sezpozIndex)); + delta.addAll(Sezpoz.listDelta(annotationType, sezpozIndex)); } SezpozModule deltaExtensions = new SezpozModule(delta); @@ -357,19 +358,19 @@ public abstract class ExtensionFinder implements ExtensionPoint { } }; } catch (Throwable e) { - LOGGER.log(Level.SEVERE, "Failed to create Guice container from newly added plugins",e); + LOGGER.log(Level.SEVERE, "Failed to create Guice container from newly added plugins", e); throw new ExtensionRefreshException(e); } } - private Object instantiate(IndexItem item) { + private Object instantiate(IndexItem item) { try { return item.instance(); } catch (LinkageError | Exception e) { // sometimes the instantiation fails in an indirect classloading failure, // which results in a LinkageError LOGGER.log(isOptional(item.annotation()) ? Level.FINE : Level.WARNING, - "Failed to load "+item.className(), e); + "Failed to load " + item.className(), e); } return null; } @@ -388,7 +389,7 @@ public abstract class ExtensionFinder implements ExtensionPoint { public Collection> find(Class type, Hudson jenkins) { // the find method contract requires us to traverse all known components List> result = new ArrayList<>(); - for (Injector i=container; i!=null; i=i.getParent()) { + for (Injector i = container; i != null; i = i.getParent()) { _find(type, result, i); } return result; @@ -399,8 +400,8 @@ public abstract class ExtensionFinder implements ExtensionPoint { if (type.isAssignableFrom(e.getKey().getTypeLiteral().getRawType())) { Annotation a = annotations.get(e.getKey()); Object o = e.getValue().getProvider().get(); - if (o!=null) { - GuiceExtensionAnnotation gea = a!=null ? extensionAnnotations.get(a.annotationType()) : null; + if (o != null) { + GuiceExtensionAnnotation gea = a != null ? extensionAnnotations.get(a.annotationType()) : null; result.add(new ExtensionComponent<>(type.cast(o), gea != null ? gea.getOrdinal(a) : 0)); } } @@ -425,15 +426,17 @@ public abstract class ExtensionFinder implements ExtensionPoint { */ public static final Scope FAULT_TOLERANT_SCOPE = new FaultTolerantScope(true); private static final Scope QUIET_FAULT_TOLERANT_SCOPE = new FaultTolerantScope(false); - + private static final class FaultTolerantScope implements Scope { private final boolean verbose; + FaultTolerantScope(boolean verbose) { this.verbose = verbose; } + @Override public Provider scope(final Key key, final Provider unscoped) { - final Provider base = Scopes.SINGLETON.scope(key,unscoped); + final Provider base = Scopes.SINGLETON.scope(key, unscoped); return new Provider() { @Override public T get() { @@ -444,6 +447,7 @@ public abstract class ExtensionFinder implements ExtensionPoint { return null; } } + void error(Key key, Throwable x) { LOGGER.log(verbose ? Level.WARNING : Level.FINE, "Failed to instantiate " + key + "; skipping this component", x); } @@ -459,10 +463,10 @@ public abstract class ExtensionFinder implements ExtensionPoint { * so that we can take advantage of dependency injection. */ private class SezpozModule extends AbstractModule implements ProvisionListener { - private final List> index; - private final List> loadedIndex; + private final List> index; + private final List> loadedIndex; - SezpozModule(List> index) { + SezpozModule(List> index) { this.index = index; this.loadedIndex = new ArrayList<>(); } @@ -482,6 +486,7 @@ public abstract class ExtensionFinder implements ExtensionPoint { private void resolve(Class c) { resolve(c, new HashSet<>()); } + private void resolve(Class c, Set> encountered) { if (!encountered.add(c)) { return; @@ -503,7 +508,7 @@ public abstract class ExtensionFinder implements ExtensionPoint { } LOGGER.log(Level.FINER, "{0} looks OK", c); } catch (RuntimeException x) { - throw new LinkageError("Failed to resolve "+c, x); + throw new LinkageError("Failed to resolve " + c, x); } } @@ -513,26 +518,26 @@ public abstract class ExtensionFinder implements ExtensionPoint { bindListener(Matchers.any(), this); - for (final IndexItem item : index) { + for (final IndexItem item : index) { boolean optional = isOptional(item.annotation()); try { AnnotatedElement e = item.element(); Annotation a = item.annotation(); - if (!isActive(a,e)) continue; + if (!isActive(a, e)) continue; Scope scope = optional ? QUIET_FAULT_TOLERANT_SCOPE : FAULT_TOLERANT_SCOPE; if (e instanceof Class) { - Key key = Key.get((Class)e); - resolve((Class)e); - annotations.put(key,a); + Key key = Key.get((Class) e); + resolve((Class) e); + annotations.put(key, a); bind(key).in(scope); } else { Class extType; if (e instanceof Field) { - extType = ((Field)e).getType(); + extType = ((Field) e).getType(); } else if (e instanceof Method) { - extType = ((Method)e).getReturnType(); + extType = ((Method) e).getReturnType(); } else { throw new AssertionError(); } @@ -541,15 +546,15 @@ public abstract class ExtensionFinder implements ExtensionPoint { // make unique key, because Guice wants that. Key key = Key.get(extType, Names.named(item.className() + "." + item.memberName())); - annotations.put(key,a); + annotations.put(key, a); bind(key).toProvider(() -> instantiate(item)).in(scope); } loadedIndex.add(item); - } catch (Exception|LinkageError e) { + } catch (Exception | LinkageError e) { // sometimes the instantiation fails in an indirect classloading failure, // which results in a LinkageError LOGGER.log(optional ? Level.FINE : Level.WARNING, - "Failed to load "+item.className(), e); + "Failed to load " + item.className(), e); } } } @@ -623,7 +628,7 @@ public abstract class ExtensionFinder implements ExtensionPoint { */ public static final class Sezpoz extends ExtensionFinder { - private volatile List> indices; + private volatile List> indices; /** * Loads indices (ideally once but as few times as possible), then reuse them later. @@ -631,14 +636,14 @@ public abstract class ExtensionFinder implements ExtensionPoint { * {@link InitMilestone#PLUGINS_PREPARED} is attained, so this method is guaranteed to * see all the classes and indices. */ - private List> getIndices() { + private List> getIndices() { // this method cannot be synchronized because of a dead lock possibility in the following order of events: // 1. thread X can start listing indices, locking this object 'SZ' // 2. thread Y starts loading a class, locking a classloader 'CL' // 3. thread X needs to load a class, now blocked on CL // 4. thread Y decides to load extensions, now blocked on SZ. // 5. dead lock - if (indices==null) { + if (indices == null) { ClassLoader cl = Jenkins.get().getPluginManager().uberClassLoader; indices = Collections.unmodifiableList(StreamSupport.stream(Index.load(Extension.class, Object.class, cl).spliterator(), false).collect(Collectors.toList())); } @@ -653,28 +658,28 @@ public abstract class ExtensionFinder implements ExtensionPoint { */ @Override public synchronized ExtensionComponentSet refresh() { - final List> old = indices; - if (old==null) return ExtensionComponentSet.EMPTY; // we haven't loaded anything + final List> old = indices; + if (old == null) return ExtensionComponentSet.EMPTY; // we haven't loaded anything - final List> delta = listDelta(Extension.class,old); + final List> delta = listDelta(Extension.class, old); - List> r = new ArrayList<>(old); + List> r = new ArrayList<>(old); r.addAll(delta); indices = Collections.unmodifiableList(r); return new ExtensionComponentSet() { @Override public Collection> find(Class type) { - return _find(type,delta); + return _find(type, delta); } }; } - static List> listDelta(Class annotationType, List> old) { + static List> listDelta(Class annotationType, List> old) { // list up newly discovered components - final List> delta = new ArrayList<>(); + final List> delta = new ArrayList<>(); ClassLoader cl = Jenkins.get().getPluginManager().uberClassLoader; - for (IndexItem ii : Index.load(annotationType, Object.class, cl)) { + for (IndexItem ii : Index.load(annotationType, Object.class, cl)) { if (!old.contains(ii)) { delta.add(ii); } @@ -684,28 +689,28 @@ public abstract class ExtensionFinder implements ExtensionPoint { @Override public Collection> find(Class type, Hudson jenkins) { - return _find(type,getIndices()); + return _find(type, getIndices()); } /** * Finds all the matching {@link IndexItem}s that match the given type and instantiate them. */ - private Collection> _find(Class type, List> indices) { + private Collection> _find(Class type, List> indices) { List> result = new ArrayList<>(); - for (IndexItem item : indices) { + for (IndexItem item : indices) { try { Class extType = getClassFromIndex(item); - if(type.isAssignableFrom(extType)) { + if (type.isAssignableFrom(extType)) { Object instance = item.instance(); - if(instance!=null) - result.add(new ExtensionComponent<>(type.cast(instance),item.annotation())); + if (instance != null) + result.add(new ExtensionComponent<>(type.cast(instance), item.annotation())); } - } catch (LinkageError|Exception e) { + } catch (LinkageError | Exception e) { // sometimes the instantiation fails in an indirect classloading failure, // which results in a LinkageError - LOGGER.log(logLevel(item), "Failed to load "+item.className(), e); + LOGGER.log(logLevel(item), "Failed to load " + item.className(), e); } } @@ -714,7 +719,7 @@ public abstract class ExtensionFinder implements ExtensionPoint { @Override public void scout(Class extensionType, Hudson hudson) { - for (IndexItem item : getIndices()) { + for (IndexItem item : getIndices()) { try { // we might end up having multiple threads concurrently calling into element(), // but we can't synchronize this --- if we do, the one thread that's supposed to load a class @@ -722,9 +727,9 @@ public abstract class ExtensionFinder implements ExtensionPoint { // looking at the sezpoz code, it should be safe to do so Class extType = getClassFromIndex(item); // according to JDK-4993813 this is the only way to force class initialization - Class.forName(extType.getName(),true,extType.getClassLoader()); + Class.forName(extType.getName(), true, extType.getClassLoader()); } catch (Exception | LinkageError e) { - LOGGER.log(logLevel(item), "Failed to scout "+item.className(), e); + LOGGER.log(logLevel(item), "Failed to scout " + item.className(), e); } } } diff --git a/core/src/main/java/hudson/ExtensionList.java b/core/src/main/java/hudson/ExtensionList.java index 89098e86ea280a09e5efcf2188548629441993d9..7bae8ff5d83b1d2d92489b00f42bdc6ce16b84c9 100644 --- a/core/src/main/java/hudson/ExtensionList.java +++ b/core/src/main/java/hudson/ExtensionList.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson; import edu.umd.cs.findbugs.annotations.CheckForNull; @@ -62,7 +63,7 @@ import jenkins.util.io.OnMaster; * and {@link jenkins.model.Jenkins#getDescriptorList(Class)} to obtain the instances. * * @param - * Type of the extension point. This class holds instances of the subtypes of 'T'. + * Type of the extension point. This class holds instances of the subtypes of 'T'. * * @author Kohsuke Kawaguchi * @since 1.286 @@ -99,11 +100,11 @@ public class ExtensionList extends AbstractList implements OnMaster { */ @Deprecated protected ExtensionList(Hudson hudson, Class extensionType) { - this((Jenkins)hudson,extensionType); + this((Jenkins) hudson, extensionType); } protected ExtensionList(Jenkins jenkins, Class extensionType) { - this(jenkins,extensionType, new CopyOnWriteArrayList<>()); + this(jenkins, extensionType, new CopyOnWriteArrayList<>()); } /** @@ -112,7 +113,7 @@ public class ExtensionList extends AbstractList implements OnMaster { */ @Deprecated protected ExtensionList(Hudson hudson, Class extensionType, CopyOnWriteArrayList> legacyStore) { - this((Jenkins)hudson,extensionType,legacyStore); + this((Jenkins) hudson, extensionType, legacyStore); } /** @@ -120,10 +121,10 @@ public class ExtensionList extends AbstractList implements OnMaster { * @param legacyStore * Place to store manually registered instances. The version of the constructor that * omits this uses a new {@link Vector}, making the storage lifespan tied to the life of {@link ExtensionList}. - * If the manually registered instances are scoped to VM level, the caller should pass in a static list. + * If the manually registered instances are scoped to VM level, the caller should pass in a static list. */ protected ExtensionList(Jenkins jenkins, Class extensionType, CopyOnWriteArrayList> legacyStore) { - this.hudson = (Hudson)jenkins; + this.hudson = (Hudson) jenkins; this.jenkins = jenkins; this.extensionType = extensionType; this.legacyInstances = legacyStore; @@ -146,7 +147,7 @@ public class ExtensionList extends AbstractList implements OnMaster { */ public @CheckForNull U get(@NonNull Class type) { for (T ext : this) - if(ext.getClass()==type) + if (ext.getClass() == type) return type.cast(ext); return null; } @@ -154,21 +155,21 @@ public class ExtensionList extends AbstractList implements OnMaster { /** * Looks for the extension instance of the given type (subclasses excluded), * or throws an IllegalStateException. - * + * * Meant to simplify call inside @Extension annotated class to retrieve their own instance. */ public @NonNull U getInstance(@NonNull Class type) throws IllegalStateException { for (T ext : this) - if(ext.getClass()==type) + if (ext.getClass() == type) return type.cast(ext); - + throw new IllegalStateException("The class " + type.getName() + " was not found, potentially not yet loaded"); } @Override public @NonNull Iterator iterator() { - // we need to intercept mutation, so for now don't allow Iterator.remove - return new AdaptedIterator,T>(Iterators.readOnly(ensureLoaded().iterator())) { + // we need to intercept mutation, so for now don't allow Iterator.remove + return new AdaptedIterator, T>(Iterators.readOnly(ensureLoaded().iterator())) { @Override protected T adapt(ExtensionComponent item) { return item.getInstance(); @@ -187,7 +188,7 @@ public class ExtensionList extends AbstractList implements OnMaster { public T get(int index) { return ensureLoaded().get(index).getInstance(); } - + @Override public int size() { return ensureLoaded().size(); @@ -200,7 +201,7 @@ public class ExtensionList extends AbstractList implements OnMaster { return new AbstractList() { @Override public T get(int index) { - return ExtensionList.this.get(size()-index-1); + return ExtensionList.this.get(size() - index - 1); } @Override @@ -215,7 +216,7 @@ public class ExtensionList extends AbstractList implements OnMaster { try { return removeSync(o); } finally { - if(extensions!=null) { + if (extensions != null) { fireOnChangeListeners(); } } @@ -238,9 +239,9 @@ public class ExtensionList extends AbstractList implements OnMaster { private synchronized boolean removeSync(Object o) { boolean removed = removeComponent(legacyInstances, o); - if(extensions!=null) { + if (extensions != null) { List> r = new ArrayList<>(extensions); - removed |= removeComponent(r,o); + removed |= removeComponent(r, o); extensions = sort(r); } return removed; @@ -274,7 +275,7 @@ public class ExtensionList extends AbstractList implements OnMaster { try { return addSync(t); } finally { - if(extensions!=null) { + if (extensions != null) { fireOnChangeListeners(); } } @@ -283,7 +284,7 @@ public class ExtensionList extends AbstractList implements OnMaster { private synchronized boolean addSync(T t) { legacyInstances.add(new ExtensionComponent<>(t)); // if we've already filled extensions, add it - if(extensions!=null) { + if (extensions != null) { List> r = new ArrayList<>(extensions); r.add(new ExtensionComponent<>(t)); extensions = sort(r); @@ -309,13 +310,13 @@ public class ExtensionList extends AbstractList implements OnMaster { } private List> ensureLoaded() { - if(extensions!=null) + if (extensions != null) return extensions; // already loaded if (jenkins == null || jenkins.getInitLevel().compareTo(InitMilestone.PLUGINS_PREPARED) < 0) return legacyInstances; // can't perform the auto discovery until all plugins are loaded, so just make the legacy instances visible synchronized (getLoadLock()) { - if(extensions==null) { + if (extensions == null) { List> r = load(); r.addAll(legacyInstances); extensions = sort(r); @@ -328,7 +329,7 @@ public class ExtensionList extends AbstractList implements OnMaster { * Chooses the object that locks the loading of the extension instances. */ protected Object getLoadLock() { - return Objects.requireNonNull(jenkins).lookup.setIfNull(Lock.class,new Lock()); + return Objects.requireNonNull(jenkins).lookup.setIfNull(Lock.class, new Lock()); } /** @@ -338,7 +339,7 @@ public class ExtensionList extends AbstractList implements OnMaster { public void refresh(ExtensionComponentSet delta) { boolean fireOnChangeListeners = false; synchronized (getLoadLock()) { - if (extensions==null) + if (extensions == null) return; // not yet loaded. when we load it, we'll load everything visible by then, so no work needed Collection> found = load(delta); @@ -410,12 +411,12 @@ public class ExtensionList extends AbstractList implements OnMaster { */ @Deprecated public static ExtensionList create(Hudson hudson, Class type) { - return create((Jenkins)hudson,type); + return create((Jenkins) hudson, type); } @SuppressWarnings({"unchecked", "rawtypes"}) public static ExtensionList create(Jenkins jenkins, Class type) { - if(type.getAnnotation(LegacyInstancesAreScopedToHudson.class)!=null) + if (type.getAnnotation(LegacyInstancesAreScopedToHudson.class) != null) return new ExtensionList<>(jenkins, type); else { return new ExtensionList(jenkins, type, staticLegacyInstances.computeIfAbsent(type, key -> new CopyOnWriteArrayList())); diff --git a/core/src/main/java/hudson/ExtensionListListener.java b/core/src/main/java/hudson/ExtensionListListener.java index 6a29da2d465d61028f72719cc4329258c1401cd9..af3c0e18b7f480d5e96988958d016589aee56530 100644 --- a/core/src/main/java/hudson/ExtensionListListener.java +++ b/core/src/main/java/hudson/ExtensionListListener.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson; /** diff --git a/core/src/main/java/hudson/ExtensionListView.java b/core/src/main/java/hudson/ExtensionListView.java index 3655085bb95139b902a9f8c4f7ed5f9ab698ea77..0127752e46bd181934cce393260feec74db167f8 100644 --- a/core/src/main/java/hudson/ExtensionListView.java +++ b/core/src/main/java/hudson/ExtensionListView.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson; import hudson.tasks.UserNameResolver; diff --git a/core/src/main/java/hudson/ExtensionPoint.java b/core/src/main/java/hudson/ExtensionPoint.java index 426aa52b05a31e93e91882d503a7bcb31cccf9c5..e04581798fc627be8af430d624108afae198d6e4 100644 --- a/core/src/main/java/hudson/ExtensionPoint.java +++ b/core/src/main/java/hudson/ExtensionPoint.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson; import static java.lang.annotation.ElementType.TYPE; diff --git a/core/src/main/java/hudson/FeedAdapter.java b/core/src/main/java/hudson/FeedAdapter.java index 981c5cfe8816f3383b6997ecccce78ff5ef69b6a..632001ae360aed946e489fc5a385e3ee84f61319 100644 --- a/core/src/main/java/hudson/FeedAdapter.java +++ b/core/src/main/java/hudson/FeedAdapter.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson; import java.util.Calendar; diff --git a/core/src/main/java/hudson/FilePath.java b/core/src/main/java/hudson/FilePath.java index a3eb22406c32ca1bbbf7d7aa4c559ddbfb91cd4b..ca205d353b4e052e28e6ce411b1605a56918e250 100644 --- a/core/src/main/java/hudson/FilePath.java +++ b/core/src/main/java/hudson/FilePath.java @@ -23,6 +23,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson; import static hudson.FilePath.TarCompression.GZIP; @@ -278,14 +279,14 @@ public final class FilePath implements SerializableOnlyOverRemoting { } private String resolvePathIfRelative(@NonNull FilePath base, @NonNull String rel) { - if(isAbsolute(rel)) return rel; - if(base.isUnix()) { + if (isAbsolute(rel)) return rel; + if (base.isUnix()) { // shouldn't need this replace, but better safe than sorry - return base.remote+'/'+rel.replace('\\','/'); + return base.remote + '/' + rel.replace('\\', '/'); } else { // need this replace, see Slave.getWorkspaceFor and AbstractItem.getFullName, nested jobs on Windows // agents will always have a rel containing at least one '/' character. JENKINS-13649 - return base.remote+'\\'+rel.replace('/','\\'); + return base.remote + '\\' + rel.replace('/', '\\'); } } @@ -327,7 +328,7 @@ public final class FilePath implements SerializableOnlyOverRemoting { while (++i < end && ((c = path.charAt(i)) == '/' || c == '\\')) ; // Add token for separator unless we reached the end - if (i < end) tokens.add(path.substring(s, s+1)); + if (i < end) tokens.add(path.substring(s, s + 1)); s = i; } } @@ -350,7 +351,7 @@ public final class FilePath implements SerializableOnlyOverRemoting { // Normalize: remove something/.. plus separator before/after i -= 2; for (int j = 0; j < 3; j++) tokens.remove(i); - if (i > 0) tokens.remove(i-1); + if (i > 0) tokens.remove(i - 1); else if (tokens.size() > 0) tokens.remove(0); } } else @@ -367,14 +368,14 @@ public final class FilePath implements SerializableOnlyOverRemoting { */ boolean isUnix() { // if the path represents a local path, there' no need to guess. - if(!isRemote()) - return File.pathSeparatorChar!=';'; + if (!isRemote()) + return File.pathSeparatorChar != ';'; // note that we can't use the usual File.pathSeparator and etc., as the OS of // the machine where this code runs and the OS that this FilePath refers to may be different. // Windows absolute path is 'X:\...', so this is usually a good indication of Windows path - if(remote.length()>3 && remote.charAt(1)==':' && remote.charAt(2)=='\\') + if (remote.length() > 3 && remote.charAt(1) == ':' && remote.charAt(2) == '\\') return false; // Windows can handle '/' as a path separator but Unix can't, // so err on Unix side @@ -403,7 +404,7 @@ public final class FilePath implements SerializableOnlyOverRemoting { * Creates a zip file from this directory or a file and sends that to the given output stream. */ public void zip(OutputStream os) throws IOException, InterruptedException { - zip(os,(FileFilter)null); + zip(os, (FileFilter) null); } public void zip(FilePath dst) throws IOException, InterruptedException { @@ -422,7 +423,7 @@ public final class FilePath implements SerializableOnlyOverRemoting { * @since 1.315 */ public void zip(OutputStream os, FileFilter filter) throws IOException, InterruptedException { - archive(ArchiverFactory.ZIP,os,filter); + archive(ArchiverFactory.ZIP, os, filter); } /** @@ -438,7 +439,7 @@ public final class FilePath implements SerializableOnlyOverRemoting { */ @Deprecated public void createZipArchive(OutputStream os, final String glob) throws IOException, InterruptedException { - archive(ArchiverFactory.ZIP,os,glob); + archive(ArchiverFactory.ZIP, os, glob); } /** @@ -451,7 +452,7 @@ public final class FilePath implements SerializableOnlyOverRemoting { * @since 1.315 */ public void zip(OutputStream os, final String glob) throws IOException, InterruptedException { - archive(ArchiverFactory.ZIP,os,glob); + archive(ArchiverFactory.ZIP, os, glob); } /** @@ -514,6 +515,7 @@ public final class FilePath implements SerializableOnlyOverRemoting { final OutputStream out = channel != null ? new RemoteOutputStream(os) : os; return act(new Archive(factory, out, scanner, verificationRoot, noFollowLinks)); } + private static class Archive extends MasterToSlaveFileCallable { private final ArchiverFactory factory; private final OutputStream out; @@ -528,6 +530,7 @@ public final class FilePath implements SerializableOnlyOverRemoting { this.verificationRoot = verificationRoot; this.noFollowLinks = noFollowLinks; } + @Override public Integer invoke(File f, VirtualChannel channel) throws IOException { Archiver a = factory.create(out); @@ -543,11 +546,11 @@ public final class FilePath implements SerializableOnlyOverRemoting { } public int archive(final ArchiverFactory factory, OutputStream os, final FileFilter filter) throws IOException, InterruptedException { - return archive(factory,os,new DirScanner.Filter(filter)); + return archive(factory, os, new DirScanner.Filter(filter)); } public int archive(final ArchiverFactory factory, OutputStream os, final String glob) throws IOException, InterruptedException { - return archive(factory,os,new DirScanner.Glob(glob,null)); + return archive(factory, os, new DirScanner.Glob(glob, null)); } /** @@ -560,25 +563,30 @@ public final class FilePath implements SerializableOnlyOverRemoting { */ public void unzip(final FilePath target) throws IOException, InterruptedException { // TODO: post release, re-unite two branches by introducing FileStreamCallable that resolves InputStream - if (channel != target.channel) {// local -> remote or remote->local + if (channel != target.channel) { // local -> remote or remote->local final RemoteInputStream in = new RemoteInputStream(read(), Flag.GREEDY); target.act(new UnzipRemote(in)); - } else {// local -> local or remote->remote + } else { // local -> local or remote->remote target.act(new UnzipLocal(this)); } } + private static class UnzipRemote extends MasterToSlaveFileCallable { private final RemoteInputStream in; + UnzipRemote(RemoteInputStream in) { this.in = in; } + @Override public Void invoke(File dir, VirtualChannel channel) throws IOException, InterruptedException { unzip(dir, in); return null; } + private static final long serialVersionUID = 1L; } + private static class UnzipLocal extends MasterToSlaveFileCallable { private final FilePath filePath; @@ -595,6 +603,7 @@ public final class FilePath implements SerializableOnlyOverRemoting { unzip(dir, new File(this.filePath.getRemote())); // shortcut to local file return null; } + private static final long serialVersionUID = 1L; } @@ -611,29 +620,34 @@ public final class FilePath implements SerializableOnlyOverRemoting { public void untar(final FilePath target, final TarCompression compression) throws IOException, InterruptedException { final FilePath source = FilePath.this; // TODO: post release, re-unite two branches by introducing FileStreamCallable that resolves InputStream - if (source.channel != target.channel) {// local -> remote or remote->local + if (source.channel != target.channel) { // local -> remote or remote->local final RemoteInputStream in = new RemoteInputStream(source.read(), Flag.GREEDY); target.act(new UntarRemote(source.getName(), compression, in)); - } else {// local -> local or remote->remote + } else { // local -> local or remote->remote target.act(new UntarLocal(source, compression)); } } + private static class UntarRemote extends MasterToSlaveFileCallable { private final TarCompression compression; private final RemoteInputStream in; private final String name; + UntarRemote(String name, TarCompression compression, RemoteInputStream in) { this.compression = compression; this.in = in; this.name = name; } + @Override public Void invoke(File dir, VirtualChannel channel) throws IOException, InterruptedException { readFromTar(name, dir, compression.extract(in)); return null; } + private static final long serialVersionUID = 1L; } + private static class UntarLocal extends MasterToSlaveFileCallable { private final TarCompression compression; private final FilePath filePath; @@ -642,11 +656,13 @@ public final class FilePath implements SerializableOnlyOverRemoting { this.filePath = source; this.compression = compression; } + @Override public Void invoke(File dir, VirtualChannel channel) throws IOException, InterruptedException { readFromTar(this.filePath.getName(), dir, compression.extract(this.filePath.read())); return null; } + private static final long serialVersionUID = 1L; } @@ -662,16 +678,20 @@ public final class FilePath implements SerializableOnlyOverRemoting { final InputStream in = new RemoteInputStream(_in, Flag.GREEDY); act(new UnzipFrom(in)); } + private static class UnzipFrom extends MasterToSlaveFileCallable { private final InputStream in; + UnzipFrom(InputStream in) { this.in = in; } + @Override public Void invoke(File dir, VirtualChannel channel) throws IOException { unzip(dir, in); return null; } + private static final long serialVersionUID = 1L; } @@ -680,7 +700,7 @@ public final class FilePath implements SerializableOnlyOverRemoting { try { // TODO why does this not simply use ZipInputStream? IOUtils.copy(in, tmpFile); - unzip(dir,tmpFile); + unzip(dir, tmpFile); } finally { Files.delete(Util.fileToPath(tmpFile)); @@ -713,7 +733,7 @@ public final class FilePath implements SerializableOnlyOverRemoting { try { FilePath target = new FilePath(f); int mode = e.getUnixMode(); - if (mode!=0) // Ant returns 0 if the archive doesn't record the access mode + if (mode != 0) // Ant returns 0 if the archive doesn't record the access mode target.chmod(mode); } catch (InterruptedException ex) { LOGGER.log(Level.WARNING, "unable to set permissions", ex); @@ -732,8 +752,10 @@ public final class FilePath implements SerializableOnlyOverRemoting { public FilePath absolutize() throws IOException, InterruptedException { return new FilePath(channel, act(new Absolutize())); } + private static class Absolutize extends MasterToSlaveFileCallable { private static final long serialVersionUID = 1L; + @Override public String invoke(File f, VirtualChannel channel) throws IOException { return f.getAbsolutePath(); @@ -744,6 +766,7 @@ public final class FilePath implements SerializableOnlyOverRemoting { public boolean hasSymlink(FilePath verificationRoot, boolean noFollowLinks) throws IOException, InterruptedException { return act(new HasSymlink(verificationRoot == null ? null : verificationRoot.remote, noFollowLinks)); } + private static class HasSymlink extends MasterToSlaveFileCallable { private static final long serialVersionUID = 1L; private final String verificationRoot; @@ -779,6 +802,7 @@ public final class FilePath implements SerializableOnlyOverRemoting { public boolean accept(File file) { return isSymlink(file, verificationRoot, noFollowLinks); } + private static final long serialVersionUID = 1L; } @@ -794,14 +818,18 @@ public final class FilePath implements SerializableOnlyOverRemoting { public void symlinkTo(final String target, final TaskListener listener) throws IOException, InterruptedException { act(new SymlinkTo(target, listener)); } + private static class SymlinkTo extends MasterToSlaveFileCallable { private final String target; private final TaskListener listener; + SymlinkTo(String target, TaskListener listener) { this.target = target; this.listener = listener; } + private static final long serialVersionUID = 1L; + @Override public Void invoke(File f, VirtualChannel channel) throws IOException, InterruptedException { Util.createSymlink(f.getParentFile(), target, f.getName(), listener); @@ -819,8 +847,10 @@ public final class FilePath implements SerializableOnlyOverRemoting { public String readLink() throws IOException, InterruptedException { return act(new ReadLink()); } + private static class ReadLink extends MasterToSlaveFileCallable { private static final long serialVersionUID = 1L; + @Override public String invoke(File f, VirtualChannel channel) throws IOException, InterruptedException { return Util.resolveSymlink(f); @@ -853,6 +883,7 @@ public final class FilePath implements SerializableOnlyOverRemoting { public InputStream extract(InputStream in) { return new BufferedInputStream(in); } + @Override public OutputStream compress(OutputStream out) { return new BufferedOutputStream(out); @@ -861,15 +892,16 @@ public final class FilePath implements SerializableOnlyOverRemoting { GZIP { @Override public InputStream extract(InputStream _in) throws IOException { - HeadBufferingStream in = new HeadBufferingStream(_in,SIDE_BUFFER_SIZE); + HeadBufferingStream in = new HeadBufferingStream(_in, SIDE_BUFFER_SIZE); try { return new GZIPInputStream(in, 8192, true); } catch (IOException e) { // various people reported "java.io.IOException: Not in GZIP format" here, so diagnose this problem better in.fillSide(); - throw new IOException(e.getMessage()+"\nstream="+Util.toHexString(in.getSideBuffer()),e); + throw new IOException(e.getMessage() + "\nstream=" + Util.toHexString(in.getSideBuffer()), e); } } + @Override public OutputStream compress(OutputStream out) throws IOException { return new GZIPOutputStream(new BufferedOutputStream(out)); @@ -877,6 +909,7 @@ public final class FilePath implements SerializableOnlyOverRemoting { }; public abstract InputStream extract(InputStream in) throws IOException; + public abstract OutputStream compress(OutputStream in) throws IOException; } @@ -897,18 +930,22 @@ public final class FilePath implements SerializableOnlyOverRemoting { _in.close(); } } + private static class UntarFrom extends MasterToSlaveFileCallable { private final TarCompression compression; private final InputStream in; + UntarFrom(TarCompression compression, InputStream in) { this.compression = compression; this.in = in; } + @Override public Void invoke(File dir, VirtualChannel channel) throws IOException { - readFromTar("input stream",dir, compression.extract(in)); + readFromTar("input stream", dir, compression.extract(in)); return null; } + private static final long serialVersionUID = 1L; } @@ -994,7 +1031,7 @@ public final class FilePath implements SerializableOnlyOverRemoting { long sourceTimestamp = con.getLastModified(); - if(this.exists()) { + if (this.exists()) { if (lastModified != 0 && sourceTimestamp == lastModified) return false; // already up to date this.deleteContents(); @@ -1019,27 +1056,29 @@ public final class FilePath implements SerializableOnlyOverRemoting { InputStream in = archive.getProtocol().startsWith("http") ? ProxyConfiguration.getInputStream(archive) : con.getInputStream(); CountingInputStream cis = new CountingInputStream(in); try { - if(archive.toExternalForm().endsWith(".zip")) + if (archive.toExternalForm().endsWith(".zip")) unzipFrom(cis); else - untarFrom(cis,GZIP); + untarFrom(cis, GZIP); } catch (IOException e) { throw new IOException(String.format("Failed to unpack %s (%d bytes read of total %d)", - archive,cis.getByteCount(),con.getContentLength()),e); + archive, cis.getByteCount(), con.getContentLength()), e); } timestamp.touch(sourceTimestamp); return true; } catch (IOException e) { - throw new IOException("Failed to install "+archive+" to "+remote,e); + throw new IOException("Failed to install " + archive + " to " + remote, e); } } // this reads from arbitrary URL private static final class Unpack extends MasterToSlaveFileCallable { private final URL archive; + Unpack(URL archive) { this.archive = archive; } + @Override public Void invoke(File dir, VirtualChannel channel) throws IOException, InterruptedException { try (InputStream in = archive.openStream()) { CountingInputStream cis = new CountingInputStream(in); @@ -1094,7 +1133,7 @@ public final class FilePath implements SerializableOnlyOverRemoting { * Place the data from {@link FileItem} into the file location specified by this {@link FilePath} object. */ public void copyFrom(FileItem file) throws IOException, InterruptedException { - if(channel==null) { + if (channel == null) { try { file.write(new File(remote)); } catch (IOException e) { @@ -1105,7 +1144,7 @@ public final class FilePath implements SerializableOnlyOverRemoting { } else { try (InputStream i = file.getInputStream(); OutputStream o = write()) { - org.apache.commons.io.IOUtils.copy(i,o); + org.apache.commons.io.IOUtils.copy(i, o); } } } @@ -1142,20 +1181,20 @@ public final class FilePath implements SerializableOnlyOverRemoting { * so that one can perform local file operations. */ public T act(final FileCallable callable) throws IOException, InterruptedException { - return act(callable,callable.getClass().getClassLoader()); + return act(callable, callable.getClass().getClassLoader()); } private T act(final FileCallable callable, ClassLoader cl) throws IOException, InterruptedException { - if(channel!=null) { + if (channel != null) { // run this on a remote system try { - DelegatingCallable wrapper = new FileCallableWrapper<>(callable, cl, this); + DelegatingCallable wrapper = new FileCallableWrapper<>(callable, cl, this); for (FileCallableWrapperFactory factory : ExtensionList.lookup(FileCallableWrapperFactory.class)) { wrapper = factory.wrap(wrapper); } return channel.call(wrapper); } catch (TunneledInterruptedException e) { - throw (InterruptedException)new InterruptedException(e.getMessage()).initCause(e); + throw (InterruptedException) new InterruptedException(e.getMessage()).initCause(e); } } else { // the file is on the local machine. @@ -1174,7 +1213,7 @@ public final class FilePath implements SerializableOnlyOverRemoting { */ public abstract static class FileCallableWrapperFactory implements ExtensionPoint { - public abstract DelegatingCallable wrap(DelegatingCallable callable); + public abstract DelegatingCallable wrap(DelegatingCallable callable); } @@ -1225,15 +1264,15 @@ public final class FilePath implements SerializableOnlyOverRemoting { */ public Future actAsync(final FileCallable callable) throws IOException, InterruptedException { try { - DelegatingCallable wrapper = new FileCallableWrapper<>(callable, this); + DelegatingCallable wrapper = new FileCallableWrapper<>(callable, this); for (FileCallableWrapperFactory factory : ExtensionList.lookup(FileCallableWrapperFactory.class)) { wrapper = factory.wrap(wrapper); } - return (channel!=null ? channel : localChannel) + return (channel != null ? channel : localChannel) .callAsync(wrapper); } catch (IOException e) { // wrap it into a new IOException so that we get the caller's stack trace as well. - throw new IOException("remote file operation failed",e); + throw new IOException("remote file operation failed", e); } } @@ -1241,8 +1280,8 @@ public final class FilePath implements SerializableOnlyOverRemoting { * Executes some program on the machine that this {@link FilePath} exists, * so that one can perform local file operations. */ - public V act(Callable callable) throws IOException, InterruptedException, E { - if(channel!=null) { + public V act(Callable callable) throws IOException, InterruptedException, E { + if (channel != null) { // run this on a remote system return channel.call(callable); } else { @@ -1258,20 +1297,23 @@ public final class FilePath implements SerializableOnlyOverRemoting { * * @since 1.522 */ - public Callable asCallableWith(final FileCallable task) { + public Callable asCallableWith(final FileCallable task) { return new CallableWith<>(task); } + private class CallableWith implements Callable { private final FileCallable task; + CallableWith(FileCallable task) { this.task = task; } + @Override public V call() throws IOException { try { return act(task); } catch (InterruptedException e) { - throw (IOException)new InterruptedIOException().initCause(e); + throw (IOException) new InterruptedIOException().initCause(e); } } @@ -1290,8 +1332,10 @@ public final class FilePath implements SerializableOnlyOverRemoting { public URI toURI() throws IOException, InterruptedException { return act(new ToURI()); } + private static class ToURI extends MasterToSlaveFileCallable { private static final long serialVersionUID = 1L; + @Override public URI invoke(File f, VirtualChannel channel) { return f.toURI(); @@ -1316,7 +1360,7 @@ public final class FilePath implements SerializableOnlyOverRemoting { Jenkins j = Jenkins.getInstanceOrNull(); if (j != null) { for (Computer c : j.getComputers()) { - if (getChannel()==c.getChannel()) { + if (getChannel() == c.getChannel()) { return c; } } @@ -1332,11 +1376,13 @@ public final class FilePath implements SerializableOnlyOverRemoting { throw new IOException("Failed to mkdirs: " + remote); } } + private static class Mkdirs extends MasterToSlaveFileCallable { private static final long serialVersionUID = 1L; + @Override public Boolean invoke(File f, VirtualChannel channel) throws IOException, InterruptedException { - if(mkdirs(f) || f.exists()) + if (mkdirs(f) || f.exists()) return true; // OK // following Ant task to avoid possible race condition. @@ -1390,8 +1436,10 @@ public final class FilePath implements SerializableOnlyOverRemoting { public void deleteRecursive() throws IOException, InterruptedException { act(new DeleteRecursive()); } + private static class DeleteRecursive extends MasterToSlaveFileCallable { private static final long serialVersionUID = 1L; + @Override public Void invoke(File f, VirtualChannel channel) throws IOException { Util.deleteRecursive(fileToPath(f), path -> path.toFile()); @@ -1405,8 +1453,10 @@ public final class FilePath implements SerializableOnlyOverRemoting { public void deleteContents() throws IOException, InterruptedException { act(new DeleteContents()); } + private static class DeleteContents extends MasterToSlaveFileCallable { private static final long serialVersionUID = 1L; + @Override public Void invoke(File f, VirtualChannel channel) throws IOException { Util.deleteContentsRecursive(fileToPath(f), path -> path.toFile()); @@ -1422,28 +1472,29 @@ public final class FilePath implements SerializableOnlyOverRemoting { public String getBaseName() { String n = getName(); int idx = n.lastIndexOf('.'); - if (idx<0) return n; - return n.substring(0,idx); + if (idx < 0) return n; + return n.substring(0, idx); } /** * Gets just the file name portion without directories. * * For example, "foo.txt" for "../abc/foo.txt" */ + public String getName() { String r = remote; - if(r.endsWith("\\") || r.endsWith("/")) - r = r.substring(0,r.length()-1); + if (r.endsWith("\\") || r.endsWith("/")) + r = r.substring(0, r.length() - 1); - int len = r.length()-1; - while(len>=0) { + int len = r.length() - 1; + while (len >= 0) { char ch = r.charAt(len); - if(ch=='\\' || ch=='/') + if (ch == '\\' || ch == '/') break; len--; } - return r.substring(len+1); + return r.substring(len + 1); } /** @@ -1460,7 +1511,7 @@ public final class FilePath implements SerializableOnlyOverRemoting { * Returns a {@link FilePath} by adding the given suffix to this path name. */ public FilePath withSuffix(String suffix) { - return new FilePath(channel,remote+suffix); + return new FilePath(channel, remote + suffix); } /** @@ -1469,7 +1520,7 @@ public final class FilePath implements SerializableOnlyOverRemoting { * @return a file on the same channel */ public @NonNull FilePath child(String relOrAbsolute) { - return new FilePath(this,relOrAbsolute); + return new FilePath(this, relOrAbsolute); } /** @@ -1481,11 +1532,11 @@ public final class FilePath implements SerializableOnlyOverRemoting { int i = remote.length() - 2; for (; i >= 0; i--) { char ch = remote.charAt(i); - if(ch=='\\' || ch=='/') + if (ch == '\\' || ch == '/') break; } - return i >= 0 ? new FilePath( channel, remote.substring(0,i+1) ) : null; + return i >= 0 ? new FilePath(channel, remote.substring(0, i + 1)) : null; } /** @@ -1505,17 +1556,21 @@ public final class FilePath implements SerializableOnlyOverRemoting { try { return new FilePath(this, act(new CreateTempFile(prefix, suffix))); } catch (IOException e) { - throw new IOException("Failed to create a temp file on "+remote,e); + throw new IOException("Failed to create a temp file on " + remote, e); } } + private static class CreateTempFile extends MasterToSlaveFileCallable { private final String prefix; private final String suffix; + CreateTempFile(String prefix, String suffix) { this.prefix = prefix; this.suffix = suffix; } + private static final long serialVersionUID = 1L; + @Override public String invoke(File dir, VirtualChannel channel) throws IOException { File f = File.createTempFile(prefix, suffix, dir); @@ -1540,7 +1595,7 @@ public final class FilePath implements SerializableOnlyOverRemoting { * @see File#createTempFile(String, String) */ public FilePath createTextTempFile(final String prefix, final String suffix, final String contents) throws IOException, InterruptedException { - return createTextTempFile(prefix,suffix,contents,true); + return createTextTempFile(prefix, suffix, contents, true); } /** @@ -1569,24 +1624,27 @@ public final class FilePath implements SerializableOnlyOverRemoting { try { return new FilePath(channel, act(new CreateTextTempFile(inThisDirectory, prefix, suffix, contents))); } catch (IOException e) { - throw new IOException("Failed to create a temp file on "+remote,e); + throw new IOException("Failed to create a temp file on " + remote, e); } } + private static class CreateTextTempFile extends MasterToSlaveFileCallable { private static final long serialVersionUID = 1L; private final boolean inThisDirectory; private final String prefix; private final String suffix; private final String contents; + CreateTextTempFile(boolean inThisDirectory, String prefix, String suffix, String contents) { this.inThisDirectory = inThisDirectory; this.prefix = prefix; this.suffix = suffix; this.contents = contents; } + @Override public String invoke(File dir, VirtualChannel channel) throws IOException { - if(!inThisDirectory) + if (!inThisDirectory) dir = new File(System.getProperty("java.io.tmpdir")); else mkdirs(dir); @@ -1595,7 +1653,7 @@ public final class FilePath implements SerializableOnlyOverRemoting { try { f = File.createTempFile(prefix, suffix, dir); } catch (IOException e) { - throw new IOException("Failed to create a temporary directory in "+dir,e); + throw new IOException("Failed to create a temporary directory in " + dir, e); } try (Writer w = new FileWriter(f)) { @@ -1631,15 +1689,19 @@ public final class FilePath implements SerializableOnlyOverRemoting { String name = String.join(".", s); return new FilePath(this, act(new CreateTempDir(name))); } catch (IOException e) { - throw new IOException("Failed to create a temp directory on "+remote,e); + throw new IOException("Failed to create a temp directory on " + remote, e); } } + private static class CreateTempDir extends MasterToSlaveFileCallable { private final String name; + CreateTempDir(String name) { this.name = name; } + private static final long serialVersionUID = 1L; + @Override public String invoke(File dir, VirtualChannel channel) throws IOException { @@ -1669,8 +1731,10 @@ public final class FilePath implements SerializableOnlyOverRemoting { act(new Delete()); return true; } + private static class Delete extends MasterToSlaveFileCallable { private static final long serialVersionUID = 1L; + @Override public Void invoke(File f, VirtualChannel channel) throws IOException { Util.deleteFile(f); @@ -1684,8 +1748,10 @@ public final class FilePath implements SerializableOnlyOverRemoting { public boolean exists() throws IOException, InterruptedException { return act(new Exists()); } + private static class Exists extends MasterToSlaveFileCallable { private static final long serialVersionUID = 1L; + @Override public Boolean invoke(File f, VirtualChannel channel) throws IOException { return f.exists(); @@ -1702,8 +1768,10 @@ public final class FilePath implements SerializableOnlyOverRemoting { public long lastModified() throws IOException, InterruptedException { return act(new LastModified()); } + private static class LastModified extends MasterToSlaveFileCallable { private static final long serialVersionUID = 1L; + @Override public Long invoke(File f, VirtualChannel channel) throws IOException { return f.lastModified(); @@ -1718,19 +1786,23 @@ public final class FilePath implements SerializableOnlyOverRemoting { public void touch(final long timestamp) throws IOException, InterruptedException { act(new Touch(timestamp)); } + private static class Touch extends MasterToSlaveFileCallable { private final long timestamp; + Touch(long timestamp) { this.timestamp = timestamp; } + private static final long serialVersionUID = -5094638816500738429L; + @Override public Void invoke(File f, VirtualChannel channel) throws IOException { - if(!f.exists()) { + if (!f.exists()) { Files.newOutputStream(fileToPath(f)).close(); } - if(!f.setLastModified(timestamp)) - throw new IOException("Failed to set the timestamp of "+f+" to "+timestamp); + if (!f.setLastModified(timestamp)) + throw new IOException("Failed to set the timestamp of " + f + " to " + timestamp); return null; } } @@ -1738,25 +1810,29 @@ public final class FilePath implements SerializableOnlyOverRemoting { private void setLastModifiedIfPossible(final long timestamp) throws IOException, InterruptedException { String message = act(new SetLastModified(timestamp)); - if (message!=null) { + if (message != null) { LOGGER.warning(message); } } + private static class SetLastModified extends MasterToSlaveFileCallable { private final long timestamp; + SetLastModified(long timestamp) { this.timestamp = timestamp; } + private static final long serialVersionUID = -828220335793641630L; + @Override public String invoke(File f, VirtualChannel channel) throws IOException { - if(!f.setLastModified(timestamp)) { + if (!f.setLastModified(timestamp)) { if (Functions.isWindows()) { // On Windows this seems to fail often. See JENKINS-11073 // Therefore don't fail, but just log a warning - return "Failed to set the timestamp of "+f+" to "+timestamp; + return "Failed to set the timestamp of " + f + " to " + timestamp; } else { - throw new IOException("Failed to set the timestamp of "+f+" to "+timestamp); + throw new IOException("Failed to set the timestamp of " + f + " to " + timestamp); } } return null; @@ -1769,8 +1845,10 @@ public final class FilePath implements SerializableOnlyOverRemoting { public boolean isDirectory() throws IOException, InterruptedException { return act(new IsDirectory()); } + private static class IsDirectory extends MasterToSlaveFileCallable { private static final long serialVersionUID = 1L; + @Override public Boolean invoke(File f, VirtualChannel channel) throws IOException { return f.isDirectory(); @@ -1785,8 +1863,10 @@ public final class FilePath implements SerializableOnlyOverRemoting { public long length() throws IOException, InterruptedException { return act(new Length()); } + private static class Length extends MasterToSlaveFileCallable { private static final long serialVersionUID = 1L; + @Override public Long invoke(File f, VirtualChannel channel) throws IOException { return f.length(); @@ -1800,8 +1880,10 @@ public final class FilePath implements SerializableOnlyOverRemoting { public long getFreeDiskSpace() throws IOException, InterruptedException { return act(new GetFreeDiskSpace()); } + private static class GetFreeDiskSpace extends MasterToSlaveFileCallable { private static final long serialVersionUID = 1L; + @Override public Long invoke(File f, VirtualChannel channel) throws IOException { return f.getFreeSpace(); @@ -1815,8 +1897,10 @@ public final class FilePath implements SerializableOnlyOverRemoting { public long getTotalDiskSpace() throws IOException, InterruptedException { return act(new GetTotalDiskSpace()); } + private static class GetTotalDiskSpace extends MasterToSlaveFileCallable { private static final long serialVersionUID = 1L; + @Override public Long invoke(File f, VirtualChannel channel) throws IOException { return f.getTotalSpace(); @@ -1830,8 +1914,10 @@ public final class FilePath implements SerializableOnlyOverRemoting { public long getUsableDiskSpace() throws IOException, InterruptedException { return act(new GetUsableDiskSpace()); } + private static class GetUsableDiskSpace extends MasterToSlaveFileCallable { private static final long serialVersionUID = 1L; + @Override public Long invoke(File f, VirtualChannel channel) throws IOException { return f.getUsableSpace(); @@ -1859,15 +1945,18 @@ public final class FilePath implements SerializableOnlyOverRemoting { * @see #mode() */ public void chmod(final int mask) throws IOException, InterruptedException { - if(!isUnix() || mask==-1) return; + if (!isUnix() || mask == -1) return; act(new Chmod(mask)); } + private static class Chmod extends MasterToSlaveFileCallable { private static final long serialVersionUID = 1L; private final int mask; + Chmod(int mask) { this.mask = mask; } + @Override public Void invoke(File f, VirtualChannel channel) throws IOException { _chmod(f, mask); @@ -1882,7 +1971,7 @@ public final class FilePath implements SerializableOnlyOverRemoting { private static void _chmod(File f, int mask) throws IOException { // TODO WindowsPosix actually does something here (WindowsLibC._wchmod); should we let it? // Anyway the existing calls already skip this method if on Windows. - if (File.pathSeparatorChar==';') return; // noop + if (File.pathSeparatorChar == ';') return; // noop Files.setPosixFilePermissions(fileToPath(f), Util.modeToPermissions(mask)); } @@ -1898,11 +1987,13 @@ public final class FilePath implements SerializableOnlyOverRemoting { * @see #chmod(int) */ public int mode() throws IOException, InterruptedException, PosixException { - if(!isUnix()) return -1; + if (!isUnix()) return -1; return act(new Mode()); } + private static class Mode extends MasterToSlaveFileCallable { private static final long serialVersionUID = 1L; + @Override public Integer invoke(File f, VirtualChannel channel) throws IOException { return IOUtils.mode(f); @@ -1917,7 +2008,7 @@ public final class FilePath implements SerializableOnlyOverRemoting { */ @NonNull public List list() throws IOException, InterruptedException { - return list((FileFilter)null); + return list((FileFilter) null); } /** @@ -1952,6 +2043,7 @@ public final class FilePath implements SerializableOnlyOverRemoting { public boolean accept(File f) { return f.isDirectory(); } + private static final long serialVersionUID = 1L; } @@ -1971,12 +2063,16 @@ public final class FilePath implements SerializableOnlyOverRemoting { } return act(new ListFilter(filter), (filter != null ? filter : this).getClass().getClassLoader()); } + private static class ListFilter extends MasterToSlaveFileCallable> { private final FileFilter filter; + ListFilter(FileFilter filter) { this.filter = filter; } + private static final long serialVersionUID = 1L; + @Override public List invoke(File f, VirtualChannel channel) throws IOException { File[] children = f.listFiles(filter); @@ -2037,23 +2133,27 @@ public final class FilePath implements SerializableOnlyOverRemoting { public FilePath[] list(final String includes, final String excludes, final boolean defaultExcludes) throws IOException, InterruptedException { return act(new ListGlob(includes, excludes, defaultExcludes)); } + private static class ListGlob extends MasterToSlaveFileCallable { private final String includes; private final String excludes; private final boolean defaultExcludes; + ListGlob(String includes, String excludes, boolean defaultExcludes) { this.includes = includes; this.excludes = excludes; this.defaultExcludes = defaultExcludes; } + private static final long serialVersionUID = 1L; + @Override public FilePath[] invoke(File f, VirtualChannel channel) throws IOException { String[] files = glob(f, includes, excludes, defaultExcludes); FilePath[] r = new FilePath[files.length]; - for( int i=0; i { private static final long serialVersionUID = 1L; + @Override public String invoke(File f, VirtualChannel channel) throws IOException, InterruptedException { return new String(Files.readAllBytes(fileToPath(f)), Charset.defaultCharset()); @@ -2297,7 +2400,7 @@ public final class FilePath implements SerializableOnlyOverRemoting { * file, it might not be fully written yet. */ public OutputStream write() throws IOException, InterruptedException { - if(channel==null) { + if (channel == null) { File f = new File(remote).getAbsoluteFile(); mkdirs(f.getParentFile()); return Files.newOutputStream(fileToPath(f)); @@ -2305,8 +2408,10 @@ public final class FilePath implements SerializableOnlyOverRemoting { return act(new WritePipe()); } + private static class WritePipe extends MasterToSlaveFileCallable { private static final long serialVersionUID = 1L; + @Override public OutputStream invoke(File f, VirtualChannel channel) throws IOException, InterruptedException { f = f.getAbsoluteFile(); @@ -2325,14 +2430,17 @@ public final class FilePath implements SerializableOnlyOverRemoting { public void write(final String content, final String encoding) throws IOException, InterruptedException { act(new Write(encoding, content)); } + private static class Write extends MasterToSlaveFileCallable { private static final long serialVersionUID = 1L; private final String encoding; private final String content; + Write(String encoding, String content) { this.encoding = encoding; this.content = content; } + @Override public Void invoke(File f, VirtualChannel channel) throws IOException { mkdirs(f.getParentFile()); @@ -2351,8 +2459,10 @@ public final class FilePath implements SerializableOnlyOverRemoting { public String digest() throws IOException, InterruptedException { return act(new Digest()); } + private static class Digest extends MasterToSlaveFileCallable { private static final long serialVersionUID = 1L; + @Override public String invoke(File f, VirtualChannel channel) throws IOException { return Util.getDigestOf(f); @@ -2364,17 +2474,21 @@ public final class FilePath implements SerializableOnlyOverRemoting { * be on the some host */ public void renameTo(final FilePath target) throws IOException, InterruptedException { - if(this.channel != target.channel) { + if (this.channel != target.channel) { throw new IOException("renameTo target must be on the same host"); } act(new RenameTo(target)); } + private static class RenameTo extends MasterToSlaveFileCallable { private final FilePath target; + RenameTo(FilePath target) { this.target = target; } + private static final long serialVersionUID = 1L; + @Override public Void invoke(File f, VirtualChannel channel) throws IOException { Files.move(fileToPath(f), fileToPath(new File(target.remote)), LinkOption.NOFOLLOW_LINKS); @@ -2388,31 +2502,35 @@ public final class FilePath implements SerializableOnlyOverRemoting { * @since 1.308. */ public void moveAllChildrenTo(final FilePath target) throws IOException, InterruptedException { - if(this.channel != target.channel) { + if (this.channel != target.channel) { throw new IOException("pullUpTo target must be on the same host"); } act(new MoveAllChildrenTo(target)); } + private static class MoveAllChildrenTo extends MasterToSlaveFileCallable { private final FilePath target; + MoveAllChildrenTo(FilePath target) { this.target = target; } + private static final long serialVersionUID = 1L; + @Override public Void invoke(File f, VirtualChannel channel) throws IOException { // JENKINS-16846: if f.getName() is the same as one of the files/directories in f, // then the rename op will fail - File tmp = new File(f.getAbsolutePath()+".__rename"); + File tmp = new File(f.getAbsolutePath() + ".__rename"); if (!f.renameTo(tmp)) - throw new IOException("Failed to rename "+f+" to "+tmp); + throw new IOException("Failed to rename " + f + " to " + tmp); File t = new File(target.getRemote()); - for(File child : tmp.listFiles()) { + for (File child : tmp.listFiles()) { File target = new File(t, child.getName()); - if(!child.renameTo(target)) - throw new IOException("Failed to rename "+child+" to "+target); + if (!child.renameTo(target)) + throw new IOException("Failed to rename " + child + " to " + target); } Files.deleteIfExists(Util.fileToPath(tmp)); return null; @@ -2428,7 +2546,7 @@ public final class FilePath implements SerializableOnlyOverRemoting { copyTo(out); } } catch (IOException e) { - throw new IOException("Failed to copy "+this+" to "+target,e); + throw new IOException("Failed to copy " + this + " to " + target, e); } } @@ -2448,11 +2566,14 @@ public final class FilePath implements SerializableOnlyOverRemoting { target.chmod(mode()); target.setLastModifiedIfPossible(lastModified()); } + private static class CopyToWithPermission extends MasterToSlaveFileCallable { private final FilePath target; + CopyToWithPermission(FilePath target) { this.target = target; } + @Override public Void invoke(File f, VirtualChannel channel) throws IOException { File targetFile = new File(target.remote); @@ -2475,12 +2596,15 @@ public final class FilePath implements SerializableOnlyOverRemoting { // this is needed because I/O operation is asynchronous syncIO(); } + private static class CopyTo extends MasterToSlaveFileCallable { private static final long serialVersionUID = 4088559042349254141L; private final OutputStream out; + CopyTo(OutputStream out) { this.out = out; } + @Override public Void invoke(File f, VirtualChannel channel) throws IOException { try (InputStream fis = Files.newInputStream(fileToPath(f))) { @@ -2499,12 +2623,12 @@ public final class FilePath implements SerializableOnlyOverRemoting { */ private void syncIO() throws InterruptedException { try { - if (channel!=null) + if (channel != null) channel.syncLocalIO(); } catch (AbstractMethodError e) { // legacy agent.jar. Handle this gracefully try { - LOGGER.log(Level.WARNING,"Looks like an old agent.jar. Please update "+ Which.jarFile(Channel.class)+" to the new version",e); + LOGGER.log(Level.WARNING, "Looks like an old agent.jar. Please update " + Which.jarFile(Channel.class) + " to the new version", e); } catch (IOException ignored) { // really ignore this time } @@ -2530,7 +2654,9 @@ public final class FilePath implements SerializableOnlyOverRemoting { * relative path name to the output file. Path separator must be '/'. */ void open(String fileName) throws IOException; + void write(byte[] buf, int len) throws IOException; + void close() throws IOException; } @@ -2542,7 +2668,7 @@ public final class FilePath implements SerializableOnlyOverRemoting { * @since 1.312 */ public int copyRecursiveTo(FilePath target) throws IOException, InterruptedException { - return copyRecursiveTo("**/*",target); + return copyRecursiveTo("**/*", target); } /** @@ -2557,7 +2683,7 @@ public final class FilePath implements SerializableOnlyOverRemoting { * the number of files copied. */ public int copyRecursiveTo(String fileMask, FilePath target) throws IOException, InterruptedException { - return copyRecursiveTo(fileMask,null,target); + return copyRecursiveTo(fileMask, null, target); } /** @@ -2599,11 +2725,11 @@ public final class FilePath implements SerializableOnlyOverRemoting { * @since 2.196 */ public int copyRecursiveTo(final DirScanner scanner, final FilePath target, final String description, @NonNull TarCompression compression) throws IOException, InterruptedException { - if(this.channel==target.channel) { + if (this.channel == target.channel) { // local to local copy. return act(new CopyRecursiveLocal(target, scanner)); } else - if(this.channel==null) { + if (this.channel == null) { // local -> remote copy final Pipe pipe = Pipe.createLocalToRemote(); @@ -2622,10 +2748,10 @@ public final class FilePath implements SerializableOnlyOverRemoting { Future future = actAsync(new CopyRecursiveRemoteToLocal(pipe, scanner, compression)); try { - readFromTar(remote + '/' + description,new File(target.remote),compression.extract(pipe.getIn())); - } catch (IOException e) {// BuildException or IOException + readFromTar(remote + '/' + description, new File(target.remote), compression.extract(pipe.getIn())); + } catch (IOException e) { // BuildException or IOException try { - future.get(3,TimeUnit.SECONDS); + future.get(3, TimeUnit.SECONDS); throw e; // the remote side completed successfully, so the error must be local } catch (ExecutionException x) { // report both errors @@ -2656,11 +2782,14 @@ public final class FilePath implements SerializableOnlyOverRemoting { private static class CopyRecursiveLocal extends MasterToSlaveFileCallable { private final FilePath target; private final DirScanner scanner; + CopyRecursiveLocal(FilePath target, DirScanner scanner) { this.target = target; this.scanner = scanner; } + private static final long serialVersionUID = 1L; + @Override public Integer invoke(File base, VirtualChannel channel) throws IOException { if (!base.exists()) { @@ -2694,6 +2823,7 @@ public final class FilePath implements SerializableOnlyOverRemoting { count.incrementAndGet(); } } + private boolean tryCopyWithAttributes(File f, Path targetPath) { try { Files.copy(fileToPath(f), targetPath, @@ -2704,10 +2834,12 @@ public final class FilePath implements SerializableOnlyOverRemoting { } return true; } + @Override public boolean understandsSymlink() { return true; } + @SuppressFBWarnings(value = "PATH_TRAVERSAL_IN", justification = "TODO needs triage") @Override public void visitSymlink(File link, String target, String relativePath) throws IOException { @@ -2723,6 +2855,7 @@ public final class FilePath implements SerializableOnlyOverRemoting { return count.get(); } } + private static class ReadFromTar extends MasterToSlaveFileCallable { private final Pipe pipe; private final String description; @@ -2735,7 +2868,9 @@ public final class FilePath implements SerializableOnlyOverRemoting { this.description = description; this.compression = compression; } + private static final long serialVersionUID = 1L; + @Override public Void invoke(File f, VirtualChannel channel) throws IOException { try (InputStream in = pipe.getIn()) { @@ -2744,31 +2879,38 @@ public final class FilePath implements SerializableOnlyOverRemoting { } } } + private static class WriteToTar extends MasterToSlaveFileCallable { private final DirScanner scanner; private final Pipe pipe; private final TarCompression compression; + WriteToTar(DirScanner scanner, Pipe pipe, @NonNull TarCompression compression) { this.scanner = scanner; this.pipe = pipe; this.compression = compression; } + private static final long serialVersionUID = 1L; + @Override public Integer invoke(File f, VirtualChannel channel) throws IOException, InterruptedException { return writeToTar(f, scanner, compression.compress(pipe.getOut())); } } + private static class CopyRecursiveRemoteToLocal extends MasterToSlaveFileCallable { private static final long serialVersionUID = 1L; private final Pipe pipe; private final DirScanner scanner; private final TarCompression compression; + CopyRecursiveRemoteToLocal(Pipe pipe, DirScanner scanner, @NonNull TarCompression compression) { this.pipe = pipe; this.scanner = scanner; this.compression = compression; } + @Override public Integer invoke(File f, VirtualChannel channel) throws IOException { try (OutputStream out = pipe.getOut()) { @@ -2807,7 +2949,7 @@ public final class FilePath implements SerializableOnlyOverRemoting { private static Integer writeToTar(File baseDir, DirScanner scanner, OutputStream out) throws IOException { Archiver tw = ArchiverFactory.TAR.create(out); try { - scanner.scan(baseDir,tw); + scanner.scan(baseDir, tw); } finally { tw.close(); } @@ -2861,18 +3003,19 @@ public final class FilePath implements SerializableOnlyOverRemoting { * @since 1.89 */ public Launcher createLauncher(TaskListener listener) throws IOException, InterruptedException { - if(channel==null) + if (channel == null) return new LocalLauncher(listener); else - return new RemoteLauncher(listener,channel,channel.call(new IsUnix())); + return new RemoteLauncher(listener, channel, channel.call(new IsUnix())); } - private static final class IsUnix extends MasterToSlaveCallable { + private static final class IsUnix extends MasterToSlaveCallable { @Override @NonNull public Boolean call() throws IOException { - return File.pathSeparatorChar==':'; + return File.pathSeparatorChar == ':'; } + private static final long serialVersionUID = 1L; } @@ -2937,26 +3080,30 @@ public final class FilePath implements SerializableOnlyOverRemoting { public @CheckForNull String validateAntFileMask(final String fileMasks, final int bound, final boolean caseSensitive) throws IOException, InterruptedException { return act(new ValidateAntFileMask(fileMasks, caseSensitive, bound)); } + private static class ValidateAntFileMask extends MasterToSlaveFileCallable { private final String fileMasks; private final boolean caseSensitive; private final int bound; + ValidateAntFileMask(String fileMasks, boolean caseSensitive, int bound) { this.fileMasks = fileMasks; this.caseSensitive = caseSensitive; this.bound = bound; } + private static final long serialVersionUID = 1; + @Override public String invoke(File dir, VirtualChannel channel) throws IOException, InterruptedException { - if(fileMasks.startsWith("~")) + if (fileMasks.startsWith("~")) return Messages.FilePath_TildaDoesntWork(); - StringTokenizer tokens = new StringTokenizer(fileMasks,","); + StringTokenizer tokens = new StringTokenizer(fileMasks, ","); - while(tokens.hasMoreTokens()) { + while (tokens.hasMoreTokens()) { final String fileMask = tokens.nextToken().trim(); - if(hasMatch(dir,fileMask,caseSensitive)) + if (hasMatch(dir, fileMask, caseSensitive)) continue; // no error on this portion // JENKINS-5253 - if we can get some match in case insensitive mode @@ -2967,11 +3114,11 @@ public final class FilePath implements SerializableOnlyOverRemoting { // in 1.172 we introduced an incompatible change to stop using ' ' as the separator // so see if we can match by using ' ' as the separator - if(fileMask.contains(" ")) { + if (fileMask.contains(" ")) { boolean matched = true; for (String token : Util.tokenize(fileMask)) - matched &= hasMatch(dir,token,caseSensitive); - if(matched) + matched &= hasMatch(dir, token, caseSensitive); + if (matched) return Messages.FilePath_validateAntFileMask_whitespaceSeparator(); } @@ -2979,28 +3126,28 @@ public final class FilePath implements SerializableOnlyOverRemoting { // to this: (1) the user gave us aa/bb/cc/dd where cc/dd was correct // and (2) the user gave us cc/dd where aa/bb/cc/dd was correct. - {// check the (1) above first - String f=fileMask; - while(true) { + { // check the (1) above first + String f = fileMask; + while (true) { int idx = findSeparator(f); - if(idx==-1) break; - f=f.substring(idx+1); + if (idx == -1) break; + f = f.substring(idx + 1); - if(hasMatch(dir,f,caseSensitive)) - return Messages.FilePath_validateAntFileMask_doesntMatchAndSuggest(fileMask,f); + if (hasMatch(dir, f, caseSensitive)) + return Messages.FilePath_validateAntFileMask_doesntMatchAndSuggest(fileMask, f); } } - {// check the (2) above next as this is more expensive. + { // check the (2) above next as this is more expensive. // Try prepending "**/" to see if that results in a match - FileSet fs = Util.createFileSet(dir,"**/"+fileMask); + FileSet fs = Util.createFileSet(dir, "**/" + fileMask); fs.setCaseSensitive(caseSensitive); DirectoryScanner ds = fs.getDirectoryScanner(new Project()); - if(ds.getIncludedFilesCount()!=0) { + if (ds.getIncludedFilesCount() != 0) { // try shorter name first so that the suggestion results in least amount of changes String[] names = ds.getIncludedFiles(); - Arrays.sort(names,SHORTER_STRING_FIRST); - for( String f : names) { + Arrays.sort(names, SHORTER_STRING_FIRST); + for (String f : names) { // now we want to decompose f to the leading portion that matched "**" // and the trailing portion that matched the file mask, so that // we can suggest the user error. @@ -3008,43 +3155,43 @@ public final class FilePath implements SerializableOnlyOverRemoting { // this is not a very efficient/clever way to do it, but it's relatively simple StringBuilder prefix = new StringBuilder(); - while(true) { + while (true) { int idx = findSeparator(f); - if(idx==-1) break; + if (idx == -1) break; prefix.append(f, 0, idx).append('/'); - f=f.substring(idx+1); - if(hasMatch(dir,prefix+fileMask,caseSensitive)) - return Messages.FilePath_validateAntFileMask_doesntMatchAndSuggest(fileMask, prefix+fileMask); + f = f.substring(idx + 1); + if (hasMatch(dir, prefix + fileMask, caseSensitive)) + return Messages.FilePath_validateAntFileMask_doesntMatchAndSuggest(fileMask, prefix + fileMask); } } } } - {// finally, see if we can identify any sub portion that's valid. Otherwise bail out + { // finally, see if we can identify any sub portion that's valid. Otherwise bail out String previous = null; String pattern = fileMask; - while(true) { - if(hasMatch(dir,pattern,caseSensitive)) { + while (true) { + if (hasMatch(dir, pattern, caseSensitive)) { // found a match - if(previous==null) - return Messages.FilePath_validateAntFileMask_portionMatchAndSuggest(fileMask,pattern); + if (previous == null) + return Messages.FilePath_validateAntFileMask_portionMatchAndSuggest(fileMask, pattern); else - return Messages.FilePath_validateAntFileMask_portionMatchButPreviousNotMatchAndSuggest(fileMask,pattern,previous); + return Messages.FilePath_validateAntFileMask_portionMatchButPreviousNotMatchAndSuggest(fileMask, pattern, previous); } int idx = findSeparator(pattern); - if(idx<0) {// no more path component left to go back - if(pattern.equals(fileMask)) + if (idx < 0) { // no more path component left to go back + if (pattern.equals(fileMask)) return Messages.FilePath_validateAntFileMask_doesntMatchAnything(fileMask); else - return Messages.FilePath_validateAntFileMask_doesntMatchAnythingAndSuggest(fileMask,pattern); + return Messages.FilePath_validateAntFileMask_doesntMatchAnythingAndSuggest(fileMask, pattern); } // cut off the trailing component and try again previous = pattern; - pattern = pattern.substring(0,idx); + pattern = pattern.substring(0, idx); } } } @@ -3054,6 +3201,7 @@ public final class FilePath implements SerializableOnlyOverRemoting { private boolean hasMatch(File dir, String pattern, boolean bCaseSensitive) throws InterruptedException { class Cancel extends RuntimeException {} + DirectoryScanner ds = bound == Integer.MAX_VALUE ? new DirectoryScanner() : new DirectoryScanner() { int ticks; long start = System.currentTimeMillis(); @@ -3074,13 +3222,13 @@ public final class FilePath implements SerializableOnlyOverRemoting { try { ds.scan(); } catch (Cancel c) { - if (ds.getIncludedFilesCount()!=0 || ds.getIncludedDirsCount()!=0) { + if (ds.getIncludedFilesCount() != 0 || ds.getIncludedDirsCount() != 0) { return true; } else { - throw (InterruptedException)new InterruptedException("no matches found within " + bound).initCause(c); + throw (InterruptedException) new InterruptedException("no matches found within " + bound).initCause(c); } } - return ds.getIncludedFilesCount()!=0 || ds.getIncludedDirsCount()!=0; + return ds.getIncludedFilesCount() != 0 || ds.getIncludedDirsCount() != 0; } /** @@ -3089,9 +3237,9 @@ public final class FilePath implements SerializableOnlyOverRemoting { private int findSeparator(String pattern) { int idx1 = pattern.indexOf('\\'); int idx2 = pattern.indexOf('/'); - if(idx1==-1) return idx2; - if(idx2==-1) return idx1; - return Math.min(idx1,idx2); + if (idx1 == -1) return idx2; + if (idx2 == -1) return idx1; + return Math.min(idx1, idx2); } } @@ -3131,7 +3279,7 @@ public final class FilePath implements SerializableOnlyOverRemoting { * Shortcut for {@link #validateFileMask(String,boolean,boolean)} with {@code errorIfNotExist} true, as the left-hand side can be null. */ public static FormValidation validateFileMask(@CheckForNull FilePath path, String value, boolean caseSensitive) throws IOException { - if(path==null) return FormValidation.ok(); + if (path == null) return FormValidation.ok(); return path.validateFileMask(value, true, caseSensitive); } @@ -3164,15 +3312,15 @@ public final class FilePath implements SerializableOnlyOverRemoting { checkPermissionForValidate(); value = fixEmpty(value); - if(value==null) + if (value == null) return FormValidation.ok(); try { - if(!exists()) // no workspace. can't check + if (!exists()) // no workspace. can't check return FormValidation.ok(); String msg = validateAntFileMask(value, VALIDATE_ANT_FILE_MASK_BOUND, caseSensitive); - if(errorIfNotExist) return FormValidation.error(msg); + if (errorIfNotExist) return FormValidation.error(msg); else return FormValidation.warning(msg); } catch (InterruptedException e) { return FormValidation.ok(Messages.FilePath_did_not_manage_to_validate_may_be_too_sl(value)); @@ -3202,24 +3350,24 @@ public final class FilePath implements SerializableOnlyOverRemoting { value = fixEmpty(value); // none entered yet, or something is seriously wrong - if(value==null) return FormValidation.ok(); + if (value == null) return FormValidation.ok(); // a common mistake is to use wildcard - if(value.contains("*")) return FormValidation.error(Messages.FilePath_validateRelativePath_wildcardNotAllowed()); + if (value.contains("*")) return FormValidation.error(Messages.FilePath_validateRelativePath_wildcardNotAllowed()); try { - if(!exists()) // no base directory. can't check + if (!exists()) // no base directory. can't check return FormValidation.ok(); FilePath path = child(value); - if(path.exists()) { + if (path.exists()) { if (expectingFile) { - if(!path.isDirectory()) + if (!path.isDirectory()) return FormValidation.ok(); else return FormValidation.error(Messages.FilePath_validateRelativePath_notFile(value)); } else { - if(path.isDirectory()) + if (path.isDirectory()) return FormValidation.ok(); else return FormValidation.error(Messages.FilePath_validateRelativePath_notDirectory(value)); @@ -3228,7 +3376,7 @@ public final class FilePath implements SerializableOnlyOverRemoting { String msg = expectingFile ? Messages.FilePath_validateRelativePath_noSuchFile(value) : Messages.FilePath_validateRelativePath_noSuchDirectory(value); - if(errorIfNotExist) return FormValidation.error(msg); + if (errorIfNotExist) return FormValidation.error(msg); else return FormValidation.warning(msg); } catch (InterruptedException e) { return FormValidation.ok(); @@ -3247,11 +3395,11 @@ public final class FilePath implements SerializableOnlyOverRemoting { * A convenience method over {@link #validateRelativePath(String, boolean, boolean)}. */ public FormValidation validateRelativeDirectory(String value, boolean errorIfNotExist) throws IOException { - return validateRelativePath(value,errorIfNotExist,false); + return validateRelativePath(value, errorIfNotExist, false); } public FormValidation validateRelativeDirectory(String value) throws IOException { - return validateRelativeDirectory(value,true); + return validateRelativeDirectory(value, true); } @Deprecated @Override @@ -3261,7 +3409,7 @@ public final class FilePath implements SerializableOnlyOverRemoting { } public VirtualChannel getChannel() { - if(channel!=null) return channel; + if (channel != null) return channel; else return localChannel; } @@ -3269,7 +3417,7 @@ public final class FilePath implements SerializableOnlyOverRemoting { * Returns true if this {@link FilePath} represents a remote file. */ public boolean isRemote() { - return channel!=null; + return channel != null; } private void writeObject(ObjectOutputStream oos) throws IOException { @@ -3279,7 +3427,7 @@ public final class FilePath implements SerializableOnlyOverRemoting { } oos.defaultWriteObject(); - oos.writeBoolean(channel==null); + oos.writeBoolean(channel == null); } private Channel _getChannelForSerialization() { @@ -3295,7 +3443,7 @@ public final class FilePath implements SerializableOnlyOverRemoting { Channel channel = _getChannelForSerialization(); ois.defaultReadObject(); - if(ois.readBoolean()) { + if (ois.readBoolean()) { this.channel = channel; } else { this.channel = null; @@ -3317,7 +3465,7 @@ public final class FilePath implements SerializableOnlyOverRemoting { /** * Adapts {@link FileCallable} to {@link Callable}. */ - private static class FileCallableWrapper implements DelegatingCallable { + private static class FileCallableWrapper implements DelegatingCallable { private final FileCallable callable; private transient ClassLoader classLoader; private final FilePath filePath; @@ -3371,6 +3519,7 @@ public final class FilePath implements SerializableOnlyOverRemoting { private TunneledInterruptedException(InterruptedException cause) { super(cause); } + private static final long serialVersionUID = 1L; } @@ -3383,6 +3532,7 @@ public final class FilePath implements SerializableOnlyOverRemoting { public static FilePath getHomeDirectory(VirtualChannel ch) throws InterruptedException, IOException { return ch.call(new GetHomeDirectory()); } + private static class GetHomeDirectory extends MasterToSlaveCallable { @Override public FilePath call() throws IOException { @@ -3398,18 +3548,18 @@ public final class FilePath implements SerializableOnlyOverRemoting { private static final long serialVersionUID = 1; - private final Map files; + private final Map files; /** * Create a “scanner” (it actually does no scanning). * @param files a map from logical relative paths as per {@link FileVisitor#visit}, to actual relative paths within the scanned directory */ - public ExplicitlySpecifiedDirScanner(Map files) { + public ExplicitlySpecifiedDirScanner(Map files) { this.files = files; } @Override public void scan(File dir, FileVisitor visitor) throws IOException { - for (Map.Entry entry : files.entrySet()) { + for (Map.Entry entry : files.entrySet()) { String archivedPath = entry.getKey(); assert archivedPath.indexOf('\\') == -1; String workspacePath = entry.getValue(); @@ -3482,7 +3632,7 @@ public final class FilePath implements SerializableOnlyOverRemoting { private static final long serialVersionUID = 1L; private String potentialChildRelativePath; - private IsDescendant(@NonNull String potentialChildRelativePath){ + private IsDescendant(@NonNull String potentialChildRelativePath) { this.potentialChildRelativePath = potentialChildRelativePath; } @@ -3531,7 +3681,7 @@ public final class FilePath implements SerializableOnlyOverRemoting { } Path currentFileAbsolutePath = currentFilePath.toAbsolutePath(); - try{ + try { Path child = currentFileAbsolutePath.toRealPath(); if (!child.startsWith(parentRealPath)) { LOGGER.log(Level.FINE, "Child [{0}] does not start with parent [{1}] => not descendant", new Object[]{ child, parentRealPath }); @@ -3545,7 +3695,7 @@ public final class FilePath implements SerializableOnlyOverRemoting { Path child = currentFileAbsolutePath.normalize(); Path parent = parentAbsolutePath.normalize(); return child.startsWith(parent); - } catch(FileSystemException e) { + } catch (FileSystemException e) { LOGGER.log(Level.WARNING, String.format("Problem during call to the method toRealPath on %s", currentFileAbsolutePath), e); return false; } @@ -3554,7 +3704,7 @@ public final class FilePath implements SerializableOnlyOverRemoting { return true; } - private @CheckForNull Path getDirectChild(Path parentPath, String childPath){ + private @CheckForNull Path getDirectChild(Path parentPath, String childPath) { Path current = parentPath.resolve(childPath); while (current != null && !parentPath.equals(current.getParent())) { current = current.getParent(); @@ -3611,6 +3761,7 @@ public final class FilePath implements SerializableOnlyOverRemoting { public boolean accept(File file) { return !isSymlink(file, verificationRoot, noFollowLinks); } + private static final long serialVersionUID = 1L; } } diff --git a/core/src/main/java/hudson/FileSystemProvisioner.java b/core/src/main/java/hudson/FileSystemProvisioner.java index e2dbb4480ff857f2ef0cd2cc03694df70b5313ae..d93f2c8e8b76ee0978435e83e52033242f7472ad 100644 --- a/core/src/main/java/hudson/FileSystemProvisioner.java +++ b/core/src/main/java/hudson/FileSystemProvisioner.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson; import hudson.model.AbstractBuild; @@ -36,11 +37,11 @@ import jenkins.model.Jenkins; */ @Deprecated public abstract class FileSystemProvisioner implements Describable { - public abstract void prepareWorkspace(AbstractBuild build, FilePath ws, TaskListener listener) throws IOException, InterruptedException; + public abstract void prepareWorkspace(AbstractBuild build, FilePath ws, TaskListener listener) throws IOException, InterruptedException; public abstract void discardWorkspace(AbstractProject project, FilePath ws) throws IOException, InterruptedException; - public abstract WorkspaceSnapshot snapshot(AbstractBuild build, FilePath ws, String glob, TaskListener listener) throws IOException, InterruptedException; + public abstract WorkspaceSnapshot snapshot(AbstractBuild build, FilePath ws, String glob, TaskListener listener) throws IOException, InterruptedException; @Override public Descriptor getDescriptor() { diff --git a/core/src/main/java/hudson/Functions.java b/core/src/main/java/hudson/Functions.java index 2d54d3358f9237a7e6e9509a7519adb6b6120c6d..b41fb8cd2164e516148303280c79a1fd50506d0e 100644 --- a/core/src/main/java/hudson/Functions.java +++ b/core/src/main/java/hudson/Functions.java @@ -1,20 +1,20 @@ /* * The MIT License - * + * * Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi, * Yahoo! Inc., Stephen Connolly, Tom Huybrechts, Alan Harder, Manufacture * Francaise des Pneumatiques Michelin, Romain Seguy - * + * * 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 @@ -23,6 +23,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson; import edu.umd.cs.findbugs.annotations.CheckForNull; @@ -211,7 +212,7 @@ public class Functions { public static boolean isModelWithChildren(Object o) { return o instanceof ModelObjectWithChildren; } - + @Deprecated public static boolean isMatrixProject(Object o) { return o != null && o.getClass().getName().equals("hudson.matrix.MatrixProject"); @@ -293,8 +294,8 @@ public class Functions { see https://wiki.jenkins-ci.org/display/JENKINS/Hyperlinks+in+HTML */ - context.setVariable("resURL",rootURL+getResourcePath()); - context.setVariable("imagesURL",rootURL+getResourcePath()+"/images"); + context.setVariable("resURL", rootURL + getResourcePath()); + context.setVariable("imagesURL", rootURL + getResourcePath() + "/images"); context.setVariable("divBasedFormLayout", true); context.setVariable("userAgent", currentRequest.getHeader("User-Agent")); IconSet.initPageVariables(context); @@ -312,12 +313,12 @@ public class Functions { * if c' is not parameterized. */ public static Class getTypeParameter(Class c, Class base, int n) { - Type parameterization = Types.getBaseClass(c,base); + Type parameterization = Types.getBaseClass(c, base); if (parameterization instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) parameterization; - return Types.erasure(Types.getTypeArgument(pt,n)); + return Types.erasure(Types.getTypeArgument(pt, n)); } else { - throw new AssertionError(c+" doesn't properly parameterize "+base); + throw new AssertionError(c + " doesn't properly parameterize " + base); } } @@ -330,9 +331,9 @@ public class Functions { * like "-5", "+/-0", "+3". */ public static String getDiffString(int i) { - if(i==0) return "±0"; + if (i == 0) return "±0"; String s = Integer.toString(i); - if(i>0) return "+"+s; + if (i > 0) return "+" + s; else return s; } @@ -340,9 +341,9 @@ public class Functions { * {@link #getDiffString(int)} that doesn't show anything for +/-0 */ public static String getDiffString2(int i) { - if(i==0) return ""; + if (i == 0) return ""; String s = Integer.toString(i); - if(i>0) return "+"+s; + if (i > 0) return "+" + s; else return s; } @@ -351,10 +352,10 @@ public class Functions { * if there's something to print */ public static String getDiffString2(String prefix, int i, String suffix) { - if(i==0) return ""; + if (i == 0) return ""; String s = Integer.toString(i); - if(i>0) return prefix+"+"+s+suffix; - else return prefix+s+suffix; + if (i > 0) return prefix + "+" + s + suffix; + else return prefix + s + suffix; } /** @@ -363,7 +364,7 @@ public class Functions { public static String addSuffix(int n, String singular, String plural) { StringBuilder buf = new StringBuilder(); buf.append(n).append(' '); - if(n==1) + if (n == 1) buf.append(singular); else buf.append(plural); @@ -374,16 +375,16 @@ public class Functions { List ancestors = req.getAncestors(); // find the first and last Run instances - Ancestor f=null,l=null; + Ancestor f = null, l = null; for (Ancestor anc : ancestors) { - if(anc.getObject() instanceof Run) { - if(f==null) f=anc; - l=anc; + if (anc.getObject() instanceof Run) { + if (f == null) f = anc; + l = anc; } } - if(l==null) return null; // there was no Run object + if (l == null) return null; // there was no Run object - String head = f.getPrev().getUrl()+'/'; + String head = f.getPrev().getUrl() + '/'; String base = l.getUrl(); String reqUri = req.getOriginalRequestURI(); @@ -400,7 +401,7 @@ public class Functions { // Remove that many from request URL, ignoring extra slashes String rest = reqUri.replaceFirst("(?:/+[^/]*){" + slashCount + "}", ""); - return new RunUrl( (Run) f.getObject(), head, base, rest); + return new RunUrl((Run) f.getObject(), head, base, rest); } /** @@ -408,8 +409,8 @@ public class Functions { * @since 1.213 */ public static Area getScreenResolution() { - Cookie res = Functions.getCookie(Stapler.getCurrentRequest(),"screenResolution"); - if(res!=null) + Cookie res = Functions.getCookie(Stapler.getCurrentRequest(), "screenResolution"); + if (res != null) return Area.parse(res.getValue()); return null; } @@ -474,10 +475,10 @@ public class Functions { } private String getUrl(Run n) { - if(n ==null) + if (n == null) return null; else { - return head+n.getNumber()+rest; + return head + n.getNumber() + rest; } } } @@ -510,7 +511,7 @@ public class Functions { /** * Gets the system property indicated by the specified key. - * + * * Delegates to {@link SystemProperties#getString(String)}. */ @Restricted(DoNotUse.class) @@ -533,14 +534,14 @@ public class Functions { } public static boolean isWindows() { - return File.pathSeparatorChar==';'; + return File.pathSeparatorChar == ';'; } - + public static boolean isGlibcSupported() { try { GNUCLibrary.LIBC.getpid(); return true; - } catch(Throwable t) { + } catch (Throwable t) { return false; } } @@ -568,6 +569,7 @@ public class Functions { * @return date, source, level, message+thrown * @see SimpleFormatter#format(LogRecord) */ + private static String[] logRecordPreformat(LogRecord r) { String source; if (r.getSourceClassName() == null) { @@ -599,11 +601,11 @@ public class Functions { return list; } - public static Cookie getCookie(HttpServletRequest req,String name) { + public static Cookie getCookie(HttpServletRequest req, String name) { Cookie[] cookies = req.getCookies(); - if(cookies!=null) { + if (cookies != null) { for (Cookie cookie : cookies) { - if(cookie.getName().equals(name)) { + if (cookie.getName().equals(name)) { return cookie; } } @@ -611,13 +613,14 @@ public class Functions { return null; } - public static String getCookie(HttpServletRequest req,String name, String defaultValue) { + public static String getCookie(HttpServletRequest req, String name, String defaultValue) { Cookie c = getCookie(req, name); - if(c==null || c.getValue()==null) return defaultValue; + if (c == null || c.getValue() == null) return defaultValue; return c.getValue(); } private static final Pattern ICON_SIZE = Pattern.compile("\\d+x\\d+"); + @Restricted(NoExternalUse.class) public static String validateIconSize(String iconSize) throws SecurityException { if (!ICON_SIZE.matcher(iconSize).matches()) { @@ -642,28 +645,28 @@ public class Functions { /** * Creates a sub map by using the given range (both ends inclusive). */ - public static SortedMap filter(SortedMap map, String from, String to) { - if(from==null && to==null) return map; - if(to==null) - return map.headMap(Integer.parseInt(from)-1); - if(from==null) + public static SortedMap filter(SortedMap map, String from, String to) { + if (from == null && to == null) return map; + if (to == null) + return map.headMap(Integer.parseInt(from) - 1); + if (from == null) return map.tailMap(Integer.parseInt(to)); - return map.subMap(Integer.parseInt(to),Integer.parseInt(from)-1); + return map.subMap(Integer.parseInt(to), Integer.parseInt(from) - 1); } /** * Creates a sub map by using the given range (upper end inclusive). */ @Restricted(NoExternalUse.class) - public static SortedMap filterExcludingFrom(SortedMap map, String from, String to) { - if(from==null && to==null) return map; - if(to==null) + public static SortedMap filterExcludingFrom(SortedMap map, String from, String to) { + if (from == null && to == null) return map; + if (to == null) return map.headMap(Integer.parseInt(from)); - if(from==null) + if (from == null) return map.tailMap(Integer.parseInt(to)); - return map.subMap(Integer.parseInt(to),Integer.parseInt(from)); + return map.subMap(Integer.parseInt(to), Integer.parseInt(from)); } private static final SimpleFormatter formatter = new SimpleFormatter(); @@ -684,7 +687,7 @@ public class Functions { } public static boolean isCollapsed(String paneId) { - return PaneStatusProperties.forCurrentUser().isCollapsed(paneId); + return PaneStatusProperties.forCurrentUser().isCollapsed(paneId); } @Restricted(NoExternalUse.class) @@ -713,11 +716,11 @@ public class Functions { * This is used to determine the "current" URL assigned to the given object, * so that one can compute relative URLs from it. */ - public static String getNearestAncestorUrl(StaplerRequest req,Object it) { + public static String getNearestAncestorUrl(StaplerRequest req, Object it) { List list = req.getAncestors(); - for( int i=list.size()-1; i>=0; i-- ) { + for (int i = list.size() - 1; i >= 0; i--) { Ancestor anc = (Ancestor) list.get(i); - if(anc.getObject()==it) + if (anc.getObject() == it) return anc.getUrl(); } return null; @@ -728,17 +731,17 @@ public class Functions { */ public static String getSearchURL() { List list = Stapler.getCurrentRequest().getAncestors(); - for( int i=list.size()-1; i>=0; i-- ) { + for (int i = list.size() - 1; i >= 0; i--) { Ancestor anc = (Ancestor) list.get(i); - if(anc.getObject() instanceof SearchableModelObject) - return anc.getUrl()+"/search/"; + if (anc.getObject() instanceof SearchableModelObject) + return anc.getUrl() + "/search/"; } return null; } public static String appendSpaceIfNotNull(String n) { - if(n==null) return null; - else return n+' '; + if (n == null) return null; + else return n + ' '; } /** @@ -759,8 +762,8 @@ public class Functions { } public static boolean isMultiline(String s) { - if(s==null) return false; - return s.indexOf('\r')>=0 || s.indexOf('\n')>=0; + if (s == null) return false; + return s.indexOf('\r') >= 0 || s.indexOf('\n') >= 0; } public static String encode(String s) { @@ -794,26 +797,26 @@ public class Functions { } public static String xmlUnescape(String s) { - return s.replace("<","<").replace(">",">").replace("&","&"); + return s.replace("<", "<").replace(">", ">").replace("&", "&"); } public static String htmlAttributeEscape(String text) { - StringBuilder buf = new StringBuilder(text.length()+64); - for( int i=0; i') + if (ch == '>') buf.append(">"); else - if(ch=='&') + if (ch == '&') buf.append("&"); else - if(ch=='"') + if (ch == '"') buf.append("""); else - if(ch=='\'') + if (ch == '\'') buf.append("'"); else buf.append(ch); @@ -822,7 +825,7 @@ public class Functions { } public static void checkPermission(Permission permission) throws IOException, ServletException { - checkPermission(Jenkins.get(),permission); + checkPermission(Jenkins.get(), permission); } public static void checkPermission(AccessControlled object, Permission permission) throws IOException, ServletException { @@ -839,19 +842,19 @@ public class Functions { public static void checkPermission(Object object, Permission permission) throws IOException, ServletException { if (permission == null) return; - + if (object instanceof AccessControlled) - checkPermission((AccessControlled) object,permission); + checkPermission((AccessControlled) object, permission); else { List ancs = Stapler.getCurrentRequest().getAncestors(); - for(Ancestor anc : Iterators.reverse(ancs)) { + for (Ancestor anc : Iterators.reverse(ancs)) { Object o = anc.getObject(); if (o instanceof AccessControlled) { - checkPermission((AccessControlled) o,permission); + checkPermission((AccessControlled) o, permission); return; } } - checkPermission(Jenkins.get(),permission); + checkPermission(Jenkins.get(), permission); } } @@ -862,7 +865,7 @@ public class Functions { * If null, returns true. This defaulting is convenient in making the use of this method terse. */ public static boolean hasPermission(Permission permission) throws IOException, ServletException { - return hasPermission(Jenkins.get(),permission); + return hasPermission(Jenkins.get(), permission); } /** @@ -873,13 +876,13 @@ public class Functions { if (permission == null) return true; if (object instanceof AccessControlled) - return ((AccessControlled)object).hasPermission(permission); + return ((AccessControlled) object).hasPermission(permission); else { List ancs = Stapler.getCurrentRequest().getAncestors(); - for(Ancestor anc : Iterators.reverse(ancs)) { + for (Ancestor anc : Iterators.reverse(ancs)) { Object o = anc.getObject(); if (o instanceof AccessControlled) { - return ((AccessControlled)o).hasPermission(permission); + return ((AccessControlled) o).hasPermission(permission); } } return Jenkins.get().hasPermission(permission); @@ -889,7 +892,7 @@ public class Functions { public static void adminCheck(StaplerRequest req, StaplerResponse rsp, Object required, Permission permission) throws IOException, ServletException { // this is legacy --- all views should be eventually converted to // the permission based model. - if(required!=null && !Hudson.adminCheck(req, rsp)) { + if (required != null && !Hudson.adminCheck(req, rsp)) { // check failed. commit the FORBIDDEN response, then abort. rsp.setStatus(HttpServletResponse.SC_FORBIDDEN); rsp.getOutputStream().close(); @@ -897,7 +900,7 @@ public class Functions { } // make sure the user owns the necessary permission to access this page. - if(permission!=null) + if (permission != null) checkPermission(permission); } @@ -906,13 +909,13 @@ public class Functions { */ public static String inferHudsonURL(StaplerRequest req) { String rootUrl = Jenkins.get().getRootUrl(); - if(rootUrl !=null) + if (rootUrl != null) // prefer the one explicitly configured, to work with load-balancer, frontend, etc. return rootUrl; StringBuilder buf = new StringBuilder(); buf.append(req.getScheme()).append("://"); buf.append(req.getServerName()); - if(! (req.getScheme().equals("http") && req.getLocalPort()==80 || req.getScheme().equals("https") && req.getLocalPort()==443)) + if (! (req.getScheme().equals("http") && req.getLocalPort() == 80 || req.getScheme().equals("https") && req.getLocalPort() == 443)) buf.append(':').append(req.getLocalPort()); buf.append(req.getContextPath()).append('/'); return buf.toString(); @@ -922,14 +925,15 @@ public class Functions { * Returns the link to be displayed in the footer of the UI. */ public static String getFooterURL() { - if(footerURL == null) { + if (footerURL == null) { footerURL = SystemProperties.getString("hudson.footerURL"); - if(StringUtils.isBlank(footerURL)) { + if (StringUtils.isBlank(footerURL)) { footerURL = "https://www.jenkins.io/"; } } return footerURL; } + private static String footerURL = null; public static List getJobPropertyDescriptors(Class clazz) { @@ -940,7 +944,7 @@ public class Functions { return DescriptorVisibilityFilter.apply(job, JobPropertyDescriptor.getPropertyDescriptors(job.getClass())); } - public static List> getBuildWrapperDescriptors(AbstractProject project) { + public static List> getBuildWrapperDescriptors(AbstractProject project) { return BuildWrappers.getFor(project); } @@ -952,15 +956,15 @@ public class Functions { return AuthorizationStrategy.all(); } - public static List> getBuilderDescriptors(AbstractProject project) { + public static List> getBuilderDescriptors(AbstractProject project) { return BuildStepDescriptor.filter(Builder.all(), project.getClass()); } - public static List> getPublisherDescriptors(AbstractProject project) { + public static List> getPublisherDescriptors(AbstractProject project) { return BuildStepDescriptor.filter(Publisher.all(), project.getClass()); } - public static List> getSCMDescriptors(AbstractProject project) { + public static List> getSCMDescriptors(AbstractProject project) { return SCM._for((Job) project); } @@ -1062,7 +1066,7 @@ public class Functions { for (ExtensionComponent c : exts.getComponents()) { Descriptor d = c.getInstance(); - if (d.getGlobalConfigPage()==null) continue; + if (d.getGlobalConfigPage() == null) continue; if (!Jenkins.get().hasPermission(d.getRequiredGlobalConfigPagePermission())) { continue; @@ -1077,7 +1081,7 @@ public class Functions { List answer = new ArrayList<>(r.size()); for (Tag d : r) answer.add(d.d); - return DescriptorVisibilityFilter.apply(Jenkins.get(),answer); + return DescriptorVisibilityFilter.apply(Jenkins.get(), answer); } /** @@ -1103,7 +1107,7 @@ public class Functions { for (ExtensionComponent c : exts.getComponents()) { Descriptor d = c.getInstance(); - if (d.getGlobalConfigPage()==null) continue; + if (d.getGlobalConfigPage() == null) continue; if (predicate.test(d)) { r.add(new Tag(c.ordinal(), d)); @@ -1114,7 +1118,7 @@ public class Functions { List answer = new ArrayList<>(r.size()); for (Tag d : r) answer.add(d.d); - return DescriptorVisibilityFilter.apply(Jenkins.get(),answer); + return DescriptorVisibilityFilter.apply(Jenkins.get(), answer); } /** @@ -1184,7 +1188,7 @@ public class Functions { if (ac != null) { return hasAnyPermission(ac, permissions); } - + return hasAnyPermission(Jenkins.get(), permissions); } } @@ -1219,7 +1223,7 @@ public class Functions { checkAnyPermission((AccessControlled) object, permissions); else { List ancs = Stapler.getCurrentRequest().getAncestors(); - for(Ancestor anc : Iterators.reverse(ancs)) { + for (Ancestor anc : Iterators.reverse(ancs)) { Object o = anc.getObject(); if (o instanceof AccessControlled) { checkAnyPermission((AccessControlled) o, permissions); @@ -1243,14 +1247,14 @@ public class Functions { private StringBuilder buildSuperclassHierarchy(Class c, StringBuilder buf) { Class sc = c.getSuperclass(); - if (sc!=null) buildSuperclassHierarchy(sc,buf).append(':'); + if (sc != null) buildSuperclassHierarchy(sc, buf).append(':'); return buf.append(c.getName()); } @Override public int compareTo(Tag that) { int r = Double.compare(that.ordinal, this.ordinal); - if (r!=0) return r; // descending for ordinal by reversing the order for compare + if (r != 0) return r; // descending for ordinal by reversing the order for compare return this.hierarchy.compareTo(that.hierarchy); } } @@ -1258,13 +1262,14 @@ public class Functions { * Computes the path to the icon of the given action * from the context path. */ + public static String getIconFilePath(Action a) { String name = a.getIconFileName(); - if (name==null) return null; + if (name == null) return null; if (name.startsWith("/")) return name.substring(1); else - return "images/24x24/"+name; + return "images/24x24/" + name; } /** @@ -1272,70 +1277,70 @@ public class Functions { * but handle null gracefully. */ public static int size2(Object o) throws Exception { - if(o==null) return 0; - return ASTSizeFunction.sizeOf(o,Introspector.getUberspect()); + if (o == null) return 0; + return ASTSizeFunction.sizeOf(o, Introspector.getUberspect()); } /** * Computes the relative path from the current page to the given item. */ public static String getRelativeLinkTo(Item p) { - Map ancestors = new HashMap<>(); - View view=null; + Map ancestors = new HashMap<>(); + View view = null; StaplerRequest request = Stapler.getCurrentRequest(); - for( Ancestor a : request.getAncestors() ) { - ancestors.put(a.getObject(),a.getRelativePath()); - if(a.getObject() instanceof View) + for (Ancestor a : request.getAncestors()) { + ancestors.put(a.getObject(), a.getRelativePath()); + if (a.getObject() instanceof View) view = (View) a.getObject(); } String path = ancestors.get(p); - if(path!=null) { + if (path != null) { return normalizeURI(path + '/'); } - Item i=p; + Item i = p; String url = ""; - while(true) { + while (true) { ItemGroup ig = i.getParent(); - url = i.getShortUrl()+url; + url = i.getShortUrl() + url; - if(ig== Jenkins.get() || (view != null && ig == view.getOwner().getItemGroup())) { + if (ig == Jenkins.get() || (view != null && ig == view.getOwner().getItemGroup())) { assert i instanceof TopLevelItem; if (view != null) { // assume p and the current page belong to the same view, so return a relative path // (even if they did not, View.getItem does not by default verify ownership) - return normalizeURI(ancestors.get(view)+'/'+url); + return normalizeURI(ancestors.get(view) + '/' + url); } else { // otherwise return a path from the root Hudson - return normalizeURI(request.getContextPath()+'/'+p.getUrl()); + return normalizeURI(request.getContextPath() + '/' + p.getUrl()); } } path = ancestors.get(ig); - if(path!=null) { - return normalizeURI(path+'/'+url); + if (path != null) { + return normalizeURI(path + '/' + url); } assert ig instanceof Item; // if not, ig must have been the Hudson instance i = (Item) ig; } } - + private static String normalizeURI(String uri) { return URI.create(uri).normalize().toString(); } - + /** * Gets all the {@link TopLevelItem}s recursively in the {@link ItemGroup} tree. - * + * * @since 1.512 */ public static List getAllTopLevelItems(ItemGroup root) { return root.getAllItems(TopLevelItem.class); } - + /** * Gets the relative name or display name to the given item from the specified group. * @@ -1354,41 +1359,41 @@ public class Functions { if (p == null) return null; if (g == null) return useDisplayName ? p.getFullDisplayName() : p.getFullName(); String separationString = useDisplayName ? " » " : "/"; - + // first list up all the parents - Map parents = new HashMap<>(); - int depth=0; - while (g!=null) { + Map parents = new HashMap<>(); + int depth = 0; + while (g != null) { parents.put(g, depth++); if (g instanceof Item) - g = ((Item)g).getParent(); + g = ((Item) g).getParent(); else g = null; } StringBuilder buf = new StringBuilder(); - Item i=p; + Item i = p; while (true) { - if (buf.length()>0) buf.insert(0,separationString); - buf.insert(0,useDisplayName ? i.getDisplayName() : i.getName()); + if (buf.length() > 0) buf.insert(0, separationString); + buf.insert(0, useDisplayName ? i.getDisplayName() : i.getName()); ItemGroup gr = i.getParent(); Integer d = parents.get(gr); - if (d!=null) { - for (int j=d; j>0; j--) { - buf.insert(0,separationString); - buf.insert(0,".."); + if (d != null) { + for (int j = d; j > 0; j--) { + buf.insert(0, separationString); + buf.insert(0, ".."); } return buf.toString(); } if (gr instanceof Item) - i = (Item)gr; + i = (Item) gr; else // Parent is a group, but not an item return null; } } - + /** * Gets the name to the given item relative to given group. * @@ -1403,9 +1408,9 @@ public class Functions { @Nullable public static String getRelativeNameFrom(@CheckForNull Item p, @CheckForNull ItemGroup g) { return getRelativeNameFrom(p, g, false); - } - - + } + + /** * Gets the relative display name to the given item from the specified group. * @@ -1422,15 +1427,15 @@ public class Functions { return getRelativeNameFrom(p, g, true); } - public static Map dumpAllThreads() { - Map sorted = new TreeMap<>(new ThreadSorter()); + public static Map dumpAllThreads() { + Map sorted = new TreeMap<>(new ThreadSorter()); sorted.putAll(Thread.getAllStackTraces()); return sorted; } public static ThreadInfo[] getThreadInfos() { ThreadMXBean mbean = ManagementFactory.getThreadMXBean(); - return mbean.dumpAllThreads(mbean.isObjectMonitorUsageSupported(),mbean.isSynchronizerUsageSupported()); + return mbean.dumpAllThreads(mbean.isObjectMonitorUsageSupported(), mbean.isSynchronizerUsageSupported()); } public static ThreadGroupMap sortThreadsAndGetGroupMap(ThreadInfo[] list) { @@ -1441,12 +1446,12 @@ public class Functions { // Common code for sorting Threads/ThreadInfos by ThreadGroup private static class ThreadSorterBase { - protected Map map = new HashMap<>(); + protected Map map = new HashMap<>(); ThreadSorterBase() { ThreadGroup tg = Thread.currentThread().getThreadGroup(); while (tg.getParent() != null) tg = tg.getParent(); - Thread[] threads = new Thread[tg.activeCount()*2]; + Thread[] threads = new Thread[tg.activeCount() * 2]; int threadsLen = tg.enumerate(threads, true); for (int i = 0; i < threadsLen; i++) { ThreadGroup group = threads[i].getThreadGroup(); @@ -1456,8 +1461,8 @@ public class Functions { protected int compare(long idA, long idB) { String tga = map.get(idA), tgb = map.get(idB); - int result = (tga!=null?-1:0) + (tgb!=null?1:0); // Will be non-zero if only one is null - if (result==0 && tga!=null) + int result = (tga != null ? -1 : 0) + (tgb != null ? 1 : 0); // Will be non-zero if only one is null + if (result == 0 && tga != null) result = tga.compareToIgnoreCase(tgb); return result; } @@ -1526,7 +1531,7 @@ public class Functions { } sb.append('\n'); StackTraceElement[] stackTrace = ti.getStackTrace(); - for (int i=0; i < stackTrace.length; i++) { + for (int i = 0; i < stackTrace.length; i++) { StackTraceElement ste = stackTrace[i]; sb.append("\tat ").append(ste); sb.append('\n'); @@ -1574,9 +1579,9 @@ public class Functions { public static String jsStringEscape(String s) { if (s == null) return null; StringBuilder buf = new StringBuilder(); - for( int i=0; i T defaulted(T value, T defaultValue) { - return value!=null ? value : defaultValue; + return value != null ? value : defaultValue; } /** @@ -1669,6 +1674,7 @@ public class Functions { doPrintStackTrace(s, t, null, "", new HashSet<>()); return s.toString(); } + private static void doPrintStackTrace(@NonNull StringBuilder s, @NonNull Throwable t, @CheckForNull Throwable higher, @NonNull String prefix, @NonNull Set encountered) { if (!encountered.add(t)) { s.append("\n"); @@ -1741,8 +1747,8 @@ public class Functions { * Minimum 5 rows. */ public static int determineRows(String s) { - if(s==null) return 5; - return Math.max(5,LINE_END.split(s).length); + if (s == null) return 5; + return Math.max(5, LINE_END.split(s).length); } /** @@ -1776,7 +1782,7 @@ public class Functions { */ public static JellyContext getCurrentJellyContext() { JellyContext context = ExpressionFactory2.CURRENT_CONTEXT.get(); - assert context!=null; + assert context != null; return context; } @@ -1796,8 +1802,8 @@ public class Functions { * Warning: do not call this with a {@link RunList}, or you will break lazy loading! */ public static List subList(List base, int maxSize) { - if(maxSize0) { - if (buf.charAt(buf.length()-1)!='/') + if (buf.length() > 0) { + if (buf.charAt(buf.length() - 1) != '/') buf.append('/'); - if (s.charAt(0)=='/') s=s.substring(1); + if (s.charAt(0) == '/') s = s.substring(1); } buf.append(s); } @@ -1826,9 +1832,9 @@ public class Functions { * * @return null in case the action should not be presented to the user. */ - public static @CheckForNull String getActionUrl(String itUrl,Action action) { + public static @CheckForNull String getActionUrl(String itUrl, Action action) { String urlName = action.getUrlName(); - if(urlName==null) return null; // Should not be displayed + if (urlName == null) return null; // Should not be displayed try { if (new URI(urlName).isAbsolute()) { return urlName; @@ -1837,11 +1843,11 @@ public class Functions { Logger.getLogger(Functions.class.getName()).log(Level.WARNING, "Failed to parse URL for {0}: {1}", new Object[] {action, x}); return null; } - if(urlName.startsWith("/")) - return joinPath(Stapler.getCurrentRequest().getContextPath(),urlName); + if (urlName.startsWith("/")) + return joinPath(Stapler.getCurrentRequest().getContextPath(), urlName); else // relative URL name - return joinPath(Stapler.getCurrentRequest().getContextPath()+'/'+itUrl,urlName); + return joinPath(Stapler.getCurrentRequest().getContextPath() + '/' + itUrl, urlName); } /** @@ -1852,12 +1858,12 @@ public class Functions { public static String toEmailSafeString(String projectName) { // TODO: escape non-ASCII characters StringBuilder buf = new StringBuilder(projectName.length()); - for( int i=0; i=0) + if (('a' <= ch && ch <= 'z') + || ('A' <= ch && ch <= 'Z') + || ('0' <= ch && ch <= '9') + || "-_.".indexOf(ch) >= 0) buf.append(ch); else buf.append('_'); // escape @@ -1876,9 +1882,9 @@ public class Functions { // This makes it work correctly when Hudson runs behind a reverse proxy. String url = Jenkins.get().getRootUrl(); try { - if(url!=null) { + if (url != null) { String host = new URL(url).getHost(); - if(host!=null) + if (host != null) return host; } } catch (MalformedURLException e) { @@ -1895,7 +1901,7 @@ public class Functions { */ @Deprecated public String getCheckUrl(String userDefined, Object descriptor, String field) { - if(userDefined!=null || field==null) return userDefined; + if (userDefined != null || field == null) return userDefined; if (descriptor instanceof Descriptor) { Descriptor d = (Descriptor) descriptor; return d.getCheckUrl(field); @@ -1908,13 +1914,13 @@ public class Functions { * @since 1.528 */ public void calcCheckUrl(Map attributes, String userDefined, Object descriptor, String field) { - if(userDefined!=null || field==null) return; + if (userDefined != null || field == null) return; if (descriptor instanceof Descriptor) { Descriptor d = (Descriptor) descriptor; CheckMethod m = d.getCheckMethod(field); - attributes.put("checkUrl",m.toStemUrl()); - attributes.put("checkDependsOn",m.getDependsOn()); + attributes.put("checkUrl", m.toStemUrl()); + attributes.put("checkDependsOn", m.getDependsOn()); } } @@ -1926,8 +1932,8 @@ public class Functions { public boolean hyperlinkMatchesCurrentPage(String href) throws UnsupportedEncodingException { String url = Stapler.getCurrentRequest().getRequestURL().toString(); if (href == null || href.length() <= 1) return ".".equals(href) && url.endsWith("/"); - url = URLDecoder.decode(url,"UTF-8"); - href = URLDecoder.decode(href,"UTF-8"); + url = URLDecoder.decode(url, "UTF-8"); + href = URLDecoder.decode(href, "UTF-8"); if (url.endsWith("/")) url = url.substring(0, url.length() - 1); if (href.endsWith("/")) href = href.substring(0, href.length() - 1); @@ -1943,13 +1949,14 @@ public class Functions { */ public static List getPageDecorators() { // this method may be called to render start up errors, at which point Hudson doesn't exist yet. see JENKINS-3608 - if(Jenkins.getInstanceOrNull()==null) return Collections.emptyList(); + if (Jenkins.getInstanceOrNull() == null) return Collections.emptyList(); return PageDecorator.all(); } /** * Gets only one {@link SimplePageDecorator}. * @since 2.128 */ + public static SimplePageDecorator getSimplePageDecorator() { return SimplePageDecorator.first(); } @@ -1966,8 +1973,8 @@ public class Functions { * Prepend a prefix only when there's the specified body. */ public String prepend(String prefix, String body) { - if(body!=null && body.length()>0) - return prefix+body; + if (body != null && body.length() > 0) + return prefix + body; return body; } @@ -1992,11 +1999,11 @@ public class Functions { } public static Locale getCurrentLocale() { - Locale locale=null; + Locale locale = null; StaplerRequest req = Stapler.getCurrentRequest(); - if(req!=null) + if (req != null) locale = req.getLocale(); - if(locale==null) + if (locale == null) locale = Locale.getDefault(); return locale; } @@ -2016,7 +2023,7 @@ public class Functions { buf.append(""); } for (ConsoleAnnotationDescriptor d : ConsoleAnnotationDescriptor.all()) { - String path = cp+"/descriptor/"+d.clazz.getName(); + String path = cp + "/descriptor/" + d.clazz.getName(); if (d.hasScript()) buf.append(""); if (d.hasStylesheet()) @@ -2113,9 +2120,9 @@ public class Functions { } public List filterDescriptors(Object context, Iterable descriptors) { - return DescriptorVisibilityFilter.apply(context,descriptors); + return DescriptorVisibilityFilter.apply(context, descriptors); } - + /** * Returns true if we are running unit tests. */ @@ -2154,13 +2161,13 @@ public class Functions { } public static String createRenderOnDemandProxy(JellyContext context, String attributesToCapture) { - return Stapler.getCurrentRequest().createJavaScriptProxy(new RenderOnDemandClosure(context,attributesToCapture)); + return Stapler.getCurrentRequest().createJavaScriptProxy(new RenderOnDemandClosure(context, attributesToCapture)); } public static String getCurrentDescriptorByNameUrl() { return Descriptor.getCurrentDescriptorByNameUrl(); } - + public static String setCurrentDescriptorByNameUrl(String value) { String o = getCurrentDescriptorByNameUrl(); Stapler.getCurrentRequest().setAttribute("currentDescriptorByNameUrl", value); @@ -2185,7 +2192,7 @@ public class Functions { * Used for arguments to internationalized expressions to avoid escape */ public static Object rawHtml(Object o) { - return o==null ? null : new RawHtmlArgument(o); + return o == null ? null : new RawHtmlArgument(o); } public static ArrayList getCLICommands() { @@ -2211,30 +2218,30 @@ public class Functions { */ @Deprecated public String getUserAvatar(User user, String avatarSize) { - return getAvatar(user,avatarSize); + return getAvatar(user, avatarSize); } - - + + /** * Returns human readable information about file size - * + * * @param size file size in bytes * @return file size in appropriate unit */ - public static String humanReadableByteSize(long size){ + public static String humanReadableByteSize(long size) { String measure = "B"; - if(size < 1024){ + if (size < 1024) { return size + " " + measure; } double number = size; - if(number>=1024){ - number = number/1024; + if (number >= 1024) { + number = number / 1024; measure = "KB"; - if(number>=1024){ - number = number/1024; + if (number >= 1024) { + number = number / 1024; measure = "MB"; - if(number>=1024){ - number=number/1024; + if (number >= 1024) { + number = number / 1024; measure = "GB"; } } @@ -2267,8 +2274,8 @@ public class Functions { */ public static void advertiseHeaders(HttpServletResponse rsp) { Jenkins j = Jenkins.getInstanceOrNull(); - if (j!=null) { - rsp.setHeader("X-Hudson","1.395"); + if (j != null) { + rsp.setHeader("X-Hudson", "1.395"); rsp.setHeader("X-Jenkins", Jenkins.VERSION); rsp.setHeader("X-Jenkins-Session", Jenkins.SESSION_HASH); } diff --git a/core/src/main/java/hudson/Indenter.java b/core/src/main/java/hudson/Indenter.java index aa4348b57a9bbc54b2a5b89fe272e4ed663562c5..90a1d403e225972a32fc3f21c5d3f190571d0d97 100644 --- a/core/src/main/java/hudson/Indenter.java +++ b/core/src/main/java/hudson/Indenter.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson; import hudson.model.Job; @@ -34,12 +35,12 @@ public abstract class Indenter { protected abstract int getNestLevel(J job); public final String getCss(J job) { - return "padding-left: "+getNestLevel(job)*2+"em"; + return "padding-left: " + getNestLevel(job) * 2 + "em"; } public final String getRelativeShift(J job) { int i = getNestLevel(job); - if(i==0) return null; - return "position:relative; left: "+ i *2+"em"; + if (i == 0) return null; + return "position:relative; left: " + i * 2 + "em"; } } diff --git a/core/src/main/java/hudson/Launcher.java b/core/src/main/java/hudson/Launcher.java index 5b67208c5c93793bc0f12276f828f12849ca88dd..6ea7375ff5a95060e266ddc3618f79cba222be5b 100644 --- a/core/src/main/java/hudson/Launcher.java +++ b/core/src/main/java/hudson/Launcher.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson; import static org.apache.commons.io.output.NullOutputStream.NULL_OUTPUT_STREAM; @@ -119,7 +120,7 @@ public abstract class Launcher { * @since 2.246 */ @Restricted(Beta.class) - public void prepareFilterRules(@CheckForNull Run run, @NonNull EnvVarsFilterableBuilder builder){ + public void prepareFilterRules(@CheckForNull Run run, @NonNull EnvVarsFilterableBuilder builder) { List specificRuleList = builder.buildEnvVarsFilterRules(); EnvVarsFilterRuleWrapper ruleWrapper = EnvVarsFilterRuleWrapper.createRuleWrapper(run, builder, this, specificRuleList); this.setEnvVarsFilterRuleWrapper(ruleWrapper); @@ -173,8 +174,8 @@ public abstract class Launcher { @Deprecated @CheckForNull public Computer getComputer() { - for( Computer c : Jenkins.get().getComputers() ) - if(c.getChannel()==channel) + for (Computer c : Jenkins.get().getComputers()) + if (c.getChannel() == channel) return c; return null; } @@ -486,7 +487,7 @@ public abstract class Launcher { * @since 2.246 */ @Restricted(Beta.class) - public ProcStarter buildStep(EnvVarsFilterableBuilder envVarsFilterableBuilder){ + public ProcStarter buildStep(EnvVarsFilterableBuilder envVarsFilterableBuilder) { this.envVarsFilterableBuilder = envVarsFilterableBuilder; return this; } @@ -571,8 +572,8 @@ public abstract class Launcher { * Use {@link #launch()} and its associated builder pattern */ @Deprecated - public final Proc launch(String cmd, Map env, OutputStream out, FilePath workDir) throws IOException { - return launch(cmd,Util.mapToEnv(env),out,workDir); + public final Proc launch(String cmd, Map env, OutputStream out, FilePath workDir) throws IOException { + return launch(cmd, Util.mapToEnv(env), out, workDir); } /** @@ -642,8 +643,8 @@ public abstract class Launcher { * Use {@link #launch()} and its associated builder pattern */ @Deprecated - public final Proc launch(String cmd,String[] env,OutputStream out, FilePath workDir) throws IOException { - return launch(Util.tokenize(cmd),env,out,workDir); + public final Proc launch(String cmd, String[] env, OutputStream out, FilePath workDir) throws IOException { + return launch(Util.tokenize(cmd), env, out, workDir); } /** @@ -775,19 +776,19 @@ public abstract class Launcher { * becomes the "current" process), these variables will be also set. */ public abstract Channel launchChannel(@NonNull String[] cmd, @NonNull OutputStream out, - @CheckForNull FilePath workDir, @NonNull Map envVars) throws IOException, InterruptedException; + @CheckForNull FilePath workDir, @NonNull Map envVars) throws IOException, InterruptedException; /** * Returns true if this {@link Launcher} is going to launch on Unix. */ public boolean isUnix() { - return File.pathSeparatorChar==':'; + return File.pathSeparatorChar == ':'; } /** * Calls {@link ProcessTree#killAll(Map)} to kill processes. */ - public abstract void kill(Map modelEnvVars) throws IOException, InterruptedException; + public abstract void kill(Map modelEnvVars) throws IOException, InterruptedException; /** * Prints out the command line to the listener so that users know what we are doing. @@ -796,7 +797,7 @@ public abstract class Launcher { StringBuilder buf = new StringBuilder(); if (workDir != null) { buf.append('['); - if(showFullPath) + if (showFullPath) buf.append(workDir.getRemote()); else buf.append(workDir.getRemote().replaceFirst("^.+[/\\\\]", "")); @@ -805,8 +806,8 @@ public abstract class Launcher { buf.append('$'); for (String c : cmd) { buf.append(' '); - if(c.indexOf(' ')>=0) { - if(c.indexOf('"')>=0) + if (c.indexOf(' ') >= 0) { + if (c.indexOf('"') >= 0) buf.append('\'').append(c).append('\''); else buf.append('"').append(c).append('"'); @@ -827,8 +828,8 @@ public abstract class Launcher { * @param workDir The work dir. */ protected final void maskedPrintCommandLine(@NonNull List cmd, @CheckForNull boolean[] mask, @CheckForNull FilePath workDir) { - if(mask==null) { - printCommandLine(cmd.toArray(new String[0]),workDir); + if (mask == null) { + printCommandLine(cmd.toArray(new String[0]), workDir); return; } @@ -845,7 +846,7 @@ public abstract class Launcher { } protected final void maskedPrintCommandLine(@NonNull String[] cmd, @NonNull boolean[] mask, @CheckForNull FilePath workDir) { - maskedPrintCommandLine(Arrays.asList(cmd),mask,workDir); + maskedPrintCommandLine(Arrays.asList(cmd), mask, workDir); } /** @@ -858,7 +859,7 @@ public abstract class Launcher { public final Launcher decorateFor(@NonNull Node node) { Launcher l = this; for (LauncherDecorator d : LauncherDecorator.all()) - l = d.decorate(l,node); + l = d.decorate(l, node); return l; } @@ -880,7 +881,7 @@ public abstract class Launcher { @Override public Proc launch(ProcStarter starter) throws IOException { - starter.commands.addAll(0,Arrays.asList(prefix)); + starter.commands.addAll(0, Arrays.asList(prefix)); boolean[] masks = starter.masks; if (masks != null) { starter.masks = prefix(masks); @@ -890,7 +891,7 @@ public abstract class Launcher { @Override public Channel launchChannel(String[] cmd, OutputStream out, FilePath workDir, Map envVars) throws IOException, InterruptedException { - return outer.launchChannel(prefix(cmd),out,workDir,envVars); + return outer.launchChannel(prefix(cmd), out, workDir, envVars); } @Override @@ -899,15 +900,15 @@ public abstract class Launcher { } private String[] prefix(@NonNull String[] args) { - String[] newArgs = new String[args.length+prefix.length]; - System.arraycopy(prefix,0,newArgs,0,prefix.length); - System.arraycopy(args,0,newArgs,prefix.length,args.length); + String[] newArgs = new String[args.length + prefix.length]; + System.arraycopy(prefix, 0, newArgs, 0, prefix.length); + System.arraycopy(args, 0, newArgs, prefix.length, args.length); return newArgs; } private boolean[] prefix(@NonNull boolean[] args) { - boolean[] newArgs = new boolean[args.length+prefix.length]; - System.arraycopy(args,0,newArgs,prefix.length,args.length); + boolean[] newArgs = new boolean[args.length + prefix.length]; + System.arraycopy(args, 0, newArgs, prefix.length, args.length); return newArgs; } }; @@ -935,7 +936,7 @@ public abstract class Launcher { @Override public Proc launch(ProcStarter starter) throws IOException { EnvVars e = new EnvVars(env); - if (starter.envs!=null) { + if (starter.envs != null) { for (String env : starter.envs) { e.addLine(env); } @@ -948,7 +949,7 @@ public abstract class Launcher { public Channel launchChannel(String[] cmd, OutputStream out, FilePath workDir, Map envVars) throws IOException, InterruptedException { EnvVars e = new EnvVars(env); e.putAll(envVars); - return outer.launchChannel(cmd,out,workDir,e); + return outer.launchChannel(cmd, out, workDir, e); } @Override @@ -986,27 +987,27 @@ public abstract class Launcher { // replace variables in command line String[] jobCmd = new String[ps.commands.size()]; - for ( int idx = 0 ; idx < jobCmd.length; idx++ ) + for (int idx = 0; idx < jobCmd.length; idx++) jobCmd[idx] = jobEnv.expand(ps.commands.get(idx)); return new LocalProc(jobCmd, Util.mapToEnv(jobEnv), - ps.reverseStdin ?LocalProc.SELFPUMP_INPUT:ps.stdin, - ps.reverseStdout?LocalProc.SELFPUMP_OUTPUT:ps.stdout, - ps.reverseStderr?LocalProc.SELFPUMP_OUTPUT:ps.stderr, + ps.reverseStdin ? LocalProc.SELFPUMP_INPUT : ps.stdin, + ps.reverseStdout ? LocalProc.SELFPUMP_OUTPUT : ps.stdout, + ps.reverseStderr ? LocalProc.SELFPUMP_OUTPUT : ps.stderr, toFile(ps.pwd)); } private File toFile(FilePath f) { - return f==null ? null : new File(f.getRemote()); + return f == null ? null : new File(f.getRemote()); } @Override - public Channel launchChannel(String[] cmd, OutputStream out, FilePath workDir, Map envVars) throws IOException { + public Channel launchChannel(String[] cmd, OutputStream out, FilePath workDir, Map envVars) throws IOException { printCommandLine(cmd, workDir); ProcessBuilder pb = new ProcessBuilder(cmd); pb.directory(toFile(workDir)); - if (envVars!=null) pb.environment().putAll(envVars); + if (envVars != null) pb.environment().putAll(envVars); return launchChannel(out, pb); } @@ -1026,10 +1027,10 @@ public abstract class Launcher { final Process proc = pb.start(); - final Thread t2 = new StreamCopyThread(pb.command()+": stderr copier", proc.getErrorStream(), out); + final Thread t2 = new StreamCopyThread(pb.command() + ": stderr copier", proc.getErrorStream(), out); t2.start(); - return new Channel("locally launched channel on "+ pb.command(), + return new Channel("locally launched channel on " + pb.command(), Computer.threadPoolForRemoting, proc.getInputStream(), proc.getOutputStream(), out) { /** @@ -1040,7 +1041,7 @@ public abstract class Launcher { super.terminate(e); ProcessTree pt = ProcessTree.get(); try { - pt.killAll(proc,cookie); + pt.killAll(proc, cookie); } catch (InterruptedException x) { LOGGER.log(Level.INFO, "Interrupted", x); } @@ -1109,11 +1110,11 @@ public abstract class Launcher { @Override public Proc launch(ProcStarter ps) throws IOException { final OutputStream out = ps.stdout == null || ps.stdoutListener != null ? null : new RemoteOutputStream(new CloseProofOutputStream(ps.stdout)); - final OutputStream err = ps.stderr==null ? null : new RemoteOutputStream(new CloseProofOutputStream(ps.stderr)); + final OutputStream err = ps.stderr == null ? null : new RemoteOutputStream(new CloseProofOutputStream(ps.stderr)); final InputStream in = ps.stdin == null || ps.stdin == NULL_INPUT_STREAM ? null : new RemoteInputStream(ps.stdin, false); final FilePath psPwd = ps.pwd; - final String workDir = psPwd==null ? null : psPwd.getRemote(); + final String workDir = psPwd == null ? null : psPwd.getRemote(); try { RemoteLaunchCallable remote = new RemoteLaunchCallable(ps.commands, ps.masks, ps.envs, in, ps.reverseStdin, out, ps.reverseStdout, err, ps.reverseStderr, ps.quiet, workDir, listener, ps.stdoutListener); @@ -1122,20 +1123,20 @@ public abstract class Launcher { envVarsFilterRuleWrapper = null; return new ProcImpl(getChannel().call(remote)); } catch (InterruptedException e) { - throw (IOException)new InterruptedIOException().initCause(e); + throw (IOException) new InterruptedIOException().initCause(e); } } @Override - public Channel launchChannel(String[] cmd, OutputStream err, FilePath _workDir, Map envOverrides) throws IOException, InterruptedException { + public Channel launchChannel(String[] cmd, OutputStream err, FilePath _workDir, Map envOverrides) throws IOException, InterruptedException { printCommandLine(cmd, _workDir); Pipe out = Pipe.createRemoteToLocal(); - final String workDir = _workDir==null ? null : _workDir.getRemote(); + final String workDir = _workDir == null ? null : _workDir.getRemote(); OutputStream os = getChannel().call(new RemoteChannelLaunchCallable(cmd, out, err, workDir, envOverrides)); - return new Channel("remotely launched channel on "+channel, + return new Channel("remotely launched channel on " + channel, Computer.threadPoolForRemoting, out.getIn(), new BufferedOutputStream(os)); } @@ -1145,7 +1146,7 @@ public abstract class Launcher { } @Override - public void kill(final Map modelEnvVars) throws IOException, InterruptedException { + public void kill(final Map modelEnvVars) throws IOException, InterruptedException { getChannel().call(new KillTask(modelEnvVars)); } @@ -1154,7 +1155,7 @@ public abstract class Launcher { return "RemoteLauncher[" + getChannel() + "]"; } - private static final class KillTask extends MasterToSlaveCallable { + private static final class KillTask extends MasterToSlaveCallable { private final Map modelEnvVars; KillTask(Map modelEnvVars) { @@ -1316,7 +1317,7 @@ public abstract class Launcher { public static class IOTriplet implements Serializable { @CheckForNull - InputStream stdout,stderr; + InputStream stdout, stderr; @CheckForNull OutputStream stdin; private static final long serialVersionUID = 1L; @@ -1324,16 +1325,19 @@ public abstract class Launcher { /** * Remoting interface of a remote process */ + public interface RemoteProcess { int join() throws InterruptedException, IOException; + void kill() throws IOException, InterruptedException; + boolean isAlive() throws IOException, InterruptedException; @NonNull IOTriplet getIOtriplet(); } - private static class RemoteLaunchCallable extends MasterToSlaveCallable { + private static class RemoteLaunchCallable extends MasterToSlaveCallable { private final @NonNull List cmd; private final @CheckForNull boolean[] masks; private final @CheckForNull String[] env; @@ -1386,14 +1390,14 @@ public abstract class Launcher { } else { ps.stdout(out); } - if(workDir!=null) ps.pwd(workDir); + if (workDir != null) ps.pwd(workDir); if (reverseStdin) ps.writeStdin(); if (reverseStdout) ps.readStdout(); if (reverseStderr) ps.readStderr(); final Proc p = ps.start(); - return channel.export(RemoteProcess.class,new RemoteProcess() { + return channel.export(RemoteProcess.class, new RemoteProcess() { @Override public int join() throws InterruptedException, IOException { try { @@ -1436,7 +1440,7 @@ public abstract class Launcher { private static final long serialVersionUID = 1L; } - private static class RemoteChannelLaunchCallable extends MasterToSlaveCallable { + private static class RemoteChannelLaunchCallable extends MasterToSlaveCallable { @NonNull private final String[] cmd; @NonNull @@ -1446,10 +1450,10 @@ public abstract class Launcher { @NonNull private final OutputStream err; @NonNull - private final Map envOverrides; + private final Map envOverrides; RemoteChannelLaunchCallable(@NonNull String[] cmd, @NonNull Pipe out, @NonNull OutputStream err, - @CheckForNull String workDir, @NonNull Map envOverrides) { + @CheckForNull String workDir, @NonNull Map envOverrides) { this.cmd = cmd; this.out = out; this.err = new RemoteOutputStream(err); @@ -1464,9 +1468,9 @@ public abstract class Launcher { workDir == null ? null : new File(workDir)); List cmdLines = Arrays.asList(cmd); - new StreamCopyThread("stdin copier for remote agent on "+cmdLines, + new StreamCopyThread("stdin copier for remote agent on " + cmdLines, p.getInputStream(), out.getOut()).start(); - new StreamCopyThread("stderr copier for remote agent on "+cmdLines, + new StreamCopyThread("stderr copier for remote agent on " + cmdLines, p.getErrorStream(), err).start(); // TODO: don't we need to join? @@ -1483,10 +1487,10 @@ public abstract class Launcher { private static EnvVars inherit(@CheckForNull String[] env) { // convert String[] to Map first EnvVars m = new EnvVars(); - if(env!=null) { + if (env != null) { for (String e : env) { int index = e.indexOf('='); - m.put(e.substring(0,index), e.substring(index+1)); + m.put(e.substring(0, index), e.substring(index + 1)); } } // then do the inheritance @@ -1496,7 +1500,7 @@ public abstract class Launcher { /** * Expands the list of environment variables by inheriting current env variables. */ - private static EnvVars inherit(@NonNull Map overrides) { + private static EnvVars inherit(@NonNull Map overrides) { EnvVars m = new EnvVars(EnvVars.masterEnvVars); m.overrideExpandingAll(overrides); return m; diff --git a/core/src/main/java/hudson/LocalPluginManager.java b/core/src/main/java/hudson/LocalPluginManager.java index ede9554f5f4886ddf7f4e75da99156145ea3278b..d1fcfd678e3ad442e794eb9c82d56f15576b5847 100644 --- a/core/src/main/java/hudson/LocalPluginManager.java +++ b/core/src/main/java/hudson/LocalPluginManager.java @@ -46,7 +46,7 @@ public class LocalPluginManager extends PluginManager { * @param rootDir Jenkins home directory. */ public LocalPluginManager(@CheckForNull ServletContext context, @NonNull File rootDir) { - super(context, new File(rootDir,"plugins")); + super(context, new File(rootDir, "plugins")); } /** diff --git a/core/src/main/java/hudson/Lookup.java b/core/src/main/java/hudson/Lookup.java index b0b40ba89151d9d5a9f8a1a5e55c70b0c89f99c5..ba051f72a633c638e4ec61b76960abd190aad983 100644 --- a/core/src/main/java/hudson/Lookup.java +++ b/core/src/main/java/hudson/Lookup.java @@ -32,14 +32,14 @@ import java.util.concurrent.ConcurrentHashMap; * @author Kohsuke Kawaguchi */ public class Lookup { - private final ConcurrentHashMap data = new ConcurrentHashMap<>(); + private final ConcurrentHashMap data = new ConcurrentHashMap<>(); public T get(Class type) { return type.cast(data.get(type)); } public T set(Class type, T instance) { - return type.cast(data.put(type,instance)); + return type.cast(data.put(type, instance)); } /** @@ -51,7 +51,7 @@ public class Lookup { */ public T setIfNull(Class type, T instance) { Object o = data.putIfAbsent(type, instance); - if (o!=null) return type.cast(o); + if (o != null) return type.cast(o); return instance; } } diff --git a/core/src/main/java/hudson/Main.java b/core/src/main/java/hudson/Main.java index 8ae8dfcd76ed15dd0253d35d172fe75dc5638e58..625fef0c52ee88f5103110148c8816a09411a1bc 100644 --- a/core/src/main/java/hudson/Main.java +++ b/core/src/main/java/hudson/Main.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson; import com.thoughtworks.xstream.core.util.Base64Encoder; @@ -69,7 +70,7 @@ public class Main { /** @see #remotePost */ public static int run(String[] args) throws Exception { String home = getHudsonHome(); - if (home==null) { + if (home == null) { System.err.println("JENKINS_HOME is not set."); return -1; } @@ -83,7 +84,7 @@ public class Main { private static String getHudsonHome() { String home = EnvVars.masterEnvVars.get("JENKINS_HOME"); - if (home!=null) return home; + if (home != null) return home; return EnvVars.masterEnvVars.get("HUDSON_HOME"); } @@ -95,30 +96,30 @@ public class Main { String projectName = args[0]; String home = getHudsonHome(); - if(!home.endsWith("/")) home = home + '/'; // make sure it ends with '/' + if (!home.endsWith("/")) home = home + '/'; // make sure it ends with '/' // check for authentication info String auth = new URL(home).getUserInfo(); - if(auth != null) auth = "Basic " + new Base64Encoder().encode(auth.getBytes(StandardCharsets.UTF_8)); + if (auth != null) auth = "Basic " + new Base64Encoder().encode(auth.getBytes(StandardCharsets.UTF_8)); - {// check if the home is set correctly + { // check if the home is set correctly HttpURLConnection con = open(new URL(home)); if (auth != null) con.setRequestProperty("Authorization", auth); con.connect(); - if(con.getResponseCode()!=200 - || con.getHeaderField("X-Hudson")==null) { - System.err.println(home+" is not Hudson ("+con.getResponseMessage()+")"); + if (con.getResponseCode() != 200 + || con.getHeaderField("X-Hudson") == null) { + System.err.println(home + " is not Hudson (" + con.getResponseMessage() + ")"); return -1; } } URL jobURL = new URL(home + "job/" + Util.encode(projectName).replace("/", "/job/") + "/"); - {// check if the job name is correct + { // check if the job name is correct HttpURLConnection con = open(new URL(jobURL, "acceptBuildResult")); if (auth != null) con.setRequestProperty("Authorization", auth); con.connect(); - if(con.getResponseCode()!=200) { + if (con.getResponseCode() != 200) { System.err.println(jobURL + " is not a valid external job (" + con.getResponseCode() + " " + con.getResponseMessage() + ")"); return -1; } @@ -130,7 +131,7 @@ public class Main { HttpURLConnection con = open(new URL(home + "crumbIssuer/api/xml?xpath=concat(//crumbRequestField,\":\",//crumb)'")); if (auth != null) con.setRequestProperty("Authorization", auth); - String line = IOUtils.readFirstLine(con.getInputStream(),"UTF-8"); + String line = IOUtils.readFirstLine(con.getInputStream(), "UTF-8"); String[] components = line.split(":"); if (components.length == 2) { crumbField = components[0]; @@ -141,31 +142,31 @@ public class Main { } // write the output to a temporary file first. - File tmpFile = File.createTempFile("jenkins","log"); + File tmpFile = File.createTempFile("jenkins", "log"); try { int ret; try (OutputStream os = Files.newOutputStream(tmpFile.toPath()); Writer w = new OutputStreamWriter(os, StandardCharsets.UTF_8)) { w.write(""); - w.write(""); + w.write(""); w.flush(); // run the command long start = System.currentTimeMillis(); List cmd = new ArrayList<>(Arrays.asList(args).subList(1, args.length)); - Proc proc = new Proc.LocalProc(cmd.toArray(new String[0]),(String[])null,System.in, - new DualOutputStream(System.out,new EncodingStream(os))); + Proc proc = new Proc.LocalProc(cmd.toArray(new String[0]), (String[]) null, System.in, + new DualOutputStream(System.out, new EncodingStream(os))); ret = proc.join(); - w.write(""+ret+""+(System.currentTimeMillis()-start)+""); + w.write("" + ret + "" + (System.currentTimeMillis() - start) + ""); } catch (InvalidPathException e) { throw new IOException(e); } URL location = new URL(jobURL, "postBuildResult"); - while(true) { + while (true) { try { // start a remote connection HttpURLConnection con = open(location); @@ -175,7 +176,7 @@ public class Main { } con.setDoOutput(true); // this tells HttpURLConnection not to buffer the whole thing - con.setFixedLengthStreamingMode((int)tmpFile.length()); + con.setFixedLengthStreamingMode((int) tmpFile.length()); con.connect(); // send the data try (InputStream in = Files.newInputStream(tmpFile.toPath())) { @@ -184,13 +185,13 @@ public class Main { throw new IOException(e); } - if(con.getResponseCode()!=200) { + if (con.getResponseCode() != 200) { org.apache.commons.io.IOUtils.copy(con.getErrorStream(), System.err); } return ret; } catch (HttpRetryException e) { - if(e.getLocation()!=null) { + if (e.getLocation() != null) { // retry with the new location location = new URL(e.getLocation()); continue; @@ -208,7 +209,7 @@ public class Main { * Connects to the given HTTP URL and configure time out, to avoid infinite hang. */ private static HttpURLConnection open(URL url) throws IOException { - HttpURLConnection c = (HttpURLConnection)url.openConnection(); + HttpURLConnection c = (HttpURLConnection) url.openConnection(); c.setReadTimeout(TIMEOUT); c.setConnectTimeout(TIMEOUT); return c; @@ -225,10 +226,10 @@ public class Main { * This is also set if running inside {@code mvn hpi:run} since plugins parent POM 2.30. */ @SuppressFBWarnings(value = "MS_SHOULD_BE_FINAL", justification = "for debugging") - public static boolean isDevelopmentMode = SystemProperties.getBoolean(Main.class.getName()+".development"); + public static boolean isDevelopmentMode = SystemProperties.getBoolean(Main.class.getName() + ".development"); /** * Time out for socket connection to Hudson. */ - public static final int TIMEOUT = SystemProperties.getInteger(Main.class.getName()+".timeout",15000); + public static final int TIMEOUT = SystemProperties.getInteger(Main.class.getName() + ".timeout", 15000); } diff --git a/core/src/main/java/hudson/MarkupText.java b/core/src/main/java/hudson/MarkupText.java index 0317a7e1b0164f349d253559fbfb90000934b7bf..182565205ecfa373cc3d4ffe5506dca79adfba82 100644 --- a/core/src/main/java/hudson/MarkupText.java +++ b/core/src/main/java/hudson/MarkupText.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson; import java.util.ArrayList; @@ -66,7 +67,7 @@ public class MarkupText extends AbstractMarkupText { @Override public int compareTo(Tag that) { - return this.pos-that.pos; + return this.pos - that.pos; } } @@ -74,7 +75,7 @@ public class MarkupText extends AbstractMarkupText { * Represents a substring of a {@link MarkupText}. */ public final class SubText extends AbstractMarkupText { - private final int start,end; + private final int start, end; private final int[] groups; public SubText(Matcher m, int textOffset) { @@ -82,10 +83,10 @@ public class MarkupText extends AbstractMarkupText { end = m.end() + textOffset; int cnt = m.groupCount(); - groups = new int[cnt*2]; - for( int i=0; i…}. */ public void href(String url) { - addHyperlink(0,length(),url); + addHyperlink(0, length(), url); } /** @@ -146,8 +147,8 @@ public class MarkupText extends AbstractMarkupText { * groups captured by '(...)' in the regexp. */ public int start(int groupIndex) { - if(groupIndex==0) return start; - return groups[groupIndex*2-2]; + if (groupIndex == 0) return start; + return groups[groupIndex * 2 - 2]; } /** @@ -161,8 +162,8 @@ public class MarkupText extends AbstractMarkupText { * Gets the end index of the captured group within {@link MarkupText#getText()}. */ public int end(int groupIndex) { - if(groupIndex==0) return end; - return groups[groupIndex*2-1]; + if (groupIndex == 0) return end; + return groups[groupIndex * 2 - 1]; } /** @@ -176,9 +177,9 @@ public class MarkupText extends AbstractMarkupText { * Gets the text that represents the captured group. */ public String group(int groupIndex) { - if(start(groupIndex)==-1) + if (start(groupIndex) == -1) return null; - return text.substring(start(groupIndex),end(groupIndex)); + return text.substring(start(groupIndex), end(groupIndex)); } /** @@ -195,24 +196,24 @@ public class MarkupText extends AbstractMarkupText { public String replace(String s) { StringBuilder buf = new StringBuilder(s.length() + 10); - for( int i=0; i 9) { - buf.append('$').append(ch); + buf.append('$').append(ch); } else { - // add the group text - String group = group(groupId); - if (group != null) - buf.append(group); + // add the group text + String group = group(groupId); + if (group != null) + buf.append(group); } } else { @@ -226,7 +227,7 @@ public class MarkupText extends AbstractMarkupText { @Override protected SubText createSubText(Matcher m) { - return new SubText(m,start); + return new SubText(m, start); } } @@ -252,29 +253,29 @@ public class MarkupText extends AbstractMarkupText { */ @Override public SubText subText(int start, int end) { - return new SubText(start, end<0 ? text.length()+1+end : end); + return new SubText(start, end < 0 ? text.length() + 1 + end : end); } @Override - public void addMarkup( int startPos, int endPos, String startTag, String endTag ) { + public void addMarkup(int startPos, int endPos, String startTag, String endTag) { rangeCheck(startPos); rangeCheck(endPos); - if(startPos>endPos) throw new IndexOutOfBoundsException(); + if (startPos > endPos) throw new IndexOutOfBoundsException(); // when multiple tags are added to the same range, we want them to show up like // abc, not abc. Also, we'd like abcdef, // not abcdef. Do this by inserting them to different places. tags.add(new Tag(startPos, startTag)); - tags.add(0,new Tag(endPos,endTag)); + tags.add(0, new Tag(endPos, endTag)); } public void addMarkup(int pos, String tag) { rangeCheck(pos); - tags.add(new Tag(pos,tag)); + tags.add(new Tag(pos, tag)); } private void rangeCheck(int pos) { - if(pos<0 || pos>text.length()) + if (pos < 0 || pos > text.length()) throw new IndexOutOfBoundsException(); } @@ -298,8 +299,8 @@ public class MarkupText extends AbstractMarkupText { * If false, the escape is for the normal HTML, thus SP becomes &nbsp; and CR/LF becomes {@code
} */ public String toString(boolean preEscape) { - if(tags.isEmpty()) - return preEscape? Util.xmlEscape(text) : Util.escape(text); // the most common case + if (tags.isEmpty()) + return preEscape ? Util.xmlEscape(text) : Util.escape(text); // the most common case Collections.sort(tags); @@ -307,14 +308,14 @@ public class MarkupText extends AbstractMarkupText { int copied = 0; // # of chars already copied from text to buf for (Tag tag : tags) { - if (copied { */ public Permalink get(String id) { for (Permalink p : this) - if(p.getId().equals(id)) + if (p.getId().equals(id)) return p; return null; } @@ -63,7 +64,7 @@ public final class PermalinkList extends ArrayList { for (Permalink p : this) ids.add(p.getId()); String nearest = EditDistance.findNearest(id, ids); - if(nearest==null) return null; + if (nearest == null) return null; return get(nearest); } } diff --git a/core/src/main/java/hudson/Platform.java b/core/src/main/java/hudson/Platform.java index 2195f571aceec8d86f1c64313f6fd6d6d9a3a4cd..23ab0caa6653a7a36e43460320976067f41afc8b 100644 --- a/core/src/main/java/hudson/Platform.java +++ b/core/src/main/java/hudson/Platform.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson; import hudson.util.VersionNumber; @@ -36,10 +37,10 @@ import java.util.Locale; * @author Kohsuke Kawaguchi */ public enum Platform { - WINDOWS(';'),UNIX(':'); + WINDOWS(';'), UNIX(':'); /** - * The character that separates paths in environment variables like PATH and CLASSPATH. + * The character that separates paths in environment variables like PATH and CLASSPATH. * On Windows ';' and on Unix ':'. * * @see File#pathSeparator @@ -51,7 +52,7 @@ public enum Platform { } public static Platform current() { - if(File.pathSeparatorChar==':') return UNIX; + if (File.pathSeparatorChar == ':') return UNIX; return WINDOWS; } @@ -65,7 +66,7 @@ public enum Platform { */ public static boolean isSnowLeopardOrLater() { try { - return isDarwin() && new VersionNumber(System.getProperty("os.version")).compareTo(new VersionNumber("10.6"))>=0; + return isDarwin() && new VersionNumber(System.getProperty("os.version")).compareTo(new VersionNumber("10.6")) >= 0; } catch (IllegalArgumentException e) { // failed to parse the version return false; diff --git a/core/src/main/java/hudson/Plugin.java b/core/src/main/java/hudson/Plugin.java index 0942db8fd90d78018a35e46339340961367e359c..41eafeabf5455e808fabef36335e461a801a33a1 100644 --- a/core/src/main/java/hudson/Plugin.java +++ b/core/src/main/java/hudson/Plugin.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson; import com.thoughtworks.xstream.XStream; @@ -266,7 +267,7 @@ public abstract class Plugin implements Saveable, StaplerProxy { */ protected void load() throws IOException { XmlFile xml = getConfigXml(); - if(xml.exists()) + if (xml.exists()) xml.unmarshal(this); } @@ -277,7 +278,7 @@ public abstract class Plugin implements Saveable, StaplerProxy { */ @Override public void save() throws IOException { - if(BulkChange.contains(this)) return; + if (BulkChange.contains(this)) return; XmlFile config = getConfigXml(); config.write(this); SaveableListener.fireOnChange(this, config); @@ -294,7 +295,7 @@ public abstract class Plugin implements Saveable, StaplerProxy { */ protected XmlFile getConfigXml() { return new XmlFile(Jenkins.XSTREAM, - new File(Jenkins.get().getRootDir(),wrapper.getShortName()+".xml")); + new File(Jenkins.get().getRootDir(), wrapper.getShortName() + ".xml")); } @Override diff --git a/core/src/main/java/hudson/PluginFirstClassLoader.java b/core/src/main/java/hudson/PluginFirstClassLoader.java index 8aee057e7b39ce99bcaff8cd63292d6cc7b07fa9..a990ea329e5a5078176db077cd62afddb2cd1ec7 100644 --- a/core/src/main/java/hudson/PluginFirstClassLoader.java +++ b/core/src/main/java/hudson/PluginFirstClassLoader.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Olivier Lamy - * + * * 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 @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson; import java.io.File; @@ -49,47 +50,47 @@ public class PluginFirstClassLoader private List urls = new CopyOnWriteArrayList<>(); @Override - public void addPathFiles( Collection paths ) + public void addPathFiles(Collection paths) throws IOException { - for ( File f : paths ) + for (File f : paths) { - urls.add( f.toURI().toURL() ); - addPathFile( f ); + urls.add(f.toURI().toURL()); + addPathFile(f); } } /** * @return List of jar used by the plugin /WEB-INF/lib/*.jar and classes directory /WEB-INF/classes */ - public List getURLs() + public List getURLs() { return urls; } @Override - protected Enumeration findResources( String name, boolean skipParent ) + protected Enumeration findResources(String name, boolean skipParent) throws IOException { - return super.findResources( name, skipParent ); + return super.findResources(name, skipParent); } @Override - public Enumeration findResources( String name ) + public Enumeration findResources(String name) throws IOException { - return super.findResources( name ); + return super.findResources(name); } @Override - public URL getResource( String name ) + public URL getResource(String name) { - return super.getResource( name ); + return super.getResource(name); } @Override - public InputStream getResourceAsStream( String name ) + public InputStream getResourceAsStream(String name) { - return super.getResourceAsStream( name ); + return super.getResourceAsStream(name); } } diff --git a/core/src/main/java/hudson/PluginManager.java b/core/src/main/java/hudson/PluginManager.java index 9b9f3814652745b7757af27905761283c37bef7c..e13fb0605666f185993312459360d407ce03eb6c 100644 --- a/core/src/main/java/hudson/PluginManager.java +++ b/core/src/main/java/hudson/PluginManager.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson; import static hudson.init.InitMilestone.COMPLETED; @@ -207,7 +208,7 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas // Secure initialization CHECK_UPDATE_SLEEP_TIME_MILLIS = SystemProperties.getInteger(PluginManager.class.getName() + ".checkUpdateSleepTimeMillis", 1000); CHECK_UPDATE_ATTEMPTS = SystemProperties.getInteger(PluginManager.class.getName() + ".checkUpdateAttempts", 1); - } catch(RuntimeException e) { + } catch (RuntimeException e) { LOGGER.warning(String.format("There was an error initializing the PluginManager. Exception: %s", e)); } finally { CHECK_UPDATE_ATTEMPTS = CHECK_UPDATE_ATTEMPTS > 0 ? CHECK_UPDATE_ATTEMPTS : 1; @@ -244,7 +245,7 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas @NonNull Jenkins jenkins) throws ReflectiveOperationException { try { return doCreate(klass, jenkins); - } catch(NoSuchMethodException e) { + } catch (NoSuchMethodException e) { // Constructor not found. Will try the remaining ones. return null; } @@ -275,9 +276,9 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas } } LOGGER.log(WARNING, String.format("Provided custom plugin manager [%s] does not provide any of the suitable constructors. Using default.", pmClassName)); - } catch(ClassCastException e) { + } catch (ClassCastException e) { LOGGER.log(WARNING, String.format("Provided class [%s] does not extend PluginManager. Using default.", pmClassName)); - } catch(Exception e) { + } catch (Exception e) { LOGGER.log(WARNING, String.format("Unable to instantiate custom plugin manager [%s]. Using default.", pmClassName), e); } } @@ -360,7 +361,7 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas } catch (IOException e) { throw new UncheckedIOException(e); } - String workDir = SystemProperties.getString(PluginManager.class.getName()+".workDir"); + String workDir = SystemProperties.getString(PluginManager.class.getName() + ".workDir"); this.workDir = StringUtils.isBlank(workDir) ? null : new File(workDir); strategy = createPluginStrategy(); @@ -417,15 +418,15 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas } }); - requires(listUpPlugins).attains(PLUGINS_LISTED).add("Preparing plugins",new Executable() { + requires(listUpPlugins).attains(PLUGINS_LISTED).add("Preparing plugins", new Executable() { @Override public void run(Reactor session) throws Exception { // once we've listed plugins, we can fill in the reactor with plugin-specific initialization tasks TaskGraphBuilder g = new TaskGraphBuilder(); - final Map inspectedShortNames = new HashMap<>(); + final Map inspectedShortNames = new HashMap<>(); - for( final File arc : archives ) { + for (final File arc : archives) { g.followedBy().notFatal().attains(PLUGINS_LISTED).add("Inspecting plugin " + arc, new Executable() { @Override public void run(Reactor session1) throws Exception { @@ -436,7 +437,7 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas p.isBundled = containsHpiJpi(bundledPlugins, arc.getName()); plugins.add(p); } catch (IOException e) { - failedPlugins.add(new FailedPlugin(arc.getName(),e)); + failedPlugins.add(new FailedPlugin(arc.getName(), e)); throw e; } } @@ -448,11 +449,11 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas private boolean isDuplicate(PluginWrapper p) { String shortName = p.getShortName(); if (inspectedShortNames.containsKey(shortName)) { - LOGGER.info("Ignoring "+arc+" because "+inspectedShortNames.get(shortName)+" is already loaded"); + LOGGER.info("Ignoring " + arc + " because " + inspectedShortNames.get(shortName) + " is already loaded"); return true; } - inspectedShortNames.put(shortName,arc); + inspectedShortNames.put(shortName, arc); return false; } }); @@ -497,7 +498,7 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas // obtain topologically sorted list and overwrite the list for (PluginWrapper p : cgd.getSorted()) { - if(p.isActive()) + if (p.isActive()) activePlugins.add(p); } } catch (CycleDetectedException e) { // TODO this should be impossible, since we override reactOnCycle to not throw the exception @@ -637,9 +638,9 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas Set copiedPlugins = new HashSet<>(); Set dependencies = new HashSet<>(); - for( String pluginPath : plugins) { - String fileName = pluginPath.substring(pluginPath.lastIndexOf('/')+1); - if(fileName.length()==0) { + for (String pluginPath : plugins) { + String fileName = pluginPath.substring(pluginPath.lastIndexOf('/') + 1); + if (fileName.length() == 0) { // see http://www.nabble.com/404-Not-Found-error-when-clicking-on-help-td24508544.html // I suspect some containers are returning directory names. continue; @@ -661,7 +662,7 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas LOGGER.log(Level.SEVERE, "Failed to resolve dependencies for the bundled plugin " + fileName, e); } } catch (IOException e) { - LOGGER.log(Level.SEVERE, "Failed to extract the bundled plugin "+fileName,e); + LOGGER.log(Level.SEVERE, "Failed to extract the bundled plugin " + fileName, e); } } @@ -854,8 +855,8 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas * this is necessary since the bundled plugins are still called *.hpi */ private boolean containsHpiJpi(Collection bundledPlugins, String name) { - return bundledPlugins.contains(name.replaceAll("\\.hpi",".jpi")) - || bundledPlugins.contains(name.replaceAll("\\.jpi",".hpi")); + return bundledPlugins.contains(name.replaceAll("\\.hpi", ".jpi")) + || bundledPlugins.contains(name.replaceAll("\\.jpi", ".hpi")); } /** @@ -891,11 +892,11 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas sn = p.getShortName(); } PluginWrapper pw = getPlugin(sn); - if (pw!=null) { + if (pw != null) { if (removeExisting) { // try to load disabled plugins for (Iterator i = plugins.iterator(); i.hasNext();) { pw = i.next(); - if(sn.equals(pw.getShortName())) { + if (sn.equals(pw.getShortName())) { i.remove(); break; } @@ -907,7 +908,7 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas if (p == null) { p = strategy.createPluginWrapper(arc); } - if (p.supportsDynamicLoad()== YesNoMaybe.NO) + if (p.supportsDynamicLoad() == YesNoMaybe.NO) throw new RestartRequiredException(Messages._PluginManager_PluginDoesntSupportDynamicLoad_RestartRequired(sn)); // there's no need to do cyclic dependency check, because we are deploying one at a time, @@ -936,7 +937,7 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas activePlugins.remove(p); plugins.remove(p); p.releaseClassLoader(); - throw new IOException("Failed to install "+ sn +" plugin",e); + throw new IOException("Failed to install " + sn + " plugin", e); } LOGGER.log(FINE, "Plugin {0}:{1} dynamically {2}", new Object[] {p.getShortName(), p.getVersion(), batch != null ? "loaded but not yet started" : "installed"}); @@ -949,12 +950,12 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas Map pluginsByName = plugins.stream().collect(Collectors.toMap(PluginWrapper::getShortName, p -> p)); // recalculate dependencies of plugins optionally depending the newly deployed ones. - for (PluginWrapper depender: this.plugins) { + for (PluginWrapper depender : this.plugins) { if (plugins.contains(depender)) { // skip itself. continue; } - for (Dependency d: depender.getOptionalDependencies()) { + for (Dependency d : depender.getOptionalDependencies()) { PluginWrapper dependee = pluginsByName.get(d.shortName); if (dependee != null) { // this plugin depends on the newly loaded one! @@ -1000,7 +1001,7 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas Set dependents = new HashSet<>(); for (PluginWrapper possibleDependent : plugins) { // No need to check if plugin is dependent of itself - if(possibleDependent.getShortName().equals(plugin.getShortName())) { + if (possibleDependent.getShortName().equals(plugin.getShortName())) { continue; } @@ -1049,13 +1050,13 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas */ protected void copyBundledPlugin(URL src, String fileName) throws IOException { LOGGER.log(FINE, "Copying {0}", src); - fileName = fileName.replace(".hpi",".jpi"); // normalize fileNames to have the correct suffix - String legacyName = fileName.replace(".jpi",".hpi"); + fileName = fileName.replace(".hpi", ".jpi"); // normalize fileNames to have the correct suffix + String legacyName = fileName.replace(".jpi", ".hpi"); long lastModified = getModificationDate(src); File file = new File(rootDir, fileName); // normalization first, if the old file exists. - rename(new File(rootDir,legacyName),file); + rename(new File(rootDir, legacyName), file); // update file if: // - no file exists today @@ -1074,11 +1075,11 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas } /*package*/ static @CheckForNull Manifest parsePluginManifest(URL bundledJpi) { - try (URLClassLoader cl = new URLClassLoader(new URL[]{bundledJpi})){ - InputStream in=null; + try (URLClassLoader cl = new URLClassLoader(new URL[]{bundledJpi})) { + InputStream in = null; try { URL res = cl.findResource(PluginWrapper.MANIFEST_FILENAME); - if (res!=null) { + if (res != null) { in = getBundledJpiManifestStream(res); return new Manifest(in); } @@ -1086,7 +1087,7 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas Util.closeAndLogFailures(in, LOGGER, PluginWrapper.MANIFEST_FILENAME, bundledJpi.toString()); } } catch (IOException e) { - LOGGER.log(WARNING, "Failed to parse manifest of "+bundledJpi, e); + LOGGER.log(WARNING, "Failed to parse manifest of " + bundledJpi, e); } return null; } @@ -1108,10 +1109,10 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas final JarURLConnection jarURLConnection = (JarURLConnection) uc; final String entryName = jarURLConnection.getEntryName(); - try(JarFile jarFile = jarURLConnection.getJarFile()) { + try (JarFile jarFile = jarURLConnection.getJarFile()) { final JarEntry entry = entryName != null && jarFile != null ? jarFile.getJarEntry(entryName) : null; if (entry != null) { - try(InputStream i = jarFile.getInputStream(entry)) { + try (InputStream i = jarFile.getInputStream(entry)) { byte[] manifestBytes = IOUtils.toByteArray(i); in = new ByteArrayInputStream(manifestBytes); } @@ -1243,7 +1244,7 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas @CheckForNull public PluginWrapper getPlugin(String shortName) { for (PluginWrapper p : getPlugins()) { - if(p.getShortName().equals(shortName)) + if (p.getShortName().equals(shortName)) return p; } return null; @@ -1260,7 +1261,7 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas @CheckForNull public PluginWrapper getPlugin(Class pluginClazz) { for (PluginWrapper p : getPlugins()) { - if(pluginClazz.isInstance(p.getPlugin())) + if (pluginClazz.isInstance(p.getPlugin())) return p; } return null; @@ -1275,7 +1276,7 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas public List getPlugins(Class pluginSuperclass) { List result = new ArrayList<>(); for (PluginWrapper p : getPlugins()) { - if(pluginSuperclass.isInstance(p.getPlugin())) + if (pluginSuperclass.isInstance(p.getPlugin())) result.add(p); } return Collections.unmodifiableList(result); @@ -1297,7 +1298,7 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas * @deprecated Use {@link ServiceLoader} instead, or (more commonly) {@link ExtensionList}. */ @Deprecated - public Collection> discover( Class spi ) { + public Collection> discover(Class spi) { Set> result = new HashSet<>(); for (PluginWrapper p : activePlugins) { @@ -1316,8 +1317,8 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas PluginWrapper oneAndOnly = null; ClassLoader cl = c.getClassLoader(); for (PluginWrapper p : activePlugins) { - if (p.classLoader==cl) { - if (oneAndOnly!=null) + if (p.classLoader == cl) { + if (oneAndOnly != null) return null; // ambiguous oneAndOnly = p; } @@ -1470,7 +1471,7 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas public HttpResponse doPlugins() { Jenkins.get().checkPermission(Jenkins.ADMINISTER); JSONArray response = new JSONArray(); - Map allPlugins = new HashMap<>(); + Map allPlugins = new HashMap<>(); for (PluginWrapper plugin : plugins) { JSONObject pluginInfo = new JSONObject(); pluginInfo.put("installed", true); @@ -1495,9 +1496,9 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas response.add(pluginInfo); } for (UpdateSite site : Jenkins.get().getUpdateCenter().getSiteList()) { - for (UpdateSite.Plugin plugin: site.getAvailables()) { + for (UpdateSite.Plugin plugin : site.getAvailables()) { JSONObject pluginInfo = allPlugins.get(plugin.name); - if(pluginInfo == null) { + if (pluginInfo == null) { pluginInfo = new JSONObject(); pluginInfo.put("installed", false); } @@ -1556,13 +1557,13 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas Enumeration en = req.getParameterNames(); while (en.hasMoreElements()) { String n = en.nextElement(); - if(n.startsWith("plugin.")) { + if (n.startsWith("plugin.")) { n = n.substring(7); plugins.add(n); } } - boolean dynamicLoad = req.getParameter("dynamicLoad")!=null; + boolean dynamicLoad = req.getParameter("dynamicLoad") != null; install(plugins, dynamicLoad); rsp.sendRedirect("../updateCenter/"); @@ -1681,11 +1682,11 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas Thread.sleep(500); failures = false; for (Future jobFuture : installJobs) { - if(!jobFuture.isDone() && !jobFuture.isCancelled()) { + if (!jobFuture.isDone() && !jobFuture.isCancelled()) { continue INSTALLING; } UpdateCenter.UpdateCenterJob job = jobFuture.get(); - if(job instanceof InstallationJob && ((InstallationJob)job).status instanceof DownloadJob.Failure) { + if (job instanceof InstallationJob && ((InstallationJob) job).status instanceof DownloadJob.Failure) { failures = true; } } @@ -1695,7 +1696,7 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas break; } updateCenter.persistInstallStatus(); - if(!failures) { + if (!failures) { try (ACLContext acl = ACL.as2(currentAuth)) { InstallUtil.proceedToNextStateFrom(InstallState.INITIAL_PLUGINS_INSTALLING); } @@ -1737,7 +1738,7 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas jenkins.checkPermission(Jenkins.ADMINISTER); ProxyConfiguration pc = req.bindJSON(ProxyConfiguration.class, req.getSubmittedForm()); - if (pc.name==null) { + if (pc.name == null) { jenkins.proxy = null; ProxyConfiguration.getXmlFile().delete(); } else { @@ -1749,6 +1750,7 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas interface PluginCopier { void copy(File target) throws Exception; + void cleanup(); } @@ -1779,9 +1781,9 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas @Override public void copy(File target) throws Exception { - try(InputStream input = ProxyConfiguration.getInputStream(new URL(url))) { + try (InputStream input = ProxyConfiguration.getInputStream(new URL(url))) { Files.copy(input, target.toPath()); - } catch(Exception e) { + } catch (Exception e) { throw e; } } @@ -1804,7 +1806,7 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas PluginCopier copier; ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory()); List items = upload.parseRequest(req); - if(StringUtils.isNotBlank(items.get(1).getString())) { + if (StringUtils.isNotBlank(items.get(1).getString())) { // this is a URL deployment fileName = items.get(1).getString(); copier = new UrlPluginCopier(fileName); @@ -1815,11 +1817,11 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas copier = new FileUploadPluginCopier(fileItem); } - if("".equals(fileName)){ + if ("".equals(fileName)) { return new HttpRedirect("advanced"); } // we allow the upload of the new jpi's and the legacy hpi's - if(!fileName.endsWith(".jpi") && !fileName.endsWith(".hpi")){ + if (!fileName.endsWith(".jpi") && !fileName.endsWith(".hpi")) { throw new Failure(hudson.model.Messages.Hudson_NotAPlugin(fileName)); } @@ -1860,7 +1862,7 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas .element("optional", p.contains("resolution:=optional"))); } } - } catch(IOException e) { + } catch (IOException e) { LOGGER.log(WARNING, "Unable to setup dependency list for plugin upload", e); } @@ -1879,17 +1881,17 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas @Restricted(NoExternalUse.class) @RequirePOST public FormValidation doCheckPluginUrl(StaplerRequest request, @QueryParameter String value) throws IOException { - if(StringUtils.isNotBlank(value)) { + if (StringUtils.isNotBlank(value)) { try { URL url = new URL(value); - if(!url.getProtocol().startsWith("http")) { + if (!url.getProtocol().startsWith("http")) { return FormValidation.error(Messages.PluginManager_invalidUrl()); } - if(!url.getProtocol().equals("https")) { + if (!url.getProtocol().equals("https")) { return FormValidation.warning(Messages.PluginManager_insecureUrl()); } - } catch(MalformedURLException e) { + } catch (MalformedURLException e) { return FormValidation.error(e.getMessage()); } } @@ -1921,7 +1923,7 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas .withDuringActionExceptions(new Class[] {Exception.class}) // what we do with a failed attempt due to an allowed exception, return an FormValidation.error with the message - .withDuringActionExceptionListener( (attempt, e) -> FormValidation.errorWithMarkup(e.getClass().getSimpleName() + ": " + e.getLocalizedMessage())) + .withDuringActionExceptionListener((attempt, e) -> FormValidation.errorWithMarkup(e.getClass().getSimpleName() + ": " + e.getLocalizedMessage())) // lets get our retrier object .build(); @@ -1988,7 +1990,7 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas if (name != null) return name; } } catch (IOException e) { - LOGGER.log(WARNING, "Failed to identify the short name from "+t,e); + LOGGER.log(WARNING, "Failed to identify the short name from " + t, e); } return FilenameUtils.getBaseName(t.getName()); // fall back to the base name of what's uploaded } @@ -2020,7 +2022,7 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas List> jobs = new ArrayList<>(); UpdateCenter uc = Jenkins.get().getUpdateCenter(); // TODO call uc.updateAllSites() when available? perhaps not, since we should not block on network here - for (Map.Entry requestedPlugin : parseRequestedPlugins(configXml).entrySet()) { + for (Map.Entry requestedPlugin : parseRequestedPlugins(configXml).entrySet()) { PluginWrapper pw = getPlugin(requestedPlugin.getKey()); if (pw == null) { // install new UpdateSite.Plugin toInstall = uc.getPlugin(requestedPlugin.getKey(), requestedPlugin.getValue()); @@ -2078,7 +2080,7 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas JSONArray response = new JSONArray(); - for (Map.Entry p : parseRequestedPlugins(req.getInputStream()).entrySet()) { + for (Map.Entry p : parseRequestedPlugins(req.getInputStream()).entrySet()) { PluginWrapper pw = getPlugin(p.getKey()); JSONObject j = new JSONObject() .accumulate("name", p.getKey()) @@ -2106,8 +2108,8 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas /** * Parses configuration XML files and picks up references to XML files. */ - public Map parseRequestedPlugins(InputStream configXml) throws IOException { - final Map requestedPlugins = new TreeMap<>(); + public Map parseRequestedPlugins(InputStream configXml) throws IOException { + final Map requestedPlugins = new TreeMap<>(); try { SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); @@ -2137,7 +2139,7 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas }); } catch (SAXException x) { - throw new IOException("Failed to parse XML",x); + throw new IOException("Failed to parse XML", x); } catch (ParserConfigurationException e) { throw new AssertionError(e); // impossible since we don't tweak XMLParser } @@ -2177,6 +2179,7 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas @Restricted(NoExternalUse.class) // table.jelly public static final class MetadataCache { private final Map data = new HashMap<>(); + public T of(String key, Class type, Supplier func) { return type.cast(data.computeIfAbsent(key, _ignored -> func.get())); } @@ -2259,16 +2262,17 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas return "classLoader " + getClass().getName(); } } + @SuppressFBWarnings(value = "MS_SHOULD_BE_FINAL", justification = "for script console") - public static boolean FAST_LOOKUP = !SystemProperties.getBoolean(PluginManager.class.getName()+".noFastLookup"); + public static boolean FAST_LOOKUP = !SystemProperties.getBoolean(PluginManager.class.getName() + ".noFastLookup"); /** @deprecated in Jenkins 2.222 use {@link Jenkins#ADMINISTER} instead */ @Deprecated - public static final Permission UPLOAD_PLUGINS = new Permission(Jenkins.PERMISSIONS, "UploadPlugins", Messages._PluginManager_UploadPluginsPermission_Description(),Jenkins.ADMINISTER,PermissionScope.JENKINS); + public static final Permission UPLOAD_PLUGINS = new Permission(Jenkins.PERMISSIONS, "UploadPlugins", Messages._PluginManager_UploadPluginsPermission_Description(), Jenkins.ADMINISTER, PermissionScope.JENKINS); /** @deprecated in Jenkins 2.222 use {@link Jenkins#ADMINISTER} instead */ @Deprecated - public static final Permission CONFIGURE_UPDATECENTER = new Permission(Jenkins.PERMISSIONS, "ConfigureUpdateCenter", Messages._PluginManager_ConfigureUpdateCenterPermission_Description(),Jenkins.ADMINISTER,PermissionScope.JENKINS); + public static final Permission CONFIGURE_UPDATECENTER = new Permission(Jenkins.PERMISSIONS, "ConfigureUpdateCenter", Messages._PluginManager_ConfigureUpdateCenterPermission_Description(), Jenkins.ADMINISTER, PermissionScope.JENKINS); /** * Remembers why a plugin failed to deploy. @@ -2306,7 +2310,7 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas * Stores {@link Plugin} instances. */ /*package*/ static final class PluginInstanceStore { - final Map store = new ConcurrentHashMap<>(); + final Map store = new ConcurrentHashMap<>(); } /** @@ -2326,10 +2330,10 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas @Override public boolean isActivated() { - if(pluginsWithCycle == null){ + if (pluginsWithCycle == null) { pluginsWithCycle = new ArrayList<>(); for (PluginWrapper p : Jenkins.get().getPluginManager().getPlugins()) { - if(p.hasCycleDependency()){ + if (p.hasCycleDependency()) { pluginsWithCycle.add(p); isActive = true; } @@ -2367,10 +2371,10 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas * @param requiredVersion the lowest version which is OK (e.g. 2.2.2) * @param message the message to show (plain text) */ - public void ifPluginOlderThenReport(String pluginName, String requiredVersion, String message){ + public void ifPluginOlderThenReport(String pluginName, String requiredVersion, String message) { Plugin plugin = Jenkins.get().getPlugin(pluginName); - if(plugin != null){ - if(plugin.getWrapper().getVersionNumber().isOlderThan(new VersionNumber(requiredVersion))) { + if (plugin != null) { + if (plugin.getWrapper().getVersionNumber().isOlderThan(new VersionNumber(requiredVersion))) { pluginsToBeUpdated.put(pluginName, new PluginUpdateInfo(pluginName, message)); } } @@ -2402,6 +2406,7 @@ public abstract class PluginManager extends AbstractModelObject implements OnMas public static class PluginUpdateInfo { public final String pluginName; public final String message; + private PluginUpdateInfo(String pluginName, String message) { this.pluginName = pluginName; this.message = message; diff --git a/core/src/main/java/hudson/PluginStrategy.java b/core/src/main/java/hudson/PluginStrategy.java index 5dfc8136573aa81de276ee0338af20944f19ad69..2b237931c038e6daf9b7d920fdf3ba7d7832ffc3 100644 --- a/core/src/main/java/hudson/PluginStrategy.java +++ b/core/src/main/java/hudson/PluginStrategy.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Tom Huybrechts - * + * * 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 @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson; import edu.umd.cs.findbugs.annotations.NonNull; @@ -43,13 +44,13 @@ import java.util.logging.Logger; */ public interface PluginStrategy extends ExtensionPoint { - /** - * Creates a plugin wrapper, which provides a management interface for the plugin - * @param archive + /** + * Creates a plugin wrapper, which provides a management interface for the plugin + * @param archive * Either a directory that points to a pre-exploded plugin, or an jpi file, or an jpl file. - */ - PluginWrapper createPluginWrapper(File archive) - throws IOException; + */ + PluginWrapper createPluginWrapper(File archive) + throws IOException; /** * Finds the plugin name without actually unpacking anything {@link #createPluginWrapper} would. @@ -58,32 +59,32 @@ public interface PluginStrategy extends ExtensionPoint { */ @NonNull String getShortName(File archive) throws IOException; - /** - * Loads the plugin and starts it. - * - *

- * This should be done after all the classloaders are constructed for all - * the plugins, so that dependencies can be properly loaded by plugins. - */ - void load(PluginWrapper wrapper) throws IOException; + /** + * Loads the plugin and starts it. + * + *

+ * This should be done after all the classloaders are constructed for all + * the plugins, so that dependencies can be properly loaded by plugins. + */ + void load(PluginWrapper wrapper) throws IOException; - /** - * Optionally start services provided by the plugin. Should be called - * when all plugins are loaded. - */ - void initializeComponents(PluginWrapper plugin); + /** + * Optionally start services provided by the plugin. Should be called + * when all plugins are loaded. + */ + void initializeComponents(PluginWrapper plugin); - /** - * Find components of the given type using the assigned strategy. - * - * + /** + * Find components of the given type using the assigned strategy. + * + * * @param type The component type * @param hudson The Hudson scope * @return Sequence of components - * @since 1.400 - */ - List> findComponents(Class type, Hudson hudson); - + * @since 1.400 + */ + List> findComponents(Class type, Hudson hudson); + /** * Called when a plugin is installed, but there was already a plugin installed which optionally depended on that plugin. * The class loader of the existing depending plugin should be updated diff --git a/core/src/main/java/hudson/PluginWrapper.java b/core/src/main/java/hudson/PluginWrapper.java index 5e0f24a12e971479f243326b556eee587532fd61..a42596726cdbdc9ec0d6744bb5acff681d639fab 100644 --- a/core/src/main/java/hudson/PluginWrapper.java +++ b/core/src/main/java/hudson/PluginWrapper.java @@ -22,6 +22,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson; import static hudson.PluginWrapper.PluginDisableStatus.ALREADY_DISABLED; @@ -118,7 +119,7 @@ public class PluginWrapper implements Comparable, ModelObject { * A plugin won't be loaded unless his declared dependencies are present and match the required minimal version. * This can be set to false to disable the version check (legacy behaviour) */ - private static final boolean ENABLE_PLUGIN_DEPENDENCIES_VERSION_CHECK = Boolean.parseBoolean(System.getProperty(PluginWrapper.class.getName()+"." + "dependenciesVersionCheck.enabled", "true")); + private static final boolean ENABLE_PLUGIN_DEPENDENCIES_VERSION_CHECK = Boolean.parseBoolean(System.getProperty(PluginWrapper.class.getName() + "." + "dependenciesVersionCheck.enabled", "true")); /** * {@link PluginManager} to which this belongs to. @@ -442,10 +443,10 @@ public class PluginWrapper implements Comparable, ModelObject { public Dependency(String s) { int idx = s.indexOf(':'); - if(idx==-1) - throw new IllegalArgumentException("Illegal dependency specifier "+s); - this.shortName = Util.intern(s.substring(0,idx)); - String version = Util.intern(s.substring(idx+1)); + if (idx == -1) + throw new IllegalArgumentException("Illegal dependency specifier " + s); + this.shortName = Util.intern(s.substring(0, idx)); + String version = Util.intern(s.substring(idx + 1)); boolean isOptional = false; String[] osgiProperties = version.split("[;]"); @@ -474,13 +475,13 @@ public class PluginWrapper implements Comparable, ModelObject { * @param archive * A .jpi archive file jar file, or a .jpl linked plugin. * @param manifest - * The manifest for the plugin + * The manifest for the plugin * @param baseResourceURL - * A URL pointing to the resources for this plugin + * A URL pointing to the resources for this plugin * @param classLoader - * a classloader that loads classes from this plugin and its dependencies + * a classloader that loads classes from this plugin and its dependencies * @param disableFile - * if this file exists on startup, the plugin will not be activated + * if this file exists on startup, the plugin will not be activated * @param dependencies a list of mandatory dependencies * @param optionalDependencies a list of optional dependencies */ @@ -533,11 +534,11 @@ public class PluginWrapper implements Comparable, ModelObject { // use the name captured in the manifest, as often plugins // depend on the specific short name in its URLs. String n = manifest.getMainAttributes().getValue("Short-Name"); - if(n!=null) return n; + if (n != null) return n; // maven seems to put this automatically, so good fallback to check. n = manifest.getMainAttributes().getValue("Extension-Name"); - if(n!=null) return n; + if (n != null) return n; // otherwise infer from the file name, since older plugins don't have // this entry. @@ -641,7 +642,7 @@ public class PluginWrapper implements Comparable, ModelObject { @Deprecated public String getLongName() { String name = manifest.getMainAttributes().getValue("Long-Name"); - if(name!=null) return name; + if (name != null) return name; return shortName; } @@ -651,7 +652,7 @@ public class PluginWrapper implements Comparable, ModelObject { @Exported public YesNoMaybe supportsDynamicLoad() { String v = manifest.getMainAttributes().getValue("Support-Dynamic-Loading"); - if (v==null) return YesNoMaybe.MAYBE; + if (v == null) return YesNoMaybe.MAYBE; return Boolean.parseBoolean(v) ? YesNoMaybe.YES : YesNoMaybe.NO; } @@ -665,11 +666,11 @@ public class PluginWrapper implements Comparable, ModelObject { private String getVersionOf(Manifest manifest) { String v = manifest.getMainAttributes().getValue("Plugin-Version"); - if(v!=null) return v; + if (v != null) return v; // plugins generated before maven-hpi-plugin 1.3 should still have this attribute v = manifest.getMainAttributes().getValue("Implementation-Version"); - if(v!=null) return v; + if (v != null) return v; return "???"; } @@ -682,10 +683,10 @@ public class PluginWrapper implements Comparable, ModelObject { @Exported public @CheckForNull String getRequiredCoreVersion() { String v = manifest.getMainAttributes().getValue("Jenkins-Version"); - if (v!= null) return v; + if (v != null) return v; v = manifest.getMainAttributes().getValue("Hudson-Version"); - if (v!= null) return v; + if (v != null) return v; return null; } @@ -748,7 +749,7 @@ public class PluginWrapper implements Comparable, ModelObject { try { ((Closeable) classLoader).close(); } catch (IOException e) { - LOGGER.log(WARNING, "Failed to shut down classloader",e); + LOGGER.log(WARNING, "Failed to shut down classloader", e); } } @@ -760,8 +761,8 @@ public class PluginWrapper implements Comparable, ModelObject { LOGGER.log(Level.FINEST, "Plugin {0} has been already enabled. Skipping the enable() operation", getShortName()); return; } - if(!disableFile.delete()) - throw new IOException("Failed to delete "+disableFile); + if (!disableFile.delete()) + throw new IOException("Failed to delete " + disableFile); } /** @@ -890,11 +891,11 @@ public class PluginWrapper implements Comparable, ModelObject { return active && !hasCycleDependency(); } - public boolean hasCycleDependency(){ + public boolean hasCycleDependency() { return hasCycleDependency; } - public void setHasCycleDependency(boolean hasCycle){ + public void setHasCycleDependency(boolean hasCycle) { hasCycleDependency = hasCycle; } @@ -922,7 +923,7 @@ public class PluginWrapper implements Comparable, ModelObject { } public void setPlugin(Plugin plugin) { - Jenkins.lookup(PluginInstanceStore.class).store.put(this,plugin); + Jenkins.lookup(PluginInstanceStore.class).store.put(this, plugin); plugin.wrapper = this; } @@ -932,7 +933,7 @@ public class PluginWrapper implements Comparable, ModelObject { public boolean hasLicensesXml() { try { - new URL(baseResourceURL,"WEB-INF/licenses.xml").openStream().close(); + new URL(baseResourceURL, "WEB-INF/licenses.xml").openStream().close(); return true; } catch (IOException e) { return false; @@ -1053,7 +1054,7 @@ public class PluginWrapper implements Comparable, ModelObject { public UpdateSite.Plugin getUpdateInfo() { UpdateCenter uc = Jenkins.get().getUpdateCenter(); UpdateSite.Plugin p = uc.getPlugin(getShortName(), getVersionNumber()); - if(p!=null && p.isNewerThan(getVersion())) return p; + if (p != null && p.isNewerThan(getVersion())) return p; return null; } @@ -1081,7 +1082,7 @@ public class PluginWrapper implements Comparable, ModelObject { */ @Exported public boolean hasUpdate() { - return getUpdateInfo()!=null; + return getUpdateInfo() != null; } @Exported @@ -1165,7 +1166,7 @@ public class PluginWrapper implements Comparable, ModelObject { * Where is the backup file? */ public File getBackupFile() { - return new File(Jenkins.get().getRootDir(),"plugins/"+getShortName() + ".bak"); + return new File(Jenkins.get().getRootDir(), "plugins/" + getShortName() + ".bak"); } /** @@ -1238,8 +1239,8 @@ public class PluginWrapper implements Comparable, ModelObject { * Depending on whether the user said "dismiss" or "correct", send him to the right place. */ public void doAct(StaplerRequest req, StaplerResponse rsp) throws IOException { - if(req.hasParameter("correct")) { - rsp.sendRedirect(req.getContextPath()+"/pluginManager"); + if (req.hasParameter("correct")) { + rsp.sendRedirect(req.getContextPath() + "/pluginManager"); } } diff --git a/core/src/main/java/hudson/Proc.java b/core/src/main/java/hudson/Proc.java index 24cd16552295f3516985b2fec945b89cc3f238da..6bcb6d416819a92a8b744723cfad2977bd4aa822 100644 --- a/core/src/main/java/hudson/Proc.java +++ b/core/src/main/java/hudson/Proc.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, CloudBees, 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 @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson; import edu.umd.cs.findbugs.annotations.CheckForNull; @@ -141,7 +142,7 @@ public abstract class Proc { public abstract OutputStream getStdin(); private static final ExecutorService executor = Executors.newCachedThreadPool(new ExceptionCatchingThreadFactory(new NamingThreadFactory(new ClassLoaderSanityThreadFactory(new DaemonThreadFactory()), "Proc.executor"))); - + /** * Like {@link #join} but can be given a maximum time to wait. * @param timeout number of time units @@ -175,42 +176,42 @@ public abstract class Proc { latch.countDown(); } } - + /** * Locally launched process. */ public static final class LocalProc extends Proc { private final Process proc; - private final Thread copier,copier2; + private final Thread copier, copier2; private final OutputStream out; private final EnvVars cookie; private final String name; - private final InputStream stdout,stderr; + private final InputStream stdout, stderr; private final OutputStream stdin; - public LocalProc(String cmd, Map env, OutputStream out, File workDir) throws IOException { - this(cmd,Util.mapToEnv(env),out,workDir); + public LocalProc(String cmd, Map env, OutputStream out, File workDir) throws IOException { + this(cmd, Util.mapToEnv(env), out, workDir); } - public LocalProc(String[] cmd, Map env,InputStream in, OutputStream out) throws IOException { - this(cmd,Util.mapToEnv(env),in,out); + public LocalProc(String[] cmd, Map env, InputStream in, OutputStream out) throws IOException { + this(cmd, Util.mapToEnv(env), in, out); } - public LocalProc(String cmd,String[] env,OutputStream out, File workDir) throws IOException { - this( Util.tokenize(cmd), env, out, workDir ); + public LocalProc(String cmd, String[] env, OutputStream out, File workDir) throws IOException { + this(Util.tokenize(cmd), env, out, workDir); } - public LocalProc(String[] cmd,String[] env,OutputStream out, File workDir) throws IOException { - this(cmd,env,null,out,workDir); + public LocalProc(String[] cmd, String[] env, OutputStream out, File workDir) throws IOException { + this(cmd, env, null, out, workDir); } - public LocalProc(String[] cmd,String[] env,InputStream in,OutputStream out) throws IOException { - this(cmd,env,in,out,null); + public LocalProc(String[] cmd, String[] env, InputStream in, OutputStream out) throws IOException { + this(cmd, env, in, out, null); } - public LocalProc(String[] cmd,String[] env,InputStream in,OutputStream out, File workDir) throws IOException { - this(cmd,env,in,out,null,workDir); + public LocalProc(String[] cmd, String[] env, InputStream in, OutputStream out, File workDir) throws IOException { + this(cmd, env, in, out, null, workDir); } /** @@ -218,30 +219,30 @@ public abstract class Proc { * null to redirect stderr to stdout. */ @SuppressFBWarnings(value = "COMMAND_INJECTION", justification = "Command injection is the point of this old, barely used class.") - public LocalProc(String[] cmd,String[] env,InputStream in,OutputStream out,OutputStream err,File workDir) throws IOException { - this( calcName(cmd), - stderr(environment(new ProcessBuilder(cmd),env).directory(workDir), err==null || err== SELFPUMP_OUTPUT), - in, out, err ); + public LocalProc(String[] cmd, String[] env, InputStream in, OutputStream out, OutputStream err, File workDir) throws IOException { + this(calcName(cmd), + stderr(environment(new ProcessBuilder(cmd), env).directory(workDir), err == null || err == SELFPUMP_OUTPUT), + in, out, err); } private static ProcessBuilder stderr(ProcessBuilder pb, boolean redirectError) { - if(redirectError) pb.redirectErrorStream(true); + if (redirectError) pb.redirectErrorStream(true); return pb; } private static ProcessBuilder environment(ProcessBuilder pb, String[] env) { - if(env!=null) { + if (env != null) { Map m = pb.environment(); m.clear(); for (String e : env) { int idx = e.indexOf('='); - m.put(e.substring(0,idx),e.substring(idx+1)); + m.put(e.substring(0, idx), e.substring(idx + 1)); } } return pb; } - private LocalProc( String name, ProcessBuilder procBuilder, InputStream in, OutputStream out, OutputStream err ) throws IOException { + private LocalProc(String name, ProcessBuilder procBuilder, InputStream in, OutputStream out, OutputStream err) throws IOException { Logger.getLogger(Proc.class.getName()).log(Level.FINE, "Running: {0}", name); this.name = name; this.out = out; @@ -253,11 +254,11 @@ public abstract class Proc { this.proc = procBuilder.start(); InputStream procInputStream = proc.getInputStream(); - if (out==SELFPUMP_OUTPUT) { + if (out == SELFPUMP_OUTPUT) { stdout = procInputStream; copier = null; } else { - copier = new StreamCopyThread(name+": stdout copier", procInputStream, out); + copier = new StreamCopyThread(name + ": stdout copier", procInputStream, out); copier.start(); stdout = null; } @@ -267,21 +268,21 @@ public abstract class Proc { stdin = null; proc.getOutputStream().close(); } else - if (in==SELFPUMP_INPUT) { + if (in == SELFPUMP_INPUT) { stdin = proc.getOutputStream(); } else { - new StdinCopyThread(name+": stdin copier",in,proc.getOutputStream()).start(); + new StdinCopyThread(name + ": stdin copier", in, proc.getOutputStream()).start(); stdin = null; } InputStream procErrorStream = proc.getErrorStream(); - if(err!=null) { - if (err==SELFPUMP_OUTPUT) { + if (err != null) { + if (err == SELFPUMP_OUTPUT) { stderr = procErrorStream; copier2 = null; } else { stderr = null; - copier2 = new StreamCopyThread(name+": stderr copier", procErrorStream, err); + copier2 = new StreamCopyThread(name + ": stderr copier", procErrorStream, err); copier2.start(); } } else { @@ -290,7 +291,7 @@ public abstract class Proc { // according to the source code, Sun JREs still still returns a distinct reader end of a pipe that needs to be closed. // but apparently at least on some IBM JDK5, returned input and error streams are the same. // so try to close them smartly - if (procErrorStream!=procInputStream) { + if (procErrorStream != procInputStream) { procErrorStream.close(); } copier2 = null; @@ -319,12 +320,12 @@ public abstract class Proc { @Override public int join() throws InterruptedException, IOException { // show what we are waiting for in the thread title - // since this involves some native work, let's have some soak period before enabling this by default + // since this involves some native work, let's have some soak period before enabling this by default Thread t = Thread.currentThread(); String oldName = t.getName(); if (SHOW_PID) { ProcessTree.OSProcess p = ProcessTree.get().get(proc); - t.setName(oldName+" "+(p!=null?"waiting for pid="+p.getPid():"waiting for "+name)); + t.setName(oldName + " " + (p != null ? "waiting for pid=" + p.getPid() : "waiting for " + name)); } try { @@ -332,14 +333,14 @@ public abstract class Proc { // see https://www.jenkins.io/redirect/troubleshooting/process-leaked-file-descriptors // problems like that shows up as infinite wait in join(), which confuses great many users. // So let's do a timed wait here and try to diagnose the problem - if (copier!=null) copier.join(TimeUnit.SECONDS.toMillis(10)); - if(copier2!=null) copier2.join(TimeUnit.SECONDS.toMillis(10)); - if((copier!=null && copier.isAlive()) || (copier2!=null && copier2.isAlive())) { + if (copier != null) copier.join(TimeUnit.SECONDS.toMillis(10)); + if (copier2 != null) copier2.join(TimeUnit.SECONDS.toMillis(10)); + if ((copier != null && copier.isAlive()) || (copier2 != null && copier2.isAlive())) { // looks like handles are leaking. // closing these handles should terminate the threads. String msg = "Process leaked file descriptors. See https://www.jenkins.io/redirect/troubleshooting/process-leaked-file-descriptors for more information"; Throwable e = new Exception().fillInStackTrace(); - LOGGER.log(Level.WARNING,msg,e); + LOGGER.log(Level.WARNING, msg, e); // doing proc.getInputStream().close() hangs in FileInputStream.close0() // it could be either because another thread is blocking on read, or @@ -388,7 +389,7 @@ public abstract class Proc { * Destroys the child process without join. */ private void destroy() throws InterruptedException { - ProcessTree.get().killAll(proc,cookie); + ProcessTree.get().killAll(proc, cookie); } /** @@ -467,9 +468,9 @@ public abstract class Proc { kill(); throw e; } catch (ExecutionException e) { - if(e.getCause() instanceof IOException) - throw (IOException)e.getCause(); - throw new IOException("Failed to join the process",e); + if (e.getCause() instanceof IOException) + throw (IOException) e.getCause(); + throw new IOException("Failed to join the process", e); } catch (CancellationException x) { return -1; } finally { @@ -506,7 +507,7 @@ public abstract class Proc { */ @SuppressFBWarnings(value = "MS_SHOULD_BE_FINAL", justification = "for debugging") public static boolean SHOW_PID = false; - + /** * An instance of {@link Proc}, which has an internal workaround for JENKINS-23271. * It presumes that the instance of the object is guaranteed to be used after the {@link Proc#join()} call. diff --git a/core/src/main/java/hudson/ProxyConfiguration.java b/core/src/main/java/hudson/ProxyConfiguration.java index cecd40f979a0ffeb4bda13e743be723d91523062..c087c00ceb8c8e082c1dcaa2f6e7b23b108b6996 100644 --- a/core/src/main/java/hudson/ProxyConfiguration.java +++ b/core/src/main/java/hudson/ProxyConfiguration.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson; import com.thoughtworks.xstream.XStream; @@ -89,8 +90,8 @@ public final class ProxyConfiguration extends AbstractDescribableImpl getNoProxyHostPatterns(String noProxyHost) { - if (noProxyHost==null) return Collections.emptyList(); + if (noProxyHost == null) return Collections.emptyList(); List r = new ArrayList<>(); for (String s : noProxyHost.split("[ \t\n,|]+")) { - if (s.length()==0) continue; + if (s.length() == 0) continue; r.add(Pattern.compile(s.replace(".", "\\.").replace("*", ".*"))); } return r; @@ -257,18 +258,18 @@ public final class ProxyConfiguration extends AbstractDescribableImpl 0) { + + if (DEFAULT_CONNECT_TIMEOUT_MILLIS > 0) { con.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT_MILLIS); } - + if (JenkinsJVM.isJenkinsJVM()) { // this code may run on an agent decorate(con); } @@ -362,7 +363,7 @@ public final class ProxyConfiguration extends AbstractDescribableImpl 0 ? DEFAULT_CONNECT_TIMEOUT_MILLIS : (int)TimeUnit.SECONDS.toMillis(30)); - + method.getParams().setParameter("http.socket.timeout", DEFAULT_CONNECT_TIMEOUT_MILLIS > 0 ? DEFAULT_CONNECT_TIMEOUT_MILLIS : (int) TimeUnit.SECONDS.toMillis(30)); + HttpClient client = new HttpClient(); if (Util.fixEmptyAndTrim(name) != null && !isNoProxyHost(host, noProxyHost)) { client.getHostConfiguration().setProxy(name, port); @@ -454,7 +455,7 @@ public final class ProxyConfiguration extends AbstractDescribableImpl= 0){ + if (userName.indexOf('\\') >= 0) { final String domain = userName.substring(0, userName.indexOf('\\')); final String user = userName.substring(userName.indexOf('\\') + 1); return new NTCredentials(user, Secret.fromString(password).getPlainText(), "", domain); diff --git a/core/src/main/java/hudson/ResponseHeaderFilter.java b/core/src/main/java/hudson/ResponseHeaderFilter.java index 4460208a733db1fc74ca859376d395886bb6e37d..90fb0be87d37a8350f0550f94dbe561d2fc4dde1 100644 --- a/core/src/main/java/hudson/ResponseHeaderFilter.java +++ b/core/src/main/java/hudson/ResponseHeaderFilter.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, id:digerata - * + * * 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 @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson; import java.io.IOException; @@ -47,61 +48,61 @@ import javax.servlet.http.HttpServletResponse; * down Hudson page load times. *

* To enable this filter, edit the web.xml file to include: - * + * *

  * <filter>
- * 		<filter-name>change-headers-filter</filter-name>
- * 		<filter-class>hudson.ResponseHeaderFilter</filter-class>
- * 		<init-param>
- * 			<param-name>Pragma</param-name>
- * 			<param-value>public</param-value>
- * 		</init-param>
- * 		<init-param>
- * 			<param-name>Cache-Control</param-name>
- * 			<param-value>max-age=86400, public</param-value>
- * 		</init-param>
+ *         <filter-name>change-headers-filter</filter-name>
+ *         <filter-class>hudson.ResponseHeaderFilter</filter-class>
+ *         <init-param>
+ *             <param-name>Pragma</param-name>
+ *             <param-value>public</param-value>
+ *         </init-param>
+ *         <init-param>
+ *             <param-name>Cache-Control</param-name>
+ *             <param-value>max-age=86400, public</param-value>
+ *         </init-param>
  * </filter>
- * 
+ *
  * And down below that:
- * 
+ *
  * <filter-mapping>
- * 		<filter-name>Headers</filter-name>
- * 		<url-pattern>/*</url-pattern>
+ *         <filter-name>Headers</filter-name>
+ *         <url-pattern>/*</url-pattern>
  * </filter-mapping>
  * 
- * + * *

- * In the case of the tomcat cache problem, it is important that the url-pattern for + * In the case of the tomcat cache problem, it is important that the url-pattern for * the filter matches the url-pattern set for the security-constraint. - * + * * @author Mike Wille */ public class ResponseHeaderFilter implements Filter { - private FilterConfig config; + private FilterConfig config; - @Override - public void init(FilterConfig filterConfig) throws ServletException { - config = filterConfig; - } + @Override + public void init(FilterConfig filterConfig) throws ServletException { + config = filterConfig; + } - @Override - public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, - ServletException { - HttpServletResponse httpResp = (HttpServletResponse) resp; + @Override + public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, + ServletException { + HttpServletResponse httpResp = (HttpServletResponse) resp; - Enumeration e = config.getInitParameterNames(); + Enumeration e = config.getInitParameterNames(); - // for each configuration element... - while(e.hasMoreElements()) { - String headerName = (String) e.nextElement(); - String headerValue = config.getInitParameter(headerName); - // set the header with the given name and value - httpResp.setHeader(headerName, headerValue); - } - chain.doFilter(req, resp); - } + // for each configuration element... + while (e.hasMoreElements()) { + String headerName = (String) e.nextElement(); + String headerValue = config.getInitParameter(headerName); + // set the header with the given name and value + httpResp.setHeader(headerName, headerValue); + } + chain.doFilter(req, resp); + } - @Override - public void destroy() { - } + @Override + public void destroy() { + } } diff --git a/core/src/main/java/hudson/StructuredForm.java b/core/src/main/java/hudson/StructuredForm.java index 5d0e28dc5c6efce83beac6ee3ac83b4ac16b93f1..708d0120dc9df711373d3de42b89c4e04d4fbc49 100644 --- a/core/src/main/java/hudson/StructuredForm.java +++ b/core/src/main/java/hudson/StructuredForm.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson; import java.util.Collections; @@ -58,15 +59,16 @@ public class StructuredForm { * Because of the way structured form submission work, this is convenient way of * handling repeated multi-value entries. * - * @since 1.233 + * @since 1.233 */ + public static List toList(JSONObject parent, String propertyName) { Object v = parent.get(propertyName); - if(v==null) + if (v == null) return Collections.emptyList(); - if(v instanceof JSONObject) - return Collections.singletonList((JSONObject)v); - if(v instanceof JSONArray) + if (v instanceof JSONObject) + return Collections.singletonList((JSONObject) v); + if (v instanceof JSONArray) return (List) v; throw new IllegalArgumentException(); diff --git a/core/src/main/java/hudson/TcpSlaveAgentListener.java b/core/src/main/java/hudson/TcpSlaveAgentListener.java index 717c1df9195310b8802a933f6d82aebd13b2a346..eb6358f7a3f31c93db97046311f31566a6cf25f1 100644 --- a/core/src/main/java/hudson/TcpSlaveAgentListener.java +++ b/core/src/main/java/hudson/TcpSlaveAgentListener.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Stephen Connolly - * + * * 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 @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson; import edu.umd.cs.findbugs.annotations.Nullable; @@ -90,12 +91,12 @@ public final class TcpSlaveAgentListener extends Thread { * Use 0 to choose a random port. */ public TcpSlaveAgentListener(int port) throws IOException { - super("TCP agent listener port="+port); + super("TCP agent listener port=" + port); try { serverSocket = ServerSocketChannel.open(); serverSocket.socket().bind(new InetSocketAddress(port)); } catch (BindException e) { - throw (BindException)new BindException("Failed to listen on port "+port+" because it's already in use.").initCause(e); + throw (BindException) new BindException("Failed to listen on port " + port + " because it's already in use.").initCause(e); } this.configuredPort = port; setUncaughtExceptionHandler((t, e) -> { @@ -193,8 +194,8 @@ public final class TcpSlaveAgentListener extends Thread { }).start(); } } catch (IOException e) { - if(!shuttingDown) { - LOGGER.log(Level.SEVERE,"Failed to accept TCP connections", e); + if (!shuttingDown) { + LOGGER.log(Level.SEVERE, "Failed to accept TCP connections", e); } } } @@ -218,7 +219,7 @@ public final class TcpSlaveAgentListener extends Thread { try { serverSocket.close(); } catch (IOException e) { - LOGGER.log(Level.WARNING, "Failed to close down TCP port",e); + LOGGER.log(Level.WARNING, "Failed to close down TCP port", e); } } @@ -235,10 +236,10 @@ public final class TcpSlaveAgentListener extends Thread { ConnectionHandler(Socket s, ConnectionHandlerFailureCallback parentTerminator) { this.s = s; - synchronized(getClass()) { + synchronized (getClass()) { id = iotaGen++; } - setName("TCP agent connection handler #"+id+" with "+s.getRemoteSocketAddress()); + setName("TCP agent connection handler #" + id + " with " + s.getRemoteSocketAddress()); setUncaughtExceptionHandler((t, e) -> { LOGGER.log(Level.SEVERE, "Uncaught exception in TcpSlaveAgentListener ConnectionHandler " + t, e); try { @@ -264,17 +265,17 @@ public final class TcpSlaveAgentListener extends Thread { String header = new String(head, StandardCharsets.US_ASCII); if (header.startsWith("GET ")) { // this looks like an HTTP client - respondHello(header,s); + respondHello(header, s); return; } // otherwise assume this is AgentProtocol and start from the beginning - String s = new DataInputStream(new SequenceInputStream(new ByteArrayInputStream(head),in)).readUTF(); + String s = new DataInputStream(new SequenceInputStream(new ByteArrayInputStream(head), in)).readUTF(); - if(s.startsWith("Protocol:")) { + if (s.startsWith("Protocol:")) { String protocol = s.substring(9); AgentProtocol p = AgentProtocol.of(protocol); - if (p!=null) { + if (p != null) { if (Jenkins.get().getAgentProtocols().contains(protocol)) { LOGGER.log(p instanceof PingAgentProtocol ? Level.FINE : Level.INFO, "Accepted {0} connection #{1} from {2}", new Object[] {protocol, id, this.s.getRemoteSocketAddress()}); p.handle(this.s); @@ -287,7 +288,7 @@ public final class TcpSlaveAgentListener extends Thread { error("Unrecognized protocol: " + s, this.s); } } catch (InterruptedException e) { - LOGGER.log(Level.WARNING,"Connection #"+id+" aborted",e); + LOGGER.log(Level.WARNING, "Connection #" + id + " aborted", e); try { s.close(); } catch (IOException ex) { @@ -319,7 +320,7 @@ public final class TcpSlaveAgentListener extends Thread { response = "HTTP/1.0 200 OK\r\n" + "Content-Type: text/plain;charset=UTF-8\r\n" + "\r\n" + - "Jenkins-Agent-Protocols: " + getAgentProtocolNames()+"\r\n" + + "Jenkins-Agent-Protocols: " + getAgentProtocolNames() + "\r\n" + "Jenkins-Version: " + Jenkins.VERSION + "\r\n" + "Jenkins-Session: " + Jenkins.SESSION_HASH + "\r\n" + "Client: " + s.getInetAddress().getHostAddress() + "\r\n" + @@ -505,7 +506,7 @@ public final class TcpSlaveAgentListener extends Thread { } public static void schedule(Thread originThread, Throwable cause) { - schedule(originThread, cause,5000); + schedule(originThread, cause, 5000); } public static void schedule(Thread originThread, Throwable cause, long approxDelay) { @@ -528,7 +529,7 @@ public final class TcpSlaveAgentListener extends Thread { } } - private static int iotaGen=1; + private static int iotaGen = 1; private static final Logger LOGGER = Logger.getLogger(TcpSlaveAgentListener.class.getName()); @@ -541,7 +542,7 @@ public final class TcpSlaveAgentListener extends Thread { */ @SuppressFBWarnings(value = "MS_SHOULD_BE_FINAL", justification = "Accessible via System Groovy Scripts") @Restricted(NoExternalUse.class) - public static String CLI_HOST_NAME = SystemProperties.getString(TcpSlaveAgentListener.class.getName()+".hostName"); + public static String CLI_HOST_NAME = SystemProperties.getString(TcpSlaveAgentListener.class.getName() + ".hostName"); /** * Port number that we advertise protocol clients to connect to. @@ -555,5 +556,5 @@ public final class TcpSlaveAgentListener extends Thread { */ @SuppressFBWarnings(value = "MS_SHOULD_BE_FINAL", justification = "Accessible via System Groovy Scripts") @Restricted(NoExternalUse.class) - public static Integer CLI_PORT = SystemProperties.getInteger(TcpSlaveAgentListener.class.getName()+".port"); + public static Integer CLI_PORT = SystemProperties.getInteger(TcpSlaveAgentListener.class.getName() + ".port"); } diff --git a/core/src/main/java/hudson/URLConnectionDecorator.java b/core/src/main/java/hudson/URLConnectionDecorator.java index f3794f4e33ea03467ea36486b0d4b32067104856..95c8a4e6bd349e70e127aaff33bb74d7dd926c22 100644 --- a/core/src/main/java/hudson/URLConnectionDecorator.java +++ b/core/src/main/java/hudson/URLConnectionDecorator.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson; diff --git a/core/src/main/java/hudson/Util.java b/core/src/main/java/hudson/Util.java index e66820214612d7f6155520f8101779457dd2cc98..66d2d262b4421549f4e5042ce30b38ebe9ca0095 100644 --- a/core/src/main/java/hudson/Util.java +++ b/core/src/main/java/hudson/Util.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson; import edu.umd.cs.findbugs.annotations.CheckForNull; @@ -138,10 +139,10 @@ public class Util { * @since 1.176 */ @NonNull - public static List filter( @NonNull Iterable base, @NonNull Class type ) { + public static List filter(@NonNull Iterable base, @NonNull Class type) { List r = new ArrayList<>(); for (Object i : base) { - if(type.isInstance(i)) + if (type.isInstance(i)) r.add(type.cast(i)); } return r; @@ -151,8 +152,8 @@ public class Util { * Creates a filtered sublist. */ @NonNull - public static List filter( @NonNull List base, @NonNull Class type ) { - return filter((Iterable)base,type); + public static List filter(@NonNull List base, @NonNull Class type) { + return filter((Iterable) base, type); } /** @@ -168,7 +169,7 @@ public class Util { * */ @Nullable - public static String replaceMacro( @CheckForNull String s, @NonNull Map properties) { + public static String replaceMacro(@CheckForNull String s, @NonNull Map properties) { return replaceMacro(s, new VariableResolver.ByMap<>(properties)); } @@ -180,30 +181,30 @@ public class Util { */ @Nullable public static String replaceMacro(@CheckForNull String s, @NonNull VariableResolver resolver) { - if (s == null) { - return null; - } + if (s == null) { + return null; + } - int idx=0; - while(true) { + int idx = 0; + while (true) { Matcher m = VARIABLE.matcher(s); - if(!m.find(idx)) return s; + if (!m.find(idx)) return s; String key = m.group().substring(1); // escape the dollar sign or get the key to resolve String value; - if(key.charAt(0)=='$') { + if (key.charAt(0) == '$') { value = "$"; } else { - if(key.charAt(0)=='{') key = key.substring(1,key.length()-1); + if (key.charAt(0) == '{') key = key.substring(1, key.length() - 1); value = resolver.resolve(key); } - if(value==null) + if (value == null) idx = m.end(); // skip this else { - s = s.substring(0,m.start())+value+s.substring(m.end()); + s = s.substring(0, m.start()) + value + s.substring(m.end()); idx = m.start() + value.length(); } } @@ -435,15 +436,15 @@ 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(@NonNull IOException e, @NonNull TaskListener listener ) { + public static void displayIOException(@NonNull IOException e, @NonNull TaskListener listener) { String msg = getWin32ErrorMessage(e); - if(msg!=null) + if (msg != null) listener.getLogger().println(msg); } @CheckForNull public static String getWin32ErrorMessage(@NonNull IOException e) { - return getWin32ErrorMessage((Throwable)e); + return getWin32ErrorMessage((Throwable) e); } /** @@ -455,19 +456,19 @@ public class Util { @CheckForNull public static String getWin32ErrorMessage(Throwable e) { String msg = e.getMessage(); - if(msg!=null) { + if (msg != null) { Matcher m = errorCodeParser.matcher(msg); - if(m.matches()) { + if (m.matches()) { try { ResourceBundle rb = ResourceBundle.getBundle("/hudson/win32errors"); - return rb.getString("error"+m.group(1)); + return rb.getString("error" + m.group(1)); } catch (RuntimeException ignored) { // silently recover from resource related failures } } } - if(e.getCause()!=null) + if (e.getCause() != null) return getWin32ErrorMessage(e.getCause()); return null; // no message } @@ -482,9 +483,9 @@ public class Util { public static String getWin32ErrorMessage(int n) { try { ResourceBundle rb = ResourceBundle.getBundle("/hudson/win32errors"); - return rb.getString("error"+n); + return rb.getString("error" + n); } catch (MissingResourceException e) { - LOGGER.log(Level.WARNING,"Failed to find resource bundle",e); + LOGGER.log(Level.WARNING, "Failed to find resource bundle", e); return null; } } @@ -505,7 +506,7 @@ public class Util { * @deprecated Use {@link IOUtils#copy(InputStream, OutputStream)} */ @Deprecated - public static void copyStream(@NonNull InputStream in,@NonNull OutputStream out) throws IOException { + public static void copyStream(@NonNull InputStream in, @NonNull OutputStream out) throws IOException { IOUtils.copy(in, out); } @@ -549,23 +550,23 @@ public class Util { */ @NonNull public static String[] tokenize(@NonNull String s, @CheckForNull String delimiter) { - return QuotedStringTokenizer.tokenize(s,delimiter); + return QuotedStringTokenizer.tokenize(s, delimiter); } @NonNull public static String[] tokenize(@NonNull String s) { - return tokenize(s," \t\n\r\f"); + return tokenize(s, " \t\n\r\f"); } /** * Converts the map format of the environment variables to the K=V format in the array. */ @NonNull - public static String[] mapToEnv(@NonNull Map m) { + public static String[] mapToEnv(@NonNull Map m) { String[] r = new String[m.size()]; - int idx=0; + int idx = 0; - for (final Map.Entry e : m.entrySet()) { + for (final Map.Entry e : m.entrySet()) { r[idx++] = e.getKey() + '=' + e.getValue(); } return r; @@ -573,8 +574,8 @@ public class Util { public static int min(int x, @NonNull int... values) { for (int i : values) { - if(i= 10) return Messages.Util_second(seconds); else if (seconds >= 1) - return Messages.Util_second(seconds+(float)(millisecs/100)/10); // render "1.2 sec" - else if(millisecs>=100) - return Messages.Util_second((float)(millisecs/10)/100); // render "0.12 sec". + return Messages.Util_second(seconds + (float) (millisecs / 100) / 10); // render "1.2 sec" + else if (millisecs >= 100) + return Messages.Util_second((float) (millisecs / 10) / 100); // render "0.12 sec". else return Messages.Util_millisecond(millisecs); } @@ -809,9 +810,9 @@ public class Util { @NonNull @Deprecated 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). + 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). s += "s"; return s; } @@ -820,10 +821,10 @@ public class Util { * Create a sub-list by only picking up instances of the specified type. */ @NonNull - public static List createSubList(@NonNull Collection source, @NonNull Class type ) { + public static List createSubList(@NonNull Collection source, @NonNull Class type) { List r = new ArrayList<>(); for (Object item : source) { - if(type.isInstance(item)) + if (type.isInstance(item)) r.add(type.cast(item)); } return r; @@ -850,7 +851,7 @@ public class Util { for (int i = 0; i < s.length(); i++) { int c = s.charAt(i); - if (c<128 && c!=' ') { + if (c < 128 && c != ' ') { out.append((char) c); } else { // 1 char -> UTF8 @@ -873,6 +874,7 @@ public class Util { } private static final boolean[] uriMap = new boolean[123]; + static { String raw = "! $ &'()*+,-. 0123456789 = @ABCDEFGHIJKLMNOPQRSTUVWXYZ _ abcdefghijklmnopqrstuvwxyz"; @@ -888,6 +890,7 @@ public class Util { } private static final boolean[] fullUriMap = new boolean[123]; + static { String raw = " 0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz"; // !"#$%&'()*+,-./0123456789:;<=>?@ [\]^_` {|}~ @@ -924,11 +927,11 @@ public class Util { * single path component used in constructing a URL. */ @NonNull - public static String fullEncode(@NonNull String s){ + public static String fullEncode(@NonNull String s) { return encode(s, fullUriMap); } - private static String encode(String s, boolean[] map){ + private static String encode(String s, boolean[] map) { boolean escaped = false; StringBuilder out = null; CharsetEncoder enc = null; @@ -936,7 +939,7 @@ public class Util { char c; for (int i = 0, m = s.length(); i < m; i++) { int codePoint = Character.codePointAt(s, i); - if((codePoint&0xffffff80)==0) { // 1 byte + if ((codePoint & 0xffffff80) == 0) { // 1 byte c = s.charAt(i); if (c > 122 || map[c]) { if (!escaped) { @@ -978,7 +981,7 @@ public class Util { out.append(toDigit(aByte & 0xF)); } - if(Character.charCount(codePoint) > 1) { + if (Character.charCount(codePoint) > 1) { i++; // we processed two characters } } @@ -987,14 +990,14 @@ public class Util { } private static char toDigit(int n) { - return (char)(n < 10 ? '0' + n : 'A' + n - 10); + return (char) (n < 10 ? '0' + n : 'A' + n - 10); } /** * Surrounds by a single-quote. */ public static String singleQuote(String s) { - return '\''+s+'\''; + return '\'' + s + '\''; } /** @@ -1002,34 +1005,34 @@ public class Util { */ @Nullable public static String escape(@CheckForNull String text) { - if (text==null) return null; - StringBuilder buf = new StringBuilder(text.length()+64); - for( int i=0; i"); else - if(ch=='<') + if (ch == '<') buf.append("<"); else - if(ch=='>') + if (ch == '>') buf.append(">"); else - if(ch=='&') + if (ch == '&') buf.append("&"); else - if(ch=='"') + if (ch == '"') buf.append("""); else - if(ch=='\'') + if (ch == '\'') buf.append("'"); else - if(ch==' ') { + if (ch == ' ') { // All spaces in a block of consecutive spaces are converted to // non-breaking space ( ) except for the last one. This allows // significant whitespace to be retained without prohibiting wrapping. - char nextCh = i+1 < text.length() ? text.charAt(i+1) : 0; - buf.append(nextCh==' ' ? " " : " "); + char nextCh = i + 1 < text.length() ? text.charAt(i + 1) : 0; + buf.append(nextCh == ' ' ? " " : " "); } else buf.append(ch); @@ -1039,16 +1042,16 @@ public class Util { @NonNull public static String xmlEscape(@NonNull String text) { - StringBuilder buf = new StringBuilder(text.length()+64); - for( int i=0; i') + if (ch == '>') buf.append(">"); else - if(ch=='&') + if (ch == '&') buf.append("&"); else buf.append(ch); @@ -1101,7 +1104,7 @@ public class Util { */ @CheckForNull public static String fixEmpty(@CheckForNull String s) { - if(s==null || s.length()==0) return null; + if (s == null || s.length() == 0) return null; return s; } @@ -1112,7 +1115,7 @@ public class Util { */ @CheckForNull public static String fixEmptyAndTrim(@CheckForNull String s) { - if(s==null) return null; + if (s == null) return null; return fixEmpty(s.trim()); } @@ -1178,11 +1181,11 @@ public class Util { @NonNull public static String getFileName(@NonNull String filePath) { int idx = filePath.lastIndexOf('\\'); - if(idx>=0) - return getFileName(filePath.substring(idx+1)); + if (idx >= 0) + return getFileName(filePath.substring(idx + 1)); idx = filePath.lastIndexOf('/'); - if(idx>=0) - return getFileName(filePath.substring(idx+1)); + if (idx >= 0) + return getFileName(filePath.substring(idx + 1)); return filePath; } @@ -1194,9 +1197,9 @@ public class Util { @NonNull public static String join(@NonNull Collection strings, @NonNull String separator) { StringBuilder buf = new StringBuilder(); - boolean first=true; + boolean first = true; for (Object s : strings) { - if(first) first=false; + if (first) first = false; else buf.append(separator); buf.append(s); } @@ -1242,14 +1245,14 @@ public class Util { StringTokenizer tokens; - tokens = new StringTokenizer(includes,","); - while(tokens.hasMoreTokens()) { + tokens = new StringTokenizer(includes, ","); + while (tokens.hasMoreTokens()) { String token = tokens.nextToken().trim(); fs.createInclude().setName(token); } - if(excludes!=null) { - tokens = new StringTokenizer(excludes,","); - while(tokens.hasMoreTokens()) { + if (excludes != null) { + tokens = new StringTokenizer(excludes, ","); + while (tokens.hasMoreTokens()) { String token = tokens.nextToken().trim(); fs.createExclude().setName(token); } @@ -1259,7 +1262,7 @@ public class Util { @NonNull public static FileSet createFileSet(@NonNull File baseDir, @NonNull String includes) { - return createFileSet(baseDir,includes,null); + return createFileSet(baseDir, includes, null); } private static void tryToDeleteSymlink(@NonNull File symlink) { @@ -1376,6 +1379,7 @@ public class Util { } private static final AtomicBoolean warnedSymlinks = new AtomicBoolean(); + private static void warnWindowsSymlink() { if (warnedSymlinks.compareAndSet(false, true)) { LOGGER.warning("Symbolic links enabled on this platform but disabled for this user; run as administrator or use Local Security Policy > Security Settings > Local Policies > User Rights Assignment > Create symbolic links"); @@ -1400,11 +1404,11 @@ public class Util { @CheckForNull public static File resolveSymlinkToFile(@NonNull File link) throws InterruptedException, IOException { String target = resolveSymlink(link); - if (target==null) return null; + if (target == null) return null; File f = new File(target); if (f.isAbsolute()) return f; // absolute symlink - return new File(link.getParentFile(),target); // relative symlink + return new File(link.getParentFile(), target); // relative symlink } /** @@ -1450,7 +1454,7 @@ public class Util { @Deprecated public static String encodeRFC2396(String url) { try { - return new URI(null,url,null).toASCIIString(); + return new URI(null, url, null).toASCIIString(); } catch (URISyntaxException e) { LOGGER.log(Level.WARNING, "Failed to encode {0}", url); // could this ever happen? return url; @@ -1463,7 +1467,7 @@ public class Util { */ @NonNull public static String wrapToErrorSpan(@NonNull String s) { - s = ""+s+""; + s = "" + s + ""; return s; } @@ -1596,8 +1600,8 @@ public class Util { 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); - else return new File(p.substring(0,pos)+ext); + if (pos < 0) return new File(p + ext); + else return new File(p.substring(0, pos) + ext); } /** @@ -1606,7 +1610,7 @@ public class Util { */ @Nullable public static String intern(@CheckForNull String s) { - return s==null ? s : s.intern(); + return s == null ? s : s.intern(); } /** @@ -1623,10 +1627,10 @@ public class Util { @Restricted(NoExternalUse.class) public static boolean isAbsoluteUri(@NonNull String uri) { int idx = uri.indexOf(':'); - if (idx<0) return false; // no ':'. can't be absolute + if (idx < 0) return false; // no ':'. can't be absolute // #, ?, and / must not be before ':' - return idx<_indexOf(uri, '#') && idx<_indexOf(uri,'?') && idx<_indexOf(uri,'/'); + return idx < _indexOf(uri, '#') && idx < _indexOf(uri, '?') && idx < _indexOf(uri, '/'); } /** @@ -1643,7 +1647,7 @@ public class Util { */ private static int _indexOf(@NonNull String s, char ch) { int idx = s.indexOf(ch); - if (idx<0) return s.length(); + if (idx < 0) return s.length(); return idx; } @@ -1657,7 +1661,7 @@ public class Util { p.load(new StringReader(properties)); return p; } - + /** * Closes the item and logs error to the log in the case of error. * Logging will be performed on the {@code WARNING} level. @@ -1668,14 +1672,14 @@ public class Util { * @since 2.19, but TODO update once un-restricted */ @Restricted(NoExternalUse.class) - public static void closeAndLogFailures(@CheckForNull Closeable toClose, @NonNull Logger logger, + public static void closeAndLogFailures(@CheckForNull Closeable toClose, @NonNull Logger logger, @NonNull String closeableName, @NonNull String closeableOwner) { if (toClose == null) { return; } try { toClose.close(); - } catch(IOException ex) { + } catch (IOException ex) { LogRecord record = new LogRecord(Level.WARNING, "Failed to close {0} of {1}"); record.setParameters(new Object[] { closeableName, closeableOwner }); record.setThrown(ex); @@ -1727,7 +1731,7 @@ public class Util { throw new IOException(e); } } - + /** * Create a directory by creating all nonexistent parent directories first. * @@ -1791,21 +1795,21 @@ public class Util { * even if there are only 3 hours between. As well as "10am" to "2pm" both on the same day, returns 0. */ @Restricted(NoExternalUse.class) - public static long daysBetween(@NonNull Date a, @NonNull Date b){ + public static long daysBetween(@NonNull Date a, @NonNull Date b) { LocalDate aLocal = a.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); LocalDate bLocal = b.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); return ChronoUnit.DAYS.between(aLocal, bLocal); } - + /** * @return positive number of days between the given date and now * @see #daysBetween(Date, Date) */ @Restricted(NoExternalUse.class) - public static long daysElapsedSince(@NonNull Date date){ + public static long daysElapsedSince(@NonNull Date date) { return Math.max(0, daysBetween(date, new Date())); } - + /** * Find the specific ancestor, or throw an exception. * Useful for an ancestor we know is inside the URL to ease readability @@ -1819,7 +1823,7 @@ public class Util { return t; } - public static final FastDateFormat XS_DATETIME_FORMATTER = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss'Z'",new SimpleTimeZone(0,"GMT")); + public static final FastDateFormat XS_DATETIME_FORMATTER = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss'Z'", new SimpleTimeZone(0, "GMT")); // Note: RFC822 dates must not be localized! public static final FastDateFormat RFC822_DATETIME_FORMATTER @@ -1830,9 +1834,9 @@ public class Util { /** * On Unix environment that cannot run "ln", set this to true. */ - public static boolean NO_SYMLINK = SystemProperties.getBoolean(Util.class.getName()+".noSymLink"); + public static boolean NO_SYMLINK = SystemProperties.getBoolean(Util.class.getName() + ".noSymLink"); - public static boolean SYMLINK_ESCAPEHATCH = SystemProperties.getBoolean(Util.class.getName()+".symlinkEscapeHatch"); + public static boolean SYMLINK_ESCAPEHATCH = SystemProperties.getBoolean(Util.class.getName() + ".symlinkEscapeHatch"); /** * The number of additional times we will attempt to delete files/directory trees diff --git a/core/src/main/java/hudson/WebAppMain.java b/core/src/main/java/hudson/WebAppMain.java index 82aee9f2f9acc720c0560d080036a33bcccc8bab..b4b24f858fd6c004676f8cec56187c595d74171a 100644 --- a/core/src/main/java/hudson/WebAppMain.java +++ b/core/src/main/java/hudson/WebAppMain.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson; import static java.util.logging.Level.FINE; @@ -154,7 +155,7 @@ public class WebAppMain implements ServletContextListener { JenkinsJVMAccess._setJenkinsJVM(true); final ServletContext context = event.getServletContext(); - File home=null; + File home = null; try { // use the current request to determine the language @@ -169,12 +170,12 @@ public class WebAppMain implements ServletContextListener { JVM jvm; try { jvm = new JVM(); - new URLClassLoader(new URL[0],getClass().getClassLoader()); - } catch(SecurityException e) { + new URLClassLoader(new URL[0], getClass().getClassLoader()); + } catch (SecurityException e) { throw new InsufficientPermissionDetected(e); } - try {// remove Sun PKCS11 provider if present. See http://wiki.jenkins-ci.org/display/JENKINS/Solaris+Issue+6276483 + try { // remove Sun PKCS11 provider if present. See http://wiki.jenkins-ci.org/display/JENKINS/Solaris+Issue+6276483 Security.removeProvider("SunPKCS11-Solaris"); } catch (SecurityException e) { // ignore this error. @@ -187,33 +188,33 @@ public class WebAppMain implements ServletContextListener { try { Util.createDirectories(home.toPath()); } catch (IOException | InvalidPathException e) { - throw (NoHomeDir)new NoHomeDir(home).initCause(e); + throw (NoHomeDir) new NoHomeDir(home).initCause(e); } - LOGGER.info("Jenkins home directory: "+ home +" found at: " + describedHomeDir.description); + LOGGER.info("Jenkins home directory: " + home + " found at: " + describedHomeDir.description); recordBootAttempt(home); // make sure that we are using XStream in the "enhanced" (JVM-specific) mode - if(jvm.bestReflectionProvider().getClass()==PureJavaReflectionProvider.class) { + if (jvm.bestReflectionProvider().getClass() == PureJavaReflectionProvider.class) { throw new IncompatibleVMDetected(); // nope } // make sure this is servlet 2.4 container or above try { - ServletResponse.class.getMethod("setCharacterEncoding",String.class); + ServletResponse.class.getMethod("setCharacterEncoding", String.class); } catch (NoSuchMethodException e) { - throw (IncompatibleServletVersionDetected)new IncompatibleServletVersionDetected(ServletResponse.class).initCause(e); + throw (IncompatibleServletVersionDetected) new IncompatibleServletVersionDetected(ServletResponse.class).initCause(e); } // make sure that we see Ant 1.7 try { FileSet.class.getMethod("getDirectoryScanner"); } catch (NoSuchMethodException e) { - throw (IncompatibleAntVersionDetected)new IncompatibleAntVersionDetected(FileSet.class).initCause(e); + throw (IncompatibleAntVersionDetected) new IncompatibleAntVersionDetected(FileSet.class).initCause(e); } // make sure AWT is functioning, or else JFreeChart won't even load. - if(ChartUtil.awtProblemCause!=null) { + if (ChartUtil.awtProblemCause != null) { throw new AWTProblem(ChartUtil.awtProblemCause); } @@ -232,7 +233,7 @@ public class WebAppMain implements ServletContextListener { installExpressionFactory(event); - context.setAttribute(APP,new HudsonIsLoading()); + context.setAttribute(APP, new HudsonIsLoading()); if (SystemProperties.getBoolean(FORCE_SESSION_TRACKING_BY_COOKIE_PROP, true)) { context.setSessionTrackingModes(EnumSet.of(SessionTrackingMode.COOKIE)); } @@ -257,13 +258,13 @@ public class WebAppMain implements ServletContextListener { LOGGER.info("Jenkins is fully up and running"); success = true; } catch (Error e) { - new HudsonFailedToLoad(e).publish(context,_home); + new HudsonFailedToLoad(e).publish(context, _home); throw e; } catch (Exception e) { - new HudsonFailedToLoad(e).publish(context,_home); + new HudsonFailedToLoad(e).publish(context, _home); } finally { Jenkins instance = Jenkins.getInstanceOrNull(); - if(!success && instance!=null) + if (!success && instance != null) instance.cleanUp(); } } @@ -272,7 +273,7 @@ public class WebAppMain implements ServletContextListener { } catch (BootFailure e) { e.publish(context, home); } catch (Error | RuntimeException e) { - LOGGER.log(SEVERE, "Failed to initialize Jenkins",e); + LOGGER.log(SEVERE, "Failed to initialize Jenkins", e); throw e; } } @@ -288,10 +289,10 @@ public class WebAppMain implements ServletContextListener { * @see BootFailure */ private void recordBootAttempt(File home) { - try (OutputStream o=Files.newOutputStream(BootFailure.getBootFailureFile(home).toPath(), StandardOpenOption.CREATE, StandardOpenOption.APPEND)) { + try (OutputStream o = Files.newOutputStream(BootFailure.getBootFailureFile(home).toPath(), StandardOpenOption.CREATE, StandardOpenOption.APPEND)) { o.write((new Date() + System.getProperty("line.separator", "\n")).getBytes(Charset.defaultCharset())); } catch (IOException | InvalidPathException e) { - LOGGER.log(WARNING, "Failed to record boot attempts",e); + LOGGER.log(WARNING, "Failed to record boot attempts", e); } } @@ -311,7 +312,8 @@ public class WebAppMain implements ServletContextListener { public static class FileAndDescription { public final File file; public final String description; - public FileAndDescription(File file,String description) { + + public FileAndDescription(File file, String description) { this.file = file; this.description = description; } @@ -334,36 +336,36 @@ public class WebAppMain implements ServletContextListener { // check the system property for the home directory first for (String name : HOME_NAMES) { String sysProp = SystemProperties.getString(name); - if(sysProp!=null) - return new FileAndDescription(new File(sysProp.trim()),"SystemProperties.getProperty(\""+name+"\")"); + if (sysProp != null) + return new FileAndDescription(new File(sysProp.trim()), "SystemProperties.getProperty(\"" + name + "\")"); } // look at the env var next for (String name : HOME_NAMES) { String env = EnvVars.masterEnvVars.get(name); - if(env!=null) - return new FileAndDescription(new File(env.trim()).getAbsoluteFile(),"EnvVars.masterEnvVars.get(\""+name+"\")"); + if (env != null) + return new FileAndDescription(new File(env.trim()).getAbsoluteFile(), "EnvVars.masterEnvVars.get(\"" + name + "\")"); } // otherwise pick a place by ourselves String root = event.getServletContext().getRealPath("/WEB-INF/workspace"); - if(root!=null) { + if (root != null) { File ws = new File(root.trim()); - if(ws.exists()) + if (ws.exists()) // Hudson <1.42 used to prefer this before ~/.hudson, so // check the existence and if it's there, use it. // otherwise if this is a new installation, prefer ~/.hudson - return new FileAndDescription(ws,"getServletContext().getRealPath(\"/WEB-INF/workspace\")"); + return new FileAndDescription(ws, "getServletContext().getRealPath(\"/WEB-INF/workspace\")"); } - File legacyHome = new File(new File(System.getProperty("user.home")),".hudson"); + File legacyHome = new File(new File(System.getProperty("user.home")), ".hudson"); if (legacyHome.exists()) { - return new FileAndDescription(legacyHome,"$user.home/.hudson"); // before rename, this is where it was stored + return new FileAndDescription(legacyHome, "$user.home/.hudson"); // before rename, this is where it was stored } - File newHome = new File(new File(System.getProperty("user.home")),".jenkins"); - return new FileAndDescription(newHome,"$user.home/.jenkins"); + File newHome = new File(new File(System.getProperty("user.home")), ".jenkins"); + return new FileAndDescription(newHome, "$user.home/.jenkins"); } @Override @@ -401,5 +403,5 @@ public class WebAppMain implements ServletContextListener { } } - private static final String[] HOME_NAMES = {"JENKINS_HOME","HUDSON_HOME"}; + private static final String[] HOME_NAMES = {"JENKINS_HOME", "HUDSON_HOME"}; } diff --git a/core/src/main/java/hudson/WorkspaceSnapshot.java b/core/src/main/java/hudson/WorkspaceSnapshot.java index 25938f580f05c7f48dc7204baf6c065ac9c57575..19d536700f8a3a003e8afb22cd99da7fc80e63a5 100644 --- a/core/src/main/java/hudson/WorkspaceSnapshot.java +++ b/core/src/main/java/hudson/WorkspaceSnapshot.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson; import hudson.model.AbstractBuild; @@ -44,7 +45,7 @@ public abstract class WorkspaceSnapshot implements Action { * @param listener * Send the progress of the restoration to this listener. Never null. */ - public abstract void restoreTo(AbstractBuild owner, FilePath dst, TaskListener listener) throws IOException, InterruptedException; + public abstract void restoreTo(AbstractBuild owner, FilePath dst, TaskListener listener) throws IOException, InterruptedException; @Override public String getIconFileName() { diff --git a/core/src/main/java/hudson/XmlFile.java b/core/src/main/java/hudson/XmlFile.java index c9f0478f0bb45fac7a0ffd897d0fd036a220764e..f624104df673e647c01d71e53959f3d6c76ce8ca 100644 --- a/core/src/main/java/hudson/XmlFile.java +++ b/core/src/main/java/hudson/XmlFile.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson; import com.thoughtworks.xstream.XStream; @@ -126,7 +127,7 @@ public final class XmlFile { private static final ThreadLocal writing = new ThreadLocal<>(); public XmlFile(File file) { - this(DEFAULT_XSTREAM,file); + this(DEFAULT_XSTREAM, file); } public XmlFile(XStream xs, File file) { @@ -158,12 +159,12 @@ public final class XmlFile { */ public Object read() throws IOException { if (LOGGER.isLoggable(Level.FINE)) { - LOGGER.fine("Reading "+file); + LOGGER.fine("Reading " + file); } try (InputStream in = new BufferedInputStream(Files.newInputStream(file.toPath()))) { return xs.fromXML(in); } catch (RuntimeException | Error e) { - throw new IOException("Unable to read "+file,e); + throw new IOException("Unable to read " + file, e); } } @@ -174,7 +175,7 @@ public final class XmlFile { * The unmarshalled object. Usually the same as {@code o}, but would be different * if the XML representation is completely new. */ - public Object unmarshal( Object o ) throws IOException { + public Object unmarshal(Object o) throws IOException { return unmarshal(o, false); } @@ -195,11 +196,11 @@ public final class XmlFile { return xs.unmarshal(DEFAULT_DRIVER.createReader(in), o); } } catch (RuntimeException | Error e) { - throw new IOException("Unable to read "+file,e); + throw new IOException("Unable to read " + file, e); } } - public void write( Object o ) throws IOException { + public void write(Object o) throws IOException { mkdirs(); AtomicFileWriter w = force ? new AtomicFileWriter(file) @@ -215,7 +216,7 @@ public final class XmlFile { writing.set(null); } w.commit(); - } catch(RuntimeException e) { + } catch (RuntimeException e) { throw new IOException(e); } finally { w.abort(); @@ -250,7 +251,7 @@ public final class XmlFile { public void delete() throws IOException { Files.deleteIfExists(Util.fileToPath(file)); } - + public void mkdirs() throws IOException { Util.createDirectories(Util.fileToPath(file.getParentFile())); } @@ -313,6 +314,7 @@ public final class XmlFile { public String sniffEncoding() throws IOException { class Eureka extends SAXException { final String encoding; + Eureka(String encoding) { this.encoding = encoding; } @@ -345,11 +347,11 @@ public final class XmlFile { } private void attempt() throws Eureka { - if(loc==null) return; + if (loc == null) return; if (loc instanceof Locator2) { Locator2 loc2 = (Locator2) loc; String e = loc2.getEncoding(); - if(e!=null) + if (e != null) throw new Eureka(e); } } @@ -357,7 +359,7 @@ public final class XmlFile { // can't reach here throw new AssertionError(); } catch (Eureka e) { - if(e.encoding!=null) + if (e.encoding != null) return e.encoding; // the environment can contain old version of Xerces and others that do not support Locator2 // in such a case, assume UTF-8 rather than fail, since Jenkins internally always write XML in UTF-8 diff --git a/core/src/main/java/hudson/cli/AbstractBuildRangeCommand.java b/core/src/main/java/hudson/cli/AbstractBuildRangeCommand.java index 8d966dc924d96a1bff1872d2eff506489f626f30..ead7f267ff6084b7b160cebbeff49b9955175442 100644 --- a/core/src/main/java/hudson/cli/AbstractBuildRangeCommand.java +++ b/core/src/main/java/hudson/cli/AbstractBuildRangeCommand.java @@ -15,18 +15,18 @@ import org.kohsuke.args4j.Argument; */ @Deprecated public abstract class AbstractBuildRangeCommand extends CLICommand { - @Argument(metaVar="JOB",usage="Name of the job to build",required=true,index=0) - public AbstractProject job; + @Argument(metaVar = "JOB", usage = "Name of the job to build", required = true, index = 0) + public AbstractProject job; - @Argument(metaVar="RANGE",usage="Range of the build records to delete. 'N-M', 'N,M', or 'N'",required=true,index=1) + @Argument(metaVar = "RANGE", usage = "Range of the build records to delete. 'N-M', 'N,M', or 'N'", required = true, index = 1) public String range; @Override protected int run() throws Exception { - RangeSet rs = RangeSet.fromString(range,false); + RangeSet rs = RangeSet.fromString(range, false); - return act((List)job.getBuilds(rs)); + return act((List) job.getBuilds(rs)); } - protected abstract int act(List> builds) throws IOException; + protected abstract int act(List> builds) throws IOException; } diff --git a/core/src/main/java/hudson/cli/AddJobToViewCommand.java b/core/src/main/java/hudson/cli/AddJobToViewCommand.java index 116ab82adf28b27b438506746ce721b476377039..6bab9deeb7d1ab6f717ef9fe17c316885e30d746 100644 --- a/core/src/main/java/hudson/cli/AddJobToViewCommand.java +++ b/core/src/main/java/hudson/cli/AddJobToViewCommand.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.cli; import hudson.Extension; @@ -37,11 +38,11 @@ import org.kohsuke.args4j.Argument; @Extension public class AddJobToViewCommand extends CLICommand { - @Argument(usage="Name of the view", required=true, index=0) + @Argument(usage = "Name of the view", required = true, index = 0) private View view; @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") - @Argument(usage="Job names", required=true, index=1) + @Argument(usage = "Job names", required = true, index = 1) private List jobs; @Override @@ -56,7 +57,7 @@ public class AddJobToViewCommand extends CLICommand { if (!(view instanceof DirectlyModifiableView)) throw new IllegalStateException( "'" + view.getDisplayName() + "' view can not be modified directly"); - for (TopLevelItem job: jobs) { + for (TopLevelItem job : jobs) { ((DirectlyModifiableView) view).add(job); } diff --git a/core/src/main/java/hudson/cli/BuildCommand.java b/core/src/main/java/hudson/cli/BuildCommand.java index bb84871a7f1c947c69a2c62d9d7d7f9df286e676..b4f7ae15e0a1e5401e9fa309c2cea92e5a3264c3 100644 --- a/core/src/main/java/hudson/cli/BuildCommand.java +++ b/core/src/main/java/hudson/cli/BuildCommand.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.cli; import hudson.AbortException; @@ -70,28 +71,28 @@ public class BuildCommand extends CLICommand { return Messages.BuildCommand_ShortDescription(); } - @Argument(metaVar="JOB",usage="Name of the job to build",required=true) - public Job job; + @Argument(metaVar = "JOB", usage = "Name of the job to build", required = true) + public Job job; - @Option(name="-f", usage="Follow the build progress. Like -s only interrupts are not passed through to the build.") + @Option(name = "-f", usage = "Follow the build progress. Like -s only interrupts are not passed through to the build.") public boolean follow = false; - @Option(name="-s",usage="Wait until the completion/abortion of the command. Interrupts are passed through to the build.") + @Option(name = "-s", usage = "Wait until the completion/abortion of the command. Interrupts are passed through to the build.") public boolean sync = false; - @Option(name="-w",usage="Wait until the start of the command") + @Option(name = "-w", usage = "Wait until the start of the command") public boolean wait = false; - @Option(name="-c",usage="Check for SCM changes before starting the build, and if there's no change, exit without doing a build") + @Option(name = "-c", usage = "Check for SCM changes before starting the build, and if there's no change, exit without doing a build") public boolean checkSCM = false; - @Option(name="-p",usage="Specify the build parameters in the key=value format.") - public Map parameters = new HashMap<>(); + @Option(name = "-p", usage = "Specify the build parameters in the key=value format.") + public Map parameters = new HashMap<>(); - @Option(name="-v",usage="Prints out the console output of the build. Use with -s") + @Option(name = "-v", usage = "Prints out the console output of the build. Use with -s") public boolean consoleOutput = false; - @Option(name="-r") @Deprecated + @Option(name = "-r") @Deprecated public int retryCnt = 10; protected static final String BUILD_SCHEDULING_REFUSED = "Build scheduling Refused by an extension, hence not in Queue."; @@ -103,8 +104,8 @@ public class BuildCommand extends CLICommand { ParametersAction a = null; if (!parameters.isEmpty()) { ParametersDefinitionProperty pdp = job.getProperty(ParametersDefinitionProperty.class); - if (pdp==null) - throw new IllegalStateException(job.getFullDisplayName()+" is not parameterized but the -p option was specified."); + if (pdp == null) + throw new IllegalStateException(job.getFullDisplayName() + " is not parameterized but the -p option was specified."); //TODO: switch to type annotations after the migration to Java 1.8 List values = new ArrayList<>(); @@ -112,7 +113,7 @@ public class BuildCommand extends CLICommand { for (Map.Entry e : parameters.entrySet()) { String name = e.getKey(); ParameterDefinition pd = pdp.getParameterDefinition(name); - if (pd==null) { + if (pd == null) { String nearest = EditDistance.findNearest(name, pdp.getParameterDefinitionNames()); throw new CmdLineException(null, nearest == null ? String.format("'%s' is not a valid parameter.", name) : @@ -120,20 +121,20 @@ public class BuildCommand extends CLICommand { } ParameterValue val = pd.createValue(this, Util.fixNull(e.getValue())); if (val == null) { - throw new CmdLineException(null, String.format("Cannot resolve the value for the parameter '%s'.",name)); + throw new CmdLineException(null, String.format("Cannot resolve the value for the parameter '%s'.", name)); } values.add(val); } // handle missing parameters by adding as default values ISSUE JENKINS-7162 - for(ParameterDefinition pd : pdp.getParameterDefinitions()) { + for (ParameterDefinition pd : pdp.getParameterDefinitions()) { if (parameters.containsKey(pd.getName())) continue; // not passed in use default ParameterValue defaultValue = pd.getDefaultParameterValue(); if (defaultValue == null) { - throw new CmdLineException(null, String.format("No default value for the parameter '%s'.",pd.getName())); + throw new CmdLineException(null, String.format("No default value for the parameter '%s'.", pd.getName())); } values.add(defaultValue); } @@ -144,7 +145,7 @@ public class BuildCommand extends CLICommand { if (checkSCM) { SCMTriggerItem item = SCMTriggerItem.SCMTriggerItems.asSCMTriggerItem(job); if (item == null) - throw new AbortException(job.getFullDisplayName()+" has no SCM trigger, but checkSCM was specified"); + throw new AbortException(job.getFullDisplayName() + " has no SCM trigger, but checkSCM was specified"); // preemptively check for a polling veto if (SCMDecisionHandler.firstShouldPollVeto(job) != null) { return 0; @@ -157,21 +158,21 @@ public class BuildCommand extends CLICommand { String msg = Messages.BuildCommand_CLICause_CannotBuildUnknownReasons(job.getFullDisplayName()); if (job instanceof ParameterizedJobMixIn.ParameterizedJob && ((ParameterizedJobMixIn.ParameterizedJob) job).isDisabled()) { msg = Messages.BuildCommand_CLICause_CannotBuildDisabled(job.getFullDisplayName()); - } else if (job.isHoldOffBuildUntilSave()){ + } else if (job.isHoldOffBuildUntilSave()) { msg = Messages.BuildCommand_CLICause_CannotBuildConfigNotSaved(job.getFullDisplayName()); } throw new IllegalStateException(msg); } Queue.Item item = ParameterizedJobMixIn.scheduleBuild2(job, 0, new CauseAction(new CLICause(Jenkins.getAuthentication2().getName())), a); - QueueTaskFuture> f = item != null ? (QueueTaskFuture)item.getFuture() : null; - + QueueTaskFuture> f = item != null ? (QueueTaskFuture) item.getFuture() : null; + if (wait || sync || follow) { if (f == null) { throw new IllegalStateException(BUILD_SCHEDULING_REFUSED); } - Run b = f.waitForStart(); // wait for the start - stdout.println("Started "+b.getFullDisplayName()); + Run b = f.waitForStart(); // wait for the start + stdout.println("Started " + b.getFullDisplayName()); stdout.flush(); if (sync || follow) { @@ -182,13 +183,13 @@ public class BuildCommand extends CLICommand { // exception on a slow/busy machine, if it takes // longish to create the log file int retryInterval = 100; - for (int i=0;i<=retryCnt;) { + for (int i = 0; i <= retryCnt; ) { try { b.writeWholeLogTo(stdout); break; } catch (FileNotFoundException | NoSuchFileException e) { - if ( i == retryCnt ) { + if (i == retryCnt) { Exception myException = new AbortException(); myException.initCause(e); throw myException; @@ -199,7 +200,7 @@ public class BuildCommand extends CLICommand { } } f.get(); // wait for the completion - stdout.println("Completed "+b.getFullDisplayName()+" : "+b.getResult()); + stdout.println("Completed " + b.getFullDisplayName() + " : " + b.getResult()); return b.getResult().ordinal; } catch (InterruptedException e) { if (follow) { @@ -238,15 +239,15 @@ public class BuildCommand extends CLICommand { public static class CLICause extends UserIdCause { - private String startedBy; + private String startedBy; - public CLICause(){ - startedBy = "unknown"; - } + public CLICause() { + startedBy = "unknown"; + } - public CLICause(String startedBy){ - this.startedBy = startedBy; - } + public CLICause(String startedBy) { + this.startedBy = startedBy; + } @Override public String getShortDescription() { diff --git a/core/src/main/java/hudson/cli/CLIAction.java b/core/src/main/java/hudson/cli/CLIAction.java index a5583b874c97248951a963a78bbeb1913570c008..d42e974452a2cc77c6d99bcc6c2c1cf50986003c 100644 --- a/core/src/main/java/hudson/cli/CLIAction.java +++ b/core/src/main/java/hudson/cli/CLIAction.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.cli; import hudson.Extension; @@ -128,14 +129,17 @@ public class CLIAction implements UnprotectedRootAction, StaplerProxy { sentBytes += data.length; sentCount++; } + @Override public void close() throws IOException { doClose(); } } + private void doClose() { close(); } + @Override protected void opened() { try { @@ -156,6 +160,7 @@ public class CLIAction implements UnprotectedRootAction, StaplerProxy { } }, "CLI handler for " + authentication.getName()).start(); } + @Override protected void binary(byte[] payload, int offset, int len) { try { @@ -166,10 +171,12 @@ public class CLIAction implements UnprotectedRootAction, StaplerProxy { error(x); } } + @Override protected void error(Throwable cause) { LOGGER.log(Level.WARNING, null, cause); } + @Override protected void closed(int statusCode, String reason) { LOGGER.fine(() -> "closed: " + statusCode + ": " + reason); @@ -182,7 +189,7 @@ public class CLIAction implements UnprotectedRootAction, StaplerProxy { @Override public Object getTarget() { StaplerRequest req = Stapler.getCurrentRequest(); - if (req.getRestOfPath().length()==0 && "POST".equals(req.getMethod())) { + if (req.getRestOfPath().length() == 0 && "POST".equals(req.getMethod())) { // CLI connection request if ("false".equals(req.getParameter("remoting"))) { throw new PlainCliEndpointResponse(); @@ -204,15 +211,18 @@ public class CLIAction implements UnprotectedRootAction, StaplerProxy { private final PipedInputStream stdin = new PipedInputStream(); private final PipedOutputStream stdinMatch = new PipedOutputStream(); private final Authentication authentication; + ServerSideImpl(PlainCLIProtocol.Output out, Authentication authentication) throws IOException { super(out); stdinMatch.connect(stdin); this.authentication = authentication; } + @Override protected void onArg(String text) { args.add(text); } + @Override protected void onLocale(String text) { for (Locale _locale : Locale.getAvailableLocales()) { @@ -223,6 +233,7 @@ public class CLIAction implements UnprotectedRootAction, StaplerProxy { } LOGGER.log(Level.WARNING, "unknown client locale {0}", text); } + @Override protected void onEncoding(String text) { try { @@ -231,18 +242,22 @@ public class CLIAction implements UnprotectedRootAction, StaplerProxy { LOGGER.log(Level.WARNING, "unknown client charset {0}", text); } } + @Override protected void onStart() { ready(); } + @Override protected void onStdin(byte[] chunk) throws IOException { stdinMatch.write(chunk); } + @Override protected void onEndStdin() throws IOException { stdinMatch.close(); } + @Override protected void handleClose() { ready(); @@ -250,10 +265,12 @@ public class CLIAction implements UnprotectedRootAction, StaplerProxy { runningThread.interrupt(); } } + private synchronized void ready() { ready = true; notifyAll(); } + void run() throws IOException, InterruptedException { synchronized (this) { while (!ready) { diff --git a/core/src/main/java/hudson/cli/CLICommand.java b/core/src/main/java/hudson/cli/CLICommand.java index d27d0b6beff5fcfb8a8a16ef146df6a6105ddf7e..389f0bcbf71c8f97fce01d74ea281b57e4fb1141 100644 --- a/core/src/main/java/hudson/cli/CLICommand.java +++ b/core/src/main/java/hudson/cli/CLICommand.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.cli; import edu.umd.cs.findbugs.annotations.CheckForNull; @@ -115,15 +116,15 @@ public abstract class CLICommand implements ExtensionPoint, Cloneable { * (In contrast, calling {@code System.out.println(...)} would print out * the message to the server log file, which is probably not what you want. */ - public transient PrintStream stdout,stderr; + public transient PrintStream stdout, stderr; /** - * Shared text, which is reported back to CLI if an error happens in commands + * Shared text, which is reported back to CLI if an error happens in commands * taking lists of parameters. * @since 2.26 */ static final String CLI_LISTPARAM_SUMMARY_ERROR_TEXT = "Error occurred while performing this command, see previous stderr output."; - + /** * Connected to stdin of the CLI agent. * @@ -168,13 +169,13 @@ public abstract class CLICommand implements ExtensionPoint, Cloneable { public String getName() { String name = getClass().getName(); name = name.substring(name.lastIndexOf('.') + 1); // short name - name = name.substring(name.lastIndexOf('$')+1); - if(name.endsWith("Command")) - name = name.substring(0,name.length()-7); // trim off the command + name = name.substring(name.lastIndexOf('$') + 1); + if (name.endsWith("Command")) + name = name.substring(0, name.length() - 7); // trim off the command // convert "FooBarZot" into "foo-bar-zot" // Locale is fixed so that "CreateInstance" always become "create-instance" no matter where this is run. - return name.replaceAll("([a-z0-9])([A-Z])","$1-$2").toLowerCase(Locale.ENGLISH); + return name.replaceAll("([a-z0-9])([A-Z])", "$1-$2").toLowerCase(Locale.ENGLISH); } /** @@ -185,7 +186,7 @@ public abstract class CLICommand implements ExtensionPoint, Cloneable { /** * Entry point to the CLI command. - * + * *

* The default implementation uses args4j to parse command line arguments and call {@link #run()}, * but if that processing is undesirable, subtypes can directly override this method and leave {@link #run()} @@ -280,7 +281,7 @@ public abstract class CLICommand implements ExtensionPoint, Cloneable { Functions.printStackTrace(e, stderr); return 1; } finally { - if(sc != null) + if (sc != null) sc.setAuthentication(old); // restore } } @@ -335,8 +336,8 @@ public abstract class CLICommand implements ExtensionPoint, Cloneable { * @since 2.266 */ public Authentication getTransportAuthentication2() { - Authentication a = transportAuth; - if (a==null) a = Jenkins.ANONYMOUS2; + Authentication a = transportAuth; + if (a == null) a = Jenkins.ANONYMOUS2; return a; } @@ -365,7 +366,7 @@ public abstract class CLICommand implements ExtensionPoint, Cloneable { /** * Executes the command, and return the exit code. - * + * *

* This is an internal contract between {@link CLICommand} and its subtype. * To execute CLI method from outside, use {@link #main(List, Locale, InputStream, PrintStream, PrintStream)} @@ -446,7 +447,7 @@ public abstract class CLICommand implements ExtensionPoint, Cloneable { /** * Called while producing usage. This is a good method to override * to render the general description of the command that goes beyond - * a single-line summary. + * a single-line summary. */ protected void printUsageSummary(PrintStream stderr) { stderr.println(getShortDescription()); @@ -505,9 +506,9 @@ public abstract class CLICommand implements ExtensionPoint, Cloneable { */ protected void registerOptionHandlers() { try { - for (Class c : Index.list(OptionHandlerExtension.class, Jenkins.get().pluginManager.uberClassLoader,Class.class)) { + for (Class c : Index.list(OptionHandlerExtension.class, Jenkins.get().pluginManager.uberClassLoader, Class.class)) { Type t = Types.getBaseClass(c, OptionHandler.class); - CmdLineParser.registerHandler(Types.erasure(Types.getTypeArgument(t,0)), c); + CmdLineParser.registerHandler(Types.erasure(Types.getTypeArgument(t, 0)), c); } } catch (IOException e) { throw new Error(e); @@ -526,7 +527,7 @@ public abstract class CLICommand implements ExtensionPoint, Cloneable { */ public static CLICommand clone(String name) { for (CLICommand cmd : all()) - if(name.equals(cmd.getName())) + if (name.equals(cmd.getName())) return cmd.createClone(); return null; } @@ -560,10 +561,10 @@ public abstract class CLICommand implements ExtensionPoint, Cloneable { final ResourceClassIterator itr = new DiscoverClasses(cls).findResourceClasses(servicesIter); - while(itr.hasNext()) { + while (itr.hasNext()) { Class h = itr.nextResourceClass().loadClass(); Class c = Types.erasure(Types.getTypeArgument(Types.getBaseClass(h, OptionHandler.class), 0)); - CmdLineParser.registerHandler(c,h); + CmdLineParser.registerHandler(c, h); } } } diff --git a/core/src/main/java/hudson/cli/CliCrumbExclusion.java b/core/src/main/java/hudson/cli/CliCrumbExclusion.java index f96547788610702fe77131e4cb879799ade6ab59..4e3064f4317822d2e3fffb0afbf39a7cd37a5cc8 100644 --- a/core/src/main/java/hudson/cli/CliCrumbExclusion.java +++ b/core/src/main/java/hudson/cli/CliCrumbExclusion.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.cli; import hudson.Extension; diff --git a/core/src/main/java/hudson/cli/CloneableCLICommand.java b/core/src/main/java/hudson/cli/CloneableCLICommand.java index f6a4c60b02c12a17b77481735f1d3b421adfe800..74d789179f5f854fca16ca914569f2fa54d060ea 100644 --- a/core/src/main/java/hudson/cli/CloneableCLICommand.java +++ b/core/src/main/java/hudson/cli/CloneableCLICommand.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.cli; /** @@ -34,7 +35,7 @@ public abstract class CloneableCLICommand extends CLICommand implements Cloneabl @Override protected CLICommand createClone() { try { - return (CLICommand)clone(); + return (CLICommand) clone(); } catch (CloneNotSupportedException e) { throw new AssertionError(e); } diff --git a/core/src/main/java/hudson/cli/ConnectNodeCommand.java b/core/src/main/java/hudson/cli/ConnectNodeCommand.java index 6968bb274f77c223e2845fcb67df04ed063e69b3..0d3e9049205adc3a8ea26db273a34011ccfa1a6f 100644 --- a/core/src/main/java/hudson/cli/ConnectNodeCommand.java +++ b/core/src/main/java/hudson/cli/ConnectNodeCommand.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.cli; import hudson.AbortException; @@ -41,10 +42,10 @@ import org.kohsuke.args4j.Option; public class ConnectNodeCommand extends CLICommand { @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") - @Argument(metaVar="NAME", usage="Agent name, or empty string for built-in node; comma-separated list is supported", required=true, multiValued=true) + @Argument(metaVar = "NAME", usage = "Agent name, or empty string for built-in node; comma-separated list is supported", required = true, multiValued = true) private List nodes; - @Option(name="-f", usage="Cancel any currently pending connect operation and retry from scratch") + @Option(name = "-f", usage = "Cancel any currently pending connect operation and retry from scratch") public boolean force = false; private static final Logger LOGGER = Logger.getLogger(ConnectNodeCommand.class.getName()); diff --git a/core/src/main/java/hudson/cli/Connection.java b/core/src/main/java/hudson/cli/Connection.java index fb2568717532c05dc7b0d0add0cf9513e19d6ee5..eb97d996ff01f6040dc4c64a11c64829bfbb69b7 100644 --- a/core/src/main/java/hudson/cli/Connection.java +++ b/core/src/main/java/hudson/cli/Connection.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.cli; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; @@ -69,7 +70,7 @@ public class Connection { public final DataOutputStream dout; public Connection(Socket socket) throws IOException { - this(SocketChannelStream.in(socket),SocketChannelStream.out(socket)); + this(SocketChannelStream.in(socket), SocketChannelStream.out(socket)); } public Connection(InputStream in, OutputStream out) { @@ -118,7 +119,7 @@ public class Connection { public T readObject() throws IOException, ClassNotFoundException { ObjectInputStream ois = new ObjectInputStreamEx(in, getClass().getClassLoader(), ClassFilter.DEFAULT); - return (T)ois.readObject(); + return (T) ois.readObject(); } public void writeKey(Key key) throws IOException { @@ -153,8 +154,9 @@ public class Connection { * each other. */ public KeyAgreement diffieHellman(boolean side) throws IOException, GeneralSecurityException { - return diffieHellman(side,512); + return diffieHellman(side, 512); } + public KeyAgreement diffieHellman(boolean side, int keySize) throws IOException, GeneralSecurityException { KeyPair keyPair; PublicKey otherHalf; @@ -203,7 +205,7 @@ public class Connection { cin.init(Cipher.DECRYPT_MODE, sessionKey, createIv(sessionKey)); CipherInputStream i = new CipherInputStream(in, cin); - return new Connection(i,o); + return new Connection(i, o); } private IvParameterSpec createIv(SecretKey sessionKey) { @@ -218,8 +220,8 @@ public class Connection { */ public static byte[] fold(byte[] bytes, int size) { byte[] r = new byte[size]; - for (int i=Math.max(bytes.length,size)-1; i>=0; i-- ) { - r[i%r.length] ^= bytes[i%bytes.length]; + for (int i = Math.max(bytes.length, size) - 1; i >= 0; i--) { + r[i % r.length] ^= bytes[i % bytes.length]; } return r; } @@ -231,7 +233,7 @@ public class Connection { private String detectKeyAlgorithm(PublicKey kp) { if (kp instanceof RSAPublicKey) return "RSA"; if (kp instanceof DSAPublicKey) return "DSA"; - throw new IllegalArgumentException("Unknown public key type: "+kp); + throw new IllegalArgumentException("Unknown public key type: " + kp); } /** @@ -243,7 +245,7 @@ public class Connection { writeUTF(algorithm); writeKey(key.getPublic()); - Signature sig = Signature.getInstance("SHA1with"+algorithm); + Signature sig = Signature.getInstance("SHA1with" + algorithm); sig.initSign(key.getPrivate()); sig.update(key.getPublic().getEncoded()); sig.update(sharedSecret); @@ -259,7 +261,7 @@ public class Connection { PublicKey spk = KeyFactory.getInstance(serverKeyAlgorithm).generatePublic(readKey()); // verify the identity of the server - Signature sig = Signature.getInstance("SHA1with"+serverKeyAlgorithm); + Signature sig = Signature.getInstance("SHA1with" + serverKeyAlgorithm); sig.initVerify(spk); sig.update(spk.getEncoded()); sig.update(sharedSecret); diff --git a/core/src/main/java/hudson/cli/ConsoleCommand.java b/core/src/main/java/hudson/cli/ConsoleCommand.java index 771a40b8c9f74c6703232c64364dc5d6fe950278..12d9ef1dff2d3b62c58bfff4f0e170f1a0273b08 100644 --- a/core/src/main/java/hudson/cli/ConsoleCommand.java +++ b/core/src/main/java/hudson/cli/ConsoleCommand.java @@ -27,36 +27,36 @@ public class ConsoleCommand extends CLICommand { return Messages.ConsoleCommand_ShortDescription(); } - @Argument(metaVar="JOB",usage="Name of the job",required=true) - public Job job; + @Argument(metaVar = "JOB", usage = "Name of the job", required = true) + public Job job; - @Argument(metaVar="BUILD",usage="Build number or permalink to point to the build. Defaults to the last build",required=false,index=1) - public String build="lastBuild"; + @Argument(metaVar = "BUILD", usage = "Build number or permalink to point to the build. Defaults to the last build", required = false, index = 1) + public String build = "lastBuild"; - @Option(name="-f",usage="If the build is in progress, stay around and append console output as it comes, like 'tail -f'") + @Option(name = "-f", usage = "If the build is in progress, stay around and append console output as it comes, like 'tail -f'") public boolean follow = false; - @Option(name="-n",metaVar="N",usage="Display the last N lines") + @Option(name = "-n", metaVar = "N", usage = "Display the last N lines") public int n = -1; @Override protected int run() throws Exception { job.checkPermission(Item.READ); - Run run; + Run run; try { int n = Integer.parseInt(build); run = job.getBuildByNumber(n); - if (run==null) - throw new IllegalArgumentException("No such build #"+n); + if (run == null) + throw new IllegalArgumentException("No such build #" + n); } catch (NumberFormatException e) { // maybe a permalink? Permalink p = job.getPermalinks().get(build); - if (p!=null) { + if (p != null) { run = p.resolve(job); - if (run==null) - throw new IllegalStateException("Permalink "+build+" produced no build", e); + if (run == null) + throw new IllegalStateException("Permalink " + build + " produced no build", e); } else { Permalink nearest = job.getPermalinks().findNearest(build); throw new IllegalArgumentException(nearest == null ? @@ -68,7 +68,7 @@ public class ConsoleCommand extends CLICommand { OutputStreamWriter w = new OutputStreamWriter(stdout, getClientCharset()); try { - long pos = n>=0 ? seek(run) : 0; + long pos = n >= 0 ? seek(run) : 0; if (follow) { AnnotatedLargeText logText; @@ -97,38 +97,39 @@ public class ConsoleCommand extends CLICommand { private long seek(Run run) throws IOException { class RingBuffer { long[] lastNlines = new long[n]; - int ptr=0; + int ptr = 0; RingBuffer() { - for (int i=0; i=0) { - for (int i=0; i= 0) { + for (int i = 0; i < len; i++) { byte ch = buf[i]; - boolean isNL = ch=='\r' || ch=='\n'; + boolean isNL = ch == '\r' || ch == '\n'; if (!isNL && prevIsNL) rb.add(pos); - if (isNL && prevIsNL && !(prev=='\r' && ch=='\n')) rb.add(pos); + if (isNL && prevIsNL && !(prev == '\r' && ch == '\n')) rb.add(pos); pos++; prev = ch; prevIsNL = isNL; diff --git a/core/src/main/java/hudson/cli/CopyJobCommand.java b/core/src/main/java/hudson/cli/CopyJobCommand.java index 41aa8836b704ed00da233cd415375588e852e203..021d34d7616728d4ac1d6a0492a1d1d614356d6a 100644 --- a/core/src/main/java/hudson/cli/CopyJobCommand.java +++ b/core/src/main/java/hudson/cli/CopyJobCommand.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.cli; import hudson.Extension; @@ -32,7 +33,7 @@ import org.kohsuke.args4j.Argument; /** * Copies a job from CLI. - * + * * @author Kohsuke Kawaguchi */ @Extension @@ -42,18 +43,18 @@ public class CopyJobCommand extends CLICommand { return Messages.CopyJobCommand_ShortDescription(); } - @Argument(metaVar="SRC",usage="Name of the job to copy",required=true) + @Argument(metaVar = "SRC", usage = "Name of the job to copy", required = true) public TopLevelItem src; - @Argument(metaVar="DST",usage="Name of the new job to be created.",index=1,required=true) + @Argument(metaVar = "DST", usage = "Name of the new job to be created.", index = 1, required = true) public String dst; @Override protected int run() throws Exception { Jenkins jenkins = Jenkins.get(); - if (jenkins.getItemByFullName(dst)!=null) { - throw new IllegalStateException("Job '"+dst+"' already exists"); + if (jenkins.getItemByFullName(dst) != null) { + throw new IllegalStateException("Job '" + dst + "' already exists"); } ModifiableTopLevelItemGroup ig = jenkins; @@ -73,7 +74,7 @@ public class CopyJobCommand extends CLICommand { dst = dst.substring(i + 1); } - ig.copy(src,dst).save(); + ig.copy(src, dst).save(); return 0; } } diff --git a/core/src/main/java/hudson/cli/CreateJobCommand.java b/core/src/main/java/hudson/cli/CreateJobCommand.java index 859d3e060c1377ecc42ee97c6e07b6b8d96c3f47..4b3dc23d98579d7ee882f3a437b9fa68c32052a9 100644 --- a/core/src/main/java/hudson/cli/CreateJobCommand.java +++ b/core/src/main/java/hudson/cli/CreateJobCommand.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.cli; import hudson.Extension; @@ -31,7 +32,7 @@ import org.kohsuke.args4j.Argument; /** * Creates a new job by reading stdin as a configuration XML file. - * + * * @author Kohsuke Kawaguchi */ @Extension @@ -41,15 +42,15 @@ public class CreateJobCommand extends CLICommand { return Messages.CreateJobCommand_ShortDescription(); } - @Argument(metaVar="NAME",usage="Name of the job to create",required=true) + @Argument(metaVar = "NAME", usage = "Name of the job to create", required = true) public String name; @Override protected int run() throws Exception { Jenkins h = Jenkins.get(); - if (h.getItemByFullName(name)!=null) { - throw new IllegalStateException("Job '"+name+"' already exists"); + if (h.getItemByFullName(name) != null) { + throw new IllegalStateException("Job '" + name + "' already exists"); } ModifiableTopLevelItemGroup ig = h; diff --git a/core/src/main/java/hudson/cli/CreateNodeCommand.java b/core/src/main/java/hudson/cli/CreateNodeCommand.java index 81b91af89986ae0bbcad978512315ada3d31105a..24aa9256e0067371c901902937cde030cfd02db3 100644 --- a/core/src/main/java/hudson/cli/CreateNodeCommand.java +++ b/core/src/main/java/hudson/cli/CreateNodeCommand.java @@ -37,7 +37,7 @@ import org.kohsuke.args4j.Argument; @Extension public class CreateNodeCommand extends CLICommand { - @Argument(metaVar="NODE", usage="Name of the node") + @Argument(metaVar = "NODE", usage = "Name of the node") public String nodeName; @Override diff --git a/core/src/main/java/hudson/cli/CreateViewCommand.java b/core/src/main/java/hudson/cli/CreateViewCommand.java index 0506c3a002376a8d0b345eb69643004a1ea546d5..db61aa59127675519ab858181275e04482ccd567 100644 --- a/core/src/main/java/hudson/cli/CreateViewCommand.java +++ b/core/src/main/java/hudson/cli/CreateViewCommand.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.cli; import hudson.Extension; @@ -36,7 +37,7 @@ import org.kohsuke.args4j.Argument; @Extension public class CreateViewCommand extends CLICommand { - @Argument(usage="Name of the view to use instead of the one in XML") + @Argument(usage = "Name of the view to use instead of the one in XML") public String viewName = null; @Override diff --git a/core/src/main/java/hudson/cli/DeleteBuildsCommand.java b/core/src/main/java/hudson/cli/DeleteBuildsCommand.java index c0a86ad3cbc4f842cff94dba083265c4a34c5d97..6d62eb9db937f38a91853c5dd266368c1c82ff7c 100644 --- a/core/src/main/java/hudson/cli/DeleteBuildsCommand.java +++ b/core/src/main/java/hudson/cli/DeleteBuildsCommand.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.cli; import hudson.Extension; @@ -65,7 +66,7 @@ public class DeleteBuildsCommand extends RunRangeCommand { } } - stdout.println("Deleted "+hsBuilds.size()+" builds"); + stdout.println("Deleted " + hsBuilds.size() + " builds"); return 0; } diff --git a/core/src/main/java/hudson/cli/DeleteJobCommand.java b/core/src/main/java/hudson/cli/DeleteJobCommand.java index f3c4924968f1ed37c3ef8ad06885feb3ab61e3c0..b203fc59c1c25e174545345be6d63584cd0cad60 100644 --- a/core/src/main/java/hudson/cli/DeleteJobCommand.java +++ b/core/src/main/java/hudson/cli/DeleteJobCommand.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.cli; import hudson.AbortException; @@ -41,7 +42,7 @@ import org.kohsuke.args4j.Argument; public class DeleteJobCommand extends CLICommand { @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") - @Argument(usage="Name of the job(s) to delete", required=true, multiValued=true) + @Argument(usage = "Name of the job(s) to delete", required = true, multiValued = true) private List jobs; @Override @@ -58,20 +59,20 @@ public class DeleteJobCommand extends CLICommand { final HashSet hs = new HashSet<>(jobs); - for (String job_s: hs) { + for (String job_s : hs) { AbstractItem job; try { job = (AbstractItem) jenkins.getItemByFullName(job_s); - if(job == null) { + if (job == null) { throw new IllegalArgumentException("No such job '" + job_s + "'"); } job.checkPermission(Item.DELETE); job.delete(); } catch (Exception e) { - if(hs.size() == 1) { + if (hs.size() == 1) { throw e; } diff --git a/core/src/main/java/hudson/cli/DeleteNodeCommand.java b/core/src/main/java/hudson/cli/DeleteNodeCommand.java index 1b77a8e20eabe9ec18f289d6dde3b3f652507a40..5989aa247b6729eb3cd9144cef81c0c19afd1cbf 100644 --- a/core/src/main/java/hudson/cli/DeleteNodeCommand.java +++ b/core/src/main/java/hudson/cli/DeleteNodeCommand.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.cli; import hudson.AbortException; @@ -40,7 +41,7 @@ import org.kohsuke.args4j.Argument; public class DeleteNodeCommand extends CLICommand { @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") - @Argument(usage="Names of nodes to delete", required=true, multiValued=true) + @Argument(usage = "Names of nodes to delete", required = true, multiValued = true) private List nodes; @Override @@ -69,7 +70,7 @@ public class DeleteNodeCommand extends CLICommand { node.toComputer().doDoDelete(); } catch (Exception e) { - if(hs.size() == 1) { + if (hs.size() == 1) { throw e; } diff --git a/core/src/main/java/hudson/cli/DeleteViewCommand.java b/core/src/main/java/hudson/cli/DeleteViewCommand.java index 436bf34f30d355b3afd686b4519b83ecebb47433..33a1743464b43014cc6f6be4e5ed53c9d09491a6 100644 --- a/core/src/main/java/hudson/cli/DeleteViewCommand.java +++ b/core/src/main/java/hudson/cli/DeleteViewCommand.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.cli; import hudson.AbortException; @@ -40,7 +41,7 @@ import org.kohsuke.args4j.Argument; public class DeleteViewCommand extends CLICommand { @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") - @Argument(usage="View names to delete", required=true, multiValued=true) + @Argument(usage = "View names to delete", required = true, multiValued = true) private List views; @Override @@ -59,7 +60,7 @@ public class DeleteViewCommand extends CLICommand { ViewOptionHandler voh = new ViewOptionHandler(null, null, null); - for(String view_s : hs) { + for (String view_s : hs) { View view; try { @@ -80,7 +81,7 @@ public class DeleteViewCommand extends CLICommand { group.deleteView(view); } catch (Exception e) { - if(hs.size() == 1) { + if (hs.size() == 1) { throw e; } diff --git a/core/src/main/java/hudson/cli/DisablePluginCommand.java b/core/src/main/java/hudson/cli/DisablePluginCommand.java index 79d3a09f82501832456907bcb3860202d16d8a19..53af28828ddb6ae7499e93a52fcb86ec9611d100 100644 --- a/core/src/main/java/hudson/cli/DisablePluginCommand.java +++ b/core/src/main/java/hudson/cli/DisablePluginCommand.java @@ -221,13 +221,13 @@ public class DisablePluginCommand extends CLICommand { */ private int getResultCode(PluginWrapper.PluginDisableResult result) { int returnCode = 0; - switch (result.getStatus()){ + switch (result.getStatus()) { case NOT_DISABLED_DEPENDANTS: returnCode = RETURN_CODE_NOT_DISABLED_DEPENDANTS; break; case NO_SUCH_PLUGIN: returnCode = RETURN_CODE_NO_SUCH_PLUGIN; - break; + break; default: for (PluginWrapper.PluginDisableResult oneDependentResult : result.getDependentsDisableStatus()) { returnCode = getResultCode(oneDependentResult); diff --git a/core/src/main/java/hudson/cli/DisconnectNodeCommand.java b/core/src/main/java/hudson/cli/DisconnectNodeCommand.java index 4ae3b057532d290f537cb6cd4294fec68974db35..eb080cf1eb987fc571ecc92875a9110a27eb3f5b 100644 --- a/core/src/main/java/hudson/cli/DisconnectNodeCommand.java +++ b/core/src/main/java/hudson/cli/DisconnectNodeCommand.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.cli; import hudson.AbortException; diff --git a/core/src/main/java/hudson/cli/GetJobCommand.java b/core/src/main/java/hudson/cli/GetJobCommand.java index f26ad48bdb3a4c7605f7484d085f48cd292e4143..d94044ef461c25203f452f5a981395f46e833bb8 100644 --- a/core/src/main/java/hudson/cli/GetJobCommand.java +++ b/core/src/main/java/hudson/cli/GetJobCommand.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.cli; import hudson.Extension; @@ -32,7 +33,7 @@ import org.kohsuke.args4j.Argument; */ @Extension public class GetJobCommand extends CLICommand { - @Argument(metaVar="JOB",usage="Name of the job",required=true) + @Argument(metaVar = "JOB", usage = "Name of the job", required = true) public AbstractItem job; @Override diff --git a/core/src/main/java/hudson/cli/GetNodeCommand.java b/core/src/main/java/hudson/cli/GetNodeCommand.java index d508a594075933a7e19d5cb1bf3286985603ed05..62dd21826029ea4eca94cd0260a894aa21ed0f8e 100644 --- a/core/src/main/java/hudson/cli/GetNodeCommand.java +++ b/core/src/main/java/hudson/cli/GetNodeCommand.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.cli; import hudson.Extension; @@ -37,7 +38,7 @@ import org.kohsuke.args4j.Argument; @Extension public class GetNodeCommand extends CLICommand { - @Argument(metaVar="NODE", usage="Name of the node", required=true) + @Argument(metaVar = "NODE", usage = "Name of the node", required = true) public Node node; @Override diff --git a/core/src/main/java/hudson/cli/GetViewCommand.java b/core/src/main/java/hudson/cli/GetViewCommand.java index 1486d324ebc825b09d13647ffacd89164d21b08f..e94bb7947a8125599b2f8ae9b698a8365ff58d29 100644 --- a/core/src/main/java/hudson/cli/GetViewCommand.java +++ b/core/src/main/java/hudson/cli/GetViewCommand.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.cli; import hudson.Extension; @@ -34,7 +35,7 @@ import org.kohsuke.args4j.Argument; @Extension public class GetViewCommand extends CLICommand { - @Argument(usage="Name of the view to obtain", required=true) + @Argument(usage = "Name of the view to obtain", required = true) private View view; @Override diff --git a/core/src/main/java/hudson/cli/GroovyCommand.java b/core/src/main/java/hudson/cli/GroovyCommand.java index bb894bf5389c3ec26aa487581decb383027c3c27..066fd909fa86472c141db6f91e312e35cf340c6e 100644 --- a/core/src/main/java/hudson/cli/GroovyCommand.java +++ b/core/src/main/java/hudson/cli/GroovyCommand.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.cli; import groovy.lang.Binding; @@ -47,13 +48,13 @@ public class GroovyCommand extends CLICommand { return Messages.GroovyCommand_ShortDescription(); } - @Argument(metaVar="SCRIPT",usage="Script to be executed. Only '=' (to represent stdin) is supported.") + @Argument(metaVar = "SCRIPT", usage = "Script to be executed. Only '=' (to represent stdin) is supported.") public String script; /** * Remaining arguments. */ - @Argument(metaVar="ARGUMENTS", index=1, usage="Command line arguments to pass into script.") + @Argument(metaVar = "ARGUMENTS", index = 1, usage = "Command line arguments to pass into script.") public List remaining = new ArrayList<>(); @Override @@ -62,13 +63,13 @@ public class GroovyCommand extends CLICommand { Jenkins.get().checkPermission(Jenkins.ADMINISTER); Binding binding = new Binding(); - binding.setProperty("out",new PrintWriter(stdout,true)); - binding.setProperty("stdin",stdin); - binding.setProperty("stdout",stdout); - binding.setProperty("stderr",stderr); + binding.setProperty("out", new PrintWriter(stdout, true)); + binding.setProperty("stdin", stdin); + binding.setProperty("stdout", stdout); + binding.setProperty("stderr", stderr); GroovyShell groovy = new GroovyShell(Jenkins.get().getPluginManager().uberClassLoader, binding); - groovy.run(loadScript(),"RemoteClass",remaining.toArray(new String[0])); + groovy.run(loadScript(), "RemoteClass", remaining.toArray(new String[0])); return 0; } @@ -76,7 +77,7 @@ public class GroovyCommand extends CLICommand { * Loads the script from the argument. */ private String loadScript() throws CmdLineException, IOException, InterruptedException { - if(script==null) + if (script == null) throw new CmdLineException(null, "No script is specified"); if (script.equals("=")) return IOUtils.toString(stdin); diff --git a/core/src/main/java/hudson/cli/GroovyshCommand.java b/core/src/main/java/hudson/cli/GroovyshCommand.java index d7eb47453be3aa14c62f960b1073f7b761bc2e8d..75c0a9c18e375a0fd57015f1dc7d9827562c0ae3 100644 --- a/core/src/main/java/hudson/cli/GroovyshCommand.java +++ b/core/src/main/java/hudson/cli/GroovyshCommand.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.cli; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; @@ -54,7 +55,7 @@ public class GroovyshCommand extends CLICommand { return Messages.GroovyshCommand_ShortDescription(); } - @Argument(metaVar="ARGS") public List args = new ArrayList<>(); + @Argument(metaVar = "ARGS") public List args = new ArrayList<>(); @Override protected int run() { @@ -83,23 +84,23 @@ public class GroovyshCommand extends CLICommand { Binding binding = new Binding(); // redirect "println" to the CLI - binding.setProperty("out", new PrintWriter(stdout,true)); + binding.setProperty("out", new PrintWriter(stdout, true)); binding.setProperty("hudson", Jenkins.get()); // backward compatibility binding.setProperty("jenkins", Jenkins.get()); - IO io = new IO(new BufferedInputStream(stdin),stdout,stderr); + IO io = new IO(new BufferedInputStream(stdin), stdout, stderr); final ClassLoader cl = Jenkins.get().pluginManager.uberClassLoader; Closure registrar = new Closure(null, null) { private static final long serialVersionUID = 1L; @SuppressWarnings("unused") - @SuppressFBWarnings(value="UMAC_UNCALLABLE_METHOD_OF_ANONYMOUS_CLASS",justification="Closure invokes this via reflection") + @SuppressFBWarnings(value = "UMAC_UNCALLABLE_METHOD_OF_ANONYMOUS_CLASS", justification = "Closure invokes this via reflection") public Object doCall(Object[] args) { assert args.length == 1; assert args[0] instanceof Shell; - Shell shell = (Shell)args[0]; + Shell shell = (Shell) args[0]; XmlCommandRegistrar r = new XmlCommandRegistrar(shell, cl); r.register(GroovyshCommand.class.getResource("commands.xml")); diff --git a/core/src/main/java/hudson/cli/HelpCommand.java b/core/src/main/java/hudson/cli/HelpCommand.java index 0743dc8e4d84015f15d6e3d4797884d4388de791..9e606102894b6cd7a88be494ed8c45d4b11848a9 100644 --- a/core/src/main/java/hudson/cli/HelpCommand.java +++ b/core/src/main/java/hudson/cli/HelpCommand.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.cli; import hudson.AbortException; @@ -39,7 +40,7 @@ import org.springframework.security.access.AccessDeniedException; @Extension public class HelpCommand extends CLICommand { - @Argument(metaVar="COMMAND", usage="Name of the command") + @Argument(metaVar = "COMMAND", usage = "Name of the command") public String command; @Override @@ -63,13 +64,13 @@ public class HelpCommand extends CLICommand { } private int showAllCommands() { - Map commands = new TreeMap<>(); + Map commands = new TreeMap<>(); for (CLICommand c : CLICommand.all()) - commands.put(c.getName(),c); + commands.put(c.getName(), c); for (CLICommand c : commands.values()) { - stderr.println(" "+c.getName()); - stderr.println(" "+c.getShortDescription()); + stderr.println(" " + c.getName()); + stderr.println(" " + c.getShortDescription()); } return 0; @@ -83,7 +84,7 @@ public class HelpCommand extends CLICommand { } command.printUsage(stderr, command.getCmdLineParser()); - + return 0; } } diff --git a/core/src/main/java/hudson/cli/InstallPluginCommand.java b/core/src/main/java/hudson/cli/InstallPluginCommand.java index d39c13f6a8c8b929c41dfc71d3fdba9ae3d0cfd1..cc9d3b59f91d417ac57f7bdb88613a2c6474289f 100644 --- a/core/src/main/java/hudson/cli/InstallPluginCommand.java +++ b/core/src/main/java/hudson/cli/InstallPluginCommand.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.cli; import hudson.AbortException; @@ -48,7 +49,7 @@ import org.kohsuke.args4j.Option; /** * Installs a plugin either from a file, an URL, or from update center. - * + * * @author Kohsuke Kawaguchi * @since 1.331 */ @@ -60,7 +61,7 @@ public class InstallPluginCommand extends CLICommand { return Messages.InstallPluginCommand_ShortDescription(); } - @Argument(metaVar="SOURCE",required=true,usage= + @Argument(metaVar = "SOURCE", required = true, usage = "If this is an URL, Jenkins downloads the URL and installs that as a plugin. " + "If it is the string ‘=’, the file will be read from standard input of the command. " + "Otherwise the name is assumed to be the short name of the plugin in the existing update center (like ‘findbugs’), " + @@ -73,10 +74,10 @@ public class InstallPluginCommand extends CLICommand { @Option(name = "-name", usage = "No longer used.") public String name; - @Option(name="-restart",usage="Restart Jenkins upon successful installation.") + @Option(name = "-restart", usage = "Restart Jenkins upon successful installation.") public boolean restart; - @Option(name="-deploy",usage="Deploy plugins right away without postponing them until the reboot.") + @Option(name = "-deploy", usage = "Deploy plugins right away without postponing them until the reboot.") public boolean dynamicLoad; @Override @@ -124,15 +125,15 @@ public class InstallPluginCommand extends CLICommand { } else { // try to find matching min version number VersionNumber version = new VersionNumber(source.substring(index + 1)); - p = h.getUpdateCenter().getPlugin(source.substring(0,index), version); + p = h.getUpdateCenter().getPlugin(source.substring(0, index), version); if (p == null) { p = h.getUpdateCenter().getPlugin(source); } } - if (p!=null) { + if (p != null) { stdout.println(Messages.InstallPluginCommand_InstallingFromUpdateCenter(source)); Throwable e = p.deploy(dynamicLoad).get().getError(); - if (e!=null) { + if (e != null) { AbortException myException = new AbortException("Failed to install plugin " + source); myException.initCause(e); throw myException; @@ -150,12 +151,12 @@ public class InstallPluginCommand extends CLICommand { Set candidates = new HashSet<>(); for (UpdateSite s : h.getUpdateCenter().getSites()) { Data dt = s.getData(); - if (dt==null) + if (dt == null) stdout.println(Messages.InstallPluginCommand_NoUpdateDataRetrieved(s.getUrl())); else candidates.addAll(dt.plugins.keySet()); } - stdout.println(Messages.InstallPluginCommand_DidYouMean(source,EditDistance.findNearest(source,candidates))); + stdout.println(Messages.InstallPluginCommand_DidYouMean(source, EditDistance.findNearest(source, candidates))); } } diff --git a/core/src/main/java/hudson/cli/ListChangesCommand.java b/core/src/main/java/hudson/cli/ListChangesCommand.java index 618e4d93346ce653a7a6f5c663a31b725b6040b9..36b81e5630afcb07f78db782ba9eb43ded644a54 100644 --- a/core/src/main/java/hudson/cli/ListChangesCommand.java +++ b/core/src/main/java/hudson/cli/ListChangesCommand.java @@ -37,7 +37,7 @@ public class ListChangesCommand extends RunRangeCommand { XML, CSV, PLAIN } - @Option(name="-format",usage="Controls how the output from this command is printed.") + @Option(name = "-format", usage = "Controls how the output from this command is printed.") public Format format = Format.PLAIN; @Override diff --git a/core/src/main/java/hudson/cli/ListJobsCommand.java b/core/src/main/java/hudson/cli/ListJobsCommand.java index 67207ba3ebccd14b6f176f66accc15af53dc6757..1a366227ddbc654f2f35375615305c4a8846935b 100644 --- a/core/src/main/java/hudson/cli/ListJobsCommand.java +++ b/core/src/main/java/hudson/cli/ListJobsCommand.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.cli; import hudson.Extension; @@ -34,7 +35,7 @@ import org.kohsuke.args4j.Argument; /** * Lists all jobs (in a specific view). - * + * * @author Michael Koch */ @Extension @@ -44,7 +45,7 @@ public class ListJobsCommand extends CLICommand { return Messages.ListJobsCommand_ShortDescription(); } - @Argument(metaVar="NAME",usage="Name of the view",required=false) + @Argument(metaVar = "NAME", usage = "Name of the view", required = false) public String name; @Override diff --git a/core/src/main/java/hudson/cli/ListPluginsCommand.java b/core/src/main/java/hudson/cli/ListPluginsCommand.java index 1b3b657d8ac3d51d89076554a0dfb2dac802fa00..9312bedb10ff28d3e551ceae01d7b44e92af1114 100644 --- a/core/src/main/java/hudson/cli/ListPluginsCommand.java +++ b/core/src/main/java/hudson/cli/ListPluginsCommand.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.cli; import hudson.Extension; @@ -50,7 +51,7 @@ public class ListPluginsCommand extends CLICommand { protected int run() { Jenkins h = Jenkins.get(); h.checkPermission(Jenkins.ADMINISTER); - + PluginManager pluginManager = h.getPluginManager(); if (this.name != null) { diff --git a/core/src/main/java/hudson/cli/OnlineNodeCommand.java b/core/src/main/java/hudson/cli/OnlineNodeCommand.java index eaaf2a50e92e39fdde0f980f97c1f3051f23d7f9..e4a37fa74c6eda6871ebb8677293b8f8061c18dc 100644 --- a/core/src/main/java/hudson/cli/OnlineNodeCommand.java +++ b/core/src/main/java/hudson/cli/OnlineNodeCommand.java @@ -68,7 +68,7 @@ public class OnlineNodeCommand extends CLICommand { } } - if (errorOccurred){ + if (errorOccurred) { throw new AbortException(CLI_LISTPARAM_SUMMARY_ERROR_TEXT); } return 0; diff --git a/core/src/main/java/hudson/cli/QuietDownCommand.java b/core/src/main/java/hudson/cli/QuietDownCommand.java index 6df018abddbdd74db12e1c4992b31f54bb4ebbeb..c4cd7e02a97fce6d1b2956fad862223d70f7bf0c 100644 --- a/core/src/main/java/hudson/cli/QuietDownCommand.java +++ b/core/src/main/java/hudson/cli/QuietDownCommand.java @@ -40,13 +40,13 @@ public class QuietDownCommand extends CLICommand { private static final Logger LOGGER = Logger.getLogger(QuietDownCommand.class.getName()); - @Option(name="-block",usage="Block until the system really quiets down and no builds are running") + @Option(name = "-block", usage = "Block until the system really quiets down and no builds are running") public boolean block = false; - @Option(name="-timeout",usage="If non-zero, only block up to the specified number of milliseconds") + @Option(name = "-timeout", usage = "If non-zero, only block up to the specified number of milliseconds") public int timeout = 0; - @Option(name="-reason",usage="Reason for quiet down that will be visible to users") + @Option(name = "-reason", usage = "Reason for quiet down that will be visible to users") public String reason = null; @Override diff --git a/core/src/main/java/hudson/cli/ReloadJobCommand.java b/core/src/main/java/hudson/cli/ReloadJobCommand.java index b2bac818f409ce9dc14f9036247b94db56be5fcd..cea8823144bc94345745315c8bfffa37a3f22d69 100644 --- a/core/src/main/java/hudson/cli/ReloadJobCommand.java +++ b/core/src/main/java/hudson/cli/ReloadJobCommand.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.cli; import hudson.AbortException; @@ -43,7 +44,7 @@ import org.kohsuke.args4j.Argument; @Extension public class ReloadJobCommand extends CLICommand { - @Argument(usage="Name of the job(s) to reload", required=true, multiValued=true) + @Argument(usage = "Name of the job(s) to reload", required = true, multiValued = true) private List jobs; private static final Logger LOGGER = Logger.getLogger(ReloadJobCommand.class.getName()); @@ -62,7 +63,7 @@ public class ReloadJobCommand extends CLICommand { final HashSet hs = new HashSet<>(jobs); - for (String job_s: hs) { + for (String job_s : hs) { AbstractItem job = null; try { @@ -73,7 +74,7 @@ public class ReloadJobCommand extends CLICommand { LOGGER.log(Level.WARNING, "Unsupported item type: {0}", item.getClass().getName()); } - if(job == null) { + if (job == null) { AbstractItem project = Items.findNearest(AbstractItem.class, job_s, jenkins); throw new IllegalArgumentException(project == null ? "No such item \u2018" + job_s + "\u2019 exists." : @@ -84,7 +85,7 @@ public class ReloadJobCommand extends CLICommand { job.checkPermission(Item.CONFIGURE); job.doReload(); } catch (Exception e) { - if(hs.size() == 1) { + if (hs.size() == 1) { throw e; } diff --git a/core/src/main/java/hudson/cli/RemoveJobFromViewCommand.java b/core/src/main/java/hudson/cli/RemoveJobFromViewCommand.java index 1da9f978d11c35fc7d2bee90c74837fa8d7c8f62..416796b82e464c2d16766fbd5afc8a7c6553989d 100644 --- a/core/src/main/java/hudson/cli/RemoveJobFromViewCommand.java +++ b/core/src/main/java/hudson/cli/RemoveJobFromViewCommand.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.cli; import hudson.Extension; @@ -37,10 +38,10 @@ import org.kohsuke.args4j.Argument; @Extension public class RemoveJobFromViewCommand extends CLICommand { - @Argument(usage="Name of the view", required=true, index=0) + @Argument(usage = "Name of the view", required = true, index = 0) private View view; - @Argument(usage="Job names", required=true, index=1) + @Argument(usage = "Job names", required = true, index = 1) private List jobs; @Override @@ -55,7 +56,7 @@ public class RemoveJobFromViewCommand extends CLICommand { if (!(view instanceof DirectlyModifiableView)) throw new IllegalStateException("'" + view.getDisplayName() + "' view can not be modified directly"); - for (TopLevelItem job: jobs) { + for (TopLevelItem job : jobs) { ((DirectlyModifiableView) view).remove(job); } diff --git a/core/src/main/java/hudson/cli/RunRangeCommand.java b/core/src/main/java/hudson/cli/RunRangeCommand.java index a7cee1eb7c1f8ae578623bd807c983c18347ff1e..6d6afe11caa11c512cb169bbe4db3242fde6b527 100644 --- a/core/src/main/java/hudson/cli/RunRangeCommand.java +++ b/core/src/main/java/hudson/cli/RunRangeCommand.java @@ -12,18 +12,18 @@ import org.kohsuke.args4j.Argument; * @since 2.62 */ public abstract class RunRangeCommand extends CLICommand { - @Argument(metaVar="JOB",usage="Name of the job to build",required=true,index=0) - public Job job; + @Argument(metaVar = "JOB", usage = "Name of the job to build", required = true, index = 0) + public Job job; - @Argument(metaVar="RANGE",usage="Range of the build records to delete. 'N-M', 'N,M', or 'N'",required=true,index=1) + @Argument(metaVar = "RANGE", usage = "Range of the build records to delete. 'N-M', 'N,M', or 'N'", required = true, index = 1) public String range; @Override protected int run() throws Exception { - RangeSet rs = RangeSet.fromString(range,false); + RangeSet rs = RangeSet.fromString(range, false); - return act((List)job.getBuilds(rs)); + return act((List) job.getBuilds(rs)); } - protected abstract int act(List> builds) throws IOException; + protected abstract int act(List> builds) throws IOException; } diff --git a/core/src/main/java/hudson/cli/SetBuildDescriptionCommand.java b/core/src/main/java/hudson/cli/SetBuildDescriptionCommand.java index 6560479f22f42fb1ae39da51a66e04420a30e96e..458e22419369fa9dcde66171ddb04763496cb0fe 100644 --- a/core/src/main/java/hudson/cli/SetBuildDescriptionCommand.java +++ b/core/src/main/java/hudson/cli/SetBuildDescriptionCommand.java @@ -18,30 +18,30 @@ public class SetBuildDescriptionCommand extends CLICommand implements Serializab return Messages.SetBuildDescriptionCommand_ShortDescription(); } - @Argument(metaVar="JOB",usage="Name of the job to build",required=true,index=0) - public transient Job job; + @Argument(metaVar = "JOB", usage = "Name of the job to build", required = true, index = 0) + public transient Job job; - @Argument(metaVar="BUILD#",usage="Number of the build",required=true,index=1) + @Argument(metaVar = "BUILD#", usage = "Number of the build", required = true, index = 1) public int number; - - @Argument(metaVar="DESCRIPTION",required=true,usage="Description to be set. '=' to read from stdin.", index=2) + + @Argument(metaVar = "DESCRIPTION", required = true, usage = "Description to be set. '=' to read from stdin.", index = 2) public String description; @Override protected int run() throws Exception { - Run run = job.getBuildByNumber(number); + Run run = job.getBuildByNumber(number); if (run == null) - throw new IllegalArgumentException("No such build #"+number); + throw new IllegalArgumentException("No such build #" + number); run.checkPermission(Run.UPDATE); if ("=".equals(description)) { - description = IOUtils.toString(stdin); + description = IOUtils.toString(stdin); } - + run.setDescription(description); - + return 0; } - + } diff --git a/core/src/main/java/hudson/cli/SetBuildDisplayNameCommand.java b/core/src/main/java/hudson/cli/SetBuildDisplayNameCommand.java index e07a115f4f63a9e376cae12e1b01b66f9f7d5dc4..08befa394684c37e59f467f5767b9eedd474dbcf 100644 --- a/core/src/main/java/hudson/cli/SetBuildDisplayNameCommand.java +++ b/core/src/main/java/hudson/cli/SetBuildDisplayNameCommand.java @@ -16,13 +16,13 @@ public class SetBuildDisplayNameCommand extends CLICommand implements Serializab return Messages.SetBuildDisplayNameCommand_ShortDescription(); } - @Argument(metaVar="JOB", usage="Name of the job to build", required=true, index=0) + @Argument(metaVar = "JOB", usage = "Name of the job to build", required = true, index = 0) public transient Job job; - @Argument(metaVar="BUILD#", usage="Number of the build", required=true, index=1) + @Argument(metaVar = "BUILD#", usage = "Number of the build", required = true, index = 1) public int number; - @Argument(metaVar="DISPLAYNAME", required=true, usage="DisplayName to be set. '-' to read from stdin.", index=2) + @Argument(metaVar = "DISPLAYNAME", required = true, usage = "DisplayName to be set. '-' to read from stdin.", index = 2) public String displayName; @Override diff --git a/core/src/main/java/hudson/cli/UpdateJobCommand.java b/core/src/main/java/hudson/cli/UpdateJobCommand.java index 77649867ec812e2ea7fbfafcc8895a9fc4938c36..396d2d229cc2b44e91a9b1e4d8d4263bb8ef9ece 100644 --- a/core/src/main/java/hudson/cli/UpdateJobCommand.java +++ b/core/src/main/java/hudson/cli/UpdateJobCommand.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.cli; import hudson.Extension; @@ -34,7 +35,7 @@ import org.kohsuke.args4j.Argument; */ @Extension public class UpdateJobCommand extends CLICommand { - @Argument(metaVar="JOB",usage="Name of the job",required=true) + @Argument(metaVar = "JOB", usage = "Name of the job", required = true) public AbstractItem job; @Override @@ -44,7 +45,7 @@ public class UpdateJobCommand extends CLICommand { @Override protected int run() throws Exception { - job.updateByXml((Source)new StreamSource(stdin)); + job.updateByXml((Source) new StreamSource(stdin)); return 0; } } diff --git a/core/src/main/java/hudson/cli/UpdateNodeCommand.java b/core/src/main/java/hudson/cli/UpdateNodeCommand.java index 1d311908cb5f1e7b263fafda1146ce333a2b2a65..c9210f89cc689b5809305be138d4c73743096336 100644 --- a/core/src/main/java/hudson/cli/UpdateNodeCommand.java +++ b/core/src/main/java/hudson/cli/UpdateNodeCommand.java @@ -37,7 +37,7 @@ import org.kohsuke.args4j.Argument; @Extension public class UpdateNodeCommand extends CLICommand { - @Argument(metaVar="NODE", usage="Name of the node", required=true) + @Argument(metaVar = "NODE", usage = "Name of the node", required = true) public Node node; @Override diff --git a/core/src/main/java/hudson/cli/UpdateViewCommand.java b/core/src/main/java/hudson/cli/UpdateViewCommand.java index d952ae5d034412421a9689d190b7845fa609b1a9..36561f34f3f0c544cbb68542813126b226a4e95f 100644 --- a/core/src/main/java/hudson/cli/UpdateViewCommand.java +++ b/core/src/main/java/hudson/cli/UpdateViewCommand.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.cli; import hudson.Extension; @@ -35,7 +36,7 @@ import org.kohsuke.args4j.Argument; @Extension public class UpdateViewCommand extends CLICommand { - @Argument(usage="Name of the view to update", required=true) + @Argument(usage = "Name of the view to update", required = true) private View view; @Override diff --git a/core/src/main/java/hudson/cli/VersionCommand.java b/core/src/main/java/hudson/cli/VersionCommand.java index 17b9cc1d4ad8aaae77149a9ba25d2f9f2ed8f64b..8b77c417d187c510883bc7143c397d1858dbda02 100644 --- a/core/src/main/java/hudson/cli/VersionCommand.java +++ b/core/src/main/java/hudson/cli/VersionCommand.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.cli; import hudson.Extension; diff --git a/core/src/main/java/hudson/cli/WaitNodeOfflineCommand.java b/core/src/main/java/hudson/cli/WaitNodeOfflineCommand.java index 319e4424a9e44b8b95d1b00b19403f0a805dc994..fee99ef6bf1a0a351fcf9d51ebf8479f0e3df6a9 100644 --- a/core/src/main/java/hudson/cli/WaitNodeOfflineCommand.java +++ b/core/src/main/java/hudson/cli/WaitNodeOfflineCommand.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.cli; import hudson.Extension; @@ -35,7 +36,7 @@ import org.kohsuke.args4j.Argument; @Extension public class WaitNodeOfflineCommand extends CLICommand { - @Argument(metaVar="NODE", usage="Name of the node", required=true) + @Argument(metaVar = "NODE", usage = "Name of the node", required = true) public Node node; @Override diff --git a/core/src/main/java/hudson/cli/WaitNodeOnlineCommand.java b/core/src/main/java/hudson/cli/WaitNodeOnlineCommand.java index 2e9713ad6f4cd4e6034ca11f8e1ae9748d1315cf..95a621b087b03d61745c267befbfbb748d8cdbb5 100644 --- a/core/src/main/java/hudson/cli/WaitNodeOnlineCommand.java +++ b/core/src/main/java/hudson/cli/WaitNodeOnlineCommand.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.cli; import hudson.Extension; @@ -35,7 +36,7 @@ import org.kohsuke.args4j.Argument; @Extension public class WaitNodeOnlineCommand extends CLICommand { - @Argument(metaVar="NODE", usage="Name of the node", required=true) + @Argument(metaVar = "NODE", usage = "Name of the node", required = true) public Node node; @Override diff --git a/core/src/main/java/hudson/cli/WhoAmICommand.java b/core/src/main/java/hudson/cli/WhoAmICommand.java index 19db3787c303494e12ac9e48b69922779292da0a..a4ecc4af79d0665cba81d69ec76cd69067a171a2 100644 --- a/core/src/main/java/hudson/cli/WhoAmICommand.java +++ b/core/src/main/java/hudson/cli/WhoAmICommand.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.cli; import hudson.Extension; @@ -43,10 +44,10 @@ public class WhoAmICommand extends CLICommand { @Override protected int run() { Authentication a = Jenkins.getAuthentication2(); - stdout.println("Authenticated as: "+a.getName()); + stdout.println("Authenticated as: " + a.getName()); stdout.println("Authorities:"); for (GrantedAuthority ga : a.getAuthorities()) { - stdout.println(" "+ga.getAuthority()); + stdout.println(" " + ga.getAuthority()); } return 0; } diff --git a/core/src/main/java/hudson/cli/declarative/CLIMethod.java b/core/src/main/java/hudson/cli/declarative/CLIMethod.java index 13ddffbf5d2fb7c0b5503efe4900a56f8276b3a4..7b9c35202bb906fa491d903c4e0d061b017a2d68 100644 --- a/core/src/main/java/hudson/cli/declarative/CLIMethod.java +++ b/core/src/main/java/hudson/cli/declarative/CLIMethod.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.cli.declarative; import static java.lang.annotation.ElementType.METHOD; diff --git a/core/src/main/java/hudson/cli/declarative/CLIRegisterer.java b/core/src/main/java/hudson/cli/declarative/CLIRegisterer.java index 13b2841db09488cc07dbdf6f247cb2b17dc07783..8b2f2348c577a14166dd9f231c1fef0fc48ef168 100644 --- a/core/src/main/java/hudson/cli/declarative/CLIRegisterer.java +++ b/core/src/main/java/hudson/cli/declarative/CLIRegisterer.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.cli.declarative; import static java.util.logging.Level.SEVERE; @@ -79,8 +80,8 @@ public class CLIRegisterer extends ExtensionFinder { @Override public Collection> find(Class type, Hudson jenkins) { - if (type==CLICommand.class) - return (List)discover(jenkins); + if (type == CLICommand.class) + return (List) discover(jenkins); else return Collections.emptyList(); } @@ -90,9 +91,9 @@ public class CLIRegisterer extends ExtensionFinder { */ private Method findResolver(Class type) throws IOException { List resolvers = Util.filter(Index.list(CLIResolver.class, Jenkins.get().getPluginManager().uberClassLoader), Method.class); - for ( ; type!=null; type=type.getSuperclass()) + for ( ; type != null; type = type.getSuperclass()) for (Method m : resolvers) - if (m.getReturnType()==type) + if (m.getReturnType() == type) return m; return null; } @@ -102,13 +103,13 @@ public class CLIRegisterer extends ExtensionFinder { List> r = new ArrayList<>(); try { - for ( final Method m : Util.filter(Index.list(CLIMethod.class, jenkins.getPluginManager().uberClassLoader),Method.class)) { + for (final Method m : Util.filter(Index.list(CLIMethod.class, jenkins.getPluginManager().uberClassLoader), Method.class)) { try { // command name final String name = m.getAnnotation(CLIMethod.class).name(); final ResourceBundleHolder res = loadMessageBundle(m); - res.format("CLI."+name+".shortDescription"); // make sure we have the resource, to fail early + res.format("CLI." + name + ".shortDescription"); // make sure we have the resource, to fail early r.add(new ExtensionComponent<>(new CloneableCLICommand() { @Override @@ -277,11 +278,11 @@ public class CLIRegisterer extends ExtensionFinder { } })); } catch (ClassNotFoundException | MissingResourceException e) { - LOGGER.log(SEVERE,"Failed to process @CLIMethod: "+m,e); + LOGGER.log(SEVERE, "Failed to process @CLIMethod: " + m, e); } } } catch (IOException e) { - LOGGER.log(SEVERE, "Failed to discover @CLIMethod",e); + LOGGER.log(SEVERE, "Failed to discover @CLIMethod", e); } return r; diff --git a/core/src/main/java/hudson/cli/declarative/CLIResolver.java b/core/src/main/java/hudson/cli/declarative/CLIResolver.java index 71c3cf4e23888d3f065fd15736e94d7594792c03..80f1d19edff4ef08bafebbaaa70fbd8865dd39df 100644 --- a/core/src/main/java/hudson/cli/declarative/CLIResolver.java +++ b/core/src/main/java/hudson/cli/declarative/CLIResolver.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.cli.declarative; import static java.lang.annotation.ElementType.METHOD; diff --git a/core/src/main/java/hudson/cli/declarative/MethodBinder.java b/core/src/main/java/hudson/cli/declarative/MethodBinder.java index 08438aac9d870e9f4c0160cda56c33f906d23468..91dfd11da7f09534426f30b4d4731b36a6d234d0 100644 --- a/core/src/main/java/hudson/cli/declarative/MethodBinder.java +++ b/core/src/main/java/hudson/cli/declarative/MethodBinder.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.cli.declarative; import hudson.cli.CLICommand; @@ -93,15 +94,15 @@ class MethodBinder { } }; Option option = p.annotation(Option.class); - if (option!=null) { - parser.addOption(setter,option); + if (option != null) { + parser.addOption(setter, option); } Argument arg = p.annotation(Argument.class); - if (arg!=null) { - if (bias>0) arg = new ArgumentImpl(arg,bias); - parser.addArgument(setter,arg); + if (arg != null) { + if (bias > 0) arg = new ArgumentImpl(arg, bias); + parser.addArgument(setter, arg); } - if (p.type()==CLICommand.class) + if (p.type() == CLICommand.class) arguments[index] = command; if (p.type().isPrimitive()) @@ -111,7 +112,7 @@ class MethodBinder { public Object call(Object instance) throws Exception { try { - return method.invoke(instance,arguments); + return method.invoke(instance, arguments); } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t instanceof Exception) @@ -155,7 +156,7 @@ class MethodBinder { @Override public int index() { - return base.index()+bias; + return base.index() + bias; } @Override diff --git a/core/src/main/java/hudson/cli/handlers/AbstractProjectOptionHandler.java b/core/src/main/java/hudson/cli/handlers/AbstractProjectOptionHandler.java index 405ce2fcc32d93f41414f9fdda7fb9b0effa8404..ab7402de65aec14e2ff9c32530398e18f1cf05c4 100644 --- a/core/src/main/java/hudson/cli/handlers/AbstractProjectOptionHandler.java +++ b/core/src/main/java/hudson/cli/handlers/AbstractProjectOptionHandler.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.cli.handlers; import hudson.model.AbstractProject; diff --git a/core/src/main/java/hudson/cli/handlers/JobOptionHandler.java b/core/src/main/java/hudson/cli/handlers/JobOptionHandler.java index bcbbb404a891ec8b1284d3f8e6b12fedfffb27be..51929315034132c9d50fe561b76cada51707b716 100644 --- a/core/src/main/java/hudson/cli/handlers/JobOptionHandler.java +++ b/core/src/main/java/hudson/cli/handlers/JobOptionHandler.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.cli.handlers; import hudson.model.Job; diff --git a/core/src/main/java/hudson/cli/handlers/NodeOptionHandler.java b/core/src/main/java/hudson/cli/handlers/NodeOptionHandler.java index 3b2a985f4d3e56576b26c345b7ad244b1c4ebb0d..45bd0f4e679b17c3e6110c03fdf1ef0435bdffa0 100644 --- a/core/src/main/java/hudson/cli/handlers/NodeOptionHandler.java +++ b/core/src/main/java/hudson/cli/handlers/NodeOptionHandler.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.cli.handlers; import hudson.model.Node; diff --git a/core/src/main/java/hudson/cli/handlers/ParameterizedJobOptionHandler.java b/core/src/main/java/hudson/cli/handlers/ParameterizedJobOptionHandler.java index 5776c221433e42957e3355f57c43b35c1cc2cf26..a37dbf1790f1174dd24c9ab5d6e4fdf4e77abaa7 100644 --- a/core/src/main/java/hudson/cli/handlers/ParameterizedJobOptionHandler.java +++ b/core/src/main/java/hudson/cli/handlers/ParameterizedJobOptionHandler.java @@ -40,7 +40,7 @@ import org.kohsuke.args4j.spi.Setter; @MetaInfServices(OptionHandler.class) @SuppressWarnings("rawtypes") public class ParameterizedJobOptionHandler extends GenericItemOptionHandler { - + public ParameterizedJobOptionHandler(CmdLineParser parser, OptionDef option, Setter setter) { super(parser, option, setter); } diff --git a/core/src/main/java/hudson/cli/handlers/ViewOptionHandler.java b/core/src/main/java/hudson/cli/handlers/ViewOptionHandler.java index 7a68946c16515492a67a62bc465dfe72cee05eb1..65656c15e33c8e4f3b31881affcd48f049a1d9a7 100644 --- a/core/src/main/java/hudson/cli/handlers/ViewOptionHandler.java +++ b/core/src/main/java/hudson/cli/handlers/ViewOptionHandler.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.cli.handlers; import edu.umd.cs.findbugs.annotations.CheckForNull; @@ -94,7 +95,7 @@ public class ViewOptionHandler extends OptionHandler { View view = null; final StringTokenizer tok = new StringTokenizer(name, "/"); - while(tok.hasMoreTokens()) { + while (tok.hasMoreTokens()) { String viewName = tok.nextToken(); diff --git a/core/src/main/java/hudson/console/AnnotatedLargeText.java b/core/src/main/java/hudson/console/AnnotatedLargeText.java index d3f8aa3301bd331c4a91b8d8119e8e370898c3ea..e074044e806da4ad5aeb919c372f7a114a17f918 100644 --- a/core/src/main/java/hudson/console/AnnotatedLargeText.java +++ b/core/src/main/java/hudson/console/AnnotatedLargeText.java @@ -23,6 +23,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.console; import static java.lang.Math.abs; @@ -90,15 +91,15 @@ public class AnnotatedLargeText extends LargeText { } public void doProgressiveHtml(StaplerRequest req, StaplerResponse rsp) throws IOException { - req.setAttribute("html",true); - doProgressText(req,rsp); + req.setAttribute("html", true); + doProgressText(req, rsp); } /** * Aliasing what I think was a wrong name in {@link LargeText} */ public void doProgressiveText(StaplerRequest req, StaplerResponse rsp) throws IOException { - doProgressText(req,rsp); + doProgressText(req, rsp); } /** @@ -107,7 +108,7 @@ public class AnnotatedLargeText extends LargeText { */ private boolean isHtml() { StaplerRequest req = Stapler.getCurrentRequest(); - return req!=null && req.getAttribute("html")!=null; + return req != null && req.getAttribute("html") != null; } @Override @@ -117,15 +118,15 @@ public class AnnotatedLargeText extends LargeText { private ConsoleAnnotator createAnnotator(StaplerRequest req) throws IOException { try { - String base64 = req!=null ? req.getHeader("X-ConsoleAnnotator") : null; - if (base64!=null) { + String base64 = req != null ? req.getHeader("X-ConsoleAnnotator") : null; + if (base64 != null) { Cipher sym = PASSING_ANNOTATOR.decrypt(); try (ObjectInputStream ois = new ObjectInputStreamEx(new GZIPInputStream( new CipherInputStream(new ByteArrayInputStream(Base64.getDecoder().decode(base64.getBytes(StandardCharsets.UTF_8))), sym)), Jenkins.get().pluginManager.uberClassLoader)) { long timestamp = ois.readLong(); - if (TimeUnit.HOURS.toMillis(1) > abs(System.currentTimeMillis()-timestamp)) + if (TimeUnit.HOURS.toMillis(1) > abs(System.currentTimeMillis() - timestamp)) // don't deserialize something too old to prevent a replay attack return getConsoleAnnotator(ois); } catch (RuntimeException ex) { @@ -150,7 +151,7 @@ public class AnnotatedLargeText extends LargeText { if (isHtml()) return writeHtmlTo(start, w); else - return super.writeLogTo(start,w); + return super.writeLogTo(start, w); } /** @@ -176,16 +177,16 @@ public class AnnotatedLargeText extends LargeText { public long writeHtmlTo(long start, Writer w) throws IOException { ConsoleAnnotationOutputStream caw = new ConsoleAnnotationOutputStream<>( w, createAnnotator(Stapler.getCurrentRequest()), context, charset); - long r = super.writeLogTo(start,caw); + long r = super.writeLogTo(start, caw); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Cipher sym = PASSING_ANNOTATOR.encrypt(); - ObjectOutputStream oos = AnonymousClassWarnings.checkingObjectOutputStream(new GZIPOutputStream(new CipherOutputStream(baos,sym))); + ObjectOutputStream oos = AnonymousClassWarnings.checkingObjectOutputStream(new GZIPOutputStream(new CipherOutputStream(baos, sym))); oos.writeLong(System.currentTimeMillis()); // send timestamp to prevent a replay attack oos.writeObject(caw.getConsoleAnnotator()); oos.close(); StaplerResponse rsp = Stapler.getCurrentResponse(); - if (rsp!=null) + if (rsp != null) rsp.setHeader("X-ConsoleAnnotator", Base64.getEncoder().encodeToString(baos.toByteArray())); return r; } @@ -193,5 +194,5 @@ public class AnnotatedLargeText extends LargeText { /** * Used for sending the state of ConsoleAnnotator to the client, because we are deserializing this object later. */ - private static final CryptoConfidentialKey PASSING_ANNOTATOR = new CryptoConfidentialKey(AnnotatedLargeText.class,"consoleAnnotator"); + private static final CryptoConfidentialKey PASSING_ANNOTATOR = new CryptoConfidentialKey(AnnotatedLargeText.class, "consoleAnnotator"); } diff --git a/core/src/main/java/hudson/console/ConsoleAnnotationDescriptor.java b/core/src/main/java/hudson/console/ConsoleAnnotationDescriptor.java index 3f9a17d1431785ffac2e8299894f23ca117f48aa..e13d65ea46273e98f95221fbce981f9d4a56de71 100644 --- a/core/src/main/java/hudson/console/ConsoleAnnotationDescriptor.java +++ b/core/src/main/java/hudson/console/ConsoleAnnotationDescriptor.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.console; import hudson.DescriptorExtensionList; @@ -63,26 +64,26 @@ public abstract class ConsoleAnnotationDescriptor extends Descriptor,ConsoleAnnotationDescriptor> all() { + public static DescriptorExtensionList, ConsoleAnnotationDescriptor> all() { return (DescriptorExtensionList) Jenkins.get().getDescriptorList(ConsoleNote.class); } } diff --git a/core/src/main/java/hudson/console/ConsoleAnnotationOutputStream.java b/core/src/main/java/hudson/console/ConsoleAnnotationOutputStream.java index 6e70a743d82414b9abce1cc1682aa45228b4d564..d2ac95da65bd7ec0af627b606dfa59dfe8fac095 100644 --- a/core/src/main/java/hudson/console/ConsoleAnnotationOutputStream.java +++ b/core/src/main/java/hudson/console/ConsoleAnnotationOutputStream.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.console; import hudson.MarkupText; @@ -69,7 +70,7 @@ public class ConsoleAnnotationOutputStream extends LineTransformationOutputSt this.out = out; this.ann = ConsoleAnnotator.cast(ann); this.context = context; - this.lineOut = new WriterOutputStream(line,charset); + this.lineOut = new WriterOutputStream(line, charset); } public ConsoleAnnotator getConsoleAnnotator() { @@ -86,19 +87,19 @@ public class ConsoleAnnotationOutputStream extends LineTransformationOutputSt line.reset(); final StringBuffer strBuf = line.getStringBuffer(); - int next = ConsoleNote.findPreamble(in,0,sz); + int next = ConsoleNote.findPreamble(in, 0, sz); - List> annotators=null; + List> annotators = null; - {// perform byte[]->char[] while figuring out the char positions of the BLOBs + { // perform byte[]->char[] while figuring out the char positions of the BLOBs int written = 0; - while (next>=0) { - if (next>written) { - lineOut.write(in,written,next-written); + while (next >= 0) { + if (next > written) { + lineOut.write(in, written, next - written); lineOut.flush(); written = next; } else { - assert next==written; + assert next == written; } // character position of this annotation in this line @@ -109,13 +110,13 @@ public class ConsoleAnnotationOutputStream extends LineTransformationOutputSt try { final ConsoleNote a = ConsoleNote.readFrom(new DataInputStream(b)); - if (a!=null) { - if (annotators==null) + if (a != null) { + if (annotators == null) annotators = new ArrayList<>(); annotators.add(new ConsoleAnnotator() { @Override public ConsoleAnnotator annotate(T context, MarkupText text) { - return a.annotate(context,text,charPos); + return a.annotate(context, text, charPos); } }); } @@ -128,22 +129,22 @@ public class ConsoleAnnotationOutputStream extends LineTransformationOutputSt written += bytesUsed; - next = ConsoleNote.findPreamble(in,written,sz-written); + next = ConsoleNote.findPreamble(in, written, sz - written); } // finish the remaining bytes->chars conversion - lineOut.write(in,written,sz-written); + lineOut.write(in, written, sz - written); - if (annotators!=null) { + if (annotators != null) { // aggregate newly retrieved ConsoleAnnotators into the current one. - if (ann!=null) annotators.add(ann); + if (ann != null) annotators.add(ann); ann = ConsoleAnnotator.combine(annotators); } } lineOut.flush(); MarkupText mt = new MarkupText(strBuf.toString()); - if (ann!=null) - ann = ann.annotate(context,mt); + if (ann != null) + ann = ann.annotate(context, mt); out.write(mt.toString(true)); // this perform escapes } @@ -172,14 +173,14 @@ public class ConsoleAnnotationOutputStream extends LineTransformationOutputSt private void reset() { StringBuffer buf = getStringBuffer(); - if (buf.length()>4096) + if (buf.length() > 4096) out = new StringWriter(256); else buf.setLength(0); } private StringBuffer getStringBuffer() { - StringWriter w = (StringWriter)out; + StringWriter w = (StringWriter) out; return w.getBuffer(); } } diff --git a/core/src/main/java/hudson/console/ConsoleAnnotator.java b/core/src/main/java/hudson/console/ConsoleAnnotator.java index 9761439320feef5c7e37286a13c18afb23f6dcb5..8f289fd70cb91710d240d1756c6c2de5aeabc6b7 100644 --- a/core/src/main/java/hudson/console/ConsoleAnnotator.java +++ b/core/src/main/java/hudson/console/ConsoleAnnotator.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.console; import edu.umd.cs.findbugs.annotations.CheckForNull; @@ -81,14 +82,14 @@ public abstract class ConsoleAnnotator implements Serializable { * To indicate that you are not interested in the following lines, return {@code null}. */ @CheckForNull - public abstract ConsoleAnnotator annotate(@NonNull T context, @NonNull MarkupText text ); + public abstract ConsoleAnnotator annotate(@NonNull T context, @NonNull MarkupText text); /** * Cast operation that restricts T. */ @SuppressWarnings("unchecked") public static ConsoleAnnotator cast(ConsoleAnnotator a) { - return (ConsoleAnnotator)a; + return (ConsoleAnnotator) a; } @SuppressWarnings({"unchecked", "rawtypes"}) // unclear to jglick what is going on here @@ -104,9 +105,9 @@ public abstract class ConsoleAnnotator implements Serializable { ListIterator> itr = list.listIterator(); while (itr.hasNext()) { ConsoleAnnotator a = itr.next(); - ConsoleAnnotator b = a.annotate(context,text); - if (a!=b) { - if (b==null) itr.remove(); + ConsoleAnnotator b = a.annotate(context, text); + if (a != b) { + if (b == null) itr.remove(); else itr.set(b); } } @@ -147,7 +148,7 @@ public abstract class ConsoleAnnotator implements Serializable { for (ConsoleAnnotatorFactory f : ConsoleAnnotatorFactory.all()) { if (f.type().isInstance(context)) { ConsoleAnnotator ca = f.newInstance(context); - if (ca!=null) + if (ca != null) r.add(ca); } } diff --git a/core/src/main/java/hudson/console/ConsoleAnnotatorFactory.java b/core/src/main/java/hudson/console/ConsoleAnnotatorFactory.java index 538b97359105f02ed5a9d8b0577a3dbb2d4a5308..b2f6948fd155f9f7f8edab2798d563f9be193196 100644 --- a/core/src/main/java/hudson/console/ConsoleAnnotatorFactory.java +++ b/core/src/main/java/hudson/console/ConsoleAnnotatorFactory.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.console; import hudson.Extension; @@ -61,7 +62,7 @@ import org.kohsuke.stapler.WebMethod; * in the same resource directory that you normally put Jelly scripts), which will be loaded into * the HTML page whenever the console notes are used. This allows you to use minimal markup in * code generation, and do the styling in CSS and perform the rest of the interesting work as a CSS behaviour/JavaScript. - * + * * @author Kohsuke Kawaguchi * @since 1.349 */ @@ -87,7 +88,7 @@ public abstract class ConsoleAnnotatorFactory implements ExtensionPoint { public Class type() { Type type = Types.getBaseClass(getClass(), ConsoleAnnotatorFactory.class); if (type instanceof ParameterizedType) - return Types.erasure(Types.getTypeArgument(type,0)); + return Types.erasure(Types.getTypeArgument(type, 0)); else return Object.class; } @@ -96,27 +97,27 @@ public abstract class ConsoleAnnotatorFactory implements ExtensionPoint { * Returns true if this descriptor has a JavaScript to be inserted on applicable console page. */ public boolean hasScript() { - return getResource("/script.js") !=null; + return getResource("/script.js") != null; } public boolean hasStylesheet() { - return getResource("/style.css") !=null; + return getResource("/style.css") != null; } private URL getResource(String fileName) { Class c = getClass(); - return c.getClassLoader().getResource(c.getName().replace('.','/').replace('$','/')+ fileName); + return c.getClassLoader().getResource(c.getName().replace('.', '/').replace('$', '/') + fileName); } /** * Serves the JavaScript file associated with this console annotator factory. */ - @WebMethod(name="script.js") + @WebMethod(name = "script.js") public void doScriptJs(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { rsp.serveFile(req, getResource("/script.js"), TimeUnit.DAYS.toMillis(1)); } - @WebMethod(name="style.css") + @WebMethod(name = "style.css") public void doStyleCss(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { rsp.serveFile(req, getResource("/style.css"), TimeUnit.DAYS.toMillis(1)); } diff --git a/core/src/main/java/hudson/console/ConsoleLogFilter.java b/core/src/main/java/hudson/console/ConsoleLogFilter.java index 3f54674477db4c216bbf47635907eefa536e4e72..3523fce8e9d25de1516597489ffe2a7d480eab12 100644 --- a/core/src/main/java/hudson/console/ConsoleLogFilter.java +++ b/core/src/main/java/hudson/console/ConsoleLogFilter.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright 2010 Yahoo! 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 diff --git a/core/src/main/java/hudson/console/ConsoleNote.java b/core/src/main/java/hudson/console/ConsoleNote.java index 62a9349c02c0c51bd14dffebdcc6cb0050ab3ad0..8183934aedcec7ba3fdca0f1a5041b4b27e552bc 100644 --- a/core/src/main/java/hudson/console/ConsoleNote.java +++ b/core/src/main/java/hudson/console/ConsoleNote.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.console; import com.jcraft.jzlib.GZIPInputStream; @@ -161,7 +162,7 @@ public abstract class ConsoleNote implements Serializable, Describable implements Serializable, Describable implements Serializable, Describable implements Serializable, Describable implements Serializable, Describable implements Serializable, Describable

"+html+"
"); + "
" + html + "
"); return null; } @@ -59,7 +60,7 @@ public class ExpandableDetailsNote extends ConsoleNote { return new ExpandableDetailsNote(buttonCaption, html).encode(); } catch (IOException e) { // impossible, but don't make this a fatal problem - LOGGER.log(Level.WARNING, "Failed to serialize "+HyperlinkNote.class,e); + LOGGER.log(Level.WARNING, "Failed to serialize " + HyperlinkNote.class, e); return ""; } } diff --git a/core/src/main/java/hudson/console/HyperlinkNote.java b/core/src/main/java/hudson/console/HyperlinkNote.java index 38464ceecc9d1bdd0d8017ea829be87b6adbf40d..f8e7e65208383d7c2359d4f6f45fda850fae0935 100644 --- a/core/src/main/java/hudson/console/HyperlinkNote.java +++ b/core/src/main/java/hudson/console/HyperlinkNote.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.console; import hudson.Extension; @@ -61,15 +62,15 @@ public class HyperlinkNote extends ConsoleNote { String url = this.url; if (url.startsWith("/")) { StaplerRequest req = Stapler.getCurrentRequest(); - if (req!=null) { + if (req != null) { // if we are serving HTTP request, we want to use app relative URL - url = req.getContextPath()+url; + url = req.getContextPath() + url; } else { // otherwise presumably this is rendered for e-mails and other non-HTTP stuff - url = Jenkins.get().getRootUrl()+url.substring(1); + url = Jenkins.get().getRootUrl() + url.substring(1); } } - text.addMarkup(charPos, charPos + length, "", ""); + text.addMarkup(charPos, charPos + length, "", ""); return null; } @@ -91,10 +92,10 @@ public class HyperlinkNote extends ConsoleNote { // break the conversion. text = text.replace('\n', ' '); try { - return constructor.apply(url,text.length()).encode()+text; + return constructor.apply(url, text.length()).encode() + text; } catch (IOException e) { // impossible, but don't make this a fatal problem - LOGGER.log(Level.WARNING, "Failed to serialize "+HyperlinkNote.class,e); + LOGGER.log(Level.WARNING, "Failed to serialize " + HyperlinkNote.class, e); return text; } } diff --git a/core/src/main/java/hudson/console/LineTransformationOutputStream.java b/core/src/main/java/hudson/console/LineTransformationOutputStream.java index dce4ddaf76793706bf362313526a06ae0dbfc857..e5d84ee770cefa5f57f70491c6979873403f5eda 100644 --- a/core/src/main/java/hudson/console/LineTransformationOutputStream.java +++ b/core/src/main/java/hudson/console/LineTransformationOutputStream.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.console; import hudson.util.ByteArrayOutputStream2; @@ -46,21 +47,21 @@ public abstract class LineTransformationOutputStream extends OutputStream { * Contents of the whole line, including the EOL code like CR/LF. * @param len * Specifies the length of the valid contents in 'b'. The rest is garbage. - * This is so that the caller doesn't have to allocate an array of the exact size. + * This is so that the caller doesn't have to allocate an array of the exact size. */ protected abstract void eol(byte[] b, int len) throws IOException; @Override public void write(int b) throws IOException { buf.write(b); - if (b==LF) eol(); + if (b == LF) eol(); } private void eol() throws IOException { - eol(buf.getBuffer(),buf.size()); + eol(buf.getBuffer(), buf.size()); // reuse the buffer under normal circumstances, but don't let the line buffer grow unbounded - if (buf.size()>4096) + if (buf.size() > 4096) buf = new ByteArrayOutputStream2(); else buf.reset(); @@ -68,9 +69,9 @@ public abstract class LineTransformationOutputStream extends OutputStream { @Override public void write(byte[] b, int off, int len) throws IOException { - int end = off+len; + int end = off + len; - for( int i=off; i0) { + if (buf.size() > 0) { /* because LargeText cuts output at the line end boundary, this is possible only for the very end of the console output, if the output ends without NL. @@ -97,15 +98,15 @@ public abstract class LineTransformationOutputStream extends OutputStream { protected String trimEOL(String line) { int slen = line.length(); - while (slen>0) { - char ch = line.charAt(slen-1); - if (ch=='\r' || ch=='\n') { + while (slen > 0) { + char ch = line.charAt(slen - 1); + if (ch == '\r' || ch == '\n') { slen--; continue; } break; } - line = line.substring(0,slen); + line = line.substring(0, slen); return line; } diff --git a/core/src/main/java/hudson/console/ModelHyperlinkNote.java b/core/src/main/java/hudson/console/ModelHyperlinkNote.java index 86d8b044833f46d10738c2d8c77d096142adfb1c..51f41350163442b6bd75fef2cb4c4416f32f6984 100644 --- a/core/src/main/java/hudson/console/ModelHyperlinkNote.java +++ b/core/src/main/java/hudson/console/ModelHyperlinkNote.java @@ -31,23 +31,23 @@ public class ModelHyperlinkNote extends HyperlinkNote { } public static String encodeTo(@NonNull User u) { - return encodeTo(u,u.getDisplayName()); + return encodeTo(u, u.getDisplayName()); } public static String encodeTo(User u, String text) { - return encodeTo('/'+u.getUrl(),text); + return encodeTo('/' + u.getUrl(), text); } public static String encodeTo(Item item) { - return encodeTo(item,item.getFullDisplayName()); + return encodeTo(item, item.getFullDisplayName()); } public static String encodeTo(Item item, String text) { - return encodeTo('/'+item.getUrl(),text); + return encodeTo('/' + item.getUrl(), text); } public static String encodeTo(Run r) { - return encodeTo('/'+r.getUrl(),r.getDisplayName()); + return encodeTo('/' + r.getUrl(), r.getDisplayName()); } public static String encodeTo(Node node) { @@ -77,7 +77,7 @@ public class ModelHyperlinkNote extends HyperlinkNote { return "Hyperlinks to models"; } } - + private static final long serialVersionUID = 1L; private static final Logger LOGGER = Logger.getLogger(ModelHyperlinkNote.class.getName()); diff --git a/core/src/main/java/hudson/console/PlainTextConsoleOutputStream.java b/core/src/main/java/hudson/console/PlainTextConsoleOutputStream.java index 9b94490f3a312fa8a5d63cb9503f060b8a06d009..f3b5bd8adf7e6b8139804bdea9c12b30bb1996e4 100644 --- a/core/src/main/java/hudson/console/PlainTextConsoleOutputStream.java +++ b/core/src/main/java/hudson/console/PlainTextConsoleOutputStream.java @@ -49,16 +49,16 @@ public class PlainTextConsoleOutputStream extends LineTransformationOutputStream @Override protected void eol(byte[] in, int sz) throws IOException { - int next = ConsoleNote.findPreamble(in,0,sz); + int next = ConsoleNote.findPreamble(in, 0, sz); // perform byte[]->char[] while figuring out the char positions of the BLOBs int written = 0; - while (next>=0) { - if (next>written) { - out.write(in,written,next-written); + while (next >= 0) { + if (next > written) { + out.write(in, written, next - written); written = next; } else { - assert next==written; + assert next == written; } int rest = sz - next; @@ -70,10 +70,10 @@ public class PlainTextConsoleOutputStream extends LineTransformationOutputStream written += bytesUsed; - next = ConsoleNote.findPreamble(in,written,sz-written); + next = ConsoleNote.findPreamble(in, written, sz - written); } // finish the remaining bytes->chars conversion - out.write(in,written,sz-written); + out.write(in, written, sz - written); } } diff --git a/core/src/main/java/hudson/console/UrlAnnotator.java b/core/src/main/java/hudson/console/UrlAnnotator.java index f9cc1fc5505050d4503f2725f23c02694023755c..7422faee4b2c1824a30a8e5311db5cebbc6203b1 100644 --- a/core/src/main/java/hudson/console/UrlAnnotator.java +++ b/core/src/main/java/hudson/console/UrlAnnotator.java @@ -23,10 +23,10 @@ public class UrlAnnotator extends ConsoleAnnotatorFactory { public ConsoleAnnotator annotate(Object context, MarkupText text) { for (SubText t : text.findTokens(URL)) { int prev = t.start() - 1; - char ch = prev>=0 ? text.charAt(prev) : ' '; + char ch = prev >= 0 ? text.charAt(prev) : ' '; int idx = OPEN.indexOf(ch); - if (idx>=0) {// if inside a bracket, exclude the end bracket. - t=t.subText(0,t.getText().indexOf(CLOSE.charAt(idx))); + if (idx >= 0) { // if inside a bracket, exclude the end bracket. + t = t.subText(0, t.getText().indexOf(CLOSE.charAt(idx))); } t.href(t.getText()); } @@ -44,6 +44,6 @@ public class UrlAnnotator extends ConsoleAnnotatorFactory { private static final Pattern URL = Pattern.compile("\\b(http|https|file|ftp)://[^\\s<>]+[^\\s<>,\\.:\"'()\\[\\]=]"); private static final String OPEN = "'\"()[]<>"; - private static final String CLOSE= "'\")(][><"; + private static final String CLOSE = "'\")(][><"; } } diff --git a/core/src/main/java/hudson/diagnosis/HudsonHomeDiskUsageChecker.java b/core/src/main/java/hudson/diagnosis/HudsonHomeDiskUsageChecker.java index 4e3cf6b95febfd1a648b7712fbca9df1ce364793..8b38c3e5a776618f9f55c6707e4d53bfcdf084a3 100644 --- a/core/src/main/java/hudson/diagnosis/HudsonHomeDiskUsageChecker.java +++ b/core/src/main/java/hudson/diagnosis/HudsonHomeDiskUsageChecker.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.diagnosis; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; @@ -48,14 +49,14 @@ public class HudsonHomeDiskUsageChecker extends PeriodicWork { protected void doRun() { long free = Jenkins.get().getRootDir().getUsableSpace(); long total = Jenkins.get().getRootDir().getTotalSpace(); - if(free<=0 || total<=0) { + if (free <= 0 || total <= 0) { // information unavailable. pointless to try. LOGGER.info("JENKINS_HOME disk usage information isn't available. aborting to monitor"); cancel(); return; } - LOGGER.fine("Monitoring disk usage of JENKINS_HOME. total="+total+" free="+free); + LOGGER.fine("Monitoring disk usage of JENKINS_HOME. total=" + total + " free=" + free); // if it's more than 90% full and less than the minimum, activate @@ -71,5 +72,5 @@ public class HudsonHomeDiskUsageChecker extends PeriodicWork { */ @SuppressFBWarnings(value = "MS_SHOULD_BE_FINAL", justification = "for script console") public static long FREE_SPACE_THRESHOLD = SystemProperties.getLong(HudsonHomeDiskUsageChecker.class.getName() - + ".freeSpaceThreshold", 1024L*1024*1024*10); + + ".freeSpaceThreshold", 1024L * 1024 * 1024 * 10); } diff --git a/core/src/main/java/hudson/diagnosis/HudsonHomeDiskUsageMonitor.java b/core/src/main/java/hudson/diagnosis/HudsonHomeDiskUsageMonitor.java index 9562952408d80155a3459a9cefc3398c516d5fd6..b3ba5d34e9fa1e272881ff4abff4d78fccd761f3 100644 --- a/core/src/main/java/hudson/diagnosis/HudsonHomeDiskUsageMonitor.java +++ b/core/src/main/java/hudson/diagnosis/HudsonHomeDiskUsageMonitor.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.diagnosis; import hudson.Extension; @@ -56,10 +57,10 @@ public final class HudsonHomeDiskUsageMonitor extends AdministrativeMonitor { public boolean isActivated() { return activated; } - + @Override public String getDisplayName() { - return Messages.HudsonHomeDiskUsageMonitor_DisplayName(); + return Messages.HudsonHomeDiskUsageMonitor_DisplayName(); } /** @@ -67,7 +68,7 @@ public final class HudsonHomeDiskUsageMonitor extends AdministrativeMonitor { */ @RequirePOST public HttpResponse doAct(@QueryParameter String no) throws IOException { - if(no!=null) { + if (no != null) { disable(true); return HttpResponses.redirectViaContextPath("/manage"); } else { @@ -83,8 +84,8 @@ public final class HudsonHomeDiskUsageMonitor extends AdministrativeMonitor { * Binds a solution to the URL. */ public Solution getSolution(String id) { - for( Solution s : Solution.all() ) - if(s.id.equals(id)) + for (Solution s : Solution.all()) + if (s.id.equals(id)) return s; return null; } @@ -129,7 +130,7 @@ public final class HudsonHomeDiskUsageMonitor extends AdministrativeMonitor { * Returns the URL of this monitor, relative to the context path. */ public String getUrl() { - return HudsonHomeDiskUsageMonitor.get().getUrl()+"/solution/"+id; + return HudsonHomeDiskUsageMonitor.get().getUrl() + "/solution/" + id; } /** diff --git a/core/src/main/java/hudson/diagnosis/MemoryUsageMonitor.java b/core/src/main/java/hudson/diagnosis/MemoryUsageMonitor.java index 06ed43cb1a78e79413ff27510687686455320155..797ee03d6b21ea3231d83ed1b5777e32cd003dd2 100644 --- a/core/src/main/java/hudson/diagnosis/MemoryUsageMonitor.java +++ b/core/src/main/java/hudson/diagnosis/MemoryUsageMonitor.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.diagnosis; import hudson.Extension; @@ -49,7 +50,7 @@ import org.kohsuke.stapler.QueryParameter; @Extension @Symbol("memoryUsage") public final class MemoryUsageMonitor extends PeriodicWork { /** - * A memory group is conceptually a set of memory pools. + * A memory group is conceptually a set of memory pools. */ public static final class MemoryGroup { private final List pools = new ArrayList<>(); @@ -58,11 +59,11 @@ public final class MemoryUsageMonitor extends PeriodicWork { * Trend of the memory usage, after GCs. * So this shows the accurate snapshot of the footprint of live objects. */ - public final MultiStageTimeSeries used = new MultiStageTimeSeries(Messages._MemoryUsageMonitor_USED(), ColorPalette.RED, 0,0); + public final MultiStageTimeSeries used = new MultiStageTimeSeries(Messages._MemoryUsageMonitor_USED(), ColorPalette.RED, 0, 0); /** * Trend of the maximum memory size, after GCs. */ - public final MultiStageTimeSeries max = new MultiStageTimeSeries(Messages._MemoryUsageMonitor_TOTAL(), ColorPalette.BLUE, 0,0); + public final MultiStageTimeSeries max = new MultiStageTimeSeries(Messages._MemoryUsageMonitor_TOTAL(), ColorPalette.BLUE, 0, 0); private MemoryGroup(List pools, MemoryType type) { for (MemoryPoolMXBean pool : pools) { @@ -76,7 +77,7 @@ public final class MemoryUsageMonitor extends PeriodicWork { long max = 0; for (MemoryPoolMXBean pool : pools) { MemoryUsage usage = pool.getCollectionUsage(); - if(usage==null) continue; // not available + if (usage == null) continue; // not available used += usage.getUsed(); max += usage.getMax(); } @@ -94,7 +95,7 @@ public final class MemoryUsageMonitor extends PeriodicWork { */ public TrendChart doGraph(@QueryParameter String type) throws IOException { Jenkins.get().checkAnyPermission(Jenkins.SYSTEM_READ, Jenkins.MANAGE); - return MultiStageTimeSeries.createTrendChart(TimeScale.parse(type),used,max); + return MultiStageTimeSeries.createTrendChart(TimeScale.parse(type), used, max); } } diff --git a/core/src/main/java/hudson/diagnosis/NullIdDescriptorMonitor.java b/core/src/main/java/hudson/diagnosis/NullIdDescriptorMonitor.java index ac9ead6692926a3754ef77ab01327b4184798ac3..43a1505aa606ac5f750642626602d1c95a7ab126 100644 --- a/core/src/main/java/hudson/diagnosis/NullIdDescriptorMonitor.java +++ b/core/src/main/java/hudson/diagnosis/NullIdDescriptorMonitor.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.diagnosis; import static hudson.init.InitMilestone.EXTENSIONS_AUGMENTED; @@ -65,7 +66,7 @@ public class NullIdDescriptorMonitor extends AdministrativeMonitor { return Collections.unmodifiableList(problems); } - @Initializer(after=EXTENSIONS_AUGMENTED) + @Initializer(after = EXTENSIONS_AUGMENTED) public void verify() { Jenkins h = Jenkins.get(); for (Descriptor d : h.getExtensionList(Descriptor.class)) { @@ -74,14 +75,14 @@ public class NullIdDescriptorMonitor extends AdministrativeMonitor { try { id = d.getId(); } catch (Throwable t) { - LOGGER.log(Level.SEVERE,MessageFormat.format("Descriptor {0} from plugin {1} with display name {2} reported an exception for ID", - d, p == null ? "???" : p.getLongName(), d.getDisplayName()),t); + LOGGER.log(Level.SEVERE, MessageFormat.format("Descriptor {0} from plugin {1} with display name {2} reported an exception for ID", + d, p == null ? "???" : p.getLongName(), d.getDisplayName()), t); problems.add(d); continue; } - if (id==null) { + if (id == null) { LOGGER.severe(MessageFormat.format("Descriptor {0} from plugin {1} with display name {2} has null ID", - d, p==null?"???":p.getLongName(), d.getDisplayName())); + d, p == null ? "???" : p.getLongName(), d.getDisplayName())); problems.add(d); } } diff --git a/core/src/main/java/hudson/diagnosis/OldDataMonitor.java b/core/src/main/java/hudson/diagnosis/OldDataMonitor.java index 283fe73e48a6d82f26a41668f9ada60bd6e0e884..6bce4ae05f0b4d51c152f0f62c7ac5b230007a7a 100644 --- a/core/src/main/java/hudson/diagnosis/OldDataMonitor.java +++ b/core/src/main/java/hudson/diagnosis/OldDataMonitor.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.diagnosis; import com.thoughtworks.xstream.converters.UnmarshallingContext; @@ -77,7 +78,7 @@ import org.kohsuke.stapler.interceptor.RequirePOST; public class OldDataMonitor extends AdministrativeMonitor { private static final Logger LOGGER = Logger.getLogger(OldDataMonitor.class.getName()); - private ConcurrentMap data = new ConcurrentHashMap<>(); + private ConcurrentMap data = new ConcurrentHashMap<>(); /** * Gets instance of the monitor. @@ -105,9 +106,9 @@ public class OldDataMonitor extends AdministrativeMonitor { return !data.isEmpty(); } - public Map getData() { - Map r = new HashMap<>(); - for (Map.Entry entry : this.data.entrySet()) { + public Map getData() { + Map r = new HashMap<>(); + for (Map.Entry entry : this.data.entrySet()) { Saveable s = entry.getKey().get(); if (s != null) { r.put(s, entry.getValue()); @@ -191,6 +192,7 @@ public class OldDataMonitor extends AdministrativeMonitor { private static class ReportException extends Exception { private String version; + private ReportException(String version) { this.version = version; } @@ -206,7 +208,7 @@ public class OldDataMonitor extends AdministrativeMonitor { int i = 0; for (Throwable e : errors) { if (e instanceof ReportException) { - report(obj, ((ReportException)e).version); + report(obj, ((ReportException) e).version); } else { if (Main.isUnitTest) { LOGGER.log(Level.INFO, "Trouble loading " + obj, e); @@ -273,7 +275,7 @@ public class OldDataMonitor extends AdministrativeMonitor { @Override public String toString() { - return min==null ? "" : min + (single ? "" : " - " + max.toString()); + return min == null ? "" : min + (single ? "" : " - " + max.toString()); } /** @@ -357,7 +359,7 @@ public class OldDataMonitor extends AdministrativeMonitor { * would see the warning again after next restart). */ List removed = new ArrayList<>(); - for (Map.Entry entry : data.entrySet()) { + for (Map.Entry entry : data.entrySet()) { if (matchingPredicate.test(entry)) { Saveable s = entry.getKey().get(); if (s != null) { @@ -396,15 +398,19 @@ public class OldDataMonitor extends AdministrativeMonitor { private static final class SimpleSaveableReference implements SaveableReference { private final Saveable instance; + SimpleSaveableReference(Saveable instance) { this.instance = instance; } + @Override public Saveable get() { return instance; } + @Override public int hashCode() { return instance.hashCode(); } + @Override public boolean equals(Object obj) { return obj instanceof SimpleSaveableReference && instance.equals(((SimpleSaveableReference) obj).instance); } @@ -414,9 +420,11 @@ public class OldDataMonitor extends AdministrativeMonitor { private static final class RunSaveableReference implements SaveableReference { private final String id; - RunSaveableReference(Run r) { + + RunSaveableReference(Run r) { id = r.getExternalizableId(); } + @Override public Saveable get() { try { return Run.fromExternalizableId(id); @@ -426,9 +434,11 @@ public class OldDataMonitor extends AdministrativeMonitor { return null; } } + @Override public int hashCode() { return id.hashCode(); } + @Override public boolean equals(Object obj) { return obj instanceof RunSaveableReference && id.equals(((RunSaveableReference) obj).id); } diff --git a/core/src/main/java/hudson/diagnosis/ReverseProxySetupMonitor.java b/core/src/main/java/hudson/diagnosis/ReverseProxySetupMonitor.java index 10c72113ddbea284344d3b6e776b7479c7681cb5..af7b2579db745bfc2b6d911480c2f7a2f2ced210 100644 --- a/core/src/main/java/hudson/diagnosis/ReverseProxySetupMonitor.java +++ b/core/src/main/java/hudson/diagnosis/ReverseProxySetupMonitor.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.diagnosis; import hudson.Extension; @@ -115,7 +116,7 @@ public class ReverseProxySetupMonitor extends AdministrativeMonitor { @RestrictedSince("2.235") @RequirePOST public HttpResponse doAct(@QueryParameter String no) throws IOException { - if(no!=null) { // dismiss + if (no != null) { // dismiss Jenkins.get().checkPermission(Jenkins.ADMINISTER); disable(true); // of course the irony is that this redirect won't work diff --git a/core/src/main/java/hudson/diagnosis/TooManyJobsButNoView.java b/core/src/main/java/hudson/diagnosis/TooManyJobsButNoView.java index ee1e1566c3b70912180299a2592a093b083db210..6412ac63bcb2a38bd5daeabd407b76ee3b7bd0a2 100644 --- a/core/src/main/java/hudson/diagnosis/TooManyJobsButNoView.java +++ b/core/src/main/java/hudson/diagnosis/TooManyJobsButNoView.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.diagnosis; import hudson.Extension; @@ -37,7 +38,7 @@ import org.kohsuke.stapler.interceptor.RequirePOST; * If Hudson is run with a lot of jobs but no views, suggest the user that they can create views. * *

- * I noticed at an user visit that some users didn't notice the '+' icon in the tab bar. + * I noticed at an user visit that some users didn't notice the '+' icon in the tab bar. * * @author Kohsuke Kawaguchi */ @@ -65,11 +66,11 @@ public class TooManyJobsButNoView extends AdministrativeMonitor { @RequirePOST public void doAct(StaplerRequest req, StaplerResponse rsp) throws IOException { Jenkins.get().checkPermission(Jenkins.ADMINISTER); - if(req.hasParameter("no")) { + if (req.hasParameter("no")) { disable(true); - rsp.sendRedirect(req.getContextPath()+"/manage"); + rsp.sendRedirect(req.getContextPath() + "/manage"); } else { - rsp.sendRedirect(req.getContextPath()+"/newView"); + rsp.sendRedirect(req.getContextPath() + "/newView"); } } diff --git a/core/src/main/java/hudson/init/InitMilestone.java b/core/src/main/java/hudson/init/InitMilestone.java index 4ee9fa26f418dff4022b7a29b9c70ff43780d1c8..5e8c03c3e05545415ee01626815f30aea20d8b16 100644 --- a/core/src/main/java/hudson/init/InitMilestone.java +++ b/core/src/main/java/hudson/init/InitMilestone.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.init; import org.jvnet.hudson.reactor.Executable; @@ -49,7 +50,7 @@ import org.jvnet.hudson.reactor.TaskGraphBuilder; *

  • JOB_CONFIG_ADAPTED
  • *
  • COMPLETED * - * + * * @author Kohsuke Kawaguchi */ public enum InitMilestone implements Milestone { @@ -131,8 +132,8 @@ public enum InitMilestone implements Milestone { public static TaskBuilder ordering() { TaskGraphBuilder b = new TaskGraphBuilder(); InitMilestone[] v = values(); - for (int i=0; i * To register, put {@link MetaInfServices} on your implementation. - * + * * @author Kohsuke Kawaguchi */ public class InitStrategy { @@ -58,10 +58,10 @@ public class InitStrategy { return r; } - + private void listPluginFiles(PluginManager pm, String extension, Collection all) throws IOException { File[] files = pm.rootDir.listFiles(new FilterByExtension(extension)); - if (files==null) + if (files == null) throw new IOException("Jenkins is unable to create " + pm.rootDir + "\nPerhaps its security privilege is insufficient"); all.addAll(Arrays.asList(files)); @@ -99,7 +99,7 @@ public class InitStrategy { /** * Selectively skip some of the initialization tasks. - * + * * @return * true to skip the execution. */ diff --git a/core/src/main/java/hudson/init/Initializer.java b/core/src/main/java/hudson/init/Initializer.java index 61b1c272be7c3bc9124d21b77258dafff64aa0d1..8248cabbde04f76199da17a95920bbe2a3d5e1c5 100644 --- a/core/src/main/java/hudson/init/Initializer.java +++ b/core/src/main/java/hudson/init/Initializer.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.init; import static hudson.init.InitMilestone.COMPLETED; diff --git a/core/src/main/java/hudson/init/InitializerFinder.java b/core/src/main/java/hudson/init/InitializerFinder.java index 8b11b5740c509271f9072e246c6aa83919dd4b03..938cbd5d78e39986bcd0a1ada725a883d633abdd 100644 --- a/core/src/main/java/hudson/init/InitializerFinder.java +++ b/core/src/main/java/hudson/init/InitializerFinder.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.init; import org.jvnet.hudson.reactor.Milestone; @@ -33,7 +34,7 @@ import org.jvnet.hudson.reactor.Milestone; public class InitializerFinder extends TaskMethodFinder { public InitializerFinder(ClassLoader cl) { - super(Initializer.class,InitMilestone.class,cl); + super(Initializer.class, InitMilestone.class, cl); } public InitializerFinder() { diff --git a/core/src/main/java/hudson/init/TaskMethodFinder.java b/core/src/main/java/hudson/init/TaskMethodFinder.java index 9925ca41900f1516ba6e55258541cfc4907a7a19..b15869ba8831f30d96110108b2f6084975e3558e 100644 --- a/core/src/main/java/hudson/init/TaskMethodFinder.java +++ b/core/src/main/java/hudson/init/TaskMethodFinder.java @@ -44,10 +44,15 @@ abstract class TaskMethodFinder extends TaskBuilder { // working around the restriction that Java doesn't allow annotation types to extend interfaces protected abstract String displayNameOf(T i); + protected abstract String[] requiresOf(T i); + protected abstract String[] attainsOf(T i); + protected abstract Milestone afterOf(T i); + protected abstract Milestone beforeOf(T i); + protected abstract boolean fatalOf(T i); @Override @@ -57,7 +62,7 @@ abstract class TaskMethodFinder extends TaskBuilder { if (filter(e)) continue; // already reported once T i = e.getAnnotation(type); - if (i==null) continue; // stale index + if (i == null) continue; // stale index result.add(new TaskImpl(i, e)); } @@ -77,13 +82,13 @@ abstract class TaskMethodFinder extends TaskBuilder { protected String getDisplayNameOf(Method e, T i) { Class c = e.getDeclaringClass(); String key = displayNameOf(i); - if (key.length()==0) return c.getSimpleName()+"."+e.getName(); + if (key.length() == 0) return c.getSimpleName() + "." + e.getName(); try { ResourceBundleHolder rb = ResourceBundleHolder.get( c.getClassLoader().loadClass(c.getPackage().getName() + ".Messages")); return rb.format(key); } catch (ClassNotFoundException x) { - LOGGER.log(WARNING, "Failed to load "+x.getMessage()+" for "+ e,x); + LOGGER.log(WARNING, "Failed to load " + x.getMessage() + " for " + e, x); return key; } catch (MissingResourceException x) { LOGGER.log(WARNING, "Could not find key '" + key + "' in " + c.getPackage().getName() + ".Messages", x); @@ -98,14 +103,14 @@ abstract class TaskMethodFinder extends TaskBuilder { try { Class[] pt = e.getParameterTypes(); Object[] args = new Object[pt.length]; - for (int i=0; i extends TaskBuilder { private Object lookUp(Class type) { Jenkins j = Jenkins.get(); assert j != null : "This method is only invoked after the Jenkins singleton instance has been set"; - if (type==Jenkins.class || type==Hudson.class) + if (type == Jenkins.class || type == Hudson.class) return j; Injector i = j.getInjector(); - if (i!=null) + if (i != null) return i.getInstance(type); - throw new IllegalArgumentException("Unable to inject "+type); + throw new IllegalArgumentException("Unable to inject " + type); } /** @@ -189,7 +194,7 @@ abstract class TaskMethodFinder extends TaskBuilder { List r = new ArrayList<>(); for (String s : tokens) { try { - r.add((Milestone)Enum.valueOf(milestoneType,s)); + r.add((Milestone) Enum.valueOf(milestoneType, s)); } catch (IllegalArgumentException x) { r.add(new MilestoneImpl(s)); } diff --git a/core/src/main/java/hudson/init/TermMilestone.java b/core/src/main/java/hudson/init/TermMilestone.java index 85efd8d5eab71aab90f674533a9c21857b32c3f7..5146e2dbb4eb71fcc04dada164f1695cc10a0c6e 100644 --- a/core/src/main/java/hudson/init/TermMilestone.java +++ b/core/src/main/java/hudson/init/TermMilestone.java @@ -44,8 +44,8 @@ public enum TermMilestone implements Milestone { public static TaskBuilder ordering() { TaskGraphBuilder b = new TaskGraphBuilder(); TermMilestone[] v = values(); - for (int i=0; i { public TerminatorFinder(ClassLoader cl) { super(Terminator.class, TermMilestone.class, cl); } - + @Override protected String displayNameOf(Terminator i) { return i.displayName(); diff --git a/core/src/main/java/hudson/init/impl/GroovyInitScript.java b/core/src/main/java/hudson/init/impl/GroovyInitScript.java index 69a36cc18e3eec1465018fba17b83cada70e0fb5..17f6a4702c940b82e3b0e5af183cc0088ae69a5c 100644 --- a/core/src/main/java/hudson/init/impl/GroovyInitScript.java +++ b/core/src/main/java/hudson/init/impl/GroovyInitScript.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.init.impl; import static hudson.init.InitMilestone.JOB_CONFIG_ADAPTED; @@ -36,7 +37,7 @@ import jenkins.util.groovy.GroovyHookScript; * @author Kohsuke Kawaguchi */ public class GroovyInitScript { - @Initializer(after=JOB_CONFIG_ADAPTED) + @Initializer(after = JOB_CONFIG_ADAPTED) public static void init(Jenkins j) { new GroovyHookScript("init", j.servletContext, j.getRootDir(), j.getPluginManager().uberClassLoader).run(); } diff --git a/core/src/main/java/hudson/init/impl/InitialUserContent.java b/core/src/main/java/hudson/init/impl/InitialUserContent.java index 810bcdcce7d4cdaa7db2ccf86745f39c895a6c59..81cc279eb909ed5be6843b919608f6e482e988ec 100644 --- a/core/src/main/java/hudson/init/impl/InitialUserContent.java +++ b/core/src/main/java/hudson/init/impl/InitialUserContent.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.init.impl; import static hudson.init.InitMilestone.JOB_CONFIG_ADAPTED; @@ -39,12 +40,12 @@ import org.apache.commons.io.FileUtils; * @author Kohsuke Kawaguchi */ public class InitialUserContent { - @Initializer(after=JOB_CONFIG_ADAPTED) + @Initializer(after = JOB_CONFIG_ADAPTED) public static void init(Jenkins h) throws IOException { File userContentDir = new File(h.getRootDir(), "userContent"); if (!Files.isDirectory(Util.fileToPath(userContentDir))) { Util.createDirectories(Util.fileToPath(userContentDir)); - FileUtils.writeStringToFile(new File(userContentDir,"readme.txt"), Messages.Hudson_USER_CONTENT_README() + "\n"); + FileUtils.writeStringToFile(new File(userContentDir, "readme.txt"), Messages.Hudson_USER_CONTENT_README() + "\n"); } } } diff --git a/core/src/main/java/hudson/init/impl/InstallUncaughtExceptionHandler.java b/core/src/main/java/hudson/init/impl/InstallUncaughtExceptionHandler.java index eea0f4eea857a6149e9c57aeb659658005ad0e74..e09237bef91850f4b0be75d0892070ac2d884a07 100644 --- a/core/src/main/java/hudson/init/impl/InstallUncaughtExceptionHandler.java +++ b/core/src/main/java/hudson/init/impl/InstallUncaughtExceptionHandler.java @@ -53,7 +53,7 @@ public class InstallUncaughtExceptionHandler { String id = UUID.randomUUID().toString(); LOGGER.log(isEOFException(e) ? Level.FINE : Level.WARNING, "Caught unhandled exception with ID " + id, e); req.setAttribute("jenkins.exception.id", id); - req.setAttribute("javax.servlet.error.exception",e); + req.setAttribute("javax.servlet.error.exception", e); rsp.setStatus(code); try { WebApp.get(j.servletContext).getSomeStapler().invoke(req, rsp, j, "/oops"); diff --git a/core/src/main/java/hudson/lifecycle/ExitLifecycle.java b/core/src/main/java/hudson/lifecycle/ExitLifecycle.java index 01855e1e225e03a6df1b158e068400fcae66ce31..f8fcc3abefbf8a999b3521aaec3bd19bc3b72024 100644 --- a/core/src/main/java/hudson/lifecycle/ExitLifecycle.java +++ b/core/src/main/java/hudson/lifecycle/ExitLifecycle.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.lifecycle; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; diff --git a/core/src/main/java/hudson/lifecycle/Lifecycle.java b/core/src/main/java/hudson/lifecycle/Lifecycle.java index 04123c797ef0bbe0db50ec322d438e5a7f8fe362..8e84179b5a0fba6d2478874599e78f58e0743c0e 100644 --- a/core/src/main/java/hudson/lifecycle/Lifecycle.java +++ b/core/src/main/java/hudson/lifecycle/Lifecycle.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.lifecycle; import hudson.ExtensionPoint; @@ -57,13 +58,13 @@ public abstract class Lifecycle implements ExtensionPoint { * @return never null */ public static synchronized Lifecycle get() { - if(INSTANCE==null) { + if (INSTANCE == null) { Lifecycle instance; String p = SystemProperties.getString("hudson.lifecycle"); - if(p!=null) { + if (p != null) { try { ClassLoader cl = Jenkins.get().getPluginManager().uberClassLoader; - instance = (Lifecycle)cl.loadClass(p).getDeclaredConstructor().newInstance(); + instance = (Lifecycle) cl.loadClass(p).getDeclaredConstructor().newInstance(); } catch (NoSuchMethodException e) { NoSuchMethodError x = new NoSuchMethodError(e.getMessage()); x.initCause(e); @@ -95,7 +96,7 @@ public abstract class Lifecycle implements ExtensionPoint { } } } else { - if(Functions.isWindows()) { + if (Functions.isWindows()) { instance = new Lifecycle() { @Override public void verifyRestartable() throws RestartNotSupportedException { @@ -103,7 +104,7 @@ public abstract class Lifecycle implements ExtensionPoint { "Default Windows lifecycle does not support restart."); } }; - } else if (System.getenv("SMF_FMRI")!=null && System.getenv("SMF_RESTARTER")!=null) { + } else if (System.getenv("SMF_FMRI") != null && System.getenv("SMF_RESTARTER") != null) { // when we are run by Solaris SMF, these environment variables are set. instance = new SolarisSMFLifecycle(); } else { @@ -111,7 +112,7 @@ public abstract class Lifecycle implements ExtensionPoint { try { instance = new UnixLifecycle(); } catch (final IOException e) { - LOGGER.log(Level.WARNING, "Failed to install embedded lifecycle implementation",e); + LOGGER.log(Level.WARNING, "Failed to install embedded lifecycle implementation", e); instance = new Lifecycle() { @Override public void verifyRestartable() throws RestartNotSupportedException { @@ -139,7 +140,7 @@ public abstract class Lifecycle implements ExtensionPoint { */ public File getHudsonWar() { String war = SystemProperties.getString("executable-war"); - if(war!=null && new File(war).exists()) + if (war != null && new File(war).exists()) return new File(war); return null; } @@ -156,7 +157,7 @@ public abstract class Lifecycle implements ExtensionPoint { File dest = getHudsonWar(); // this should be impossible given the canRewriteHudsonWar method, // but let's be defensive - if(dest==null) throw new IOException("jenkins.war location is not known."); + if (dest == null) throw new IOException("jenkins.war location is not known."); // backing up the old jenkins.war before it gets lost due to upgrading // (newly downloaded jenkins.war and 'backup' (jenkins.war.tmp) are the same files @@ -164,7 +165,7 @@ public abstract class Lifecycle implements ExtensionPoint { File bak = new File(dest.getPath() + ".bak"); if (!by.equals(bak)) FileUtils.copyFile(dest, bak); - + FileUtils.copyFile(by, dest); // we don't want to keep backup if we are downgrading if (by.equals(bak)) { @@ -213,7 +214,7 @@ public abstract class Lifecycle implements ExtensionPoint { */ public void verifyRestartable() throws RestartNotSupportedException { // the rewriteHudsonWar method isn't overridden. - if (!Util.isOverridden(Lifecycle.class,getClass(), "restart")) + if (!Util.isOverridden(Lifecycle.class, getClass(), "restart")) throw new RestartNotSupportedException("Restart is not supported in this running mode (" + getClass().getName() + ")."); } diff --git a/core/src/main/java/hudson/lifecycle/SolarisSMFLifecycle.java b/core/src/main/java/hudson/lifecycle/SolarisSMFLifecycle.java index eecc28ea26de47089894afe8004422a10c407d92..2dd362936599357c8aec7fa9ff669e4c0999d15b 100644 --- a/core/src/main/java/hudson/lifecycle/SolarisSMFLifecycle.java +++ b/core/src/main/java/hudson/lifecycle/SolarisSMFLifecycle.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.lifecycle; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; diff --git a/core/src/main/java/hudson/lifecycle/UnixLifecycle.java b/core/src/main/java/hudson/lifecycle/UnixLifecycle.java index 498db2c0e98456b6eb6847bfa03f8c5efd5d1bf0..ca8f50b9f589d4d462c11b4452fff139a244f79e 100644 --- a/core/src/main/java/hudson/lifecycle/UnixLifecycle.java +++ b/core/src/main/java/hudson/lifecycle/UnixLifecycle.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.lifecycle; import static hudson.util.jna.GNUCLibrary.FD_CLOEXEC; @@ -74,16 +75,16 @@ public class UnixLifecycle extends Lifecycle { // close all files upon exec, except stdin, stdout, and stderr int sz = LIBC.getdtablesize(); - for(int i=3; i' + getHudsonWar().getAbsolutePath() + '\n'); @@ -133,14 +134,14 @@ public class WindowsServiceLifecycle extends Lifecycle { task.getLogger().println("Restarting a service"); String exe = System.getenv("WINSW_EXECUTABLE"); File executable; - if (exe!=null) executable = new File(exe); + if (exe != null) executable = new File(exe); else executable = new File(home, "hudson.exe"); if (!executable.exists()) executable = new File(home, "jenkins.exe"); // use restart! to run hudson/jenkins.exe restart in a separate process, so it doesn't kill itself int r = new LocalLauncher(task).launch().cmds(executable, "restart!") .stdout(task).pwd(home).join(); - if(r!=0) + if (r != 0) throw new IOException(baos.toString()); } diff --git a/core/src/main/java/hudson/logging/LogRecorder.java b/core/src/main/java/hudson/logging/LogRecorder.java index 9c54a8e0db3bdc49e0cf98579584aade48485dc7..db0fe5be09e500d027efb271b48bfe5074180dce 100644 --- a/core/src/main/java/hudson/logging/LogRecorder.java +++ b/core/src/main/java/hudson/logging/LogRecorder.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.logging; import com.google.common.annotations.VisibleForTesting; @@ -116,7 +117,7 @@ public class LogRecorder extends AbstractModelObject implements Saveable { this.name = name; // register it only once when constructed, and when this object dies // WeakLogHandler will remove it - new WeakLogHandler(handler,Logger.getLogger("")); + new WeakLogHandler(handler, Logger.getLogger("")); } private Object readResolve() { @@ -242,7 +243,7 @@ public class LogRecorder extends AbstractModelObject implements Saveable { private transient /* almost final*/ Logger logger; public Target(String name, Level level) { - this(name,level.intValue()); + this(name, level.intValue()); } public Target(String name, int level) { @@ -252,7 +253,7 @@ public class LogRecorder extends AbstractModelObject implements Saveable { @DataBoundConstructor public Target(String name, String level) { - this(name,Level.parse(level)); + this(name, Level.parse(level)); } public Level getLevel() { @@ -282,16 +283,16 @@ public class LogRecorder extends AbstractModelObject implements Saveable { @Deprecated public boolean includes(LogRecord r) { - if(r.getLevel().intValue() < level) + if (r.getLevel().intValue() < level) return false; // below the threshold if (name.length() == 0) { return true; // like root logger, includes everything } String logName = r.getLoggerName(); - if(logName==null || !logName.startsWith(name)) + if (logName == null || !logName.startsWith(name)) return false; // not within this logger String rest = logName.substring(name.length()); - return rest.startsWith(".") || rest.length()==0; + return rest.startsWith(".") || rest.length() == 0; } @SuppressFBWarnings(value = "NP_BOOLEAN_RETURN_NULL", justification = "converting this to YesNoMaybe would break backward compatibility") @@ -301,10 +302,10 @@ public class LogRecorder extends AbstractModelObject implements Saveable { return levelSufficient; // include if level matches } String logName = r.getLoggerName(); - if(logName==null || !logName.startsWith(name)) + if (logName == null || !logName.startsWith(name)) return null; // not in the domain of this logger String rest = logName.substring(name.length()); - if (rest.startsWith(".") || rest.length()==0) { + if (rest.startsWith(".") || rest.length() == 0) { return levelSufficient; // include if level matches } return null; @@ -322,7 +323,7 @@ public class LogRecorder extends AbstractModelObject implements Saveable { */ public void enable() { Logger l = getLogger(); - if(!l.isLoggable(getLevel())) + if (!l.isLoggable(getLevel())) l.setLevel(getLevel()); new SetLevel(name, getLevel()).broadcast(); } @@ -344,21 +345,24 @@ public class LogRecorder extends AbstractModelObject implements Saveable { } } - private static final class SetLevel extends MasterToSlaveCallable { + private static final class SetLevel extends MasterToSlaveCallable { /** known loggers (kept per agent), to avoid GC */ @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") private static final Set loggers = new HashSet<>(); private final String name; private final Level level; + SetLevel(String name, Level level) { this.name = name; this.level = level; } + @Override public Void call() throws Error { Logger logger = Logger.getLogger(name); loggers.add(logger); logger.setLevel(level); return null; } + void broadcast() { for (Computer c : Jenkins.get().getComputers()) { if (c.getName().length() > 0) { // i.e. not master @@ -407,14 +411,14 @@ public class LogRecorder extends AbstractModelObject implements Saveable { * Accepts submission from the configuration page. */ @POST - public synchronized void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { + public synchronized void doConfigSubmit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { Jenkins.get().checkPermission(Jenkins.ADMINISTER); JSONObject src = req.getSubmittedForm(); String newName = src.getString("name"), redirect = "."; XmlFile oldFile = null; - if(!name.equals(newName)) { + if (!name.equals(newName)) { Jenkins.checkGoodName(newName); oldFile = getConfigFile(); // rename @@ -430,7 +434,7 @@ public class LogRecorder extends AbstractModelObject implements Saveable { setLoggers(newTargets); save(); - if (oldFile!=null) oldFile.delete(); + if (oldFile != null) oldFile.delete(); rsp.sendRedirect2(redirect); } @@ -455,7 +459,7 @@ public class LogRecorder extends AbstractModelObject implements Saveable { */ @Override public synchronized void save() throws IOException { - if(BulkChange.contains(this)) return; + if (BulkChange.contains(this)) return; handlePluginUpdatingLegacyLogManagerMap(); getConfigFile().write(this); @@ -519,8 +523,8 @@ public class LogRecorder extends AbstractModelObject implements Saveable { /** * RSS feed for log entries. */ - public void doRss( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { - LogRecorderManager.doRss(req,rsp,getLogRecords()); + public void doRss(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { + LogRecorderManager.doRss(req, rsp, getLogRecords()); } /** @@ -542,8 +546,8 @@ public class LogRecorder extends AbstractModelObject implements Saveable { * @return a map (sorted by display name) from computer to (nonempty) list of log records * @since 1.519 */ - public Map> getSlaveLogRecords() { - Map> result = new TreeMap<>(new Comparator() { + public Map> getSlaveLogRecords() { + Map> result = new TreeMap<>(new Comparator() { final Collator COLL = Collator.getInstance(); @Override @@ -581,8 +585,8 @@ public class LogRecorder extends AbstractModelObject implements Saveable { public static final XStream XSTREAM = new XStream2(); static { - XSTREAM.alias("log",LogRecorder.class); - XSTREAM.alias("target",Target.class); + XSTREAM.alias("log", LogRecorder.class); + XSTREAM.alias("target", Target.class); } /** diff --git a/core/src/main/java/hudson/logging/LogRecorderManager.java b/core/src/main/java/hudson/logging/LogRecorderManager.java index 8a13849f3f891836fe47ce6f248fec4e40aba47f..0ea3a58267adf0cc8a1d4c4709fd4d49427c7d67 100644 --- a/core/src/main/java/hudson/logging/LogRecorderManager.java +++ b/core/src/main/java/hudson/logging/LogRecorderManager.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.logging; import static hudson.init.InitMilestone.PLUGINS_PREPARED; @@ -83,7 +84,7 @@ public class LogRecorderManager extends AbstractModelObject implements ModelObje @Deprecated @Restricted(NoExternalUse.class) @RestrictedSince("TODO") - public final transient Map logRecorders = new CopyOnWriteMap.Tree<>(); + public final transient Map logRecorders = new CopyOnWriteMap.Tree<>(); private List recorders; @@ -102,7 +103,7 @@ public class LogRecorderManager extends AbstractModelObject implements ModelObje Map values = recorders.stream() .collect(toMap(LogRecorder::getName, Function.identity())); - ((CopyOnWriteMap) logRecorders).replaceBy(values); + ((CopyOnWriteMap) logRecorders).replaceBy(values); } @Override @@ -133,11 +134,11 @@ public class LogRecorderManager extends AbstractModelObject implements ModelObje public void load() throws IOException { recorders.clear(); File dir = configDir(); - File[] files = dir.listFiles((FileFilter)new WildcardFileFilter("*.xml")); - if(files==null) return; + File[] files = dir.listFiles((FileFilter) new WildcardFileFilter("*.xml")); + if (files == null) return; for (File child : files) { String name = child.getName(); - name = name.substring(0,name.length()-4); // cut off ".xml" + name = name.substring(0, name.length() - 4); // cut off ".xml" LogRecorder lr = new LogRecorder(name); lr.load(); recorders.add(lr); @@ -157,13 +158,13 @@ public class LogRecorderManager extends AbstractModelObject implements ModelObje recorders.add(new LogRecorder(name)); // redirect to the config screen - return new HttpRedirect(name+"/configure"); + return new HttpRedirect(name + "/configure"); } @Override public ContextMenu doChildrenContextMenu(StaplerRequest request, StaplerResponse response) throws Exception { ContextMenu menu = new ContextMenu(); - menu.add("all","All Jenkins Logs"); + menu.add("all", "All Jenkins Logs"); for (LogRecorder lr : recorders) { menu.add(lr.getSearchUrl(), lr.getDisplayName()); } @@ -181,7 +182,7 @@ public class LogRecorderManager extends AbstractModelObject implements ModelObje public HttpResponse doConfigLogger(@QueryParameter String name, @QueryParameter String level) { Jenkins.get().checkPermission(Jenkins.ADMINISTER); Level lv; - if(level.equals("inherit")) + if (level.equals("inherit")) lv = null; else lv = Level.parse(level.toUpperCase(Locale.ENGLISH)); @@ -198,7 +199,7 @@ public class LogRecorderManager extends AbstractModelObject implements ModelObje /** * RSS feed for log entries. */ - public void doRss( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { + public void doRss(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { doRss(req, rsp, Jenkins.logRecords); } @@ -209,18 +210,18 @@ public class LogRecorderManager extends AbstractModelObject implements ModelObje // filter log records based on the log level String entryType = "all"; String level = req.getParameter("level"); - if(level!=null) { + if (level != null) { Level threshold = Level.parse(level); List filtered = new ArrayList<>(); for (LogRecord r : logs) { - if(r.getLevel().intValue() >= threshold.intValue()) + if (r.getLevel().intValue() >= threshold.intValue()) filtered.add(r); } logs = filtered; entryType = level; } - RSS.forwardToRss("Jenkins:log (" + entryType + " entries)","", logs, new FeedAdapter() { + RSS.forwardToRss("Jenkins:log (" + entryType + " entries)", "", logs, new FeedAdapter() { @Override public String getEntryTitle(LogRecord entry) { return entry.getMessage(); @@ -252,10 +253,10 @@ public class LogRecorderManager extends AbstractModelObject implements ModelObje public String getEntryAuthor(LogRecord entry) { return JenkinsLocationConfiguration.get().getAdminAddress(); } - },req,rsp); + }, req, rsp); } - @Initializer(before=PLUGINS_PREPARED) + @Initializer(before = PLUGINS_PREPARED) public static void init(Jenkins h) throws IOException { h.getLog().load(); } diff --git a/core/src/main/java/hudson/logging/WeakLogHandler.java b/core/src/main/java/hudson/logging/WeakLogHandler.java index 21fd6bdfe2cc9fa70cc730926c3d73a0bc7d33fc..bc0cb1c349a47f6d0a47449d013a9d232b952336 100644 --- a/core/src/main/java/hudson/logging/WeakLogHandler.java +++ b/core/src/main/java/hudson/logging/WeakLogHandler.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.logging; import java.io.UnsupportedEncodingException; @@ -50,27 +51,27 @@ public final class WeakLogHandler extends Handler { @Override public void publish(LogRecord record) { Handler t = resolve(); - if(t!=null) + if (t != null) t.publish(record); } @Override public void flush() { Handler t = resolve(); - if(t!=null) + if (t != null) t.flush(); } @Override public void close() throws SecurityException { Handler t = resolve(); - if(t!=null) + if (t != null) t.close(); } private Handler resolve() { Handler r = target.get(); - if(r==null) + if (r == null) logger.removeHandler(this); return r; } @@ -79,7 +80,7 @@ public final class WeakLogHandler extends Handler { public void setFormatter(Formatter newFormatter) throws SecurityException { super.setFormatter(newFormatter); Handler t = resolve(); - if(t!=null) + if (t != null) t.setFormatter(newFormatter); } @@ -87,7 +88,7 @@ public final class WeakLogHandler extends Handler { public void setEncoding(String encoding) throws SecurityException, UnsupportedEncodingException { super.setEncoding(encoding); Handler t = resolve(); - if(t!=null) + if (t != null) t.setEncoding(encoding); } @@ -95,7 +96,7 @@ public final class WeakLogHandler extends Handler { public void setFilter(Filter newFilter) throws SecurityException { super.setFilter(newFilter); Handler t = resolve(); - if(t!=null) + if (t != null) t.setFilter(newFilter); } @@ -103,7 +104,7 @@ public final class WeakLogHandler extends Handler { public void setErrorManager(ErrorManager em) { super.setErrorManager(em); Handler t = resolve(); - if(t!=null) + if (t != null) t.setErrorManager(em); } @@ -111,14 +112,14 @@ public final class WeakLogHandler extends Handler { public void setLevel(Level newLevel) throws SecurityException { super.setLevel(newLevel); Handler t = resolve(); - if(t!=null) + if (t != null) t.setLevel(newLevel); } @Override public boolean isLoggable(LogRecord record) { Handler t = resolve(); - if(t!=null) + if (t != null) return t.isLoggable(record); else return super.isLoggable(record); diff --git a/core/src/main/java/hudson/markup/EscapedMarkupFormatter.java b/core/src/main/java/hudson/markup/EscapedMarkupFormatter.java index 338eea2652fe7072699f8d18c4c0a536a115f7ed..de83afabce6ced4b9e2c78264525e2c8f0f66ba9 100644 --- a/core/src/main/java/hudson/markup/EscapedMarkupFormatter.java +++ b/core/src/main/java/hudson/markup/EscapedMarkupFormatter.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.markup; import hudson.Extension; diff --git a/core/src/main/java/hudson/markup/MarkupFormatter.java b/core/src/main/java/hudson/markup/MarkupFormatter.java index 14a293790e3a7cd1bcd259a6af49ef0cfe2668e6..e588e0cfcc8e73b3729c7f4b0dee58d52c16d2e9 100644 --- a/core/src/main/java/hudson/markup/MarkupFormatter.java +++ b/core/src/main/java/hudson/markup/MarkupFormatter.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.markup; import edu.umd.cs.findbugs.annotations.CheckForNull; @@ -62,7 +63,7 @@ import org.kohsuke.stapler.verb.POST; * Implement the following methods to enable and control CodeMirror syntax highlighting * public String getCodeMirrorMode() // return null to disable CodeMirror dynamically * public String getCodeMirrorConfig() - * + * *

    Views

    *

    * This extension point must have a valid {@code config.jelly} that feeds the constructor. @@ -92,7 +93,7 @@ public abstract class MarkupFormatter extends AbstractDescribableImpl all() { + public static DescriptorExtensionList all() { return Jenkins.get(). getDescriptorList(MarkupFormatter.class); } diff --git a/core/src/main/java/hudson/model/AbstractBuild.java b/core/src/main/java/hudson/model/AbstractBuild.java index a6ea4845b0db65448e0c26a9bae9272f9ba8168a..4c02e525904d51bd5bc6ba09da28c6bb86442d58 100644 --- a/core/src/main/java/hudson/model/AbstractBuild.java +++ b/core/src/main/java/hudson/model/AbstractBuild.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import static java.util.logging.Level.WARNING; @@ -102,7 +103,7 @@ import org.xml.sax.SAXException; * @author Kohsuke Kawaguchi * @see AbstractProject */ -public abstract class AbstractBuild

    ,R extends AbstractBuild> extends Run implements Queue.Executable, LazyBuildMixIn.LazyLoadingRun, RunWithSCM { +public abstract class AbstractBuild

    , R extends AbstractBuild> extends Run implements Queue.Executable, LazyBuildMixIn.LazyLoadingRun, RunWithSCM { /** * Set if we want the blame information to flow from upstream to downstream build. @@ -157,7 +158,7 @@ public abstract class AbstractBuild

    ,R extends Abs */ protected transient List buildEnvironments; - private final transient LazyBuildMixIn.RunMixIn runMixIn = new LazyBuildMixIn.RunMixIn() { + private final transient LazyBuildMixIn.RunMixIn runMixIn = new LazyBuildMixIn.RunMixIn() { @Override protected R asRun() { return _this(); } @@ -179,7 +180,7 @@ public abstract class AbstractBuild

    ,R extends Abs return getParent(); } - @Override public final LazyBuildMixIn.RunMixIn getRunMixIn() { + @Override public final LazyBuildMixIn.RunMixIn getRunMixIn() { return runMixIn; } @@ -208,7 +209,7 @@ public abstract class AbstractBuild

    ,R extends Abs * null, for example if the agent that this build run no longer exists. */ public @CheckForNull Node getBuiltOn() { - if (builtOn==null || builtOn.equals("")) + if (builtOn == null || builtOn.equals("")) return Jenkins.get(); else return Jenkins.get().getNode(builtOn); @@ -218,7 +219,7 @@ public abstract class AbstractBuild

    ,R extends Abs * Returns the name of the agent it was built on; null or "" if built by the built-in node. * (null happens when we read old record that didn't have this information.) */ - @Exported(name="builtOn") + @Exported(name = "builtOn") public String getBuiltOnStr() { return builtOn; } @@ -230,7 +231,7 @@ public abstract class AbstractBuild

    ,R extends Abs * * @since 1.429 */ - protected void setBuiltOnStr( String builtOn ) { + protected void setBuiltOnStr(String builtOn) { this.builtOn = builtOn; } @@ -248,7 +249,7 @@ public abstract class AbstractBuild

    ,R extends Abs * @since 1.421 * @see AbstractProject#getRootProject() */ - public AbstractBuild getRootBuild() { + public AbstractBuild getRootBuild() { return this; } @@ -271,7 +272,7 @@ public abstract class AbstractBuild

    ,R extends Abs * {@link #getDisplayName()}. */ public String getUpUrl() { - return Functions.getNearestAncestorUrl(Stapler.getCurrentRequest(),getParent())+'/'; + return Functions.getNearestAncestorUrl(Stapler.getCurrentRequest(), getParent()) + '/'; } /** @@ -288,9 +289,9 @@ public abstract class AbstractBuild

    ,R extends Abs * @since 1.319 */ public final @CheckForNull FilePath getWorkspace() { - if (workspace==null) return null; + if (workspace == null) return null; Node n = getBuiltOn(); - if (n==null) return null; + if (n == null) return null; return n.createPath(workspace); } @@ -310,7 +311,7 @@ public abstract class AbstractBuild

    ,R extends Abs */ public final FilePath getModuleRoot() { FilePath ws = getWorkspace(); - if (ws==null) return null; + if (ws == null) return null; return getParent().getScm().getModuleRoot(ws, this); } @@ -323,7 +324,7 @@ public abstract class AbstractBuild

    ,R extends Abs */ public FilePath[] getModuleRoots() { FilePath ws = getWorkspace(); - if (ws==null) return null; + if (ws == null) return null; return getParent().getScm().getModuleRoots(ws, this); } @@ -348,7 +349,7 @@ public abstract class AbstractBuild

    ,R extends Abs public Set calculateCulprits() { Set c = RunWithSCM.super.calculateCulprits(); - AbstractBuild p = getPreviousCompletedBuild(); + AbstractBuild p = getPreviousCompletedBuild(); if (upstreamCulprits) { // If we have dependencies since the last successful build, add their authors to our list if (p != null && p.getPreviousNotFailedBuild() != null) { @@ -463,7 +464,7 @@ public abstract class AbstractBuild

    ,R extends Abs public Result run(@NonNull BuildListener listener) throws Exception { final Node node = getCurrentNode(); - assert builtOn==null; + assert builtOn == null; builtOn = node.getNodeName(); hudsonVersion = Jenkins.VERSION; this.listener = listener; @@ -515,7 +516,7 @@ public abstract class AbstractBuild

    ,R extends Abs getProject().getScmCheckoutStrategy().preCheckout(AbstractBuild.this, launcher, this.listener); getProject().getScmCheckoutStrategy().checkout(this); - if (!preBuild(listener,project.getProperties())) + if (!preBuild(listener, project.getProperties())) return Result.FAILURE; result = doRun(listener); @@ -535,8 +536,8 @@ public abstract class AbstractBuild

    ,R extends Abs // this is ugly, but for historical reason, if non-null value is returned // it should become the final result. - if (result==null) result = getResult(); - if (result==null) result = Result.SUCCESS; + if (result == null) result = getResult(); + if (result == null) result = Result.SUCCESS; return result; } @@ -574,7 +575,7 @@ public abstract class AbstractBuild

    ,R extends Abs } } catch (IOException | RuntimeException e) { // exceptions are only logged, to give a chance to all environments to tear down - if(e instanceof IOException) { + if (e instanceof IOException) { // similar to Run#handleFatalBuildProblem(BuildListener, Throwable) Util.displayIOException((IOException) e, listener); } @@ -605,24 +606,24 @@ public abstract class AbstractBuild

    ,R extends Abs if (project instanceof BuildableItemWithBuildWrappers) { BuildableItemWithBuildWrappers biwbw = (BuildableItemWithBuildWrappers) project; for (BuildWrapper bw : biwbw.getBuildWrappersList()) - l = bw.decorateLauncher(AbstractBuild.this,l,listener); + l = bw.decorateLauncher(AbstractBuild.this, l, listener); } - for (RunListener rl: RunListener.all()) { + for (RunListener rl : RunListener.all()) { Environment environment = rl.setUpEnvironment(AbstractBuild.this, l, listener); if (environment != null) { buildEnvironments.add(environment); } } - for (NodeProperty nodeProperty: Jenkins.get().getGlobalNodeProperties()) { + for (NodeProperty nodeProperty : Jenkins.get().getGlobalNodeProperties()) { Environment environment = nodeProperty.setUp(AbstractBuild.this, l, listener); if (environment != null) { buildEnvironments.add(environment); } } - for (NodeProperty nodeProperty: currentNode.getNodeProperties()) { + for (NodeProperty nodeProperty : currentNode.getNodeProperties()) { Environment environment = nodeProperty.setUp(AbstractBuild.this, l, listener); if (environment != null) { buildEnvironments.add(environment); @@ -633,15 +634,15 @@ public abstract class AbstractBuild

    ,R extends Abs } public void defaultCheckout() throws IOException, InterruptedException { - AbstractBuild build = AbstractBuild.this; + AbstractBuild build = AbstractBuild.this; AbstractProject project = build.getProject(); - for (int retryCount=project.getScmCheckoutRetryCount(); ; retryCount--) { + for (int retryCount = project.getScmCheckoutRetryCount(); ; retryCount--) { build.scm = NullChangeLogParser.INSTANCE; try { File changeLogFile = new File(build.getRootDir(), "changelog.xml"); - if (project.checkout(build, launcher,listener, changeLogFile)) { + if (project.checkout(build, launcher, listener, changeLogFile)) { // check out succeeded SCM scm = project.getScm(); for (SCMListener l : SCMListener.all()) { @@ -657,20 +658,20 @@ public abstract class AbstractBuild

    ,R extends Abs for (SCMListener l : SCMListener.all()) try { - l.onChangeLogParsed(build,listener,build.getChangeSet()); + l.onChangeLogParsed(build, listener, build.getChangeSet()); } catch (Exception e) { - throw new IOException("Failed to parse changelog",e); + throw new IOException("Failed to parse changelog", e); } // Get a chance to do something after checkout and changelog is done - scm.postCheckout( build, launcher, build.getWorkspace(), listener ); + scm.postCheckout(build, launcher, build.getWorkspace(), listener); return; } } catch (AbortException e) { listener.error(e.getMessage()); } catch (ClosedByInterruptException | InterruptedIOException e) { - throw (InterruptedException)new InterruptedException().initCause(e); + throw (InterruptedException) new InterruptedException().initCause(e); } catch (IOException e) { // checkout error not yet reported Functions.printStackTrace(e, listener.getLogger()); @@ -716,7 +717,7 @@ public abstract class AbstractBuild

    ,R extends Abs @Override public void cleanUp(BuildListener listener) throws Exception { - if (lease!=null) { + if (lease != null) { lease.release(); lease = null; } @@ -729,12 +730,12 @@ public abstract class AbstractBuild

    ,R extends Abs * Use {@link #performAllBuildSteps(BuildListener, Map, boolean)} */ @Deprecated - protected final void performAllBuildStep(BuildListener listener, Map buildSteps, boolean phase) throws InterruptedException, IOException { - performAllBuildSteps(listener,buildSteps.values(),phase); + protected final void performAllBuildStep(BuildListener listener, Map buildSteps, boolean phase) throws InterruptedException, IOException { + performAllBuildSteps(listener, buildSteps.values(), phase); } - protected final boolean performAllBuildSteps(BuildListener listener, Map buildSteps, boolean phase) throws InterruptedException, IOException { - return performAllBuildSteps(listener,buildSteps.values(),phase); + protected final boolean performAllBuildSteps(BuildListener listener, Map buildSteps, boolean phase) throws InterruptedException, IOException { + return performAllBuildSteps(listener, buildSteps.values(), phase); } /** @@ -743,7 +744,7 @@ public abstract class AbstractBuild

    ,R extends Abs */ @Deprecated protected final void performAllBuildStep(BuildListener listener, Iterable buildSteps, boolean phase) throws InterruptedException, IOException { - performAllBuildSteps(listener,buildSteps,phase); + performAllBuildSteps(listener, buildSteps, phase); } /** @@ -757,9 +758,9 @@ public abstract class AbstractBuild

    ,R extends Abs protected final boolean performAllBuildSteps(BuildListener listener, Iterable buildSteps, boolean phase) throws InterruptedException, IOException { boolean r = true; for (BuildStep bs : buildSteps) { - if ((bs instanceof Publisher && ((Publisher)bs).needsToRunAfterFinalized()) ^ phase) + if ((bs instanceof Publisher && ((Publisher) bs).needsToRunAfterFinalized()) ^ phase) try { - if (!perform(bs,listener)) { + if (!perform(bs, listener)) { LOGGER.log(Level.FINE, "{0} : {1} failed", new Object[] {AbstractBuild.this, bs}); r = false; if (phase) { @@ -851,17 +852,17 @@ public abstract class AbstractBuild

    ,R extends Abs } } - protected final boolean preBuild(BuildListener listener,Map steps) { - return preBuild(listener,steps.values()); + protected final boolean preBuild(BuildListener listener, Map steps) { + return preBuild(listener, steps.values()); } - protected final boolean preBuild(BuildListener listener,Collection steps) { - return preBuild(listener,(Iterable)steps); + protected final boolean preBuild(BuildListener listener, Collection steps) { + return preBuild(listener, (Iterable) steps); } - protected final boolean preBuild(BuildListener listener,Iterable steps) { + protected final boolean preBuild(BuildListener listener, Iterable steps) { for (BuildStep bs : steps) - if (!bs.prebuild(AbstractBuild.this,listener)) { + if (!bs.prebuild(AbstractBuild.this, listener)) { LOGGER.log(Level.FINE, "{0} : {1} failed", new Object[] {AbstractBuild.this, bs}); return false; } @@ -876,6 +877,7 @@ public abstract class AbstractBuild

    ,R extends Abs */ private static class TearDownCheckEnvironment extends Environment { private boolean tornDown = false; + @Override public boolean tearDown(AbstractBuild build, BuildListener listener) throws IOException, InterruptedException { this.tornDown = true; @@ -896,22 +898,22 @@ public abstract class AbstractBuild

    ,R extends Abs @Exported @NonNull public ChangeLogSet getChangeSet() { synchronized (changeSetLock) { - if (scm==null) { + if (scm == null) { scm = NullChangeLogParser.INSTANCE; } } ChangeLogSet cs = null; - if (changeSet!=null) + if (changeSet != null) cs = changeSet.get(); - if (cs==null) + if (cs == null) cs = calcChangeSet(); // defensive check. if the calculation fails (such as through an exception), // set a dummy value so that it'll work the next time. the exception will // be still reported, giving the plugin developer an opportunity to fix it. - if (cs==null) + if (cs == null) cs = ChangeLogSet.createEmpty(this); changeSet = new WeakReference<>(cs); @@ -938,9 +940,9 @@ public abstract class AbstractBuild

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

    ,R extends Abs } } - project.getScm().buildEnvVars(this,env); + project.getScm().buildEnvVars(this, env); - if (buildEnvironments!=null) + if (buildEnvironments != null) for (Environment e : buildEnvironments) e.buildEnvVars(env); for (EnvironmentContributingAction a : getActions(EnvironmentContributingAction.class)) - a.buildEnvVars(this,env); + a.buildEnvVars(this, env); EnvVars.resolve(env); @@ -985,12 +987,12 @@ public abstract class AbstractBuild

    ,R extends Abs */ public EnvironmentList getEnvironments() { Executor e = Executor.currentExecutor(); - if (e!=null && e.getCurrentExecutable()==this) { - if (buildEnvironments==null) buildEnvironments = new ArrayList<>(); + if (e != null && e.getCurrentExecutable() == this) { + if (buildEnvironments == null) buildEnvironments = new ArrayList<>(); return new EnvironmentList(buildEnvironments); } - return new EnvironmentList(buildEnvironments==null ? Collections.emptyList() : Collections.unmodifiableList(new ArrayList<>(buildEnvironments))); + return new EnvironmentList(buildEnvironments == null ? Collections.emptyList() : Collections.unmodifiableList(new ArrayList<>(buildEnvironments))); } public Calendar due() { @@ -1006,7 +1008,7 @@ public abstract class AbstractBuild

    ,R extends Abs } @SuppressWarnings("deprecation") - public List getPersistentActions(){ + public List getPersistentActions() { return super.getActions(); } @@ -1055,26 +1057,26 @@ public abstract class AbstractBuild

    ,R extends Abs * @return * The returned map is mutable so that subtypes can put more values. */ - public Map getBuildVariables() { - Map r = new HashMap<>(); + public Map getBuildVariables() { + Map r = new HashMap<>(); ParametersAction parameters = getAction(ParametersAction.class); - if (parameters!=null) { + if (parameters != null) { // this is a rather round about way of doing this... for (ParameterValue p : parameters) { String v = p.createVariableResolver(this).resolve(p.getName()); - if (v!=null) r.put(p.getName(),v); + if (v != null) r.put(p.getName(), v); } } // allow the BuildWrappers to contribute additional build variables if (project instanceof BuildableItemWithBuildWrappers) { for (BuildWrapper bw : ((BuildableItemWithBuildWrappers) project).getBuildWrappersList()) - bw.makeBuildVariables(this,r); + bw.makeBuildVariables(this, r); } for (BuildVariableContributor bvc : BuildVariableContributor.all()) - bvc.buildVariablesFor(this,r); + bvc.buildVariablesFor(this, r); return r; } @@ -1127,22 +1129,22 @@ public abstract class AbstractBuild

    ,R extends Abs // if any of the downstream project is configured with 'keep dependency component', // we need to keep this log OUTER: - for (AbstractProject p : getParent().getDownstreamProjects()) { + for (AbstractProject p : getParent().getDownstreamProjects()) { if (!p.isKeepDependencies()) continue; - AbstractBuild fb = p.getFirstBuild(); - if (fb==null) continue; // no active record + AbstractBuild fb = p.getFirstBuild(); + if (fb == null) continue; // no active record // is there any active build that depends on us? for (int i : getDownstreamRelationship(p).listNumbersReverse()) { // TODO: this is essentially a "find intersection between two sparse sequences" // and we should be able to do much better. - if (i b = p.getBuildByNumber(i); - if (b!=null) + AbstractBuild b = p.getBuildByNumber(i); + if (b != null) return Messages.AbstractBuild_KeptBecause(p.hasPermission(Item.READ) ? b.toString() : "?"); } } @@ -1162,7 +1164,7 @@ public abstract class AbstractBuild

    ,R extends Abs RangeSet rs = new RangeSet(); FingerprintAction f = getAction(FingerprintAction.class); - if (f==null) return rs; + if (f == null) return rs; // look for fingerprints that point to this build as the source, and merge them all for (Fingerprint e : f.getFingerprints().values()) { @@ -1173,7 +1175,7 @@ public abstract class AbstractBuild

    ,R extends Abs rs.add(e.getRangeSet(that)); } else { BuildPtr o = e.getOriginal(); - if (o!=null && o.is(this)) + if (o != null && o.is(this)) rs.add(e.getRangeSet(that)); } } @@ -1186,14 +1188,14 @@ public abstract class AbstractBuild

    ,R extends Abs * the actual build objects, in ascending order. * @since 1.150 */ - public Iterable> getDownstreamBuilds(final AbstractProject that) { + public Iterable> getDownstreamBuilds(final AbstractProject that) { final Iterable nums = getDownstreamRelationship(that).listNumbers(); return new Iterable>() { @Override public Iterator> iterator() { return Iterators.removeNull( - new AdaptedIterator>(nums) { + new AdaptedIterator>(nums) { @Override protected AbstractBuild adapt(Integer item) { return that.getBuildByNumber(item); @@ -1213,7 +1215,7 @@ public abstract class AbstractBuild

    ,R extends Abs */ public int getUpstreamRelationship(AbstractProject that) { FingerprintAction f = getAction(FingerprintAction.class); - if (f==null) return -1; + if (f == null) return -1; int n = -1; @@ -1228,8 +1230,8 @@ public abstract class AbstractBuild

    ,R extends Abs } } else { BuildPtr o = e.getOriginal(); - if (o!=null && o.belongsTo(that)) - n = Math.max(n,o.getNumber()); + if (o != null && o.belongsTo(that)) + n = Math.max(n, o.getNumber()); } } @@ -1244,9 +1246,9 @@ public abstract class AbstractBuild

    ,R extends Abs * null if no such upstream build was found, or it was found but the * build record is already lost. */ - public AbstractBuild getUpstreamRelationshipBuild(AbstractProject that) { + public AbstractBuild getUpstreamRelationshipBuild(AbstractProject that) { int n = getUpstreamRelationship(that); - if (n==-1) return null; + if (n == -1) return null; return that.getBuildByNumber(n); } @@ -1258,11 +1260,11 @@ public abstract class AbstractBuild

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

    ,R extends Abs * @return empty if there is no {@link FingerprintAction} (even if there is an {@link Cause.UpstreamCause}) * @see #getTransitiveUpstreamBuilds() */ - public Map getUpstreamBuilds() { + public Map getUpstreamBuilds() { return _getUpstreamBuilds(getParent().getUpstreamProjects()); } @@ -1281,16 +1283,16 @@ public abstract class AbstractBuild

    ,R extends Abs * Works like {@link #getUpstreamBuilds()} but also includes all the transitive * dependencies as well. */ - public Map getTransitiveUpstreamBuilds() { + public Map getTransitiveUpstreamBuilds() { return _getUpstreamBuilds(getParent().getTransitiveUpstreamProjects()); } private Map _getUpstreamBuilds(Collection projects) { - Map r = new HashMap<>(); + Map r = new HashMap<>(); for (AbstractProject p : projects) { int n = getUpstreamRelationship(p); - if (n>=0) - r.put(p,n); + if (n >= 0) + r.put(p, n); } return r; } @@ -1299,23 +1301,23 @@ public abstract class AbstractBuild

    ,R extends Abs * Gets the changes in the dependency between the given build and this build. * @return empty if there is no {@link FingerprintAction} */ - public Map getDependencyChanges(AbstractBuild from) { - if (from==null) return Collections.emptyMap(); // make it easy to call this from views + public Map getDependencyChanges(AbstractBuild from) { + if (from == null) return Collections.emptyMap(); // make it easy to call this from views FingerprintAction n = this.getAction(FingerprintAction.class); FingerprintAction o = from.getAction(FingerprintAction.class); - if (n==null || o==null) return Collections.emptyMap(); + if (n == null || o == null) return Collections.emptyMap(); - Map ndep = n.getDependencies(true); - Map odep = o.getDependencies(true); + Map ndep = n.getDependencies(true); + Map odep = o.getDependencies(true); - Map r = new HashMap<>(); + Map r = new HashMap<>(); - for (Map.Entry entry : odep.entrySet()) { + for (Map.Entry entry : odep.entrySet()) { AbstractProject p = entry.getKey(); Integer oldNumber = entry.getValue(); Integer newNumber = ndep.get(p); - if (newNumber!=null && oldNumber.compareTo(newNumber)<0) { - r.put(p,new DependencyChange(p,oldNumber,newNumber)); + if (newNumber != null && oldNumber.compareTo(newNumber) < 0) { + r.put(p, new DependencyChange(p, oldNumber, newNumber)); } } @@ -1345,7 +1347,7 @@ public abstract class AbstractBuild

    ,R extends Abs public final AbstractBuild to; - public DependencyChange(AbstractProject project, int fromId, int toId) { + public DependencyChange(AbstractProject project, int fromId, int toId) { this.project = project; this.fromId = fromId; this.toId = toId; @@ -1362,11 +1364,11 @@ public abstract class AbstractBuild

    ,R extends Abs public List getBuilds() { List r = new ArrayList<>(); - AbstractBuild b = project.getNearestBuild(fromId); - if (b!=null && b.getNumber()==fromId) + AbstractBuild b = project.getNearestBuild(fromId); + if (b != null && b.getNumber() == fromId) b = b.getNextBuild(); // fromId exclusive - while (b!=null && b.getNumber()<=toId) { + while (b != null && b.getNumber() <= toId) { r.add(b); b = b.getNextBuild(); } @@ -1386,7 +1388,7 @@ public abstract class AbstractBuild

    ,R extends Abs @Deprecated @RequirePOST // #doStop() should be preferred, but better to be safe public void doStop(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { - doStop().generateResponse(req,rsp,this); + doStop().generateResponse(req, rsp, this); } /** @@ -1400,9 +1402,9 @@ public abstract class AbstractBuild

    ,R extends Abs @RequirePOST public synchronized HttpResponse doStop() throws IOException, ServletException { Executor e = getExecutor(); - if (e==null) + if (e == null) e = getOneOffExecutor(); - if (e!=null) + if (e != null) return e.doStop(); else // nothing is building diff --git a/core/src/main/java/hudson/model/AbstractCIBase.java b/core/src/main/java/hudson/model/AbstractCIBase.java index 13fb0b563580fef02bea87bbf87386d9f272901e..cb2332cbb0a32208760a1e131e3e6418b10e9d01 100644 --- a/core/src/main/java/hudson/model/AbstractCIBase.java +++ b/core/src/main/java/hudson/model/AbstractCIBase.java @@ -86,6 +86,7 @@ public abstract class AbstractCIBase extends Node implements ItemGroup getDisabledAdministrativeMonitors(){ + public Set getDisabledAdministrativeMonitors() { synchronized (this.disabledAdministrativeMonitors) { return new HashSet<>(disabledAdministrativeMonitors); } @@ -131,15 +132,15 @@ public abstract class AbstractCIBase extends Node implements ItemGroup getComputerMap(); + protected abstract Map getComputerMap(); /* ================================================================================================================= * Computer API uses package protection heavily * ============================================================================================================== */ - private void updateComputer(Node n, Map byNameMap, Set used, boolean automaticAgentLaunch) { + private void updateComputer(Node n, Map byNameMap, Set used, boolean automaticAgentLaunch) { Computer c = byNameMap.get(n.getNodeName()); - if (c!=null) { + if (c != null) { try { c.setNode(n); // reuse used.add(c); @@ -157,12 +158,12 @@ public abstract class AbstractCIBase extends Node implements ItemGroup computers = getComputerMap(); + Map computers = getComputerMap(); // we always need Computer for the built-in node as a fallback in case there's no other Computer. - if(n.getNumExecutors()>0 || n==Jenkins.get()) { + if (n.getNumExecutors() > 0 || n == Jenkins.get()) { try { c = n.createComputer(); - } catch(RuntimeException ex) { // Just in case there is a bogus extension + } catch (RuntimeException ex) { // Just in case there is a bogus extension LOGGER.log(Level.WARNING, "Error retrieving computer for node " + n.getNodeName() + ", continuing", ex); } if (c == null) { @@ -194,7 +195,7 @@ public abstract class AbstractCIBase extends Node implements ItemGroup computers = getComputerMap(); + Map computers = getComputerMap(); for (Map.Entry e : computers.entrySet()) { if (e.getValue() == computer) { computers.remove(e.getKey()); @@ -207,7 +208,7 @@ public abstract class AbstractCIBase extends Node implements ItemGroup computers = getComputerMap(); + Map computers = getComputerMap(); return computers.get(n); } @@ -231,18 +232,18 @@ public abstract class AbstractCIBase extends Node implements ItemGroup computers = getComputerMap(); + final Map computers = getComputerMap(); final Set old = new HashSet<>(computers.size()); Queue.withLock(new Runnable() { @Override public void run() { - Map byName = new HashMap<>(); + Map byName = new HashMap<>(); for (Computer c : computers.values()) { old.add(c); Node node = c.getNode(); if (node == null) continue; // this computer is gone - byName.put(node.getNodeName(),c); + byName.put(node.getNodeName(), c); } Set used = new HashSet<>(old.size()); diff --git a/core/src/main/java/hudson/model/AbstractDescribableImpl.java b/core/src/main/java/hudson/model/AbstractDescribableImpl.java index b1ac6dd8477f2333e4adce210b726ed7e1805385..2e339875b940d649276bfb1d660ddc7f47832c59 100644 --- a/core/src/main/java/hudson/model/AbstractDescribableImpl.java +++ b/core/src/main/java/hudson/model/AbstractDescribableImpl.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import hudson.Extension; diff --git a/core/src/main/java/hudson/model/AbstractItem.java b/core/src/main/java/hudson/model/AbstractItem.java index 47a715a0aa122cf6d9a5c2db62f6c57df6972c33..458718e89aff71aedd6b5d2ac3b32e448eccb1a7 100644 --- a/core/src/main/java/hudson/model/AbstractItem.java +++ b/core/src/main/java/hudson/model/AbstractItem.java @@ -22,6 +22,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import static hudson.model.queue.Executables.getParentOf; @@ -133,7 +134,7 @@ public abstract class AbstractItem extends Actionable implements Item, HttpDelet } @Override - @Exported(visibility=999) + @Exported(visibility = 999) public String getName() { return name; } @@ -162,7 +163,7 @@ public abstract class AbstractItem extends Actionable implements Item, HttpDelet @Override @Exported public String getDisplayName() { - if(null!=displayName) { + if (null != displayName) { return displayName; } // if the displayName is not set, then return the name as we use to do @@ -202,7 +203,7 @@ public abstract class AbstractItem extends Actionable implements Item, HttpDelet /** * This bridge method is to maintain binary compatibility with {@link TopLevelItem#getParent()}. */ - @WithBridgeMethods(value=Jenkins.class,castRequired=true) + @WithBridgeMethods(value = Jenkins.class, castRequired = true) @Override public @NonNull ItemGroup getParent() { if (parent == null) { throw new IllegalStateException("no parent set on " + getClass().getName() + "[" + name + "]"); @@ -281,7 +282,7 @@ public abstract class AbstractItem extends Actionable implements Item, HttpDelet // TODO: Create an Item.RENAME permission to use here, see JENKINS-18649. if (!hasPermission(Item.CONFIGURE)) { if (parent instanceof AccessControlled) { - ((AccessControlled)parent).checkPermission(Item.CREATE); + ((AccessControlled) parent).checkPermission(Item.CREATE); } checkPermission(Item.DELETE); } @@ -318,17 +319,17 @@ public abstract class AbstractItem extends Actionable implements Item, HttpDelet if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Unable to rename the job {0}: name {1} is already in use. " + "User {2} has no {3} permission for existing job with the same name", - new Object[] {this.getFullName(), newName, ctx.getPreviousContext2().getAuthentication().getName(), Item.DISCOVER.name} ); + new Object[] {this.getFullName(), newName, ctx.getPreviousContext2().getAuthentication().getName(), Item.DISCOVER.name}); } // Don't explicitly mention that there is another item with the same name. throw new Failure(Messages.Jenkins_NotAllowedName(newName)); } } - } catch(AccessDeniedException ex) { + } catch (AccessDeniedException ex) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Unable to rename the job {0}: name {1} is already in use. " + "User {2} has {3} permission, but no {4} for existing job with the same name", - new Object[] {this.getFullName(), newName, User.current(), Item.DISCOVER.name, Item.READ.name} ); + new Object[] {this.getFullName(), newName, User.current(), Item.DISCOVER.name, Item.READ.name}); } throw new Failure(Messages.AbstractItem_NewNameInUse(newName)); } @@ -386,7 +387,7 @@ public abstract class AbstractItem extends Actionable implements Item, HttpDelet boolean success = false; - try {// rename data files + try { // rename data files boolean interrupted = false; boolean renamed = false; @@ -477,16 +478,16 @@ public abstract class AbstractItem extends Actionable implements Item, HttpDelet @Exported public final String getFullName() { String n = getParent().getFullName(); - if(n.length()==0) return getName(); - else return n+'/'+getName(); + if (n.length() == 0) return getName(); + else return n + '/' + getName(); } @Override @Exported public final String getFullDisplayName() { String n = getParent().getFullDisplayName(); - if(n.length()==0) return getDisplayName(); - else return n+" » "+getDisplayName(); + if (n.length() == 0) return getDisplayName(); + else return n + " » " + getDisplayName(); } /** @@ -543,11 +544,11 @@ public abstract class AbstractItem extends Actionable implements Item, HttpDelet String shortUrl = getShortUrl(); String uri = req == null ? null : req.getRequestURI(); if (req != null) { - String seed = Functions.getNearestAncestorUrl(req,this); + String seed = Functions.getNearestAncestorUrl(req, this); LOGGER.log(Level.FINER, "seed={0} for {1} from {2}", new Object[] {seed, this, uri}); - if(seed!=null) { + if (seed != null) { // trim off the context path portion and leading '/', but add trailing '/' - return seed.substring(req.getContextPath().length()+1)+'/'; + return seed.substring(req.getContextPath().length() + 1) + '/'; } List ancestors = req.getAncestors(); if (!ancestors.isEmpty()) { @@ -590,7 +591,7 @@ public abstract class AbstractItem extends Actionable implements Item, HttpDelet } @Override - @Exported(visibility=999,name="url") + @Exported(visibility = 999, name = "url") public final String getAbsoluteUrl() { return Item.super.getAbsoluteUrl(); } @@ -615,7 +616,7 @@ public abstract class AbstractItem extends Actionable implements Item, HttpDelet */ @Override public synchronized void save() throws IOException { - if(BulkChange.contains(this)) return; + if (BulkChange.contains(this)) return; getConfigFile().write(this); SaveableListener.fireOnChange(this, getConfigFile()); } @@ -627,11 +628,14 @@ public abstract class AbstractItem extends Actionable implements Item, HttpDelet protected Object writeReplace() { return XmlFile.replaceIfNotAtTopLevel(this, () -> new Replacer(this)); } + private static class Replacer { private final String fullName; + Replacer(AbstractItem i) { fullName = i.getFullName(); } + private Object readResolve() { Jenkins j = Jenkins.getInstanceOrNull(); if (j == null) { @@ -646,7 +650,7 @@ public abstract class AbstractItem extends Actionable implements Item, HttpDelet * Accepts the new description. */ @RequirePOST - public synchronized void doSubmitDescription( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { + public synchronized void doSubmitDescription(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { checkPermission(CONFIGURE); setDescription(req.getParameter("description")); @@ -660,7 +664,7 @@ public abstract class AbstractItem extends Actionable implements Item, HttpDelet * which should now be unused by core but is left in case plugins are still using it. */ @RequirePOST - public void doDoDelete( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, InterruptedException { + public void doDoDelete(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, InterruptedException { delete(); if (req == null || rsp == null) { // CLI return; @@ -682,7 +686,7 @@ public abstract class AbstractItem extends Actionable implements Item, HttpDelet } @Override - public void delete( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { + public void delete(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { try { delete(); rsp.setStatus(204); @@ -825,7 +829,7 @@ public abstract class AbstractItem extends Actionable implements Item, HttpDelet } if (req.getMethod().equals("POST")) { // submission - updateByXml((Source)new StreamSource(req.getReader())); + updateByXml((Source) new StreamSource(req.getReader())); return; } @@ -839,6 +843,7 @@ public abstract class AbstractItem extends Actionable implements Item, HttpDelet * The user must have at least {@link #EXTENDED_READ}. * If he lacks {@link #CONFIGURE}, then any {@link Secret}s detected will be masked out. */ + @Restricted(NoExternalUse.class) public void writeConfigDotXml(OutputStream os) throws IOException { checkPermission(EXTENDED_READ); @@ -866,7 +871,7 @@ public abstract class AbstractItem extends Actionable implements Item, HttpDelet */ @Deprecated public void updateByXml(StreamSource source) throws IOException { - updateByXml((Source)source); + updateByXml((Source) source); } /** @@ -890,13 +895,13 @@ public abstract class AbstractItem extends Actionable implements Item, HttpDelet // try to reflect the changes by reloading Object o = new XmlFile(Items.XSTREAM, out.getTemporaryFile()).unmarshalNullingOut(this); - if (o!=this) { + if (o != this) { // ensure that we've got the same job type. extending this code to support updating // to different job type requires destroying & creating a new job type - throw new IOException("Expecting "+this.getClass()+" but got "+o.getClass()+" instead"); + throw new IOException("Expecting " + this.getClass() + " but got " + o.getClass() + " instead"); } - Items.whileUpdatingByXml(new NotReallyRoleSensitiveCallable() { + Items.whileUpdatingByXml(new NotReallyRoleSensitiveCallable() { @Override public Void call() throws IOException { onLoad(getParent(), getRootDir().getName()); return null; @@ -977,10 +982,10 @@ public abstract class AbstractItem extends Actionable implements Item, HttpDelet */ @CLIResolver public static AbstractItem resolveForCLI( - @Argument(required=true,metaVar="NAME",usage="Item name") String name) throws CmdLineException { + @Argument(required = true, metaVar = "NAME", usage = "Item name") String name) throws CmdLineException { // TODO can this (and its pseudo-override in AbstractProject) share code with GenericItemOptionHandler, used for explicit CLICommand’s rather than CLIMethod’s? AbstractItem item = Jenkins.get().getItemByFullName(name, AbstractItem.class); - if (item==null) { + if (item == null) { AbstractItem project = Items.findNearest(AbstractItem.class, name, Jenkins.get()); throw new CmdLineException(null, project == null ? Messages.AbstractItem_NoSuchJobExistsWithoutSuggestion(name) : Messages.AbstractItem_NoSuchJobExists(name, project.getFullName())); diff --git a/core/src/main/java/hudson/model/AbstractModelObject.java b/core/src/main/java/hudson/model/AbstractModelObject.java index 0d1d6982db800ae4bbb0d316acea3c5faaff693f..f6c7104f8e42843d9178601be34dce3cb9a14134 100644 --- a/core/src/main/java/hudson/model/AbstractModelObject.java +++ b/core/src/main/java/hudson/model/AbstractModelObject.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import hudson.search.Search; @@ -37,7 +38,7 @@ import org.kohsuke.stapler.interceptor.RequirePOST; /** * {@link ModelObject} with some convenience methods. - * + * * @author Kohsuke Kawaguchi */ public abstract class AbstractModelObject implements SearchableModelObject { @@ -46,16 +47,16 @@ public abstract class AbstractModelObject implements SearchableModelObject { */ protected final void sendError(Exception e, StaplerRequest req, StaplerResponse rsp) throws ServletException, IOException { req.setAttribute("exception", e); - sendError(e.getMessage(),req,rsp); + sendError(e.getMessage(), req, rsp); } protected final void sendError(Exception e) throws ServletException, IOException { - sendError(e,Stapler.getCurrentRequest(),Stapler.getCurrentResponse()); + sendError(e, Stapler.getCurrentRequest(), Stapler.getCurrentResponse()); } protected final void sendError(String message, StaplerRequest req, StaplerResponse rsp) throws ServletException, IOException { - req.setAttribute("message",message); - rsp.forward(this,"error",req); + req.setAttribute("message", message); + rsp.forward(this, "error", req); } /** @@ -63,29 +64,29 @@ public abstract class AbstractModelObject implements SearchableModelObject { * If true, the message is put in a PRE tag. */ protected final void sendError(String message, StaplerRequest req, StaplerResponse rsp, boolean pre) throws ServletException, IOException { - req.setAttribute("message",message); - if(pre) - req.setAttribute("pre",true); - rsp.forward(this,"error",req); + req.setAttribute("message", message); + if (pre) + req.setAttribute("pre", true); + rsp.forward(this, "error", req); } protected final void sendError(String message) throws ServletException, IOException { - sendError(message,Stapler.getCurrentRequest(),Stapler.getCurrentResponse()); + sendError(message, Stapler.getCurrentRequest(), Stapler.getCurrentResponse()); } /** * Convenience method to verify that the current request is a POST request. - * - * @deprecated + * + * @deprecated * Use {@link RequirePOST} on your method. */ @Deprecated protected final void requirePOST() throws ServletException { StaplerRequest req = Stapler.getCurrentRequest(); - if (req==null) return; // invoked outside the context of servlet + if (req == null) return; // invoked outside the context of servlet String method = req.getMethod(); - if(!method.equalsIgnoreCase("POST")) - throw new ServletException("Must be POST, Can't be "+method); + if (!method.equalsIgnoreCase("POST")) + throw new ServletException("Must be POST, Can't be " + method); } /** @@ -104,7 +105,7 @@ public abstract class AbstractModelObject implements SearchableModelObject { public Search getSearch() { for (SearchFactory sf : SearchFactory.all()) { Search s = sf.createFor(this); - if (s!=null) + if (s != null) return s; } return new Search(); diff --git a/core/src/main/java/hudson/model/AbstractProject.java b/core/src/main/java/hudson/model/AbstractProject.java index cd669b8bb4942bab69529d51ebc7f9741f8a31ff..9dfaf72e21d759ed299c67a8b038a00948c683e7 100644 --- a/core/src/main/java/hudson/model/AbstractProject.java +++ b/core/src/main/java/hudson/model/AbstractProject.java @@ -25,6 +25,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import static hudson.scm.PollingResult.BUILD_NOW; @@ -135,7 +136,7 @@ import org.kohsuke.stapler.verb.POST; * @see AbstractBuild */ @SuppressWarnings("rawtypes") -public abstract class AbstractProject

    ,R extends AbstractBuild> extends Job implements BuildableItem, LazyBuildMixIn.LazyLoadingJob, ParameterizedJobMixIn.ParameterizedJob { +public abstract class AbstractProject

    , R extends AbstractBuild> extends Job implements BuildableItem, LazyBuildMixIn.LazyLoadingJob, ParameterizedJobMixIn.ParameterizedJob { /** * {@link SCM} associated with the project. @@ -154,7 +155,7 @@ public abstract class AbstractProject

    ,R extends A */ private transient volatile SCMRevisionState pollingBaseline = null; - private transient LazyBuildMixIn buildMixIn; + private transient LazyBuildMixIn buildMixIn; /** * All the builds keyed by their build number. @@ -230,9 +231,9 @@ public abstract class AbstractProject

    ,R extends A /** * List of all {@link Trigger}s for this project. */ - protected volatile DescribableList,TriggerDescriptor> triggers = new DescribableList<>(this); - private static final AtomicReferenceFieldUpdater triggersUpdater - = AtomicReferenceFieldUpdater.newUpdater(AbstractProject.class,DescribableList.class,"triggers"); + protected volatile DescribableList, TriggerDescriptor> triggers = new DescribableList<>(this); + private static final AtomicReferenceFieldUpdater triggersUpdater + = AtomicReferenceFieldUpdater.newUpdater(AbstractProject.class, DescribableList.class, "triggers"); /** * {@link Action}s contributed from subsidiary objects associated with @@ -254,7 +255,7 @@ public abstract class AbstractProject

    ,R extends A private String customWorkspace; protected AbstractProject(ItemGroup parent, String name) { - super(parent,name); + super(parent, name); buildMixIn = createBuildMixIn(); builds = buildMixIn.getRunMap(); @@ -266,19 +267,20 @@ public abstract class AbstractProject

    ,R extends A } } - private LazyBuildMixIn createBuildMixIn() { - return new LazyBuildMixIn() { + private LazyBuildMixIn createBuildMixIn() { + return new LazyBuildMixIn() { @SuppressWarnings("unchecked") // untypable @Override protected P asJob() { return (P) AbstractProject.this; } + @Override protected Class getBuildClass() { return AbstractProject.this.getBuildClass(); } }; } - @Override public LazyBuildMixIn getLazyBuildMixIn() { + @Override public LazyBuildMixIn getLazyBuildMixIn() { return buildMixIn; } @@ -313,18 +315,18 @@ public abstract class AbstractProject

    ,R extends A LOGGER.log(Level.WARNING, "could not start trigger while loading project '" + getFullName() + "'", e); } } - if(scm==null) + if (scm == null) scm = new NullSCM(); // perhaps it was pointing to a plugin that no longer exists. - if(transientActions==null) + if (transientActions == null) transientActions = new Vector<>(); // happens when loaded from disk updateTransientActions(); } @WithBridgeMethods(List.class) - protected DescribableList,TriggerDescriptor> triggers() { + protected DescribableList, TriggerDescriptor> triggers() { if (triggers == null) { - triggersUpdater.compareAndSet(this,null,new DescribableList,TriggerDescriptor>(this)); + triggersUpdater.compareAndSet(this, null, new DescribableList, TriggerDescriptor>(this)); } return triggers; } @@ -351,7 +353,7 @@ public abstract class AbstractProject

    ,R extends A // prevent a new build while a delete operation is in progress makeDisabled(true); FilePath ws = getWorkspace(); - if(ws!=null) { + if (ws != null) { Node on = getLastBuiltOn(); getScm().processWorkspaceBeforeDeletion(this, ws, on); } @@ -379,10 +381,10 @@ public abstract class AbstractProject

    ,R extends A */ @Override public @CheckForNull Label getAssignedLabel() { - if(canRoam) + if (canRoam) return null; - if(assignedNode==null) + if (assignedNode == null) return Jenkins.get().getSelfLabel(); return Jenkins.get().getLabel(assignedNode); } @@ -405,9 +407,9 @@ public abstract class AbstractProject

    ,R extends A /** * Gets the textual representation of the assigned label as it was entered by the user. */ - @Exported(name="labelExpression") + @Exported(name = "labelExpression") public String getAssignedLabelString() { - if (canRoam || assignedNode==null) return null; + if (canRoam || assignedNode == null) return null; try { Label.parseExpression(assignedNode); return assignedNode; @@ -421,12 +423,12 @@ public abstract class AbstractProject

    ,R extends A * Sets the assigned label. */ public void setAssignedLabel(Label l) throws IOException { - if(l==null) { + if (l == null) { canRoam = true; assignedNode = null; } else { canRoam = false; - if(l== Jenkins.get().getSelfLabel()) assignedNode = null; + if (l == Jenkins.get().getSelfLabel()) assignedNode = null; else assignedNode = l.getExpression(); } save(); @@ -445,7 +447,7 @@ public abstract class AbstractProject

    ,R extends A */ @Override public String getPronoun() { - return AlternativeUiTextProvider.get(PRONOUN, this,Messages.AbstractProject_Pronoun()); + return AlternativeUiTextProvider.get(PRONOUN, this, Messages.AbstractProject_Pronoun()); } /** @@ -470,7 +472,7 @@ public abstract class AbstractProject

    ,R extends A * @return never null. * @see AbstractBuild#getRootBuild() */ - public AbstractProject getRootProject() { + public AbstractProject getRootProject() { if (this instanceof TopLevelItem) { return this; } else { @@ -512,11 +514,11 @@ public abstract class AbstractProject

    ,R extends A @CheckForNull private AbstractBuild getBuildForDeprecatedMethods() { Executor e = Executor.currentExecutor(); - if(e!=null) { + if (e != null) { Executable exe = e.getCurrentExecutable(); if (exe instanceof AbstractBuild) { AbstractBuild b = (AbstractBuild) exe; - if(b.getProject()==this) + if (b.getProject() == this) return b; } } @@ -537,7 +539,7 @@ public abstract class AbstractProject

    ,R extends A */ public final @CheckForNull FilePath getSomeWorkspace() { R b = getSomeBuildWithWorkspace(); - if (b!=null) return b.getWorkspace(); + if (b != null) return b.getWorkspace(); for (WorkspaceBrowser browser : ExtensionList.lookup(WorkspaceBrowser.class)) { FilePath f = browser.getWorkspace(this); if (f != null) return f; @@ -553,7 +555,7 @@ public abstract class AbstractProject

    ,R extends A public final R getSomeBuildWithWorkspace() { for (R b = getLastBuild(); b != null; b = b.getPreviousBuild()) { FilePath ws = b.getWorkspace(); - if (ws!=null) return b; + if (ws != null) return b; } return null; } @@ -561,7 +563,7 @@ public abstract class AbstractProject

    ,R extends A private R getSomeBuildWithExistingWorkspace() throws IOException, InterruptedException { for (R b = getLastBuild(); b != null; b = b.getPreviousBuild()) { FilePath ws = b.getWorkspace(); - if (ws!=null && ws.exists()) return b; + if (ws != null && ws.exists()) return b; } return null; } @@ -599,7 +601,7 @@ public abstract class AbstractProject

    ,R extends A @Override public int getQuietPeriod() { - return quietPeriod!=null ? quietPeriod : Jenkins.get().getQuietPeriod(); + return quietPeriod != null ? quietPeriod : Jenkins.get().getQuietPeriod(); } public SCMCheckoutStrategy getScmCheckoutStrategy() { @@ -613,12 +615,12 @@ public abstract class AbstractProject

    ,R extends A public int getScmCheckoutRetryCount() { - return scmCheckoutRetryCount !=null ? scmCheckoutRetryCount : Jenkins.get().getScmCheckoutRetryCount(); + return scmCheckoutRetryCount != null ? scmCheckoutRetryCount : Jenkins.get().getScmCheckoutRetryCount(); } // ugly name because of EL public boolean getHasCustomQuietPeriod() { - return quietPeriod!=null; + return quietPeriod != null; } /** @@ -629,7 +631,7 @@ public abstract class AbstractProject

    ,R extends A save(); } - public boolean hasCustomScmCheckoutRetryCount(){ + public boolean hasCustomScmCheckoutRetryCount() { return scmCheckoutRetryCount != null; } @@ -679,9 +681,9 @@ public abstract class AbstractProject

    ,R extends A /** * Validates the retry count Regex */ - public FormValidation doCheckRetryCount(@QueryParameter String value)throws IOException,ServletException{ + public FormValidation doCheckRetryCount(@QueryParameter String value)throws IOException, ServletException { // retry count is optional so this is ok - if(value == null || value.trim().equals("")) + if (value == null || value.trim().equals("")) return FormValidation.ok(); if (!value.matches("[0-9]*")) { return FormValidation.error("Invalid retry count"); @@ -712,7 +714,7 @@ public abstract class AbstractProject

    ,R extends A @Override public BallColor getIconColor() { - if(isDisabled()) + if (isDisabled()) return isBuilding() ? BallColor.DISABLED_ANIME : BallColor.DISABLED; else return super.getIconColor(); @@ -733,7 +735,7 @@ public abstract class AbstractProject

    ,R extends A Vector ta = new Vector<>(); for (JobProperty p : Util.fixNull(properties)) - ta.addAll(p.getJobActions((P)this)); + ta.addAll(p.getJobActions((P) this)); for (TransientProjectActionFactory tpaf : TransientProjectActionFactory.all()) { try { @@ -752,7 +754,7 @@ public abstract class AbstractProject

    ,R extends A * This method couldn't be called {@code getPublishers()} because existing methods * in sub-classes return different inconsistent types. */ - public abstract DescribableList> getPublishersList(); + public abstract DescribableList> getPublishersList(); @Override public void addProperty(JobProperty jobProp) throws IOException { @@ -766,8 +768,8 @@ public abstract class AbstractProject

    ,R extends A @Override @POST - public void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException { - super.doConfigSubmit(req,rsp); + public void doConfigSubmit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException { + super.doConfigSubmit(req, rsp); updateTransientActions(); @@ -791,7 +793,7 @@ public abstract class AbstractProject

    ,R extends A * @return whether the build was actually scheduled */ public boolean scheduleBuild(int quietPeriod, Cause c, Action... actions) { - return scheduleBuild2(quietPeriod,c,actions)!=null; + return scheduleBuild2(quietPeriod, c, actions) != null; } /** @@ -803,7 +805,7 @@ public abstract class AbstractProject

    ,R extends A */ @WithBridgeMethods(Future.class) public QueueTaskFuture scheduleBuild2(int quietPeriod, Cause c, Action... actions) { - return scheduleBuild2(quietPeriod,c,Arrays.asList(actions)); + return scheduleBuild2(quietPeriod, c, Arrays.asList(actions)); } /** @@ -856,9 +858,9 @@ public abstract class AbstractProject

    ,R extends A * @see SCMTriggerItem#schedulePolling */ public boolean schedulePolling() { - if(isDisabled()) return false; + if (isDisabled()) return false; SCMTrigger scmt = getTrigger(SCMTrigger.class); - if(scmt==null) return false; + if (scmt == null) return false; scmt.run(); return true; } @@ -1006,7 +1008,7 @@ public abstract class AbstractProject

    ,R extends A public Node getLastBuiltOn() { // where was it built on? AbstractBuild b = getLastBuild(); - if(b==null) + if (b == null) return null; else return b.getBuiltOn(); @@ -1031,9 +1033,9 @@ public abstract class AbstractProject

    ,R extends A * Because the downstream build is in progress, and we are configured to wait for that. */ public static class BecauseOfDownstreamBuildInProgress extends CauseOfBlockage { - public final AbstractProject up; + public final AbstractProject up; - public BecauseOfDownstreamBuildInProgress(AbstractProject up) { + public BecauseOfDownstreamBuildInProgress(AbstractProject up) { this.up = up; } @@ -1047,9 +1049,9 @@ public abstract class AbstractProject

    ,R extends A * Because the upstream build is in progress, and we are configured to wait for that. */ public static class BecauseOfUpstreamBuildInProgress extends CauseOfBlockage { - public final AbstractProject up; + public final AbstractProject up; - public BecauseOfUpstreamBuildInProgress(AbstractProject up) { + public BecauseOfUpstreamBuildInProgress(AbstractProject up) { this.up = up; } @@ -1082,13 +1084,13 @@ public abstract class AbstractProject

    ,R extends A } } if (blockBuildWhenDownstreamBuilding()) { - AbstractProject bup = getBuildingDownstream(); - if (bup!=null) + AbstractProject bup = getBuildingDownstream(); + if (bup != null) return new BecauseOfDownstreamBuildInProgress(bup); } if (blockBuildWhenUpstreamBuilding()) { - AbstractProject bup = getBuildingUpstream(); - if (bup!=null) + AbstractProject bup = getBuildingUpstream(); + if (bup != null) return new BecauseOfUpstreamBuildInProgress(bup); } return null; @@ -1105,7 +1107,7 @@ public abstract class AbstractProject

    ,R extends A Set unblockedTasks = Jenkins.get().getQueue().getUnblockedTasks(); for (AbstractProject tup : getTransitiveDownstreamProjects()) { - if (tup!=this && (tup.isBuilding() || unblockedTasks.contains(tup))) + if (tup != this && (tup.isBuilding() || unblockedTasks.contains(tup))) return tup; } return null; @@ -1122,7 +1124,7 @@ public abstract class AbstractProject

    ,R extends A Set unblockedTasks = Jenkins.get().getQueue().getUnblockedTasks(); for (AbstractProject tup : getTransitiveUpstreamProjects()) { - if (tup!=this && (tup.isBuilding() || unblockedTasks.contains(tup))) + if (tup != this && (tup.isBuilding() || unblockedTasks.contains(tup))) return tup; } return null; @@ -1141,7 +1143,7 @@ public abstract class AbstractProject

    ,R extends A @Override // same as ParameterizedJob version except calls possibly overridden newBuild public @CheckForNull R createExecutable() throws IOException { - if(isDisabled()) return null; + if (isDisabled()) return null; return newBuild(); } @@ -1170,7 +1172,7 @@ public abstract class AbstractProject

    ,R extends A */ @Deprecated public Resource getWorkspaceResource() { - return new Resource(getFullDisplayName()+" workspace"); + return new Resource(getFullDisplayName() + " workspace"); } /** @@ -1199,11 +1201,11 @@ public abstract class AbstractProject

    ,R extends A public boolean checkout(AbstractBuild build, Launcher launcher, BuildListener listener, File changelogFile) throws IOException, InterruptedException { SCM scm = getScm(); - if(scm==null) + if (scm == null) return true; // no SCM FilePath workspace = build.getWorkspace(); - if(workspace!=null){ + if (workspace != null) { workspace.mkdirs(); } else { throw new AbortException("Cannot checkout SCM, workspace is not defined"); @@ -1224,13 +1226,13 @@ public abstract class AbstractProject

    ,R extends A */ private void calcPollingBaseline(AbstractBuild build, Launcher launcher, TaskListener listener) throws IOException, InterruptedException { SCMRevisionState baseline = build.getAction(SCMRevisionState.class); - if (baseline==null) { + if (baseline == null) { try { baseline = getScm().calcRevisionsFromBuild(build, launcher, listener); } catch (AbstractMethodError e) { baseline = SCMRevisionState.NONE; // pre-1.345 SCM implementations, which doesn't use the baseline in polling } - if (baseline!=null) + if (baseline != null) build.addAction(baseline); } pollingBaseline = baseline; @@ -1243,7 +1245,7 @@ public abstract class AbstractProject

    ,R extends A * Use {@link #poll(TaskListener)} instead. */ @Deprecated - public boolean pollSCMChanges( TaskListener listener ) { + public boolean pollSCMChanges(TaskListener listener) { return poll(listener).hasChanges(); } @@ -1256,9 +1258,9 @@ public abstract class AbstractProject

    ,R extends A * * @since 1.345 */ - public PollingResult poll( TaskListener listener ) { + public PollingResult poll(TaskListener listener) { SCM scm = getScm(); - if (scm==null) { + if (scm == null) { listener.getLogger().println(Messages.AbstractProject_NoSCM()); return NO_CHANGES; } @@ -1273,20 +1275,20 @@ public abstract class AbstractProject

    ,R extends A } R lb = getLastBuild(); - if (lb==null) { + if (lb == null) { listener.getLogger().println(Messages.AbstractProject_NoBuilds()); return isInQueue() ? NO_CHANGES : BUILD_NOW; } - if (pollingBaseline==null) { + if (pollingBaseline == null) { R success = getLastSuccessfulBuild(); // if we have a persisted baseline, we'll find it by this - for (R r=lb; r!=null; r=r.getPreviousBuild()) { + for (R r = lb; r != null; r = r.getPreviousBuild()) { SCMRevisionState s = r.getAction(SCMRevisionState.class); - if (s!=null) { + if (s != null) { pollingBaseline = s; break; } - if (r==success) break; // searched far enough + if (r == success) break; // searched far enough } // NOTE-NO-BASELINE: // if we don't have baseline yet, it means the data is built by old Hudson that doesn't set the baseline @@ -1296,24 +1298,24 @@ public abstract class AbstractProject

    ,R extends A try { SCMPollListener.fireBeforePolling(this, listener); PollingResult r = _poll(listener, scm); - SCMPollListener.firePollingSuccess(this,listener, r); + SCMPollListener.firePollingSuccess(this, listener, r); return r; } catch (AbortException e) { listener.getLogger().println(e.getMessage()); listener.fatalError(Messages.AbstractProject_Aborted()); - LOGGER.log(Level.FINE, "Polling "+this+" aborted",e); - SCMPollListener.firePollingFailed(this, listener,e); + LOGGER.log(Level.FINE, "Polling " + this + " aborted", e); + SCMPollListener.firePollingFailed(this, listener, e); return NO_CHANGES; } catch (IOException e) { Functions.printStackTrace(e, listener.fatalError(e.getMessage())); - SCMPollListener.firePollingFailed(this, listener,e); + SCMPollListener.firePollingFailed(this, listener, e); return NO_CHANGES; } catch (InterruptedException e) { Functions.printStackTrace(e, listener.fatalError(Messages.AbstractProject_PollingABorted())); - SCMPollListener.firePollingFailed(this, listener,e); + SCMPollListener.firePollingFailed(this, listener, e); return NO_CHANGES; } catch (RuntimeException | Error e) { - SCMPollListener.firePollingFailed(this, listener,e); + SCMPollListener.firePollingFailed(this, listener, e); throw e; } } @@ -1326,10 +1328,10 @@ public abstract class AbstractProject

    ,R extends A R b = getSomeBuildWithExistingWorkspace(); if (b == null) b = getLastBuild(); // lock the workspace for the given build - FilePath ws=b.getWorkspace(); + FilePath ws = b.getWorkspace(); - WorkspaceOfflineReason workspaceOfflineReason = workspaceOffline( b ); - if ( workspaceOfflineReason != null ) { + WorkspaceOfflineReason workspaceOfflineReason = workspaceOffline(b); + if (workspaceOfflineReason != null) { // workspace offline for (WorkspaceBrowser browser : ExtensionList.lookup(WorkspaceBrowser.class)) { ws = browser.getWorkspace(this); @@ -1343,18 +1345,18 @@ public abstract class AbstractProject

    ,R extends A // However, first there are some conditions in which we do not want to do so. // give time for agents to come online if we are right after reconnection (JENKINS-8408) long running = Jenkins.get().getInjector().getInstance(Uptime.class).getUptime(); - long remaining = TimeUnit.MINUTES.toMillis(10)-running; - if (remaining>0 && /* this logic breaks tests of polling */!Functions.getIsUnitTest()) { - listener.getLogger().print(Messages.AbstractProject_AwaitingWorkspaceToComeOnline(remaining/1000)); - listener.getLogger().println( " (" + workspaceOfflineReason.name() + ")"); + long remaining = TimeUnit.MINUTES.toMillis(10) - running; + if (remaining > 0 && /* this logic breaks tests of polling */!Functions.getIsUnitTest()) { + listener.getLogger().print(Messages.AbstractProject_AwaitingWorkspaceToComeOnline(remaining / 1000)); + listener.getLogger().println(" (" + workspaceOfflineReason.name() + ")"); return NO_CHANGES; } // Do not trigger build, if no suitable agent is online if (workspaceOfflineReason.equals(WorkspaceOfflineReason.all_suitable_nodes_are_offline)) { // No suitable executor is online - listener.getLogger().print(Messages.AbstractProject_AwaitingWorkspaceToComeOnline(running/1000)); - listener.getLogger().println( " (" + workspaceOfflineReason.name() + ")"); + listener.getLogger().print(Messages.AbstractProject_AwaitingWorkspaceToComeOnline(running / 1000)); + listener.getLogger().println(" (" + workspaceOfflineReason.name() + ")"); return NO_CHANGES; } @@ -1363,11 +1365,11 @@ public abstract class AbstractProject

    ,R extends A // if the build is fixed on a node, then attempting a build will do us // no good. We should just wait for the agent to come back. listener.getLogger().print(Messages.AbstractProject_NoWorkspace()); - listener.getLogger().println( " (" + workspaceOfflineReason.name() + ")"); + listener.getLogger().println(" (" + workspaceOfflineReason.name() + ")"); return NO_CHANGES; } - listener.getLogger().println( ws==null + listener.getLogger().println(ws == null ? Messages.AbstractProject_WorkspaceOffline() : Messages.AbstractProject_NoWorkspace()); if (isInQueue()) { @@ -1377,7 +1379,7 @@ public abstract class AbstractProject

    ,R extends A // build now, or nothing will ever be built listener.getLogger().print(Messages.AbstractProject_NewBuildForWorkspace()); - listener.getLogger().println( " (" + workspaceOfflineReason.name() + ")"); + listener.getLogger().println(" (" + workspaceOfflineReason.name() + ")"); return BUILD_NOW; } else { WorkspaceList l = b.getBuiltOn().toComputer().getWorkspaceList(); @@ -1387,8 +1389,8 @@ public abstract class AbstractProject

    ,R extends A } else { // polling without workspace LOGGER.fine("Polling SCM changes of " + getName()); - if (pollingBaseline==null) // see NOTE-NO-BASELINE above - calcPollingBaseline(getLastBuild(),null,listener); + if (pollingBaseline == null) // see NOTE-NO-BASELINE above + calcPollingBaseline(getLastBuild(), null, listener); PollingResult r = scm.poll(this, null, null, listener, pollingBaseline); pollingBaseline = r.remote; return r; @@ -1403,14 +1405,14 @@ public abstract class AbstractProject

    ,R extends A // so better throughput is achieved over time (modulo the initial cost of creating that many workspaces) // by having multiple workspaces Node node = lb.getBuiltOn(); - Launcher launcher = ws.createLauncher(listener).decorateByEnv(getEnvironment(node,listener)); + Launcher launcher = ws.createLauncher(listener).decorateByEnv(getEnvironment(node, listener)); WorkspaceList.Lease lease = l.acquire(ws, !concurrentBuild); try { String nodeName = node != null ? node.getSelfLabel().getName() : "[node_unavailable]"; listener.getLogger().println("Polling SCM changes on " + nodeName); LOGGER.fine("Polling SCM changes of " + getName()); - if (pollingBaseline==null) // see NOTE-NO-BASELINE above - calcPollingBaseline(lb,launcher,listener); + if (pollingBaseline == null) // see NOTE-NO-BASELINE above + calcPollingBaseline(lb, launcher, listener); PollingResult r = scm.poll(this, launcher, ws, listener, pollingBaseline); pollingBaseline = r.remote; return r; @@ -1436,13 +1438,13 @@ public abstract class AbstractProject

    ,R extends A if (label != null) { //Invalid label. Put in queue to make administrator fix - if(label.getNodes().isEmpty()) { + if (label.getNodes().isEmpty()) { return false; } //Returns true, if all suitable nodes are offline return label.isOffline(); } else { - if(canRoam) { + if (canRoam) { for (Node n : Jenkins.get().getNodes()) { Computer c = n.toComputer(); if (c != null && c.isOnline() && c.isAcceptingTasks() && n.getMode() == Mode.NORMAL) { @@ -1466,7 +1468,7 @@ public abstract class AbstractProject

    ,R extends A return applicableClouds.isEmpty() ? WorkspaceOfflineReason.all_suitable_nodes_are_offline : WorkspaceOfflineReason.use_ondemand_slave; } - if (ws==null || !ws.exists()) { + if (ws == null || !ws.exists()) { return WorkspaceOfflineReason.nonexisting_workspace; } @@ -1488,8 +1490,8 @@ public abstract class AbstractProject

    ,R extends A * @since 1.191 */ public boolean hasParticipant(User user) { - for( R build = getLastBuild(); build!=null; build=build.getPreviousBuild()) - if(build.hasParticipant(user)) + for (R build = getLastBuild(); build != null; build = build.getPreviousBuild()) + if (build.hasParticipant(user)) return true; return false; } @@ -1508,15 +1510,15 @@ public abstract class AbstractProject

    ,R extends A * Adds a new {@link Trigger} to this {@link Project} if not active yet. */ public void addTrigger(Trigger trigger) throws IOException { - addToList(trigger,triggers()); + addToList(trigger, triggers()); } public void removeTrigger(TriggerDescriptor trigger) throws IOException { - removeFromList(trigger,triggers()); + removeFromList(trigger, triggers()); } protected final synchronized > - void addToList( T item, List collection ) throws IOException { + void addToList(T item, List collection) throws IOException { //No support to replace item in position, remove then add removeFromList(item.getDescriptor(), collection); collection.add(item); @@ -1527,9 +1529,9 @@ public abstract class AbstractProject

    ,R extends A protected final synchronized > void removeFromList(Descriptor item, List collection) throws IOException { final Iterator iCollection = collection.iterator(); - while(iCollection.hasNext()) { + while (iCollection.hasNext()) { final T next = iCollection.next(); - if(next.getDescriptor()==item) { + if (next.getDescriptor() == item) { // found it iCollection.remove(); save(); @@ -1539,7 +1541,7 @@ public abstract class AbstractProject

    ,R extends A } } - @Override public Map> getTriggers() { + @Override public Map> getTriggers() { return triggers().toMap(); } @@ -1548,7 +1550,7 @@ public abstract class AbstractProject

    ,R extends A */ public T getTrigger(Class clazz) { for (Trigger p : triggers()) { - if(clazz.isInstance(p)) + if (clazz.isInstance(p)) return clazz.cast(p); } return null; @@ -1572,7 +1574,7 @@ public abstract class AbstractProject

    ,R extends A return Jenkins.get().getDependencyGraph().getDownstream(this); } - @Exported(name="downstreamProjects") + @Exported(name = "downstreamProjects") @Restricted(DoNotUse.class) // only for exporting public List getDownstreamProjectsForApi() { List r = new ArrayList<>(); @@ -1588,7 +1590,7 @@ public abstract class AbstractProject

    ,R extends A return Jenkins.get().getDependencyGraph().getUpstream(this); } - @Exported(name="upstreamProjects") + @Exported(name = "upstreamProjects") @Restricted(DoNotUse.class) // only for exporting public List getUpstreamProjectsForApi() { List r = new ArrayList<>(); @@ -1608,7 +1610,7 @@ public abstract class AbstractProject

    ,R extends A */ public final List getBuildTriggerUpstreamProjects() { ArrayList result = new ArrayList<>(); - for (AbstractProject ap : getUpstreamProjects()) { + for (AbstractProject ap : getUpstreamProjects()) { BuildTrigger buildTrigger = ap.getPublishersList().get(BuildTrigger.class); if (buildTrigger != null) if (buildTrigger.getChildJobs(ap).contains(this)) @@ -1644,7 +1646,7 @@ public abstract class AbstractProject

    ,R extends A * numbers of that project. */ public SortedMap getRelationship(AbstractProject that) { - TreeMap r = new TreeMap<>(REVERSE_INTEGER_COMPARATOR); + TreeMap r = new TreeMap<>(REVERSE_INTEGER_COMPARATOR); checkAndRecord(that, r, this.getBuilds()); // checkAndRecord(that, r, that.getBuilds()); @@ -1660,14 +1662,14 @@ public abstract class AbstractProject

    ,R extends A private void checkAndRecord(AbstractProject that, TreeMap r, Iterable builds) { for (R build : builds) { RangeSet rs = build.getDownstreamRelationship(that); - if(rs==null || rs.isEmpty()) + if (rs == null || rs.isEmpty()) continue; int n = build.getNumber(); RangeSet value = r.get(n); - if(value==null) - r.put(n,rs); + if (value == null) + r.put(n, rs); else value.add(rs); } @@ -1712,15 +1714,15 @@ public abstract class AbstractProject

    ,R extends A @Deprecated public int getDelay(StaplerRequest req) throws ServletException { String delay = req.getParameter("delay"); - if (delay==null) return getQuietPeriod(); + if (delay == null) return getQuietPeriod(); try { // TODO: more unit handling - if(delay.endsWith("sec")) delay=delay.substring(0,delay.length()-3); - if(delay.endsWith("secs")) delay=delay.substring(0,delay.length()-4); + if (delay.endsWith("sec")) delay = delay.substring(0, delay.length() - 3); + if (delay.endsWith("secs")) delay = delay.substring(0, delay.length() - 4); return Integer.parseInt(delay); } catch (NumberFormatException e) { - throw new ServletException("Invalid delay parameter value: "+delay, e); + throw new ServletException("Invalid delay parameter value: " + delay, e); } } @@ -1731,7 +1733,7 @@ public abstract class AbstractProject

    ,R extends A } @Override // in case schedulePolling was overridden - public void doPolling( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { + public void doPolling(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { BuildAuthorizationToken.checkPermission((Job) this, authToken, req, rsp); schedulePolling(); rsp.sendRedirect("."); @@ -1739,20 +1741,20 @@ public abstract class AbstractProject

    ,R extends A @Override protected void submit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException { - super.submit(req,rsp); + super.submit(req, rsp); JSONObject json = req.getSubmittedForm(); makeDisabled(json.optBoolean("disable")); jdk = json.optString("jdk", null); - if(json.optBoolean("hasCustomQuietPeriod", json.has("quiet_period"))) { + if (json.optBoolean("hasCustomQuietPeriod", json.has("quiet_period"))) { quietPeriod = json.optInt("quiet_period"); } else { quietPeriod = null; } - if(json.optBoolean("hasCustomScmCheckoutRetryCount", json.has("scmCheckoutRetryCount"))) { + if (json.optBoolean("hasCustomScmCheckoutRetryCount", json.has("scmCheckoutRetryCount"))) { scmCheckoutRetryCount = json.optInt("scmCheckoutRetryCount"); } else { scmCheckoutRetryCount = null; @@ -1761,11 +1763,11 @@ public abstract class AbstractProject

    ,R extends A blockBuildWhenDownstreamBuilding = json.optBoolean("blockBuildWhenDownstreamBuilding"); blockBuildWhenUpstreamBuilding = json.optBoolean("blockBuildWhenUpstreamBuilding"); - if(req.hasParameter("customWorkspace.directory")) { + if (req.hasParameter("customWorkspace.directory")) { // Workaround for JENKINS-25221 while plugins are being updated. LOGGER.log(Level.WARNING, "label assignment is using legacy 'customWorkspace.directory'"); customWorkspace = Util.fixEmptyAndTrim(req.getParameter("customWorkspace.directory")); - } else if(json.optBoolean("hasCustomWorkspace", json.has("customWorkspace"))) { + } else if (json.optBoolean("hasCustomWorkspace", json.has("customWorkspace"))) { customWorkspace = Util.fixEmptyAndTrim(json.optString("customWorkspace")); } else { customWorkspace = null; @@ -1777,9 +1779,9 @@ public abstract class AbstractProject

    ,R extends A else scmCheckoutStrategy = null; - if(json.optBoolean("hasSlaveAffinity", json.has("label"))) { + if (json.optBoolean("hasSlaveAffinity", json.has("label"))) { assignedNode = Util.fixEmptyAndTrim(json.optString("label")); - } else if(req.hasParameter("_.assignedLabelString")) { + } else if (req.hasParameter("_.assignedLabelString")) { // Workaround for JENKINS-25372 while plugin is being updated. // Keep this condition second for JENKINS-25533 LOGGER.log(Level.WARNING, "label assignment is using legacy '_.assignedLabelString'"); @@ -1787,7 +1789,7 @@ public abstract class AbstractProject

    ,R extends A } else { assignedNode = null; } - canRoam = assignedNode==null; + canRoam = assignedNode == null; keepDependencies = json.has("keepDependencies"); @@ -1795,13 +1797,13 @@ public abstract class AbstractProject

    ,R extends A authToken = BuildAuthorizationToken.create(req); - setScm(SCMS.parseSCM(req,this)); + setScm(SCMS.parseSCM(req, this)); for (Trigger t : triggers()) t.stop(); triggers.replaceBy(buildDescribable(req, Trigger.for_(this))); for (Trigger t : triggers()) - t.start(this,true); + t.start(this, true); } /** @@ -1810,7 +1812,7 @@ public abstract class AbstractProject

    ,R extends A */ @Deprecated protected final > List buildDescribable(StaplerRequest req, List> descriptors, String prefix) throws FormException, ServletException { - return buildDescribable(req,descriptors); + return buildDescribable(req, descriptors); } protected final > List buildDescribable(StaplerRequest req, List> descriptors) @@ -1831,7 +1833,7 @@ public abstract class AbstractProject

    ,R extends A /** * Serves the workspace files. */ - public DirectoryBrowserSupport doWs( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, InterruptedException { + public DirectoryBrowserSupport doWs(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, InterruptedException { checkPermission(Item.WORKSPACE); FilePath ws = getSomeWorkspace(); if (ws == null || !ws.exists()) { @@ -1840,7 +1842,7 @@ public abstract class AbstractProject

    ,R extends A // (E.g. return 404, or send empty doc.) // Not critical; client can just check if content type is not text/plain, // which also serves to detect old versions of Hudson. - req.getView(this,"noWorkspace.jelly").forward(req,rsp); + req.getView(this, "noWorkspace.jelly").forward(req, rsp); return null; } else { Computer c = ws.toComputer(); @@ -1861,8 +1863,8 @@ public abstract class AbstractProject

    ,R extends A public HttpResponse doDoWipeOutWorkspace() throws IOException, ServletException, InterruptedException { checkPermission(Functions.isWipeOutPermissionEnabled() ? WIPEOUT : BUILD); R b = getSomeBuildWithWorkspace(); - FilePath ws = b!=null ? b.getWorkspace() : null; - if (ws!=null && getScm().processWorkspaceBeforeDeletion(this, ws, b.getBuiltOn())) { + FilePath ws = b != null ? b.getWorkspace() : null; + if (ws != null && getScm().processWorkspaceBeforeDeletion(this, ws, b.getBuiltOn())) { ws.deleteRecursive(); for (WorkspaceListener wl : WorkspaceListener.all()) { wl.afterDelete(this); @@ -1870,7 +1872,7 @@ public abstract class AbstractProject

    ,R extends A return new HttpRedirect("."); } else { // If we get here, that means the SCM blocked the workspace deletion. - return new ForwardToView(this,"wipeOutWorkspaceBlocked.jelly"); + return new ForwardToView(this, "wipeOutWorkspaceBlocked.jelly"); } } @@ -1906,7 +1908,7 @@ public abstract class AbstractProject

    ,R extends A } @Restricted(DoNotUse.class) - public FormValidation doCheckAssignedLabelString(@AncestorInPath AbstractProject project, + public FormValidation doCheckAssignedLabelString(@AncestorInPath AbstractProject project, @QueryParameter String value) { // Provide a legacy interface in case plugins are not going through p:config-assignedLabel // see: JENKINS-25372 @@ -1914,7 +1916,7 @@ public abstract class AbstractProject

    ,R extends A return doCheckLabel(project, value); } - public FormValidation doCheckLabel(@AncestorInPath AbstractProject project, + public FormValidation doCheckLabel(@AncestorInPath AbstractProject project, @QueryParameter String value) { return LabelExpression.validate(value, project); } @@ -1931,8 +1933,8 @@ public abstract class AbstractProject

    ,R extends A return LabelExpression.validate(value, project); } - public FormValidation doCheckCustomWorkspace(@QueryParameter String customWorkspace){ - if(Util.fixEmptyAndTrim(customWorkspace)==null) + public FormValidation doCheckCustomWorkspace(@QueryParameter String customWorkspace) { + if (Util.fixEmptyAndTrim(customWorkspace) == null) return FormValidation.error(Messages.AbstractProject_CustomWorkspaceEmpty()); else return FormValidation.ok(); @@ -1941,7 +1943,7 @@ public abstract class AbstractProject

    ,R extends A public AutoCompletionCandidates doAutoCompleteUpstreamProjects(@QueryParameter String value) { AutoCompletionCandidates candidates = new AutoCompletionCandidates(); List jobs = Jenkins.get().getItems(j -> j instanceof Job && j.getFullName().startsWith(value)); - for (TopLevelItem job: jobs) { + for (TopLevelItem job : jobs) { candidates.add(job.getFullName()); } return candidates; @@ -1969,7 +1971,7 @@ public abstract class AbstractProject

    ,R extends A * @see Items#findNearest */ public static @CheckForNull AbstractProject findNearest(String name) { - return findNearest(name,Jenkins.get()); + return findNearest(name, Jenkins.get()); } /** @@ -2003,9 +2005,9 @@ public abstract class AbstractProject

    ,R extends A */ @CLIResolver public static AbstractProject resolveForCLI( - @Argument(required=true,metaVar="NAME",usage="Job name") String name) throws CmdLineException { + @Argument(required = true, metaVar = "NAME", usage = "Job name") String name) throws CmdLineException { AbstractProject item = Jenkins.get().getItemByFullName(name, AbstractProject.class); - if (item==null) { + if (item == null) { AbstractProject project = AbstractProject.findNearest(name); throw new CmdLineException(null, project == null ? Messages.AbstractItem_NoSuchJobExistsWithoutSuggestion(name) : Messages.AbstractItem_NoSuchJobExists(name, project.getFullName())); @@ -2034,7 +2036,7 @@ public abstract class AbstractProject

    ,R extends A * @since 1.410 */ public void setCustomWorkspace(String customWorkspace) throws IOException { - this.customWorkspace= Util.fixEmptyAndTrim(customWorkspace); + this.customWorkspace = Util.fixEmptyAndTrim(customWorkspace); save(); } diff --git a/core/src/main/java/hudson/model/AbstractStatusIcon.java b/core/src/main/java/hudson/model/AbstractStatusIcon.java index ea8c573ba9696ce8974f23dd81e518e686f1b8ec..4f2c4886b807526f01de513602b1d8e76b3e3b2c 100644 --- a/core/src/main/java/hudson/model/AbstractStatusIcon.java +++ b/core/src/main/java/hudson/model/AbstractStatusIcon.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; /** diff --git a/core/src/main/java/hudson/model/Action.java b/core/src/main/java/hudson/model/Action.java index 89cabe7271b9bbf6c3cd6fd9e1f74a20a72e9b68..08addd77361e67c3a00bfa07f61024b03b0b1ade 100644 --- a/core/src/main/java/hudson/model/Action.java +++ b/core/src/main/java/hudson/model/Action.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Michael B. Donohue - * + * * 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 @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import edu.umd.cs.findbugs.annotations.CheckForNull; diff --git a/core/src/main/java/hudson/model/Actionable.java b/core/src/main/java/hudson/model/Actionable.java index ff1456c9c741464cdab2d0ed3e7f83b21a64f36b..6fcb173fc6ad595441406177d93b9310d74b153b 100644 --- a/core/src/main/java/hudson/model/Actionable.java +++ b/core/src/main/java/hudson/model/Actionable.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Stephen Connolly - * + * * 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 @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import edu.umd.cs.findbugs.annotations.NonNull; @@ -90,7 +91,7 @@ public abstract class Actionable extends AbstractModelObject implements ModelObj * @return an unmodifiable, possible empty list * @since 1.548 */ - @Exported(name="actions") + @Exported(name = "actions") @NonNull public final List getAllActions() { List _actions = getActions(); @@ -147,7 +148,7 @@ public abstract class Actionable extends AbstractModelObject implements ModelObj */ @SuppressWarnings("ConstantConditions") public void addAction(@NonNull Action a) { - if(a==null) { + if (a == null) { throw new IllegalArgumentException("Action must be non-null"); } getActions().add(a); @@ -306,7 +307,7 @@ public abstract class Actionable extends AbstractModelObject implements ModelObj /** @deprecated No clear purpose, since subclasses may have overridden {@link #getActions}, and does not consider {@link TransientActionFactory}. */ @Deprecated public Action getAction(int index) { - if(actions==null) return null; + if (actions == null) return null; return actions.get(index); } @@ -336,19 +337,19 @@ public abstract class Actionable extends AbstractModelObject implements ModelObj public Object getDynamic(String token, StaplerRequest req, StaplerResponse rsp) { for (Action a : getAllActions()) { - if(a==null) + if (a == null) continue; // be defensive String urlName = a.getUrlName(); - if(urlName==null) + if (urlName == null) continue; - if(urlName.equals(token)) + if (urlName.equals(token)) return a; } return null; } @Override public ContextMenu doContextMenu(StaplerRequest request, StaplerResponse response) throws Exception { - return new ContextMenu().from(this,request,response); + return new ContextMenu().from(this, request, response); } private static final Logger LOGGER = Logger.getLogger(Actionable.class.getName()); diff --git a/core/src/main/java/hudson/model/AdministrativeMonitor.java b/core/src/main/java/hudson/model/AdministrativeMonitor.java index 0f163ac5b6ed3c961a60e80b4499c9a785847fdb..3c70207ff892e6572fb1fdcddb8176cc806271d9 100644 --- a/core/src/main/java/hudson/model/AdministrativeMonitor.java +++ b/core/src/main/java/hudson/model/AdministrativeMonitor.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import hudson.Extension; @@ -108,7 +109,7 @@ public abstract class AdministrativeMonitor extends AbstractModelObject implemen * Returns the URL of this monitor, relative to the context path, like "administrativeMonitor/foobar". */ public String getUrl() { - return "administrativeMonitor/"+id; + return "administrativeMonitor/" + id; } @Override @@ -175,7 +176,7 @@ public abstract class AdministrativeMonitor extends AbstractModelObject implemen public void doDisable(StaplerRequest req, StaplerResponse rsp) throws IOException { Jenkins.get().checkPermission(Jenkins.ADMINISTER); disable(true); - rsp.sendRedirect2(req.getContextPath()+"/manage"); + rsp.sendRedirect2(req.getContextPath() + "/manage"); } /** diff --git a/core/src/main/java/hudson/model/AllView.java b/core/src/main/java/hudson/model/AllView.java index cd154206a422e1a19444ebb320279ae0d05ad2f6..eb2d80ebcec749f0d5e6928d45a45b1e83e44e16 100644 --- a/core/src/main/java/hudson/model/AllView.java +++ b/core/src/main/java/hudson/model/AllView.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Tom Huybrechts - * + * * 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 @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import edu.umd.cs.findbugs.annotations.NonNull; @@ -72,7 +73,7 @@ public class AllView extends View { this(name); this.owner = owner; } - + @Override public boolean isEditable() { return false; @@ -94,13 +95,13 @@ public class AllView extends View { throws IOException, ServletException { ItemGroup ig = getOwner().getItemGroup(); if (ig instanceof ModifiableItemGroup) - return ((ModifiableItemGroup)ig).doCreateItem(req, rsp); + return ((ModifiableItemGroup) ig).doCreateItem(req, rsp); return null; } @Override public Collection getItems() { - return (Collection)getOwner().getItemGroup().getItems(); + return (Collection) getOwner().getItemGroup().getItems(); } @Override @@ -138,7 +139,7 @@ public class AllView extends View { // modern name, we are safe return primaryView; } - if (SystemProperties.getBoolean(AllView.class.getName()+".JENKINS-38606", true)) { + if (SystemProperties.getBoolean(AllView.class.getName() + ".JENKINS-38606", true)) { AllView allView = null; for (View v : views) { if (DEFAULT_VIEW_NAME.equals(v.getViewName())) { diff --git a/core/src/main/java/hudson/model/AperiodicWork.java b/core/src/main/java/hudson/model/AperiodicWork.java index 4fd5e231072a20f011ffb648e3ee04540a3deaad..0443c9d4abf3f66db88782624943e8a40f0dd549 100644 --- a/core/src/main/java/hudson/model/AperiodicWork.java +++ b/core/src/main/java/hudson/model/AperiodicWork.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import static hudson.init.InitMilestone.JOB_CONFIG_ADAPTED; @@ -49,7 +50,7 @@ import jenkins.util.Timer; * @author vjuranek * @since 1.410 */ -@SuppressFBWarnings(value="PREDICTABLE_RANDOM", justification = "The random is just used for an initial delay.") +@SuppressFBWarnings(value = "PREDICTABLE_RANDOM", justification = "The random is just used for an initial delay.") public abstract class AperiodicWork extends SafeTimerTask implements ExtensionPoint { protected final Logger logger = Logger.getLogger(getClass().getName()); @@ -81,18 +82,18 @@ public abstract class AperiodicWork extends SafeTimerTask implements ExtensionPo public long getInitialDelay() { long l = RANDOM.nextLong(); // Math.abs(Long.MIN_VALUE)==Long.MIN_VALUE! - if (l==Long.MIN_VALUE) + if (l == Long.MIN_VALUE) l++; - return Math.abs(l)%getRecurrencePeriod(); + return Math.abs(l) % getRecurrencePeriod(); } @Override - public final void doRun() throws Exception{ + public final void doRun() throws Exception { doAperiodicRun(); Timer.get().schedule(getNewInstance(), getRecurrencePeriod(), TimeUnit.MILLISECONDS); } - @Initializer(after= JOB_CONFIG_ADAPTED) + @Initializer(after = JOB_CONFIG_ADAPTED) public static void init() { // start all AperidocWorks ExtensionList extensionList = all(); diff --git a/core/src/main/java/hudson/model/Api.java b/core/src/main/java/hudson/model/Api.java index bb2658d7cc9e4edfa37dab2bc33bb8dea3a9f9e7..11db76c3581d40f90e21fc77681dd296cc5ce7d5 100644 --- a/core/src/main/java/hudson/model/Api.java +++ b/core/src/main/java/hudson/model/Api.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi, Seiji Sogabe - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import hudson.ExtensionList; @@ -104,9 +105,9 @@ public class Api extends AbstractModelObject { String[] excludes = req.getParameterValues("exclude"); - if(xpath==null && excludes==null) { + if (xpath == null && excludes == null) { // serve the whole thing - rsp.serveExposedBean(req,bean,Flavor.XML); + rsp.serveExposedBean(req, bean, Flavor.XML); return; } @@ -115,7 +116,7 @@ public class Api extends AbstractModelObject { // first write to String Model p = MODEL_BUILDER.get(bean.getClass()); TreePruner pruner = tree != null ? new NamedPathPruner(tree) : new ByDepth(1 - depth); - p.writeTo(bean,pruner,Flavor.XML.createDataWriter(bean,sw)); + p.writeTo(bean, pruner, Flavor.XML.createDataWriter(bean, sw)); // apply XPath FilteredFunctionContext functionContext = new FilteredFunctionContext(); @@ -123,33 +124,33 @@ public class Api extends AbstractModelObject { try { Document dom = new SAXReader().read(new StringReader(sw.toString())); // apply exclusions - if (excludes!=null) { + if (excludes != null) { for (String exclude : excludes) { XPath xExclude = dom.createXPath(exclude); xExclude.setFunctionContext(functionContext); List list = xExclude.selectNodes(dom); for (org.dom4j.Node n : list) { Element parent = n.getParent(); - if(parent!=null) + if (parent != null) parent.remove(n); } } } - - if(xpath==null) { - result = dom; + + if (xpath == null) { + result = dom; } else { XPath comp = dom.createXPath(xpath); comp.setFunctionContext(functionContext); List list = comp.selectNodes(dom); - if (wrapper!=null) { + if (wrapper != null) { // check if the wrapper is a valid entity name // First position: letter or underscore // Other positions: \w (letter, number, underscore), dash or dot String validNameRE = "^[a-zA-Z_][\\w-\\.]*$"; - if(!wrapper.matches(validNameRE)) { + if (!wrapper.matches(validNameRE)) { rsp.setStatus(HttpServletResponse.SC_BAD_REQUEST); rsp.getWriter().print(Messages.Api_WrapperParamInvalid()); return; @@ -160,7 +161,7 @@ public class Api extends AbstractModelObject { if (o instanceof String) { root.addText(o.toString()); } else { - root.add(((org.dom4j.Node)o).detach()); + root.add(((org.dom4j.Node) o).detach()); } } result = root; @@ -170,7 +171,7 @@ public class Api extends AbstractModelObject { return; } else if (list.size() > 1) { rsp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - rsp.getWriter().print(Messages.Api_MultipleMatch(xpath,list.size())); + rsp.getWriter().print(Messages.Api_MultipleMatch(xpath, list.size())); return; } else { result = list.get(0); @@ -178,8 +179,8 @@ public class Api extends AbstractModelObject { } } catch (DocumentException e) { - LOGGER.log(Level.FINER, "Failed to do XPath/wrapper handling. XML is as follows:"+sw, e); - throw new IOException("Failed to do XPath/wrapper handling. Turn on FINER logging to view XML.",e); + LOGGER.log(Level.FINER, "Failed to do XPath/wrapper handling. XML is as follows:" + sw, e); + throw new IOException("Failed to do XPath/wrapper handling. Turn on FINER logging to view XML.", e); } @@ -226,7 +227,7 @@ public class Api extends AbstractModelObject { public void doJson(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { if (req.getParameter("jsonp") == null || permit(req)) { setHeaders(rsp); - rsp.serveExposedBean(req,bean, req.getParameter("jsonp") == null ? Flavor.JSON : Flavor.JSONP); + rsp.serveExposedBean(req, bean, req.getParameter("jsonp") == null ? Flavor.JSON : Flavor.JSONP); } else { rsp.sendError(HttpURLConnection.HTTP_FORBIDDEN, "jsonp forbidden; implement jenkins.security.SecureRequester"); } @@ -237,7 +238,7 @@ public class Api extends AbstractModelObject { */ public void doPython(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { setHeaders(rsp); - rsp.serveExposedBean(req,bean, Flavor.PYTHON); + rsp.serveExposedBean(req, bean, Flavor.PYTHON); } private boolean permit(StaplerRequest req) { diff --git a/core/src/main/java/hudson/model/AsyncAperiodicWork.java b/core/src/main/java/hudson/model/AsyncAperiodicWork.java index b5ad5b07d44f4a5055326e98d367adce0202f8ed..294b471f990fe8161abfd106aa567890813c8f1b 100644 --- a/core/src/main/java/hudson/model/AsyncAperiodicWork.java +++ b/core/src/main/java/hudson/model/AsyncAperiodicWork.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import hudson.Functions; @@ -37,8 +38,8 @@ import jenkins.util.SystemProperties; /** * {@link AperiodicWork} that takes a long time to run. Similar to {@link AsyncPeriodicWork}, see {@link AsyncPeriodicWork} for - * details and {@link AperiodicWork} for differences between {@link AperiodicWork} and {@link PeriodicWork}. - * + * details and {@link AperiodicWork} for differences between {@link AperiodicWork} and {@link PeriodicWork}. + * * @author vjuranek * @since 1.410 */ @@ -94,8 +95,8 @@ public abstract class AsyncAperiodicWork extends AperiodicWork { protected AsyncAperiodicWork(String name) { this.name = name; this.logRotateMillis = TimeUnit.MINUTES.toMillis( - SystemProperties.getLong(getClass().getName()+".logRotateMinutes", LOG_ROTATE_MINUTES)); - this.logRotateSize = SystemProperties.getLong(getClass().getName() +".logRotateSize", LOG_ROTATE_SIZE); + SystemProperties.getLong(getClass().getName() + ".logRotateMinutes", LOG_ROTATE_MINUTES)); + this.logRotateSize = SystemProperties.getLong(getClass().getName() + ".logRotateSize", LOG_ROTATE_SIZE); } /** @@ -104,7 +105,7 @@ public abstract class AsyncAperiodicWork extends AperiodicWork { @Override public final void doAperiodicRun() { try { - if(thread!=null && thread.isAlive()) { + if (thread != null && thread.isAlive()) { logger.log(getSlowLoggingLevel(), "{0} thread is still running. Execution aborted.", name); return; } @@ -127,10 +128,10 @@ public abstract class AsyncAperiodicWork extends AperiodicWork { logger.log(getNormalLoggingLevel(), "Finished {0}. {1,number} ms", new Object[]{name, stopTime - startTime}); - },name+" thread"); - thread.start(); + }, name + " thread"); + thread.start(); } catch (Throwable t) { - logger.log(Level.SEVERE, name+" thread failed with error", t); + logger.log(Level.SEVERE, name + " thread failed with error", t); } } diff --git a/core/src/main/java/hudson/model/AsyncPeriodicWork.java b/core/src/main/java/hudson/model/AsyncPeriodicWork.java index 1a6ce7cadaf3bb1b0512043e19672ca141804348..3b75984454f25804b6cbbdc0fe5f20f324bd4162 100644 --- a/core/src/main/java/hudson/model/AsyncPeriodicWork.java +++ b/core/src/main/java/hudson/model/AsyncPeriodicWork.java @@ -87,7 +87,7 @@ public abstract class AsyncPeriodicWork extends PeriodicWork { @SuppressWarnings("deprecation") // in this case we really want to use PeriodicWork.logger since it reports the impl class public final void doRun() { try { - if(thread!=null && thread.isAlive()) { + if (thread != null && thread.isAlive()) { logger.log(this.getSlowLoggingLevel(), "{0} thread is still running. Execution aborted.", name); return; } @@ -112,7 +112,7 @@ public abstract class AsyncPeriodicWork extends PeriodicWork { logger.log(getNormalLoggingLevel(), "Finished {0}. {1,number} ms", new Object[]{name, stopTime - startTime}); - },name+" thread"); + }, name + " thread"); thread.start(); } catch (Throwable t) { LogRecord lr = new LogRecord(this.getErrorLoggingLevel(), "{0} thread failed with error"); @@ -214,11 +214,11 @@ public abstract class AsyncPeriodicWork extends PeriodicWork { protected File getLogFile() { return new File(getLogsRoot(), "/tasks/" + name + ".log"); } - + /** * Returns the logging level at which normal messages are displayed. - * - * @return + * + * @return * The logging level as @Level. * * @since 1.551 @@ -226,7 +226,7 @@ public abstract class AsyncPeriodicWork extends PeriodicWork { protected Level getNormalLoggingLevel() { return Level.INFO; } - + /** * Returns the logging level at which previous task still executing messages is displayed. * @@ -241,8 +241,8 @@ public abstract class AsyncPeriodicWork extends PeriodicWork { /** * Returns the logging level at which error messages are displayed. - * - * @return + * + * @return * The logging level as @Level. * * @since 1.551 @@ -250,7 +250,7 @@ public abstract class AsyncPeriodicWork extends PeriodicWork { protected Level getErrorLoggingLevel() { return Level.SEVERE; } - + /** * Executes the task. * diff --git a/core/src/main/java/hudson/model/AutoCompletionCandidates.java b/core/src/main/java/hudson/model/AutoCompletionCandidates.java index 19fff10cca296ea4b944d30519a6d381f5d47047..dbc3f6ea1c186bdb1642cae7e4d844194d2c74fc 100644 --- a/core/src/main/java/hudson/model/AutoCompletionCandidates.java +++ b/core/src/main/java/hudson/model/AutoCompletionCandidates.java @@ -74,7 +74,7 @@ public class AutoCompletionCandidates implements HttpResponse { for (String value : values) { r.suggestions.add(new hudson.search.Search.Item(value)); } - rsp.serveExposedBean(req,r, Flavor.JSON); + rsp.serveExposedBean(req, r, Flavor.JSON); } /** @@ -92,7 +92,7 @@ public class AutoCompletionCandidates implements HttpResponse { * @since 1.489 */ public static AutoCompletionCandidates ofJobNames(final Class type, final String value, @CheckForNull Item self, ItemGroup container) { - if (self==container) + if (self == container) container = self.getParent(); return ofJobNames(type, value, container); } @@ -122,7 +122,7 @@ public class AutoCompletionCandidates implements HttpResponse { @Override public void onItem(Item i) { String itemName = contextualNameOf(i); - + //Check user's setting on whether to do case sensitive comparison, configured in user -> configure //This is the same setting that is used by the global search field, should be consistent throughout //the whole application. @@ -131,7 +131,7 @@ public class AutoCompletionCandidates implements HttpResponse { if ((startsWithImpl(itemName, value, caseInsensitive) || startsWithImpl(value, itemName, caseInsensitive)) // 'foobar' is a valid candidate if the current value is 'foo'. // Also, we need to visit 'foo' if the current value is 'foo/bar' - && (value.length()> itemName.length() || !itemName.substring(value.length()).contains("/")) + && (value.length() > itemName.length() || !itemName.substring(value.length()).contains("/")) // but 'foobar/zot' isn't if the current value is 'foo' // we'll first show 'foobar' and then wait for the user to type '/' to show the rest && i.hasPermission(Item.READ) @@ -149,22 +149,22 @@ public class AutoCompletionCandidates implements HttpResponse { } private String contextualNameOf(Item i) { - if (prefix.endsWith("/") || prefix.length()==0) - return prefix+i.getName(); + if (prefix.endsWith("/") || prefix.length() == 0) + return prefix + i.getName(); else - return prefix+'/'+i.getName(); + return prefix + '/' + i.getName(); } } - if (container==null || container==Jenkins.get()) { + if (container == null || container == Jenkins.get()) { new Visitor("").onItemGroup(Jenkins.get()); } else { new Visitor("").onItemGroup(container); if (value.startsWith("/")) new Visitor("/").onItemGroup(Jenkins.get()); - for ( String p="../"; value.startsWith(p); p+="../") { - container = ((Item)container).getParent(); + for (String p = "../"; value.startsWith(p); p += "../") { + container = ((Item) container).getParent(); new Visitor(p).onItemGroup(container); } } diff --git a/core/src/main/java/hudson/model/BallColor.java b/core/src/main/java/hudson/model/BallColor.java index bbaa6cda6d449a4d7970a887524174c1cde419c7..5913f59466f9364349dcdb2d2d2007d425e2da80 100644 --- a/core/src/main/java/hudson/model/BallColor.java +++ b/core/src/main/java/hudson/model/BallColor.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Simon Wiest - * + * * 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 @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import hudson.util.ColorPalette; @@ -37,7 +38,7 @@ import org.kohsuke.stapler.Stapler; * *

    * There are four basic colors, plus their animated "bouncy" versions. - * {@link #ordinal()} is the sort order. + * {@link #ordinal()} is the sort order. * *

    * Note that multiple {@link BallColor} instances may map to the same @@ -53,22 +54,22 @@ import org.kohsuke.stapler.Stapler; * @author Kohsuke Kawaguchi */ public enum BallColor implements StatusIcon { - RED("red",Messages._BallColor_Failed(), ColorPalette.RED), - RED_ANIME("red_anime",Messages._BallColor_InProgress(), ColorPalette.RED), - YELLOW("yellow",Messages._BallColor_Unstable(), ColorPalette.YELLOW), - YELLOW_ANIME("yellow_anime",Messages._BallColor_InProgress(), ColorPalette.YELLOW), - BLUE("blue",Messages._BallColor_Success(), ColorPalette.BLUE), - BLUE_ANIME("blue_anime",Messages._BallColor_InProgress(), ColorPalette.BLUE), + RED("red", Messages._BallColor_Failed(), ColorPalette.RED), + RED_ANIME("red_anime", Messages._BallColor_InProgress(), ColorPalette.RED), + YELLOW("yellow", Messages._BallColor_Unstable(), ColorPalette.YELLOW), + YELLOW_ANIME("yellow_anime", Messages._BallColor_InProgress(), ColorPalette.YELLOW), + BLUE("blue", Messages._BallColor_Success(), ColorPalette.BLUE), + BLUE_ANIME("blue_anime", Messages._BallColor_InProgress(), ColorPalette.BLUE), // for historical reasons they are called grey. - GREY("grey",Messages._BallColor_Disabled(), ColorPalette.GREY), - GREY_ANIME("grey_anime",Messages._BallColor_InProgress(), ColorPalette.GREY), - - DISABLED("disabled",Messages._BallColor_Disabled(), ColorPalette.GREY), - DISABLED_ANIME("disabled_anime",Messages._BallColor_InProgress(), ColorPalette.GREY), - ABORTED("aborted",Messages._BallColor_Aborted(), ColorPalette.DARK_GREY), - ABORTED_ANIME("aborted_anime",Messages._BallColor_InProgress(), ColorPalette.DARK_GREY), - NOTBUILT("nobuilt",Messages._BallColor_NotBuilt(), ColorPalette.LIGHT_GREY), - NOTBUILT_ANIME("nobuilt_anime",Messages._BallColor_InProgress(), ColorPalette.LIGHT_GREY) + GREY("grey", Messages._BallColor_Disabled(), ColorPalette.GREY), + GREY_ANIME("grey_anime", Messages._BallColor_InProgress(), ColorPalette.GREY), + + DISABLED("disabled", Messages._BallColor_Disabled(), ColorPalette.GREY), + DISABLED_ANIME("disabled_anime", Messages._BallColor_InProgress(), ColorPalette.GREY), + ABORTED("aborted", Messages._BallColor_Aborted(), ColorPalette.DARK_GREY), + ABORTED_ANIME("aborted_anime", Messages._BallColor_InProgress(), ColorPalette.DARK_GREY), + NOTBUILT("nobuilt", Messages._BallColor_NotBuilt(), ColorPalette.LIGHT_GREY), + NOTBUILT_ANIME("nobuilt_anime", Messages._BallColor_InProgress(), ColorPalette.LIGHT_GREY) ; private final Localizable description; @@ -83,7 +84,7 @@ public enum BallColor implements StatusIcon { this.baseColor = baseColor; // name() is not usable in the constructor, so I have to repeat the name twice // in the constants definition. - this.image = image+ (image.endsWith("_anime")?".gif":".png"); + this.image = image + (image.endsWith("_anime") ? ".gif" : ".png"); this.description = description; } @@ -112,7 +113,7 @@ public enum BallColor implements StatusIcon { @Override public String getImageOf(String size) { - return Stapler.getCurrentRequest().getContextPath()+ Jenkins.RESOURCE_PATH+"/images/"+size+'/'+image; + return Stapler.getCurrentRequest().getContextPath() + Jenkins.RESOURCE_PATH + "/images/" + size + '/' + image; } /** @@ -149,15 +150,15 @@ public enum BallColor implements StatusIcon { * Gets the animated version. */ public BallColor anime() { - if(isAnimated()) return this; - else return valueOf(name()+"_ANIME"); + if (isAnimated()) return this; + else return valueOf(name() + "_ANIME"); } /** * Gets the unanimated version. */ public BallColor noAnime() { - if(isAnimated()) return valueOf(name().substring(0,name().length()-"_ANIME".length())); + if (isAnimated()) return valueOf(name().substring(0, name().length() - "_ANIME".length())); else return this; } diff --git a/core/src/main/java/hudson/model/BooleanParameterDefinition.java b/core/src/main/java/hudson/model/BooleanParameterDefinition.java index 4b7dae08aac01c1dd8f58f108afe45457b2ff7c6..d4958d9ea297c39697b7749ab77604215f6478c7 100644 --- a/core/src/main/java/hudson/model/BooleanParameterDefinition.java +++ b/core/src/main/java/hudson/model/BooleanParameterDefinition.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import edu.umd.cs.findbugs.annotations.CheckForNull; @@ -87,7 +88,7 @@ public class BooleanParameterDefinition extends SimpleParameterDefinition { @Override public ParameterValue createValue(String value) { - return new BooleanParameterValue(getName(),Boolean.parseBoolean(value),getDescription()); + return new BooleanParameterValue(getName(), Boolean.parseBoolean(value), getDescription()); } @Override diff --git a/core/src/main/java/hudson/model/BooleanParameterValue.java b/core/src/main/java/hudson/model/BooleanParameterValue.java index c48cad87a69e041f1916b0ebe9f5f17cdad6b5c6..d449623301cc94808e30c61a9c92b3c42d0de803 100644 --- a/core/src/main/java/hudson/model/BooleanParameterValue.java +++ b/core/src/main/java/hudson/model/BooleanParameterValue.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Luca Domenico Milanesio, Tom Huybrechts - * + * * 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 @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import hudson.EnvVars; @@ -33,7 +34,7 @@ import org.kohsuke.stapler.export.Exported; * {@link ParameterValue} created from {@link BooleanParameterDefinition}. */ public class BooleanParameterValue extends ParameterValue { - @Exported(visibility=4) + @Exported(visibility = 4) public final boolean value; @DataBoundConstructor @@ -55,9 +56,9 @@ public class BooleanParameterValue extends ParameterValue { * Exposes the name/value as an environment variable. */ @Override - public void buildEnvironment(Run build, EnvVars env) { - env.put(name,Boolean.toString(value)); - env.put(name.toUpperCase(Locale.ENGLISH),Boolean.toString(value)); // backward compatibility pre 1.345 + public void buildEnvironment(Run build, EnvVars env) { + env.put(name, Boolean.toString(value)); + env.put(name.toUpperCase(Locale.ENGLISH), Boolean.toString(value)); // backward compatibility pre 1.345 } @Override @@ -85,7 +86,7 @@ public class BooleanParameterValue extends ParameterValue { @Override public String toString() { - return "(BooleanParameterValue) " + getName() + "='" + value + "'"; + return "(BooleanParameterValue) " + getName() + "='" + value + "'"; } @Override public String getShortDescription() { diff --git a/core/src/main/java/hudson/model/Build.java b/core/src/main/java/hudson/model/Build.java index 7daa7b4cf0b03153a34ef698011ad72cf82900c8..49d126b8e8481e914357555d0c2b936c3641c5d2 100644 --- a/core/src/main/java/hudson/model/Build.java +++ b/core/src/main/java/hudson/model/Build.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import static hudson.model.Result.FAILURE; @@ -82,8 +83,8 @@ import org.kohsuke.accmod.restrictions.NoExternalUse; * * @author Kohsuke Kawaguchi */ -public abstract class Build

    ,B extends Build> - extends AbstractBuild { +public abstract class Build

    , B extends Build> + extends AbstractBuild { /** * Creates a new build. @@ -100,7 +101,7 @@ public abstract class Build

    ,B extends Build> * Loads a build from a log file. */ protected Build(P project, File buildDir) throws IOException { - super(project,buildDir); + super(project, buildDir); } // @@ -140,9 +141,9 @@ public abstract class Build

    ,B extends Build> @Override protected Result doRun(@NonNull BuildListener listener) throws Exception { - if(!preBuild(listener,project.getBuilders())) + if (!preBuild(listener, project.getBuilders())) return FAILURE; - if(!preBuild(listener,project.getPublishersList())) + if (!preBuild(listener, project.getPublishersList())) return FAILURE; Result r = null; @@ -151,16 +152,16 @@ public abstract class Build

    ,B extends Build> ParametersAction parameters = getAction(ParametersAction.class); if (parameters != null) - parameters.createBuildWrappers(Build.this,wrappers); + parameters.createBuildWrappers(Build.this, wrappers); - for( BuildWrapper w : wrappers ) { - Environment e = w.setUp((AbstractBuild)Build.this, launcher, listener); - if(e==null) + for (BuildWrapper w : wrappers) { + Environment e = w.setUp((AbstractBuild) Build.this, launcher, listener); + if (e == null) return r = FAILURE; buildEnvironments.add(e); } - if(!build(listener,project.getBuilders())) + if (!build(listener, project.getBuilders())) r = FAILURE; } catch (InterruptedException e) { r = Executor.currentExecutor().abortResult(); @@ -194,8 +195,8 @@ public abstract class Build

    ,B extends Build> } private boolean build(@NonNull BuildListener listener, @NonNull Collection steps) throws IOException, InterruptedException { - for( BuildStep bs : steps ) { - if(!perform(bs,listener)) { + for (BuildStep bs : steps) { + if (!perform(bs, listener)) { LOGGER.log(Level.FINE, "{0} : {1} failed", new Object[] {Build.this, bs}); return false; } diff --git a/core/src/main/java/hudson/model/BuildAuthorizationToken.java b/core/src/main/java/hudson/model/BuildAuthorizationToken.java index 43563b6f4611fddf7827ad5f404a73c97e0d4aab..48aea15b0897cd640f237f45ce98880a3af6c172 100644 --- a/core/src/main/java/hudson/model/BuildAuthorizationToken.java +++ b/core/src/main/java/hudson/model/BuildAuthorizationToken.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import com.thoughtworks.xstream.converters.basic.AbstractSingleValueConverter; @@ -55,22 +56,22 @@ public final class BuildAuthorizationToken { public static BuildAuthorizationToken create(StaplerRequest req) { if (req.getParameter("pseudoRemoteTrigger") != null) { String token = Util.fixEmpty(req.getParameter("authToken")); - if(token!=null) + if (token != null) return new BuildAuthorizationToken(token); } - + return null; } - @Deprecated public static void checkPermission(AbstractProject project, BuildAuthorizationToken token, StaplerRequest req, StaplerResponse rsp) throws IOException { - checkPermission((Job) project, token, req, rsp); + @Deprecated public static void checkPermission(AbstractProject project, BuildAuthorizationToken token, StaplerRequest req, StaplerResponse rsp) throws IOException { + checkPermission((Job) project, token, req, rsp); } - public static void checkPermission(Job project, BuildAuthorizationToken token, StaplerRequest req, StaplerResponse rsp) throws IOException { + public static void checkPermission(Job project, BuildAuthorizationToken token, StaplerRequest req, StaplerResponse rsp) throws IOException { if (!Jenkins.get().isUseSecurity()) return; // everyone is authorized - if(token!=null && token.token != null) { + if (token != null && token.token != null) { //check the provided token String providedToken = req.getParameter("token"); if (providedToken != null && providedToken.equals(token.token)) @@ -101,7 +102,7 @@ public final class BuildAuthorizationToken { public static final class ConverterImpl extends AbstractSingleValueConverter { @Override public boolean canConvert(Class type) { - return type== BuildAuthorizationToken.class; + return type == BuildAuthorizationToken.class; } @Override @@ -111,7 +112,7 @@ public final class BuildAuthorizationToken { @Override public String toString(Object obj) { - return ((BuildAuthorizationToken)obj).token; + return ((BuildAuthorizationToken) obj).token; } } } diff --git a/core/src/main/java/hudson/model/BuildBadgeAction.java b/core/src/main/java/hudson/model/BuildBadgeAction.java index 4cdeffaaa5d79f95a096db1fb37e4955aa92be39..da848424eeafaae682c96d145512699814825c4f 100644 --- a/core/src/main/java/hudson/model/BuildBadgeAction.java +++ b/core/src/main/java/hudson/model/BuildBadgeAction.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; /** diff --git a/core/src/main/java/hudson/model/BuildListener.java b/core/src/main/java/hudson/model/BuildListener.java index 10043b633b22c2301cec142a4aeade9bda4a0e83..0f8fc060f27e58b75c97271b41f040104dc7543b 100644 --- a/core/src/main/java/hudson/model/BuildListener.java +++ b/core/src/main/java/hudson/model/BuildListener.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import java.io.PrintStream; diff --git a/core/src/main/java/hudson/model/BuildTimelineWidget.java b/core/src/main/java/hudson/model/BuildTimelineWidget.java index 43a37a082a014da85858278511661f00c2347b78..563f8a18823a547083c6dbc65c56dc93d7926e7b 100644 --- a/core/src/main/java/hudson/model/BuildTimelineWidget.java +++ b/core/src/main/java/hudson/model/BuildTimelineWidget.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import hudson.Util; @@ -60,17 +61,17 @@ public class BuildTimelineWidget { public TimelineEventList doData(StaplerRequest req, @QueryParameter long min, @QueryParameter long max) throws IOException { TimelineEventList result = new TimelineEventList(); - for (Run r : builds.byTimestamp(min,max)) { + for (Run r : builds.byTimestamp(min, max)) { Event e = new Event(); e.start = new Date(r.getStartTimeInMillis()); - e.end = new Date(r.getStartTimeInMillis()+r.getDuration()); + e.end = new Date(r.getStartTimeInMillis() + r.getDuration()); // due to SimileAjax.HTML.deEntify (in simile-ajax-bundle.js), "<" are transformed back to "<", but not the "<"; // to protect against XSS e.title = Util.escape(r.getFullDisplayName()).replace("<", "<"); - e.link = req.getContextPath()+'/'+r.getUrl(); + e.link = req.getContextPath() + '/' + r.getUrl(); BallColor c = r.getIconColor(); - e.color = String.format("#%06X",c.getBaseColor().darker().getRGB()&0xFFFFFF); - e.classname = "event-"+c.noAnime().toString()+" " + (c.isAnimated()?"animated":""); + e.color = String.format("#%06X", c.getBaseColor().darker().getRGB() & 0xFFFFFF); + e.classname = "event-" + c.noAnime().toString() + " " + (c.isAnimated() ? "animated" : ""); result.add(e); } return result; diff --git a/core/src/main/java/hudson/model/BuildVariableContributor.java b/core/src/main/java/hudson/model/BuildVariableContributor.java index 67cdc4d965e09ccf94342672cef9dedf5f6a379d..5054e10f48cd1e83c79ee6581bcc7068c5242b60 100644 --- a/core/src/main/java/hudson/model/BuildVariableContributor.java +++ b/core/src/main/java/hudson/model/BuildVariableContributor.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import hudson.ExtensionList; @@ -62,7 +63,7 @@ public abstract class BuildVariableContributor implements ExtensionPoint { * Partially built variable map. Implementation of this method is expected to * add additional variables here. Never null. */ - public abstract void buildVariablesFor(AbstractBuild build, Map variables); + public abstract void buildVariablesFor(AbstractBuild build, Map variables); /** * Returns all the registered {@link BuildVariableContributor}s. diff --git a/core/src/main/java/hudson/model/BuildableItem.java b/core/src/main/java/hudson/model/BuildableItem.java index 0d65214e4378535633be61f177c4b2174ad78b52..52fbeb97df78223147f35beba7e8061ba54772f1 100644 --- a/core/src/main/java/hudson/model/BuildableItem.java +++ b/core/src/main/java/hudson/model/BuildableItem.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import hudson.model.Queue.Task; @@ -35,24 +36,25 @@ import hudson.model.Queue.Task; * @author Kohsuke Kawaguchi */ public interface BuildableItem extends Item, Task { - /** - * @deprecated - * Use {@link #scheduleBuild(Cause)}. Since 1.283 - */ + /** + * @deprecated + * Use {@link #scheduleBuild(Cause)}. Since 1.283 + */ @Deprecated default boolean scheduleBuild() { - return scheduleBuild(new Cause.LegacyCodeCause()); - } + return scheduleBuild(new Cause.LegacyCodeCause()); + } + + boolean scheduleBuild(Cause c); + /** + * @deprecated + * Use {@link #scheduleBuild(int, Cause)}. Since 1.283 + */ - boolean scheduleBuild(Cause c); - /** - * @deprecated - * Use {@link #scheduleBuild(int, Cause)}. Since 1.283 - */ @Deprecated - default boolean scheduleBuild(int quietPeriod) { - return scheduleBuild(quietPeriod, new Cause.LegacyCodeCause()); - } + default boolean scheduleBuild(int quietPeriod) { + return scheduleBuild(quietPeriod, new Cause.LegacyCodeCause()); + } - boolean scheduleBuild(int quietPeriod, Cause c); + boolean scheduleBuild(int quietPeriod, Cause c); } diff --git a/core/src/main/java/hudson/model/BuildableItemWithBuildWrappers.java b/core/src/main/java/hudson/model/BuildableItemWithBuildWrappers.java index c79daa2ca23506f9bd6f0c4b76faebfcdd11a779..74f39b2928aa3dbb6fb860b7d7f738f7a3c7bbf2 100644 --- a/core/src/main/java/hudson/model/BuildableItemWithBuildWrappers.java +++ b/core/src/main/java/hudson/model/BuildableItemWithBuildWrappers.java @@ -18,7 +18,7 @@ public interface BuildableItemWithBuildWrappers extends BuildableItem { * This method must be always implemented as {@code (AbstractProject)this}, but * defining this method emphasizes the fact that this cast must be doable. */ - AbstractProject asProject(); + AbstractProject asProject(); /** * {@link BuildWrapper}s associated with this {@link AbstractProject}. @@ -27,5 +27,5 @@ public interface BuildableItemWithBuildWrappers extends BuildableItem { * can be empty but never null. This list is live, and changes to it will be reflected * to the project configuration. */ - DescribableList> getBuildWrappersList(); + DescribableList> getBuildWrappersList(); } diff --git a/core/src/main/java/hudson/model/Cause.java b/core/src/main/java/hudson/model/Cause.java index b58129f19ae1c641aa47060eaebd204904974fd6..6990dd2b39e085a93bf2032e4c8fef9480915dde 100644 --- a/core/src/main/java/hudson/model/Cause.java +++ b/core/src/main/java/hudson/model/Cause.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import com.thoughtworks.xstream.converters.UnmarshallingContext; @@ -70,7 +71,7 @@ public abstract class Cause { * To have rich HTML output on the UI, provide a custom {@code description.jelly} view for your subclass. * See the documentation. */ - @Exported(visibility=3) + @Exported(visibility = 3) public abstract String getShortDescription(); /** @@ -96,21 +97,21 @@ public abstract class Cause { * this ought to be {@code transient}. * @since 1.568 */ - public void onLoad(@NonNull Run build) { + public void onLoad(@NonNull Run build) { if (build instanceof AbstractBuild) { onLoad((AbstractBuild) build); } } - void onLoad(@NonNull Job job, int buildNumber) { - Run build = job.getBuildByNumber(buildNumber); + void onLoad(@NonNull Job job, int buildNumber) { + Run build = job.getBuildByNumber(buildNumber); if (build != null) { onLoad(build); } } @Deprecated - public void onLoad(AbstractBuild build) { + public void onLoad(AbstractBuild build) { if (Util.isOverridden(Cause.class, getClass(), "onLoad", Run.class)) { onLoad((Run) build); } @@ -132,6 +133,7 @@ public abstract class Cause { public static class LegacyCodeCause extends Cause { @SuppressFBWarnings(value = "URF_UNREAD_FIELD", justification = "for backward compatibility") private StackTraceElement [] stackTrace; + public LegacyCodeCause() { stackTrace = new Exception().getStackTrace(); } @@ -169,8 +171,8 @@ public abstract class Cause { */ // for backward bytecode compatibility @Deprecated - public UpstreamCause(AbstractBuild up) { - this((Run)up); + public UpstreamCause(AbstractBuild up) { + this((Run) up); } public UpstreamCause(Run up) { @@ -192,14 +194,14 @@ public abstract class Cause { } @Override - public void onLoad(@NonNull Job _job, int _buildNumber) { + public void onLoad(@NonNull Job _job, int _buildNumber) { Item i = Jenkins.get().getItemByFullName(this.upstreamProject); if (!(i instanceof Job)) { // cannot initialize upstream causes return; } - Job j = (Job)i; + Job j = (Job) i; for (Cause c : this.upstreamCauses) { c.onLoad(j, upstreamBuild); } @@ -252,23 +254,23 @@ public abstract class Cause { /** * Returns true if this cause points to a build in the specified job. */ - public boolean pointsTo(Job j) { + public boolean pointsTo(Job j) { return j.getFullName().equals(upstreamProject); } /** * Returns true if this cause points to the specified build. */ - public boolean pointsTo(Run r) { - return r.getNumber()==upstreamBuild && pointsTo(r.getParent()); + public boolean pointsTo(Run r) { + return r.getNumber() == upstreamBuild && pointsTo(r.getParent()); } - @Exported(visibility=3) + @Exported(visibility = 3) public String getUpstreamProject() { return upstreamProject; } - @Exported(visibility=3) + @Exported(visibility = 3) public int getUpstreamBuild() { return upstreamBuild; } @@ -276,12 +278,12 @@ public abstract class Cause { /** * @since 1.505 */ - public @CheckForNull Run getUpstreamRun() { - Job job = Jenkins.get().getItemByFullName(upstreamProject, Job.class); + public @CheckForNull Run getUpstreamRun() { + Job job = Jenkins.get().getItemByFullName(upstreamProject, Job.class); return job != null ? job.getBuildByNumber(upstreamBuild) : null; } - @Exported(visibility=3) + @Exported(visibility = 3) public String getUpstreamUrl() { return upstreamUrl; } @@ -289,7 +291,7 @@ public abstract class Cause { public List getUpstreamCauses() { return upstreamCauses; } - + @Override public String getShortDescription() { return Messages.Cause_UpstreamCause_ShortDescription(upstreamProject, upstreamBuild); @@ -311,7 +313,7 @@ public abstract class Cause { listener.getLogger().println( Messages.Cause_UpstreamCause_ShortDescription( ModelHyperlinkNote.encodeTo('/' + upstreamUrl, upstreamProject), - ModelHyperlinkNote.encodeTo('/'+upstreamUrl+upstreamBuild, Integer.toString(upstreamBuild))) + ModelHyperlinkNote.encodeTo('/' + upstreamUrl + upstreamBuild, Integer.toString(upstreamBuild))) ); if (upstreamCauses != null && !upstreamCauses.isEmpty()) { indent(listener, depth); @@ -333,6 +335,7 @@ public abstract class Cause { public static class ConverterImpl extends XStream2.PassthruConverter { public ConverterImpl(XStream2 xstream) { super(xstream); } + @Override protected void callback(UpstreamCause uc, UnmarshallingContext context) { if (uc.upstreamCause != null) { uc.upstreamCauses.add(uc.upstreamCause); @@ -346,10 +349,12 @@ public abstract class Cause { @Override public String getShortDescription() { return "(deeply nested causes)"; } + @Override public String toString() { return "JENKINS-14814"; } - @Override public void onLoad(@NonNull Job _job, int _buildNumber) {} + + @Override public void onLoad(@NonNull Job _job, int _buildNumber) {} } } @@ -363,6 +368,7 @@ public abstract class Cause { @Deprecated public static class UserCause extends Cause { private String authenticationName; + public UserCause() { this.authenticationName = Jenkins.getAuthentication2().getName(); } @@ -372,10 +378,10 @@ public abstract class Cause { * @return User display name. * If the User does not exist, returns its ID. */ - @Exported(visibility=3) + @Exported(visibility = 3) public String getUserName() { - final User user = User.getById(authenticationName, false); - return user != null ? user.getDisplayName() : authenticationName; + final User user = User.getById(authenticationName, false); + return user != null ? user.getDisplayName() : authenticationName; } @Override @@ -386,7 +392,7 @@ public abstract class Cause { @Override public boolean equals(Object o) { return o instanceof UserCause && Arrays.equals(new Object[] {authenticationName}, - new Object[] {((UserCause)o).authenticationName}); + new Object[] {((UserCause) o).authenticationName}); } @Override @@ -427,7 +433,7 @@ public abstract class Cause { public String getUserId() { return userId; } - + @NonNull private String getUserIdOrUnknown() { return userId != null ? userId : User.getUnknown().getId(); @@ -485,17 +491,17 @@ public abstract class Cause { @Override public String getShortDescription() { - if(note != null) { + if (note != null) { return Messages.Cause_RemoteCause_ShortDescriptionWithNote(addr, note); } return Messages.Cause_RemoteCause_ShortDescription(addr); } - + @Exported(visibility = 3) public String getAddr() { return addr; } - + @Exported(visibility = 3) public String getNote() { return note; diff --git a/core/src/main/java/hudson/model/CauseAction.java b/core/src/main/java/hudson/model/CauseAction.java index fc225f3140af3ed27e90970bf65faa111852ad5d..eca42ffb69994030719a517f166f46a76b5def3f 100644 --- a/core/src/main/java/hudson/model/CauseAction.java +++ b/core/src/main/java/hudson/model/CauseAction.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import com.thoughtworks.xstream.converters.UnmarshallingContext; @@ -52,7 +53,7 @@ public class CauseAction implements FoldableAction, RunAction2 { @Deprecated private transient List causes; - private Map causeBag = new LinkedHashMap<>(); + private Map causeBag = new LinkedHashMap<>(); public CauseAction(Cause c) { this.causeBag.put(c, 1); @@ -64,6 +65,7 @@ public class CauseAction implements FoldableAction, RunAction2 { causeBag.put(c, cnt == null ? 1 : cnt + 1); } } + private void addCauses(Collection causes) { for (Cause cause : causes) { addCause(cause); @@ -90,10 +92,10 @@ public class CauseAction implements FoldableAction, RunAction2 { * to create an action with multiple causes use either of the constructors that support this; * to append causes retroactively to a build you must create a new {@link CauseAction} and replace the old */ - @Exported(visibility=2) + @Exported(visibility = 2) public List getCauses() { List r = new ArrayList<>(); - for (Map.Entry entry : causeBag.entrySet()) { + for (Map.Entry entry : causeBag.entrySet()) { r.addAll(Collections.nCopies(entry.getValue(), entry.getKey())); } return Collections.unmodifiableList(r); @@ -129,7 +131,7 @@ public class CauseAction implements FoldableAction, RunAction2 { * Get list of causes with duplicates combined into counters. * @return Map of Cause to number of occurrences of that Cause */ - public Map getCauseCounts() { + public Map getCauseCounts() { return Collections.unmodifiableMap(causeBag); } @@ -145,7 +147,7 @@ public class CauseAction implements FoldableAction, RunAction2 { return causeBag.keySet().iterator().next().getShortDescription(); } - @Override public void onLoad(Run owner) { + @Override public void onLoad(Run owner) { for (Cause c : causeBag.keySet()) { if (c != null) { c.onLoad(owner); @@ -156,7 +158,7 @@ public class CauseAction implements FoldableAction, RunAction2 { /** * When hooked up to build, notify {@link Cause}s. */ - @Override public void onAttached(Run owner) { + @Override public void onAttached(Run owner) { for (Cause c : causeBag.keySet()) { if (c != null) { c.onAddedTo(owner); @@ -167,7 +169,7 @@ public class CauseAction implements FoldableAction, RunAction2 { @Override public void foldIntoExisting(hudson.model.Queue.Item item, Task owner, List otherActions) { CauseAction existing = item.getAction(CauseAction.class); - if (existing!=null) { + if (existing != null) { existing.addCauses(getCauses()); return; } @@ -177,6 +179,7 @@ public class CauseAction implements FoldableAction, RunAction2 { public static class ConverterImpl extends XStream2.PassthruConverter { public ConverterImpl(XStream2 xstream) { super(xstream); } + @Override protected void callback(CauseAction ca, UnmarshallingContext context) { // if we are being read in from an older version if (ca.cause != null) { diff --git a/core/src/main/java/hudson/model/CheckPoint.java b/core/src/main/java/hudson/model/CheckPoint.java index 773421a17eb83315b46c4ac2d3c0ac53147669cb..b7a7fdb9da905aa5bce42efd0a1d4a332b0a68ce 100644 --- a/core/src/main/java/hudson/model/CheckPoint.java +++ b/core/src/main/java/hudson/model/CheckPoint.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import edu.umd.cs.findbugs.annotations.NonNull; @@ -60,7 +61,7 @@ import hudson.tasks.Recorder; * depend on its earlier result. * * @author Kohsuke Kawaguchi - * @see BuildStep#getRequiredMonitorService() + * @see BuildStep#getRequiredMonitorService() * @since 1.319 */ public final class CheckPoint { @@ -87,7 +88,7 @@ public final class CheckPoint { @Override public boolean equals(Object that) { if (that == null || getClass() != that.getClass()) return false; - return identity== ((CheckPoint) that).identity; + return identity == ((CheckPoint) that).identity; } @Override @@ -97,7 +98,7 @@ public final class CheckPoint { @Override public String toString() { - return "Check point "+internalName; + return "Check point " + internalName; } /** @@ -140,7 +141,7 @@ public final class CheckPoint { * This method can be only called from an {@link Executor} thread. * * @throws InterruptedException - * If the build (represented by the calling executor thread) is aborted while it's waiting. + * If the build (represented by the calling executor thread) is aborted while it's waiting. */ public void block() throws InterruptedException { Run.waitForCheckpoint(this, null, null); diff --git a/core/src/main/java/hudson/model/ChoiceParameterDefinition.java b/core/src/main/java/hudson/model/ChoiceParameterDefinition.java index 79570bd99511e403b4e37cb41ceadf43acfdd7e3..a2ac42447b0275b5b30572cdfd8734811691269d 100644 --- a/core/src/main/java/hudson/model/ChoiceParameterDefinition.java +++ b/core/src/main/java/hudson/model/ChoiceParameterDefinition.java @@ -202,7 +202,7 @@ public class ChoiceParameterDefinition extends SimpleParameterDefinition { return Objects.equals(defaultValue, other.defaultValue); } - @Extension @Symbol({"choice","choiceParam"}) + @Extension @Symbol({"choice", "choiceParam"}) public static class DescriptorImpl extends ParameterDescriptor { @Override public String getDisplayName() { diff --git a/core/src/main/java/hudson/model/Computer.java b/core/src/main/java/hudson/model/Computer.java index 8c1ce41e1aae0039af1e3bd9702832d752e05146..b143a938778670513a776462dd66256a1abefef1 100644 --- a/core/src/main/java/hudson/model/Computer.java +++ b/core/src/main/java/hudson/model/Computer.java @@ -23,6 +23,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST; @@ -261,7 +262,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces /** * Returns list of all boxes {@link ComputerPanelBox}s. */ - public List getComputerPanelBoxs(){ + public List getComputerPanelBoxs() { return ComputerPanelBox.all(this); } @@ -281,7 +282,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces return Collections.unmodifiableList(result); } - @SuppressWarnings({"ConstantConditions","deprecation"}) + @SuppressWarnings({"ConstantConditions", "deprecation"}) @Override public void addAction(@NonNull Action a) { if (a == null) { @@ -299,7 +300,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces * @see #relocateOldLogs() */ public @NonNull File getLogFile() { - return new File(getLogDir(),"slave.log"); + return new File(getLogDir(), "slave.log"); } /** @@ -310,7 +311,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces * @since 1.613 */ protected @NonNull File getLogDir() { - File dir = new File(Jenkins.get().getRootDir(),"logs/slaves/"+nodeName); + File dir = new File(Jenkins.get().getRootDir(), "logs/slaves/" + nodeName); synchronized (logDirLock) { try { IOUtils.mkdirs(dir); @@ -373,7 +374,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces return ""; } // fetch the localized string for "Disconnected By" - String gsub_base = hudson.slaves.Messages.SlaveComputer_DisconnectedBy("",""); + String gsub_base = hudson.slaves.Messages.SlaveComputer_DisconnectedBy("", ""); // regex to remove commented reason base string String gsub1 = "^" + gsub_base + "[\\w\\W]* \\: "; // regex to remove non-commented reason base string @@ -407,7 +408,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces /** * If {@link #getChannel()}==null, attempts to relaunch the agent. */ - public abstract void doLaunchSlaveAgent( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException; + public abstract void doLaunchSlaveAgent(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException; /** * @deprecated since 2009-01-06. Use {@link #connect(boolean)} @@ -502,10 +503,10 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces public Future disconnect(OfflineCause cause) { recordTermination(); offlineCause = cause; - if (Util.isOverridden(Computer.class,getClass(),"disconnect")) + if (Util.isOverridden(Computer.class, getClass(), "disconnect")) return disconnect(); // legacy subtypes that extend disconnect(). - connectTime=0; + connectTime = 0; return Futures.precomputed(null); } @@ -518,11 +519,11 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces @Deprecated public Future disconnect() { recordTermination(); - if (Util.isOverridden(Computer.class,getClass(),"disconnect",OfflineCause.class)) + if (Util.isOverridden(Computer.class, getClass(), "disconnect", OfflineCause.class)) // if the subtype already derives disconnect(OfflineCause), delegate to it return disconnect(null); - connectTime=0; + connectTime = 0; return Futures.precomputed(null); } @@ -618,7 +619,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces @Exported public boolean isOffline() { - return temporarilyOffline || getChannel()==null; + return temporarilyOffline || getChannel() == null; } public final boolean isOnline() { @@ -688,7 +689,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces */ @Deprecated public void setTemporarilyOffline(boolean temporarilyOffline) { - setTemporarilyOffline(temporarilyOffline,null); + setTemporarilyOffline(temporarilyOffline, null); } /** @@ -788,7 +789,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces } public RunList getBuilds() { - return RunList.fromJobs((Iterable)Jenkins.get().allItems(Job.class)).node(getNode()); + return RunList.fromJobs((Iterable) Jenkins.get().allItems(Job.class)).node(getNode()); } /** @@ -796,8 +797,8 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces * configuration is updated. */ protected void setNode(Node node) { - assert node!=null; - if(node instanceof Slave) + assert node != null; + if (node instanceof Slave) this.nodeName = node.getNodeName(); else this.nodeName = null; @@ -879,9 +880,9 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces @GuardedBy("hudson.model.Queue.lock") private void setNumExecutors(int n) { this.numExecutors = n; - final int diff = executors.size()-n; + final int diff = executors.size() - n; - if (diff>0) { + if (diff > 0) { // we have too many executors // send signal to all idle executors to potentially kill them off // need the Queue maintenance lock held to prevent concurrent job assignment on the idle executors @@ -894,7 +895,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces }); } - if (diff<0) { + if (diff < 0) { // if the number is increased, add new ones addNewExecutorIfNecessary(); } @@ -930,7 +931,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces public int countIdle() { int n = 0; for (Executor e : executors) { - if(e.isIdle()) + if (e.isIdle()) n++; } return n; @@ -940,7 +941,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces * Returns the number of {@link Executor}s that are doing some work right now. */ public final int countBusy() { - return countExecutors()-countIdle(); + return countExecutors() - countIdle(); } /** @@ -994,14 +995,14 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces // The size may change while we are populating, but let's start with a reasonable guess to minimize resizing List result = new ArrayList<>(executors.size() + oneOffExecutors.size()); int index = 0; - for (Executor e: executors) { + for (Executor e : executors) { if (e.isDisplayCell()) { result.add(new DisplayExecutor(Integer.toString(index + 1), String.format("executors/%d", index), e)); } index++; } index = 0; - for (OneOffExecutor e: oneOffExecutors) { + for (OneOffExecutor e : oneOffExecutors) { if (e.isDisplayCell()) { result.add(new DisplayExecutor("", String.format("oneOffExecutors/%d", index), e)); } @@ -1018,7 +1019,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces if (!oneOffExecutors.isEmpty()) return false; for (Executor e : executors) - if(!e.isIdle()) + if (!e.isIdle()) return false; return true; } @@ -1028,7 +1029,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces */ public final boolean isPartiallyIdle() { for (Executor e : executors) - if(e.isIdle()) + if (e.isIdle()) return true; return false; } @@ -1141,9 +1142,9 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces /** * Expose monitoring data for the remote API. */ - @Exported(inline=true) - public Map getMonitorData() { - Map r = new HashMap<>(); + @Exported(inline = true) + public Map getMonitorData() { + Map r = new HashMap<>(); if (hasPermission(CONNECT)) { for (NodeMonitor monitor : NodeMonitor.getAll()) r.put(monitor.getClass().getName(), monitor.data(this)); @@ -1155,7 +1156,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces * Gets the system properties of the JVM on this computer. * If this is the master, it returns the system property of the master computer. */ - public Map getSystemProperties() throws IOException, InterruptedException { + public Map getSystemProperties() throws IOException, InterruptedException { return RemotingDiagnostics.getSystemProperties(getChannel()); } @@ -1164,7 +1165,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces * Use {@link #getEnvironment()} instead. */ @Deprecated - public Map getEnvVars() throws IOException, InterruptedException { + public Map getEnvVars() throws IOException, InterruptedException { return getEnvironment(); } @@ -1193,19 +1194,19 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces EnvVars env = new EnvVars(); Node node = getNode(); - if (node==null) return env; // bail out + if (node == null) return env; // bail out - for (NodeProperty nodeProperty: Jenkins.get().getGlobalNodeProperties()) { - nodeProperty.buildEnvVars(env,listener); + for (NodeProperty nodeProperty : Jenkins.get().getGlobalNodeProperties()) { + nodeProperty.buildEnvVars(env, listener); } - for (NodeProperty nodeProperty: node.getNodeProperties()) { - nodeProperty.buildEnvVars(env,listener); + for (NodeProperty nodeProperty : node.getNodeProperties()) { + nodeProperty.buildEnvVars(env, listener); } // TODO: hmm, they don't really belong String rootUrl = Jenkins.get().getRootUrl(); - if(rootUrl!=null) { + if (rootUrl != null) { env.put("HUDSON_URL", rootUrl); // Legacy. env.put("JENKINS_URL", rootUrl); } @@ -1218,7 +1219,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces * @return * key is the thread name, and the value is the pre-formatted dump. */ - public Map getThreadDump() throws IOException, InterruptedException { + public Map getThreadDump() throws IOException, InterruptedException { return RemotingDiagnostics.getThreadDump(getChannel()); } @@ -1226,7 +1227,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces * Obtains the heap dump. */ public HeapDump getHeapDump() throws IOException { - return new HeapDump(this,getChannel()); + return new HeapDump(this, getChannel()); } /** @@ -1252,21 +1253,21 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces * because the agent is behind the firewall, etc.) */ public String getHostName() throws IOException, InterruptedException { - if(hostNameCached) + if (hostNameCached) // in the worst case we end up having multiple threads computing the host name simultaneously, but that's not harmful, just wasteful. return cachedHostName; VirtualChannel channel = getChannel(); - if(channel==null) return null; // can't compute right now + if (channel == null) return null; // can't compute right now - for( String address : channel.call(new ListPossibleNames())) { + for (String address : channel.call(new ListPossibleNames())) { try { InetAddress ia = InetAddress.getByName(address); - if(!(ia instanceof Inet4Address)) { + if (!(ia instanceof Inet4Address)) { LOGGER.log(Level.FINE, "{0} is not an IPv4 address", address); continue; } - if(!ComputerPinger.checkIsReachable(ia, 3)) { + if (!ComputerPinger.checkIsReachable(ia, 3)) { LOGGER.log(Level.FINE, "{0} didn't respond to ping", address); continue; } @@ -1301,7 +1302,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces oneOffExecutors.remove(e); } - private static class ListPossibleNames extends MasterToSlaveCallable,IOException> { + private static class ListPossibleNames extends MasterToSlaveCallable, IOException> { /** * In the normal case we would use {@link Computer} as the logger's name, however to * do that we would have to send the {@link Computer} class over to the remote classloader @@ -1324,12 +1325,12 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces Enumeration e = ni.getInetAddresses(); while (e.hasMoreElements()) { InetAddress ia = e.nextElement(); - if(ia.isLoopbackAddress()) { + if (ia.isLoopbackAddress()) { LOGGER.log(Level.FINE, "{0} is a loopback address", ia); continue; } - if(!(ia instanceof Inet4Address)) { + if (!(ia instanceof Inet4Address)) { LOGGER.log(Level.FINE, "{0} is not an IPv4 address", ia); continue; } @@ -1340,14 +1341,16 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces } return names; } + private static final long serialVersionUID = 1L; } - private static class GetFallbackName extends MasterToSlaveCallable { + private static class GetFallbackName extends MasterToSlaveCallable { @Override public String call() throws IOException { return SystemProperties.getString("host.name"); } + private static final long serialVersionUID = 1L; } @@ -1364,12 +1367,12 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces // // @Restricted(DoNotUse.class) - public void doRssAll( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { + public void doRssAll(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { RSS.rss(req, rsp, "Jenkins:" + getDisplayName() + " (all builds)", getUrl(), getBuilds()); } @Restricted(DoNotUse.class) - public void doRssFailed(StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { + public void doRssFailed(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { RSS.rss(req, rsp, "Jenkins:" + getDisplayName() + " (failed builds)", getUrl(), getBuilds().failureOnly()); } @@ -1380,7 +1383,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces * @since 2.215 */ @Restricted(DoNotUse.class) - public void doRssLatest( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { + public void doRssLatest(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { final List lastBuilds = new ArrayList<>(); for (AbstractProject p : Jenkins.get().allItems(AbstractProject.class)) { if (p.getLastBuild() != null) { @@ -1397,14 +1400,14 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces @RequirePOST public HttpResponse doToggleOffline(@QueryParameter String offlineMessage) throws IOException, ServletException { - if(!temporarilyOffline) { + if (!temporarilyOffline) { checkPermission(DISCONNECT); offlineMessage = Util.fixEmptyAndTrim(offlineMessage); setTemporarilyOffline(!temporarilyOffline, new OfflineCause.UserCause(User.current(), offlineMessage)); } else { checkPermission(CONNECT); - setTemporarilyOffline(!temporarilyOffline,null); + setTemporarilyOffline(!temporarilyOffline, null); } return HttpResponses.redirectToDot(); } @@ -1425,7 +1428,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces /** * Dumps the contents of the export table. */ - public void doDumpExportTable( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, InterruptedException { + public void doDumpExportTable(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, InterruptedException { // this is a debug probe and may expose sensitive information checkPermission(Jenkins.ADMINISTER); @@ -1445,7 +1448,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces } } - private static final class DumpExportTableTask extends MasterToSlaveCallable { + private static final class DumpExportTableTask extends MasterToSlaveCallable { @Override public String call() throws IOException { final Channel ch = getChannelOrFail(); @@ -1480,7 +1483,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces * Accepts the update to the node configuration. */ @POST - public void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException { + public void doConfigSubmit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException { checkPermission(CONFIGURE); String proposedName = Util.fixEmptyAndTrim(req.getSubmittedForm().getString("name")); @@ -1497,7 +1500,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces } String nExecutors = req.getSubmittedForm().getString("numExecutors"); - if (StringUtils.isBlank(nExecutors) || Integer.parseInt(nExecutors)<=0) { + if (StringUtils.isBlank(nExecutors) || Integer.parseInt(nExecutors) <= 0) { throw new FormException(Messages.Slave_InvalidConfig_Executors(nodeName), "numExecutors"); } @@ -1547,7 +1550,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces if (previous == null) { throw HttpResponses.notFound(); } - Node result = (Node)Jenkins.XSTREAM2.fromXML(source); + Node result = (Node) Jenkins.XSTREAM2.fromXML(source); if (previous.getClass() != result.getClass()) { // ensure node type doesn't change throw HttpResponses.errorWithoutStack(SC_BAD_REQUEST, "Node types do not match"); @@ -1591,7 +1594,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces /** * Handles incremental log. */ - public void doProgressiveLog( StaplerRequest req, StaplerResponse rsp) throws IOException { + public void doProgressiveLog(StaplerRequest req, StaplerResponse rsp) throws IOException { getLogText().doProgressText(req, rsp); } @@ -1641,10 +1644,10 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces */ @CLIResolver public static Computer resolveForCLI( - @Argument(required=true,metaVar="NAME",usage="Agent name, or empty string for built-in node") String name) throws CmdLineException { + @Argument(required = true, metaVar = "NAME", usage = "Agent name, or empty string for built-in node") String name) throws CmdLineException { Jenkins h = Jenkins.get(); Computer item = h.getComputer(name); - if (item==null) { + if (item == null) { List names = ComputerSet.getComputerNames(); String adv = EditDistance.findNearest(name, names); throw new IllegalArgumentException(adv == null ? @@ -1671,7 +1674,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces /*package*/ static void relocateOldLogs(File dir) { final Pattern logfile = Pattern.compile("slave-(.*)\\.log(\\.[0-9]+)?"); File[] logfiles = dir.listFiles((dir1, name) -> logfile.matcher(name).matches()); - if (logfiles==null) return; + if (logfiles == null) return; for (File f : logfiles) { Matcher m = logfile.matcher(f.getName()); @@ -1680,7 +1683,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces try { Util.createDirectories(newLocation.getParentFile().toPath()); Files.move(f.toPath(), newLocation.toPath(), StandardCopyOption.REPLACE_EXISTING); - LOGGER.log(Level.INFO, "Relocated log file {0} to {1}",new Object[] {f.getPath(),newLocation.getPath()}); + LOGGER.log(Level.INFO, "Relocated log file {0} to {1}", new Object[] {f.getPath(), newLocation.getPath()}); } catch (IOException | InvalidPathException e) { LOGGER.log(Level.WARNING, e, () -> "Cannot relocate log file " + f.getPath() + " to " + newLocation.getPath()); } @@ -1773,6 +1776,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces */ public static class TerminationRequest extends RuntimeException { private final long when; + public TerminationRequest(String message) { super(message); this.when = System.currentTimeMillis(); @@ -1789,7 +1793,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces } } - public static final PermissionGroup PERMISSIONS = new PermissionGroup(Computer.class,Messages._Computer_Permissions_Title()); + public static final PermissionGroup PERMISSIONS = new PermissionGroup(Computer.class, Messages._Computer_Permissions_Title()); public static final Permission CONFIGURE = new Permission( PERMISSIONS, diff --git a/core/src/main/java/hudson/model/ComputerPanelBox.java b/core/src/main/java/hudson/model/ComputerPanelBox.java index d5e7e45cba50ee9779a3c55ce782fa101834cebe..f75fde52d79e40ff572d29d1dc53125ad7dd5beb 100644 --- a/core/src/main/java/hudson/model/ComputerPanelBox.java +++ b/core/src/main/java/hudson/model/ComputerPanelBox.java @@ -15,19 +15,19 @@ import java.util.List; * @see hudson.model.Computer#getComputerPanelBoxs() */ -public abstract class ComputerPanelBox implements ExtensionPoint{ - +public abstract class ComputerPanelBox implements ExtensionPoint { + private Computer computer; - - - public void setComputer(Computer computer){ + + + public void setComputer(Computer computer) { this.computer = computer; } - - public Computer getComputer(){ + + public Computer getComputer() { return computer; } - + /** * Create boxes for the given computer in its page. * @@ -38,7 +38,7 @@ public abstract class ComputerPanelBox implements ExtensionPoint{ */ public static List all(Computer computer) { List boxs = new ArrayList<>(); - for(ComputerPanelBox box: ExtensionList.lookup(ComputerPanelBox.class)){ + for (ComputerPanelBox box : ExtensionList.lookup(ComputerPanelBox.class)) { box.setComputer(computer); boxs.add(box); } diff --git a/core/src/main/java/hudson/model/ComputerPinger.java b/core/src/main/java/hudson/model/ComputerPinger.java index 38894a2d5edc21e6129e6b5148baf44d38d0fd35..8aaf47a843eaf3f854d137eb48832368361495b5 100644 --- a/core/src/main/java/hudson/model/ComputerPinger.java +++ b/core/src/main/java/hudson/model/ComputerPinger.java @@ -48,7 +48,7 @@ public abstract class ComputerPinger implements ExtensionPoint { return false; } - + /** * Default pinger - use Java built-in functionality. This doesn't always work, * a host may be reachable even if this returns false. @@ -57,7 +57,7 @@ public abstract class ComputerPinger implements ExtensionPoint { public static class BuiltInComputerPinger extends ComputerPinger { @Override public boolean isReachable(InetAddress ia, int timeout) throws IOException { - return ia.isReachable((int)TimeUnit.SECONDS.toMillis(timeout)); + return ia.isReachable((int) TimeUnit.SECONDS.toMillis(timeout)); } } diff --git a/core/src/main/java/hudson/model/ComputerSet.java b/core/src/main/java/hudson/model/ComputerSet.java index 770e25814c3ef20b0cd09bd41bf3af937d7ef246..ecef09a90fc3079b9fe310dfc954b6aad9075120 100644 --- a/core/src/main/java/hudson/model/ComputerSet.java +++ b/core/src/main/java/hudson/model/ComputerSet.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import static hudson.init.InitMilestone.JOB_CONFIG_ADAPTED; @@ -86,7 +87,7 @@ public final class ComputerSet extends AbstractModelObject implements Describabl } }; - private static final DescribableList> monitors + private static final DescribableList> monitors = new DescribableList<>(MONITORS_OWNER); @Override @@ -104,7 +105,7 @@ public final class ComputerSet extends AbstractModelObject implements Describabl return monitors.toList(); } - @Exported(name="computer",inline=true) + @Exported(name = "computer", inline = true) public Computer[] get_all() { return Jenkins.get().getComputers(); } @@ -121,22 +122,22 @@ public final class ComputerSet extends AbstractModelObject implements Describabl /** * Exposing {@link NodeMonitor#all()} for Jelly binding. */ - public DescriptorExtensionList> getNodeMonitorDescriptors() { + public DescriptorExtensionList> getNodeMonitorDescriptors() { return NodeMonitor.all(); } - public static DescribableList> getMonitors() { + public static DescribableList> getMonitors() { return monitors; } /** * Returns a subset pf {@link #getMonitors()} that are {@linkplain NodeMonitor#isIgnored() not ignored}. */ - public static Map,NodeMonitor> getNonIgnoredMonitors() { - Map,NodeMonitor> r = new HashMap<>(); + public static Map, NodeMonitor> getNonIgnoredMonitors() { + Map, NodeMonitor> r = new HashMap<>(); for (NodeMonitor m : monitors) { - if(!m.isIgnored()) - r.put(m.getDescriptor(),m); + if (!m.isIgnored()) + r.put(m.getDescriptor(), m); } return r; } @@ -167,9 +168,9 @@ public final class ComputerSet extends AbstractModelObject implements Describabl */ @Exported public int getTotalExecutors() { - int r=0; + int r = 0; for (Computer c : get_all()) { - if(c.isOnline()) + if (c.isOnline()) r += c.countExecutors(); } return r; @@ -180,9 +181,9 @@ public final class ComputerSet extends AbstractModelObject implements Describabl */ @Exported public int getBusyExecutors() { - int r=0; + int r = 0; for (Computer c : get_all()) { - if(c.isOnline()) + if (c.isOnline()) r += c.countBusy(); } return r; @@ -192,9 +193,9 @@ public final class ComputerSet extends AbstractModelObject implements Describabl * {@code getTotalExecutors()-getBusyExecutors()}, plus executors that are being brought online. */ public int getIdleExecutors() { - int r=0; + int r = 0; for (Computer c : get_all()) - if((c.isOnline() || c.isConnecting()) && c.isAcceptingTasks()) + if ((c.isOnline() || c.isConnecting()) && c.isAcceptingTasks()) r += c.countIdle(); return r; } @@ -212,8 +213,8 @@ public final class ComputerSet extends AbstractModelObject implements Describabl public void do_launchAll(StaplerRequest req, StaplerResponse rsp) throws IOException { Jenkins.get().checkPermission(Jenkins.ADMINISTER); - for(Computer c : get_all()) { - if(c.isLaunchSupported()) + for (Computer c : get_all()) { + if (c.isLaunchSupported()) c.connect(true); } rsp.sendRedirect("."); @@ -225,7 +226,7 @@ public final class ComputerSet extends AbstractModelObject implements Describabl * TODO: ajax on the client side to wait until the update completion might be nice. */ @RequirePOST - public void doUpdateNow( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { + public void doUpdateNow(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { Jenkins.get().checkPermission(Jenkins.MANAGE); for (NodeMonitor nodeMonitor : NodeMonitor.getAll()) { @@ -242,17 +243,17 @@ public final class ComputerSet extends AbstractModelObject implements Describabl * First check point in creating a new agent. */ @RequirePOST - public synchronized void doCreateItem( StaplerRequest req, StaplerResponse rsp, + public synchronized void doCreateItem(StaplerRequest req, StaplerResponse rsp, @QueryParameter String name, @QueryParameter String mode, - @QueryParameter String from ) throws IOException, ServletException { + @QueryParameter String from) throws IOException, ServletException { final Jenkins app = Jenkins.get(); app.checkPermission(Computer.CREATE); - if(mode!=null && mode.equals("copy")) { + if (mode != null && mode.equals("copy")) { name = checkName(name); Node src = app.getNode(from); - if(src==null) { + if (src == null) { if (Util.fixEmpty(from) == null) { throw new Failure(Messages.ComputerSet_SpecifySlaveToCopy()); } else { @@ -269,7 +270,7 @@ public final class ComputerSet extends AbstractModelObject implements Describabl app.addNode(result); // send the browser to the config page - rsp.sendRedirect2(result.getNodeName()+"/configure"); + rsp.sendRedirect2(result.getNodeName() + "/configure"); } else { // proceed to step 2 if (mode == null) { @@ -280,7 +281,7 @@ public final class ComputerSet extends AbstractModelObject implements Describabl if (d == null) { throw new Failure("No node type ‘" + mode + "’ is known"); } - d.handleNewNodePage(this,name,req,rsp); + d.handleNewNodePage(this, name, req, rsp); } } @@ -288,9 +289,9 @@ public final class ComputerSet extends AbstractModelObject implements Describabl * Really creates a new agent. */ @POST - public synchronized void doDoCreateItem( StaplerRequest req, StaplerResponse rsp, + public synchronized void doDoCreateItem(StaplerRequest req, StaplerResponse rsp, @QueryParameter String name, - @QueryParameter String type ) throws IOException, ServletException, FormException { + @QueryParameter String type) throws IOException, ServletException, FormException { final Jenkins app = Jenkins.get(); app.checkPermission(Computer.CREATE); String fixedName = Util.fixEmptyAndTrim(name); @@ -312,13 +313,13 @@ public final class ComputerSet extends AbstractModelObject implements Describabl * @return trimmed name if valid; throws ParseException if not */ public String checkName(String name) throws Failure { - if(name==null) + if (name == null) throw new Failure("Query parameter 'name' is required"); name = name.trim(); Jenkins.checkGoodName(name); - if(Jenkins.get().getNode(name)!=null) + if (Jenkins.get().getNode(name) != null) throw new Failure(Messages.ComputerSet_SlaveAlreadyExists(name)); // looks good @@ -331,7 +332,7 @@ public final class ComputerSet extends AbstractModelObject implements Describabl public FormValidation doCheckName(@QueryParameter String value) throws IOException, ServletException { Jenkins.get().checkPermission(Computer.CREATE); - if(Util.fixEmpty(value)==null) + if (Util.fixEmpty(value) == null) return FormValidation.ok(); try { @@ -346,17 +347,17 @@ public final class ComputerSet extends AbstractModelObject implements Describabl * Accepts submission from the configuration page. */ @POST - public synchronized HttpResponse doConfigSubmit( StaplerRequest req) throws IOException, ServletException, FormException { + public synchronized HttpResponse doConfigSubmit(StaplerRequest req) throws IOException, ServletException, FormException { BulkChange bc = new BulkChange(MONITORS_OWNER); try { Jenkins.get().checkPermission(Jenkins.MANAGE); - monitors.rebuild(req,req.getSubmittedForm(),getNodeMonitorDescriptors()); + monitors.rebuild(req, req.getSubmittedForm(), getNodeMonitorDescriptors()); // add in the rest of instances are ignored instances for (Descriptor d : NodeMonitor.all()) - if(monitors.get(d)==null) { + if (monitors.get(d) == null) { NodeMonitor i = createDefaultInstance(d, true); - if(i!=null) + if (i != null) monitors.add(i); } @@ -375,7 +376,7 @@ public final class ComputerSet extends AbstractModelObject implements Describabl * {@link NodeMonitor}s are persisted in this file. */ private static XmlFile getConfigFile() { - return new XmlFile(new File(Jenkins.get().getRootDir(),"nodeMonitors.xml")); + return new XmlFile(new File(Jenkins.get().getRootDir(), "nodeMonitors.xml")); } public Api getApi() { @@ -409,7 +410,7 @@ public final class ComputerSet extends AbstractModelObject implements Describabl */ public static void initialize() {} - @Initializer(after= JOB_CONFIG_ADAPTED) + @Initializer(after = JOB_CONFIG_ADAPTED) public static void init() { // start monitoring nodes, although there's no hurry. Timer.get().schedule(new SafeTimerTask() { @@ -439,14 +440,14 @@ public final class ComputerSet extends AbstractModelObject implements Describabl static { try { - DescribableList> r + DescribableList> r = new DescribableList<>(Saveable.NOOP); // load persisted monitors XmlFile xf = getConfigFile(); - if(xf.exists()) { - DescribableList> persisted = - (DescribableList>) xf.read(); + if (xf.exists()) { + DescribableList> persisted = + (DescribableList>) xf.read(); List sanitized = new ArrayList<>(); for (NodeMonitor nm : persisted) { try { @@ -461,9 +462,9 @@ public final class ComputerSet extends AbstractModelObject implements Describabl // if we have any new monitors, let's add them for (Descriptor d : NodeMonitor.all()) - if(r.get(d)==null) { - NodeMonitor i = createDefaultInstance(d,false); - if(i!=null) + if (r.get(d) == null) { + NodeMonitor i = createDefaultInstance(d, false); + if (i != null) r.add(i); } monitors.replaceBy(r.toList()); @@ -478,7 +479,7 @@ public final class ComputerSet extends AbstractModelObject implements Describabl nm.setIgnored(ignored); return nm; } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) { - LOGGER.log(Level.SEVERE, "Failed to instantiate "+d.clazz,e); + LOGGER.log(Level.SEVERE, "Failed to instantiate " + d.clazz, e); } return null; } diff --git a/core/src/main/java/hudson/model/DependencyGraph.java b/core/src/main/java/hudson/model/DependencyGraph.java index 79c8ed7fbf9b8254d59e8f8a6749fee1dc5c3278..3788e2aefddca90c5f44bcdf3c3e7c2a62dbac8e 100644 --- a/core/src/main/java/hudson/model/DependencyGraph.java +++ b/core/src/main/java/hudson/model/DependencyGraph.java @@ -22,6 +22,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import hudson.security.ACL; @@ -72,20 +73,20 @@ public class DependencyGraph implements Comparator { private boolean built; - private Comparator> topologicalOrder; - private List> topologicallySorted; + private Comparator> topologicalOrder; + private List> topologicallySorted; /** * Builds the dependency graph. */ public DependencyGraph() { } - + public void build() { // Set full privileges while computing to avoid missing any projects the current user cannot see. - try (ACLContext ctx = ACL.as2(ACL.SYSTEM2)){ + try (ACLContext ctx = ACL.as2(ACL.SYSTEM2)) { this.computationalData = new HashMap<>(); - for( AbstractProject p : Jenkins.get().allItems(AbstractProject.class) ) + for (AbstractProject p : Jenkins.get().allItems(AbstractProject.class)) p.buildDependencyGraph(this); forward = finalize(forward); @@ -119,12 +120,12 @@ public class DependencyGraph implements Comparator { List> sccs = g.getStronglyConnectedComponents(); - final Map topoOrder = new HashMap<>(); + final Map topoOrder = new HashMap<>(); topologicallySorted = new ArrayList<>(); - int idx=0; + int idx = 0; for (SCC scc : sccs) { for (AbstractProject n : scc) { - topoOrder.put(n,idx++); + topoOrder.put(n, idx++); topologicallySorted.add(n); } } @@ -167,7 +168,7 @@ public class DependencyGraph implements Comparator { * can be empty but never null. */ public List getDownstream(AbstractProject p) { - return get(forward,p,false); + return get(forward, p, false); } /** @@ -177,12 +178,12 @@ public class DependencyGraph implements Comparator { * can be empty but never null. */ public List getUpstream(AbstractProject p) { - return get(backward,p,true); + return get(backward, p, true); } private List get(Map> map, AbstractProject src, boolean up) { List v = map.get(src); - if(v==null) return Collections.emptyList(); + if (v == null) return Collections.emptyList(); List result = new ArrayList<>(v.size()); for (DependencyGroup d : v) result.add(up ? d.getUpstreamProject() : d.getDownstreamProject()); return result; @@ -192,19 +193,19 @@ public class DependencyGraph implements Comparator { * @since 1.341 */ public List getDownstreamDependencies(AbstractProject p) { - return get(forward,p); + return get(forward, p); } /** * @since 1.341 */ public List getUpstreamDependencies(AbstractProject p) { - return get(backward,p); + return get(backward, p); } private List get(Map> map, AbstractProject src) { List v = map.get(src); - if(v==null) { + if (v == null) { return Collections.emptyList(); } else { List builder = new ArrayList<>(); @@ -221,16 +222,16 @@ public class DependencyGraph implements Comparator { */ @Deprecated public void addDependency(AbstractProject upstream, AbstractProject downstream) { - addDependency(new Dependency(upstream,downstream)); + addDependency(new Dependency(upstream, downstream)); } /** * Called during the dependency graph build phase to add a dependency edge. */ public void addDependency(Dependency dep) { - if(built) + if (built) throw new IllegalStateException(); - add(forward,dep.getUpstreamProject(),dep); + add(forward, dep.getUpstreamProject(), dep); add(backward, dep.getDownstreamProject(), dep); } @@ -240,7 +241,7 @@ public class DependencyGraph implements Comparator { @Deprecated public void addDependency(AbstractProject upstream, Collection downstream) { for (AbstractProject p : downstream) - addDependency(upstream,p); + addDependency(upstream, p); } /** @@ -249,7 +250,7 @@ public class DependencyGraph implements Comparator { @Deprecated public void addDependency(Collection upstream, AbstractProject downstream) { for (AbstractProject p : upstream) - addDependency(p,downstream); + addDependency(p, downstream); } /** @@ -259,7 +260,7 @@ public class DependencyGraph implements Comparator { for (Object o : possibleDependecyDeclarers) { if (o instanceof DependencyDeclarer) { DependencyDeclarer dd = (DependencyDeclarer) o; - dd.buildDependencyGraph(upstream,this); + dd.buildDependencyGraph(upstream, this); } } } @@ -277,11 +278,11 @@ public class DependencyGraph implements Comparator { queue.addAll(getDownstream(src)); queue.remove(dst); - while(!queue.isEmpty()) { + while (!queue.isEmpty()) { AbstractProject p = queue.pop(); - if(p==dst) + if (p == dst) return true; - if(visited.add(p)) + if (visited.add(p)) queue.addAll(getDownstream(p)); } @@ -292,14 +293,14 @@ public class DependencyGraph implements Comparator { * Gets all the direct and indirect upstream dependencies of the given project. */ public Set getTransitiveUpstream(AbstractProject src) { - return getTransitive(backward,src,true); + return getTransitive(backward, src, true); } /** * Gets all the direct and indirect downstream dependencies of the given project. */ public Set getTransitiveDownstream(AbstractProject src) { - return getTransitive(forward,src,false); + return getTransitive(forward, src, false); } private Set getTransitive(Map> direction, AbstractProject src, boolean up) { @@ -308,11 +309,11 @@ public class DependencyGraph implements Comparator { queue.add(src); - while(!queue.isEmpty()) { + while (!queue.isEmpty()) { AbstractProject p = queue.pop(); - for (AbstractProject child : get(direction,p,up)) { - if(visited.add(child)) + for (AbstractProject child : get(direction, p, up)) { + if (visited.add(child)) queue.add(child); } } @@ -336,7 +337,7 @@ public class DependencyGraph implements Comparator { private Map> finalize(Map> m) { for (Map.Entry> e : m.entrySet()) { e.getValue().sort(NAME_COMPARATOR); - e.setValue( Collections.unmodifiableList(e.getValue()) ); + e.setValue(Collections.unmodifiableList(e.getValue())); } return Collections.unmodifiableMap(m); } @@ -356,7 +357,7 @@ public class DependencyGraph implements Comparator { */ @Override public int compare(AbstractProject o1, AbstractProject o2) { - return topologicalOrder.compare(o1,o2); + return topologicalOrder.compare(o1, o2); } /** @@ -367,7 +368,7 @@ public class DependencyGraph implements Comparator { * * @since 1.521 */ - public List> getTopologicallySorted() { + public List> getTopologicallySorted() { return topologicallySorted; } @@ -413,7 +414,7 @@ public class DependencyGraph implements Comparator { * Does this method point to itself? */ public boolean pointsItself() { - return upstream==downstream; + return upstream == downstream; } @Override @@ -446,7 +447,7 @@ public class DependencyGraph implements Comparator { DependencyGroup(Dependency first) { this.upstream = first.getUpstreamProject(); - this.downstream= first.getDownstreamProject(); + this.downstream = first.getDownstreamProject(); group.add(first); } diff --git a/core/src/main/java/hudson/model/Describable.java b/core/src/main/java/hudson/model/Describable.java index e1331510d7e1711fb032ea4e0d486dd0584c3f54..d770540072335f59ad3d2173e9c59c40a82fbf8c 100644 --- a/core/src/main/java/hudson/model/Describable.java +++ b/core/src/main/java/hudson/model/Describable.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; /** diff --git a/core/src/main/java/hudson/model/Descriptor.java b/core/src/main/java/hudson/model/Descriptor.java index b1066e7428e3e19f2c6eb330c03a6bb333fb9dbc..3c9c466acdd23337fc0c9e97741be659ec0362bd 100644 --- a/core/src/main/java/hudson/model/Descriptor.java +++ b/core/src/main/java/hudson/model/Descriptor.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import static hudson.util.QuotedStringTokenizer.quote; @@ -147,12 +148,12 @@ public abstract class Descriptor> implements Saveable, */ public final transient Class clazz; - private final transient Map checkMethods = new ConcurrentHashMap<>(2); + private final transient Map checkMethods = new ConcurrentHashMap<>(2); /** * Lazily computed list of properties on {@link #clazz} and on the descriptor itself. */ - private transient volatile Map propertyTypes,globalPropertyTypes; + private transient volatile Map propertyTypes, globalPropertyTypes; /** * Represents a readable property on {@link Describable}. @@ -170,35 +171,35 @@ public abstract class Descriptor> implements Saveable, } PropertyType(Field f) { - this(f.getType(),f.getGenericType(),f.toString()); + this(f.getType(), f.getGenericType(), f.toString()); } PropertyType(Method getter) { - this(getter.getReturnType(),getter.getGenericReturnType(),getter.toString()); + this(getter.getReturnType(), getter.getGenericReturnType(), getter.toString()); } public Enum[] getEnumConstants() { - return (Enum[])clazz.getEnumConstants(); + return (Enum[]) clazz.getEnumConstants(); } /** * If the property is a collection/array type, what is an item type? */ public Class getItemType() { - if(itemType==null) + if (itemType == null) itemType = computeItemType(); return itemType; } private Class computeItemType() { - if(clazz.isArray()) { + if (clazz.isArray()) { return clazz.getComponentType(); } - if(Collection.class.isAssignableFrom(clazz)) { + if (Collection.class.isAssignableFrom(clazz)) { Type col = Types.getBaseClass(type, Collection.class); if (col instanceof ParameterizedType) - return Types.erasure(Types.getTypeArgument(col,0)); + return Types.erasure(Types.getTypeArgument(col, 0)); else return Object.class; } @@ -218,8 +219,8 @@ public abstract class Descriptor> implements Saveable, throw new AssertionError(clazz + " is not an array/collection type in " + displayName + ". See https://www.jenkins.io/redirect/developer/class-is-missing-descriptor"); } Descriptor d = Jenkins.get().getDescriptor(it); - if (d==null) - throw new AssertionError(it +" is missing its descriptor in "+displayName+". See https://www.jenkins.io/redirect/developer/class-is-missing-descriptor"); + if (d == null) + throw new AssertionError(it + " is missing its descriptor in " + displayName + ". See https://www.jenkins.io/redirect/developer/class-is-missing-descriptor"); return d; } @@ -243,7 +244,7 @@ public abstract class Descriptor> implements Saveable, * * @see #getHelpFile(String) */ - private final transient Map helpRedirect = new HashMap<>(2); + private final transient Map helpRedirect = new HashMap<>(2); private static class HelpRedirect { private final Class owner; @@ -267,8 +268,8 @@ public abstract class Descriptor> implements Saveable, * (this hack is needed since derived types can't call "getClass()" to refer to itself. */ protected Descriptor(Class clazz) { - if (clazz==self()) - clazz = (Class)getClass(); + if (clazz == self()) + clazz = (Class) getClass(); this.clazz = clazz; // doing this turns out to be very error prone, // as field initializers in derived types will override values. @@ -283,9 +284,9 @@ public abstract class Descriptor> implements Saveable, * @since 1.278 */ protected Descriptor() { - this.clazz = (Class)getClass().getEnclosingClass(); - if(clazz==null) - throw new AssertionError(getClass()+" doesn't have an outer class. Use the constructor that takes the Class object explicitly."); + this.clazz = (Class) getClass().getEnclosingClass(); + if (clazz == null) + throw new AssertionError(getClass() + " doesn't have an outer class. Use the constructor that takes the Class object explicitly."); // detect an type error Type bt = Types.getBaseClass(getClass(), Descriptor.class); @@ -293,19 +294,19 @@ public abstract class Descriptor> implements Saveable, ParameterizedType pt = (ParameterizedType) bt; // this 't' is the closest approximation of T of Descriptor. Class t = Types.erasure(pt.getActualTypeArguments()[0]); - if(!t.isAssignableFrom(clazz)) - throw new AssertionError("Outer class "+clazz+" of "+getClass()+" is not assignable to "+t+". Perhaps wrong outer class?"); + if (!t.isAssignableFrom(clazz)) + throw new AssertionError("Outer class " + clazz + " of " + getClass() + " is not assignable to " + t + ". Perhaps wrong outer class?"); } // detect a type error. this Descriptor is supposed to be returned from getDescriptor(), so make sure its type match up. // this prevents a bug like http://www.nabble.com/Creating-a-new-parameter-Type-%3A-Masked-Parameter-td24786554.html try { Method getd = clazz.getMethod("getDescriptor"); - if(!getd.getReturnType().isAssignableFrom(getClass())) { - throw new AssertionError(getClass()+" must be assignable to "+getd.getReturnType()); + if (!getd.getReturnType().isAssignableFrom(getClass())) { + throw new AssertionError(getClass() + " must be assignable to " + getd.getReturnType()); } } catch (NoSuchMethodException e) { - throw new AssertionError(getClass()+" is missing getDescriptor method.", e); + throw new AssertionError(getClass() + " is missing getDescriptor method.", e); } } @@ -353,7 +354,7 @@ public abstract class Descriptor> implements Saveable, public Class getT() { Type subTyping = Types.getBaseClass(getClass(), Descriptor.class); if (!(subTyping instanceof ParameterizedType)) { - throw new IllegalStateException(getClass()+" doesn't extend Descriptor with a type parameter."); + throw new IllegalStateException(getClass() + " doesn't extend Descriptor with a type parameter."); } return Types.erasure(Types.getTypeArgument(subTyping, 0)); } @@ -363,7 +364,7 @@ public abstract class Descriptor> implements Saveable, * Since {@link Jenkins} is a {@link DescriptorByNameOwner}, there's always one such ancestor to any request. */ public String getDescriptorUrl() { - return "descriptorByName/"+getId(); + return "descriptorByName/" + getId(); } /** @@ -371,7 +372,7 @@ public abstract class Descriptor> implements Saveable, * @since 1.406 */ public final String getDescriptorFullUrl() { - return getCurrentDescriptorByNameUrl()+'/'+getDescriptorUrl(); + return getCurrentDescriptorByNameUrl() + '/' + getDescriptorUrl(); } /** @@ -382,7 +383,7 @@ public abstract class Descriptor> implements Saveable, // this override allows RenderOnDemandClosure to preserve the proper value Object url = req.getAttribute("currentDescriptorByNameUrl"); - if (url!=null) return url.toString(); + if (url != null) return url.toString(); Ancestor a = req.findAncestor(DescriptorByNameOwner.class); return a.getUrl(); @@ -405,9 +406,9 @@ public abstract class Descriptor> implements Saveable, */ public CheckMethod getCheckMethod(String fieldName) { CheckMethod method = checkMethods.get(fieldName); - if(method==null) { - method = new CheckMethod(this,fieldName); - checkMethods.put(fieldName,method); + if (method == null) { + method = new CheckMethod(this, fieldName); + checkMethods.put(fieldName, method); } return method; @@ -418,11 +419,11 @@ public abstract class Descriptor> implements Saveable, * and sets that as the 'fillDependsOn' attribute. Also computes the URL of the doFillXyzItems and * sets that as the 'fillUrl' attribute. */ - public void calcFillSettings(String field, Map attributes) { + public void calcFillSettings(String field, Map attributes) { String capitalizedFieldName = StringUtils.capitalize(field); String methodName = "doFill" + capitalizedFieldName + "Items"; Method method = ReflectionUtils.getPublicMethodNamed(getClass(), methodName); - if(method==null) + if (method == null) throw new IllegalStateException(String.format("%s doesn't have the %s method for filling a drop-down list", getClass(), methodName)); // build query parameter line by figuring out what should be submitted @@ -436,23 +437,23 @@ public abstract class Descriptor> implements Saveable, private List buildFillDependencies(Method method, List depends) { for (Parameter p : ReflectionUtils.getParameters(method)) { QueryParameter qp = p.annotation(QueryParameter.class); - if (qp!=null) { + if (qp != null) { String name = qp.value(); - if (name.length()==0) name = p.name(); - if (name==null || name.length()==0) + if (name.length() == 0) name = p.name(); + if (name == null || name.length() == 0) continue; // unknown parameter name. we'll report the error when the form is submitted. RelativePath rp = p.annotation(RelativePath.class); - if (rp!=null) - name = rp.value()+'/'+name; + if (rp != null) + name = rp.value() + '/' + name; depends.add(name); continue; } Method m = ReflectionUtils.getPublicMethodNamed(p.type(), "fromStapler"); - if (m!=null) - buildFillDependencies(m,depends); + if (m != null) + buildFillDependencies(m, depends); } return depends; } @@ -460,11 +461,11 @@ public abstract class Descriptor> implements Saveable, /** * Computes the auto-completion setting */ - public void calcAutoCompleteSettings(String field, Map attributes) { + public void calcAutoCompleteSettings(String field, Map attributes) { String capitalizedFieldName = StringUtils.capitalize(field); String methodName = "doAutoComplete" + capitalizedFieldName; Method method = ReflectionUtils.getPublicMethodNamed(getClass(), methodName); - if(method==null) + if (method == null) return; // no auto-completion attributes.put("autoCompleteUrl", String.format("%s/%s/autoComplete%s", getCurrentDescriptorByNameUrl(), getDescriptorUrl(), capitalizedFieldName)); @@ -475,7 +476,7 @@ public abstract class Descriptor> implements Saveable, */ public @CheckForNull PropertyType getPropertyType(@NonNull Object instance, @NonNull String field) { // in global.jelly, instance==descriptor - return instance==this ? getGlobalPropertyType(field) : getPropertyType(field); + return instance == this ? getGlobalPropertyType(field) : getPropertyType(field); } /** @@ -498,7 +499,7 @@ public abstract class Descriptor> implements Saveable, * Obtains the property type of the given field of {@link #clazz} */ public PropertyType getPropertyType(String field) { - if(propertyTypes==null) + if (propertyTypes == null) propertyTypes = buildPropertyTypes(clazz); return propertyTypes.get(field); } @@ -507,7 +508,7 @@ public abstract class Descriptor> implements Saveable, * Obtains the property type of the given field of this descriptor. */ public PropertyType getGlobalPropertyType(String field) { - if(globalPropertyTypes==null) + if (globalPropertyTypes == null) globalPropertyTypes = buildPropertyTypes(getClass()); return globalPropertyTypes.get(field); } @@ -518,11 +519,11 @@ public abstract class Descriptor> implements Saveable, private Map buildPropertyTypes(Class clazz) { Map r = new HashMap<>(); for (Field f : clazz.getFields()) - r.put(f.getName(),new PropertyType(f)); + r.put(f.getName(), new PropertyType(f)); for (Method m : clazz.getMethods()) - if(m.getName().startsWith("get")) - r.put(Introspector.decapitalize(m.getName().substring(3)),new PropertyType(m)); + if (m.getName().startsWith("get")) + r.put(Introspector.decapitalize(m.getName().substring(3)), new PropertyType(m)); return r; } @@ -531,7 +532,7 @@ public abstract class Descriptor> implements Saveable, * Gets the class name nicely escaped to be usable as a key in the structured form submission. */ public final String getJsonSafeClassName() { - return getId().replace('.','-'); + return getId().replace('.', '-'); } /** @@ -541,7 +542,7 @@ public abstract class Descriptor> implements Saveable, */ @Deprecated public T newInstance(StaplerRequest req) throws FormException { - throw new UnsupportedOperationException(getClass()+" should implement newInstance(StaplerRequest,JSONObject)"); + throw new UnsupportedOperationException(getClass() + " should implement newInstance(StaplerRequest,JSONObject)"); } /** @@ -582,12 +583,12 @@ public abstract class Descriptor> implements Saveable, try { Method m = getClass().getMethod("newInstance", StaplerRequest.class); - if(!Modifier.isAbstract(m.getDeclaringClass().getModifiers())) { + if (!Modifier.isAbstract(m.getDeclaringClass().getModifiers())) { // this class overrides newInstance(StaplerRequest). // maintain the backward compatible behavior return verifyNewInstance(newInstance(req)); } else { - if (req==null) { + if (req == null) { // yes, req is supposed to be always non-null, but see the note above return verifyNewInstance(clazz.getDeclaredConstructor().newInstance()); } @@ -609,7 +610,7 @@ public abstract class Descriptor> implements Saveable, } } } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException | RuntimeException e) { - throw new LinkageError("Failed to instantiate "+clazz+" from "+RedactSecretJsonInErrorMessageSanitizer.INSTANCE.sanitize(formData),e); + throw new LinkageError("Failed to instantiate " + clazz + " from " + RedactSecretJsonInErrorMessageSanitizer.INSTANCE.sanitize(formData), e); } } @@ -624,7 +625,7 @@ public abstract class Descriptor> implements Saveable, private static class NewInstanceBindInterceptor extends BindInterceptor { private final BindInterceptor oldInterceptor; - private final IdentityHashMap processed = new IdentityHashMap<>(); + private final IdentityHashMap processed = new IdentityHashMap<>(); NewInstanceBindInterceptor(BindInterceptor oldInterceptor) { LOGGER.log(Level.FINER, "new interceptor delegating to {0}", oldInterceptor); @@ -696,9 +697,9 @@ public abstract class Descriptor> implements Saveable, * See http://hudson.361315.n4.nabble.com/Help-Hint-needed-Post-build-action-doesn-t-stay-activated-td2308833.html */ private T verifyNewInstance(T t) { - if (t!=null && t.getDescriptor()!=this) { + if (t != null && t.getDescriptor() != this) { // TODO: should this be a fatal error? - LOGGER.warning("Father of "+ t+" and its getDescriptor() points to two different instances. Probably misplaced @Extension. See http://hudson.361315.n4.nabble.com/Help-Hint-needed-Post-build-action-doesn-t-stay-activated-td2308833.html"); + LOGGER.warning("Father of " + t + " and its getDescriptor() points to two different instances. Probably misplaced @Extension. See http://hudson.361315.n4.nabble.com/Help-Hint-needed-Post-build-action-doesn-t-stay-activated-td2308833.html"); } return t; } @@ -741,31 +742,31 @@ public abstract class Descriptor> implements Saveable, * locale variations. */ public String getHelpFile(final String fieldName) { - return getHelpFile(getKlass(),fieldName); + return getHelpFile(getKlass(), fieldName); } public String getHelpFile(Klass clazz, String fieldName) { HelpRedirect r = helpRedirect.get(fieldName); - if (r!=null) return r.resolve(); + if (r != null) return r.resolve(); for (Klass c : clazz.getAncestors()) { String page = "/descriptor/" + getId() + "/help"; String suffix; - if(fieldName==null) { - suffix=""; + if (fieldName == null) { + suffix = ""; } else { - page += '/'+fieldName; - suffix='-'+fieldName; + page += '/' + fieldName; + suffix = '-' + fieldName; } try { - if(Stapler.getCurrentRequest().getView(c,"help"+suffix)!=null) + if (Stapler.getCurrentRequest().getView(c, "help" + suffix) != null) return page; } catch (IOException e) { throw new Error(e); } - if(getStaticHelpUrl(c, suffix) !=null) return page; + if (getStaticHelpUrl(c, suffix) != null) return page; } return null; } @@ -776,13 +777,13 @@ public abstract class Descriptor> implements Saveable, * @since 1.425 */ protected void addHelpFileRedirect(String fieldName, Class owner, String fieldNameToRedirectTo) { - helpRedirect.put(fieldName, new HelpRedirect(owner,fieldNameToRedirectTo)); + helpRedirect.put(fieldName, new HelpRedirect(owner, fieldNameToRedirectTo)); } /** * Checks if the given object is created from this {@link Descriptor}. */ - public final boolean isInstance( T instance ) { + public final boolean isInstance(T instance) { return clazz.isInstance(instance); } @@ -798,7 +799,7 @@ public abstract class Descriptor> implements Saveable, * As of 1.239, use {@link #configure(StaplerRequest, JSONObject)}. */ @Deprecated - public boolean configure( StaplerRequest req ) throws FormException { + public boolean configure(StaplerRequest req) throws FormException { return true; } @@ -813,7 +814,7 @@ public abstract class Descriptor> implements Saveable, * @return false * to keep the client in the same config page. */ - public boolean configure( StaplerRequest req, JSONObject json ) throws FormException { + public boolean configure(StaplerRequest req, JSONObject json) throws FormException { // compatibility return configure(req); } @@ -852,15 +853,15 @@ public abstract class Descriptor> implements Saveable, } private String getViewPage(Class clazz, String pageName, String defaultValue) { - return getViewPage(clazz,Collections.singleton(pageName),defaultValue); + return getViewPage(clazz, Collections.singleton(pageName), defaultValue); } private String getViewPage(Class clazz, Collection pageNames, String defaultValue) { - while(clazz!=Object.class && clazz!=null) { + while (clazz != Object.class && clazz != null) { for (String pageName : pageNames) { String name = clazz.getName().replace('.', '/').replace('$', '/') + "/" + pageName; - if(clazz.getClassLoader().getResource(name)!=null) - return '/'+name; + if (clazz.getClassLoader().getResource(name) != null) + return '/' + name; } clazz = clazz.getSuperclass(); } @@ -873,7 +874,7 @@ public abstract class Descriptor> implements Saveable, // it doesn't exist. // Or this error is fatal, in which case we want the developer to see what page he's missing. // so we put the page name. - return getViewPage(clazz,pageName,pageName); + return getViewPage(clazz, pageName, pageName); } protected List getPossibleViewNames(String baseName) { @@ -882,7 +883,7 @@ public abstract class Descriptor> implements Saveable, if (f instanceof JellyCompatibleFacet) { JellyCompatibleFacet jcf = (JellyCompatibleFacet) f; for (String ext : jcf.getScriptExtensions()) - names.add(baseName +ext); + names.add(baseName + ext); } } return names; @@ -894,12 +895,12 @@ public abstract class Descriptor> implements Saveable, */ @Override public synchronized void save() { - if(BulkChange.contains(this)) return; + if (BulkChange.contains(this)) return; try { getConfigFile().write(this); SaveableListener.fireOnChange(this, getConfigFile()); } catch (IOException e) { - LOGGER.log(Level.WARNING, "Failed to save "+getConfigFile(),e); + LOGGER.log(Level.WARNING, "Failed to save " + getConfigFile(), e); } } @@ -913,18 +914,18 @@ public abstract class Descriptor> implements Saveable, */ public synchronized void load() { XmlFile file = getConfigFile(); - if(!file.exists()) + if (!file.exists()) return; try { file.unmarshal(this); } catch (IOException e) { - LOGGER.log(Level.WARNING, "Failed to load "+file, e); + LOGGER.log(Level.WARNING, "Failed to load " + file, e); } } protected XmlFile getConfigFile() { - return new XmlFile(new File(Jenkins.get().getRootDir(),getId()+".xml")); + return new XmlFile(new File(Jenkins.get().getRootDir(), getId() + ".xml")); } /** @@ -942,32 +943,32 @@ public abstract class Descriptor> implements Saveable, */ public void doHelp(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { String path = req.getRestOfPath(); - if(path.contains("..")) throw new ServletException("Illegal path: "+path); + if (path.contains("..")) throw new ServletException("Illegal path: " + path); - path = path.replace('/','-'); + path = path.replace('/', '-'); PluginWrapper pw = getPlugin(); - if (pw!=null) { - rsp.setHeader("X-Plugin-Short-Name",pw.getShortName()); - rsp.setHeader("X-Plugin-Long-Name",pw.getLongName()); + if (pw != null) { + rsp.setHeader("X-Plugin-Short-Name", pw.getShortName()); + rsp.setHeader("X-Plugin-Long-Name", pw.getLongName()); rsp.setHeader("X-Plugin-From", Messages.Descriptor_From( - pw.getLongName().replace("Hudson","Jenkins").replace("hudson","jenkins"), pw.getUrl())); + pw.getLongName().replace("Hudson", "Jenkins").replace("hudson", "jenkins"), pw.getUrl())); } - for (Klass c= getKlass(); c!=null; c=c.getSuperClass()) { - RequestDispatcher rd = Stapler.getCurrentRequest().getView(c, "help"+path); - if(rd!=null) {// template based help page - rd.forward(req,rsp); + for (Klass c = getKlass(); c != null; c = c.getSuperClass()) { + RequestDispatcher rd = Stapler.getCurrentRequest().getView(c, "help" + path); + if (rd != null) { // template based help page + rd.forward(req, rsp); return; } URL url = getStaticHelpUrl(c, path); - if(url!=null) { + if (url != null) { // TODO: generalize macro expansion and perhaps even support JEXL rsp.setContentType("text/html;charset=UTF-8"); try (InputStream in = url.openStream()) { String literal = IOUtils.toString(in, StandardCharsets.UTF_8); - rsp.getWriter().println(Util.replaceMacro(literal, Collections.singletonMap("rootURL",req.getContextPath()))); + rsp.getWriter().println(Util.replaceMacro(literal, Collections.singletonMap("rootURL", req.getContextPath()))); } return; } @@ -978,15 +979,15 @@ public abstract class Descriptor> implements Saveable, private URL getStaticHelpUrl(Klass c, String suffix) { Locale locale = Stapler.getCurrentRequest().getLocale(); - String base = "help"+suffix; + String base = "help" + suffix; URL url; url = c.getResource(base + '_' + locale.getLanguage() + '_' + locale.getCountry() + '_' + locale.getVariant() + ".html"); - if(url!=null) return url; + if (url != null) return url; url = c.getResource(base + '_' + locale.getLanguage() + '_' + locale.getCountry() + ".html"); - if(url!=null) return url; + if (url != null) return url; url = c.getResource(base + '_' + locale.getLanguage() + ".html"); - if(url!=null) return url; + if (url != null) return url; // default return c.getResource(base + ".html"); @@ -999,17 +1000,17 @@ public abstract class Descriptor> implements Saveable, // to work around warning when creating a generic array type - public static T[] toArray( T... values ) { + public static T[] toArray(T... values) { return values; } - public static List toList( T... values ) { + public static List toList(T... values) { return new ArrayList<>(Arrays.asList(values)); } public static > - Map,T> toMap(Iterable describables) { - Map,T> m = new LinkedHashMap<>(); + Map, T> toMap(Iterable describables) { + Map, T> m = new LinkedHashMap<>(); for (T d : describables) { Descriptor descriptor; try { @@ -1041,7 +1042,7 @@ public abstract class Descriptor> implements Saveable, List newInstancesFromHeteroList(StaplerRequest req, JSONObject formData, String key, Collection> descriptors) throws FormException { - return newInstancesFromHeteroList(req,formData.get(key),descriptors); + return newInstancesFromHeteroList(req, formData.get(key), descriptors); } public static > @@ -1050,9 +1051,9 @@ public abstract class Descriptor> implements Saveable, List items = new ArrayList<>(); - if (formData!=null) { + if (formData != null) { for (Object o : JSONArray.fromObject(formData)) { - JSONObject jo = (JSONObject)o; + JSONObject jo = (JSONObject) o; Descriptor d = null; // 'kind' and '$class' are mutually exclusive (see class-entry.jelly), but to be more lenient on the reader side, // we check them both anyway. 'kind' (which maps to ID) is more unique than '$class', which can have multiple matching @@ -1096,7 +1097,7 @@ public abstract class Descriptor> implements Saveable, */ public static @CheckForNull T findById(Collection list, String id) { for (T d : list) { - if(d.getId().equals(id)) + if (d.getId().equals(id)) return d; } return null; @@ -1108,7 +1109,7 @@ public abstract class Descriptor> implements Saveable, */ private static @CheckForNull T findByClassName(Collection list, String className) { for (T d : list) { - if(d.getClass().getName().equals(className)) + if (d.getClass().getName().equals(className)) return d; } return null; @@ -1121,7 +1122,7 @@ public abstract class Descriptor> implements Saveable, */ public static @CheckForNull T findByDescribableClassName(Collection list, String className) { for (T d : list) { - if(d.clazz.getName().equals(className)) + if (d.clazz.getName().equals(className)) return d; } return null; @@ -1145,7 +1146,7 @@ public abstract class Descriptor> implements Saveable, */ @Deprecated public static @CheckForNull Descriptor find(String className) { - return find(ExtensionList.lookup(Descriptor.class),className); + return find(ExtensionList.lookup(Descriptor.class), className); } public static final class FormException extends Exception implements HttpResponse { @@ -1176,11 +1177,11 @@ public abstract class Descriptor> implements Saveable, @Override public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException, ServletException { if (FormApply.isApply(req)) { - FormApply.applyResponse("notificationBar.show(" + quote(getMessage())+ ",notificationBar.ERROR)") + FormApply.applyResponse("notificationBar.show(" + quote(getMessage()) + ",notificationBar.ERROR)") .generateResponse(req, rsp, node); } else { // for now, we can't really use the field name that caused the problem. - new Failure(getMessage()).generateResponse(req,rsp,node,getCause()); + new Failure(getMessage()).generateResponse(req, rsp, node, getCause()); } } } diff --git a/core/src/main/java/hudson/model/DescriptorByNameOwner.java b/core/src/main/java/hudson/model/DescriptorByNameOwner.java index e36f61df4d0033073544ae7148932e572c9976f2..6dab3573d95a6a2cf34b752c8e14e628a0cce8f6 100644 --- a/core/src/main/java/hudson/model/DescriptorByNameOwner.java +++ b/core/src/main/java/hudson/model/DescriptorByNameOwner.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import jenkins.model.Jenkins; diff --git a/core/src/main/java/hudson/model/DirectlyModifiableView.java b/core/src/main/java/hudson/model/DirectlyModifiableView.java index ffb0b1b2a7b2e7ab48088b44882b5d858f015a18..61362272c248c2d968b07705f1fdaa389d6f7e1e 100644 --- a/core/src/main/java/hudson/model/DirectlyModifiableView.java +++ b/core/src/main/java/hudson/model/DirectlyModifiableView.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; diff --git a/core/src/main/java/hudson/model/DirectoryBrowserSupport.java b/core/src/main/java/hudson/model/DirectoryBrowserSupport.java index cc4c13f14dff27786e15c7289b239c05d1f9ba00..c6c595becdc5ef1538db7b99eb8f209963972521 100644 --- a/core/src/main/java/hudson/model/DirectoryBrowserSupport.java +++ b/core/src/main/java/hudson/model/DirectoryBrowserSupport.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi, Erik Ramfelt - * + * * 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 @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; @@ -74,7 +75,7 @@ import org.kohsuke.stapler.StaplerResponse; * *

    * This object can be used in a mix-in style to provide a directory browsing capability - * to a {@link ModelObject}. + * to a {@link ModelObject}. * * @author Kohsuke Kawaguchi */ @@ -84,12 +85,12 @@ public final class DirectoryBrowserSupport implements HttpResponse { public static boolean ALLOW_SYMLINK_ESCAPE = SystemProperties.getBoolean(DirectoryBrowserSupport.class.getName() + ".allowSymlinkEscape"); /** - * Escape hatch for the protection against SECURITY-2481. If enabled, the absolute paths on Windows will be allowed. + * Escape hatch for the protection against SECURITY-2481. If enabled, the absolute paths on Windows will be allowed. */ static final String ALLOW_ABSOLUTE_PATH_PROPERTY_NAME = DirectoryBrowserSupport.class.getName() + ".allowAbsolutePath"; public final ModelObject owner; - + public final String title; private final VirtualFile base; @@ -120,7 +121,7 @@ public final class DirectoryBrowserSupport implements HttpResponse { * @param base * The root of the directory that's bound to URL. * @param title - * Used in the HTML caption. + * Used in the HTML caption. * @param icon * The icon file name, like "folder.gif" * @param serveDirIndex @@ -160,9 +161,9 @@ public final class DirectoryBrowserSupport implements HttpResponse { } try { - serveFile(req,rsp,base,icon,serveDirIndex); + serveFile(req, rsp, base, icon, serveDirIndex); } catch (InterruptedException e) { - throw new IOException("interrupted",e); + throw new IOException("interrupted", e); } } @@ -195,15 +196,15 @@ public final class DirectoryBrowserSupport implements HttpResponse { private void serveFile(StaplerRequest req, StaplerResponse rsp, VirtualFile root, String icon, boolean serveDirIndex) throws IOException, ServletException, InterruptedException { // handle form submission String pattern = req.getParameter("pattern"); - if(pattern==null) + if (pattern == null) pattern = req.getParameter("path"); // compatibility with Hudson<1.129 - if(pattern!=null && Util.isSafeToRedirectTo(pattern)) {// avoid open redirect + if (pattern != null && Util.isSafeToRedirectTo(pattern)) { // avoid open redirect rsp.sendRedirect2(pattern); return; } String path = getPath(req); - if(path.replace('\\', '/').contains("/../")) { + if (path.replace('\\', '/').contains("/../")) { // don't serve anything other than files in the artifacts dir rsp.sendError(HttpServletResponse.SC_BAD_REQUEST); return; @@ -213,38 +214,38 @@ public final class DirectoryBrowserSupport implements HttpResponse { // and the GLOB portion "**/*.xml" (the rest) StringBuilder _base = new StringBuilder(); StringBuilder _rest = new StringBuilder(); - int restSize=-1; // number of ".." needed to go back to the 'base' level. - boolean zip=false; // if we are asked to serve a zip file bundle + int restSize = -1; // number of ".." needed to go back to the 'base' level. + boolean zip = false; // if we are asked to serve a zip file bundle boolean plain = false; // if asked to serve a plain text directory listing { boolean inBase = true; - StringTokenizer pathTokens = new StringTokenizer(path,"/"); - while(pathTokens.hasMoreTokens()) { + StringTokenizer pathTokens = new StringTokenizer(path, "/"); + while (pathTokens.hasMoreTokens()) { String pathElement = pathTokens.nextToken(); // Treat * and ? as wildcard unless they match a literal filename - if((pathElement.contains("?") || pathElement.contains("*")) + if ((pathElement.contains("?") || pathElement.contains("*")) && inBase && !root.child((_base.length() > 0 ? _base + "/" : "") + pathElement).exists()) inBase = false; - if(pathElement.equals("*zip*")) { + if (pathElement.equals("*zip*")) { // the expected syntax is foo/bar/*zip*/bar.zip // the last 'bar.zip' portion is to causes browses to set a good default file name. // so the 'rest' portion ends here. - zip=true; + zip = true; break; } - if(pathElement.equals("*plain*")) { + if (pathElement.equals("*plain*")) { plain = true; break; } - StringBuilder sb = inBase?_base:_rest; - if(sb.length()>0) sb.append('/'); + StringBuilder sb = inBase ? _base : _rest; + if (sb.length() > 0) sb.append('/'); sb.append(pathElement); - if(!inBase) + if (!inBase) restSize++; } } - restSize = Math.max(restSize,0); + restSize = Math.max(restSize, 0); String base = _base.toString(); String rest = _rest.toString(); @@ -268,8 +269,8 @@ public final class DirectoryBrowserSupport implements HttpResponse { rsp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } - if(baseFile.isDirectory()) { - if(zip) { + if (baseFile.isDirectory()) { + if (zip) { rsp.setContentType("application/zip"); String includes, prefix; if (StringUtils.isBlank(rest)) { @@ -298,10 +299,10 @@ public final class DirectoryBrowserSupport implements HttpResponse { return; } - if(rest.length()==0) { + if (rest.length() == 0) { // if the target page to be displayed is a directory and the path doesn't end with '/', redirect StringBuffer reqUrl = req.getRequestURL(); - if(reqUrl.charAt(reqUrl.length()-1)!='/') { + if (reqUrl.charAt(reqUrl.length() - 1) != '/') { rsp.sendRedirect2(reqUrl.append('/').toString()); return; } @@ -310,27 +311,27 @@ public final class DirectoryBrowserSupport implements HttpResponse { List> glob = null; boolean patternUsed = rest.length() > 0; boolean containsSymlink = false; - if(patternUsed) { + if (patternUsed) { // the rest is Ant glob pattern glob = patternScan(baseFile, rest, createBackRef(restSize)); } else - if(serveDirIndex) { + if (serveDirIndex) { // serve directory index glob = baseFile.run(new BuildChildPaths(root, baseFile, req.getLocale())); containsSymlink = baseFile.containsSymLinkChild(getNoFollowLinks()); } - if(glob!=null) { + if (glob != null) { // serve glob req.setAttribute("it", this); - List parentPaths = buildParentPath(base,restSize); - req.setAttribute("parentPath",parentPaths); + List parentPaths = buildParentPath(base, restSize); + req.setAttribute("parentPath", parentPaths); req.setAttribute("backPath", createBackRef(restSize)); - req.setAttribute("topPath", createBackRef(parentPaths.size()+restSize)); + req.setAttribute("topPath", createBackRef(parentPaths.size() + restSize)); req.setAttribute("files", glob); req.setAttribute("icon", icon); req.setAttribute("path", path); - req.setAttribute("pattern",rest); + req.setAttribute("pattern", rest); req.setAttribute("dir", baseFile); req.setAttribute("showSymlinkWarning", containsSymlink); if (ResourceDomainConfiguration.isResourceRequest(req)) { @@ -347,14 +348,14 @@ public final class DirectoryBrowserSupport implements HttpResponse { } //serve a single file - if(!baseFile.exists()) { + if (!baseFile.exists()) { rsp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } boolean view = rest.equals("*view*"); - if(rest.equals("*fingerprint*")) { + if (rest.equals("*fingerprint*")) { try (InputStream fingerprintInput = baseFile.open()) { rsp.forward(Jenkins.get().getFingerprint(Util.getDigestOf(fingerprintInput)), "/", req); } @@ -372,8 +373,8 @@ public final class DirectoryBrowserSupport implements HttpResponse { long lastModified = baseFile.lastModified(); long length = baseFile.length(); - if(LOGGER.isLoggable(Level.FINE)) - LOGGER.fine("Serving "+baseFile+" with lastModified=" + lastModified + ", length=" + length); + if (LOGGER.isLoggable(Level.FINE)) + LOGGER.fine("Serving " + baseFile + " with lastModified=" + lastModified + ", length=" + length); if (view) { InputStream in; @@ -423,13 +424,13 @@ public final class DirectoryBrowserSupport implements HttpResponse { this.fragment = fragment; } - @Override + @Override public Boolean call() throws IOException { return new File(fragment).isAbsolute(); } } - private List> keepReadabilityOnlyOnDescendants(VirtualFile root, boolean patternUsed, List> pathFragmentsList){ + private List> keepReadabilityOnlyOnDescendants(VirtualFile root, boolean patternUsed, List> pathFragmentsList) { Stream> pathFragmentsStream = pathFragmentsList.stream().map((List pathFragments) -> { List mappedFragments = new ArrayList<>(pathFragments.size()); String relativePath = ""; @@ -440,7 +441,7 @@ public final class DirectoryBrowserSupport implements HttpResponse { } else { relativePath += "/" + current.title; } - + if (!current.isReadable) { if (patternUsed) { // we do not want to leak information about existence of folders / files satisfying the pattern inside that folder @@ -463,15 +464,15 @@ public final class DirectoryBrowserSupport implements HttpResponse { } return mappedFragments; }); - + if (patternUsed) { pathFragmentsStream = pathFragmentsStream.filter(Objects::nonNull); } - + return pathFragmentsStream.collect(Collectors.toList()); } - private boolean isDescendant(VirtualFile root, String relativePath){ + private boolean isDescendant(VirtualFile root, String relativePath) { try { return ALLOW_SYMLINK_ESCAPE || !root.supportIsDescendant() || root.isDescendant(relativePath); } @@ -482,7 +483,7 @@ public final class DirectoryBrowserSupport implements HttpResponse { private String getPath(StaplerRequest req) { String path = req.getRestOfPath(); - if(path.length()==0) + if (path.length() == 0) path = "/"; return path; } @@ -495,19 +496,19 @@ public final class DirectoryBrowserSupport implements HttpResponse { List r = new ArrayList<>(); StringTokenizer tokens = new StringTokenizer(pathList, "/"); int total = tokens.countTokens(); - int current=1; - while(tokens.hasMoreTokens()) { + int current = 1; + while (tokens.hasMoreTokens()) { String token = tokens.nextToken(); - r.add(new Path(createBackRef(total-current+restSize),token,true,0, true,0)); + r.add(new Path(createBackRef(total - current + restSize), token, true, 0, true, 0)); current++; } return r; } private static String createBackRef(int times) { - if(times==0) return "./"; - StringBuilder buf = new StringBuilder(3*times); - for(int i=0; i nameToVirtualFiles = collectRecursivelyAllLegalChildren(dir); sendZipUsingMap(zos, dir, nameToVirtualFiles); @@ -612,7 +613,7 @@ public final class DirectoryBrowserSupport implements HttpResponse { * File size, or null if this is not a file. */ private final long size; - + /** * If the current user can read the file. */ @@ -643,7 +644,7 @@ public final class DirectoryBrowserSupport implements HttpResponse { public boolean isFolder() { return isFolder; } - + public boolean isReadable() { return isReadable; } @@ -658,16 +659,16 @@ public final class DirectoryBrowserSupport implements HttpResponse { public String getIconName() { if (isReadable) - return isFolder?"folder.png":"text.png"; + return isFolder ? "folder.png" : "text.png"; else - return isFolder?"folder-error.png":"text-error.png"; + return isFolder ? "folder-error.png" : "text-error.png"; } public String getIconClassName() { if (isReadable) - return isFolder?"icon-folder":"icon-text"; + return isFolder ? "icon-folder" : "icon-text"; else - return isFolder?"icon-folder-error":"icon-text-error"; + return isFolder ? "icon-folder-error" : "icon-text-error"; } public long getSize() { @@ -697,7 +698,7 @@ public final class DirectoryBrowserSupport implements HttpResponse { return cal; } - public static Path createNotReadableVersionOf(Path that){ + public static Path createNotReadableVersionOf(Path that) { return new Path(that.href, that.title, that.isFolder, that.size, false); } @@ -716,15 +717,15 @@ public final class DirectoryBrowserSupport implements HttpResponse { @Override public int compare(VirtualFile lhs, VirtualFile rhs) { // directories first, files next - int r = dirRank(lhs)-dirRank(rhs); - if(r!=0) return r; + int r = dirRank(lhs) - dirRank(rhs); + if (r != 0) return r; // otherwise alphabetical return this.collator.compare(lhs.getName(), rhs.getName()); } private int dirRank(VirtualFile f) { try { - if(f.isDirectory()) return 0; + if (f.isDirectory()) return 0; else return 1; } catch (IOException ex) { return 0; @@ -732,15 +733,17 @@ public final class DirectoryBrowserSupport implements HttpResponse { } } - private static final class BuildChildPaths extends MasterToSlaveCallable>,IOException> { + private static final class BuildChildPaths extends MasterToSlaveCallable>, IOException> { private VirtualFile root; private final VirtualFile cur; private final Locale locale; + BuildChildPaths(VirtualFile root, VirtualFile cur, Locale locale) { this.root = root; this.cur = cur; this.locale = locale; } + @Override public List> call() throws IOException { return buildChildPaths(cur, locale); } @@ -750,23 +753,24 @@ public final class DirectoryBrowserSupport implements HttpResponse { * list of {@link Path} represents one child item to be shown * (this mechanism is used to skip empty intermediate directory.) */ + @SuppressFBWarnings(value = "SBSC_USE_STRINGBUFFER_CONCATENATION", justification = "no big deal") private static List> buildChildPaths(VirtualFile cur, Locale locale) throws IOException { List> r = new ArrayList<>(); VirtualFile[] files = cur.list(getNoFollowLinks()); - Arrays.sort(files,new FileComparator(locale)); - - for( VirtualFile f : files ) { + Arrays.sort(files, new FileComparator(locale)); + + for (VirtualFile f : files) { Path p = new Path(Util.rawEncode(f.getName()), f.getName(), f.isDirectory(), f.length(), f.canRead(), f.lastModified()); - if(!f.isDirectory()) { + if (!f.isDirectory()) { r.add(Collections.singletonList(p)); } else { // find all empty intermediate directory List l = new ArrayList<>(); l.add(p); String relPath = Util.rawEncode(f.getName()); - while(true) { + while (true) { // files that don't start with '.' qualify for 'meaningful files', nor SCM related files List sub = new ArrayList<>(); for (VirtualFile vf : f.list(getNoFollowLinks())) { @@ -775,11 +779,11 @@ public final class DirectoryBrowserSupport implements HttpResponse { sub.add(vf); } } - if (sub.size() !=1 || !sub.get(0).isDirectory()) + if (sub.size() != 1 || !sub.get(0).isDirectory()) break; f = sub.get(0); - relPath += '/'+Util.rawEncode(f.getName()); - l.add(new Path(relPath,f.getName(),true, f.length(), f.canRead(), f.lastModified())); + relPath += '/' + Util.rawEncode(f.getName()); + l.add(new Path(relPath, f.getName(), true, f.length(), f.canRead(), f.lastModified())); } r.add(l); } diff --git a/core/src/main/java/hudson/model/DisplayNameListener.java b/core/src/main/java/hudson/model/DisplayNameListener.java index c8c0cc6d72322e962115c3e24032d0433b19102d..2aee0c035c17b667fc7b1716c14ee305f9119f05 100644 --- a/core/src/main/java/hudson/model/DisplayNameListener.java +++ b/core/src/main/java/hudson/model/DisplayNameListener.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2011, Yahoo!, 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 @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; @@ -41,7 +42,7 @@ public class DisplayNameListener extends ItemListener { private static final Logger LOGGER = Logger.getLogger(DisplayNameListener.class.getName()); /** - * Called after the user has clicked OK in the New Job page when + * Called after the user has clicked OK in the New Job page when * Copy existing job has been selected. * The fields in item will be displayed in when the config page is loaded * displayed. @@ -49,11 +50,11 @@ public class DisplayNameListener extends ItemListener { @Override public void onCopied(Item src, Item item) { // bug 5056825 - Display name field should be cleared when you copy a job within the same folder. - if(item instanceof AbstractItem && src.getParent() == item.getParent()) { - AbstractItem dest = (AbstractItem)item; - try { + if (item instanceof AbstractItem && src.getParent() == item.getParent()) { + AbstractItem dest = (AbstractItem) item; + try { dest.setDisplayName(null); - } catch(IOException ioe) { + } catch (IOException ioe) { LOGGER.log(Level.WARNING, String.format("onCopied():Exception while trying to clear the displayName for Item.name:%s", item.getName()), ioe); } } @@ -70,9 +71,9 @@ public class DisplayNameListener extends ItemListener { @Override public void onRenamed(Item item, String oldName, String newName) { // bug 5077308 - Display name field should be cleared when you rename a job. - if(item instanceof AbstractItem) { - AbstractItem abstractItem = (AbstractItem)item; - if(oldName.equals(abstractItem.getDisplayName())) { + if (item instanceof AbstractItem) { + AbstractItem abstractItem = (AbstractItem) item; + if (oldName.equals(abstractItem.getDisplayName())) { // the user renamed the job, but the old project name which is shown as the // displayname if no displayname was set, has been set into the displayname field. // This means that the displayname was never set, so we want to set it @@ -81,7 +82,7 @@ public class DisplayNameListener extends ItemListener { LOGGER.info(String.format("onRenamed():Setting displayname to null for item.name=%s", item.getName())); abstractItem.setDisplayName(null); } - catch(IOException ioe) { + catch (IOException ioe) { LOGGER.log(Level.WARNING, String.format("onRenamed():Exception while trying to clear the displayName for Item.name:%s", item.getName()), ioe); } diff --git a/core/src/main/java/hudson/model/DownloadService.java b/core/src/main/java/hudson/model/DownloadService.java index 92713f0cf9b153a54c56eb4df0242d5d71eb899a..000ef9f48d2f386727a72dd81b2d452869cc4f70 100644 --- a/core/src/main/java/hudson/model/DownloadService.java +++ b/core/src/main/java/hudson/model/DownloadService.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import static java.util.concurrent.TimeUnit.DAYS; @@ -83,6 +84,7 @@ public class DownloadService { * * @deprecated browser-based download has been disabled */ + @Deprecated public String generateFragment() { return ""; @@ -94,7 +96,7 @@ public class DownloadService { */ public Downloadable getById(String id) { for (Downloadable d : Downloadable.all()) - if(d.getId().equals(id)) + if (d.getId().equals(id)) return d; return null; } @@ -207,8 +209,8 @@ public class DownloadService { private final String id; private final String url; private final long interval; - private volatile long due=0; - private volatile long lastAttempt=Long.MIN_VALUE; + private volatile long due = 0; + private volatile long lastAttempt = Long.MIN_VALUE; /** * Creates a new downloadable. @@ -289,14 +291,14 @@ public class DownloadService { */ @NonNull public static String idFor(@NonNull Class clazz) { - return clazz.getName().replace('$','.'); + return clazz.getName().replace('$', '.'); } /** * URL to download. */ public String getUrl() { - return Jenkins.get().getUpdateCenter().getDefaultBaseUrl()+"updates/"+url; + return Jenkins.get().getUpdateCenter().getDefaultBaseUrl() + "updates/" + url; } /** @@ -331,18 +333,18 @@ public class DownloadService { * This is where the retrieved file will be stored. */ public TextFile getDataFile() { - return new TextFile(new File(Jenkins.get().getRootDir(),"updates/"+id)); + return new TextFile(new File(Jenkins.get().getRootDir(), "updates/" + id)); } /** * When shall we retrieve this file next time? */ public long getDue() { - if(due==0) + if (due == 0) // if the file doesn't exist, this code should result // in a very small (but >0) due value, which should trigger // the retrieval immediately. - due = getDataFile().file.lastModified()+interval; + due = getDataFile().file.lastModified() + interval; return due; } @@ -352,7 +354,7 @@ public class DownloadService { */ public JSONObject getData() throws IOException { TextFile df = getDataFile(); - if(df.exists()) + if (df.exists()) try { return JSONObject.fromObject(df.read()); } catch (JSONException e) { @@ -371,7 +373,7 @@ public class DownloadService { TextFile df = getDataFile(); df.write(json); Files.setLastModifiedTime(Util.fileToPath(df.file), FileTime.fromMillis(dataTimestamp)); - LOGGER.info("Obtained the updated data file for "+id); + LOGGER.info("Obtained the updated data file for " + id); return FormValidation.ok(); } @@ -389,14 +391,14 @@ public class DownloadService { jsonString = loadJSONHTML(new URL(site + ".html?id=" + URLEncoder.encode(getId(), "UTF-8") + "&version=" + URLEncoder.encode(Jenkins.VERSION, "UTF-8"))); toolInstallerMetadataExists = true; } catch (Exception e) { - LOGGER.log(Level.FINE, "Could not load json from " + site, e ); + LOGGER.log(Level.FINE, "Could not load json from " + site, e); continue; } JSONObject o = JSONObject.fromObject(jsonString); if (signatureCheck) { - FormValidation e = updatesite.getJsonSignatureValidator(signatureValidatorPrefix +" '"+id+"'").verifySignature(o); - if (e.kind!= FormValidation.Kind.OK) { - LOGGER.log(Level.WARNING, "signature check failed for " + site, e ); + FormValidation e = updatesite.getJsonSignatureValidator(signatureValidatorPrefix + " '" + id + "'").verifySignature(o); + if (e.kind != FormValidation.Kind.OK) { + LOGGER.log(Level.WARNING, "signature check failed for " + site, e); continue; } } @@ -428,7 +430,7 @@ public class DownloadService { * @param the generic class * @return true if the list has duplicates, false otherwise */ - public static boolean hasDuplicates (List genericList, String comparator) { + public static boolean hasDuplicates(List genericList, String comparator) { if (genericList.isEmpty()) { return false; } @@ -439,9 +441,9 @@ public class DownloadService { LOGGER.warning("comparator: " + comparator + "does not exist for " + genericList.get(0).getClass() + ", " + e); return false; } - for (int i = 0; i < genericList.size(); i ++ ) { + for (int i = 0; i < genericList.size(); i++) { T data1 = genericList.get(i); - for (int j = i + 1; j < genericList.size(); j ++ ) { + for (int j = i + 1; j < genericList.size(); j++) { T data2 = genericList.get(j); try { if (field.get(data1).equals(field.get(data2))) { @@ -484,7 +486,7 @@ public class DownloadService { @CheckForNull public static Downloadable get(String id) { for (Downloadable d : all()) { - if(d.id.equals(id)) + if (d.id.equals(id)) return d; } return null; @@ -492,17 +494,17 @@ public class DownloadService { private static final Logger LOGGER = Logger.getLogger(Downloadable.class.getName()); private static final long DEFAULT_INTERVAL = - SystemProperties.getLong(Downloadable.class.getName()+".defaultInterval", DAYS.toMillis(1)); + SystemProperties.getLong(Downloadable.class.getName() + ".defaultInterval", DAYS.toMillis(1)); } // TODO this was previously referenced in the browser-based download, but should probably be checked for the server-based download @SuppressFBWarnings(value = "MS_SHOULD_BE_FINAL", justification = "Accessible via System Groovy Scripts") - public static boolean neverUpdate = SystemProperties.getBoolean(DownloadService.class.getName()+".never"); + public static boolean neverUpdate = SystemProperties.getBoolean(DownloadService.class.getName() + ".never"); /** * May be used to temporarily disable signature checking on {@link DownloadService} and {@link UpdateCenter}. * Useful when upstream signatures are broken, such as due to expired certificates. */ @SuppressFBWarnings(value = "MS_SHOULD_BE_FINAL", justification = "Accessible via System Groovy Scripts") - public static boolean signatureCheck = !SystemProperties.getBoolean(DownloadService.class.getName()+".noSignatureCheck"); + public static boolean signatureCheck = !SystemProperties.getBoolean(DownloadService.class.getName() + ".noSignatureCheck"); } diff --git a/core/src/main/java/hudson/model/Environment.java b/core/src/main/java/hudson/model/Environment.java index 889116cdc9da204edb51ab854960f592820a6ae7..987d74e7d6d228921a758ceb05475da68499dcfd 100644 --- a/core/src/main/java/hudson/model/Environment.java +++ b/core/src/main/java/hudson/model/Environment.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import hudson.EnvVars; @@ -52,60 +53,60 @@ import java.util.Map; * @see RunListener#setUpEnvironment(AbstractBuild, Launcher, BuildListener) */ public abstract class Environment { - /** - * Adds environmental variables for the builds to the given map. - * - *

    - * If the {@link Environment} object wants to pass in information to the - * build that runs, it can do so by exporting additional environment - * variables to the map. - * - *

    - * When this method is invoked, the map already contains the current - * "planned export" list. - * - * @param env - * never null. This really should have been typed as {@link EnvVars} + /** + * Adds environmental variables for the builds to the given map. + * + *

    + * If the {@link Environment} object wants to pass in information to the + * build that runs, it can do so by exporting additional environment + * variables to the map. + * + *

    + * When this method is invoked, the map already contains the current + * "planned export" list. + * + * @param env + * never null. This really should have been typed as {@link EnvVars} * but by the time we realized it it was too late. - */ - public void buildEnvVars(Map env) { - // no-op by default - } + */ + public void buildEnvVars(Map env) { + // no-op by default + } - /** - * Runs after the {@link Builder} completes, and performs a tear down. - * - *

    - * This method is invoked even when the build failed, so that the clean up - * operation can be performed regardless of the build result (for example, - * you'll want to stop application server even if a build fails.) - * - * @param build - * The same {@link Build} object given to the set up method. - * @param listener - * The same {@link BuildListener} object given to the set up - * method. - * @return true if the build can continue, false if there was an error and - * the build needs to be failed. - * @throws IOException - * terminates the build abnormally. Jenkins will handle the - * exception and reports a nice error message. - */ - public boolean tearDown(AbstractBuild build, BuildListener listener) - throws IOException, InterruptedException { - return true; - } + /** + * Runs after the {@link Builder} completes, and performs a tear down. + * + *

    + * This method is invoked even when the build failed, so that the clean up + * operation can be performed regardless of the build result (for example, + * you'll want to stop application server even if a build fails.) + * + * @param build + * The same {@link Build} object given to the set up method. + * @param listener + * The same {@link BuildListener} object given to the set up + * method. + * @return true if the build can continue, false if there was an error and + * the build needs to be failed. + * @throws IOException + * terminates the build abnormally. Jenkins will handle the + * exception and reports a nice error message. + */ + public boolean tearDown(AbstractBuild build, BuildListener listener) + throws IOException, InterruptedException { + return true; + } /** * Creates {@link Environment} implementation that just sets the variables as given in the parameter. */ - public static Environment create(final EnvVars envVars) { - return new Environment() { - @Override - public void buildEnvVars(Map env) { - env.putAll(envVars); - } - }; - } - + public static Environment create(final EnvVars envVars) { + return new Environment() { + @Override + public void buildEnvVars(Map env) { + env.putAll(envVars); + } + }; + } + } diff --git a/core/src/main/java/hudson/model/EnvironmentContributingAction.java b/core/src/main/java/hudson/model/EnvironmentContributingAction.java index 1df68de4c37f46f806a723c787c9574fab98a0d6..0de322014c23533edac67f03f11d65624170f1d3 100644 --- a/core/src/main/java/hudson/model/EnvironmentContributingAction.java +++ b/core/src/main/java/hudson/model/EnvironmentContributingAction.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import edu.umd.cs.findbugs.annotations.NonNull; diff --git a/core/src/main/java/hudson/model/EnvironmentContributor.java b/core/src/main/java/hudson/model/EnvironmentContributor.java index 926ec551060fb6caed22e01f6867a04f490a58a8..0fa5a96c70af06520bd7faadd61a4be641290470 100644 --- a/core/src/main/java/hudson/model/EnvironmentContributor.java +++ b/core/src/main/java/hudson/model/EnvironmentContributor.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import edu.umd.cs.findbugs.annotations.NonNull; diff --git a/core/src/main/java/hudson/model/EnvironmentList.java b/core/src/main/java/hudson/model/EnvironmentList.java index 1c1b07a205731c0ece2cf9569f8dff91aa6639ad..0e11a1c51ccc8f1a73a7916e030f9f56e3925bd5 100644 --- a/core/src/main/java/hudson/model/EnvironmentList.java +++ b/core/src/main/java/hudson/model/EnvironmentList.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import java.util.AbstractList; diff --git a/core/src/main/java/hudson/model/EnvironmentSpecific.java b/core/src/main/java/hudson/model/EnvironmentSpecific.java index 32663e721491cebf1ba248e17a9392bba9849577..53e127e671e53175770d9254349cb47785a6ff93 100644 --- a/core/src/main/java/hudson/model/EnvironmentSpecific.java +++ b/core/src/main/java/hudson/model/EnvironmentSpecific.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import hudson.EnvVars; @@ -28,7 +29,7 @@ import hudson.slaves.NodeSpecific; /** * Represents any concept that can be adapted for a certain environment. - * + * * Mainly for documentation purposes. * * @since 1.286 @@ -37,8 +38,8 @@ import hudson.slaves.NodeSpecific; * @see NodeSpecific */ public interface EnvironmentSpecific> { - /** - * Returns a specialized copy of T for functioning in the given environment. - */ - T forEnvironment(EnvVars environment); + /** + * Returns a specialized copy of T for functioning in the given environment. + */ + T forEnvironment(EnvVars environment); } diff --git a/core/src/main/java/hudson/model/Executor.java b/core/src/main/java/hudson/model/Executor.java index f719b65c52ebc01ff88964815c24f02b50695494..e7b14b72aebfab5a4ab28ea9b97ae54e55783f78 100644 --- a/core/src/main/java/hudson/model/Executor.java +++ b/core/src/main/java/hudson/model/Executor.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import static hudson.model.queue.Executables.getParentOf; @@ -147,7 +148,7 @@ public class Executor extends Thread implements ModelObject { private final List causes = new Vector<>(); public Executor(@NonNull Computer owner, int n) { - super("Executor #"+n+" for "+owner.getDisplayName()); + super("Executor #" + n + " for " + owner.getDisplayName()); this.owner = owner; this.queue = Jenkins.get().getQueue(); this.number = n; @@ -194,6 +195,7 @@ public class Executor extends Thread implements ModelObject { * * @since 1.417 */ + public void interrupt(Result result) { interrupt(result, false); } @@ -269,7 +271,7 @@ public class Executor extends Thread implements ModelObject { * * @since 1.425 */ - public void recordCauseOfInterruption(Run build, TaskListener listener) { + public void recordCauseOfInterruption(Run build, TaskListener listener) { List r; // atomically get&clear causes. @@ -363,7 +365,7 @@ public class Executor extends Thread implements ModelObject { workUnit.setExecutor(Executor.this); queue.onStartExecuting(Executor.this); if (LOGGER.isLoggable(FINE)) - LOGGER.log(FINE, getName()+" grabbed "+workUnit+" from queue"); + LOGGER.log(FINE, getName() + " grabbed " + workUnit + " from queue"); SubTask task = workUnit.work; Executable executable = task.createExecutable(); if (executable == null) { @@ -392,7 +394,7 @@ public class Executor extends Thread implements ModelObject { lock.readLock().unlock(); } if (LOGGER.isLoggable(FINE)) - LOGGER.log(FINE, getName()+" is going to execute "+executable); + LOGGER.log(FINE, getName() + " is going to execute " + executable); Throwable problems = null; try { @@ -419,7 +421,7 @@ public class Executor extends Thread implements ModelObject { workUnit.context.item.getAllActions(), }); } - for (Action action: workUnit.context.actions) { + for (Action action : workUnit.context.actions) { ((Actionable) executable).addAction(action); } } @@ -463,10 +465,10 @@ public class Executor extends Thread implements ModelObject { } } } catch (InterruptedException e) { - LOGGER.log(FINE, getName()+" interrupted",e); + LOGGER.log(FINE, getName() + " interrupted", e); // die peacefully - } catch(Exception | Error e) { - LOGGER.log(SEVERE, getName()+": Unexpected executor death", e); + } catch (Exception | Error e) { + LOGGER.log(SEVERE, getName() + ": Unexpected executor death", e); } finally { if (asynchronousExecution == null) { finish2(); @@ -533,7 +535,7 @@ public class Executor extends Thread implements ModelObject { /** * Same as {@link #getCurrentExecutable} but checks {@link Item#READ}. */ - @Exported(name="currentExecutable") + @Exported(name = "currentExecutable") @Restricted(DoNotUse.class) // for exporting only public Queue.Executable getCurrentExecutableForApi() { Executable candidate = getCurrentExecutable(); @@ -593,7 +595,7 @@ public class Executor extends Thread implements ModelObject { */ @Override public String getDisplayName() { - return "Executor #"+getNumber(); + return "Executor #" + getNumber(); } /** @@ -846,8 +848,8 @@ public class Executor extends Thread implements ModelObject { */ @RequirePOST @Deprecated - public void doStop( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { - doStop().generateResponse(req,rsp,this); + public void doStop(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { + doStop().generateResponse(req, rsp, this); } /** @@ -879,7 +881,7 @@ public class Executor extends Thread implements ModelObject { try { if (executable != null) { if (runExtId == null || runExtId.isEmpty() || ! (executable instanceof Run) - || (runExtId.equals(((Run) executable).getExternalizableId()))) { + || (runExtId.equals(((Run) executable).getExternalizableId()))) { final Queue.Task ownerTask = getParentOf(executable).getOwnerTask(); boolean canAbort = ownerTask.hasAbortPermission(); if (canAbort && ownerTask instanceof AccessControlled) { @@ -913,7 +915,7 @@ public class Executor extends Thread implements ModelObject { lock.readLock().lock(); try { return executable != null && getParentOf(executable).getOwnerTask().hasAbortPermission(); - } catch(RuntimeException ex) { + } catch (RuntimeException ex) { if (!(ex instanceof AccessDeniedException)) { // Prevents UI from exploding in the case of unexpected runtime exceptions LOGGER.log(WARNING, "Unhandled exception", ex); @@ -957,12 +959,12 @@ public class Executor extends Thread implements ModelObject { final Executor old = IMPERSONATION.get(); IMPERSONATION.set(Executor.this); try { - return m.invoke(o,args); + return m.invoke(o, args); } finally { IMPERSONATION.set(old); } } - }.wrap(type,core); + }.wrap(type, core); } /** diff --git a/core/src/main/java/hudson/model/ExecutorListener.java b/core/src/main/java/hudson/model/ExecutorListener.java index eb4a8cdb268184005568b43ff7b2b2325dd32c1a..6500e6acc2eccc1e6cc9c587b75024da70363c92 100644 --- a/core/src/main/java/hudson/model/ExecutorListener.java +++ b/core/src/main/java/hudson/model/ExecutorListener.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Stephen Connolly - * + * * 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 @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import hudson.ExtensionPoint; diff --git a/core/src/main/java/hudson/model/Failure.java b/core/src/main/java/hudson/model/Failure.java index 1931d505eb262d838d24851181ef31bca35a99d4..71318dd0464b57bd1afcd627c70a2afb8aa77748 100644 --- a/core/src/main/java/hudson/model/Failure.java +++ b/core/src/main/java/hudson/model/Failure.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import edu.umd.cs.findbugs.annotations.CheckForNull; @@ -37,7 +38,7 @@ import org.kohsuke.stapler.StaplerResponse; *

    * The error page is rendered into HTML, but without a stack trace. So only use * this exception when the error condition is anticipated by the program, and where - * we nor users don't need to see the stack trace to figure out the root cause. + * we nor users don't need to see the stack trace to figure out the root cause. * * @author Kohsuke Kawaguchi * @since 1.321 @@ -46,7 +47,7 @@ public class Failure extends RuntimeException implements HttpResponse { private final boolean pre; public Failure(String message) { - this(message,false); + this(message, false); } public Failure(String message, boolean pre) { @@ -63,12 +64,12 @@ public class Failure extends RuntimeException implements HttpResponse { @Override public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException, ServletException { - req.setAttribute("message",getMessage()); - if(pre) - req.setAttribute("pre",true); + req.setAttribute("message", getMessage()); + if (pre) + req.setAttribute("pre", true); if (node instanceof AbstractItem) // Maintain ancestors - rsp.forward(Jenkins.get(), ((AbstractItem)node).getUrl() + "error", req); + rsp.forward(Jenkins.get(), ((AbstractItem) node).getUrl() + "error", req); else - rsp.forward(node instanceof AbstractModelObject ? node : Jenkins.get() ,"error", req); + rsp.forward(node instanceof AbstractModelObject ? node : Jenkins.get(), "error", req); } } diff --git a/core/src/main/java/hudson/model/FileParameterDefinition.java b/core/src/main/java/hudson/model/FileParameterDefinition.java index bc4690928597e704cc10229fc163b3bc08ce3a33..dcaf022b20fa1541a13291e8ea9ed857bed7adca 100644 --- a/core/src/main/java/hudson/model/FileParameterDefinition.java +++ b/core/src/main/java/hudson/model/FileParameterDefinition.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Seiji Sogabe, Tom Huybrechts - * + * * 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 @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import edu.umd.cs.findbugs.annotations.CheckForNull; @@ -70,7 +71,7 @@ public class FileParameterDefinition extends ParameterDefinition { return p; } - @Extension @Symbol({"file","fileParam"}) + @Extension @Symbol({"file", "fileParam"}) public static class DescriptorImpl extends ParameterDescriptor { @Override public String getDisplayName() { @@ -83,17 +84,17 @@ public class FileParameterDefinition extends ParameterDefinition { } } - @Override - public ParameterValue createValue(StaplerRequest req) { + @Override + public ParameterValue createValue(StaplerRequest req) { FileItem src; try { - src = req.getFileItem( getName() ); + src = req.getFileItem(getName()); } catch (ServletException | IOException e) { // Not sure what to do here. We might want to raise this // but that would involve changing the throws for this call return null; } - if ( src == null ) { + if (src == null) { // the requested file parameter wasn't uploaded return null; } @@ -101,14 +102,14 @@ public class FileParameterDefinition extends ParameterDefinition { p.setDescription(getDescription()); p.setLocation(getName()); return p; - } + } /** * Strip off the path portion if the given path contains it. */ private String getFileName(String possiblyPathName) { - possiblyPathName = possiblyPathName.substring(possiblyPathName.lastIndexOf('/')+1); - possiblyPathName = possiblyPathName.substring(possiblyPathName.lastIndexOf('\\')+1); + possiblyPathName = possiblyPathName.substring(possiblyPathName.lastIndexOf('/') + 1); + possiblyPathName = possiblyPathName.substring(possiblyPathName.lastIndexOf('\\') + 1); return possiblyPathName; } @@ -116,7 +117,7 @@ public class FileParameterDefinition extends ParameterDefinition { @Override public ParameterValue createValue(CLICommand command, String value) throws IOException, InterruptedException { // capture the file to the server - File local = File.createTempFile("jenkins","parameter"); + File local = File.createTempFile("jenkins", "parameter"); String name; if (value.isEmpty()) { FileUtils.copyInputStreamToFile(command.stdin, local); diff --git a/core/src/main/java/hudson/model/FileParameterValue.java b/core/src/main/java/hudson/model/FileParameterValue.java index cc9f39faefee085a03b884477dbe01a216d25cfe..974f76b2f45774186c7d7d02d0a34050a8710a45 100644 --- a/core/src/main/java/hudson/model/FileParameterValue.java +++ b/core/src/main/java/hudson/model/FileParameterValue.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; @@ -87,7 +88,7 @@ public class FileParameterValue extends ParameterValue { /** * Overrides the location in the build to place this file. Initially set to {@link #getName()} - * The location could be directly the filename or also a hierarchical path. + * The location could be directly the filename or also a hierarchical path. * The intermediate folders will be created automatically. * Take care that no escape from the current directory is allowed and will result in the failure of the build. */ @@ -127,8 +128,8 @@ public class FileParameterValue extends ParameterValue { * Exposes the originalFileName as an environment variable. */ @Override - public void buildEnvironment(Run build, EnvVars env) { - env.put(name,originalFileName); + public void buildEnvironment(Run build, EnvVars env) { + env.put(name, originalFileName); } @Override @@ -152,13 +153,13 @@ public class FileParameterValue extends ParameterValue { } @Override - public BuildWrapper createBuildWrapper(AbstractBuild build) { + public BuildWrapper createBuildWrapper(AbstractBuild build) { return new BuildWrapper() { @SuppressFBWarnings(value = {"FILE_UPLOAD_FILENAME", "NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE"}, justification = "TODO needs triage") @Override public Environment setUp(AbstractBuild build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException { - if (!StringUtils.isEmpty(location) && !StringUtils.isEmpty(file.getName())) { - listener.getLogger().println("Copying file to "+location); + if (!StringUtils.isEmpty(location) && !StringUtils.isEmpty(file.getName())) { + listener.getLogger().println("Copying file to " + location); FilePath ws = build.getWorkspace(); if (ws == null) { throw new IllegalStateException("The workspace should be created when setUp method is called"); @@ -176,48 +177,48 @@ public class FileParameterValue extends ParameterValue { locationFilePath.delete(); } - locationFilePath.copyFrom(file); + locationFilePath.copyFrom(file); locationFilePath.copyTo(new FilePath(getLocationUnderBuild(build))); - } + } return new Environment() {}; } }; } - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result - + (location == null ? 0 : location.hashCode()); - return result; - } - - /** - * Compares file parameters (existing files will be considered as different). - * @since 1.586 Function has been modified in order to avoid JENKINS-19017 issue (wrong merge of builds in the queue). - */ - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - FileParameterValue other = (FileParameterValue) obj; - - if (location == null && other.location == null) - return true; // Consider null parameters as equal - - //TODO: check fingerprints or checksums to improve the behavior (JENKINS-25211) - // Return false even if files are equal - return false; - } + @Override + public int hashCode() { + final int prime = 31; + int result = super.hashCode(); + result = prime * result + + (location == null ? 0 : location.hashCode()); + return result; + } + + /** + * Compares file parameters (existing files will be considered as different). + * @since 1.586 Function has been modified in order to avoid JENKINS-19017 issue (wrong merge of builds in the queue). + */ + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (!super.equals(obj)) + return false; + if (getClass() != obj.getClass()) + return false; + FileParameterValue other = (FileParameterValue) obj; + + if (location == null && other.location == null) + return true; // Consider null parameters as equal + + //TODO: check fingerprints or checksums to improve the behavior (JENKINS-25211) + // Return false even if files are equal + return false; + } @Override public String toString() { - return "(FileParameterValue) " + getName() + "='" + originalFileName + "'"; + return "(FileParameterValue) " + getName() + "='" + originalFileName + "'"; } @Override public String getShortDescription() { @@ -228,7 +229,7 @@ public class FileParameterValue extends ParameterValue { * Serve this file parameter in response to a {@link StaplerRequest}. */ public DirectoryBrowserSupport doDynamic(StaplerRequest request, StaplerResponse response) { - AbstractBuild build = (AbstractBuild)request.findAncestor(AbstractBuild.class).getObject(); + AbstractBuild build = (AbstractBuild) request.findAncestor(AbstractBuild.class).getObject(); File fileParameter = getFileParameterFolderUnderBuild(build); return new DirectoryBrowserSupport(build, new FilePath(fileParameter), Messages.FileParameterValue_IndexTitle(), "folder.png", false); } @@ -243,7 +244,7 @@ public class FileParameterValue extends ParameterValue { return new File(getFileParameterFolderUnderBuild(build), location); } - private File getFileParameterFolderUnderBuild(AbstractBuild build){ + private File getFileParameterFolderUnderBuild(AbstractBuild build) { return new File(build.getRootDir(), FOLDER_NAME); } diff --git a/core/src/main/java/hudson/model/Fingerprint.java b/core/src/main/java/hudson/model/Fingerprint.java index fbdb97f7722ac234baf3263d58025dbacc15d3b2..d4b57badaefcc3680d42cd05133e373f8e24115b 100644 --- a/core/src/main/java/hudson/model/Fingerprint.java +++ b/core/src/main/java/hudson/model/Fingerprint.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Yahoo! 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 @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import com.infradna.tool.bridge_method_injector.WithBridgeMethods; @@ -86,7 +87,7 @@ public class Fingerprint implements ModelObject, Saveable { /** * Pointer to a {@link Build}. */ - @ExportedBean(defaultVisibility=2) + @ExportedBean(defaultVisibility = 2) public static class BuildPtr { String name; final int number; @@ -97,13 +98,13 @@ public class Fingerprint implements ModelObject, Saveable { } public BuildPtr(Run run) { - this( run.getParent().getFullName(), run.getNumber() ); + this(run.getParent().getFullName(), run.getNumber()); } /** * Gets {@link Job#getFullName() the full name of the job}. * Such job could be since then removed, so there might not be a corresponding {@link Job}. - * + * * @return A name of the job */ @Exported @@ -111,12 +112,12 @@ public class Fingerprint implements ModelObject, Saveable { public String getName() { return name; } - + /** * Checks if the current user has permission to see this pointer. * @return {@code true} if the job exists and user has {@link Item#READ} permissions - * or if the current user has {@link Jenkins#ADMINISTER} permissions. - * If the job exists, but the current user has no permission to discover it, + * or if the current user has {@link Jenkins#ADMINISTER} permissions. + * If the job exists, but the current user has no permission to discover it, * {@code false} will be returned. * If the job has been deleted and the user has no {@link Jenkins#ADMINISTER} permissions, * it also returns {@code false} in order to avoid the job existence fact exposure. @@ -128,22 +129,22 @@ public class Fingerprint implements ModelObject, Saveable { if (instance.hasPermission(Jenkins.ADMINISTER)) { return true; } - + return canDiscoverItem(name); } - - + + void setName(String newName) { name = newName; } - + /** * Gets the {@link Job} that this pointer points to, * or null if such a job no longer exists. */ - @WithBridgeMethods(value=AbstractProject.class, castRequired=true) - public Job getJob() { + @WithBridgeMethods(value = AbstractProject.class, castRequired = true) + public Job getJob() { return Jenkins.get().getItemByFullName(name, Job.class); } @@ -165,19 +166,19 @@ public class Fingerprint implements ModelObject, Saveable { */ public Run getRun() { Job j = getJob(); - if(j==null) return null; + if (j == null) return null; return j.getBuildByNumber(number); } private boolean isAlive() { - return getRun()!=null; + return getRun() != null; } /** * Returns true if {@link BuildPtr} points to the given run. */ public boolean is(Run r) { - return r.getNumber()==number && r.getParent().getFullName().equals(name); + return r.getNumber() == number && r.getParent().getFullName().equals(name); } /** @@ -193,12 +194,12 @@ public class Fingerprint implements ModelObject, Saveable { * *

    * This is useful to check if an artifact in MavenModule - * belongs to MavenModuleSet. + * belongs to MavenModuleSet. */ public boolean belongsTo(Job job) { Item p = Jenkins.get().getItemByFullName(name); - while(p!=null) { - if(p==job) + while (p != null) { + if (p == job) return true; // go up the chain while we @@ -221,13 +222,13 @@ public class Fingerprint implements ModelObject, Saveable { /** * Range of build numbers [start,end). Immutable. */ - @ExportedBean(defaultVisibility=4) + @ExportedBean(defaultVisibility = 4) public static final class Range { final int start; final int end; public Range(int start, int end) { - assert start ranges; @@ -364,10 +365,10 @@ public class Fingerprint implements ModelObject, Saveable { return new Iterable() { @Override public Iterator iterator() { - return new Iterators.FlattenIterator(ranges) { + return new Iterators.FlattenIterator(ranges) { @Override protected Iterator expand(Range range) { - return Iterators.sequence(range.start,range.end).iterator(); + return Iterators.sequence(range.start, range.end).iterator(); } }; } @@ -382,10 +383,10 @@ public class Fingerprint implements ModelObject, Saveable { return new Iterable() { @Override public Iterator iterator() { - return new Iterators.FlattenIterator(Iterators.reverse(ranges)) { + return new Iterators.FlattenIterator(Iterators.reverse(ranges)) { @Override protected Iterator expand(Range range) { - return Iterators.reverseSequence(range.start,range.end).iterator(); + return Iterators.reverseSequence(range.start, range.end).iterator(); } }; } @@ -405,27 +406,27 @@ public class Fingerprint implements ModelObject, Saveable { * If the set already includes this number, this will be a no-op. */ public synchronized void add(int n) { - for( int i=0; i intersection = new ArrayList<>(); - int lhs=0,rhs=0; - while(lhs sub = new ArrayList<>(); - int lhs=0,rhs=0; - while(lhs0) buf.append(','); + if (buf.length() > 0) buf.append(','); buf.append(r); } return buf.toString(); @@ -647,7 +648,7 @@ public class Fingerprint implements ModelObject, Saveable { * If this range is empty, this method throws an exception. */ public synchronized int max() { - return ranges.get(ranges.size()-1).end; + return ranges.get(ranges.size() - 1).end; } /** @@ -658,7 +659,7 @@ public class Fingerprint implements ModelObject, Saveable { * Note that {} is smaller than any n. */ public synchronized boolean isSmallerThan(int n) { - if(ranges.isEmpty()) return true; + if (ranges.isEmpty()) return true; return ranges.get(ranges.size() - 1).isSmallerThan(n); } @@ -679,8 +680,8 @@ public class Fingerprint implements ModelObject, Saveable { return rs; } - String[] items = Util.tokenize(list,","); - if(items.length > 1 && items.length <= StringUtils.countMatches(list, ",")) { + String[] items = Util.tokenize(list, ","); + if (items.length > 1 && items.length <= StringUtils.countMatches(list, ",")) { if (!skipError) { throw new IllegalArgumentException( String.format("Unable to parse '%s', expected correct notation M,N or M-N", list)); @@ -702,8 +703,8 @@ public class Fingerprint implements ModelObject, Saveable { continue; } - if(s.contains("-")) { - if(StringUtils.countMatches(s, "-") > 1) { + if (s.contains("-")) { + if (StringUtils.countMatches(s, "-") > 1) { if (!skipError) { throw new IllegalArgumentException(String.format( "Unable to parse '%s', expected correct notation M,N or M-N", list)); @@ -711,11 +712,11 @@ public class Fingerprint implements ModelObject, Saveable { // ignore malformed ranges like "-5-2" or "2-5-" continue; } - String[] tokens = Util.tokenize(s,"-"); + String[] tokens = Util.tokenize(s, "-"); if (tokens.length == 2) { int left = Integer.parseInt(tokens[0]); int right = Integer.parseInt(tokens[1]); - if(left < 0 || right < 0) { + if (left < 0 || right < 0) { if (!skipError) { throw new IllegalArgumentException( String.format("Unable to parse '%s', expected number above zero", list)); @@ -723,7 +724,7 @@ public class Fingerprint implements ModelObject, Saveable { // ignore a range which starts or ends under zero like "-5-3" continue; } - if(left > right) { + if (left > right) { if (!skipError) { throw new IllegalArgumentException(String.format( "Unable to parse '%s', expected string with a range M-N where M0) buf.append(','); - if(r.isSingle()) + if (buf.length() > 0) buf.append(','); + if (r.isSingle()) buf.append(r.start); else - buf.append(r.start).append('-').append(r.end-1); + buf.append(r.start).append('-').append(r.end - 1); } return buf.toString(); } @Override public Object unmarshal(HierarchicalStreamReader reader, final UnmarshallingContext context) { - if(reader.hasMoreChildren()) { + if (reader.hasMoreChildren()) { /* old format where elements are nested like 1337 1479 */ - return new RangeSet((List)collectionConv.unmarshal(reader,context)); + return new RangeSet((List) collectionConv.unmarshal(reader, context)); } else { - return RangeSet.fromString(reader.getValue(),true); + return RangeSet.fromString(reader.getValue(), true); } } } @@ -821,6 +822,7 @@ public class Fingerprint implements ModelObject, Saveable { locationChanged(item, oldName, newName); } } + private void locationChanged(Item item, String oldName, String newName) { if (item instanceof Job) { Job p = Jenkins.get().getItemByFullName(newName, Job.class); @@ -842,7 +844,7 @@ public class Fingerprint implements ModelObject, Saveable { } private static final DateConverter DATE_CONVERTER = new DateConverter(); - + /** * Time when the fingerprint has been captured. */ @@ -861,7 +863,7 @@ public class Fingerprint implements ModelObject, Saveable { /** * Range of builds that use this file keyed by a job full name. */ - private Hashtable usages = new Hashtable<>(); + private Hashtable usages = new Hashtable<>(); PersistedList facets = new PersistedList<>(this); @@ -871,7 +873,7 @@ public class Fingerprint implements ModelObject, Saveable { private transient volatile List transientFacets = null; public Fingerprint(@CheckForNull Run build, @NonNull String fileName, @NonNull byte[] md5sum) throws IOException { - this(build==null ? null : new BuildPtr(build), fileName, md5sum); + this(build == null ? null : new BuildPtr(build), fileName, md5sum); save(); } @@ -918,7 +920,7 @@ public class Fingerprint implements ModelObject, Saveable { /** * Gets the MD5 hash string. */ - @Exported(name="hash") + @Exported(name = "hash") public @NonNull String getHashString() { return Util.toHexString(md5sum); } @@ -938,7 +940,7 @@ public class Fingerprint implements ModelObject, Saveable { * string like "3 minutes" "1 day" etc. */ public @NonNull String getTimestampString() { - long duration = System.currentTimeMillis()-timestamp.getTime(); + long duration = System.currentTimeMillis() - timestamp.getTime(); return Util.getTimeSpanString(duration); } @@ -951,7 +953,7 @@ public class Fingerprint implements ModelObject, Saveable { */ public @NonNull RangeSet getRangeSet(String jobFullName) { RangeSet r = usages.get(jobFullName); - if(r==null) r = new RangeSet(); + if (r == null) r = new RangeSet(); return r; } @@ -969,11 +971,11 @@ public class Fingerprint implements ModelObject, Saveable { return r; } - public @CheckForNull Hashtable getUsages() { + public @CheckForNull Hashtable getUsages() { return usages; } - @ExportedBean(defaultVisibility=2) + @ExportedBean(defaultVisibility = 2) public static final class RangeItem { @Exported public final String name; @@ -987,7 +989,7 @@ public class Fingerprint implements ModelObject, Saveable { } // this is for remote API - @Exported(name="usage") + @Exported(name = "usage") public @NonNull List _getUsages() { List r = new ArrayList<>(); final Jenkins instance = Jenkins.get(); @@ -1035,11 +1037,11 @@ public class Fingerprint implements ModelObject, Saveable { } void addWithoutSaving(@NonNull String jobFullName, int n) { - synchronized(usages) { // TODO why not synchronized (this) like some, though not all, other accesses? + synchronized (usages) { // TODO why not synchronized (this) like some, though not all, other accesses? RangeSet r = usages.get(jobFullName); - if(r==null) { + if (r == null) { r = new RangeSet(); - usages.put(jobFullName,r); + usages.put(jobFullName, r); } r.add(n); } @@ -1054,20 +1056,20 @@ public class Fingerprint implements ModelObject, Saveable { * without losing too much information. */ public synchronized boolean isAlive() { - if(original!=null && original.isAlive()) + if (original != null && original.isAlive()) return true; - for (Map.Entry e : usages.entrySet()) { - Job j = Jenkins.get().getItemByFullName(e.getKey(),Job.class); - if(j==null) + for (Map.Entry e : usages.entrySet()) { + Job j = Jenkins.get().getItemByFullName(e.getKey(), Job.class); + if (j == null) continue; Run firstBuild = j.getFirstBuild(); - if(firstBuild==null) + if (firstBuild == null) continue; int oldest = firstBuild.getNumber(); - if(!e.getValue().isSmallerThan(oldest)) + if (!e.getValue().isSmallerThan(oldest)) return true; } return false; @@ -1078,22 +1080,22 @@ public class Fingerprint implements ModelObject, Saveable { * * @return true * if this record was modified. - * + * * @throws IOException Save failure */ public synchronized boolean trim() throws IOException { boolean modified = false; - for (Map.Entry e : new Hashtable<>(usages).entrySet()) {// copy because we mutate - Job j = Jenkins.get().getItemByFullName(e.getKey(),Job.class); - if(j==null) {// no such job any more. recycle the record + for (Map.Entry e : new Hashtable<>(usages).entrySet()) { // copy because we mutate + Job j = Jenkins.get().getItemByFullName(e.getKey(), Job.class); + if (j == null) { // no such job any more. recycle the record modified = true; usages.remove(e.getKey()); continue; } Run firstBuild = j.getFirstBuild(); - if(firstBuild==null) {// no builds. recycle the whole record + if (firstBuild == null) { // no builds. recycle the whole record modified = true; usages.remove(e.getKey()); continue; @@ -1106,17 +1108,17 @@ public class Fingerprint implements ModelObject, Saveable { // that are marked as kept RangeSet kept = new RangeSet(); Run r = firstBuild; - while (r!=null && r.isKeepLog()) { + while (r != null && r.isKeepLog()) { kept.add(r.getNumber()); r = r.getNextBuild(); } - if (r==null) { + if (r == null) { // all the build records are permanently kept ones, so we'll just have to keep 'kept' out of whatever currently in 'cur' modified |= cur.retainAll(kept); } else { // otherwise we are ready to discard [0,r.number) except those marked as 'kept' - RangeSet discarding = new RangeSet(new Range(-1,r.getNumber())); + RangeSet discarding = new RangeSet(new Range(-1, r.getNumber())); discarding.removeAll(kept); modified |= cur.removeAll(discarding); } @@ -1154,10 +1156,10 @@ public class Fingerprint implements ModelObject, Saveable { * @since 1.421 */ public @NonNull Collection getFacets() { - if (transientFacets==null) { + if (transientFacets == null) { List transientFacets = new ArrayList<>(); for (TransientFingerprintFacetFactory fff : TransientFingerprintFacetFactory.all()) { - fff.createFor(this,transientFacets); + fff.createFor(this, transientFacets); } this.transientFacets = Collections.unmodifiableList(transientFacets); } @@ -1186,7 +1188,7 @@ public class Fingerprint implements ModelObject, Saveable { @Override public int size() { - return facets.size()+transientFacets.size(); + return facets.size() + transientFacets.size(); } }; } @@ -1202,7 +1204,7 @@ public class Fingerprint implements ModelObject, Saveable { /** * Sorts {@link FingerprintFacet}s by their timestamps. - * @return Sorted list of {@link FingerprintFacet}s + * @return Sorted list of {@link FingerprintFacet}s */ public @NonNull Collection getSortedFacets() { List r = new ArrayList<>(getFacets()); @@ -1247,12 +1249,12 @@ public class Fingerprint implements ModelObject, Saveable { */ @Override public synchronized void save() throws IOException { - if(BulkChange.contains(this)) { + if (BulkChange.contains(this)) { return; } - long start=0; - if(logger.isLoggable(Level.FINE)) + long start = 0; + if (logger.isLoggable(Level.FINE)) start = System.currentTimeMillis(); FingerprintStorage configuredFingerprintStorage = FingerprintStorage.get(); @@ -1270,7 +1272,7 @@ public class Fingerprint implements ModelObject, Saveable { fileFingerprintStorage.delete(this.getHashString()); } - if(logger.isLoggable(Level.FINE)) + if (logger.isLoggable(Level.FINE)) logger.fine("Saving fingerprint " + getHashString() + " took " + (System.currentTimeMillis() - start) + "ms"); } @@ -1308,7 +1310,7 @@ public class Fingerprint implements ModelObject, Saveable { touched = true; } } - + if (usages != null) { RangeSet r = usages.get(oldName); if (r != null) { @@ -1317,12 +1319,12 @@ public class Fingerprint implements ModelObject, Saveable { touched = true; } } - + if (touched) { save(); } } - + public Api getApi() { return new Api(this); } @@ -1337,8 +1339,8 @@ public class Fingerprint implements ModelObject, Saveable { * 2. If not found, then the local storage is polled to retrieve the fingerprint */ public static @CheckForNull Fingerprint load(@NonNull String id) throws IOException { - long start=0; - if(logger.isLoggable(Level.FINE)) { + long start = 0; + if (logger.isLoggable(Level.FINE)) { start = System.currentTimeMillis(); } @@ -1359,7 +1361,7 @@ public class Fingerprint implements ModelObject, Saveable { initFacets(loaded); } - if(logger.isLoggable(Level.FINE)) { + if (logger.isLoggable(Level.FINE)) { logger.fine("Loading fingerprint took " + (System.currentTimeMillis() - start) + "ms"); } @@ -1433,7 +1435,7 @@ public class Fingerprint implements ModelObject, Saveable { + facets + "]"; } - + /** * Checks if the current user can Discover the item. * If yes, it may be displayed as a text in Fingerprint UIs. @@ -1453,7 +1455,7 @@ public class Fingerprint implements ModelObject, Saveable { if (item != null) { return true; } - + // Probably it failed due to the missing Item.DISCOVER // We try to retrieve the job using SYSTEM2 user and to check permissions manually. final Authentication userAuth = Jenkins.getAuthentication2(); @@ -1498,10 +1500,10 @@ public class Fingerprint implements ModelObject, Saveable { } static { - XSTREAM.alias("fingerprint",Fingerprint.class); - XSTREAM.alias("range",Range.class); - XSTREAM.alias("ranges",RangeSet.class); - XSTREAM.registerConverter(new HexBinaryConverter(),10); + XSTREAM.alias("fingerprint", Fingerprint.class); + XSTREAM.alias("range", Range.class); + XSTREAM.alias("ranges", RangeSet.class); + XSTREAM.registerConverter(new HexBinaryConverter(), 10); XSTREAM.registerConverter(new RangeSet.ConverterImpl( new CollectionConverter(XSTREAM.getMapper()) { @Override @@ -1509,7 +1511,7 @@ public class Fingerprint implements ModelObject, Saveable { return new ArrayList(); } } - ),10); + ), 10); } private static final Logger logger = Logger.getLogger(Fingerprint.class.getName()); diff --git a/core/src/main/java/hudson/model/FingerprintCleanupThread.java b/core/src/main/java/hudson/model/FingerprintCleanupThread.java index f7720bb78fc41bc12eb64a99f4ce227b976c9d5a..6ac6a361e8f728f247d91b59d77ac93719baa36f 100644 --- a/core/src/main/java/hudson/model/FingerprintCleanupThread.java +++ b/core/src/main/java/hudson/model/FingerprintCleanupThread.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import hudson.Extension; diff --git a/core/src/main/java/hudson/model/FingerprintMap.java b/core/src/main/java/hudson/model/FingerprintMap.java index 7679b384e39a0cd90d6b8843aa7d90aa26b9faae..b41edbb9f703d4d7055ce271cc11903302a8f53d 100644 --- a/core/src/main/java/hudson/model/FingerprintMap.java +++ b/core/src/main/java/hudson/model/FingerprintMap.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2011, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import edu.umd.cs.findbugs.annotations.CheckForNull; @@ -43,7 +44,7 @@ import jenkins.model.Jenkins; * @author Kohsuke Kawaguchi * @see Jenkins#getFingerprintMap() */ -public final class FingerprintMap extends KeyedDataStorage { +public final class FingerprintMap extends KeyedDataStorage { /** * Returns true if there's some data in the fingerprint database. @@ -60,25 +61,25 @@ public final class FingerprintMap extends KeyedDataStorage { +public class FreeStyleBuild extends Build { public FreeStyleBuild(FreeStyleProject project) throws IOException { super(project); } diff --git a/core/src/main/java/hudson/model/FreeStyleProject.java b/core/src/main/java/hudson/model/FreeStyleProject.java index 73234b815683cdc2d251188d4234063081e91333..814f2cf7e8a74046cebf8ff693440bc2b0f75fcd 100644 --- a/core/src/main/java/hudson/model/FreeStyleProject.java +++ b/core/src/main/java/hudson/model/FreeStyleProject.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, id:cactusman - * + * * 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 @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; @@ -35,10 +36,10 @@ import org.kohsuke.accmod.restrictions.NoExternalUse; /** * Free-style software project. - * + * * @author Kohsuke Kawaguchi */ -public class FreeStyleProject extends Project implements TopLevelItem { +public class FreeStyleProject extends Project implements TopLevelItem { /** * @deprecated as of 1.390 @@ -59,7 +60,7 @@ public class FreeStyleProject extends Project i @Override public DescriptorImpl getDescriptor() { - return (DescriptorImpl)Jenkins.get().getDescriptorOrDie(getClass()); + return (DescriptorImpl) Jenkins.get().getDescriptorOrDie(getClass()); } /** @@ -74,7 +75,7 @@ public class FreeStyleProject extends Project i @SuppressFBWarnings(value = "MS_PKGPROTECT", justification = "for backward compatibility") public static /*almost final*/ DescriptorImpl DESCRIPTOR; - @Extension(ordinal=1000) @Symbol({"freeStyle","freeStyleJob"}) + @Extension(ordinal = 1000) @Symbol({"freeStyle", "freeStyleJob"}) public static class DescriptorImpl extends AbstractProjectDescriptor { @SuppressFBWarnings(value = "ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD", justification = "for backward compatibility") public DescriptorImpl() { @@ -88,7 +89,7 @@ public class FreeStyleProject extends Project i @Override public FreeStyleProject newInstance(ItemGroup parent, String name) { - return new FreeStyleProject(parent,name); + return new FreeStyleProject(parent, name); } @Override diff --git a/core/src/main/java/hudson/model/FullDuplexHttpChannel.java b/core/src/main/java/hudson/model/FullDuplexHttpChannel.java index 6251bddec842322ddafb4794bf17b70b4e4b6fe2..64e2428f6a71d52fa0988418237dfd36fc1ba05f 100644 --- a/core/src/main/java/hudson/model/FullDuplexHttpChannel.java +++ b/core/src/main/java/hudson/model/FullDuplexHttpChannel.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import hudson.remoting.Channel; diff --git a/core/src/main/java/hudson/model/HealthReport.java b/core/src/main/java/hudson/model/HealthReport.java index de3cd5e028eb085965524bfffd4cf378dfa3a536..e5bb11319aa81d60677af90e0b4670196124a20f 100644 --- a/core/src/main/java/hudson/model/HealthReport.java +++ b/core/src/main/java/hudson/model/HealthReport.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi, Stephen Connolly - * + * * 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 @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import com.thoughtworks.xstream.converters.UnmarshallingContext; @@ -355,6 +356,7 @@ public class HealthReport implements Serializable, Comparable { */ public static class ConverterImpl extends XStream2.PassthruConverter { public ConverterImpl(XStream2 xstream) { super(xstream); } + @Override protected void callback(HealthReport hr, UnmarshallingContext context) { // If we are being read back in from an older version if (hr.localizibleDescription == null) { diff --git a/core/src/main/java/hudson/model/HealthReportingAction.java b/core/src/main/java/hudson/model/HealthReportingAction.java index c5fa8f0e88948469739d35cbc9789052ee5a9833..b26277cc5143f312ed2d9e9e99a9ecc681d0c29b 100644 --- a/core/src/main/java/hudson/model/HealthReportingAction.java +++ b/core/src/main/java/hudson/model/HealthReportingAction.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; /** diff --git a/core/src/main/java/hudson/model/Hudson.java b/core/src/main/java/hudson/model/Hudson.java index f8b80787dfad8fcfc875c875d136201043255201..784fa47da20e9dd0c6fa191a9d0e026afae6a9c9 100644 --- a/core/src/main/java/hudson/model/Hudson.java +++ b/core/src/main/java/hudson/model/Hudson.java @@ -23,6 +23,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import static hudson.Util.fixEmpty; @@ -74,11 +75,11 @@ public class Hudson extends Jenkins { @CLIResolver @Nullable public static Hudson getInstance() { - return (Hudson)Jenkins.get(); + return (Hudson) Jenkins.get(); } public Hudson(File root, ServletContext context) throws IOException, InterruptedException, ReactorException { - this(root,context,null); + this(root, context, null); } public Hudson(File root, ServletContext context, PluginManager pluginManager) throws IOException, InterruptedException, ReactorException { @@ -117,7 +118,7 @@ public class Hudson extends Jenkins { public Slave getSlave(String name) { Node n = getNode(name); if (n instanceof Slave) - return (Slave)n; + return (Slave) n; return null; } @@ -127,7 +128,7 @@ public class Hudson extends Jenkins { */ @Deprecated public List getSlaves() { - return (List)getNodes(); + return (List) getNodes(); } /** @@ -158,8 +159,8 @@ public class Hudson extends Jenkins { @Deprecated public TopLevelItem getJobCaseInsensitive(String name) { String match = Functions.toEmailSafeString(name); - for(TopLevelItem item : getItems()) { - if(Functions.toEmailSafeString(item.getName()).equalsIgnoreCase(match)) { + for (TopLevelItem item : getItems()) { + if (Functions.toEmailSafeString(item.getName()).equalsIgnoreCase(match)) { return item; } } @@ -183,9 +184,9 @@ public class Hudson extends Jenkins { * As on 1.267, moved to "/log/rss..." */ @Deprecated - public void doLogRss( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { + public void doLogRss(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { String qs = req.getQueryString(); - rsp.sendRedirect2("./log/rss"+(qs==null?"":'?'+qs)); + rsp.sendRedirect2("./log/rss" + (qs == null ? "" : '?' + qs)); } /** @@ -198,7 +199,7 @@ public class Hudson extends Jenkins { fixEmpty(req.getParameter("value")), fixEmpty(req.getParameter("type")), fixEmpty(req.getParameter("errorText")), - fixEmpty(req.getParameter("warningText"))).generateResponse(req,rsp,this); + fixEmpty(req.getParameter("warningText"))).generateResponse(req, rsp, this); } /** @@ -215,10 +216,10 @@ public class Hudson extends Jenkins { * or define your own check method, instead of relying on this generic one. */ @Deprecated - public FormValidation doFieldCheck(@QueryParameter(fixEmpty=true) String value, - @QueryParameter(fixEmpty=true) String type, - @QueryParameter(fixEmpty=true) String errorText, - @QueryParameter(fixEmpty=true) String warningText) { + public FormValidation doFieldCheck(@QueryParameter(fixEmpty = true) String value, + @QueryParameter(fixEmpty = true) String type, + @QueryParameter(fixEmpty = true) String errorText, + @QueryParameter(fixEmpty = true) String warningText) { if (value == null) { if (errorText != null) return FormValidation.error(errorText); @@ -252,7 +253,7 @@ public class Hudson extends Jenkins { */ @Deprecated public static boolean isWindows() { - return File.pathSeparatorChar==';'; + return File.pathSeparatorChar == ';'; } /** @@ -278,7 +279,7 @@ public class Hudson extends Jenkins { * Use {@link #checkPermission(hudson.security.Permission)} */ @Deprecated - public static boolean adminCheck(StaplerRequest req,StaplerResponse rsp) throws IOException { + public static boolean adminCheck(StaplerRequest req, StaplerResponse rsp) throws IOException { if (isAdmin(req)) return true; rsp.sendError(HttpServletResponse.SC_FORBIDDEN); @@ -319,7 +320,7 @@ public class Hudson extends Jenkins { } static { - XSTREAM.alias("hudson",Hudson.class); + XSTREAM.alias("hudson", Hudson.class); } /** diff --git a/core/src/main/java/hudson/model/InvisibleAction.java b/core/src/main/java/hudson/model/InvisibleAction.java index d921cd12f8d9e71b9af55ea8bb9c1e85d4802489..2f5ce024263236a5cf39e1a3bbf13bb616a2882b 100644 --- a/core/src/main/java/hudson/model/InvisibleAction.java +++ b/core/src/main/java/hudson/model/InvisibleAction.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; /** diff --git a/core/src/main/java/hudson/model/Item.java b/core/src/main/java/hudson/model/Item.java index d9ba493dc02bf5eda05cecdf3bdeb134bd14ff75..a57011579b154761ed16cedcc300d553b67b187b 100644 --- a/core/src/main/java/hudson/model/Item.java +++ b/core/src/main/java/hudson/model/Item.java @@ -1,19 +1,19 @@ /* * The MIT License - * + * * Copyright (c) 2004-2011, Sun Microsystems, Inc., Kohsuke Kawaguchi, Yahoo! Inc., * Manufacture Francaise des Pneumatiques Michelin, Romain Seguy - * + * * 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 @@ -22,6 +22,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import edu.umd.cs.findbugs.annotations.CheckForNull; @@ -93,7 +94,7 @@ public interface Item extends PersistenceRoot, SearchableModelObject, AccessCont * This name is also used for directory name, so it cannot contain * any character that's not allowed on the file system. * - * @see #getFullName() + * @see #getFullName() */ String getName(); @@ -199,9 +200,9 @@ public interface Item extends PersistenceRoot, SearchableModelObject, AccessCont @Deprecated default String getAbsoluteUrl() { String r = Jenkins.get().getRootUrl(); - if(r==null) + if (r == null) throw new IllegalStateException("Root URL isn't configured yet. Cannot compute absolute URL."); - return Util.encode(r+getUrl()); + return Util.encode(r + getUrl()); } /** @@ -248,7 +249,7 @@ public interface Item extends PersistenceRoot, SearchableModelObject, AccessCont */ void delete() throws IOException, InterruptedException; - PermissionGroup PERMISSIONS = new PermissionGroup(Item.class,Messages._Item_Permissions_Title()); + PermissionGroup PERMISSIONS = new PermissionGroup(Item.class, Messages._Item_Permissions_Title()); Permission CREATE = new Permission( PERMISSIONS, diff --git a/core/src/main/java/hudson/model/ItemGroup.java b/core/src/main/java/hudson/model/ItemGroup.java index 61989b1711c7b7a5886579da9c4bd9fc1d593f98..6404e82626e1e858f2d68dc7bfe8a95f194307af 100644 --- a/core/src/main/java/hudson/model/ItemGroup.java +++ b/core/src/main/java/hudson/model/ItemGroup.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import edu.umd.cs.findbugs.annotations.CheckForNull; @@ -44,12 +45,12 @@ public interface ItemGroup extends PersistenceRoot, ModelObject /** * Gets the full name of this {@link ItemGroup}. * - * @see Item#getFullName() + * @see Item#getFullName() */ String getFullName(); /** - * @see Item#getFullDisplayName() + * @see Item#getFullDisplayName() */ String getFullDisplayName(); diff --git a/core/src/main/java/hudson/model/ItemGroupMixIn.java b/core/src/main/java/hudson/model/ItemGroupMixIn.java index 54798d497868d886a6dd67726f1f78515185e936..748a13cc6ec4e033df9e824c04620a4ba0aeaf8c 100644 --- a/core/src/main/java/hudson/model/ItemGroupMixIn.java +++ b/core/src/main/java/hudson/model/ItemGroupMixIn.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, CloudBees, 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 @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import hudson.Util; @@ -97,7 +98,7 @@ public abstract class ItemGroupMixIn { * @param modulesDir * Directory that contains sub-directories for each child item. */ - public static Map loadChildren(ItemGroup parent, File modulesDir, Function1 key) { + public static Map loadChildren(ItemGroup parent, File modulesDir, Function1 key) { try { Util.createDirectories(modulesDir.toPath()); } catch (IOException e) { @@ -105,7 +106,7 @@ public abstract class ItemGroupMixIn { } File[] subdirs = modulesDir.listFiles(File::isDirectory); - CopyOnWriteMap.Tree configurations = new CopyOnWriteMap.Tree<>(); + CopyOnWriteMap.Tree configurations = new CopyOnWriteMap.Tree<>(); for (File subdir : subdirs) { try { // Try to retain the identity of an existing child object if we can. @@ -133,13 +134,13 @@ public abstract class ItemGroupMixIn { /** * {@link Item} → name function. */ - public static final Function1 KEYED_BY_NAME = Item::getName; + public static final Function1 KEYED_BY_NAME = Item::getName; /** * Creates a {@link TopLevelItem} for example from the submission of the {@code /lib/hudson/newFromList/form} tag * or throws an exception if it fails. */ - public synchronized TopLevelItem createTopLevelItem( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { + public synchronized TopLevelItem createTopLevelItem(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { acl.checkPermission(Item.CREATE); TopLevelItem result; @@ -155,38 +156,38 @@ public abstract class ItemGroupMixIn { || requestContentType.startsWith("text/xml")); String name = req.getParameter("name"); - if(name==null) + if (name == null) throw new Failure("Query parameter 'name' is required"); - {// check if the name looks good + { // check if the name looks good Jenkins.checkGoodName(name); name = name.trim(); - if(parent.getItem(name)!=null) + if (parent.getItem(name) != null) throw new Failure(Messages.Hudson_JobAlreadyExists(name)); } - if(mode!=null && mode.equals("copy")) { + if (mode != null && mode.equals("copy")) { String from = req.getParameter("from"); // resolve a name to Item Item src = Jenkins.get().getItem(from, parent); - if(src==null) { - if(Util.fixEmpty(from)==null) + if (src == null) { + if (Util.fixEmpty(from) == null) throw new Failure("Specify which job to copy"); else - throw new Failure("No such job: "+from); + throw new Failure("No such job: " + from); } if (!(src instanceof TopLevelItem)) - throw new Failure(from+" cannot be copied"); + throw new Failure(from + " cannot be copied"); - result = copy((TopLevelItem) src,name); + result = copy((TopLevelItem) src, name); } else { - if(isXmlSubmission) { + if (isXmlSubmission) { result = createProjectFromXML(name, req.getInputStream()); rsp.setStatus(HttpServletResponse.SC_OK); return result; } else { - if(mode==null) + if (mode == null) throw new Failure("No mode given"); TopLevelItemDescriptor descriptor = Items.all().findByName(mode); if (descriptor == null) { @@ -208,7 +209,7 @@ public abstract class ItemGroupMixIn { * Computes the redirection target URL for the newly created {@link TopLevelItem}. */ protected String redirectAfterCreateItem(StaplerRequest req, TopLevelItem result) throws IOException { - return req.getContextPath()+'/'+result.getUrl()+"configure"; + return req.getContextPath() + '/' + result.getUrl() + "configure"; } /** @@ -239,7 +240,7 @@ public abstract class ItemGroupMixIn { Jenkins.checkGoodName(name); ItemListener.checkBeforeCopy(src, parent); - T result = (T)createProject(src.getDescriptor(),name,false); + T result = (T) createProject(src.getDescriptor(), name, false); // copy config Files.copy(Util.fileToPath(srcConfigFile.getFile()), Util.fileToPath(Items.getConfigFile(result).getFile()), @@ -247,7 +248,7 @@ public abstract class ItemGroupMixIn { // reload from the new config final File rootDir = result.getRootDir(); - result = Items.whileUpdatingByXml(new NotReallyRoleSensitiveCallable() { + result = Items.whileUpdatingByXml(new NotReallyRoleSensitiveCallable() { @Override public T call() throws IOException { return (T) Items.load(parent, rootDir); } @@ -255,7 +256,7 @@ public abstract class ItemGroupMixIn { result.onCopiedFrom(src); add(result); - ItemListener.fireOnCopied(src,result); + ItemListener.fireOnCopied(src, result); Jenkins.get().rebuildDependencyGraphAsync(); return result; @@ -277,7 +278,7 @@ public abstract class ItemGroupMixIn { XMLUtils.safeTransform(new StreamSource(xml), new StreamResult(configXml)); // load it - TopLevelItem result = Items.whileUpdatingByXml(new NotReallyRoleSensitiveCallable() { + TopLevelItem result = Items.whileUpdatingByXml(new NotReallyRoleSensitiveCallable() { @Override public TopLevelItem call() throws IOException { return (TopLevelItem) Items.load(parent, dir); } @@ -306,7 +307,7 @@ public abstract class ItemGroupMixIn { } } - public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name, boolean notify ) + public synchronized TopLevelItem createProject(TopLevelItemDescriptor type, String name, boolean notify) throws IOException { acl.checkPermission(Item.CREATE); type.checkApplicableIn(parent); diff --git a/core/src/main/java/hudson/model/ItemVisitor.java b/core/src/main/java/hudson/model/ItemVisitor.java index e33a6849b0eda62066717fa8a0bc9c0a1344fafb..98e26c8023aa4cd5c21eea6e89ce310f0f0d21c2 100644 --- a/core/src/main/java/hudson/model/ItemVisitor.java +++ b/core/src/main/java/hudson/model/ItemVisitor.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import jenkins.model.Jenkins; @@ -46,8 +47,8 @@ public abstract class ItemVisitor { * visits the children. */ public void onItem(Item i) { - if(i instanceof ItemGroup) - onItemGroup((ItemGroup)i); + if (i instanceof ItemGroup) + onItemGroup((ItemGroup) i); } /** diff --git a/core/src/main/java/hudson/model/Items.java b/core/src/main/java/hudson/model/Items.java index ddb33a4e850507bd2136a23708ec9849cce9d252..1d0c607ad979ba91def8e5798cafc464efdd706a 100644 --- a/core/src/main/java/hudson/model/Items.java +++ b/core/src/main/java/hudson/model/Items.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import com.thoughtworks.xstream.XStream; @@ -58,7 +59,7 @@ import org.springframework.security.core.Authentication; /** * Convenience methods related to {@link Item}. - * + * * @author Kohsuke Kawaguchi */ public class Items { @@ -126,7 +127,7 @@ public class Items { * @throws T anything {@code callable} throws * @since 1.546 */ - public static V whileUpdatingByXml(Callable callable) throws T { + public static V whileUpdatingByXml(Callable callable) throws T { updatingByXml.set(true); try { return callable.call(); @@ -148,7 +149,7 @@ public class Items { /** * Returns all the registered {@link TopLevelItemDescriptor}s. */ - public static DescriptorExtensionList all() { + public static DescriptorExtensionList all() { return Jenkins.get().getDescriptorList(TopLevelItem.class); } @@ -177,7 +178,7 @@ public class Items { // fall back to root acl = Jenkins.get().getACL(); } - for (TopLevelItemDescriptor d: all()) { + for (TopLevelItemDescriptor d : all()) { if (acl.hasCreatePermission2(a, c, d) && d.isApplicableIn(c)) { result.add(d); } @@ -208,7 +209,7 @@ public class Items { public static String toNameList(Collection items) { StringBuilder buf = new StringBuilder(); for (Item item : items) { - if(buf.length()>0) + if (buf.length() > 0) buf.append(", "); buf.append(item.getFullName()); } @@ -221,7 +222,7 @@ public class Items { */ @Deprecated public static List fromNameList(String list, Class type) { - return fromNameList(null,list,type); + return fromNameList(null, list, type); } /** @@ -229,15 +230,15 @@ public class Items { */ public static List fromNameList(ItemGroup context, @NonNull String list, @NonNull Class type) { final Jenkins jenkins = Jenkins.get(); - + List r = new ArrayList<>(); - StringTokenizer tokens = new StringTokenizer(list,","); - while(tokens.hasMoreTokens()) { + StringTokenizer tokens = new StringTokenizer(list, ","); + while (tokens.hasMoreTokens()) { String fullName = tokens.nextToken().trim(); if (StringUtils.isNotEmpty(fullName)) { T item = jenkins.getItem(fullName, context, type); - if(item!=null) + if (item != null) r.add(item); } } @@ -254,12 +255,12 @@ public class Items { String[] p = path.split("/"); Stack name = new Stack<>(); - for (int i=0; i newValue = new ArrayList<>(); - while(tokens.hasMoreTokens()) { + while (tokens.hasMoreTokens()) { String relativeName = tokens.nextToken().trim(); String canonicalName = getCanonicalName(context, relativeName); - if (canonicalName.equals(oldFullName) || canonicalName.startsWith(oldFullName+'/')) { + if (canonicalName.equals(oldFullName) || canonicalName.startsWith(oldFullName + '/')) { String newCanonicalName = newFullName + canonicalName.substring(oldFullName.length()); if (relativeName.startsWith("/")) { newValue.add("/" + newCanonicalName); @@ -372,8 +373,8 @@ public class Items { * The directory that contains the config file, not the config file itself. */ public static Item load(ItemGroup parent, File dir) throws IOException { - Item item = (Item)getConfigFile(dir).read(); - item.onLoad(parent,dir.getName()); + Item item = (Item) getConfigFile(dir).read(); + item.onLoad(parent, dir.getName()); return item; } @@ -381,7 +382,7 @@ public class Items { * The file we save our configuration. */ public static XmlFile getConfigFile(File dir) { - return new XmlFile(XSTREAM,new File(dir,"config.xml")); + return new XmlFile(XSTREAM, new File(dir, "config.xml")); } /** @@ -390,7 +391,7 @@ public class Items { public static XmlFile getConfigFile(Item item) { return getConfigFile(item.getRootDir()); } - + /** * Gets all the {@link Item}s recursively in the {@link ItemGroup} tree * and filter them by the given type. The returned list will represent a snapshot view of the items present at some @@ -403,11 +404,11 @@ public class Items { * @param root Root node to start searching from * @param type Given type of of items being searched for * @return List of items matching given criteria - * + * * @since 1.512 */ public static List getAllItems(final ItemGroup root, Class type) { - return getAllItems(root ,type, t -> true); + return getAllItems(root, type, t -> true); } /** @@ -425,6 +426,7 @@ public class Items { getAllItems(root, type, r, pred); return r; } + private static void getAllItems(final ItemGroup root, Class type, List r, Predicate pred) { List items = new ArrayList<>(((ItemGroup) root).getItems(t -> t instanceof ItemGroup || (type.isInstance(t) && pred.test(type.cast(t))))); // because we add items depth first, we can use the quicker BY_NAME comparison @@ -542,7 +544,7 @@ public class Items { */ public static @CheckForNull T findNearest(Class type, String name, ItemGroup context) { List names = new ArrayList<>(); - for (T item: Jenkins.get().allItems(type)) { + for (T item : Jenkins.get().allItems(type)) { names.add(item.getRelativeNameFrom(context)); } String nearest = EditDistance.findNearest(name, names); @@ -727,9 +729,9 @@ public class Items { /** * Alias to {@link #XSTREAM} so that one can access additional methods on {@link XStream2} more easily. */ - public static final XStream2 XSTREAM2 = (XStream2)XSTREAM; + public static final XStream2 XSTREAM2 = (XStream2) XSTREAM; static { - XSTREAM.alias("project",FreeStyleProject.class); + XSTREAM.alias("project", FreeStyleProject.class); } } diff --git a/core/src/main/java/hudson/model/JDK.java b/core/src/main/java/hudson/model/JDK.java index 1eeafbbc6682905031fe19a935c58acf4eb69c8a..0c9bcbda493d6e0fd02f12da4d56fa3a8e326aa5 100644 --- a/core/src/main/java/hudson/model/JDK.java +++ b/core/src/main/java/hudson/model/JDK.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import hudson.EnvVars; @@ -103,14 +104,15 @@ public final class JDK extends ToolInstallation implements NodeSpecific, En * Gets the path to the bin directory. */ public File getBinDir() { - return new File(getHome(),"bin"); + return new File(getHome(), "bin"); } /** * Gets the path to 'java'. */ + private File getExecutable() { String execName = File.separatorChar == '\\' ? "java.exe" : "java"; - return new File(getHome(),"bin/"+execName); + return new File(getHome(), "bin/" + execName); } /** @@ -124,13 +126,13 @@ public final class JDK extends ToolInstallation implements NodeSpecific, En * @deprecated as of 1.460. Use {@link #buildEnvVars(EnvVars)} */ @Deprecated - public void buildEnvVars(Map env) { + public void buildEnvVars(Map env) { String home = getHome(); if (home == null) { return; } // see EnvVars javadoc for why this adds PATH. - env.put("PATH+JDK",home+"/bin"); + env.put("PATH+JDK", home + "/bin"); env.put("JAVA_HOME", home); } @@ -139,7 +141,7 @@ public final class JDK extends ToolInstallation implements NodeSpecific, En */ @Override public void buildEnvVars(EnvVars env) { - buildEnvVars((Map)env); + buildEnvVars((Map) env); } @Override @@ -163,7 +165,7 @@ public final class JDK extends ToolInstallation implements NodeSpecific, En try { TaskListener listener = new StreamTaskListener(new NullStream()); Launcher launcher = n.createLauncher(listener); - return launcher.launch().cmds("java","-fullversion").stdout(listener).join()==0; + return launcher.launch().cmds("java", "-fullversion").stdout(listener).join() == 0; } catch (IOException | InterruptedException e) { return false; } @@ -206,13 +208,13 @@ public final class JDK extends ToolInstallation implements NodeSpecific, En * Checks if the JAVA_HOME is a valid JAVA_HOME path. */ @Override protected FormValidation checkHomeDirectory(File value) { - File toolsJar = new File(value,"lib/tools.jar"); - File mac = new File(value,"lib/dt.jar"); + File toolsJar = new File(value, "lib/tools.jar"); + File mac = new File(value, "lib/dt.jar"); // JENKINS-25601: JDK 9+ no longer has tools.jar. Keep the existing dt.jar/tools.jar checks to be safe. File javac = new File(value, "bin/javac"); File javacExe = new File(value, "bin/javac.exe"); - if(!toolsJar.exists() && !mac.exists() && !javac.exists() && !javacExe.exists()) + if (!toolsJar.exists() && !mac.exists() && !javac.exists() && !javacExe.exists()) return FormValidation.error(Messages.Hudson_NotJDKDir(value)); return FormValidation.ok(); @@ -222,8 +224,9 @@ public final class JDK extends ToolInstallation implements NodeSpecific, En public static class ConverterImpl extends ToolConverter { public ConverterImpl(XStream2 xstream) { super(xstream); } + @Override protected String oldHomeField(ToolInstallation obj) { - return ((JDK)obj).javaHome; + return ((JDK) obj).javaHome; } } diff --git a/core/src/main/java/hudson/model/Job.java b/core/src/main/java/hudson/model/Job.java index 2658ce50c20ff796672087fda9785a10d1e8c45a..59956a91b9fa1a95872b7a6fe1b00575b6de2ee3 100644 --- a/core/src/main/java/hudson/model/Job.java +++ b/core/src/main/java/hudson/model/Job.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST; @@ -302,7 +303,7 @@ public abstract class Job, RunT extends Run, RunT extends Run, RunT extends Run, RunT extends Run, RunT extends Runlb.getNumber() : next>0) { + if (lb != null ? next > lb.getNumber() : next > 0) { this.nextBuildNumber = next; saveNextBuildNumber(); } @@ -504,7 +505,7 @@ public abstract class Job, RunT extends Run getAllJobs() { - return Collections. singleton(this); + return Collections.singleton(this); } /** @@ -513,7 +514,7 @@ public abstract class Job, RunT extends Run jobProp) throws IOException { - ((JobProperty)jobProp).setOwner(this); + ((JobProperty) jobProp).setOwner(this); properties.add(jobProp); save(); } @@ -561,7 +562,7 @@ public abstract class Job, RunT extends Run> getAllProperties() { return properties.getView(); } @@ -690,7 +691,7 @@ public abstract class Job, RunT extends Run, RunT extends Run getBuilds() { return RunList.fromRuns(_getRuns().values()); @@ -739,7 +740,7 @@ public abstract class Job, RunT extends Run getNewBuilds() { return getBuilds().limit(100); } @@ -751,7 +752,7 @@ public abstract class Job, RunT extends Run builds = new ArrayList<>(); for (Range r : rs.getRanges()) { - for (RunT b = getNearestBuild(r.start); b!=null && b.getNumber(), RunT extends Run getBuildsByTimestamp(long start, long end) { - return getBuilds().byTimestamp(start,end); + return getBuilds().byTimestamp(start, end); } @CLIResolver - public RunT getBuildForCLI(@Argument(required=true,metaVar="BUILD#",usage="Build number") String id) throws CmdLineException { + public RunT getBuildForCLI(@Argument(required = true, metaVar = "BUILD#", usage = "Build number") String id) throws CmdLineException { try { int n = Integer.parseInt(id); RunT r = getBuildByNumber(n); - if (r==null) - throw new CmdLineException(null, "No such build '#"+n+"' exists"); + if (r == null) + throw new CmdLineException(null, "No such build '#" + n + "' exists"); return r; } catch (NumberFormatException e) { - throw new CmdLineException(null, id+ "is not a number", e); + throw new CmdLineException(null, id + "is not a number", e); } } @@ -859,7 +860,7 @@ public abstract class Job, RunT extends Run, RunT extends Run, RunT extends Run, RunT extends Run, RunT extends Run, RunT extends Run, RunT extends Run, RunT extends Run builds = getEstimatedDurationCandidates(); - if(builds.isEmpty()) return -1; + if (builds.isEmpty()) return -1; long totalDuration = 0; for (RunT b : builds) { totalDuration += b.getDuration(); } - if(totalDuration==0) return -1; + if (totalDuration == 0) return -1; - return Math.round((double)totalDuration / builds.size()); + return Math.round((double) totalDuration / builds.size()); } /** @@ -1109,7 +1110,7 @@ public abstract class Job, RunT extends Run c : ((RunWithSCM) r).getChangeSets()) { + for (ChangeLogSet c : ((RunWithSCM) r).getChangeSets()) { for (ChangeLogSet.Entry e : c) { entries.add(new FeedItem(e, idx++)); } @@ -1333,7 +1334,7 @@ public abstract class Job, RunT extends Run, JobPropertyDescriptor> t = new DescribableList<>(NOOP, getAllProperties()); JSONObject jsonProperties = json.optJSONObject("properties"); if (jsonProperties != null) { - t.rebuild(req,jsonProperties,JobPropertyDescriptor.getPropertyDescriptors(Job.this.getClass())); + t.rebuild(req, jsonProperties, JobPropertyDescriptor.getPropertyDescriptors(Job.this.getClass())); } else { t.clear(); } @@ -1349,7 +1350,7 @@ public abstract class Job, RunT extends Run, RunT extends Run, RunT extends Run, RunT extends Run * When you restrict your job property to be only applicable to a certain * subtype of {@link Job}, you can use this type parameter to improve - * the type signature of this class. See {@link JobPropertyDescriptor#isApplicable(Class)}. + * the type signature of this class. See {@link JobPropertyDescriptor#isApplicable(Class)}. * * @author Kohsuke Kawaguchi * @see JobPropertyDescriptor * @since 1.72 */ @ExportedBean -public abstract class JobProperty> implements ReconfigurableDescribable>, BuildStep, ExtensionPoint { +public abstract class JobProperty> implements ReconfigurableDescribable>, BuildStep, ExtensionPoint { /** * The {@link Job} object that owns this property. * This value will be set by the Hudson code. @@ -132,7 +133,7 @@ public abstract class JobProperty> implements ReconfigurableD public Collection getJobActions(J job) { // delegate to getJobAction (singular) for backward compatible behavior Action a = getJobAction(job); - if (a==null) return Collections.emptyList(); + if (a == null) return Collections.emptyList(); return Collections.singletonList(a); } @@ -141,7 +142,7 @@ public abstract class JobProperty> implements ReconfigurableD // @Override - public boolean prebuild(AbstractBuild build, BuildListener listener) { + public boolean prebuild(AbstractBuild build, BuildListener listener) { return true; } @@ -152,7 +153,7 @@ public abstract class JobProperty> implements ReconfigurableD * Invoked after {@link Publisher}s have run. */ @Override - public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { + public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { return true; } @@ -166,14 +167,14 @@ public abstract class JobProperty> implements ReconfigurableD } @Override - public final Action getProjectAction(AbstractProject project) { - return getJobAction((J)project); + public final Action getProjectAction(AbstractProject project) { + return getJobAction((J) project); } @Override @NonNull - public final Collection getProjectActions(AbstractProject project) { - return getJobActions((J)project); + public final Collection getProjectActions(AbstractProject project) { + return getJobActions((J) project); } /** @see Job#getOverrides */ @@ -183,7 +184,7 @@ public abstract class JobProperty> implements ReconfigurableD @Override public JobProperty reconfigure(StaplerRequest req, JSONObject form) throws FormException { - return form==null ? null : getDescriptor().newInstance(req,form); + return form == null ? null : getDescriptor().newInstance(req, form); } /** diff --git a/core/src/main/java/hudson/model/JobPropertyDescriptor.java b/core/src/main/java/hudson/model/JobPropertyDescriptor.java index 36f781b67ba18ae1fc337e1866e70d3764acc0ab..1f1c3aa7e6f0751ad647798bc06d654601570f35 100644 --- a/core/src/main/java/hudson/model/JobPropertyDescriptor.java +++ b/core/src/main/java/hudson/model/JobPropertyDescriptor.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import java.lang.reflect.ParameterizedType; @@ -36,7 +37,7 @@ import org.kohsuke.stapler.StaplerRequest; /** * {@link Descriptor} for {@link JobProperty}. - * + * * @author Kohsuke Kawaguchi * @since 1.72 */ @@ -62,8 +63,8 @@ public abstract class JobPropertyDescriptor extends Descriptor> { @Override public JobProperty newInstance(StaplerRequest req, JSONObject formData) throws FormException { // JobPropertyDescriptors are bit different in that we allow them even without any user-visible configuration parameter, - // so replace the lack of form data by an empty one. - if(formData.isNullObject()) formData=new JSONObject(); + // so replace the lack of form data by an empty one. + if (formData.isNullObject()) formData = new JSONObject(); return super.newInstance(req, formData); } @@ -71,7 +72,7 @@ public abstract class JobPropertyDescriptor extends Descriptor> { /** * Returns true if this {@link JobProperty} type is applicable to the * given job type. - * + * *

    * The default implementation of this method checks if the given job type is assignable to {@code J} of * {@link JobProperty}{@code }, but subtypes can extend this to change this behavior. @@ -87,7 +88,7 @@ public abstract class JobPropertyDescriptor extends Descriptor> { Class applicable = Types.erasure(Types.getTypeArgument(pt, 0)); return applicable.isAssignableFrom(jobType); } else { - throw new AssertionError(clazz+" doesn't properly parameterize JobProperty. The isApplicable() method must be overridden."); + throw new AssertionError(clazz + " doesn't properly parameterize JobProperty. The isApplicable() method must be overridden."); } } @@ -97,7 +98,7 @@ public abstract class JobPropertyDescriptor extends Descriptor> { public static List getPropertyDescriptors(Class clazz) { List r = new ArrayList<>(); for (JobPropertyDescriptor p : all()) - if(p.isApplicable(clazz)) + if (p.isApplicable(clazz)) r.add(p); return r; } diff --git a/core/src/main/java/hudson/model/Jobs.java b/core/src/main/java/hudson/model/Jobs.java index 63117247d2260121f7fa63d05984fa7c9b78d1a1..a9452f68d8a923a152e287aad6acf80fbfe1ffd0 100644 --- a/core/src/main/java/hudson/model/Jobs.java +++ b/core/src/main/java/hudson/model/Jobs.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Tom Huybrechts - * + * * 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 @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import hudson.Extension; @@ -29,7 +30,7 @@ import java.util.List; /** * List of all installed {@link Job} types. - * + * * @author Kohsuke Kawaguchi * @deprecated since 1.281 */ @@ -49,5 +50,5 @@ public class Jobs { */ @Deprecated public static final List PROPERTIES = (List) - new DescriptorList>((Class)JobProperty.class); + new DescriptorList>((Class) JobProperty.class); } diff --git a/core/src/main/java/hudson/model/Label.java b/core/src/main/java/hudson/model/Label.java index 0e38b876f8a70c2b1d7766a48d7b6bf2030cf106..11418515075e705f2279eaad1c85c39aeb3a1648 100644 --- a/core/src/main/java/hudson/model/Label.java +++ b/core/src/main/java/hudson/model/Label.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import static hudson.Util.fixNull; @@ -100,7 +101,7 @@ public abstract class Label extends Actionable implements Comparable

    - * If you are a {@link BuildStep}, most likely you should call {@link AbstractBuild#getBuildVariableResolver()}. + * If you are a {@link BuildStep}, most likely you should call {@link AbstractBuild#getBuildVariableResolver()}. */ - public VariableResolver createVariableResolver(AbstractBuild build) { - VariableResolver[] resolvers = new VariableResolver[getParameters().size()+1]; - int i=0; + public VariableResolver createVariableResolver(AbstractBuild build) { + VariableResolver[] resolvers = new VariableResolver[getParameters().size() + 1]; + int i = 0; for (ParameterValue p : getParameters()) { if (p == null) continue; resolvers[i++] = p.createVariableResolver(build); } - + resolvers[i] = build.getBuildVariableResolver(); return new VariableResolver.Union(resolvers); } - + @Override public Iterator iterator() { return getParameters().iterator(); } - @Exported(visibility=2) + @Exported(visibility = 2) public List getParameters() { return Collections.unmodifiableList(filter(parameters)); } @@ -195,7 +196,7 @@ public class ParametersAction implements RunAction2, Iterable, Q for (ParameterValue p : getParameters()) { if (p == null) continue; Label l = p.getAssignedLabel(task); - if (l!=null) return l; + if (l != null) return l; } return null; } @@ -226,7 +227,7 @@ public class ParametersAction implements RunAction2, Iterable, Q } else { // I don't think we need multiple ParametersActions, but let's be defensive Set params = new HashSet<>(); - for (ParametersAction other: others) { + for (ParametersAction other : others) { params.addAll(other.parameters); } return !params.equals(new HashSet<>(this.parameters)); @@ -240,7 +241,7 @@ public class ParametersAction implements RunAction2, Iterable, Q */ @NonNull public ParametersAction createUpdated(Collection overrides) { - if(overrides == null) { + if (overrides == null) { ParametersAction parametersAction = new ParametersAction(parameters); parametersAction.safeParameters = this.safeParameters; return parametersAction; @@ -248,7 +249,7 @@ public class ParametersAction implements RunAction2, Iterable, Q List combinedParameters = new ArrayList<>(overrides); Set names = new HashSet<>(); - for(ParameterValue v : overrides) { + for (ParameterValue v : overrides) { if (v == null) continue; names.add(v.getName()); } diff --git a/core/src/main/java/hudson/model/ParametersDefinitionProperty.java b/core/src/main/java/hudson/model/ParametersDefinitionProperty.java index 7470330c7a0187faf900f6687e4c1edc052865a3..e09131c268a31d0c2e25b13a448bc75a04ef17fb 100644 --- a/core/src/main/java/hudson/model/ParametersDefinitionProperty.java +++ b/core/src/main/java/hudson/model/ParametersDefinitionProperty.java @@ -22,6 +22,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import static javax.servlet.http.HttpServletResponse.SC_CREATED; @@ -67,7 +68,7 @@ import org.kohsuke.stapler.export.ExportedBean; *

    The owning job needs a {@code sidepanel.jelly} and should have web methods delegating to {@link ParameterizedJobMixIn#doBuild} and {@link ParameterizedJobMixIn#doBuildWithParameters}. * The builds also need a {@code sidepanel.jelly}. */ -@ExportedBean(defaultVisibility=2) +@ExportedBean(defaultVisibility = 2) public class ParametersDefinitionProperty extends OptionalJobProperty> implements Action { @@ -87,7 +88,7 @@ public class ParametersDefinitionProperty extends OptionalJobProperty> } @Deprecated - public AbstractProject getOwner() { + public AbstractProject getOwner() { return (AbstractProject) owner; } @@ -137,8 +138,8 @@ public class ParametersDefinitionProperty extends OptionalJobProperty> * This method is supposed to be invoked from {@link ParameterizedJobMixIn#doBuild(StaplerRequest, StaplerResponse, TimeDuration)}. */ public void _doBuild(StaplerRequest req, StaplerResponse rsp, @QueryParameter TimeDuration delay) throws IOException, ServletException { - if (delay==null) - delay=new TimeDuration(TimeUnit.MILLISECONDS.convert(getJob().getQuietPeriod(), TimeUnit.SECONDS)); + if (delay == null) + delay = new TimeDuration(TimeUnit.MILLISECONDS.convert(getJob().getQuietPeriod(), TimeUnit.SECONDS)); List values = new ArrayList<>(); @@ -151,7 +152,7 @@ public class ParametersDefinitionProperty extends OptionalJobProperty> String name = jo.getString("name"); ParameterDefinition d = getParameterDefinition(name); - if(d==null) + if (d == null) throw new IllegalArgumentException("No such parameter definition: " + name); ParameterValue parameterValue = d.createValue(req, jo); if (parameterValue != null) { @@ -163,11 +164,11 @@ public class ParametersDefinitionProperty extends OptionalJobProperty> WaitingItem item = Jenkins.get().getQueue().schedule( getJob(), delay.getTimeInSeconds(), new ParametersAction(values), new CauseAction(new Cause.UserIdCause())); - if (item!=null) { + if (item != null) { String url = formData.optString("redirectTo"); - if (url==null || !Util.isSafeToRedirectTo(url)) // avoid open redirect - url = req.getContextPath()+'/'+item.getUrl(); - rsp.sendRedirect(formData.optInt("statusCode",SC_CREATED), url); + if (url == null || !Util.isSafeToRedirectTo(url)) // avoid open redirect + url = req.getContextPath() + '/' + item.getUrl(); + rsp.sendRedirect(formData.optInt("statusCode", SC_CREATED), url); } else // send the user back to the job top page. rsp.sendRedirect("."); @@ -176,19 +177,19 @@ public class ParametersDefinitionProperty extends OptionalJobProperty> /** @deprecated use {@link #buildWithParameters(StaplerRequest, StaplerResponse, TimeDuration)} */ @Deprecated public void buildWithParameters(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { - buildWithParameters(req,rsp,TimeDuration.fromString(req.getParameter("delay"))); + buildWithParameters(req, rsp, TimeDuration.fromString(req.getParameter("delay"))); } public void buildWithParameters(StaplerRequest req, StaplerResponse rsp, @CheckForNull TimeDuration delay) throws IOException, ServletException { List values = new ArrayList<>(); - for (ParameterDefinition d: parameterDefinitions) { + for (ParameterDefinition d : parameterDefinitions) { ParameterValue value = d.createValue(req); if (value != null) { values.add(value); } } - if (delay==null) - delay=new TimeDuration(TimeUnit.MILLISECONDS.convert(getJob().getQuietPeriod(), TimeUnit.SECONDS)); + if (delay == null) + delay = new TimeDuration(TimeUnit.MILLISECONDS.convert(getJob().getQuietPeriod(), TimeUnit.SECONDS)); ScheduleResult scheduleResult = Jenkins.get().getQueue().schedule2( getJob(), delay.getTimeInSeconds(), new ParametersAction(values), ParameterizedJobMixIn.getBuildCause(getJob(), req)); @@ -221,7 +222,7 @@ public class ParametersDefinitionProperty extends OptionalJobProperty> public static class DescriptorImpl extends OptionalJobPropertyDescriptor { @Override public ParametersDefinitionProperty newInstance(StaplerRequest req, JSONObject formData) throws FormException { - ParametersDefinitionProperty prop = (ParametersDefinitionProperty)super.newInstance(req, formData); + ParametersDefinitionProperty prop = (ParametersDefinitionProperty) super.newInstance(req, formData); if (prop != null && prop.parameterDefinitions.isEmpty()) { return null; } diff --git a/core/src/main/java/hudson/model/PasswordParameterDefinition.java b/core/src/main/java/hudson/model/PasswordParameterDefinition.java index ff424d159c696a805b84b467dd88c9ae8f327e16..58846ac4a2b560d9f84b74af1e83bbe5291fc91a 100644 --- a/core/src/main/java/hudson/model/PasswordParameterDefinition.java +++ b/core/src/main/java/hudson/model/PasswordParameterDefinition.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import edu.umd.cs.findbugs.annotations.CheckForNull; diff --git a/core/src/main/java/hudson/model/PasswordParameterValue.java b/core/src/main/java/hudson/model/PasswordParameterValue.java index a69b3e40317c5781f921ef9b70fd32fcaffb8de4..4f761587a370e41493e39e8d490ed91177cad123 100644 --- a/core/src/main/java/hudson/model/PasswordParameterValue.java +++ b/core/src/main/java/hudson/model/PasswordParameterValue.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import edu.umd.cs.findbugs.annotations.NonNull; @@ -56,10 +57,10 @@ public class PasswordParameterValue extends ParameterValue { } @Override - public void buildEnvironment(Run build, EnvVars env) { + public void buildEnvironment(Run build, EnvVars env) { String v = Secret.toString(value); env.put(name, v); - env.put(name.toUpperCase(Locale.ENGLISH),v); // backward compatibility pre 1.345 + env.put(name.toUpperCase(Locale.ENGLISH), v); // backward compatibility pre 1.345 } @Override diff --git a/core/src/main/java/hudson/model/PeriodicWork.java b/core/src/main/java/hudson/model/PeriodicWork.java index 9a4e7279a9df5f9baa8a44f93fb9d8df333abe52..3a5bb3b4f01f7fb46704b6036fabe5129f1ee414 100644 --- a/core/src/main/java/hudson/model/PeriodicWork.java +++ b/core/src/main/java/hudson/model/PeriodicWork.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import static hudson.init.InitMilestone.JOB_CONFIG_ADAPTED; @@ -58,7 +59,7 @@ import jenkins.util.Timer; * @author Kohsuke Kawaguchi * @see AsyncPeriodicWork */ -@SuppressFBWarnings(value="PREDICTABLE_RANDOM", justification = "The random is just used for an initial delay.") +@SuppressFBWarnings(value = "PREDICTABLE_RANDOM", justification = "The random is just used for an initial delay.") public abstract class PeriodicWork extends SafeTimerTask implements ExtensionPoint { /** @deprecated Use your own logger, or send messages to the logger in {@link AsyncPeriodicWork#execute}. */ @@ -88,9 +89,9 @@ public abstract class PeriodicWork extends SafeTimerTask implements ExtensionPoi public long getInitialDelay() { long l = RANDOM.nextLong(); // Math.abs(Long.MIN_VALUE)==Long.MIN_VALUE! - if (l==Long.MIN_VALUE) + if (l == Long.MIN_VALUE) l++; - return Math.abs(l)%getRecurrencePeriod(); + return Math.abs(l) % getRecurrencePeriod(); } /** @@ -100,7 +101,7 @@ public abstract class PeriodicWork extends SafeTimerTask implements ExtensionPoi return ExtensionList.lookup(PeriodicWork.class); } - @Initializer(after= JOB_CONFIG_ADAPTED) + @Initializer(after = JOB_CONFIG_ADAPTED) public static void init() { // start all PeriodicWorks ExtensionList extensionList = all(); @@ -115,9 +116,9 @@ public abstract class PeriodicWork extends SafeTimerTask implements ExtensionPoi } // time constants - protected static final long MIN = 1000*60; - protected static final long HOUR =60*MIN; - protected static final long DAY = 24*HOUR; + protected static final long MIN = 1000 * 60; + protected static final long HOUR = 60 * MIN; + protected static final long DAY = 24 * HOUR; private static final Random RANDOM = new Random(); diff --git a/core/src/main/java/hudson/model/PermalinkProjectAction.java b/core/src/main/java/hudson/model/PermalinkProjectAction.java index 301c966777104a6f434d741617341e529c7625fc..9013ddd5efc58f3ad8ad05dd408a06c3c54491ce 100644 --- a/core/src/main/java/hudson/model/PermalinkProjectAction.java +++ b/core/src/main/java/hudson/model/PermalinkProjectAction.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import edu.umd.cs.findbugs.annotations.CheckForNull; @@ -51,7 +52,7 @@ public interface PermalinkProjectAction extends Action { *

    * Because {@link Permalink} is a strategy-pattern object, * this method should normally return a pre-initialized - * read-only static list object. + * read-only static list object. * * @return * can be empty, but never null. @@ -87,7 +88,7 @@ public interface PermalinkProjectAction extends Action { * @return null * if the target of the permalink doesn't exist. */ - public abstract @CheckForNull Run resolve(Job job); + public abstract @CheckForNull Run resolve(Job job); /** * List of {@link Permalink}s that are built into Jenkins. @@ -106,7 +107,7 @@ public interface PermalinkProjectAction extends Action { } @Override - public Run resolve(Job job) { + public Run resolve(Job job) { return job.getLastBuild(); } }; @@ -123,7 +124,7 @@ public interface PermalinkProjectAction extends Action { @Override public boolean apply(Run run) { - return !run.isBuilding() && run.getResult()==Result.SUCCESS; + return !run.isBuilding() && run.getResult() == Result.SUCCESS; } }; public static final Permalink LAST_SUCCESSFUL_BUILD = new PeepholePermalink() { @@ -156,7 +157,7 @@ public interface PermalinkProjectAction extends Action { @Override public boolean apply(Run run) { - return !run.isBuilding() && run.getResult()==Result.FAILURE; + return !run.isBuilding() && run.getResult() == Result.FAILURE; } }; @@ -173,7 +174,7 @@ public interface PermalinkProjectAction extends Action { @Override public boolean apply(Run run) { - return !run.isBuilding() && run.getResult()==Result.UNSTABLE; + return !run.isBuilding() && run.getResult() == Result.UNSTABLE; } }; @@ -190,7 +191,7 @@ public interface PermalinkProjectAction extends Action { @Override public boolean apply(Run run) { - return !run.isBuilding() && run.getResult()!=Result.SUCCESS; + return !run.isBuilding() && run.getResult() != Result.SUCCESS; } }; public static final Permalink LAST_COMPLETED_BUILD = new PeepholePermalink() { diff --git a/core/src/main/java/hudson/model/PersistenceRoot.java b/core/src/main/java/hudson/model/PersistenceRoot.java index 4e417d0539631bc8c9cff912a4f609b2bab1fa78..759094428f34cff5f2d70da3ae819f6d0fff2490 100644 --- a/core/src/main/java/hudson/model/PersistenceRoot.java +++ b/core/src/main/java/hudson/model/PersistenceRoot.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import java.io.File; diff --git a/core/src/main/java/hudson/model/Project.java b/core/src/main/java/hudson/model/Project.java index 3ed33d9bcd1a47405f5a28edacccda2bb71cd927..7dc8b692d9401d9eda5fa165e92f157ff1fdf073 100644 --- a/core/src/main/java/hudson/model/Project.java +++ b/core/src/main/java/hudson/model/Project.java @@ -1,19 +1,19 @@ /* * The MIT License - * + * * Copyright (c) 2004-2011, Sun Microsystems, Inc., Kohsuke Kawaguchi, * Jorg Heymans, Stephen Connolly, Tom Huybrechts - * + * * 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 @@ -22,6 +22,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import hudson.Util; @@ -59,35 +60,35 @@ import org.kohsuke.stapler.StaplerResponse; * * @author Kohsuke Kawaguchi */ -public abstract class Project

    ,B extends Build> - extends AbstractProject implements SCMTriggerItem, Saveable, ProjectWithMaven, BuildableItemWithBuildWrappers { +public abstract class Project

    , B extends Build> + extends AbstractProject implements SCMTriggerItem, Saveable, ProjectWithMaven, BuildableItemWithBuildWrappers { /** * List of active {@link Builder}s configured for this project. */ - private volatile DescribableList> builders; - private static final AtomicReferenceFieldUpdater buildersSetter - = AtomicReferenceFieldUpdater.newUpdater(Project.class,DescribableList.class,"builders"); + private volatile DescribableList> builders; + private static final AtomicReferenceFieldUpdater buildersSetter + = AtomicReferenceFieldUpdater.newUpdater(Project.class, DescribableList.class, "builders"); /** * List of active {@link Publisher}s configured for this project. */ - private volatile DescribableList> publishers; - private static final AtomicReferenceFieldUpdater publishersSetter - = AtomicReferenceFieldUpdater.newUpdater(Project.class,DescribableList.class,"publishers"); + private volatile DescribableList> publishers; + private static final AtomicReferenceFieldUpdater publishersSetter + = AtomicReferenceFieldUpdater.newUpdater(Project.class, DescribableList.class, "publishers"); /** * List of active {@link BuildWrapper}s configured for this project. */ - private volatile DescribableList> buildWrappers; - private static final AtomicReferenceFieldUpdater buildWrappersSetter - = AtomicReferenceFieldUpdater.newUpdater(Project.class,DescribableList.class,"buildWrappers"); + private volatile DescribableList> buildWrappers; + private static final AtomicReferenceFieldUpdater buildWrappersSetter + = AtomicReferenceFieldUpdater.newUpdater(Project.class, DescribableList.class, "buildWrappers"); /** * Creates a new project. */ - protected Project(ItemGroup parent,String name) { - super(parent,name); + protected Project(ItemGroup parent, String name) { + super(parent, name); } @Override @@ -125,33 +126,33 @@ public abstract class Project

    ,B extends Build> * Use {@link #getPublishersList()} instead. */ @Deprecated - public Map,Publisher> getPublishers() { + public Map, Publisher> getPublishers() { return getPublishersList().toMap(); } - public DescribableList> getBuildersList() { + public DescribableList> getBuildersList() { if (builders == null) { - buildersSetter.compareAndSet(this,null,new DescribableList>(this)); + buildersSetter.compareAndSet(this, null, new DescribableList>(this)); } return builders; } - + @Override - public DescribableList> getPublishersList() { + public DescribableList> getPublishersList() { if (publishers == null) { - publishersSetter.compareAndSet(this,null,new DescribableList>(this)); + publishersSetter.compareAndSet(this, null, new DescribableList>(this)); } return publishers; } - public Map,BuildWrapper> getBuildWrappers() { + public Map, BuildWrapper> getBuildWrappers() { return getBuildWrappersList().toMap(); } @Override public DescribableList> getBuildWrappersList() { if (buildWrappers == null) { - buildWrappersSetter.compareAndSet(this,null,new DescribableList>(this)); + buildWrappersSetter.compareAndSet(this, null, new DescribableList>(this)); } return buildWrappers; } @@ -161,9 +162,9 @@ public abstract class Project

    ,B extends Build> final Set activities = new HashSet<>(); activities.addAll(super.getResourceActivities()); - activities.addAll(Util.filter(getBuildersList(),ResourceActivity.class)); - activities.addAll(Util.filter(getPublishersList(),ResourceActivity.class)); - activities.addAll(Util.filter(getBuildWrappersList(),ResourceActivity.class)); + activities.addAll(Util.filter(getBuildersList(), ResourceActivity.class)); + activities.addAll(Util.filter(getPublishersList(), ResourceActivity.class)); + activities.addAll(Util.filter(getBuildWrappersList(), ResourceActivity.class)); return activities; } @@ -192,7 +193,7 @@ public abstract class Project

    ,B extends Build> public Publisher getPublisher(Descriptor descriptor) { for (Publisher p : getPublishersList()) { - if(p.getDescriptor()==descriptor) + if (p.getDescriptor() == descriptor) return p; } return null; @@ -200,20 +201,20 @@ public abstract class Project

    ,B extends Build> @Override protected void buildDependencyGraph(DependencyGraph graph) { super.buildDependencyGraph(graph); - getPublishersList().buildDependencyGraph(this,graph); - getBuildersList().buildDependencyGraph(this,graph); - getBuildWrappersList().buildDependencyGraph(this,graph); + getPublishersList().buildDependencyGraph(this, graph); + getBuildersList().buildDependencyGraph(this, graph); + getBuildWrappersList().buildDependencyGraph(this, graph); } @Override public boolean isFingerprintConfigured() { - return getPublishersList().get(Fingerprinter.class)!=null; + return getPublishersList().get(Fingerprinter.class) != null; } @Override public MavenInstallation inferMavenInstallation() { Maven m = getBuildersList().get(Maven.class); - if (m!=null) return m.getMaven(); + if (m != null) return m.getMaven(); return null; } @@ -223,13 +224,13 @@ public abstract class Project

    ,B extends Build> // // @Override - protected void submit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException { - super.submit(req,rsp); + protected void submit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException { + super.submit(req, rsp); JSONObject json = req.getSubmittedForm(); - getBuildWrappersList().rebuild(req,json, BuildWrappers.getFor(this)); - getBuildersList().rebuildHetero(req,json, Builder.all(), "builder"); + getBuildWrappersList().rebuild(req, json, BuildWrappers.getFor(this)); + getBuildersList().rebuildHetero(req, json, Builder.all(), "builder"); getPublishersList().rebuildHetero(req, json, Publisher.all(), "publisher"); } diff --git a/core/src/main/java/hudson/model/ProminentProjectAction.java b/core/src/main/java/hudson/model/ProminentProjectAction.java index 082f87580ed3a32fa92f7f67c5a884ff446993a9..6d3e48aef31dc98eb399e781f3cd3de09945542d 100644 --- a/core/src/main/java/hudson/model/ProminentProjectAction.java +++ b/core/src/main/java/hudson/model/ProminentProjectAction.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import hudson.tasks.BuildStep; diff --git a/core/src/main/java/hudson/model/ProxyView.java b/core/src/main/java/hudson/model/ProxyView.java index e78c864947614a12d13562b59bfdaa935c4b0722..3f33302744dc8506159c84de9487c7dc1e64badc 100644 --- a/core/src/main/java/hudson/model/ProxyView.java +++ b/core/src/main/java/hudson/model/ProxyView.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Tom Huybrechts - * + * * 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 @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import hudson.Extension; @@ -42,9 +43,9 @@ import org.kohsuke.stapler.interceptor.RequirePOST; /** * A view that delegates to another. - * + * * TODO: this does not respond to renaming or deleting the proxied view. - * + * * @author Tom Huybrechts * */ @@ -117,9 +118,9 @@ public class ProxyView extends View implements StaplerFallback { checkPermission(View.CREATE); String view = Util.fixEmpty(value); - if(view==null) return FormValidation.ok(); + if (view == null) return FormValidation.ok(); - if(Jenkins.get().getView(view)!=null) + if (Jenkins.get().getView(view) != null) return FormValidation.ok(); else return FormValidation.error(Messages.ProxyView_NoSuchViewExists(value)); @@ -132,11 +133,11 @@ public class ProxyView extends View implements StaplerFallback { public String getDisplayName() { return Messages.ProxyView_DisplayName(); } - + @Override public boolean isInstantiable() { - // doesn't make sense to add a ProxyView to the global views - return !(Stapler.getCurrentRequest().findAncestorObject(ViewGroup.class) instanceof Jenkins); + // doesn't make sense to add a ProxyView to the global views + return !(Stapler.getCurrentRequest().findAncestorObject(ViewGroup.class) instanceof Jenkins); } } diff --git a/core/src/main/java/hudson/model/Queue.java b/core/src/main/java/hudson/model/Queue.java index d0dbb990c87ce92ebda2b5e17dc9c9a1d082f243..e0abed68ccd5ec51790aa64dbc177da7b0ccea0f 100644 --- a/core/src/main/java/hudson/model/Queue.java +++ b/core/src/main/java/hudson/model/Queue.java @@ -22,6 +22,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import static hudson.init.InitMilestone.JOB_CONFIG_ADAPTED; @@ -211,7 +212,7 @@ public class Queue extends ResourceController implements Saveable { * * This map is forgetful, since we can't remember everything that executed in the past. */ - private final Cache leftItems = CacheBuilder.newBuilder().expireAfterWrite(5*60, TimeUnit.SECONDS).build(); + private final Cache leftItems = CacheBuilder.newBuilder().expireAfterWrite(5 * 60, TimeUnit.SECONDS).build(); /** * Data structure created for each idle {@link Executor}. @@ -315,7 +316,7 @@ public class Queue extends ResourceController implements Saveable { @Override public String toString() { - return String.format("JobOffer[%s #%d]",executor.getOwner().getName(), executor.getNumber()); + return String.format("JobOffer[%s #%d]", executor.getOwner().getName(), executor.getNumber()); } } @@ -398,7 +399,7 @@ public class Queue extends ResourceController implements Saveable { long maxId = 0; for (Object o : items) { if (o instanceof Item) { - maxId = Math.max(maxId, ((Item)o).id); + maxId = Math.max(maxId, ((Item) o).id); } } WaitingItem.COUNTER.set(maxId); @@ -407,9 +408,9 @@ public class Queue extends ResourceController implements Saveable { for (Object o : items) { if (o instanceof Task) { // backward compatibility - schedule((Task)o, 0); + schedule((Task) o, 0); } else if (o instanceof Item) { - Item item = (Item)o; + Item item = (Item) o; if (item.task == null) { continue; // botched persistence. throw this one away @@ -447,7 +448,7 @@ public class Queue extends ResourceController implements Saveable { */ @Override public void save() { - if(BulkChange.contains(this)) return; + if (BulkChange.contains(this)) return; if (Jenkins.getInstanceOrNull() == null) { return; } @@ -460,8 +461,8 @@ public class Queue extends ResourceController implements Saveable { state.counter = WaitingItem.COUNTER.longValue(); // write out the tasks on the queue - for (Item item: getItems()) { - if(item.task instanceof TransientTask) continue; + for (Item item : getItems()) { + if (item.task instanceof TransientTask) continue; state.items.add(item); } @@ -505,7 +506,7 @@ public class Queue extends ResourceController implements Saveable { */ @Deprecated public boolean add(AbstractProject p) { - return schedule(p)!=null; + return schedule(p) != null; } /** @@ -528,7 +529,7 @@ public class Queue extends ResourceController implements Saveable { */ @Deprecated public boolean add(AbstractProject p, int quietPeriod) { - return schedule(p, quietPeriod)!=null; + return schedule(p, quietPeriod) != null; } /** @@ -665,7 +666,7 @@ public class Queue extends ResourceController implements Saveable { */ @Deprecated public boolean add(Task p, int quietPeriod) { - return schedule(p, quietPeriod)!=null; + return schedule(p, quietPeriod) != null; } public @CheckForNull WaitingItem schedule(Task p, int quietPeriod) { @@ -678,7 +679,7 @@ public class Queue extends ResourceController implements Saveable { */ @Deprecated public boolean add(Task p, int quietPeriod, Action... actions) { - return schedule(p, quietPeriod, actions)!=null; + return schedule(p, quietPeriod, actions) != null; } /** @@ -745,8 +746,8 @@ public class Queue extends ResourceController implements Saveable { item = null; } if (item != null) { - if(item.hasCancelPermission()){ - if(cancel(item)) { + if (item.hasCancelPermission()) { + if (cancel(item)) { return HttpResponses.status(HttpServletResponse.SC_NO_CONTENT); } return HttpResponses.error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not cancel run for id " + id); @@ -772,15 +773,15 @@ public class Queue extends ResourceController implements Saveable { * Generally speaking the array is sorted such that the items that are most likely built sooner are * at the end. */ - @Exported(inline=true) + @Exported(inline = true) public Item[] getItems() { Snapshot s = this.snapshot; List r = new ArrayList<>(); - for(WaitingItem p : s.waitingList) { + for (WaitingItem p : s.waitingList) { r = checkPermissionsAndAddToList(r, p); } - for (BlockedItem p : s.blockedProjects){ + for (BlockedItem p : s.blockedProjects) { r = checkPermissionsAndAddToList(r, p); } for (BuildableItem p : reverse(s.buildables)) { @@ -825,15 +826,15 @@ public class Queue extends ResourceController implements Saveable { * at the end. */ @Restricted(NoExternalUse.class) - @Exported(inline=true) + @Exported(inline = true) public StubItem[] getDiscoverableItems() { Snapshot s = this.snapshot; List r = new ArrayList<>(); - for(WaitingItem p : s.waitingList) { + for (WaitingItem p : s.waitingList) { r = filterDiscoverableItemListBasedOnPermissions(r, p); } - for (BlockedItem p : s.blockedProjects){ + for (BlockedItem p : s.blockedProjects) { r = filterDiscoverableItemListBasedOnPermissions(r, p); } for (BuildableItem p : reverse(s.buildables)) { @@ -1149,7 +1150,7 @@ public class Queue extends ResourceController implements Saveable { * Returns true if this queue contains the said project. */ public boolean contains(Task t) { - return getItem(t)!=null; + return getItem(t) != null; } /** @@ -1209,7 +1210,7 @@ public class Queue extends ResourceController implements Saveable { return causeOfBlockage; } - if(!(i instanceof BuildableItem)) { + if (!(i instanceof BuildableItem)) { // Make sure we don't queue two tasks of the same project to be built // unless that project allows concurrent builds. Once item is buildable it's ok. // @@ -1336,6 +1337,7 @@ public class Queue extends ResourceController implements Saveable { * @param runnable the operation to wrap. * @since 1.618 */ + public static Runnable wrapWithLock(Runnable runnable) { final Jenkins jenkins = Jenkins.getInstanceOrNull(); // TODO confirm safe to assume non-null and use getInstance() @@ -1482,7 +1484,7 @@ public class Queue extends ResourceController implements Saveable { // The executors that are currently waiting for a job to run. Map parked = new HashMap<>(); - {// update parked (and identify any pending items whose executor has disappeared) + { // update parked (and identify any pending items whose executor has disappeared) List lostPendings = new ArrayList<>(pendings); for (Computer c : jenkins.getComputers()) { for (Executor e : c.getAllExecutors()) { @@ -1507,7 +1509,7 @@ public class Queue extends ResourceController implements Saveable { } } // pending -> buildable - for (BuildableItem p: lostPendings) { + for (BuildableItem p : lostPendings) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "BuildableItem {0}: pending -> buildable as the assigned executor disappeared", @@ -1521,7 +1523,7 @@ public class Queue extends ResourceController implements Saveable { final QueueSorter s = sorter; - {// blocked -> buildable + { // blocked -> buildable // copy as we'll mutate the list and we want to process in a potentially different order List blockedItems = new ArrayList<>(blockedProjects.values()); // if facing a cycle of blocked tasks, ensure we process in the desired sort order @@ -1599,7 +1601,7 @@ public class Queue extends ResourceController implements Saveable { // allocate buildable jobs to executors for (BuildableItem p : new ArrayList<>( - buildables)) {// copy as we'll mutate the list in the loop + buildables)) { // copy as we'll mutate the list in the loop // one last check to make sure this build is not blocked. CauseOfBlockage causeOfBlockage = getCauseOfBlockageForItem(p); if (causeOfBlockage != null) { @@ -1701,7 +1703,7 @@ public class Queue extends ResourceController implements Saveable { Runnable runnable = makeFlyWeightTaskBuildable(p); LOGGER.log(Level.FINEST, "Converting flyweight task: {0} into a BuildableRunnable", taskDisplayName); - if(runnable != null){ + if (runnable != null) { return runnable; } @@ -1727,7 +1729,7 @@ public class Queue extends ResourceController implements Saveable { * @return a Runnable if there is an executor that can take the task, null otherwise */ @CheckForNull - private Runnable makeFlyWeightTaskBuildable(final BuildableItem p){ + private Runnable makeFlyWeightTaskBuildable(final BuildableItem p) { //we double check if this is a flyweight task if (p.task instanceof FlyweightTask) { Jenkins h = Jenkins.get(); @@ -1765,7 +1767,7 @@ public class Queue extends ResourceController implements Saveable { if (c == null || c.isOffline()) { continue; } - if (lbl!=null && !lbl.contains(n)) { + if (lbl != null && !lbl.contains(n)) { continue; } if (n.canTake(p) != null) { @@ -2208,7 +2210,7 @@ public class Queue extends ResourceController implements Saveable { public Label getAssignedLabel() { for (LabelAssignmentAction laa : getActions(LabelAssignmentAction.class)) { Label l = laa.getAssignedLabel(task); - if (l!=null) return l; + if (l != null) return l; } return task.getAssignedLabel(); } @@ -2226,7 +2228,7 @@ public class Queue extends ResourceController implements Saveable { public @CheckForNull Label getAssignedLabelFor(@NonNull SubTask st) { for (LabelAssignmentAction laa : getActions(LabelAssignmentAction.class)) { Label l = laa.getAssignedLabel(st); - if (l!=null) return l; + if (l != null) return l; } return st.getAssignedLabel(); } @@ -2239,7 +2241,7 @@ public class Queue extends ResourceController implements Saveable { */ public final List getCauses() { CauseAction ca = getAction(CauseAction.class); - if (ca!=null) + if (ca != null) return Collections.unmodifiableList(ca.getCauses()); return Collections.emptyList(); } @@ -2259,7 +2261,7 @@ public class Queue extends ResourceController implements Saveable { this.id = id; this.future = future; this.inQueueSince = System.currentTimeMillis(); - for (Action action: actions) addAction(action); + for (Action action : actions) addAction(action); } protected Item(Task task, List actions, long id, FutureImpl future, long inQueueSince) { @@ -2267,7 +2269,7 @@ public class Queue extends ResourceController implements Saveable { this.id = id; this.future = future; this.inQueueSince = inQueueSince; - for (Action action: actions) addAction(action); + for (Action action : actions) addAction(action); } @SuppressWarnings("deprecation") // JENKINS-51584 @@ -2285,7 +2287,7 @@ public class Queue extends ResourceController implements Saveable { */ @Exported public String getUrl() { - return "queue/item/"+id+'/'; + return "queue/item/" + id + '/'; } /** @@ -2294,7 +2296,7 @@ public class Queue extends ResourceController implements Saveable { @Exported public final String getWhy() { CauseOfBlockage cob = getCauseOfBlockage(); - return cob!=null ? cob.getShortDescription() : null; + return cob != null ? cob.getShortDescription() : null; } /** @@ -2339,7 +2341,7 @@ public class Queue extends ResourceController implements Saveable { @Deprecated @RequirePOST public HttpResponse doCancelQueue() { - if(hasCancelPermission()){ + if (hasCancelPermission()) { Jenkins.get().getQueue().cancel(this); } return HttpResponses.status(HttpServletResponse.SC_NO_CONTENT); @@ -2359,7 +2361,7 @@ public class Queue extends ResourceController implements Saveable { public Authentication authenticate2() { for (QueueItemAuthenticator auth : QueueItemAuthenticatorProvider.authenticators()) { Authentication a = auth.authenticate2(this); - if (a!=null) + if (a != null) return a; } return task.getDefaultAuthentication2(this); @@ -2672,7 +2674,7 @@ public class Queue extends ResourceController implements Saveable { @Override public CauseOfBlockage getCauseOfBlockage() { Jenkins jenkins = Jenkins.get(); - if(isBlockedByShutdown(task)) + if (isBlockedByShutdown(task)) return CauseOfBlockage.fromMessage(Messages._Queue_HudsonIsAboutToShutDown()); List causesOfBlockage = transientCausesOfBlockage; @@ -2704,18 +2706,18 @@ public class Queue extends ResourceController implements Saveable { @Override public boolean isStuck() { Label label = getAssignedLabel(); - if(label!=null && label.isOffline()) + if (label != null && label.isOffline()) // no executor online to process this job. definitely stuck. return true; long d = task.getEstimatedDuration(); - long elapsed = System.currentTimeMillis()-buildableStartMilliseconds; - if(d>=0) { + long elapsed = System.currentTimeMillis() - buildableStartMilliseconds; + if (d >= 0) { // if we were running elsewhere, we would have done this build ten times. - return elapsed > Math.max(d,60000L)*10; + return elapsed > Math.max(d, 60000L) * 10; } else { // more than a day in the queue - return TimeUnit.MILLISECONDS.toHours(elapsed)>24; + return TimeUnit.MILLISECONDS.toHours(elapsed) > 24; } } @@ -2777,7 +2779,7 @@ public class Queue extends ResourceController implements Saveable { */ @Exported public @CheckForNull Executable getExecutable() { - return outcome!=null ? outcome.getPrimaryWorkUnit().getExecutable() : null; + return outcome != null ? outcome.getPrimaryWorkUnit().getExecutable() : null; } /** @@ -2785,12 +2787,12 @@ public class Queue extends ResourceController implements Saveable { */ @Exported public boolean isCancelled() { - return outcome==null; + return outcome == null; } @Override void enter(Queue q) { - q.leftItems.put(getId(),this); + q.leftItems.put(getId(), this); Listeners.notify(QueueListener.class, true, l -> l.onLeft(this)); } @@ -2819,7 +2821,7 @@ public class Queue extends ResourceController implements Saveable { @Override public Object fromString(String string) { Object item = Jenkins.get().getItemByFullName(string); - if(item==null) throw new NoSuchElementException("No such job exists: "+string); + if (item == null) throw new NoSuchElementException("No such job exists: " + string); return item; } @@ -2840,16 +2842,16 @@ public class Queue extends ResourceController implements Saveable { String[] split = string.split("#"); String projectName = split[0]; int buildNumber = Integer.parseInt(split[1]); - Job job = (Job) Jenkins.get().getItemByFullName(projectName); - if(job==null) throw new NoSuchElementException("No such job exists: "+projectName); - Run run = job.getBuildByNumber(buildNumber); - if(run==null) throw new NoSuchElementException("No such build: "+string); + Job job = (Job) Jenkins.get().getItemByFullName(projectName); + if (job == null) throw new NoSuchElementException("No such job exists: " + projectName); + Run run = job.getBuildByNumber(buildNumber); + if (run == null) throw new NoSuchElementException("No such build: " + string); return run; } @Override public String toString(Object object) { - Run run = (Run) object; + Run run = (Run) object; return run.getParent().getFullName() + "#" + run.getNumber(); } }); @@ -2906,7 +2908,7 @@ public class Queue extends ResourceController implements Saveable { */ private class ItemList extends ArrayList { public T get(Task task) { - for (T item: this) { + for (T item : this) { if (item.task.equals(task)) { return item; } @@ -2916,7 +2918,7 @@ public class Queue extends ResourceController implements Saveable { public List getAll(Task task) { List result = new ArrayList<>(); - for (T item: this) { + for (T item : this) { if (item.task.equals(task)) { result.add(item); } @@ -2954,7 +2956,7 @@ public class Queue extends ResourceController implements Saveable { */ public T cancel(Task p) { T x = get(p); - if(x!=null) x.cancel(Queue.this); + if (x != null) x.cancel(Queue.this); return x; } @@ -3028,11 +3030,11 @@ public class Queue extends ResourceController implements Saveable { } } - private static class LockedHRCallable implements hudson.remoting.Callable { + private static class LockedHRCallable implements hudson.remoting.Callable { private static final long serialVersionUID = 1L; - private final hudson.remoting.Callable delegate; + private final hudson.remoting.Callable delegate; - private LockedHRCallable(hudson.remoting.Callable delegate) { + private LockedHRCallable(hudson.remoting.Callable delegate) { this.delegate = delegate; } @@ -3055,7 +3057,7 @@ public class Queue extends ResourceController implements Saveable { /** * Restores the queue content during the start up. */ - @Initializer(after=JOB_CONFIG_ADAPTED) + @Initializer(after = JOB_CONFIG_ADAPTED) public static void init(Jenkins h) { Queue queue = h.getQueue(); Item[] items = queue.getItems(); diff --git a/core/src/main/java/hudson/model/RSS.java b/core/src/main/java/hudson/model/RSS.java index 4b95c28d937f5cc15a4f921d671767b700373e18..19727656e729eb90a3c2d0bc7611b088c12c958f 100644 --- a/core/src/main/java/hudson/model/RSS.java +++ b/core/src/main/java/hudson/model/RSS.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import hudson.FeedAdapter; @@ -53,13 +54,13 @@ public final class RSS { * Controls how to render entries to RSS. */ public static void forwardToRss(String title, String url, Collection entries, FeedAdapter adapter, StaplerRequest req, HttpServletResponse rsp) throws IOException, ServletException { - req.setAttribute("adapter",adapter); - req.setAttribute("title",title); - req.setAttribute("url",url); - req.setAttribute("entries",entries); + req.setAttribute("adapter", adapter); + req.setAttribute("title", title); + req.setAttribute("url", url); + req.setAttribute("entries", entries); String flavor = req.getParameter("flavor"); - if(flavor==null) flavor="atom"; + if (flavor == null) flavor = "atom"; flavor = flavor.replace('/', '_'); // Don't allow path to any jelly if (flavor.equals("atom")) { @@ -68,7 +69,7 @@ public final class RSS { rsp.setContentType("text/xml; charset=UTF-8"); } - req.getView(Jenkins.get(),"/hudson/"+flavor+".jelly").forward(req,rsp); + req.getView(Jenkins.get(), "/hudson/" + flavor + ".jelly").forward(req, rsp); } /** diff --git a/core/src/main/java/hudson/model/ReconfigurableDescribable.java b/core/src/main/java/hudson/model/ReconfigurableDescribable.java index c3ca804c1f553041f4e4056c9471cc99d4413f42..674e0026ce60a5c4f18a5f912e9c19ab81c53514 100644 --- a/core/src/main/java/hudson/model/ReconfigurableDescribable.java +++ b/core/src/main/java/hudson/model/ReconfigurableDescribable.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import edu.umd.cs.findbugs.annotations.CheckForNull; diff --git a/core/src/main/java/hudson/model/Resource.java b/core/src/main/java/hudson/model/Resource.java index cb1e06a9cc828612c451ea4391214840ed75d109..b407f6df99d6f8de9c99c4e9124f7e4d1cfabaa5 100644 --- a/core/src/main/java/hudson/model/Resource.java +++ b/core/src/main/java/hudson/model/Resource.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import edu.umd.cs.findbugs.annotations.CheckForNull; @@ -63,14 +64,14 @@ public final class Resource { public final int numConcurrentWrite; public Resource(@CheckForNull Resource parent, @NonNull String displayName) { - this(parent,displayName,1); + this(parent, displayName, 1); } /** * @since 1.155 */ public Resource(@CheckForNull Resource parent, @NonNull String displayName, int numConcurrentWrite) { - if(numConcurrentWrite<1) + if (numConcurrentWrite < 1) throw new IllegalArgumentException(); this.parent = parent; @@ -79,7 +80,7 @@ public final class Resource { } public Resource(@NonNull String displayName) { - this(null,displayName); + this(null, displayName); } /** @@ -90,12 +91,12 @@ public final class Resource { * For R/W conflict test, this value should be set to {@link Integer#MAX_VALUE}. */ public boolean isCollidingWith(Resource that, int count) { - assert that!=null; - for(Resource r=that; r!=null; r=r.parent) - if(this.equals(r) && r.numConcurrentWrite resourceView = new AbstractCollection() { @Override public Iterator iterator() { - return new AdaptedIterator(inProgress.iterator()) { + return new AdaptedIterator(inProgress.iterator()) { @Override protected ResourceList adapt(ResourceActivity item) { return item.getResourceList(); @@ -79,9 +80,9 @@ public class ResourceController { * @throws InterruptedException * the thread can be interrupted while waiting for the available resources. */ - public void execute(@NonNull Runnable task, final ResourceActivity activity ) throws InterruptedException { + public void execute(@NonNull Runnable task, final ResourceActivity activity) throws InterruptedException { final ResourceList resources = activity.getResourceList(); - _withLock(new NotReallyRoleSensitiveCallable() { + _withLock(new NotReallyRoleSensitiveCallable() { @Override public Void call() throws InterruptedException { while (inUse.isCollidingWith(resources)) { @@ -162,7 +163,7 @@ public class ResourceController { public ResourceActivity getBlockingActivity(ResourceActivity activity) { ResourceList res = activity.getResourceList(); for (ResourceActivity a : inProgress) - if(res.isCollidingWith(a.getResourceList())) + if (res.isCollidingWith(a.getResourceList())) return a; return null; } @@ -188,7 +189,7 @@ public class ResourceController { } } - protected V _withLock(hudson.remoting.Callable callable) throws T { + protected V _withLock(hudson.remoting.Callable callable) throws T { synchronized (this) { return callable.call(); } diff --git a/core/src/main/java/hudson/model/ResourceList.java b/core/src/main/java/hudson/model/ResourceList.java index eb57076c9a9d37a4f0579b5192157bf86108931c..e94a91996a13e5e32e3c1cb22dffc6855f4784a5 100644 --- a/core/src/main/java/hudson/model/ResourceList.java +++ b/core/src/main/java/hudson/model/ResourceList.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import java.util.Arrays; @@ -39,7 +40,7 @@ import java.util.logging.Logger; * As with usual reader/writer pattern, multiple read accesses can * co-exist concurrently, but write access requires exclusive access * (the number of allowed concurrent write activity is determined by - * {@link Resource#numConcurrentWrite}. + * {@link Resource#numConcurrentWrite}. * * @author Kohsuke Kawaguchi * @since 1.121 @@ -59,7 +60,7 @@ public final class ResourceList { * The values are mostly supposed to be 1, but when {@link ResourceController} * uses a list to keep track of the union of all the activities, it can get larger. */ - private final Map write = new HashMap<>(); + private final Map write = new HashMap<>(); private static final Integer MAX_INT = Integer.MAX_VALUE; /** @@ -73,7 +74,7 @@ public final class ResourceList { * Creates union of all resources. */ public static ResourceList union(Collection lists) { - switch(lists.size()) { + switch (lists.size()) { case 0: return EMPTY; case 1: @@ -83,7 +84,7 @@ public final class ResourceList { for (ResourceList l : lists) { r.all.addAll(l.all); for (Map.Entry e : l.write.entrySet()) - r.write.put(e.getKey(), unbox(r.write.get(e.getKey()))+e.getValue()); + r.write.put(e.getKey(), unbox(r.write.get(e.getKey())) + e.getValue()); } return r; } @@ -102,7 +103,7 @@ public final class ResourceList { */ public ResourceList w(Resource r) { all.add(r); - write.put(r, unbox(write.get(r))+1); + write.put(r, unbox(write.get(r)) + 1); return this; } @@ -111,27 +112,27 @@ public final class ResourceList { * resource access. */ public boolean isCollidingWith(ResourceList that) { - return getConflict(that)!=null; + return getConflict(that) != null; } /** * Returns the resource in this list that's colliding with the given resource list. */ public Resource getConflict(ResourceList that) { - Resource r = _getConflict(this,that); - if(r!=null) return r; - return _getConflict(that,this); + Resource r = _getConflict(this, that); + if (r != null) return r; + return _getConflict(that, this); } private Resource _getConflict(ResourceList lhs, ResourceList rhs) { - for (Map.Entry r : lhs.write.entrySet()) { + for (Map.Entry r : lhs.write.entrySet()) { for (Resource l : rhs.all) { Integer v = rhs.write.get(l); - if(v!=null) // this is write/write conflict. + if (v != null) // this is write/write conflict. v += r.getValue(); else // Otherwise set it to a very large value, since it's read/write conflict v = MAX_INT; - if(r.getKey().isCollidingWith(l,unbox(v))) { + if (r.getKey().isCollidingWith(l, unbox(v))) { LOGGER.info("Collision with " + r + " and " + l); return r.getKey(); } @@ -142,11 +143,11 @@ public final class ResourceList { @Override public String toString() { - Map m = new HashMap<>(); + Map m = new HashMap<>(); for (Resource r : all) - m.put(r,"R"); - for (Map.Entry e : write.entrySet()) - m.put(e.getKey(),"W"+e.getValue()); + m.put(r, "R"); + for (Map.Entry e : write.entrySet()) + m.put(e.getKey(), "W" + e.getValue()); return m.toString(); } @@ -154,7 +155,7 @@ public final class ResourceList { * {@link Integer} unbox operation that treats null as 0. */ private static int unbox(Integer x) { - return x==null ? 0 : x; + return x == null ? 0 : x; } /** diff --git a/core/src/main/java/hudson/model/RestartListener.java b/core/src/main/java/hudson/model/RestartListener.java index 2160abc9fbdd93327d67396cd5de74bce9d5501a..828eeb0d2e2e9f4bc850ca0cdbfa5a2bb45015a5 100644 --- a/core/src/main/java/hudson/model/RestartListener.java +++ b/core/src/main/java/hudson/model/RestartListener.java @@ -63,6 +63,7 @@ public abstract class RestartListener implements ExtensionPoint { } return true; } + private static boolean blocksRestart(Executor e) { if (e.isBusy()) { AsynchronousExecution execution = e.getAsynchronousExecution(); diff --git a/core/src/main/java/hudson/model/Result.java b/core/src/main/java/hudson/model/Result.java index 72b7a87f868367d2673fe0eeefd45860a70386b2..b56867e37ed01a96ad6342056a62e9b107c8bdb5 100644 --- a/core/src/main/java/hudson/model/Result.java +++ b/core/src/main/java/hudson/model/Result.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import com.thoughtworks.xstream.converters.SingleValueConverter; @@ -51,30 +52,30 @@ public final class Result implements Serializable, CustomExportedBean { /** * The build had no errors. */ - public static final @NonNull Result SUCCESS = new Result("SUCCESS",BallColor.BLUE,0,true); + public static final @NonNull Result SUCCESS = new Result("SUCCESS", BallColor.BLUE, 0, true); /** * The build had some errors but they were not fatal. * For example, some tests failed. */ - public static final @NonNull Result UNSTABLE = new Result("UNSTABLE",BallColor.YELLOW,1,true); + public static final @NonNull Result UNSTABLE = new Result("UNSTABLE", BallColor.YELLOW, 1, true); /** * The build had a fatal error. */ - public static final @NonNull Result FAILURE = new Result("FAILURE",BallColor.RED,2,true); + public static final @NonNull Result FAILURE = new Result("FAILURE", BallColor.RED, 2, true); /** * The module was not built. *

    * This status code is used in a multi-stage build (like maven2) * where a problem in earlier stage prevented later stages from building. */ - public static final @NonNull Result NOT_BUILT = new Result("NOT_BUILT",BallColor.NOTBUILT,3,false); + public static final @NonNull Result NOT_BUILT = new Result("NOT_BUILT", BallColor.NOTBUILT, 3, false); /** * The build was manually aborted. * * If you are catching {@link InterruptedException} and interpreting it as {@link #ABORTED}, * you should check {@link Executor#abortResult()} instead (starting 1.417.) */ - public static final @NonNull Result ABORTED = new Result("ABORTED",BallColor.ABORTED,4,false); + public static final @NonNull Result ABORTED = new Result("ABORTED", BallColor.ABORTED, 4, false); private final @NonNull String name; @@ -87,7 +88,7 @@ public final class Result implements Serializable, CustomExportedBean { * Default ball color for this status. */ public final @NonNull BallColor color; - + /** * Is this a complete build - i.e. did it run to the end (not aborted)? * @since 1.526 @@ -105,7 +106,7 @@ public final class Result implements Serializable, CustomExportedBean { * Combines two {@link Result}s and returns the worse one. */ public @NonNull Result combine(@NonNull Result that) { - if(this.ordinal < that.ordinal) + if (this.ordinal < that.ordinal) return that; else return this; @@ -149,7 +150,7 @@ public final class Result implements Serializable, CustomExportedBean { public boolean isBetterOrEqualTo(@NonNull Result that) { return this.ordinal <= that.ordinal; } - + /** * Is this a complete build - i.e. did it run to the end (not aborted)? * @since 1.526 @@ -167,7 +168,7 @@ public final class Result implements Serializable, CustomExportedBean { public @NonNull String toExportedObject() { return name; } - + public static @NonNull Result fromString(@NonNull String s) { for (Result r : all) if (s.equalsIgnoreCase(r.name)) @@ -185,19 +186,19 @@ public final class Result implements Serializable, CustomExportedBean { // Maintain each Result as a singleton deserialized (like build result from an agent node) private Object readResolve() { for (Result r : all) - if (ordinal==r.ordinal) + if (ordinal == r.ordinal) return r; return FAILURE; } private static final long serialVersionUID = 1L; - private static final Result[] all = new Result[] {SUCCESS,UNSTABLE,FAILURE,NOT_BUILT,ABORTED}; + private static final Result[] all = new Result[] {SUCCESS, UNSTABLE, FAILURE, NOT_BUILT, ABORTED}; - public static final SingleValueConverter conv = new AbstractSingleValueConverter () { + public static final SingleValueConverter conv = new AbstractSingleValueConverter() { @Override public boolean canConvert(Class clazz) { - return clazz==Result.class; + return clazz == Result.class; } @Override @@ -216,8 +217,8 @@ public final class Result implements Serializable, CustomExportedBean { public int parseArguments(Parameters params) throws CmdLineException { String param = params.getParameter(0); Result v = fromString(param.replace('-', '_')); - if (v== FAILURE) { - throw new CmdLineException(owner,"No such status '"+param+"'. Did you mean "+ + if (v == FAILURE) { + throw new CmdLineException(owner, "No such status '" + param + "'. Did you mean " + EditDistance.findNearest(param.replace('-', '_').toUpperCase(), getNames())); } setter.addValue(v); diff --git a/core/src/main/java/hudson/model/ResultTrend.java b/core/src/main/java/hudson/model/ResultTrend.java index a03c22dc7c37ef4c48d8956298be26c74ca48653..b966c9bf00724e333d18297bf8e662ac9ae150ee 100644 --- a/core/src/main/java/hudson/model/ResultTrend.java +++ b/core/src/main/java/hudson/model/ResultTrend.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import java.util.Locale; @@ -28,7 +29,7 @@ import org.jvnet.localizer.Localizable; /** * Describes an {@link Result} trend by taking the comparing the result of the current and the previous build. - * + * * @author kutzi * @since 1.416 */ @@ -71,13 +72,13 @@ public enum ResultTrend { * Build didn't run (yet). */ NOT_BUILT(Messages._ResultTrend_NotBuilt()); - + private final Localizable description; ResultTrend(Localizable description) { this.description = description; } - + /** * Returns a short human-readable description of the result. */ @@ -91,35 +92,35 @@ public enum ResultTrend { public String getID() { return this.description.toString(Locale.ENGLISH).toUpperCase(Locale.ENGLISH); } - + /** * Returns the result trend of a build. - * + * * @param build the build * @return the result trend */ public static ResultTrend getResultTrend(AbstractBuild build) { - return getResultTrend((Run)build); + return getResultTrend((Run) build); } /** * Returns the result trend of a run. - * + * * @param run the run * @return the result trend - * + * * @since 1.441 */ public static ResultTrend getResultTrend(Run run) { - + Result result = run.getResult(); - + if (result == Result.ABORTED) { return ABORTED; } else if (result == Result.NOT_BUILT) { return NOT_BUILT; } - + if (result == Result.SUCCESS) { if (isFix(run)) { return FIXED; @@ -127,14 +128,14 @@ public enum ResultTrend { return SUCCESS; } } - + Run previousBuild = getPreviousNonAbortedBuild(run); if (result == Result.UNSTABLE) { if (previousBuild == null) { return UNSTABLE; } - - + + if (previousBuild.getResult() == Result.UNSTABLE) { return STILL_UNSTABLE; } else if (previousBuild.getResult() == Result.FAILURE) { @@ -149,10 +150,10 @@ public enum ResultTrend { return FAILURE; } } - + throw new IllegalArgumentException("Unknown result: '" + result + "' for build: " + run); } - + /** * Returns the previous 'not aborted' build (i.e. ignores ABORTED and NOT_BUILT builds) * or null. @@ -160,10 +161,10 @@ public enum ResultTrend { private static Run getPreviousNonAbortedBuild(Run build) { Run previousBuild = build.getPreviousBuild(); while (previousBuild != null) { - if (previousBuild.getResult() == null + if (previousBuild.getResult() == null || previousBuild.getResult() == Result.ABORTED || previousBuild.getResult() == Result.NOT_BUILT) { - + previousBuild = previousBuild.getPreviousBuild(); } else { return previousBuild; @@ -171,7 +172,7 @@ public enum ResultTrend { } return previousBuild; } - + /** * Returns true if this build represents a 'fix'. * I.e. it is the first successful build after previous @@ -182,7 +183,7 @@ public enum ResultTrend { if (build.getResult() != Result.SUCCESS) { return false; } - + Run previousBuild = getPreviousNonAbortedBuild(build); if (previousBuild != null) { return previousBuild.getResult().isWorseThan(Result.SUCCESS); diff --git a/core/src/main/java/hudson/model/RootAction.java b/core/src/main/java/hudson/model/RootAction.java index 54bb86699c698e9ff577c77424d3a3584253532b..9c431ee635ffcf09352c72837d6cae960c0a4e81 100644 --- a/core/src/main/java/hudson/model/RootAction.java +++ b/core/src/main/java/hudson/model/RootAction.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import hudson.Extension; diff --git a/core/src/main/java/hudson/model/Run.java b/core/src/main/java/hudson/model/Run.java index fa8500367c71ddbc767602dc7c01a0f949e6a552..85629405de80bc1f776fb9aba23048e4e00444d9 100644 --- a/core/src/main/java/hudson/model/Run.java +++ b/core/src/main/java/hudson/model/Run.java @@ -25,6 +25,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import static java.util.logging.Level.FINE; @@ -151,7 +152,7 @@ import org.springframework.security.core.Authentication; * @see RunListener */ @ExportedBean -public abstract class Run ,RunT extends Run> +public abstract class Run, RunT extends Run> extends Actionable implements ExtensionPoint, Comparable, AccessControlled, PersistenceRoot, DescriptorByNameOwner, OnMaster, StaplerProxy { /** @@ -334,7 +335,7 @@ public abstract class Run ,RunT extends Run,RunT extends Run getTransientActions() { List actions = new ArrayList<>(); - for (TransientBuildActionFactory factory: TransientBuildActionFactory.all()) { + for (TransientBuildActionFactory factory : TransientBuildActionFactory.all()) { for (Action created : factory.createFor(this)) { if (created == null) { LOGGER.log(WARNING, "null action added by {0}", factory); @@ -438,7 +439,7 @@ public abstract class Run ,RunT extends Run,RunT extends Run,RunT extends Run getBadgeActions() { List r = getActions(BuildBadgeAction.class); - if(isKeepLog()) { + if (isKeepLog()) { r = new ArrayList<>(r); r.add(new KeepLogBuildBadge()); } @@ -567,9 +568,9 @@ public abstract class Run ,RunT extends Run,RunT extends Run,RunT extends Run getCauses() { CauseAction a = getAction(CauseAction.class); - if (a==null) return Collections.emptyList(); + if (a == null) return Collections.emptyList(); return Collections.unmodifiableList(a.getCauses()); } @@ -622,7 +623,7 @@ public abstract class Run ,RunT extends Run,RunT extends Run,RunT extends Run,RunT extends Run') { inTag = false; @@ -756,7 +757,7 @@ public abstract class Run ,RunT extends Run,RunT extends Run,RunT extends Run,RunT extends Run,RunT extends Run,RunT extends Run,RunT extends Run,RunT extends Run,RunT extends Run,RunT extends Run fixUp = new ArrayList<>(); RunT r = _this(); // 'r' is the source of the pointer (so that we can add it to fix up if we find that the target of the pointer is inefficient.) RunT answer; while (true) { RunT n = r.previousBuildInProgress; - if (n==null) {// no field computed yet. - n=r.getPreviousBuild(); + if (n == null) { // no field computed yet. + n = r.getPreviousBuild(); fixUp.add(r); } - if (r==n || n==null) { + if (r == n || n == null) { // this indicates that we know there's no build in progress beyond this point answer = null; break; @@ -931,7 +932,7 @@ public abstract class Run ,RunT extends Run,RunT extends Run,RunT extends Run,RunT extends Run,RunT extends Run,RunT extends Run,RunT extends Run,RunT extends Run,RunT extends Run,RunT extends Run=upTo) break; + n += addArtifacts(sub, childPath + '/', childHref + '/', r, a, upTo - n); + if (n >= upTo) break; } else { // Don't store collapsed path in ArrayList (for correct data in external API) r.add(collapsed ? new SerializableArtifact(child, a.relativePath, a.href, length, a.treeNodeId) : a); - if (++n>=upTo) break; + if (++n >= upTo) break; } } return n; @@ -1253,6 +1256,7 @@ public abstract class Run ,RunT extends Run,RunT extends Run tree = new LinkedHashMap<>(); + private LinkedHashMap tree = new LinkedHashMap<>(); void updateFrom(SerializableArtifactList clone) { Map artifacts = new HashMap<>(); // need to share objects between tree and list, since computeDisplayName mutates displayPath @@ -1295,43 +1299,43 @@ public abstract class Run ,RunT extends Run getTree() { + public Map getTree() { return tree; } public void computeDisplayName() { - if(size()>LIST_CUTOFF) return; // we are not going to display file names, so no point in computing this + if (size() > LIST_CUTOFF) return; // we are not going to display file names, so no point in computing this int maxDepth = 0; int[] len = new int[size()]; String[][] tokens = new String[size()][]; - for( int i=0; i names = new HashMap<>(); + Map names = new HashMap<>(); for (int i = 0; i < tokens.length; i++) { String[] token = tokens[i]; - String displayName = combineLast(token,len[i]); + String displayName = combineLast(token, len[i]); Integer j = names.put(displayName, i); - if(j!=null) { + if (j != null) { collision = true; - if(j>=0) + if (j >= 0) len[j]++; len[i]++; - names.put(displayName,-1); // occupy this name but don't let len[i] incremented with additional collisions + names.put(displayName, -1); // occupy this name but don't let len[i] incremented with additional collisions } } - } while(collision && depth++,RunT extends Run0) buf.append('/'); + for (int i = Math.max(0, token.length - n); i < token.length; i++) { + if (buf.length() > 0) buf.append('/'); buf.append(token[i]); } return buf.toString(); @@ -1355,7 +1359,7 @@ public abstract class Run ,RunT extends Run,RunT extends Run,RunT extends Run,RunT extends Run,RunT extends Run,RunT extends Run,RunT extends Run,RunT extends Run,RunT extends Run,RunT extends Run.RunExecution exec = RunnerStack.INSTANCE.peek(); + Run.RunExecution exec = RunnerStack.INSTANCE.peek(); if (exec == null) { return; } @@ -1695,20 +1699,20 @@ public abstract class Run ,RunT extends Run.RunExecution exec = RunnerStack.INSTANCE.peek(); + while (true) { + Run.RunExecution exec = RunnerStack.INSTANCE.peek(); if (exec == null) { return; } Run b = exec.getBuild().getPreviousBuildInProgress(); - if(b==null) return; // no pending earlier build + if (b == null) return; // no pending earlier build Run.RunExecution runner = b.runner; - if(runner==null) { + if (runner == null) { // polled at the wrong moment. try again. Thread.sleep(0); continue; } - if(runner.checkpoints.waitForCheckPoint(id, listener, waiter)) + if (runner.checkpoints.waitForCheckPoint(id, listener, waiter)) return; // confirmed that the previous build reached the check point // the previous build finished without ever reaching the check point. try again. @@ -1775,7 +1779,7 @@ public abstract class Run ,RunT extends Run attributes = new HashMap<>(); + private final Map attributes = new HashMap<>(); /** * Performs the main build and returns the status code. @@ -1783,7 +1787,7 @@ public abstract class Run ,RunT extends Run,RunT extends Run,RunT extends Run getAttributes() { + public @NonNull Map getAttributes() { return attributes; } } @@ -1847,11 +1851,11 @@ public abstract class Run ,RunT extends Run,RunT extends Run,RunT extends Run,RunT extends Run,RunT extends Run,RunT extends Run,RunT extends Run,RunT extends Run,RunT extends Run,RunT extends Run,RunT extends Run new Replacer(this)); } + private static class Replacer { private final String id; + Replacer(Run r) { id = r.getExternalizableId(); } + private Object readResolve() { return fromExternalizableId(id); } @@ -2090,7 +2097,7 @@ public abstract class Run ,RunT extends Run,RunT extends Run,RunT extends Run,RunT extends Run run, @NonNull ResultTrend trend); + public abstract @CheckForNull Summary summarize(@NonNull Run run, @NonNull ResultTrend trend); } /** @@ -2212,29 +2219,29 @@ public abstract class Run ,RunT extends Run,RunT extends Run,RunT extends Run,RunT extends Run,RunT extends Run,RunT extends Run,RunT extends Run,RunT extends Run,RunT extends Run getEnvVars() { + public Map getEnvVars() { LOGGER.log(WARNING, "deprecated call to Run.getEnvVars\n\tat {0}", new Throwable().getStackTrace()[1]); try { return getEnvironment(new LogTaskListener(LOGGER, Level.INFO)); @@ -2418,14 +2425,14 @@ public abstract class Run ,RunT extends Run,RunT extends Run,RunT extends Run fromExternalizableId(String id) throws IllegalArgumentException, AccessDeniedException { + public @CheckForNull static Run fromExternalizableId(String id) throws IllegalArgumentException, AccessDeniedException { int hash = id.lastIndexOf('#'); if (hash <= 0) { throw new IllegalArgumentException("Invalid id"); @@ -2480,7 +2487,7 @@ public abstract class Run ,RunT extends Run job = j.getItemByFullName(jobName, Job.class); + Job job = j.getItemByFullName(jobName, Job.class); if (job == null) { return null; } @@ -2501,7 +2508,7 @@ public abstract class Run ,RunT extends Run,RunT extends Run,RunT extends Run,RunT extends Run { @Override public String getEntryTitle(Run entry) { - return entry.getFullDisplayName()+" ("+entry.getBuildStatusSummary().message+")"; + return entry.getFullDisplayName() + " (" + entry.getBuildStatusSummary().message + ")"; } @Override @@ -2597,7 +2607,7 @@ public abstract class Run ,RunT extends Run,RunT extends Run> extends AbstractLazyLoadRunMap implements Iterable { +public final class RunMap> extends AbstractLazyLoadRunMap implements Iterable { /** * Read-only view of this map. */ - private final SortedMap view = Collections.unmodifiableSortedMap(this); + private final SortedMap view = Collections.unmodifiableSortedMap(this); private Constructor cons; @@ -107,13 +108,13 @@ public final class RunMap> extends AbstractLazyLoadRunMap @Override public boolean hasNext() { - return next!=null; + return next != null; } @Override public R next() { last = next; - if (last!=null) + if (last != null) next = last.getPreviousBuild(); else throw new NoSuchElementException(); @@ -122,7 +123,7 @@ public final class RunMap> extends AbstractLazyLoadRunMap @Override public void remove() { - if (last==null) + if (last == null) throw new UnsupportedOperationException(); removeValue(last); } @@ -139,7 +140,7 @@ public final class RunMap> extends AbstractLazyLoadRunMap /** * Gets the read-only view of this map. */ - public SortedMap getView() { + public SortedMap getView() { return view; } @@ -167,7 +168,7 @@ public final class RunMap> extends AbstractLazyLoadRunMap /** * {@link Run} factory. */ - public interface Constructor> { + public interface Constructor> { R create(File dir) throws IOException; } @@ -226,7 +227,7 @@ public final class RunMap> extends AbstractLazyLoadRunMap @Override protected R retrieve(File d) throws IOException { - if(new File(d,"build.xml").exists()) { + if (new File(d, "build.xml").exists()) { // if the build result file isn't in the directory, ignore it. try { R b = cons.create(d); diff --git a/core/src/main/java/hudson/model/RunParameterDefinition.java b/core/src/main/java/hudson/model/RunParameterDefinition.java index b24e588f976e8ef16ebebc7c7b983eea519393e4..3ac138a8761c8bba82d8118ca58d4448e8c29988 100644 --- a/core/src/main/java/hudson/model/RunParameterDefinition.java +++ b/core/src/main/java/hudson/model/RunParameterDefinition.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Tom Huybrechts, Geoff Cummings - * + * * 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 @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import edu.umd.cs.findbugs.annotations.CheckForNull; @@ -60,7 +61,7 @@ public class RunParameterDefinition extends SimpleParameterDefinition { Stapler.CONVERT_UTILS.register(new EnumConverter(), RunParameterFilter.class); } } - + private final String projectName; private final String runId; private final RunParameterFilter filter; @@ -79,11 +80,11 @@ public class RunParameterDefinition extends SimpleParameterDefinition { /** * @deprecated as of 1.517 - */ + */ @Deprecated public RunParameterDefinition(@NonNull String name, String projectName, @CheckForNull String description) { - // delegate to updated constructor with additional RunParameterFilter parameter defaulted to ALL. - this(name, projectName, description, RunParameterFilter.ALL); + // delegate to updated constructor with additional RunParameterFilter parameter defaulted to ALL. + this(name, projectName, description, RunParameterFilter.ALL); } private RunParameterDefinition(@NonNull String name, String projectName, String runId, @CheckForNull String description, @CheckForNull RunParameterFilter filter) { @@ -118,7 +119,7 @@ public class RunParameterDefinition extends SimpleParameterDefinition { */ @Exported public RunParameterFilter getFilter() { - // if filter is null, default to RunParameterFilter.ALL + // if filter is null, default to RunParameterFilter.ALL return null == filter ? RunParameterFilter.ALL : filter; } @@ -133,14 +134,14 @@ public class RunParameterDefinition extends SimpleParameterDefinition { return getProject().getBuilds().overThresholdOnly(Result.ABORTED).completedOnly(); case SUCCESSFUL: return getProject().getBuilds().overThresholdOnly(Result.UNSTABLE).completedOnly(); - case STABLE : + case STABLE: return getProject().getBuilds().overThresholdOnly(Result.SUCCESS).completedOnly(); default: return getProject().getBuilds(); } } - @Extension @Symbol({"run","runParam"}) + @Extension @Symbol({"run", "runParam"}) public static class DescriptorImpl extends ParameterDescriptor { @Override public String getDisplayName() { @@ -156,7 +157,7 @@ public class RunParameterDefinition extends SimpleParameterDefinition { public ParameterDefinition newInstance(StaplerRequest req, JSONObject formData) throws FormException { return req.bindJSON(RunParameterDefinition.class, formData); } - + public AutoCompletionCandidates doAutoCompleteProjectName(@QueryParameter String value) { return AutoCompletionCandidates.ofJobNames(Job.class, value, null, Jenkins.get()); } @@ -169,7 +170,7 @@ public class RunParameterDefinition extends SimpleParameterDefinition { return createValue(runId); } - Run lastBuild; + Run lastBuild; Job project = getProject(); if (project == null) { @@ -184,7 +185,7 @@ public class RunParameterDefinition extends SimpleParameterDefinition { case SUCCESSFUL: lastBuild = project.getLastSuccessfulBuild(); break; - case STABLE : + case STABLE: lastBuild = project.getLastStableBuild(); break; default: @@ -193,9 +194,9 @@ public class RunParameterDefinition extends SimpleParameterDefinition { } if (lastBuild != null) { - return createValue(lastBuild.getExternalizableId()); + return createValue(lastBuild.getExternalizableId()); } else { - return null; + return null; } } diff --git a/core/src/main/java/hudson/model/RunParameterValue.java b/core/src/main/java/hudson/model/RunParameterValue.java index 1edc798366eef89326c363446753163499208ff6..23e94f66746c386ad6cf7eb76092999f16a6a4b9 100644 --- a/core/src/main/java/hudson/model/RunParameterValue.java +++ b/core/src/main/java/hudson/model/RunParameterValue.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Tom Huybrechts, Geoff Cummings - * + * * 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 @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import edu.umd.cs.findbugs.annotations.CheckForNull; @@ -63,7 +64,7 @@ public class RunParameterValue extends ParameterValue { public String getRunId() { return runId; } - + private String[] split() { if (runId == null) { return null; @@ -78,13 +79,13 @@ public class RunParameterValue extends ParameterValue { @Exported public String getJobName() { String[] r = split(); - return r == null ? null : r[0]; + return r == null ? null : r[0]; } - + @Exported public String getNumber() { String[] r = split(); - return r == null ? null : r[1]; + return r == null ? null : r[1]; } @Override @@ -96,31 +97,31 @@ public class RunParameterValue extends ParameterValue { * Exposes the name/value as an environment variable. */ @Override - public void buildEnvironment(Run build, EnvVars env) { + public void buildEnvironment(Run build, EnvVars env) { Run run = getRun(); - + String value = null == run ? "UNKNOWN" : Jenkins.get().getRootUrl() + run.getUrl(); env.put(name, value); env.put(name + ".jobName", getJobName()); // undocumented, left for backward compatibility env.put(name + "_JOBNAME", getJobName()); // prefer this version - env.put(name + ".number" , getNumber ()); // same as above - env.put(name + "_NUMBER" , getNumber ()); - + env.put(name + ".number", getNumber()); // same as above + env.put(name + "_NUMBER", getNumber()); + // if run is null, default to the standard '#1' display name format env.put(name + "_NAME", null == run ? "#" + getNumber() : run.getDisplayName()); // since 1.504 String buildResult = null == run || null == run.getResult() ? "UNKNOWN" : run.getResult().toString(); env.put(name + "_RESULT", buildResult); // since 1.517 - env.put(name.toUpperCase(Locale.ENGLISH),value); // backward compatibility pre 1.345 + env.put(name.toUpperCase(Locale.ENGLISH), value); // backward compatibility pre 1.345 } - + @Override public String toString() { - return "(RunParameterValue) " + getName() + "='" + getRunId() + "'"; + return "(RunParameterValue) " + getName() + "='" + getRunId() + "'"; } @Override public String getShortDescription() { diff --git a/core/src/main/java/hudson/model/RunnerStack.java b/core/src/main/java/hudson/model/RunnerStack.java index ddca4e94016e89e861fcce6ec56e479d81946810..6f4c57b242bfd673dc3a7bf7e3595b2d693fe87e 100644 --- a/core/src/main/java/hudson/model/RunnerStack.java +++ b/core/src/main/java/hudson/model/RunnerStack.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import edu.umd.cs.findbugs.annotations.CheckForNull; @@ -37,7 +38,7 @@ import java.util.WeakHashMap; * @since 1.319 */ final class RunnerStack { - private final Map> stack = new WeakHashMap<>(); + private final Map> stack = new WeakHashMap<>(); synchronized void push(RunExecution r) { Executor e = Executor.currentExecutor(); @@ -49,7 +50,7 @@ final class RunnerStack { Executor e = Executor.currentExecutor(); Stack s = stack.get(e); s.pop(); - if(s.isEmpty()) stack.remove(e); + if (s.isEmpty()) stack.remove(e); } /** diff --git a/core/src/main/java/hudson/model/SCMedItem.java b/core/src/main/java/hudson/model/SCMedItem.java index 142e4f51535d2b09580ae7ea2e9b27cb1bf8ad71..2cfd0dde7079a6c8b2d70ab267a461bf101ae408 100644 --- a/core/src/main/java/hudson/model/SCMedItem.java +++ b/core/src/main/java/hudson/model/SCMedItem.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import hudson.scm.PollingResult; @@ -48,7 +49,7 @@ public interface SCMedItem extends BuildableItem { * This method must be always implemented as {@code (AbstractProject)this}, but * defining this method emphasizes the fact that this cast must be doable. */ - AbstractProject asProject(); + AbstractProject asProject(); /** * Checks if there's any update in SCM, and returns true if any is found. @@ -57,7 +58,7 @@ public interface SCMedItem extends BuildableItem { * Use {@link #poll(TaskListener)} instead. */ @Deprecated - boolean pollSCMChanges( TaskListener listener ); + boolean pollSCMChanges(TaskListener listener); /** * Checks if there's any update in SCM, and returns true if any is found. diff --git a/core/src/main/java/hudson/model/Saveable.java b/core/src/main/java/hudson/model/Saveable.java index a2e8b8f9a434413a7f09cbd5acce2eb148415489..c98900d99d6449f807eb0ecd847934c3f41a42a6 100644 --- a/core/src/main/java/hudson/model/Saveable.java +++ b/core/src/main/java/hudson/model/Saveable.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import hudson.BulkChange; diff --git a/core/src/main/java/hudson/model/Slave.java b/core/src/main/java/hudson/model/Slave.java index 90b36b2c2b640ae804197f6a5225f2ca1c23f300..0ae31abe1db5e601097f7a53dc134e8e3cb7f565 100644 --- a/core/src/main/java/hudson/model/Slave.java +++ b/core/src/main/java/hudson/model/Slave.java @@ -22,6 +22,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import edu.umd.cs.findbugs.annotations.CheckForNull; @@ -93,7 +94,7 @@ import org.kohsuke.stapler.StaplerResponse; * *

    * TODO: move out more stuff to {@link DumbSlave}. - * + * * On February, 2016 a general renaming was done internally: the "slave" term was replaced by * "Agent". This change was applied in: UI labels/HTML pages, javadocs and log messages. * Java classes, fields, methods, etc were not renamed to avoid compatibility issues. @@ -102,9 +103,9 @@ import org.kohsuke.stapler.StaplerResponse; * @author Kohsuke Kawaguchi */ public abstract class Slave extends Node implements Serializable { - + private static final Logger LOGGER = Logger.getLogger(Slave.class.getName()); - + /** * Name of this agent node. */ @@ -148,9 +149,9 @@ public abstract class Slave extends Node implements Serializable { /** * Whitespace-separated labels. */ - private String label=""; + private String label = ""; - private /*almost final*/ DescribableList,NodePropertyDescriptor> nodeProperties = + private /*almost final*/ DescribableList, NodePropertyDescriptor> nodeProperties = new DescribableList<>(this); /** @@ -166,7 +167,7 @@ public abstract class Slave extends Node implements Serializable { @Deprecated protected Slave(String name, String nodeDescription, String remoteFS, String numExecutors, Mode mode, String labelString, ComputerLauncher launcher, RetentionStrategy retentionStrategy, List> nodeProperties) throws FormException, IOException { - this(name,nodeDescription,remoteFS,Util.tryParseNumber(numExecutors, 1).intValue(),mode,labelString,launcher,retentionStrategy, nodeProperties); + this(name, nodeDescription, remoteFS, Util.tryParseNumber(numExecutors, 1).intValue(), mode, labelString, launcher, retentionStrategy, nodeProperties); } /** @@ -175,7 +176,7 @@ public abstract class Slave extends Node implements Serializable { @Deprecated protected Slave(String name, String nodeDescription, String remoteFS, int numExecutors, Mode mode, String labelString, ComputerLauncher launcher, RetentionStrategy retentionStrategy) throws FormException, IOException { - this(name, nodeDescription, remoteFS, numExecutors, mode, labelString, launcher, retentionStrategy, new ArrayList()); + this(name, nodeDescription, remoteFS, numExecutors, mode, labelString, launcher, retentionStrategy, new ArrayList()); } protected Slave(@NonNull String name, String remoteFS, ComputerLauncher launcher) throws FormException, IOException { @@ -206,7 +207,7 @@ public abstract class Slave extends Node implements Serializable { if (name.equals("")) throw new FormException(Messages.Slave_InvalidConfig_NoName(), null); - if (this.numExecutors<=0) + if (this.numExecutors <= 0) throw new FormException(Messages.Slave_InvalidConfig_Executors(name), null); } @@ -305,7 +306,7 @@ public abstract class Slave extends Node implements Serializable { @Override public DescribableList, NodePropertyDescriptor> getNodeProperties() { assert nodeProperties != null; - return nodeProperties; + return nodeProperties; } @DataBoundSetter @@ -336,7 +337,7 @@ public abstract class Slave extends Node implements Serializable { } @Override - public Callable getClockDifferenceCallable() { + public Callable getClockDifferenceCallable() { return new GetClockDifference1(); } @@ -355,7 +356,7 @@ public abstract class Slave extends Node implements Serializable { } FilePath r = getWorkspaceRoot(); - if(r==null) return null; // offline + if (r == null) return null; // offline return r.child(item.getFullName()); } @@ -378,7 +379,7 @@ public abstract class Slave extends Node implements Serializable { */ public @CheckForNull FilePath getWorkspaceRoot() { FilePath r = getRootPath(); - if(r==null) return null; + if (r == null) return null; return r.child(WORKSPACE_ROOT); } @@ -392,7 +393,7 @@ public abstract class Slave extends Node implements Serializable { this.fileName = fileName; } - public void doIndex( StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { + public void doIndex(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { URLConnection con = connect(); // since we end up redirecting users to jnlpJars/foo.jar/, set the content disposition // so that browsers can download them in the right file name. @@ -405,7 +406,7 @@ public abstract class Slave extends Node implements Serializable { @Override public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException, ServletException { - doIndex(req,rsp); + doIndex(req, rsp); } private URLConnection connect() throws IOException { @@ -415,7 +416,7 @@ public abstract class Slave extends Node implements Serializable { public URL getURL() throws IOException { String name = fileName; - + // Prevent the access to war contents & prevent the folder escaping (SECURITY-195) if (!ALLOWED_JNLPJARS_FILES.contains(name)) { throw new MalformedURLException("The specified file path " + fileName + " is not allowed due to security reasons"); @@ -438,9 +439,9 @@ public abstract class Slave extends Node implements Serializable { } } } - + URL res = Jenkins.get().servletContext.getResource("/WEB-INF/" + name); - if(res==null) { + if (res == null) { throw new FileNotFoundException(name); // giving up } else { LOGGER.log(Level.FINE, "found {0}", res); @@ -492,9 +493,9 @@ public abstract class Slave extends Node implements Serializable { listener.error("Issue with creating launcher for agent " + name + ". Computer has been disconnected"); return new Launcher.DummyLauncher(listener); } else { - // TODO: ideally all the logic below should be inside the SlaveComputer class with proper locking to prevent race conditions, + // TODO: ideally all the logic below should be inside the SlaveComputer class with proper locking to prevent race conditions, // but so far there is no locks for setNode() hence it requires serious refactoring - + // Ensure that the Computer instance still points to this node // Otherwise we may end up running the command on a wrong (reconnected) Node instance. Slave node = c.getNode(); @@ -505,10 +506,10 @@ public abstract class Slave extends Node implements Serializable { } return new Launcher.DummyLauncher(listener); } - + // RemoteLauncher requires an active Channel instance to operate correctly final Channel channel = c.getChannel(); - if (channel == null) { + if (channel == null) { reportLauncherCreateError("The agent has not been fully initialized yet", "No remoting channel to the agent OR it has not been fully initialized yet", listener); return new Launcher.DummyLauncher(listener); @@ -523,22 +524,22 @@ public abstract class Slave extends Node implements Serializable { // isUnix is always set when the channel is not null, so it should never happen reportLauncherCreateError("The agent has not been fully initialized yet", "Cannot determine if the agent is a Unix one, the System status request has not completed yet. " + - "It is an invalid channel state, please report a bug to Jenkins if you see it.", + "It is an invalid channel state, please report a bug to Jenkins if you see it.", listener); return new Launcher.DummyLauncher(listener); } - + return new RemoteLauncher(listener, channel, isUnix).decorateFor(this); } } - + private void reportLauncherCreateError(@NonNull String humanReadableMsg, @CheckForNull String exceptionDetails, @NonNull TaskListener listener) { String message = "Issue with creating launcher for agent " + name + ". " + humanReadableMsg; listener.error(message); if (LOGGER.isLoggable(Level.WARNING)) { // Send stacktrace to the log as well in order to diagnose the root cause of issues like JENKINS-38527 LOGGER.log(Level.WARNING, message - + "Probably there is a race condition with Agent reconnection or disconnection, check other log entries", + + "Probably there is a race condition with Agent reconnection or disconnection, check other log entries", new IllegalStateException(exceptionDetails != null ? exceptionDetails : humanReadableMsg)); } } @@ -552,7 +553,7 @@ public abstract class Slave extends Node implements Serializable { */ @CheckForNull public SlaveComputer getComputer() { - return (SlaveComputer)toComputer(); + return (SlaveComputer) toComputer(); } @Override @@ -574,7 +575,7 @@ public abstract class Slave extends Node implements Serializable { * Invoked by XStream when this object is read into memory. */ protected Object readResolve() { - if(nodeProperties==null) + if (nodeProperties == null) nodeProperties = new DescribableList<>(this); return this; } @@ -584,7 +585,7 @@ public abstract class Slave extends Node implements Serializable { Descriptor d = Jenkins.get().getDescriptorOrDie(getClass()); if (d instanceof SlaveDescriptor) return (SlaveDescriptor) d; - throw new IllegalStateException(d.getClass()+" needs to extend from SlaveDescriptor"); + throw new IllegalStateException(d.getClass() + " needs to extend from SlaveDescriptor"); } public abstract static class SlaveDescriptor extends NodeDescriptor { @@ -596,10 +597,10 @@ public abstract class Slave extends Node implements Serializable { * Performs syntactical check on the remote FS for agents. */ public FormValidation doCheckRemoteFS(@QueryParameter String value) throws IOException, ServletException { - if(Util.fixEmptyAndTrim(value)==null) + if (Util.fixEmptyAndTrim(value) == null) return FormValidation.error(Messages.Slave_Remote_Director_Mandatory()); - if(value.startsWith("\\\\") || value.startsWith("/net/")) + if (value.startsWith("\\\\") || value.startsWith("/net/")) return FormValidation.warning(Messages.Slave_Network_Mounted_File_System_Warning()); if (Util.isRelativePath(value)) { @@ -691,7 +692,7 @@ public abstract class Slave extends Node implements Serializable { *

  • When it's read on this side as a return value, it morphs itself into {@link ClockDifference}. * */ - private static final class GetClockDifference1 extends MasterToSlaveCallable { + private static final class GetClockDifference1 extends MasterToSlaveCallable { @Override public ClockDifference call() { // this method must be being invoked locally, which means the clock is in sync @@ -705,7 +706,7 @@ public abstract class Slave extends Node implements Serializable { private static final long serialVersionUID = 1L; } - private static final class GetClockDifference2 extends MasterToSlaveCallable { + private static final class GetClockDifference2 extends MasterToSlaveCallable { /** * Capture the time on the controller when this object is sent to remote, which is when * {@link GetClockDifference1#writeReplace()} is run. @@ -730,14 +731,14 @@ public abstract class Slave extends Node implements Serializable { private Object readResolve() { long endTime = System.currentTimeMillis(); - return new ClockDifference((startTime + endTime)/2-remoteTime); + return new ClockDifference((startTime + endTime) / 2 - remoteTime); } } /** * Determines the workspace root file name for those who really really need the shortest possible path name. */ - private static final String WORKSPACE_ROOT = SystemProperties.getString(Slave.class.getName()+".workspaceRoot","workspace"); + private static final String WORKSPACE_ROOT = SystemProperties.getString(Slave.class.getName() + ".workspaceRoot", "workspace"); /** * Provides a collection of file names, which are accessible via /jnlpJars link. diff --git a/core/src/main/java/hudson/model/StatusIcon.java b/core/src/main/java/hudson/model/StatusIcon.java index 458955c2bec80861d9d7396abcdcf7eccc4b341e..b4c4bc7496284f26248e72158623bf20dddf2c90 100644 --- a/core/src/main/java/hudson/model/StatusIcon.java +++ b/core/src/main/java/hudson/model/StatusIcon.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; /** diff --git a/core/src/main/java/hudson/model/StreamBuildListener.java b/core/src/main/java/hudson/model/StreamBuildListener.java index 2ad5192653e8a5279e1b0e972b387c01140b8ee0..2b41ca48b0b8dba3ca903b3d61277035a1343d15 100644 --- a/core/src/main/java/hudson/model/StreamBuildListener.java +++ b/core/src/main/java/hudson/model/StreamBuildListener.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import hudson.util.StreamTaskListener; @@ -34,7 +35,7 @@ import java.nio.charset.Charset; * {@link BuildListener} that writes to an {@link OutputStream}. * * This class is remotable. - * + * * @author Kohsuke Kawaguchi */ public class StreamBuildListener extends StreamTaskListener implements BuildListener { @@ -61,7 +62,7 @@ public class StreamBuildListener extends StreamTaskListener implements BuildList } public StreamBuildListener(PrintStream w, Charset charset) { - super(w,charset); + super(w, charset); } private static final long serialVersionUID = 1L; diff --git a/core/src/main/java/hudson/model/StringParameterDefinition.java b/core/src/main/java/hudson/model/StringParameterDefinition.java index b65504cedddb6bc6a739c79a6deabb23bb133af2..8a5dfa9f1b04801a61d55b91582201203e485342 100644 --- a/core/src/main/java/hudson/model/StringParameterDefinition.java +++ b/core/src/main/java/hudson/model/StringParameterDefinition.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Luca Domenico Milanesio, Seiji Sogabe, Tom Huybrechts - * + * * 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 @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import edu.umd.cs.findbugs.annotations.CheckForNull; @@ -65,7 +66,7 @@ public class StringParameterDefinition extends SimpleParameterDefinition { setDefaultValue(defaultValue); setDescription(description); } - + public StringParameterDefinition(@NonNull String name, @CheckForNull String defaultValue) { this(name); setDefaultValue(defaultValue); @@ -87,7 +88,7 @@ public class StringParameterDefinition extends SimpleParameterDefinition { } /** - * + * * @return original or trimmed defaultValue (depending on trim) */ @Restricted(DoNotUse.class) // Jelly @@ -104,7 +105,7 @@ public class StringParameterDefinition extends SimpleParameterDefinition { } /** - * + * * @return trim - {@code true}, if trim options has been selected, else return {@code false}. * Trimming will happen when creating {@link StringParameterValue}s, * the value in the config will not be changed. @@ -121,7 +122,7 @@ public class StringParameterDefinition extends SimpleParameterDefinition { public void setTrim(boolean trim) { this.trim = trim; } - + @Override public StringParameterValue getDefaultParameterValue() { StringParameterValue value = new StringParameterValue(getName(), defaultValue, getDescription()); @@ -131,7 +132,7 @@ public class StringParameterDefinition extends SimpleParameterDefinition { return value; } - @Extension @Symbol({"string","stringParam"}) + @Extension @Symbol({"string", "stringParam"}) public static class DescriptorImpl extends ParameterDescriptor { @Override @NonNull diff --git a/core/src/main/java/hudson/model/StringParameterValue.java b/core/src/main/java/hudson/model/StringParameterValue.java index ad7e528ac07fb87eff376386f9ed08c4b1a0d26b..f5e0583ed56299db4abbf372a39e079a9a5c408c 100644 --- a/core/src/main/java/hudson/model/StringParameterValue.java +++ b/core/src/main/java/hudson/model/StringParameterValue.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Luca Domenico Milanesio, Tom Huybrechts - * + * * 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 @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import hudson.EnvVars; @@ -37,7 +38,7 @@ import org.kohsuke.stapler.export.Exported; * {@link ParameterValue} created from {@link StringParameterDefinition}. */ public class StringParameterValue extends ParameterValue { - @Exported(visibility=4) + @Exported(visibility = 4) @Restricted(NoExternalUse.class) public String value; @@ -55,9 +56,9 @@ public class StringParameterValue extends ParameterValue { * Exposes the name/value as an environment variable. */ @Override - public void buildEnvironment(Run build, EnvVars env) { - env.put(name,value); - env.put(name.toUpperCase(Locale.ENGLISH),value); // backward compatibility pre 1.345 + public void buildEnvironment(Run build, EnvVars env) { + env.put(name, value); + env.put(name.toUpperCase(Locale.ENGLISH), value); // backward compatibility pre 1.345 } @Override @@ -69,43 +70,43 @@ public class StringParameterValue extends ParameterValue { public String getValue() { return value; } - + /** * Trimming for value * @since 2.90 */ public void doTrim() { if (value != null) { - value = value.trim(); - } + value = value.trim(); + } } @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + (value == null ? 0 : value.hashCode()); - return result; - } + public int hashCode() { + final int prime = 31; + int result = super.hashCode(); + result = prime * result + (value == null ? 0 : value.hashCode()); + return result; + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - StringParameterValue other = (StringParameterValue) obj; - if (!Objects.equals(value, other.value)) { - return false; - } - return true; - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (!super.equals(obj)) + return false; + if (getClass() != obj.getClass()) + return false; + StringParameterValue other = (StringParameterValue) obj; + if (!Objects.equals(value, other.value)) { + return false; + } + return true; + } @Override public String toString() { - return "(StringParameterValue) " + getName() + "='" + value + "'"; + return "(StringParameterValue) " + getName() + "='" + value + "'"; } @Override public String getShortDescription() { diff --git a/core/src/main/java/hudson/model/TaskAction.java b/core/src/main/java/hudson/model/TaskAction.java index 575f35efab5c4689008fb99e46838fbe7533b546..60ca66ac053680de66a7bad69dcfe1622df72919 100644 --- a/core/src/main/java/hudson/model/TaskAction.java +++ b/core/src/main/java/hudson/model/TaskAction.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Jorg Heymans - * + * * 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 @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import hudson.console.AnnotatedLargeText; @@ -96,7 +97,7 @@ public abstract class TaskAction extends AbstractModelObject implements Action { */ public AnnotatedLargeText obtainLog() { WeakReference l = log; - if(l==null) return null; + if (l == null) return null; return l.get(); } @@ -112,10 +113,10 @@ public abstract class TaskAction extends AbstractModelObject implements Action { /** * Handles incremental log output. */ - public void doProgressiveLog( StaplerRequest req, StaplerResponse rsp) throws IOException { + public void doProgressiveLog(StaplerRequest req, StaplerResponse rsp) throws IOException { AnnotatedLargeText text = obtainLog(); - if(text!=null) { - text.doProgressText(req,rsp); + if (text != null) { + text.doProgressText(req, rsp); return; } rsp.setStatus(HttpServletResponse.SC_OK); @@ -124,10 +125,10 @@ public abstract class TaskAction extends AbstractModelObject implements Action { /** * Handles incremental log output. */ - public void doProgressiveHtml( StaplerRequest req, StaplerResponse rsp) throws IOException { + public void doProgressiveHtml(StaplerRequest req, StaplerResponse rsp) throws IOException { AnnotatedLargeText text = obtainLog(); - if(text!=null) { - text.doProgressiveHtml(req,rsp); + if (text != null) { + text.doProgressiveHtml(req, rsp); return; } rsp.setStatus(HttpServletResponse.SC_OK); @@ -140,7 +141,7 @@ public abstract class TaskAction extends AbstractModelObject implements Action { public synchronized void doClearError(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { getACL().checkPermission(getPermission()); - if(workerThread!=null && !workerThread.isRunning()) + if (workerThread != null && !workerThread.isRunning()) workerThread = null; rsp.sendRedirect("."); } diff --git a/core/src/main/java/hudson/model/TaskListener.java b/core/src/main/java/hudson/model/TaskListener.java index a466613d027f7afc5120da6008c1b361bedd912a..17269432f9553988d328d09d88251ec1d98c8f31 100644 --- a/core/src/main/java/hudson/model/TaskListener.java +++ b/core/src/main/java/hudson/model/TaskListener.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import edu.umd.cs.findbugs.annotations.NonNull; @@ -129,7 +130,7 @@ public interface TaskListener extends SerializableOnlyOverRemoting { */ @NonNull default PrintWriter error(String format, Object... args) { - return error(String.format(format,args)); + return error(String.format(format, args)); } /** diff --git a/core/src/main/java/hudson/model/TaskThread.java b/core/src/main/java/hudson/model/TaskThread.java index 60456f333fab107cbc87b1ddffe02092e7ca0b8f..2991da6211b0615f610be124d9ce448a4e706849 100644 --- a/core/src/main/java/hudson/model/TaskThread.java +++ b/core/src/main/java/hudson/model/TaskThread.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Red Hat, Inc. - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import hudson.Functions; @@ -40,7 +41,7 @@ import org.kohsuke.stapler.framework.io.LargeText; *

    * Designed to be used inside {@link TaskAction}. * - * + * * * @author Kohsuke Kawaguchi * @since 1.191 @@ -75,7 +76,7 @@ public abstract class TaskThread extends Thread { */ protected TaskThread(TaskAction owner, ListenerAndText output) { //FIXME this failed to compile super(owner.getBuild().toString()+' '+owner.getDisplayName()); - //Please implement more general way how to get information about action owner, + //Please implement more general way how to get information about action owner, //if you want it in the thread's name. super(owner.getDisplayName()); this.owner = owner; @@ -127,14 +128,14 @@ public abstract class TaskThread extends Thread { try { perform(listener); listener.getLogger().println("Completed"); - owner.workerThread = null; + owner.workerThread = null; } catch (InterruptedException e) { listener.getLogger().println("Aborted"); } catch (Exception e) { Functions.printStackTrace(e, listener.getLogger()); } finally { listener = null; - isRunning =false; + isRunning = false; } log.markAsComplete(); } @@ -175,7 +176,7 @@ public abstract class TaskThread extends Thread { */ @Deprecated public static ListenerAndText forFile(File f) throws IOException { - return forFile(f,null); + return forFile(f, null); } /** @@ -192,7 +193,7 @@ public abstract class TaskThread extends Thread { } /** - * Creates one that's backed by a file. + * Creates one that's backed by a file. */ public static ListenerAndText forFile(File f, TaskAction context) throws IOException { return new ListenerAndText( diff --git a/core/src/main/java/hudson/model/TextParameterDefinition.java b/core/src/main/java/hudson/model/TextParameterDefinition.java index da13fd7f7e4125c5ba556a26f8af9256184cbd63..4db836a7b7e51b15a35ff87f35c9467dfe737fb6 100644 --- a/core/src/main/java/hudson/model/TextParameterDefinition.java +++ b/core/src/main/java/hudson/model/TextParameterDefinition.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Luca Domenico Milanesio, Seiji Sogabe, Tom Huybrechts - * + * * 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 @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import edu.umd.cs.findbugs.annotations.CheckForNull; @@ -52,7 +53,7 @@ public class TextParameterDefinition extends StringParameterDefinition { setDescription(description); } - @Extension @Symbol({"text","textParam"}) + @Extension @Symbol({"text", "textParam"}) public static class DescriptorImpl extends ParameterDescriptor { @Override public String getDisplayName() { diff --git a/core/src/main/java/hudson/model/TextParameterValue.java b/core/src/main/java/hudson/model/TextParameterValue.java index 1e2227e303c0ca7cc21d3dfc3a9dd60420cbeaf0..2830e9128eadd3dd093928887bbb31444ae86fed 100644 --- a/core/src/main/java/hudson/model/TextParameterValue.java +++ b/core/src/main/java/hudson/model/TextParameterValue.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import org.kohsuke.stapler.DataBoundConstructor; diff --git a/core/src/main/java/hudson/model/TimeSeries.java b/core/src/main/java/hudson/model/TimeSeries.java index ddc1a644905b6e22eefcfdf7b9c4c5d0da900c6c..bcf524b42812673465e81502eef131e52a395b44 100644 --- a/core/src/main/java/hudson/model/TimeSeries.java +++ b/core/src/main/java/hudson/model/TimeSeries.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import hudson.CopyOnWrite; @@ -70,10 +71,10 @@ public final class TimeSeries implements Serializable { * the raw data stream. */ public void update(float newData) { - float data = history[0]*decay + newData*(1-decay); + float data = history[0] * decay + newData * (1 - decay); - float[] r = new float[Math.min(history.length+1,historySize)]; - System.arraycopy(history,0,r,1,Math.min(history.length,r.length-1)); + float[] r = new float[Math.min(history.length + 1, historySize)]; + System.arraycopy(history, 0, r, 1, Math.min(history.length, r.length - 1)); r[0] = data; history = r; } diff --git a/core/src/main/java/hudson/model/TopLevelItem.java b/core/src/main/java/hudson/model/TopLevelItem.java index 7af3a732b3f0d62ba5b20dd49fcba67478055d52..66f3bc7d4a2e84ee7a01fa9c3ae7a1b28c14569b 100644 --- a/core/src/main/java/hudson/model/TopLevelItem.java +++ b/core/src/main/java/hudson/model/TopLevelItem.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import hudson.Extension; diff --git a/core/src/main/java/hudson/model/TopLevelItemDescriptor.java b/core/src/main/java/hudson/model/TopLevelItemDescriptor.java index 202e9b79014f32f20abe997622cb476b8ac7f1e8..00a2633df63095f46352dc5c45d828ae20fedf2e 100644 --- a/core/src/main/java/hudson/model/TopLevelItemDescriptor.java +++ b/core/src/main/java/hudson/model/TopLevelItemDescriptor.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import edu.umd.cs.findbugs.annotations.CheckForNull; diff --git a/core/src/main/java/hudson/model/TransientBuildActionFactory.java b/core/src/main/java/hudson/model/TransientBuildActionFactory.java index dfac20cb07808ac000edb1a8807f616c3c77b59b..c4084b83b4bd26a7259580b3d897ecec7c129664 100644 --- a/core/src/main/java/hudson/model/TransientBuildActionFactory.java +++ b/core/src/main/java/hudson/model/TransientBuildActionFactory.java @@ -27,7 +27,7 @@ public abstract class TransientBuildActionFactory implements ExtensionPoint { */ public Collection createFor(Run target) { if (target instanceof AbstractBuild) - return createFor((AbstractBuild)target); + return createFor((AbstractBuild) target); else return Collections.emptyList(); } diff --git a/core/src/main/java/hudson/model/TransientComputerActionFactory.java b/core/src/main/java/hudson/model/TransientComputerActionFactory.java index d95ac4a680e11c3e135e5bb9c8045680b1954a0e..5e7b16ee66df1b5142fce430baff16dee2b7a2cc 100644 --- a/core/src/main/java/hudson/model/TransientComputerActionFactory.java +++ b/core/src/main/java/hudson/model/TransientComputerActionFactory.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import hudson.ExtensionList; @@ -62,13 +63,13 @@ public abstract class TransientComputerActionFactory implements ExtensionPoint { /** * Creates {@link Action}s for a node, using all registered {@link TransientComputerActionFactory}s. */ - public static List createAllFor(Computer target) { - List result = new ArrayList<>(); - for (TransientComputerActionFactory f: all()) { - result.addAll(f.createFor(target)); - } - return result; - } + public static List createAllFor(Computer target) { + List result = new ArrayList<>(); + for (TransientComputerActionFactory f : all()) { + result.addAll(f.createFor(target)); + } + return result; + } } diff --git a/core/src/main/java/hudson/model/TransientProjectActionFactory.java b/core/src/main/java/hudson/model/TransientProjectActionFactory.java index 55f28f74b5e69aed5ad574106990de68211a68bf..0d8979437646d92c7e4841d7a30c945260ffb50e 100644 --- a/core/src/main/java/hudson/model/TransientProjectActionFactory.java +++ b/core/src/main/java/hudson/model/TransientProjectActionFactory.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import hudson.Extension; diff --git a/core/src/main/java/hudson/model/TransientUserActionFactory.java b/core/src/main/java/hudson/model/TransientUserActionFactory.java index ecf3ff26402f5cee69b1baaac12e13fc40c2141c..273a6903efb29310eebb72caefc257583e4d0ddf 100644 --- a/core/src/main/java/hudson/model/TransientUserActionFactory.java +++ b/core/src/main/java/hudson/model/TransientUserActionFactory.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import hudson.Extension; diff --git a/core/src/main/java/hudson/model/TransientViewActionFactory.java b/core/src/main/java/hudson/model/TransientViewActionFactory.java index 498c33c39d3559997abd20c7d1bbee25adaa97f2..c1af0fe387d89f5b829c09ad301298adb4f17e2d 100644 --- a/core/src/main/java/hudson/model/TransientViewActionFactory.java +++ b/core/src/main/java/hudson/model/TransientViewActionFactory.java @@ -12,27 +12,27 @@ import java.util.List; */ public abstract class TransientViewActionFactory implements ExtensionPoint { - /** - * returns a list of (transient) actions never null, may be empty - */ - public abstract List createFor(View v); - + /** + * returns a list of (transient) actions never null, may be empty + */ + public abstract List createFor(View v); + /** * Returns all the registered {@link TransientViewActionFactory}s. */ - public static ExtensionList all() { - return ExtensionList.lookup(TransientViewActionFactory.class); - } - + public static ExtensionList all() { + return ExtensionList.lookup(TransientViewActionFactory.class); + } + /** * Creates {@link Action}s for a view, using all registered {@link TransientViewActionFactory}s. */ - public static List createAllFor(View v) { - List result = new ArrayList<>(); - for (TransientViewActionFactory f: all()) { - result.addAll(f.createFor(v)); - } - return result; - } + public static List createAllFor(View v) { + List result = new ArrayList<>(); + for (TransientViewActionFactory f : all()) { + result.addAll(f.createFor(v)); + } + return result; + } } diff --git a/core/src/main/java/hudson/model/UnprotectedRootAction.java b/core/src/main/java/hudson/model/UnprotectedRootAction.java index bb5a7b6b5f17569a693f105180b17695e90fa27a..b3ebdc2c3bc496a402d566472741fe929251b680 100644 --- a/core/src/main/java/hudson/model/UnprotectedRootAction.java +++ b/core/src/main/java/hudson/model/UnprotectedRootAction.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import hudson.ExtensionPoint; diff --git a/core/src/main/java/hudson/model/UpdateCenter.java b/core/src/main/java/hudson/model/UpdateCenter.java index 2a9302b9081e86e8421aed269673128039178a2c..27900962d1a76eebb4fefb89f1b847ecc00f4565 100644 --- a/core/src/main/java/hudson/model/UpdateCenter.java +++ b/core/src/main/java/hudson/model/UpdateCenter.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import static hudson.init.InitMilestone.PLUGINS_STARTED; @@ -161,7 +162,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas /** * Read timeout when downloading plugins, defaults to 1 minute */ - private static final int PLUGIN_DOWNLOAD_READ_TIMEOUT = (int)TimeUnit.SECONDS.toMillis(SystemProperties.getInteger(UpdateCenter.class.getName()+".pluginDownloadReadTimeoutSeconds", 60)); + private static final int PLUGIN_DOWNLOAD_READ_TIMEOUT = (int) TimeUnit.SECONDS.toMillis(SystemProperties.getInteger(UpdateCenter.class.getName() + ".pluginDownloadReadTimeoutSeconds", 60)); public static final String PREDEFINED_UPDATE_SITE_ID = "default"; @@ -169,7 +170,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas * {@linkplain UpdateSite#getId() ID} of the default update site. * @since 1.483; configurable via system property since 2.4 */ - public static final String ID_DEFAULT = SystemProperties.getString(UpdateCenter.class.getName()+".defaultUpdateSiteId", PREDEFINED_UPDATE_SITE_ID); + public static final String ID_DEFAULT = SystemProperties.getString(UpdateCenter.class.getName() + ".defaultUpdateSiteId", PREDEFINED_UPDATE_SITE_ID); @Restricted(NoExternalUse.class) public static final String ID_UPLOAD = "_upload"; @@ -216,7 +217,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas static { Logger logger = Logger.getLogger(UpdateCenter.class.getName()); LOGGER = logger; - String ucOverride = SystemProperties.getString(UpdateCenter.class.getName()+".updateCenterUrl"); + String ucOverride = SystemProperties.getString(UpdateCenter.class.getName() + ".updateCenterUrl"); if (ucOverride != null) { logger.log(Level.INFO, "Using a custom update center defined by the system property: {0}", ucOverride); UPDATE_CENTER_URL = ucOverride; @@ -277,7 +278,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas */ @NonNull public static UpdateCenter createUpdateCenter(@CheckForNull UpdateCenterConfiguration config) { - String requiredClassName = SystemProperties.getString(UpdateCenter.class.getName()+".className", null); + String requiredClassName = SystemProperties.getString(UpdateCenter.class.getName() + ".className", null); if (requiredClassName == null) { // Use the default Update Center LOGGER.log(Level.FINE, "Using the default Update Center implementation"); @@ -298,12 +299,12 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas LOGGER.log(Level.FINE, "Using the constructor {0} Update Center configuration for {1}", new Object[] {config != null ? "with" : "without", requiredClassName}); return config != null ? configConstructor.newInstance(config) : defaultConstructor.newInstance(); - } catch(ClassCastException e) { + } catch (ClassCastException e) { // Should never happen LOGGER.log(WARNING, "UpdateCenter class {0} does not extend hudson.model.UpdateCenter. Using default.", requiredClassName); - } catch(NoSuchMethodException e) { + } catch (NoSuchMethodException e) { LOGGER.log(WARNING, String.format("UpdateCenter class %s does not define one of the required constructors. Using default", requiredClassName), e); - } catch(Exception e) { + } catch (Exception e) { LOGGER.log(WARNING, String.format("Unable to instantiate custom plugin manager [%s]. Using default.", requiredClassName), e); } return createDefaultUpdateCenter(config); @@ -327,7 +328,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas * @see UpdateCenterConfiguration */ public void configure(UpdateCenterConfiguration config) { - if (config!=null) { + if (config != null) { this.config = config; } } @@ -354,7 +355,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas public UpdateCenterJob getJob(int id) { synchronized (jobs) { for (UpdateCenterJob job : jobs) { - if (job.id==id) + if (job.id == id) return job; } } @@ -370,7 +371,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas Collections.reverse(jobList); for (UpdateCenterJob job : jobList) if (job instanceof InstallationJob) { - InstallationJob ij = (InstallationJob)job; + InstallationJob ij = (InstallationJob) job; if (ij.plugin.name.equals(plugin.name) && ij.plugin.sourceId.equals(plugin.sourceId)) return ij; } @@ -406,7 +407,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas if (checkJob != null) { boolean isOffline = false; for (ConnectionStatus status : checkJob.connectionStates.values()) { - if(ConnectionStatus.FAILED.equals(status)) { + if (ConnectionStatus.FAILED.equals(status)) { isOffline = true; break; } @@ -416,12 +417,12 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas checkJob.run(); isOffline = false; for (ConnectionStatus status : checkJob.connectionStates.values()) { - if(ConnectionStatus.FAILED.equals(status)) { + if (ConnectionStatus.FAILED.equals(status)) { isOffline = true; break; } } - if(!isOffline) { // also need to download the metadata + if (!isOffline) { // also need to download the metadata updateAllSites(); } } @@ -441,8 +442,8 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas @Restricted(DoNotUse.class) // WebOnly public HttpResponse doIncompleteInstallStatus() { try { - Map jobs = InstallUtil.getPersistedInstallStatus(); - if(jobs == null) { + Map jobs = InstallUtil.getPersistedInstallStatus(); + if (jobs == null) { jobs = Collections.emptyMap(); } return HttpResponses.okJSON(jobs); @@ -464,13 +465,13 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas for (UpdateCenterJob job : jobs) { if (job instanceof InstallationJob) { InstallationJob installationJob = (InstallationJob) job; - if(!installationJob.status.isSuccess()) { + if (!installationJob.status.isSuccess()) { activeInstalls = true; } } } - if(activeInstalls) { + if (activeInstalls) { InstallUtil.persistInstallStatus(jobs); // save this info } else { @@ -491,7 +492,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas public HttpResponse doInstallStatus(StaplerRequest request) { try { String correlationId = request.getParameter("correlationId"); - Map response = new HashMap<>(); + Map response = new HashMap<>(); response.put("state", Jenkins.get().getInstallState().name()); List> installStates = new ArrayList<>(); response.put("jobs", installStates); @@ -530,7 +531,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas Collections.reverse(jobList); for (UpdateCenterJob job : jobList) if (job instanceof HudsonUpgradeJob) - return (HudsonUpgradeJob)job; + return (HudsonUpgradeJob) job; return null; } @@ -570,7 +571,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas /** * The same as {@link #getSites()} but for REST API. */ - @Exported(name="sites") + @Exported(name = "sites") public List getSiteList() { return sites.toList(); } @@ -592,14 +593,14 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas public String getLastUpdatedString() { long newestTs = 0; for (UpdateSite s : sites) { - if (s.getDataTimestamp()>newestTs) { + if (s.getDataTimestamp() > newestTs) { newestTs = s.getDataTimestamp(); } } if (newestTs == 0) { return Messages.UpdateCenter_n_a(); } - return Util.getTimeSpanString(System.currentTimeMillis()-newestTs); + return Util.getTimeSpanString(System.currentTimeMillis() - newestTs); } /** @@ -628,7 +629,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas public UpdateSite getCoreSource() { for (UpdateSite s : sites) { Data data = s.getData(); - if (data!=null && data.core!=null) + if (data != null && data.core != null) return s; } return null; @@ -653,7 +654,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas public @CheckForNull Plugin getPlugin(String artifactId) { for (UpdateSite s : sites) { Plugin p = s.getPlugin(artifactId); - if (p!=null) return p; + if (p != null) return p; } return null; } @@ -704,7 +705,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas public void doUpgrade(StaplerResponse rsp) throws IOException, ServletException { Jenkins.get().checkPermission(Jenkins.ADMINISTER); HudsonUpgradeJob job = new HudsonUpgradeJob(getCoreSource(), Jenkins.getAuthentication2()); - if(!Lifecycle.get().canRewriteHudsonWar()) { + if (!Lifecycle.get().canRewriteHudsonWar()) { sendError("Jenkins upgrade not supported in this running mode"); return; } @@ -809,7 +810,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas @RequirePOST public void doDowngrade(StaplerResponse rsp) throws IOException, ServletException { Jenkins.get().checkPermission(Jenkins.ADMINISTER); - if(!isDowngradable()) { + if (!isDowngradable()) { sendError("Jenkins downgrade is not possible, probably backup does not exist"); return; } @@ -847,7 +848,8 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas } } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to read backup version ", e); - return null;} + return null; + } } @@ -924,12 +926,12 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas */ @Override public synchronized void save() { - if(BulkChange.contains(this)) return; + if (BulkChange.contains(this)) return; try { getConfigFile().write(sites); SaveableListener.fireOnChange(this, getConfigFile()); } catch (IOException e) { - LOGGER.log(Level.WARNING, "Failed to save "+getConfigFile(),e); + LOGGER.log(Level.WARNING, "Failed to save " + getConfigFile(), e); } } @@ -938,11 +940,11 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas */ public synchronized void load() throws IOException { XmlFile file = getConfigFile(); - if(file.exists()) { + if (file.exists()) { try { - sites.replaceBy(((PersistedList)file.unmarshal(sites)).toList()); + sites.replaceBy(((PersistedList) file.unmarshal(sites)).toList()); } catch (IOException e) { - LOGGER.log(Level.WARNING, "Failed to load "+file, e); + LOGGER.log(Level.WARNING, "Failed to load " + file, e); } boolean defaultSiteExists = false; for (UpdateSite site : sites) { @@ -971,15 +973,15 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas } private XmlFile getConfigFile() { - return new XmlFile(XSTREAM,new File(Jenkins.get().root, - UpdateCenter.class.getName()+".xml")); + return new XmlFile(XSTREAM, new File(Jenkins.get().root, + UpdateCenter.class.getName() + ".xml")); } @Exported public List getAvailables() { - Map pluginMap = new LinkedHashMap<>(); + Map pluginMap = new LinkedHashMap<>(); for (UpdateSite site : sites) { - for (Plugin plugin: site.getAvailables()) { + for (Plugin plugin : site.getAvailables()) { final Plugin existing = pluginMap.get(plugin.name); if (existing == null) { pluginMap.put(plugin.name, plugin); @@ -1006,7 +1008,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas public PluginEntry[] getCategorizedAvailables() { TreeSet entries = new TreeSet<>(); for (Plugin p : getAvailables()) { - if (p.categories==null || p.categories.length==0) + if (p.categories == null || p.categories.length == 0) entries.add(new PluginEntry(p, getCategoryDisplayName(null))); else for (String c : p.categories) @@ -1017,7 +1019,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas @Restricted(NoExternalUse.class) // Jelly only public static String getCategoryDisplayName(String category) { - if (category==null) + if (category == null) return Messages.UpdateCenter_PluginCategory_misc(); try { return (String) Messages.class.getMethod( @@ -1030,12 +1032,12 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas } public List getUpdates() { - Map pluginMap = new LinkedHashMap<>(); + Map pluginMap = new LinkedHashMap<>(); final Map> incompatiblePluginMap = new LinkedHashMap<>(); final PluginManager.MetadataCache cache = new PluginManager.MetadataCache(); for (UpdateSite site : sites) { - for (Plugin plugin: site.getUpdates()) { + for (Plugin plugin : site.getUpdates()) { final Plugin existing = pluginMap.get(plugin.name); if (existing == null) { pluginMap.put(plugin.name, plugin); @@ -1066,7 +1068,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas @Restricted(NoExternalUse.class) public List getPluginsWithUnavailableUpdates() { - Map pluginMap = new LinkedHashMap<>(); + Map pluginMap = new LinkedHashMap<>(); for (PluginWrapper wrapper : Jenkins.get().getPluginManager().getPlugins()) { for (UpdateSite site : sites) { UpdateSite.Plugin plugin = site.getPlugin(wrapper.getShortName()); @@ -1094,7 +1096,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas * @since 1.501 */ public List updateAllSites() throws InterruptedException, ExecutionException { - List > futures = new ArrayList<>(); + List> futures = new ArrayList<>(); for (UpdateSite site : getSites()) { Future future = site.updateDirectly(); if (future != null) { @@ -1127,12 +1129,12 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas return false; } Data data = getData(); - return data!=null && data.hasCoreUpdates(); + return data != null && data.hasCoreUpdates(); } public Data getData() { UpdateSite cs = Jenkins.get().getUpdateCenter().getCoreSource(); - if (cs!=null) return cs.getData(); + if (cs != null) return cs.getData(); return null; } @@ -1257,7 +1259,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas URLConnection con = null; try { - con = connect(job,src); + con = connect(job, src); //JENKINS-34174 - set timeout for downloads, may hang indefinitely // particularly noticeable during 2.0 install when downloading // many plugins @@ -1275,9 +1277,9 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas int len; File dst = job.getDestination(); - File tmp = new File(dst.getPath()+".tmp"); + File tmp = new File(dst.getPath() + ".tmp"); - LOGGER.info("Downloading "+job.getName()); + LOGGER.info("Downloading " + job.getName()); Thread t = Thread.currentThread(); String oldName = t.getName(); t.setName(oldName + ": " + src); @@ -1289,7 +1291,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas InputStream in = con.getInputStream(); CountingInputStream cin = new CountingInputStream(in)) { while ((len = cin.read(buf)) >= 0) { - out.write(buf,0,len); + out.write(buf, 0, len); final int count = cin.getCount(); job.status = job.new Installing(total == -1 ? -1 : ((int) (count * 100 / total))); if (total != -1 && total < count) { @@ -1297,16 +1299,16 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas } } } catch (IOException | InvalidPathException e) { - throw new IOException("Failed to load "+src+" to "+tmp,e); + throw new IOException("Failed to load " + src + " to " + tmp, e); } finally { t.setName(oldName); } - if (total!=-1 && total!=tmp.length()) { + if (total != -1 && total != tmp.length()) { // don't know exactly how this happens, but report like // http://www.ashlux.com/wordpress/2009/08/14/hudson-and-the-sonar-plugin-fail-maveninstallation-nosuchmethoderror/ // indicates that this kind of inconsistency can happen. So let's be defensive - throw new IOException("Inconsistent file length: expected "+total+" but only got "+tmp.length()); + throw new IOException("Inconsistent file length: expected " + total + " but only got " + tmp.length()); } if (sha1 != null) { @@ -1331,7 +1333,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas // Also, since it involved name resolution, it'd be an expensive operation. extraMessage = " (redirected to: " + con.getURL() + ")"; } - throw new IOException("Failed to download from "+src+extraMessage,e); + throw new IOException("Failed to download from " + src + extraMessage, e); } } @@ -1414,9 +1416,9 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas try { URLConnection connection = ProxyConfiguration.open(url); - if(connection instanceof HttpURLConnection) { - int responseCode = ((HttpURLConnection)connection).getResponseCode(); - if(HttpURLConnection.HTTP_OK != responseCode) { + if (connection instanceof HttpURLConnection) { + int responseCode = ((HttpURLConnection) connection).getResponseCode(); + if (HttpURLConnection.HTTP_OK != responseCode) { throw new HttpRetryException("Invalid response code (" + responseCode + ") from URL: " + url, responseCode); } } else { @@ -1427,7 +1429,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas } catch (SSLHandshakeException e) { if (e.getMessage().contains("PKIX path building failed")) // fix up this crappy error message from JDK - throw new IOException("Failed to validate the SSL certificate of "+url,e); + throw new IOException("Failed to validate the SSL certificate of " + url, e); } } } @@ -1502,11 +1504,11 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas * {@link Future} to keeps track of the status of the execution. */ public Future submit() { - LOGGER.fine("Scheduling "+this+" to installerService"); + LOGGER.fine("Scheduling " + this + " to installerService"); // TODO: seems like this access to jobs should be synchronized, no? // It might get synch'd accidentally via the addJob method, but that wouldn't be good. jobs.add(this); - return installerService.submit(this,this); + return installerService.submit(this, this); } @Exported @@ -1526,7 +1528,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas /** * Immutable state of this job. */ - @Exported(inline=true) + @Exported(inline = true) public volatile RestartJenkinsJobStatus status = new RestartJenkinsJob.Pending(); /** @@ -1599,7 +1601,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas * Tests the internet connectivity. */ public final class ConnectionCheckJob extends UpdateCenterJob { - private final Vector statuses= new Vector<>(); + private final Vector statuses = new Vector<>(); final Map connectionStates = new ConcurrentHashMap<>(); @@ -1620,7 +1622,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas Future internetCheck = null; try { final String connectionCheckUrl = site.getConnectionCheckUrl(); - if (connectionCheckUrl!=null) { + if (connectionCheckUrl != null) { connectionStates.put(ConnectionStatus.INTERNET, ConnectionStatus.CHECKING); statuses.add(Messages.UpdateCenter_Status_CheckingInternet()); // Run the internet check in parallel @@ -1630,7 +1632,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas try { config.checkConnection(ConnectionCheckJob.this, connectionCheckUrl); } catch (Exception e) { - if(e.getMessage().contains("Connection timed out")) { + if (e.getMessage().contains("Connection timed out")) { // Google can't be down, so this is probably a proxy issue connectionStates.put(ConnectionStatus.INTERNET, ConnectionStatus.FAILED); statuses.add(Messages.UpdateCenter_Status_ConnectionFailed(Functions.xmlEscape(connectionCheckUrl))); @@ -1664,7 +1666,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas error = e; } - if(internetCheck != null) { + if (internetCheck != null) { try { // Wait for internet check to complete internetCheck.get(); @@ -1675,7 +1677,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas } private void addStatus(Throwable e) { - statuses.add("

    "+ Functions.xmlEscape(Functions.printThrowable(e))+"
    "); + statuses.add("
    " + Functions.xmlEscape(Functions.printThrowable(e)) + "
    "); } public String[] getStatuses() { @@ -1703,7 +1705,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas public void run() { try { PluginWrapper installed = plugin.getInstalled(); - synchronized(installed) { + synchronized (installed) { if (!installed.isEnabled()) { try { installed.enable(); @@ -1728,13 +1730,13 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas } } } - } catch(Throwable e) { + } catch (Throwable e) { LOGGER.log(Level.SEVERE, "An unexpected error occurred while attempting to enable " + plugin.getDisplayName(), e); error = e; requiresRestart = true; status = new DownloadJob.Failure(e); } - if(status instanceof DownloadJob.Pending) { + if (status instanceof DownloadJob.Pending) { status = new DownloadJob.Success(); } } @@ -1747,6 +1749,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas public NoOpJob(UpdateSite site, Authentication auth, @NonNull Plugin plugin) { super(site, auth, plugin, false); } + @Override public void run() { // do nothing @@ -1757,7 +1760,9 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas @Restricted(NoExternalUse.class) /*package*/ interface WithComputedChecksums { String getComputedSHA1(); + String getComputedSHA256(); + String getComputedSHA512(); } @@ -1768,7 +1773,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas /** * Immutable object representing the current state of this job. */ - @Exported(inline=true) + @Exported(inline = true) public volatile InstallationStatus status = new DownloadJob.Pending(); /** @@ -1857,11 +1862,11 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas @Override public void run() { try { - LOGGER.info("Starting the installation of "+getName()+" on behalf of "+getUser().getName()); + LOGGER.info("Starting the installation of " + getName() + " on behalf of " + getUser().getName()); _run(); - LOGGER.info("Installation successful: "+getName()); + LOGGER.info("Installation successful: " + getName()); status = new DownloadJob.Success(); onSuccess(); } catch (InstallationStatus e) { @@ -1873,7 +1878,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas status = new DownloadJob.Failure(e); error = e; } catch (Throwable e) { - LOGGER.log(Level.SEVERE, "Failed to install "+getName(),e); + LOGGER.log(Level.SEVERE, "Failed to install " + getName(), e); status = new DownloadJob.Failure(e); error = e; } @@ -1896,7 +1901,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas * the old file with the new file. */ protected synchronized void replace(File dst, File src) throws IOException { - File bak = Util.changeExtension(dst,".bak"); + File bak = Util.changeExtension(dst, ".bak"); moveAtomically(dst, bak); moveAtomically(src, dst); } @@ -1920,10 +1925,12 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas @ExportedBean public abstract class InstallationStatus extends Throwable { public final int id = iota.incrementAndGet(); + @Exported public boolean isSuccess() { return false; } + @Exported public final String getType() { return getClass().getSimpleName(); @@ -2137,7 +2144,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas */ @Deprecated public InstallationJob(Plugin plugin, UpdateSite site, Authentication auth) { - this(plugin,site,auth,false); + this(plugin, site, auth, false); } /** @@ -2199,7 +2206,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas // if this is a bundled plugin, make sure it won't get overwritten PluginWrapper pw = plugin.getInstalled(); - if (pw!=null && pw.isBundled()) { + if (pw != null && pw.isBundled()) { try (ACLContext ctx = ACL.as2(ACL.SYSTEM2)) { pw.doPin(); } @@ -2211,13 +2218,13 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas } catch (RestartRequiredException e) { throw new DownloadJob.SuccessButRequiresRestart(e.message); } catch (Exception e) { - throw new IOException("Failed to dynamically deploy this plugin",e); + throw new IOException("Failed to dynamically deploy this plugin", e); } } else { throw new DownloadJob.SuccessButRequiresRestart(Messages._UpdateCenter_DownloadButNotActivated()); } } finally { - synchronized(this) { + synchronized (this) { // There may be other threads waiting on completion LOGGER.fine("Install complete for: " + plugin.getDisplayName() + "@" + plugin.version); // some status other than Installing or Downloading needs to be set here @@ -2233,7 +2240,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas * @since 2.1 */ protected boolean wasInstalled() { - synchronized(UpdateCenter.this) { + synchronized (UpdateCenter.this) { for (UpdateCenterJob job : getJobs()) { if (job == this) { // oldest entries first, if we reach this instance, @@ -2241,11 +2248,11 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas return false; } if (job instanceof InstallationJob) { - InstallationJob ij = (InstallationJob)job; + InstallationJob ij = (InstallationJob) job; if (ij.plugin.equals(plugin) && ij.plugin.version.equals(plugin.version)) { // wait until other install is completed - synchronized(ij) { - if(ij.status instanceof DownloadJob.Installing || ij.status instanceof DownloadJob.Pending) { + synchronized (ij) { + if (ij.status instanceof DownloadJob.Installing || ij.status instanceof DownloadJob.Pending) { try { LOGGER.fine("Waiting for other plugin install of: " + plugin.getDisplayName() + "@" + plugin.version); ij.wait(); @@ -2272,7 +2279,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas @Override public String toString() { - return super.toString()+"[plugin="+plugin.title+"]"; + return super.toString() + "[plugin=" + plugin.title + "]"; } /** @@ -2352,6 +2359,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas Failure(Throwable problemStackTrace) { this.problemStackTrace = problemStackTrace; } + public final Throwable problemStackTrace; } @@ -2391,7 +2399,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas protected File getDestination() { File baseDir = pm.rootDir; final File legacy = new File(baseDir, plugin.name + ".hpi"); - if(legacy.exists()){ + if (legacy.exists()) { return legacy; } return new File(baseDir, plugin.name + ".jpi"); @@ -2415,15 +2423,15 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas @Override public void run() { try { - LOGGER.info("Starting the downgrade of "+getName()+" on behalf of "+getUser().getName()); + LOGGER.info("Starting the downgrade of " + getName() + " on behalf of " + getUser().getName()); _run(); - LOGGER.info("Downgrade successful: "+getName()); + LOGGER.info("Downgrade successful: " + getName()); status = new Success(); onSuccess(); } catch (Throwable e) { - LOGGER.log(Level.SEVERE, "Failed to downgrade "+getName(),e); + LOGGER.log(Level.SEVERE, "Failed to downgrade " + getName(), e); status = new DownloadJob.Failure(e); error = e; } @@ -2453,7 +2461,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas @Override public String toString() { - return super.toString()+"[plugin="+plugin.title+"]"; + return super.toString() + "[plugin=" + plugin.title + "]"; } } @@ -2538,22 +2546,24 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas public String getName() { return "jenkins.war"; } + @Override protected void onSuccess() { status = new DownloadJob.Success(); } + @Override public void run() { try { - LOGGER.info("Starting the downgrade of "+getName()+" on behalf of "+getUser().getName()); + LOGGER.info("Starting the downgrade of " + getName() + " on behalf of " + getUser().getName()); _run(); - LOGGER.info("Downgrading successful: "+getName()); + LOGGER.info("Downgrading successful: " + getName()); status = new DownloadJob.Success(); onSuccess(); } catch (Throwable e) { - LOGGER.log(Level.SEVERE, "Failed to downgrade "+getName(),e); + LOGGER.log(Level.SEVERE, "Failed to downgrade " + getName(), e); status = new DownloadJob.Failure(e); error = e; } @@ -2578,6 +2588,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas public static final class PluginEntry implements Comparable { public Plugin plugin; public String category; + private PluginEntry(Plugin p, String c) { plugin = p; category = c; @@ -2586,8 +2597,8 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas @Override public int compareTo(PluginEntry o) { int r = category.compareTo(o.category); - if (r==0) r = plugin.name.compareToIgnoreCase(o.plugin.name); - if (r==0) r = new VersionNumber(plugin.version).compareTo(new VersionNumber(o.plugin.version)); + if (r == 0) r = plugin.name.compareToIgnoreCase(o.plugin.name); + if (r == 0) r = new VersionNumber(plugin.version).compareTo(new VersionNumber(o.plugin.version)); return r; } @@ -2625,7 +2636,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas * * This has to wait until after all plugins load, to let custom UpdateCenterConfiguration take effect first. */ - @Initializer(after=PLUGINS_STARTED, fatal=false) + @Initializer(after = PLUGINS_STARTED, fatal = false) public static void init(Jenkins h) throws IOException { h.getUpdateCenter().load(); } @@ -2687,13 +2698,13 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas * Use {@link UpdateSite#neverUpdate} */ @Deprecated - public static boolean neverUpdate = SystemProperties.getBoolean(UpdateCenter.class.getName()+".never"); + public static boolean neverUpdate = SystemProperties.getBoolean(UpdateCenter.class.getName() + ".never"); public static final XStream2 XSTREAM = new XStream2(); static { - XSTREAM.alias("site",UpdateSite.class); - XSTREAM.alias("sites",PersistedList.class); + XSTREAM.alias("site", UpdateSite.class); + XSTREAM.alias("sites", PersistedList.class); } private static void moveAtomically(File src, File target) throws IOException { diff --git a/core/src/main/java/hudson/model/UpdateSite.java b/core/src/main/java/hudson/model/UpdateSite.java index 53865761eb163b5de3b4d38630da09c6515a5a57..e5b7bb3f12283210fbcba15d43a901ef8d6e4120 100644 --- a/core/src/main/java/hudson/model/UpdateSite.java +++ b/core/src/main/java/hudson/model/UpdateSite.java @@ -238,7 +238,7 @@ public class UpdateSite { if (signatureCheck) { FormValidation e = verifySignatureInternal(o); - if (e.kind!=FormValidation.Kind.OK) { + if (e.kind != FormValidation.Kind.OK) { LOGGER.severe(e.toString()); return e; } @@ -308,17 +308,17 @@ public class UpdateSite { * Returns true if it's time for us to check for new version. */ public synchronized boolean isDue() { - if(neverUpdate) return false; - if(dataTimestamp == 0) + if (neverUpdate) return false; + if (dataTimestamp == 0) dataTimestamp = getDataFile().file.lastModified(); long now = System.currentTimeMillis(); - retryWindow = Math.max(retryWindow,SECONDS.toMillis(15)); + retryWindow = Math.max(retryWindow, SECONDS.toMillis(15)); boolean due = now - dataTimestamp > DAY && now - lastAttempt > retryWindow; - if(due) { + if (due) { lastAttempt = now; - retryWindow = Math.min(retryWindow*2, HOURS.toMillis(1)); // exponential back off but at most 1 hour + retryWindow = Math.min(retryWindow * 2, HOURS.toMillis(1)); // exponential back off but at most 1 hour } return due; } @@ -365,14 +365,14 @@ public class UpdateSite { */ public JSONObject getJSONObject() { TextFile df = getDataFile(); - if(df.exists()) { + if (df.exists()) { long start = System.nanoTime(); try { JSONObject o = JSONObject.fromObject(df.read()); LOGGER.fine(() -> String.format("Loaded and parsed %s in %.01fs", df, (System.nanoTime() - start) / 1_000_000_000.0)); return o; } catch (JSONException | IOException e) { - LOGGER.log(Level.SEVERE,"Failed to parse "+df,e); + LOGGER.log(Level.SEVERE, "Failed to parse " + df, e); try { df.delete(); // if we keep this file, it will cause repeated failures } catch (IOException e2) { @@ -393,9 +393,9 @@ public class UpdateSite { public List getAvailables() { List r = new ArrayList<>(); Data data = getData(); - if(data==null) return Collections.emptyList(); + if (data == null) return Collections.emptyList(); for (Plugin p : data.plugins.values()) { - if(p.getInstalled()==null) + if (p.getInstalled() == null) r.add(p); } r.sort((plugin, t1) -> { @@ -420,7 +420,7 @@ public class UpdateSite { @CheckForNull public Plugin getPlugin(String artifactId) { Data dt = getData(); - if(dt==null) return null; + if (dt == null) return null; return dt.plugins.get(artifactId); } @@ -436,7 +436,7 @@ public class UpdateSite { @CheckForNull public String getConnectionCheckUrl() { Data dt = getData(); - if(dt==null) return "http://www.google.com/"; + if (dt == null) return "http://www.google.com/"; return dt.connectionCheckUrl; } @@ -445,7 +445,7 @@ public class UpdateSite { */ private TextFile getDataFile() { return new TextFile(new File(Jenkins.get().getRootDir(), - "updates/" + getId()+".json")); + "updates/" + getId() + ".json")); } /** @@ -457,12 +457,12 @@ public class UpdateSite { @Exported public List getUpdates() { Data data = getData(); - if(data==null) return Collections.emptyList(); // fail to determine + if (data == null) return Collections.emptyList(); // fail to determine List r = new ArrayList<>(); for (PluginWrapper pw : Jenkins.get().getPluginManager().getPlugins()) { Plugin p = pw.getUpdateInfo(); - if(p!=null) r.add(p); + if (p != null) r.add(p); } return r; @@ -474,10 +474,10 @@ public class UpdateSite { @Exported public boolean hasUpdates() { Data data = getData(); - if(data==null) return false; + if (data == null) return false; for (PluginWrapper pw : Jenkins.get().getPluginManager().getPlugins()) { - if(!pw.isBundled() && pw.getUpdateInfo()!=null) + if (!pw.isBundled() && pw.getUpdateInfo() != null) // do not advertize updates to bundled plugins, since we generally want users to get them // as a part of jenkins.war updates. This also avoids unnecessary pinning of plugins. return true; @@ -559,7 +559,7 @@ public class UpdateSite { /** * Plugins in the repository, keyed by their artifact IDs. */ - public final Map plugins = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + public final Map plugins = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); /** * List of warnings (mostly security) published with the update site. * @@ -581,9 +581,9 @@ public class UpdateSite { public final String connectionCheckUrl; Data(JSONObject o) { - this.sourceId = Util.intern((String)o.get("id")); + this.sourceId = Util.intern((String) o.get("id")); JSONObject c = o.optJSONObject("core"); - if (c!=null) { + if (c != null) { core = new Entry(sourceId, c, url); } else { core = null; @@ -618,13 +618,13 @@ public class UpdateSite { } } - for(Map.Entry e : (Set>)o.getJSONObject("plugins").entrySet()) { + for (Map.Entry e : (Set>) o.getJSONObject("plugins").entrySet()) { Plugin p = new Plugin(sourceId, e.getValue()); // JENKINS-33308 - include implied dependencies for older plugins that may need them List implicitDeps = DetachedPluginsUtil.getImpliedDependencies(p.name, p.requiredCore); - if(!implicitDeps.isEmpty()) { - for(PluginWrapper.Dependency dep : implicitDeps) { - if(!p.dependencies.containsKey(dep.shortName)) { + if (!implicitDeps.isEmpty()) { + for (PluginWrapper.Dependency dep : implicitDeps) { + if (!p.dependencies.containsKey(dep.shortName)) { p.dependencies.put(dep.shortName, dep.version); } } @@ -640,7 +640,7 @@ public class UpdateSite { } } - connectionCheckUrl = (String)o.get("connectionCheckUrl"); + connectionCheckUrl = (String) o.get("connectionCheckUrl"); } /** @@ -879,6 +879,7 @@ public class UpdateSite { * Jenkins will show a link to this URL when displaying the deprecation message. */ public final String url; + public Deprecation(String url) { this.url = url; } @@ -1069,7 +1070,7 @@ public class UpdateSite { } private static String get(JSONObject o, String prop) { - if(o.has(prop)) + if (o.has(prop)) return o.getString(prop); else return null; @@ -1163,13 +1164,13 @@ public class UpdateSite { * Dependencies of this plugin, a name -> version mapping. */ @Exported - public final Map dependencies; + public final Map dependencies; /** * Optional dependencies of this plugin. */ @Exported - public final Map optionalDependencies; + public final Map optionalDependencies; /** * Set of plugins, this plugin is a incompatible dependency to. @@ -1210,13 +1211,13 @@ public class UpdateSite { @DataBoundConstructor public Plugin(String sourceId, JSONObject o) { super(sourceId, o, UpdateSite.this.url); - this.wiki = get(o,"wiki"); - this.title = get(o,"title"); - this.excerpt = get(o,"excerpt"); - this.compatibleSinceVersion = Util.intern(get(o,"compatibleSinceVersion")); + this.wiki = get(o, "wiki"); + this.title = get(o, "title"); + this.excerpt = get(o, "excerpt"); + this.compatibleSinceVersion = Util.intern(get(o, "compatibleSinceVersion")); this.minimumJavaVersion = Util.intern(get(o, "minimumJavaVersion")); this.latest = get(o, "latest"); - this.requiredCore = Util.intern(get(o,"requiredCore")); + this.requiredCore = Util.intern(get(o, "requiredCore")); final String releaseTimestamp = get(o, "releaseTimestamp"); Date date = null; if (releaseTimestamp != null) { @@ -1237,20 +1238,20 @@ public class UpdateSite { } this.popularity = popularity; this.releaseTimestamp = date; - this.categories = o.has("labels") ? internInPlace((String[])o.getJSONArray("labels").toArray(EMPTY_STRING_ARRAY)) : null; + this.categories = o.has("labels") ? internInPlace((String[]) o.getJSONArray("labels").toArray(EMPTY_STRING_ARRAY)) : null; this.issueTrackers = o.has("issueTrackers") ? o.getJSONArray("issueTrackers").stream().map(IssueTracker::createFromJSONObject).filter(Objects::nonNull).toArray(IssueTracker[]::new) : null; JSONArray ja = o.getJSONArray("dependencies"); - int depCount = (int)ja.stream().filter(IS_DEP_PREDICATE.and(IS_NOT_OPTIONAL)).count(); - int optionalDepCount = (int)ja.stream().filter(IS_DEP_PREDICATE.and(IS_NOT_OPTIONAL.negate())).count(); + int depCount = (int) ja.stream().filter(IS_DEP_PREDICATE.and(IS_NOT_OPTIONAL)).count(); + int optionalDepCount = (int) ja.stream().filter(IS_DEP_PREDICATE.and(IS_NOT_OPTIONAL.negate())).count(); dependencies = getPresizedMutableMap(depCount); optionalDependencies = getPresizedMutableMap(optionalDepCount); - for(Object jo : o.getJSONArray("dependencies")) { + for (Object jo : o.getJSONArray("dependencies")) { JSONObject depObj = (JSONObject) jo; // Make sure there's a name attribute and that the optional value isn't true. - String depName = Util.intern(get(depObj,"name")); - if (depName!=null) { + String depName = Util.intern(get(depObj, "name")); + if (depName != null) { if (get(depObj, "optional").equals("false")) { dependencies.put(depName, Util.intern(get(depObj, "version"))); } else { @@ -1273,7 +1274,7 @@ public class UpdateSite { public String getDisplayName() { String displayName; - if(title!=null) + if (title != null) displayName = title; else displayName = name; @@ -1337,7 +1338,7 @@ public class UpdateSite { public List getNeededDependencies() { List deps = new ArrayList<>(); - for(Map.Entry e : dependencies.entrySet()) { + for (Map.Entry e : dependencies.entrySet()) { VersionNumber requiredVersion = e.getValue() != null ? new VersionNumber(e.getValue()) : null; Plugin depPlugin = Jenkins.get().getUpdateCenter().getPlugin(e.getKey(), requiredVersion); if (depPlugin == null) { @@ -1348,7 +1349,7 @@ public class UpdateSite { // Is the plugin installed already? If not, add it. PluginWrapper current = depPlugin.getInstalled(); - if (current ==null) { + if (current == null) { deps.add(depPlugin); } // If the dependency plugin is installed, is the version we depend on newer than @@ -1362,7 +1363,7 @@ public class UpdateSite { } } - for(Map.Entry e : optionalDependencies.entrySet()) { + for (Map.Entry e : optionalDependencies.entrySet()) { VersionNumber requiredVersion = e.getValue() != null ? new VersionNumber(e.getValue()) : null; Plugin depPlugin = Jenkins.get().getUpdateCenter().getPlugin(e.getKey(), requiredVersion); if (depPlugin == null) { @@ -1383,7 +1384,7 @@ public class UpdateSite { public boolean isForNewerHudson() { try { - return requiredCore!=null && new VersionNumber(requiredCore).isNewerThan( + return requiredCore != null && new VersionNumber(requiredCore).isNewerThan( new VersionNumber(Jenkins.VERSION.replaceFirst("SHOT *\\(private.*\\)", "SHOT"))); } catch (NumberFormatException nfe) { return true; // If unable to parse version @@ -1412,7 +1413,7 @@ public class UpdateSite { } catch (NumberFormatException nfe) { // unable to parse version } - for (Plugin p: getNeededDependencies()) { + for (Plugin p : getNeededDependencies()) { VersionNumber v = p.getNeededDependenciesRequiredCore(); if (versionNumber == null || v.isNewerThan(versionNumber)) versionNumber = v; } @@ -1432,7 +1433,7 @@ public class UpdateSite { } catch (NumberFormatException nfe) { logBadMinJavaVersion(); } - for (Plugin p: getNeededDependencies()) { + for (Plugin p : getNeededDependencies()) { VersionNumber v = p.getNeededDependenciesMinimumJavaVersion(); if (v == null) { continue; @@ -1471,7 +1472,7 @@ public class UpdateSite { * @since 2.158 */ public boolean isNeededDependenciesForNewerJava() { - for (Plugin p: getNeededDependencies()) { + for (Plugin p : getNeededDependencies()) { if (p.isForNewerJava() || p.isNeededDependenciesForNewerJava()) { return true; } @@ -1564,7 +1565,7 @@ public class UpdateSite { UpdateSiteWarningsConfiguration configuration = ExtensionList.lookupSingleton(UpdateSiteWarningsConfiguration.class); Set warnings = new HashSet<>(); - for (Warning warning: configuration.getAllWarnings()) { + for (Warning warning : configuration.getAllWarnings()) { if (configuration.isIgnored(warning)) { // warning is currently being ignored continue; @@ -1669,14 +1670,14 @@ public class UpdateSite { } } PluginWrapper pw = getInstalled(); - if(pw != null) { // JENKINS-34494 - check for this plugin being disabled + if (pw != null) { // JENKINS-34494 - check for this plugin being disabled Future enableJob = null; - if(!pw.isEnabled()) { + if (!pw.isEnabled()) { UpdateCenter.EnableJob job = uc.new EnableJob(UpdateSite.this, null, this, dynamicLoad); job.setCorrelationId(correlationId); enableJob = uc.addJob(job); } - if(pw.getVersionNumber().equals(new VersionNumber(version))) { + if (pw.getVersionNumber().equals(new VersionNumber(version))) { return enableJob != null ? enableJob : uc.addJob(uc.new NoOpJob(UpdateSite.this, null, this)); } } @@ -1697,6 +1698,7 @@ public class UpdateSite { /** * Making the installation web bound. */ + @RequirePOST public HttpResponse doInstall() throws IOException { deploy(false); @@ -1725,6 +1727,6 @@ public class UpdateSite { // The name uses UpdateCenter for compatibility reason. @SuppressFBWarnings(value = "MS_SHOULD_BE_FINAL", justification = "for script console") - public static boolean neverUpdate = SystemProperties.getBoolean(UpdateCenter.class.getName()+".never"); + public static boolean neverUpdate = SystemProperties.getBoolean(UpdateCenter.class.getName() + ".never"); } diff --git a/core/src/main/java/hudson/model/UsageStatistics.java b/core/src/main/java/hudson/model/UsageStatistics.java index 1b57d728240345d4b7f9b1a1ec57a52207ce94b2..0a13c0983b160e58e12f7d771b0947e3c11274e7 100644 --- a/core/src/main/java/hudson/model/UsageStatistics.java +++ b/core/src/main/java/hudson/model/UsageStatistics.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import static java.util.concurrent.TimeUnit.DAYS; @@ -102,10 +103,10 @@ public class UsageStatistics extends PageDecorator implements PersistentDescript */ public boolean isDue() { // user opted out. no data collection. - if(!Jenkins.get().isUsageStatisticsCollected() || DISABLED) return false; + if (!Jenkins.get().isUsageStatisticsCollected() || DISABLED) return false; long now = System.currentTimeMillis(); - if(now - lastAttempt > DAY) { + if (now - lastAttempt > DAY) { lastAttempt = now; return true; } @@ -116,7 +117,7 @@ public class UsageStatistics extends PageDecorator implements PersistentDescript try { if (key == null) { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); - key = (RSAPublicKey)keyFactory.generatePublic(new X509EncodedKeySpec(Util.fromHexString(keyImage))); + key = (RSAPublicKey) keyFactory.generatePublic(new X509EncodedKeySpec(Util.fromHexString(keyImage))); } return key; } catch (GeneralSecurityException e) { @@ -132,43 +133,43 @@ public class UsageStatistics extends PageDecorator implements PersistentDescript Jenkins j = Jenkins.get(); JSONObject o = new JSONObject(); - o.put("stat",1); + o.put("stat", 1); o.put("install", j.getLegacyInstanceId()); o.put("servletContainer", j.servletContext.getServerInfo()); o.put("version", Jenkins.VERSION); List nodes = new ArrayList<>(); - for( Computer c : j.getComputers() ) { + for (Computer c : j.getComputers()) { JSONObject n = new JSONObject(); - if(c.getNode()==j) { - n.put("master",true); + if (c.getNode() == j) { + n.put("master", true); n.put("jvm-vendor", System.getProperty("java.vm.vendor")); n.put("jvm-name", System.getProperty("java.vm.name")); n.put("jvm-version", System.getProperty("java.version")); } - n.put("executors",c.getNumExecutors()); + n.put("executors", c.getNumExecutors()); ArchitectureMonitor.DescriptorImpl descriptor = j.getDescriptorByType(ArchitectureMonitor.DescriptorImpl.class); n.put("os", descriptor.get(c)); nodes.add(n); } - o.put("nodes",nodes); + o.put("nodes", nodes); List plugins = new ArrayList<>(); - for( PluginWrapper pw : j.getPluginManager().getPlugins() ) { - if(!pw.isActive()) continue; // treat disabled plugins as if they are uninstalled + for (PluginWrapper pw : j.getPluginManager().getPlugins()) { + if (!pw.isActive()) continue; // treat disabled plugins as if they are uninstalled JSONObject p = new JSONObject(); - p.put("name",pw.getShortName()); - p.put("version",pw.getVersion()); + p.put("name", pw.getShortName()); + p.put("version", pw.getVersion()); plugins.add(p); } - o.put("plugins",plugins); + o.put("plugins", plugins); JSONObject jobs = new JSONObject(); // capture the descriptors as these should be small compared with the number of items // so we will walk all items only once and we can short-cut the search of descriptors TopLevelItemDescriptor[] descriptors = Items.all().toArray(new TopLevelItemDescriptor[0]); int[] counts = new int[descriptors.length]; - for (TopLevelItem item: j.allItems(TopLevelItem.class)) { + for (TopLevelItem item : j.allItems(TopLevelItem.class)) { TopLevelItemDescriptor d = item.getDescriptor(); for (int i = 0; i < descriptors.length; i++) { if (d == descriptors[i]) { @@ -181,13 +182,13 @@ public class UsageStatistics extends PageDecorator implements PersistentDescript for (int i = 0; i < descriptors.length; i++) { jobs.put(descriptors[i].getJsonSafeClassName(), counts[i]); } - o.put("jobs",jobs); + o.put("jobs", jobs); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); // json -> UTF-8 encode -> gzip -> encrypt -> base64 -> string - try (OutputStream cipheros = new CombinedCipherOutputStream(baos,getKey(),"AES"); + try (OutputStream cipheros = new CombinedCipherOutputStream(baos, getKey(), "AES"); OutputStream zipos = new GZIPOutputStream(cipheros); OutputStreamWriter w = new OutputStreamWriter(zipos, StandardCharsets.UTF_8)) { o.write(w); @@ -214,7 +215,7 @@ public class UsageStatistics extends PageDecorator implements PersistentDescript Jenkins.get().setNoUsageStatistics(json.has("usageStatisticsCollected") ? null : true); return true; } catch (IOException e) { - throw new FormException(e,"usageStatisticsCollected"); + throw new FormException(e, "usageStatisticsCollected"); } } @@ -237,12 +238,12 @@ public class UsageStatistics extends PageDecorator implements PersistentDescript // the rest of the data will be encrypted by this symmetric cipher Cipher sym = Secret.getCipher(algorithm); - sym.init(Cipher.ENCRYPT_MODE,symKey, keyAlgorithm.equals(algorithm) ? null : new IvParameterSpec(symKey.getEncoded())); - super.out = new CipherOutputStream(out,sym); + sym.init(Cipher.ENCRYPT_MODE, symKey, keyAlgorithm.equals(algorithm) ? null : new IvParameterSpec(symKey.getEncoded())); + super.out = new CipherOutputStream(out, sym); } public CombinedCipherOutputStream(OutputStream out, RSAKey key, String algorithm) throws IOException, GeneralSecurityException { - this(out,toCipher(key,Cipher.ENCRYPT_MODE),algorithm); + this(out, toCipher(key, Cipher.ENCRYPT_MODE), algorithm); } } @@ -261,18 +262,18 @@ public class UsageStatistics extends PageDecorator implements PersistentDescript String keyAlgorithm = getKeyAlgorithm(algorithm); // first read the symmetric key cipher - byte[] symKeyBytes = new byte[keyLength/8]; + byte[] symKeyBytes = new byte[keyLength / 8]; new DataInputStream(in).readFully(symKeyBytes); - SecretKey symKey = new SecretKeySpec(asym.doFinal(symKeyBytes),keyAlgorithm); + SecretKey symKey = new SecretKeySpec(asym.doFinal(symKeyBytes), keyAlgorithm); // the rest of the data will be decrypted by this symmetric cipher Cipher sym = Secret.getCipher(algorithm); - sym.init(Cipher.DECRYPT_MODE,symKey, keyAlgorithm.equals(algorithm) ? null : new IvParameterSpec(symKey.getEncoded())); - super.in = new CipherInputStream(in,sym); + sym.init(Cipher.DECRYPT_MODE, symKey, keyAlgorithm.equals(algorithm) ? null : new IvParameterSpec(symKey.getEncoded())); + super.in = new CipherInputStream(in, sym); } public CombinedCipherInputStream(InputStream in, RSAKey key, String algorithm) throws IOException, GeneralSecurityException { - this(in,toCipher(key,Cipher.DECRYPT_MODE),algorithm,key.getModulus().bitLength()); + this(in, toCipher(key, Cipher.DECRYPT_MODE), algorithm, key.getModulus().bitLength()); } } @@ -283,7 +284,7 @@ public class UsageStatistics extends PageDecorator implements PersistentDescript private static Cipher toCipher(RSAKey key, int mode) throws GeneralSecurityException { Cipher cipher = Cipher.getInstance("RSA"); - cipher.init(mode, (Key)key); + cipher.init(mode, (Key) key); return cipher; } @@ -300,5 +301,5 @@ public class UsageStatistics extends PageDecorator implements PersistentDescript private static final long DAY = DAYS.toMillis(1); @SuppressFBWarnings(value = "MS_SHOULD_BE_FINAL", justification = "for script console") - public static boolean DISABLED = SystemProperties.getBoolean(UsageStatistics.class.getName()+".disabled"); + public static boolean DISABLED = SystemProperties.getBoolean(UsageStatistics.class.getName() + ".disabled"); } diff --git a/core/src/main/java/hudson/model/User.java b/core/src/main/java/hudson/model/User.java index f88be4dd7ba23f715b35bf8f59d1aeb43b55f627..bc2a86138d1ae518f544f4b8fc6405554b28ca60 100644 --- a/core/src/main/java/hudson/model/User.java +++ b/core/src/main/java/hudson/model/User.java @@ -22,6 +22,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import com.infradna.tool.bridge_method_injector.WithBridgeMethods; @@ -221,7 +222,7 @@ public class User extends AbstractModelObject implements AccessControlled, Descr private void loadFromUserConfigFile(String userId) { XmlFile config = getConfigFile(); try { - if ( config != null && config.exists()) { + if (config != null && config.exists()) { config.unmarshal(this); this.id = userId; } @@ -745,19 +746,20 @@ public class User extends AbstractModelObject implements AccessControlled, Descr private static File getConfigFileFor(String id) { return new File(getUserFolderFor(id), "config.xml"); } - - private static File getUserFolderFor(String id){ + + private static File getUserFolderFor(String id) { return new File(getRootDir(), idStrategy().filenameOf(id)); } /** * Returns the folder that store all the user information. * Useful for plugins to save a user-specific file aside the config.xml. * Exposes implementation details that may be subject to change. - * + * * @return The folder containing the user configuration files or {@code null} if the user was not yet saved. * * @since 2.129 */ + public @CheckForNull File getUserFolder() { return getExistingUserFolder(); } diff --git a/core/src/main/java/hudson/model/UserIdMapper.java b/core/src/main/java/hudson/model/UserIdMapper.java index d84042a58906618cc752a454c250479d5e7f58de..93e6a03fd0f5cea29433dbd845b8f0b02be5b9d7 100644 --- a/core/src/main/java/hudson/model/UserIdMapper.java +++ b/core/src/main/java/hudson/model/UserIdMapper.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import edu.umd.cs.findbugs.annotations.CheckForNull; diff --git a/core/src/main/java/hudson/model/UserIdMigrator.java b/core/src/main/java/hudson/model/UserIdMigrator.java index b3e42d394ef6e4a9b08f6938a729e47f28ac8147..4af152b6acb48521c1f77aafd650dc934e8a20e9 100644 --- a/core/src/main/java/hudson/model/UserIdMigrator.java +++ b/core/src/main/java/hudson/model/UserIdMigrator.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import java.io.File; diff --git a/core/src/main/java/hudson/model/UserProperties.java b/core/src/main/java/hudson/model/UserProperties.java index 2f521b31f401df5bc1d719b5b97f108b720ee129..cb840e40752da60f2922034695e7eb36dc05607f 100644 --- a/core/src/main/java/hudson/model/UserProperties.java +++ b/core/src/main/java/hudson/model/UserProperties.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import hudson.Extension; diff --git a/core/src/main/java/hudson/model/UserProperty.java b/core/src/main/java/hudson/model/UserProperty.java index f0d7ce5b3ed74ae0cc5d02921d505089062a20d0..a9b9dbae7acd946e848c1ee8a79278fe20de8333 100644 --- a/core/src/main/java/hudson/model/UserProperty.java +++ b/core/src/main/java/hudson/model/UserProperty.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import hudson.DescriptorExtensionList; @@ -70,12 +71,12 @@ public abstract class UserProperty implements ReconfigurableDescribable all() { + public static DescriptorExtensionList all() { return Jenkins.get().getDescriptorList(UserProperty.class); } @Override public UserProperty reconfigure(StaplerRequest req, JSONObject form) throws FormException { - return form==null ? null : getDescriptor().newInstance(req, form); + return form == null ? null : getDescriptor().newInstance(req, form); } } diff --git a/core/src/main/java/hudson/model/UserPropertyDescriptor.java b/core/src/main/java/hudson/model/UserPropertyDescriptor.java index a29ab777c88067fefd76523828c1ebd062531e22..22e05ea59afff9156dcefbae965177d2f0d11b26 100644 --- a/core/src/main/java/hudson/model/UserPropertyDescriptor.java +++ b/core/src/main/java/hudson/model/UserPropertyDescriptor.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; /** diff --git a/core/src/main/java/hudson/model/View.java b/core/src/main/java/hudson/model/View.java index b743d91834e484f1ccf153b27ad15b1d4a5140fe..c2c2c6b73bfa79b65cceb762e53d6d45dbc16a84 100644 --- a/core/src/main/java/hudson/model/View.java +++ b/core/src/main/java/hudson/model/View.java @@ -22,6 +22,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST; @@ -178,7 +179,7 @@ public abstract class View extends AbstractModelObject implements AccessControll * List of {@link ViewProperty}s configured for this view. * @since 1.406 */ - private volatile DescribableList properties = new PropertyList(this); + private volatile DescribableList properties = new PropertyList(this); protected View(String name) { this.name = name; @@ -193,7 +194,7 @@ public abstract class View extends AbstractModelObject implements AccessControll * Gets all the items in this collection in a read-only view. */ @NonNull - @Exported(name="jobs") + @Exported(name = "jobs") public abstract Collection getItems(); /** @@ -209,7 +210,7 @@ public abstract class View extends AbstractModelObject implements AccessControll if (this instanceof ViewGroup) { final Collection items = new LinkedHashSet<>(getItems()); - for(View view: ((ViewGroup) this).getViews()) { + for (View view : ((ViewGroup) this).getViews()) { items.addAll(view.getAllItems()); } return Collections.unmodifiableCollection(items); @@ -242,7 +243,7 @@ public abstract class View extends AbstractModelObject implements AccessControll * * @see #rename(String) */ - @Exported(visibility=2,name="name") + @Exported(visibility = 2, name = "name") @NonNull public String getViewName() { return name; @@ -252,13 +253,13 @@ public abstract class View extends AbstractModelObject implements AccessControll * Renames this view. */ public void rename(String newName) throws Failure, FormException { - if(name.equals(newName)) return; // noop + if (name.equals(newName)) return; // noop Jenkins.checkGoodName(newName); - if(owner.getView(newName)!=null) - throw new FormException(Messages.Hudson_ViewAlreadyExists(newName),"name"); + if (owner.getView(newName) != null) + throw new FormException(Messages.Hudson_ViewAlreadyExists(newName), "name"); String oldName = name; name = newName; - owner.onViewRenamed(this,oldName,newName); + owner.onViewRenamed(this, oldName, newName); } /** @@ -303,7 +304,7 @@ public abstract class View extends AbstractModelObject implements AccessControll * Gets the view properties configured for this view. * @since 1.406 */ - public DescribableList getProperties() { + public DescribableList getProperties() { // readResolve was the best place to do this, but for compatibility reasons, // this class can no longer have readResolve() (the mechanism itself isn't suitable for class hierarchy) // see JENKINS-9431 @@ -355,7 +356,7 @@ public abstract class View extends AbstractModelObject implements AccessControll * List of all {@link ViewProperty}s exposed primarily for the remoting API. * @since 1.406 */ - @Exported(name="property",inline=true) + @Exported(name = "property", inline = true) public List getAllProperties() { return getProperties().toList(); } @@ -440,7 +441,7 @@ public abstract class View extends AbstractModelObject implements AccessControll * If true, this is a view that renders the top page of Hudson. */ public boolean isDefault() { - return getOwner().getPrimaryView()==this; + return getOwner().getPrimaryView() == this; } public List getComputers() { @@ -514,7 +515,7 @@ public abstract class View extends AbstractModelObject implements AccessControll } // Check root project for sub-job projects (e.g. matrix jobs). if (item.task instanceof AbstractProject) { - AbstractProject project = (AbstractProject) item.task; + AbstractProject project = (AbstractProject) item.task; if (viewItems.contains(project.getRootProject())) { return true; } @@ -542,7 +543,7 @@ public abstract class View extends AbstractModelObject implements AccessControll * empty string when this is the default view). */ public String getUrl() { - return isDefault() ? (owner!=null ? owner.getUrl() : "") : getViewUrl(); + return isDefault() ? (owner != null ? owner.getUrl() : "") : getViewUrl(); } /** @@ -550,7 +551,7 @@ public abstract class View extends AbstractModelObject implements AccessControll * even for the default view. */ public String getViewUrl() { - return (owner!=null ? owner.getUrl() : "") + "view/" + Util.rawEncode(getViewName()) + '/'; + return (owner != null ? owner.getUrl() : "") + "view/" + Util.rawEncode(getViewName()) + '/'; } @Override public String toString() { @@ -589,7 +590,7 @@ public abstract class View extends AbstractModelObject implements AccessControll public Object getDynamic(String token) { for (Action a : getActions()) { String url = a.getUrlName(); - if (url==null) continue; + if (url == null) continue; if (url.equals(token)) return a; } @@ -599,9 +600,9 @@ public abstract class View extends AbstractModelObject implements AccessControll /** * Gets the absolute URL of this view. */ - @Exported(visibility=2,name="url") + @Exported(visibility = 2, name = "url") public String getAbsoluteUrl() { - return Jenkins.get().getRootUrl()+getUrl(); + return Jenkins.get().getRootUrl() + getUrl(); } public Api getApi() { @@ -630,7 +631,7 @@ public abstract class View extends AbstractModelObject implements AccessControll @Deprecated public void onJobRenamed(Item item, String oldName, String newName) {} - @ExportedBean(defaultVisibility=2) + @ExportedBean(defaultVisibility = 2) public static final class UserInfo implements Comparable { private final User user; /** @@ -640,12 +641,12 @@ public abstract class View extends AbstractModelObject implements AccessControll /** * Which project did this user commit? Can be null. */ - private Job project; + private Job project; /** @see UserAvatarResolver */ String avatar; - UserInfo(User user, Job p, Calendar lastChange) { + UserInfo(User user, Job p, Calendar lastChange) { this.user = user; this.project = p; this.lastChange = lastChange; @@ -663,11 +664,11 @@ public abstract class View extends AbstractModelObject implements AccessControll @Deprecated public AbstractProject getProject() { - return project instanceof AbstractProject ? (AbstractProject)project : null; + return project instanceof AbstractProject ? (AbstractProject) project : null; } - @Exported(name="project") - public Job getJob() { + @Exported(name = "project") + public Job getJob() { return project; } @@ -675,13 +676,13 @@ public abstract class View extends AbstractModelObject implements AccessControll * Returns a human-readable string representation of when this user was last active. */ public String getLastChangeTimeString() { - if(lastChange==null) return "N/A"; - long duration = new GregorianCalendar().getTimeInMillis()- ordinal(); + if (lastChange == null) return "N/A"; + long duration = new GregorianCalendar().getTimeInMillis() - ordinal(); return Util.getTimeSpanString(duration); } public String getTimeSortKey() { - if(lastChange==null) return "-"; + if (lastChange == null) return "-"; return Util.XS_DATETIME_FORMATTER.format(lastChange.getTime()); } @@ -693,7 +694,7 @@ public abstract class View extends AbstractModelObject implements AccessControll } private long ordinal() { - if(lastChange==null) return 0; + if (lastChange == null) return 0; return lastChange.getTimeInMillis(); } } @@ -732,12 +733,12 @@ public abstract class View extends AbstractModelObject implements AccessControll public People(Jenkins parent) { this.parent = parent; // for Hudson, really load all users - Map users = getUserInfo(parent.getItems()); + Map users = getUserInfo(parent.getItems()); User unknown = User.getUnknown(); for (User u : User.getAll()) { - if(u==unknown) continue; // skip the special 'unknown' user - if(!users.containsKey(u)) - users.put(u,new UserInfo(u,null,null)); + if (u == unknown) continue; // skip the special 'unknown' user + if (!users.containsKey(u)) + users.put(u, new UserInfo(u, null, null)); } this.users = toList(users); } @@ -747,14 +748,14 @@ public abstract class View extends AbstractModelObject implements AccessControll this.users = toList(getUserInfo(parent.getItems())); } - private Map getUserInfo(Collection items) { - Map users = new HashMap<>(); + private Map getUserInfo(Collection items) { + Map users = new HashMap<>(); for (Item item : items) { for (Job job : item.getAllJobs()) { RunList> runs = job.getBuilds(); for (Run r : runs) { if (r instanceof RunWithSCM) { - RunWithSCM runWithSCM = (RunWithSCM) r; + RunWithSCM runWithSCM = (RunWithSCM) r; for (ChangeLogSet c : runWithSCM.getChangeSets()) { for (ChangeLogSet.Entry entry : c) { @@ -776,7 +777,7 @@ public abstract class View extends AbstractModelObject implements AccessControll return users; } - private List toList(Map users) { + private List toList(Map users) { ArrayList list = new ArrayList<>(users.values()); Collections.sort(list); return Collections.unmodifiableList(list); @@ -795,9 +796,9 @@ public abstract class View extends AbstractModelObject implements AccessControll for (Job job : item.getAllJobs()) { RunList> runs = job.getBuilds(); - for (Run r : runs) { + for (Run r : runs) { if (r instanceof RunWithSCM) { - RunWithSCM runWithSCM = (RunWithSCM) r; + RunWithSCM runWithSCM = (RunWithSCM) r; for (ChangeLogSet c : runWithSCM.getChangeSets()) { for (ChangeLogSet.Entry entry : c) { User user = entry.getAuthor(); @@ -821,7 +822,7 @@ public abstract class View extends AbstractModelObject implements AccessControll private final Collection items; private final User unknown; - private final Map users = new HashMap<>(); + private final Map users = new HashMap<>(); private final Set modified = new HashSet<>(); private final String iconSize; public final ModelObject parent; @@ -848,7 +849,7 @@ public abstract class View extends AbstractModelObject implements AccessControll @Override protected void compute() throws Exception { int itemCount = 0; for (Item item : items) { - for (Job job : item.getAllJobs()) { + for (Job job : item.getAllJobs()) { RunList> builds = job.getBuilds(); int buildCount = 0; for (Run r : builds) { @@ -924,7 +925,7 @@ public abstract class View extends AbstractModelObject implements AccessControll accumulate("avatar", i.avatar != null ? i.avatar : Stapler.getCurrentRequest().getContextPath() + Functions.getResourcePath() + "/images/svgs/person.svg"). accumulate("timeSortKey", i.getTimeSortKey()). accumulate("lastChangeTimeString", i.getLastChangeTimeString()); - Job p = i.getJob(); + Job p = i.getJob(); if (p != null) { entry.accumulate("projectUrl", p.getUrl()).accumulate("projectFullDisplayName", p.getFullDisplayName()); } @@ -956,9 +957,9 @@ public abstract class View extends AbstractModelObject implements AccessControll } void addDisplayNamesToSearchIndex(SearchIndexBuilder sib, Collection items) { - for(TopLevelItem item : items) { + for (TopLevelItem item : items) { - if(LOGGER.isLoggable(Level.FINE)) { + if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(String.format("Adding url=%s,displayName=%s", item.getSearchUrl(), item.getDisplayName())); } @@ -973,11 +974,13 @@ public abstract class View extends AbstractModelObject implements AccessControll * @since 2.200 */ protected void makeSearchIndex(SearchIndexBuilder sib) { - sib.add(new CollectionSearchIndex() {// for jobs in the view + sib.add(new CollectionSearchIndex() { // for jobs in the view @Override protected TopLevelItem get(String key) { return getItem(key); } + @Override protected Collection all() { return getItems(); } + @Override protected String getName(TopLevelItem o) { // return the name instead of the display for suggestion searching @@ -1001,7 +1004,7 @@ public abstract class View extends AbstractModelObject implements AccessControll * Accepts the new description. */ @RequirePOST - public synchronized void doSubmitDescription( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { + public synchronized void doSubmitDescription(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { checkPermission(CONFIGURE); description = req.getParameter("description"); @@ -1015,7 +1018,7 @@ public abstract class View extends AbstractModelObject implements AccessControll * Subtypes should override the {@link #submit(StaplerRequest)} method. */ @POST - public final synchronized void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException { + public final synchronized void doConfigSubmit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException { checkPermission(CONFIGURE); submit(req); @@ -1030,7 +1033,7 @@ public abstract class View extends AbstractModelObject implements AccessControll save(); - FormApply.success("../" + Util.rawEncode(name)).generateResponse(req,rsp,this); + FormApply.success("../" + Util.rawEncode(name)).generateResponse(req, rsp, this); } /** @@ -1049,7 +1052,7 @@ public abstract class View extends AbstractModelObject implements AccessControll owner.deleteView(this); - rsp.sendRedirect2(req.getContextPath()+"/" + owner.getUrl()); + rsp.sendRedirect2(req.getContextPath() + "/" + owner.getUrl()); } @@ -1063,7 +1066,7 @@ public abstract class View extends AbstractModelObject implements AccessControll * @return * null if fails. */ - public abstract Item doCreateItem( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException; + public abstract Item doCreateItem(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException; /** * Makes sure that the given name is good as a job name. @@ -1151,11 +1154,11 @@ public abstract class View extends AbstractModelObject implements AccessControll return categories; } - public void doRssAll( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { + public void doRssAll(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { RSS.rss(req, rsp, "Jenkins:" + getDisplayName() + " (all builds)", getUrl(), getBuilds().newBuilds()); } - public void doRssFailed( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { + public void doRssFailed(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { RSS.rss(req, rsp, "Jenkins:" + getDisplayName() + " (failed builds)", getUrl(), getBuilds().failureOnly().newBuilds()); } @@ -1167,13 +1170,13 @@ public abstract class View extends AbstractModelObject implements AccessControll return new BuildTimelineWidget(getBuilds()); } - public void doRssLatest( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { + public void doRssLatest(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { List lastBuilds = new ArrayList<>(); for (TopLevelItem item : getItems()) { if (item instanceof Job) { Job job = (Job) item; Run lb = job.getLastBuild(); - if(lb!=null) lastBuilds.add(lb); + if (lb != null) lastBuilds.add(lb); } } RSS.rss(req, rsp, "Jenkins:" + getDisplayName() + " (latest builds)", getUrl(), RunList.fromRuns(lastBuilds), Run.FEED_ADAPTER_LATEST); @@ -1230,12 +1233,12 @@ public abstract class View extends AbstractModelObject implements AccessControll // data XMLUtils.safeTransform(source, new StreamResult(out)); out.close(); - } catch (TransformerException|SAXException e) { + } catch (TransformerException | SAXException e) { throw new IOException("Failed to persist configuration.xml", e); } // try to reflect the changes by reloading - try (InputStream in = new BufferedInputStream(new ByteArrayInputStream(out.toString().getBytes(StandardCharsets.UTF_8)))){ + try (InputStream in = new BufferedInputStream(new ByteArrayInputStream(out.toString().getBytes(StandardCharsets.UTF_8)))) { // Do not allow overwriting view name as it might collide with another // view in same ViewGroup and might not satisfy Jenkins.checkGoodName. String oldname = name; @@ -1244,14 +1247,14 @@ public abstract class View extends AbstractModelObject implements AccessControll if (!o.getClass().equals(getClass())) { // ensure that we've got the same view type. extending this code to support updating // to different view type requires destroying & creating a new view type - throw new IOException("Expecting view type: "+this.getClass()+" but got: "+o.getClass()+" instead." + + throw new IOException("Expecting view type: " + this.getClass() + " but got: " + o.getClass() + " instead." + "\nShould you needed to change to a new view type, you must first delete and then re-create " + "the view with the new view type."); } name = oldname; owner = oldOwner; - } catch (StreamException | ConversionException | Error e) {// mostly reflection errors - throw new IOException("Unable to read",e); + } catch (StreamException | ConversionException | Error e) { // mostly reflection errors + throw new IOException("Unable to read", e); } save(); } @@ -1260,7 +1263,7 @@ public abstract class View extends AbstractModelObject implements AccessControll public ModelObjectWithContextMenu.ContextMenu doChildrenContextMenu(StaplerRequest request, StaplerResponse response) throws Exception { ModelObjectWithContextMenu.ContextMenu m = new ModelObjectWithContextMenu.ContextMenu(); for (TopLevelItem i : getItems()) - m.add(i.getShortUrl(),i.getDisplayName()); + m.add(i.getShortUrl(), i.getDisplayName()); return m; } @@ -1275,7 +1278,7 @@ public abstract class View extends AbstractModelObject implements AccessControll /** * Returns all the registered {@link ViewDescriptor}s. */ - public static DescriptorExtensionList all() { + public static DescriptorExtensionList all() { return Jenkins.get().getDescriptorList(View.class); } @@ -1308,14 +1311,14 @@ public abstract class View extends AbstractModelObject implements AccessControll public static final Comparator SORTER = Comparator.comparing(View::getViewName); - public static final PermissionGroup PERMISSIONS = new PermissionGroup(View.class,Messages._View_Permissions_Title()); + public static final PermissionGroup PERMISSIONS = new PermissionGroup(View.class, Messages._View_Permissions_Title()); /** * Permission to create new views. */ - public static final Permission CREATE = new Permission(PERMISSIONS,"Create", Messages._View_CreatePermission_Description(), Permission.CREATE, PermissionScope.ITEM_GROUP); - public static final Permission DELETE = new Permission(PERMISSIONS,"Delete", Messages._View_DeletePermission_Description(), Permission.DELETE, PermissionScope.ITEM_GROUP); - public static final Permission CONFIGURE = new Permission(PERMISSIONS,"Configure", Messages._View_ConfigurePermission_Description(), Permission.CONFIGURE, PermissionScope.ITEM_GROUP); - public static final Permission READ = new Permission(PERMISSIONS,"Read", Messages._View_ReadPermission_Description(), Permission.READ, PermissionScope.ITEM_GROUP); + public static final Permission CREATE = new Permission(PERMISSIONS, "Create", Messages._View_CreatePermission_Description(), Permission.CREATE, PermissionScope.ITEM_GROUP); + public static final Permission DELETE = new Permission(PERMISSIONS, "Delete", Messages._View_DeletePermission_Description(), Permission.DELETE, PermissionScope.ITEM_GROUP); + public static final Permission CONFIGURE = new Permission(PERMISSIONS, "Configure", Messages._View_ConfigurePermission_Description(), Permission.CONFIGURE, PermissionScope.ITEM_GROUP); + public static final Permission READ = new Permission(PERMISSIONS, "Read", Messages._View_ReadPermission_Description(), Permission.READ, PermissionScope.ITEM_GROUP); @SuppressFBWarnings(value = "RV_RETURN_VALUE_IGNORED_NO_SIDE_EFFECT", justification = "to guard against potential future compiler optimizations") @Initializer(before = InitMilestone.SYSTEM_CONFIG_LOADED) @@ -1350,11 +1353,11 @@ public abstract class View extends AbstractModelObject implements AccessControll String name = req.getParameter("name"); Jenkins.checkGoodName(name); - if(owner.getView(name)!=null) + if (owner.getView(name) != null) throw new Failure(Messages.Hudson_ViewAlreadyExists(name)); - if (mode==null || mode.length()==0) { - if(isXmlSubmission) { + if (mode == null || mode.length() == 0) { + if (isXmlSubmission) { View v = createViewFromXML(name, req.getInputStream()); owner.getACL().checkCreatePermission(owner, v.getDescriptor()); v.owner = owner; @@ -1382,7 +1385,7 @@ public abstract class View extends AbstractModelObject implements AccessControll v.owner = owner; // redirect to the config screen - rsp.sendRedirect2(req.getContextPath()+'/'+v.getUrl()+v.getPostConstructLandingPage()); + rsp.sendRedirect2(req.getContextPath() + '/' + v.getUrl() + v.getPostConstructLandingPage()); return v; } @@ -1392,11 +1395,11 @@ public abstract class View extends AbstractModelObject implements AccessControll String from = req.getParameter("from"); View src = owner.getView(from); - if(src==null) { - if(Util.fixEmpty(from)==null) + if (src == null) { + if (Util.fixEmpty(from) == null) throw new Failure("Specify which view to copy"); else - throw new Failure("No such view: "+from); + throw new Failure("No such view: " + from); } String xml = Jenkins.XSTREAM.toXML(src); v = createViewFromXML(name, new ByteArrayInputStream(xml.getBytes(Charset.defaultCharset()))); @@ -1415,12 +1418,12 @@ public abstract class View extends AbstractModelObject implements AccessControll if (name != null) v.name = name; Jenkins.checkGoodName(v.name); return v; - } catch(StreamException|ConversionException|Error e) {// mostly reflection errors - throw new IOException("Unable to read",e); + } catch (StreamException | ConversionException | Error e) { // mostly reflection errors + throw new IOException("Unable to read", e); } } - public static class PropertyList extends DescribableList { + public static class PropertyList extends DescribableList { private PropertyList(View owner) { super(owner); } @@ -1429,7 +1432,7 @@ public abstract class View extends AbstractModelObject implements AccessControll } public View getOwner() { - return (View)owner; + return (View) owner; } @Override diff --git a/core/src/main/java/hudson/model/ViewDescriptor.java b/core/src/main/java/hudson/model/ViewDescriptor.java index 3b31a2f710635df2c91d6dba7e5e1d2327edc8d0..7a77f4e553544e58548399444856fd6d447b333b 100644 --- a/core/src/main/java/hudson/model/ViewDescriptor.java +++ b/core/src/main/java/hudson/model/ViewDescriptor.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import edu.umd.cs.findbugs.annotations.CheckForNull; @@ -70,7 +71,7 @@ public abstract class ViewDescriptor extends Descriptor { * Jelly fragment included in the "new view" page. */ public final String getNewViewDetailPage() { - return '/'+clazz.getName().replace('.','/').replace('$','/')+"/newViewDetail.jelly"; + return '/' + clazz.getName().replace('.', '/').replace('$', '/') + "/newViewDetail.jelly"; } protected ViewDescriptor(Class clazz) { @@ -142,7 +143,7 @@ public abstract class ViewDescriptor extends Descriptor { // no custom name, no need to check return FormValidation.ok(); } - for (View v: view.owner.getViews()) { + for (View v : view.owner.getViews()) { if (v.getViewName().equals(view.getViewName())) { continue; } diff --git a/core/src/main/java/hudson/model/ViewGroup.java b/core/src/main/java/hudson/model/ViewGroup.java index d0e9f95cdbb9d85a554d14ae6d89a97a1789d117..1072f394322be9c4058e13faf209978cd937886c 100644 --- a/core/src/main/java/hudson/model/ViewGroup.java +++ b/core/src/main/java/hudson/model/ViewGroup.java @@ -1,19 +1,19 @@ /* * The MIT License - * + * * Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi, * Tom Huybrechts, Alan Harder - * + * * 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 @@ -22,6 +22,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import edu.umd.cs.findbugs.annotations.NonNull; @@ -157,5 +158,5 @@ public interface ViewGroup extends Saveable, ModelObject, AccessControlled { default List getViewActions() { return Jenkins.get().getActions(); } - + } diff --git a/core/src/main/java/hudson/model/ViewGroupMixIn.java b/core/src/main/java/hudson/model/ViewGroupMixIn.java index 9505e47cb5c6f38e0dcf198b9df64f9c1bbd8d1b..0494758071528c081b87f158f7c31f80c7106f3a 100644 --- a/core/src/main/java/hudson/model/ViewGroupMixIn.java +++ b/core/src/main/java/hudson/model/ViewGroupMixIn.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import edu.umd.cs.findbugs.annotations.CheckForNull; @@ -132,7 +133,7 @@ public abstract class ViewGroupMixIn { // Fallback to subview of primary view if it is a ViewGroup View pv = getPrimaryView(); if (pv instanceof ViewGroup) - return ((ViewGroup)pv).getView(name); + return ((ViewGroup) pv).getView(name); if (pv instanceof AllView && AllView.DEFAULT_VIEW_NAME.equals(pv.name)) { // JENKINS-38606: primary view is the default AllView, is somebody using an old link to localized form? for (Locale l : Locale.getAvailableLocales()) { @@ -169,7 +170,7 @@ public abstract class ViewGroupMixIn { @CheckForNull public View getPrimaryView() { View v = getView(primaryView()); - if(v==null && !views().isEmpty()) // fallback + if (v == null && !views().isEmpty()) // fallback v = views().get(0); return v; } diff --git a/core/src/main/java/hudson/model/ViewJob.java b/core/src/main/java/hudson/model/ViewJob.java index 1a69809e154b65c9bde6d2a87d4f63bb5f3fadc0..5e8227450bde5c7ab7db089974f77e8f3035485f 100644 --- a/core/src/main/java/hudson/model/ViewJob.java +++ b/core/src/main/java/hudson/model/ViewJob.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; @@ -47,8 +48,8 @@ import org.kohsuke.stapler.StaplerResponse; * * @author Kohsuke Kawaguchi */ -public abstract class ViewJob, RunT extends Run> - extends Job { +public abstract class ViewJob, RunT extends Run> + extends Job { private static final Logger LOGGER = Logger.getLogger(ViewJob.class.getName()); @@ -84,11 +85,11 @@ public abstract class ViewJob, RunT extends Run< */ @Deprecated protected ViewJob(Jenkins parent, String name) { - super(parent,name); + super(parent, name); } protected ViewJob(ItemGroup parent, String name) { - super(parent,name); + super(parent, name); } @Override @@ -103,20 +104,20 @@ public abstract class ViewJob, RunT extends Run< } @Override - protected SortedMap _getRuns() { - if(notLoaded || runs==null) { + protected SortedMap _getRuns() { + if (notLoaded || runs == null) { // if none is loaded yet, do so immediately. - synchronized(this) { - if(runs==null) + synchronized (this) { + if (runs == null) runs = new RunMap<>(); - if(notLoaded) { + if (notLoaded) { notLoaded = false; - _reload(); + _reload(); } } } - if(nextUpdate, RunT extends Run< } reloadQueue = reloadThread.reloadQueue; } - synchronized(reloadQueue) { + synchronized (reloadQueue) { reloadQueue.add(this); reloadQueue.notify(); } @@ -150,7 +151,7 @@ public abstract class ViewJob, RunT extends Run< reload(); } finally { reloadingInProgress = false; - nextUpdate = reloadPeriodically ? System.currentTimeMillis()+TimeUnit.MINUTES.toMillis(1) : Long.MAX_VALUE; + nextUpdate = reloadPeriodically ? System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(1) : Long.MAX_VALUE; } } @@ -163,8 +164,8 @@ public abstract class ViewJob, RunT extends Run< protected abstract void reload(); @Override - protected void submit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException { - super.submit(req,rsp); + protected void submit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException { + super.submit(req, rsp); // make sure to reload to reflect this config change. nextUpdate = 0; } @@ -188,12 +189,12 @@ public abstract class ViewJob, RunT extends Run< } private ViewJob getNext() throws InterruptedException { - synchronized(reloadQueue) { + synchronized (reloadQueue) { // reload operations might eat InterruptException, // so check the status every so often - while(reloadQueue.isEmpty() && !terminating()) + while (reloadQueue.isEmpty() && !terminating()) reloadQueue.wait(TimeUnit.MINUTES.toMillis(1)); - if(terminating()) + if (terminating()) throw new InterruptedException(); // terminate now ViewJob job = reloadQueue.iterator().next(); reloadQueue.remove(job); @@ -230,8 +231,8 @@ public abstract class ViewJob, RunT extends Run< *

    * We then switched to submission via HTTP, so this reloading is no longer necessary, so only do this * when explicitly requested. - * + * */ @SuppressFBWarnings(value = "MS_SHOULD_BE_FINAL", justification = "for script console") - public static boolean reloadPeriodically = SystemProperties.getBoolean(ViewJob.class.getName()+".reloadPeriodically"); + public static boolean reloadPeriodically = SystemProperties.getBoolean(ViewJob.class.getName() + ".reloadPeriodically"); } diff --git a/core/src/main/java/hudson/model/ViewProperty.java b/core/src/main/java/hudson/model/ViewProperty.java index 04d3fc4fd76745bd95ab3217db1c40ac7c364280..31ad3078d449e5bca5c8e242c9c3034e06b20ac0 100644 --- a/core/src/main/java/hudson/model/ViewProperty.java +++ b/core/src/main/java/hudson/model/ViewProperty.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import hudson.DescriptorExtensionList; @@ -63,12 +64,12 @@ public class ViewProperty implements ReconfigurableDescribable, Ex return (ViewPropertyDescriptor) Jenkins.get().getDescriptorOrDie(getClass()); } - public static DescriptorExtensionList all() { + public static DescriptorExtensionList all() { return Jenkins.get().getDescriptorList(ViewProperty.class); } @Override public ViewProperty reconfigure(StaplerRequest req, JSONObject form) throws Descriptor.FormException { - return form==null ? null : getDescriptor().newInstance(req, form); + return form == null ? null : getDescriptor().newInstance(req, form); } } diff --git a/core/src/main/java/hudson/model/ViewPropertyDescriptor.java b/core/src/main/java/hudson/model/ViewPropertyDescriptor.java index da0e0bbb516c5aa9774026fe902dd1efd77d05a3..a8d9b40082a05103414108bbbb44111e50ffde8d 100644 --- a/core/src/main/java/hudson/model/ViewPropertyDescriptor.java +++ b/core/src/main/java/hudson/model/ViewPropertyDescriptor.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; /** diff --git a/core/src/main/java/hudson/model/WorkspaceCleanupThread.java b/core/src/main/java/hudson/model/WorkspaceCleanupThread.java index e73d1976a47cfc15af65e94d096924e4af802b9f..00ef65c4a92e97c2190328ff351ec84795d89224 100644 --- a/core/src/main/java/hudson/model/WorkspaceCleanupThread.java +++ b/core/src/main/java/hudson/model/WorkspaceCleanupThread.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model; import edu.umd.cs.findbugs.annotations.NonNull; @@ -103,40 +104,40 @@ public class WorkspaceCleanupThread extends AsyncPeriodicWork { // TODO: the use of remoting is not optimal. // One remoting can execute "exists", "lastModified", and "delete" all at once. // (Could even invert master loop so that one FileCallable takes care of all known items.) - if(!dir.exists()) { + if (!dir.exists()) { LOGGER.log(Level.FINE, "Directory {0} does not exist", dir); return false; } // if younger than a month, keep it long now = new Date().getTime(); - if(dir.lastModified() + retainForDays * DAY > now) { - LOGGER.log(Level.FINE, "Directory {0} is only {1} old, so not deleting", new Object[] {dir, Util.getTimeSpanString(now-dir.lastModified())}); + if (dir.lastModified() + retainForDays * DAY > now) { + LOGGER.log(Level.FINE, "Directory {0} is only {1} old, so not deleting", new Object[] {dir, Util.getTimeSpanString(now - dir.lastModified())}); return false; } // TODO could also be good to add checkbox that lets users configure a workspace to never be auto-cleaned. // TODO check instead for SCMTriggerItem: - if (item instanceof AbstractProject) { - AbstractProject p = (AbstractProject) item; + if (item instanceof AbstractProject) { + AbstractProject p = (AbstractProject) item; Node lb = p.getLastBuiltOn(); LOGGER.log(Level.FINER, "Directory {0} is last built on {1}", new Object[] {dir, lb}); - if(lb!=null && lb.equals(n)) { + if (lb != null && lb.equals(n)) { // this is the active workspace. keep it. LOGGER.log(Level.FINE, "Directory {0} is the last workspace for {1}", new Object[] {dir, p}); return false; } - - if(!p.getScm().processWorkspaceBeforeDeletion((Job) p,dir,n)) { + + if (!p.getScm().processWorkspaceBeforeDeletion((Job) p, dir, n)) { LOGGER.log(Level.FINE, "Directory deletion of {0} is vetoed by SCM", dir); return false; } } // TODO this may only check the last build in fact: - if (item instanceof Job) { - Job j = (Job) item; + if (item instanceof Job) { + Job j = (Job) item; if (j.isBuilding()) { LOGGER.log(Level.FINE, "Job {0} is building, so not deleting", item.getFullDisplayName()); return false; @@ -153,16 +154,16 @@ public class WorkspaceCleanupThread extends AsyncPeriodicWork { * Can be used to disable workspace clean up. */ @SuppressFBWarnings(value = "MS_SHOULD_BE_FINAL", justification = "Accessible via System Groovy Scripts") - public static boolean disabled = SystemProperties.getBoolean(WorkspaceCleanupThread.class.getName()+".disabled"); + public static boolean disabled = SystemProperties.getBoolean(WorkspaceCleanupThread.class.getName() + ".disabled"); /** * How often the clean up should run. This is final as Jenkins will not reflect changes anyway. */ - public static final int recurrencePeriodHours = SystemProperties.getInteger(WorkspaceCleanupThread.class.getName()+".recurrencePeriodHours", 24); + public static final int recurrencePeriodHours = SystemProperties.getInteger(WorkspaceCleanupThread.class.getName() + ".recurrencePeriodHours", 24); /** * Number of days workspaces should be retained. */ @SuppressFBWarnings(value = "MS_SHOULD_BE_FINAL", justification = "Accessible via System Groovy Scripts") - public static int retainForDays = SystemProperties.getInteger(WorkspaceCleanupThread.class.getName()+".retainForDays", 30); + public static int retainForDays = SystemProperties.getInteger(WorkspaceCleanupThread.class.getName() + ".retainForDays", 30); } diff --git a/core/src/main/java/hudson/model/WorkspaceListener.java b/core/src/main/java/hudson/model/WorkspaceListener.java index 1fce5b907d177772d78b1cefc296042d66b405fe..4a6089164a16b2caf4df7a9263599b5bcb4b382e 100644 --- a/core/src/main/java/hudson/model/WorkspaceListener.java +++ b/core/src/main/java/hudson/model/WorkspaceListener.java @@ -5,21 +5,21 @@ import hudson.ExtensionPoint; import hudson.FilePath; public abstract class WorkspaceListener implements ExtensionPoint { - + /** * Called after a workspace is deleted successfully. */ public void afterDelete(AbstractProject project) { - + } /** * Called before a build uses a workspace. IE, before any SCM checkout. */ public void beforeUse(AbstractBuild b, FilePath workspace, BuildListener listener) { - + } - + /** * All registered {@link WorkspaceListener}s. */ diff --git a/core/src/main/java/hudson/model/labels/LabelAtom.java b/core/src/main/java/hudson/model/labels/LabelAtom.java index cca9b29ed753d3c15abcf4388b78972f9897cdb0..5c56d296a3acba35dee288f9d79cac892ff50916 100644 --- a/core/src/main/java/hudson/model/labels/LabelAtom.java +++ b/core/src/main/java/hudson/model/labels/LabelAtom.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model.labels; import com.thoughtworks.xstream.converters.MarshallingContext; @@ -67,7 +68,7 @@ import org.kohsuke.stapler.verb.POST; /** * Atomic single token label, like "foo" or "bar". - * + * * @author Kohsuke Kawaguchi * @since 1.372 */ @@ -78,7 +79,7 @@ public class LabelAtom extends Label implements Saveable { private static /* Script Console modifiable */ boolean ALLOW_FOLDER_TRAVERSAL = SystemProperties.getBoolean(LabelAtom.class.getName() + ".allowFolderTraversal"); - private DescribableList properties = + private DescribableList properties = new DescribableList<>(this); @CopyOnWrite @@ -162,7 +163,7 @@ public class LabelAtom extends Label implements Saveable { @Override public V accept(LabelVisitor visitor, P param) { - return visitor.onAtom(this,param); + return visitor.onAtom(this, param); } @Override @@ -176,7 +177,7 @@ public class LabelAtom extends Label implements Saveable { } /*package*/ XmlFile getConfigFile() { - return new XmlFile(XSTREAM, new File(Jenkins.get().root, "labels/"+name+".xml")); + return new XmlFile(XSTREAM, new File(Jenkins.get().root, "labels/" + name + ".xml")); } @Override @@ -184,22 +185,22 @@ public class LabelAtom extends Label implements Saveable { if (isInvalidName()) { throw new IOException("Invalid label"); } - if(BulkChange.contains(this)) return; + if (BulkChange.contains(this)) return; try { getConfigFile().write(this); SaveableListener.fireOnChange(this, getConfigFile()); } catch (IOException e) { - LOGGER.log(Level.WARNING, "Failed to save "+getConfigFile(),e); + LOGGER.log(Level.WARNING, "Failed to save " + getConfigFile(), e); } } public void load() { XmlFile file = getConfigFile(); - if(file.exists()) { + if (file.exists()) { try { file.unmarshal(this); } catch (IOException e) { - LOGGER.log(Level.WARNING, "Failed to load "+file, e); + LOGGER.log(Level.WARNING, "Failed to load " + file, e); } } properties.setOwner(this); @@ -218,7 +219,7 @@ public class LabelAtom extends Label implements Saveable { * Accepts the update to the node configuration. */ @POST - public void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException { + public void doConfigSubmit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException { final Jenkins app = Jenkins.get(); app.checkPermission(Jenkins.ADMINISTER); @@ -246,7 +247,7 @@ public class LabelAtom extends Label implements Saveable { */ @RequirePOST @Restricted(DoNotUse.class) - public synchronized void doSubmitDescription( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { + public synchronized void doSubmitDescription(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { Jenkins.get().checkPermission(Jenkins.ADMINISTER); setDescription(req.getParameter("description")); @@ -273,9 +274,9 @@ public class LabelAtom extends Label implements Saveable { try { Jenkins.checkGoodName(name); // additional restricted chars - for( int i=0; i all() { + public static DescriptorExtensionList all() { return Jenkins.get().getDescriptorList(LabelAtomProperty.class); } } diff --git a/core/src/main/java/hudson/model/labels/LabelAtomPropertyDescriptor.java b/core/src/main/java/hudson/model/labels/LabelAtomPropertyDescriptor.java index b9b9312939f1c498e720c07116f3615adbf0f348..3c45b2e0a76e44348230f1759c739cbceef116e7 100644 --- a/core/src/main/java/hudson/model/labels/LabelAtomPropertyDescriptor.java +++ b/core/src/main/java/hudson/model/labels/LabelAtomPropertyDescriptor.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model.labels; import hudson.Extension; @@ -31,7 +32,7 @@ import hudson.model.Descriptor; * *

    * Put {@link Extension} on your descriptor implementation to have it auto-registered. - * + * *

    * When extending this class, override {@link Descriptor#getDisplayName()}. In the * context of LabelAtomPropertyDescriptor, this function is used to determine the label of diff --git a/core/src/main/java/hudson/model/labels/LabelExpression.java b/core/src/main/java/hudson/model/labels/LabelExpression.java index 00a81c27155576a20f804950f57c369de1cb4257..55a34a010e14fe99a7665152f89936600e045a09 100644 --- a/core/src/main/java/hudson/model/labels/LabelExpression.java +++ b/core/src/main/java/hudson/model/labels/LabelExpression.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model.labels; import antlr.ANTLRException; @@ -44,7 +45,7 @@ import jenkins.model.labels.LabelValidator; /** * Boolean expression of labels. - * + * * @author Kohsuke Kawaguchi * @since 1.372 */ @@ -62,7 +63,7 @@ public abstract class LabelExpression extends Label { public final Label base; public Not(Label base) { - super('!'+paren(LabelOperatorPrecedence.NOT,base)); + super('!' + paren(LabelOperatorPrecedence.NOT, base)); this.base = base; } @@ -89,7 +90,7 @@ public abstract class LabelExpression extends Label { public final Label base; public Paren(Label base) { - super('('+base.getExpression()+')'); + super('(' + base.getExpression() + ')'); this.base = base; } @@ -113,13 +114,13 @@ public abstract class LabelExpression extends Label { * Puts the label name into a parenthesis if the given operator will have a higher precedence. */ static String paren(LabelOperatorPrecedence op, Label l) { - if (op.compareTo(l.precedence())<0) - return '('+l.getExpression()+')'; + if (op.compareTo(l.precedence()) < 0) + return '(' + l.getExpression() + ')'; return l.getExpression(); } public abstract static class Binary extends LabelExpression { - public final Label lhs,rhs; + public final Label lhs, rhs; protected Binary(Label lhs, Label rhs, LabelOperatorPrecedence op) { super(combine(lhs, rhs, op)); @@ -128,7 +129,7 @@ public abstract class LabelExpression extends Label { } private static String combine(Label lhs, Label rhs, LabelOperatorPrecedence op) { - return paren(op,lhs)+op.str+paren(op,rhs); + return paren(op, lhs) + op.str + paren(op, rhs); } /** @@ -137,7 +138,7 @@ public abstract class LabelExpression extends Label { */ @Override public boolean matches(VariableResolver resolver) { - return op(lhs.matches(resolver),rhs.matches(resolver)); + return op(lhs.matches(resolver), rhs.matches(resolver)); } protected abstract boolean op(boolean a, boolean b); diff --git a/core/src/main/java/hudson/model/labels/LabelOperatorPrecedence.java b/core/src/main/java/hudson/model/labels/LabelOperatorPrecedence.java index a917d97b0563cdf7efaabd6fa7638456d1b8244d..b70f0036af76ed356ee36e9264b9a7b20f5b817d 100644 --- a/core/src/main/java/hudson/model/labels/LabelOperatorPrecedence.java +++ b/core/src/main/java/hudson/model/labels/LabelOperatorPrecedence.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model.labels; /** diff --git a/core/src/main/java/hudson/model/labels/LabelVisitor.java b/core/src/main/java/hudson/model/labels/LabelVisitor.java index fcb2f9b58eab6162335806d8263340cdd3fe34e5..0fb8114f32c0cc0dbd50baf4b360e1ac61d9eccf 100644 --- a/core/src/main/java/hudson/model/labels/LabelVisitor.java +++ b/core/src/main/java/hudson/model/labels/LabelVisitor.java @@ -7,7 +7,7 @@ package hudson.model.labels; * @see LabelExpression#accept(LabelVisitor, Object) * @since 1.420 */ -public abstract class LabelVisitor { +public abstract class LabelVisitor { public abstract V onAtom(LabelAtom a, P param); public abstract V onParen(LabelExpression.Paren p, P param); diff --git a/core/src/main/java/hudson/model/listeners/ItemListener.java b/core/src/main/java/hudson/model/listeners/ItemListener.java index 13522ef500a65726c2383685fab5dbe8f551611e..aef431c3207b4e7093fc7bb6cda01d6a9e751ff9 100644 --- a/core/src/main/java/hudson/model/listeners/ItemListener.java +++ b/core/src/main/java/hudson/model/listeners/ItemListener.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model.listeners; import hudson.Extension; @@ -231,7 +232,7 @@ public class ItemListener implements ExtensionPoint { } Listeners.notify(ItemListener.class, false, l -> l.onLocationChanged(rootItem, oldFullName, newFullName)); if (rootItem instanceof ItemGroup) { - for (final Item child : Items.allItems2(ACL.SYSTEM2, (ItemGroup)rootItem, Item.class)) { + for (final Item child : Items.allItems2(ACL.SYSTEM2, (ItemGroup) rootItem, Item.class)) { final String childNew = child.getFullName(); assert childNew.startsWith(newFullName); assert childNew.charAt(newFullName.length()) == '/'; diff --git a/core/src/main/java/hudson/model/listeners/RunListener.java b/core/src/main/java/hudson/model/listeners/RunListener.java index 148f419908399b570c3ad0b30abe138be6f44e34..0ecbf725c792d9c8200e317f0914d3b9a7a3ff4f 100644 --- a/core/src/main/java/hudson/model/listeners/RunListener.java +++ b/core/src/main/java/hudson/model/listeners/RunListener.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Tom Huybrechts - * + * * 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 @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model.listeners; import edu.umd.cs.findbugs.annotations.NonNull; @@ -57,7 +58,7 @@ import org.jvnet.tiger_types.Types; * *

    * This is an abstract class so that methods added in the future won't break existing listeners. - * + * * @author Kohsuke Kawaguchi * @since 1.145 */ @@ -71,9 +72,9 @@ public abstract class RunListener implements ExtensionPoint { protected RunListener() { Type type = Types.getBaseClass(getClass(), RunListener.class); if (type instanceof ParameterizedType) - targetType = Types.erasure(Types.getTypeArgument(type,0)); + targetType = Types.erasure(Types.getTypeArgument(type, 0)); else - throw new IllegalStateException(getClass()+" uses the raw type for extending RunListener"); + throw new IllegalStateException(getClass() + " uses the raw type for extending RunListener"); } /** @@ -156,8 +157,8 @@ public abstract class RunListener implements ExtensionPoint { * to suppress a stack trace by the receiver. * @since 1.410 */ - public Environment setUpEnvironment( AbstractBuild build, Launcher launcher, BuildListener listener ) throws IOException, InterruptedException, RunnerAbortedException { - return new Environment() {}; + public Environment setUpEnvironment(AbstractBuild build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException, RunnerAbortedException { + return new Environment() {}; } /** diff --git a/core/src/main/java/hudson/model/listeners/SCMListener.java b/core/src/main/java/hudson/model/listeners/SCMListener.java index 02cd62e34038e5aec4a276fade07c1800b1de10f..afb93bf2c7ab98335d16228116bc0ddff2a34ac6 100644 --- a/core/src/main/java/hudson/model/listeners/SCMListener.java +++ b/core/src/main/java/hudson/model/listeners/SCMListener.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model.listeners; import edu.umd.cs.findbugs.annotations.CheckForNull; @@ -51,7 +52,7 @@ import jenkins.model.Jenkins; * This is an abstract class so that methods added in the future won't break existing listeners. * *

    - * Once instantiated, use the {@link #register()} method to start receiving events. + * Once instantiated, use the {@link #register()} method to start receiving events. * * @author Kohsuke Kawaguchi * @see jenkins.model.Jenkins#getSCMListeners() @@ -65,7 +66,7 @@ public abstract class SCMListener implements ExtensionPoint { * @throws Exception if the checkout should be considered failed * @since 1.568 */ - public void onCheckout(Run build, SCM scm, FilePath workspace, TaskListener listener, @CheckForNull File changelogFile, @CheckForNull SCMRevisionState pollingBaseline) throws Exception {} + public void onCheckout(Run build, SCM scm, FilePath workspace, TaskListener listener, @CheckForNull File changelogFile, @CheckForNull SCMRevisionState pollingBaseline) throws Exception {} /** * Called once the changelog is determined. @@ -79,7 +80,7 @@ public abstract class SCMListener implements ExtensionPoint { *

    * If a build failed before we successfully determine changelog, this method * will not be invoked (for example, if "cvs update" failed.) OTOH, this method - * is invoked before the actual build (like ant invocation) happens. + * is invoked before the actual build (like ant invocation) happens. * *

    * This is an opportunity for SCM-related plugins to act on changelog. @@ -105,17 +106,17 @@ public abstract class SCMListener implements ExtensionPoint { * * @throws Exception * If any exception is thrown from this method, it will be recorded - * and causes the build to fail. + * and causes the build to fail. * @since 1.568 */ - public void onChangeLogParsed(Run build, SCM scm, TaskListener listener, ChangeLogSet changelog) throws Exception { + public void onChangeLogParsed(Run build, SCM scm, TaskListener listener, ChangeLogSet changelog) throws Exception { if (build instanceof AbstractBuild && listener instanceof BuildListener && Util.isOverridden(SCMListener.class, getClass(), "onChangeLogParsed", AbstractBuild.class, BuildListener.class, ChangeLogSet.class)) { onChangeLogParsed((AbstractBuild) build, (BuildListener) listener, changelog); } } @Deprecated - public void onChangeLogParsed(AbstractBuild build, BuildListener listener, ChangeLogSet changelog) throws Exception { + public void onChangeLogParsed(AbstractBuild build, BuildListener listener, ChangeLogSet changelog) throws Exception { if (Util.isOverridden(SCMListener.class, getClass(), "onChangeLogParsed", Run.class, SCM.class, TaskListener.class, ChangeLogSet.class)) { onChangeLogParsed(build, build.getProject().getScm(), listener, changelog); } diff --git a/core/src/main/java/hudson/model/listeners/SCMPollListener.java b/core/src/main/java/hudson/model/listeners/SCMPollListener.java index 48fa919117909c719c84c2280db40b5afa664e60..341f91ac79b880d31250f02babd61ec9432adaca 100644 --- a/core/src/main/java/hudson/model/listeners/SCMPollListener.java +++ b/core/src/main/java/hudson/model/listeners/SCMPollListener.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model.listeners; import hudson.ExtensionList; @@ -48,7 +49,7 @@ public abstract class SCMPollListener implements ExtensionPoint { * Connected to the polling log. */ // TODO switch to Job - public void onBeforePolling( AbstractProject project, TaskListener listener ) {} + public void onBeforePolling(AbstractProject project, TaskListener listener) {} /** * Called when the polling successfully concluded. @@ -56,7 +57,7 @@ public abstract class SCMPollListener implements ExtensionPoint { * @param result * The result of the polling. */ - public void onPollingSuccess( AbstractProject project, TaskListener listener, PollingResult result) {} + public void onPollingSuccess(AbstractProject project, TaskListener listener, PollingResult result) {} /** * Called when the polling concluded with an error. @@ -65,24 +66,24 @@ public abstract class SCMPollListener implements ExtensionPoint { * The problem reported. This can include {@link InterruptedException} (that corresponds to the user cancelling it), * some anticipated problems like {@link IOException}, or bug in the code ({@link RuntimeException}) */ - public void onPollingFailed( AbstractProject project, TaskListener listener, Throwable exception) {} + public void onPollingFailed(AbstractProject project, TaskListener listener, Throwable exception) {} - public static void fireBeforePolling( AbstractProject project, TaskListener listener ) { + public static void fireBeforePolling(AbstractProject project, TaskListener listener) { Listeners.notify(SCMPollListener.class, true, l -> l.onBeforePolling(project, listener)); } - public static void firePollingSuccess( AbstractProject project, TaskListener listener, PollingResult result ) { + public static void firePollingSuccess(AbstractProject project, TaskListener listener, PollingResult result) { Listeners.notify(SCMPollListener.class, true, l -> l.onPollingSuccess(project, listener, result)); - } + } - public static void firePollingFailed( AbstractProject project, TaskListener listener, Throwable exception ) { + public static void firePollingFailed(AbstractProject project, TaskListener listener, Throwable exception) { Listeners.notify(SCMPollListener.class, true, l -> l.onPollingFailed(project, listener, exception)); - } + } - /** - * Returns all the registered {@link SCMPollListener}s. - */ - public static ExtensionList all() { - return ExtensionList.lookup( SCMPollListener.class ); - } + /** + * Returns all the registered {@link SCMPollListener}s. + */ + public static ExtensionList all() { + return ExtensionList.lookup(SCMPollListener.class); + } } diff --git a/core/src/main/java/hudson/model/listeners/SaveableListener.java b/core/src/main/java/hudson/model/listeners/SaveableListener.java index 5df4f298284d82c54ae8abe37aad65098ec1fd04..51cac4861a578547c58080cebbd248d32050374b 100644 --- a/core/src/main/java/hudson/model/listeners/SaveableListener.java +++ b/core/src/main/java/hudson/model/listeners/SaveableListener.java @@ -1,19 +1,19 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Tom Huybrechts, * Andrew Bayer - * + * * 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 @@ -22,6 +22,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model.listeners; import hudson.Extension; @@ -78,7 +79,7 @@ public abstract class SaveableListener implements ExtensionPoint { public static void fireOnChange(Saveable o, XmlFile file) { for (SaveableListener l : all()) { try { - l.onChange(o,file); + l.onChange(o, file); } catch (ThreadDeath t) { throw t; } catch (Throwable t) { diff --git a/core/src/main/java/hudson/model/queue/AbstractQueueSorterImpl.java b/core/src/main/java/hudson/model/queue/AbstractQueueSorterImpl.java index 486bd4c96b3a91cb33e89e979b53cb966285ec9e..99ac92828bb5e099aea9efb9b8671c0aae26a43c 100644 --- a/core/src/main/java/hudson/model/queue/AbstractQueueSorterImpl.java +++ b/core/src/main/java/hudson/model/queue/AbstractQueueSorterImpl.java @@ -31,7 +31,7 @@ public abstract class AbstractQueueSorterImpl extends QueueSorter implements Com */ @Override public int compare(BuildableItem lhs, BuildableItem rhs) { - return Long.compare(lhs.buildableStartMilliseconds,rhs.buildableStartMilliseconds); + return Long.compare(lhs.buildableStartMilliseconds, rhs.buildableStartMilliseconds); } /** diff --git a/core/src/main/java/hudson/model/queue/AbstractSubTask.java b/core/src/main/java/hudson/model/queue/AbstractSubTask.java index b8de10e02ce1e5eee3ba5ecc42631209fa99f90c..8888eaab72c93129925e1204265594699ff0196a 100644 --- a/core/src/main/java/hudson/model/queue/AbstractSubTask.java +++ b/core/src/main/java/hudson/model/queue/AbstractSubTask.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model.queue; /** diff --git a/core/src/main/java/hudson/model/queue/CauseOfBlockage.java b/core/src/main/java/hudson/model/queue/CauseOfBlockage.java index 9aad22d4ddc643a2cfff5e66add7a6c0d8461ca2..a9919488308513b676b463c770ed86f1ef521236 100644 --- a/core/src/main/java/hudson/model/queue/CauseOfBlockage.java +++ b/core/src/main/java/hudson/model/queue/CauseOfBlockage.java @@ -102,7 +102,7 @@ public abstract class CauseOfBlockage { String name = node.toComputer() != null ? node.toComputer().getDisplayName() : node.getDisplayName(); return Messages.Queue_NodeOffline(name); } - + @Override public void print(TaskListener listener) { listener.getLogger().println( @@ -182,7 +182,7 @@ public abstract class CauseOfBlockage { String name = node.toComputer() != null ? node.toComputer().getDisplayName() : node.getDisplayName(); return Messages.Queue_WaitingForNextAvailableExecutorOn(name); } - + @Override public void print(TaskListener listener) { listener.getLogger().println(Messages.Queue_WaitingForNextAvailableExecutorOn(ModelHyperlinkNote.encodeTo(node))); diff --git a/core/src/main/java/hudson/model/queue/Executables.java b/core/src/main/java/hudson/model/queue/Executables.java index 3da70ed2aab4cb0f0fc630a764c328c638e14231..396133fe4d3361ebe30203fc2bccc2f957ff2636 100644 --- a/core/src/main/java/hudson/model/queue/Executables.java +++ b/core/src/main/java/hudson/model/queue/Executables.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model.queue; import edu.umd.cs.findbugs.annotations.CheckForNull; @@ -35,13 +36,13 @@ import java.lang.reflect.Method; * @author Kohsuke Kawaguchi */ public class Executables { - + /** * Due to the return type change in {@link Executable} in 1.377, the caller needs a special precaution now. * @param e Executable * @return Discovered subtask */ - public static @NonNull SubTask getParentOf(@NonNull Executable e) + public static @NonNull SubTask getParentOf(@NonNull Executable e) throws Error, RuntimeException { try { return e.getParent(); @@ -51,13 +52,13 @@ public class Executables { m.setAccessible(true); return (SubTask) m.invoke(e); } catch (IllegalAccessException x) { - throw (Error)new IllegalAccessError().initCause(x); + throw (Error) new IllegalAccessError().initCause(x); } catch (NoSuchMethodException x) { - throw (Error)new NoSuchMethodError().initCause(x); + throw (Error) new NoSuchMethodError().initCause(x); } catch (InvocationTargetException x) { Throwable y = x.getTargetException(); - if (y instanceof Error) throw (Error)y; - if (y instanceof RuntimeException) throw (RuntimeException)y; + if (y instanceof Error) throw (Error) y; + if (y instanceof RuntimeException) throw (RuntimeException) y; throw new Error(x); } } diff --git a/core/src/main/java/hudson/model/queue/FoldableAction.java b/core/src/main/java/hudson/model/queue/FoldableAction.java index dff6a610a283b91ea449b8852ec7b1a9227d45f5..4b368a2b9d15db144c83f256cc17f6936a3fbb65 100644 --- a/core/src/main/java/hudson/model/queue/FoldableAction.java +++ b/core/src/main/java/hudson/model/queue/FoldableAction.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model.queue; import hudson.model.Action; diff --git a/core/src/main/java/hudson/model/queue/FutureImpl.java b/core/src/main/java/hudson/model/queue/FutureImpl.java index 6009b2fe700ceace016732d274a1933b805e776f..f6bba013f2cc4a5cee919a65e3bc81ef0d701ce7 100644 --- a/core/src/main/java/hudson/model/queue/FutureImpl.java +++ b/core/src/main/java/hudson/model/queue/FutureImpl.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model.queue; import edu.umd.cs.findbugs.annotations.NonNull; @@ -73,8 +74,8 @@ public final class FutureImpl extends AsyncFutureImpl implements Que public boolean cancel(boolean mayInterruptIfRunning) { Queue q = Jenkins.get().getQueue(); synchronized (this) { - if(!executors.isEmpty()) { - if(mayInterruptIfRunning) + if (!executors.isEmpty()) { + if (mayInterruptIfRunning) for (Executor e : executors) e.interrupt(); return mayInterruptIfRunning; diff --git a/core/src/main/java/hudson/model/queue/FutureLoad.java b/core/src/main/java/hudson/model/queue/FutureLoad.java index a46ef6f22329425aed156999cf6bf76255686792..1d3046d09288c80a082d0c080351bf26147e86ca 100644 --- a/core/src/main/java/hudson/model/queue/FutureLoad.java +++ b/core/src/main/java/hudson/model/queue/FutureLoad.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model.queue; /** @@ -51,6 +52,6 @@ public final class FutureLoad { @Override public String toString() { - return "startTime="+startTime+",#executors="+numExecutors+",duration="+duration; + return "startTime=" + startTime + ",#executors=" + numExecutors + ",duration=" + duration; } } diff --git a/core/src/main/java/hudson/model/queue/Latch.java b/core/src/main/java/hudson/model/queue/Latch.java index c8b3619589405350acbbd7727000faea6309758c..3479c0599c387789992a40648035e99a4ac0773d 100644 --- a/core/src/main/java/hudson/model/queue/Latch.java +++ b/core/src/main/java/hudson/model/queue/Latch.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model.queue; import hudson.AbortException; @@ -36,7 +37,7 @@ import hudson.AbortException; */ class Latch { private final int n; - private int i=0; + private int i = 0; /** * If the synchronization on the latch is aborted/interrupted, * point to the stack trace where that happened. If null, @@ -55,7 +56,7 @@ class Latch { public synchronized void abort(Throwable cause) { interrupted = new AbortException(); - if (cause!=null) + if (cause != null) interrupted.initCause(cause); notifyAll(); } @@ -79,15 +80,15 @@ class Latch { throw e; } - check(n*2); + check(n * 2); } private void check(int threshold) throws InterruptedException { i++; - if (i==threshold) { + if (i == threshold) { notifyAll(); } else { - while (i predict(MappingWorksheet plan, Computer computer, long start, long end) { // maintain backward compatibility by calling the old signature. - return predict(computer,start,end); + return predict(computer, start, end); } /** @@ -96,9 +97,9 @@ public abstract class LoadPredictor implements ExtensionPoint { if (e.isIdle()) continue; long eta = e.getEstimatedRemainingTimeMillis(); - long end = eta<0 ? eternity : now + eta; // when does this task end? + long end = eta < 0 ? eternity : now + eta; // when does this task end? if (end < start) continue; // should be over by the 'start' time. - fl.add(new FutureLoad(start, end-start, 1)); + fl.add(new FutureLoad(start, end - start, 1)); } return fl; } diff --git a/core/src/main/java/hudson/model/queue/MappingWorksheet.java b/core/src/main/java/hudson/model/queue/MappingWorksheet.java index f6f5edb35df9069c7d4eeff3e3ddb4c9d22db750..54829ec0dac204ea9d3db278cc25bc4ec33b1dce 100644 --- a/core/src/main/java/hudson/model/queue/MappingWorksheet.java +++ b/core/src/main/java/hudson/model/queue/MappingWorksheet.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model.queue; import static java.lang.Math.max; @@ -128,10 +129,10 @@ public class MappingWorksheet { * Is this executor chunk and the given work chunk compatible? Can the latter be run on the former? */ public boolean canAccept(WorkChunk c) { - if (this.size() toMap() { - Map r = new HashMap<>(); - for (int i=0; i toMap() { + Map r = new HashMap<>(); + for (int i = 0; i < size(); i++) + r.put(get(i), assigned(i)); return r; } @@ -275,9 +276,9 @@ public class MappingWorksheet { */ public boolean isPartiallyValid() { int[] used = new int[executors.size()]; - for (int i=0; i ec.capacity()) @@ -291,7 +292,7 @@ public class MappingWorksheet { */ public boolean isCompletelyValid() { for (ExecutorChunk ec : mapping) - if (ec==null) return false; // unassigned + if (ec == null) return false; // unassigned return isPartiallyValid(); } @@ -303,27 +304,27 @@ public class MappingWorksheet { if (!isCompletelyValid()) throw new IllegalStateException(); - for (int i=0; i offers) { - this(item,offers,LoadPredictor.all()); + this(item, offers, LoadPredictor.all()); } public MappingWorksheet(BuildableItem item, List offers, Collection loadPredictors) { this.item = item; // group executors by their computers - Map> j = new HashMap<>(); + Map> j = new HashMap<>(); for (ExecutorSlot o : offers) { Computer c = o.getExecutor().getOwner(); List l = j.computeIfAbsent(c, k -> new ArrayList<>()); l.add(o); } - {// take load prediction into account and reduce the available executor pool size accordingly + { // take load prediction into account and reduce the available executor pool size accordingly long duration = item.task.getEstimatedDuration(); if (duration > 0) { long now = System.currentTimeMillis(); @@ -336,20 +337,20 @@ public class MappingWorksheet { int peak = 0; OUTER: for (LoadPredictor lp : loadPredictors) { - for (FutureLoad fl : Iterables.limit(lp.predict(this,e.getKey(), now, now + duration),100)) { - peak = max(peak,timeline.insert(fl.startTime, fl.startTime+fl.duration, fl.numExecutors)); - if (peak>=max) break OUTER; + for (FutureLoad fl : Iterables.limit(lp.predict(this, e.getKey(), now, now + duration), 100)) { + peak = max(peak, timeline.insert(fl.startTime, fl.startTime + fl.duration, fl.numExecutors)); + if (peak >= max) break OUTER; } } - int minIdle = max-peak; // minimum number of idle nodes during this time period + int minIdle = max - peak; // minimum number of idle nodes during this time period // total predicted load could exceed available executors [JENKINS-8882] - if (minIdle<0) { + if (minIdle < 0) { // Should we toss a warning/info message? minIdle = 0; } - if (minIdle group : j.values()) { if (group.isEmpty()) continue; // evict empty group ExecutorChunk ec = new ExecutorChunk(group, executors.size()); - if (ec.node==null) continue; // evict out of sync node + if (ec.node == null) continue; // evict out of sync node executors.add(ec); } this.executors = Collections.unmodifiableList(executors); // group execution units into chunks. use of LinkedHashMap ensures that the main work comes at the top - Map> m = new LinkedHashMap<>(); + Map> m = new LinkedHashMap<>(); for (SubTask meu : item.task.getSubTasks()) { Object c = meu.getSameNodeConstraint(); - if (c==null) c = new Object(); + if (c == null) c = new Object(); List l = m.computeIfAbsent(c, k -> new ArrayList<>()); l.add(meu); @@ -377,7 +378,7 @@ public class MappingWorksheet { // build into the final shape List works = new ArrayList<>(); for (List group : m.values()) { - works.add(new WorkChunk(group,works.size())); + works.add(new WorkChunk(group, works.size())); } this.works = Collections.unmodifiableList(works); } diff --git a/core/src/main/java/hudson/model/queue/QueueSorter.java b/core/src/main/java/hudson/model/queue/QueueSorter.java index a6cd487a767c12ab153deae7ea955f46816bbaa1..939d1c6fdff5af163b66b68b212d2dca7f310230 100644 --- a/core/src/main/java/hudson/model/queue/QueueSorter.java +++ b/core/src/main/java/hudson/model/queue/QueueSorter.java @@ -62,17 +62,17 @@ public abstract class QueueSorter implements ExtensionPoint { * * {@link Queue#Queue(LoadBalancer)} is too early to do this */ - @Initializer(after=JOB_CONFIG_ADAPTED) + @Initializer(after = JOB_CONFIG_ADAPTED) public static void installDefaultQueueSorter() { ExtensionList all = all(); if (all.isEmpty()) return; Queue q = Jenkins.get().getQueue(); - if (q.getSorter()!=null) return; // someone has already installed something. leave that alone. + if (q.getSorter() != null) return; // someone has already installed something. leave that alone. q.setSorter(all.get(0)); - if (all.size()>1) - LOGGER.warning("Multiple QueueSorters are registered. Only the first one is used and the rest are ignored: "+all); + if (all.size() > 1) + LOGGER.warning("Multiple QueueSorters are registered. Only the first one is used and the rest are ignored: " + all); } private static final Logger LOGGER = Logger.getLogger(QueueSorter.class.getName()); diff --git a/core/src/main/java/hudson/model/queue/QueueTaskDispatcher.java b/core/src/main/java/hudson/model/queue/QueueTaskDispatcher.java index eaa0ec18f34ba9179aaa152f2f262084a996c970..9b51bedb36a8dab0a3c564427dad80d4a6128876 100644 --- a/core/src/main/java/hudson/model/queue/QueueTaskDispatcher.java +++ b/core/src/main/java/hudson/model/queue/QueueTaskDispatcher.java @@ -98,7 +98,7 @@ public abstract class QueueTaskDispatcher implements ExtensionPoint { * @since 1.413 */ public @CheckForNull CauseOfBlockage canTake(Node node, BuildableItem item) { - return canTake(node,item.task); // backward compatible behaviour + return canTake(node, item.task); // backward compatible behaviour } /** diff --git a/core/src/main/java/hudson/model/queue/ScheduleResult.java b/core/src/main/java/hudson/model/queue/ScheduleResult.java index 91ef54ddb17a9b049e60824332f130613f34c115..ed43b651917e1f68388a2e0a9e78d77f94a25998 100644 --- a/core/src/main/java/hudson/model/queue/ScheduleResult.java +++ b/core/src/main/java/hudson/model/queue/ScheduleResult.java @@ -58,6 +58,7 @@ public abstract class ScheduleResult { public static final class Created extends ScheduleResult { private final WaitingItem item; + private Created(WaitingItem item) { this.item = item; } diff --git a/core/src/main/java/hudson/model/queue/SubTask.java b/core/src/main/java/hudson/model/queue/SubTask.java index 80d4528efcc36a84d7c437e9e3749bb0d48c1bd1..98c9e0bacbafee4756c306225244ed6ab6e4a066 100644 --- a/core/src/main/java/hudson/model/queue/SubTask.java +++ b/core/src/main/java/hudson/model/queue/SubTask.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model.queue; import edu.umd.cs.findbugs.annotations.CheckForNull; diff --git a/core/src/main/java/hudson/model/queue/SubTaskContributor.java b/core/src/main/java/hudson/model/queue/SubTaskContributor.java index ccd92ec79a45b51da203323567c455e974ab14bb..72bfb80a397a4da8ee7805ddddfb3a67f8c589d1 100644 --- a/core/src/main/java/hudson/model/queue/SubTaskContributor.java +++ b/core/src/main/java/hudson/model/queue/SubTaskContributor.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model.queue; import hudson.Extension; @@ -40,7 +41,7 @@ import java.util.Collections; * @since 1.377 */ public abstract class SubTaskContributor implements ExtensionPoint { - public Collection forProject(AbstractProject p) { + public Collection forProject(AbstractProject p) { return Collections.emptyList(); } diff --git a/core/src/main/java/hudson/model/queue/Tasks.java b/core/src/main/java/hudson/model/queue/Tasks.java index 5fdadcfb2f746902f30e7b747ba0d3aed939f77b..fe007200f1b4f797c54b27d3cab3b88da68cb4e1 100644 --- a/core/src/main/java/hudson/model/queue/Tasks.java +++ b/core/src/main/java/hudson/model/queue/Tasks.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model.queue; import edu.umd.cs.findbugs.annotations.CheckForNull; @@ -76,7 +77,7 @@ public class Tasks { } p = o; } - return p instanceof hudson.model.Item ? (hudson.model.Item)p : null; + return p instanceof hudson.model.Item ? (hudson.model.Item) p : null; } /** @deprecated call {@link Queue.Task#getDefaultAuthentication()} directly */ diff --git a/core/src/main/java/hudson/model/queue/Timeline.java b/core/src/main/java/hudson/model/queue/Timeline.java index 1d70c03e26de17e0d8b8ac9c397657f86710c30e..ee7c4d54deef2a7d5830a2b81c1daebc458be9ab 100644 --- a/core/src/main/java/hudson/model/queue/Timeline.java +++ b/core/src/main/java/hudson/model/queue/Timeline.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model.queue; import static java.lang.Math.max; @@ -44,7 +45,7 @@ final class Timeline { * Obtains q(t) for the given t. */ private int at(long t) { - SortedMap head = data.subMap(t,Long.MAX_VALUE); + SortedMap head = data.subMap(t, Long.MAX_VALUE); if (head.isEmpty()) return 0; return data.get(head.firstKey())[0]; } @@ -105,15 +106,15 @@ final class Timeline { long t = start; // check if 'start' satisfies the two conditions by moving t across [start,start+duration) while (t - start < duration) { - if (at(t)>n) { + if (at(t) > n) { // value too big. what's the next t that's worth trying? Long nxt = next(t); - if (nxt==null) return null; + if (nxt == null) return null; start = nxt; continue OUTER; } else { Long nxt = next(t); - if (nxt==null) t = Long.MAX_VALUE; + if (nxt == null) t = Long.MAX_VALUE; else t = nxt; } } diff --git a/core/src/main/java/hudson/model/queue/WorkUnit.java b/core/src/main/java/hudson/model/queue/WorkUnit.java index 8aed254e31eebbfa983c633055705890ce74d89f..8c2924b49ba5c120eab1aa9eb817c04b9cf510f3 100644 --- a/core/src/main/java/hudson/model/queue/WorkUnit.java +++ b/core/src/main/java/hudson/model/queue/WorkUnit.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model.queue; import edu.umd.cs.findbugs.annotations.CheckForNull; @@ -98,14 +99,14 @@ public final class WorkUnit { * represented by {@link Task} itself. */ public boolean isMainWork() { - return context.task==work; + return context.task == work; } @Override public String toString() { - if (work==context.task) - return super.toString()+"[work="+context.task.getFullDisplayName()+"]"; + if (work == context.task) + return super.toString() + "[work=" + context.task.getFullDisplayName() + "]"; else - return super.toString()+"[work="+work+",context.task="+context.task.getFullDisplayName()+"]"; + return super.toString() + "[work=" + work + ",context.task=" + context.task.getFullDisplayName() + "]"; } } diff --git a/core/src/main/java/hudson/model/queue/WorkUnitContext.java b/core/src/main/java/hudson/model/queue/WorkUnitContext.java index 1b534855270f2e03416069545667e9ed97be436c..31829ba7dd1f2d16bb902a16a5726b1e31b838eb 100644 --- a/core/src/main/java/hudson/model/queue/WorkUnitContext.java +++ b/core/src/main/java/hudson/model/queue/WorkUnitContext.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.model.queue; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; @@ -74,7 +75,7 @@ public final class WorkUnitContext { public WorkUnitContext(BuildableItem item) { this.item = item; this.task = item.task; - this.future = (FutureImpl)item.getFuture(); + this.future = (FutureImpl) item.getFuture(); // JENKINS-51584 do not use item.getAllActions() here. this.actions = new ArrayList<>(item.getActions()); // +1 for the main task @@ -88,7 +89,7 @@ public final class WorkUnitContext { // Unclear if this will work with AsynchronousExecution; it *seems* this is only called from synchronize which is only called from synchronizeStart which is only called from an executor thread. Executor e = Executor.currentExecutor(); if (e.getCurrentWorkUnit().isMainWork()) { - e.getOwner().taskAccepted(e,task); + e.getOwner().taskAccepted(e, task); for (ExecutorListener listener : ExtensionList.lookup(ExecutorListener.class)) { try { listener.taskAccepted(e, task); @@ -160,7 +161,7 @@ public final class WorkUnitContext { */ @Restricted(NoExternalUse.class) public void synchronizeEnd(Executor e, Queue.Executable executable, Throwable problems, long duration) throws InterruptedException { - // Let code waiting for the build to finish (future.get()) finishes when there is a faulty SubTask by setting + // Let code waiting for the build to finish (future.get()) finishes when there is a faulty SubTask by setting // the future always. try { endLatch.synchronize(); @@ -197,8 +198,8 @@ public final class WorkUnitContext { * When one of the work unit is aborted, call this method to abort all the other work units. */ public synchronized void abort(Throwable cause) { - if (cause==null) throw new IllegalArgumentException(); - if (aborted!=null) return; // already aborted + if (cause == null) throw new IllegalArgumentException(); + if (aborted != null) return; // already aborted aborted = cause; startLatch.abort(cause); endLatch.abort(cause); @@ -206,7 +207,7 @@ public final class WorkUnitContext { Thread c = Thread.currentThread(); for (WorkUnit wu : workUnits) { Executor e = wu.getExecutor(); - if (e!=null && e!=c) + if (e != null && e != c) e.interrupt(); } } diff --git a/core/src/main/java/hudson/node_monitors/AbstractAsyncNodeMonitorDescriptor.java b/core/src/main/java/hudson/node_monitors/AbstractAsyncNodeMonitorDescriptor.java index 842c9bed0ea764dcedaad315ef9152430fed92c9..8e46a3705718766ccb40db1f9f98afa6fd1b2075 100644 --- a/core/src/main/java/hudson/node_monitors/AbstractAsyncNodeMonitorDescriptor.java +++ b/core/src/main/java/hudson/node_monitors/AbstractAsyncNodeMonitorDescriptor.java @@ -51,14 +51,14 @@ public abstract class AbstractAsyncNodeMonitorDescriptor extends AbstractNode /** * Creates a {@link Callable} that performs the monitoring when executed. */ - protected abstract @CheckForNull Callable createCallable(Computer c); + protected abstract @CheckForNull Callable createCallable(Computer c); @Override protected T monitor(Computer c) throws IOException, InterruptedException { VirtualChannel ch = c.getChannel(); if (ch != null) { - Callable cc = createCallable(c); - if (cc!=null) + Callable cc = createCallable(c); + if (cc != null) return ch.call(cc); } return null; @@ -80,17 +80,17 @@ public abstract class AbstractAsyncNodeMonitorDescriptor extends AbstractNode * Perform monitoring with detailed reporting. */ protected final @NonNull Result monitorDetailed() throws InterruptedException { - Map> futures = new HashMap<>(); + Map> futures = new HashMap<>(); Set skipped = new HashSet<>(); for (Computer c : Jenkins.get().getComputers()) { try { VirtualChannel ch = c.getChannel(); - futures.put(c,null); // sentinel value - if (ch!=null) { + futures.put(c, null); // sentinel value + if (ch != null) { Callable cc = createCallable(c); - if (cc!=null) - futures.put(c,ch.callAsync(cc)); + if (cc != null) + futures.put(c, ch.callAsync(cc)); } } catch (RuntimeException | IOException e) { error(c, e); @@ -100,16 +100,16 @@ public abstract class AbstractAsyncNodeMonitorDescriptor extends AbstractNode final long now = System.currentTimeMillis(); final long end = now + getMonitoringTimeOut(); - final Map data = new HashMap<>(); + final Map data = new HashMap<>(); for (Map.Entry> e : futures.entrySet()) { Computer c = e.getKey(); Future f = futures.get(c); data.put(c, null); // sentinel value - if (f!=null) { + if (f != null) { try { - data.put(c,f.get(Math.max(0,end-System.currentTimeMillis()), MILLISECONDS)); + data.put(c, f.get(Math.max(0, end - System.currentTimeMillis()), MILLISECONDS)); } catch (RuntimeException | TimeoutException | ExecutionException x) { error(c, x); } diff --git a/core/src/main/java/hudson/node_monitors/AbstractDiskSpaceMonitor.java b/core/src/main/java/hudson/node_monitors/AbstractDiskSpaceMonitor.java index dce9ca3e14e1da8a52c4cdfb379be28236efb306..38230dd80f915d5baa2e2368550f0f1597e75926 100644 --- a/core/src/main/java/hudson/node_monitors/AbstractDiskSpaceMonitor.java +++ b/core/src/main/java/hudson/node_monitors/AbstractDiskSpaceMonitor.java @@ -28,7 +28,7 @@ public abstract class AbstractDiskSpaceMonitor extends NodeMonitor { } public long getThresholdBytes() { - if (freeSpaceThreshold==null) + if (freeSpaceThreshold == null) return DEFAULT_THRESHOLD; // backward compatibility with the data format that didn't have 'freeSpaceThreshold' try { return DiskSpace.parse(freeSpaceThreshold).size; @@ -39,12 +39,12 @@ public abstract class AbstractDiskSpaceMonitor extends NodeMonitor { @Override public Object data(Computer c) { - DiskSpace size = markNodeOfflineIfDiskspaceIsTooLow(c); - - // mark online (again), if free space is over threshold - if(size!=null && size.size > getThresholdBytes() && c.isOffline() && c.getOfflineCause() instanceof DiskSpace) - if(this.getClass().equals(((DiskSpace)c.getOfflineCause()).getTrigger())) - if(getDescriptor().markOnline(c)) { + DiskSpace size = markNodeOfflineIfDiskspaceIsTooLow(c); + + // mark online (again), if free space is over threshold + if (size != null && size.size > getThresholdBytes() && c.isOffline() && c.getOfflineCause() instanceof DiskSpace) + if (this.getClass().equals(((DiskSpace) c.getOfflineCause()).getTrigger())) + if (getDescriptor().markOnline(c)) { LOGGER.info(Messages.DiskSpaceMonitor_MarkedOnline(c.getDisplayName())); } return size; @@ -59,15 +59,15 @@ public abstract class AbstractDiskSpaceMonitor extends NodeMonitor { @Restricted(NoExternalUse.class) public DiskSpace markNodeOfflineIfDiskspaceIsTooLow(Computer c) { DiskSpace size = (DiskSpace) super.data(c); - if(size!=null && size.size < getThresholdBytes()) { - size.setTriggered(this.getClass(), true); - if(getDescriptor().markOffline(c,size)) { - LOGGER.warning(Messages.DiskSpaceMonitor_MarkedOffline(c.getDisplayName())); - } + if (size != null && size.size < getThresholdBytes()) { + size.setTriggered(this.getClass(), true); + if (getDescriptor().markOffline(c, size)) { + LOGGER.warning(Messages.DiskSpaceMonitor_MarkedOffline(c.getDisplayName())); + } } return size; } private static final Logger LOGGER = Logger.getLogger(AbstractDiskSpaceMonitor.class.getName()); - private static final long DEFAULT_THRESHOLD = 1024L*1024*1024; + private static final long DEFAULT_THRESHOLD = 1024L * 1024 * 1024; } diff --git a/core/src/main/java/hudson/node_monitors/AbstractNodeMonitorDescriptor.java b/core/src/main/java/hudson/node_monitors/AbstractNodeMonitorDescriptor.java index 11b11f55a33d6b1391512c750138c675a58e92ea..4a2386c2a1b179a56416b72655ca719776088f9c 100644 --- a/core/src/main/java/hudson/node_monitors/AbstractNodeMonitorDescriptor.java +++ b/core/src/main/java/hudson/node_monitors/AbstractNodeMonitorDescriptor.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.node_monitors; import hudson.Util; @@ -134,7 +135,7 @@ public abstract class AbstractNodeMonitorDescriptor extends Descriptor extends Descriptor monitor() throws InterruptedException { - Map data = new HashMap<>(); - for( Computer c : Jenkins.get().getComputers() ) { + protected Map monitor() throws InterruptedException { + Map data = new HashMap<>(); + for (Computer c : Jenkins.get().getComputers()) { try { - Thread.currentThread().setName("Monitoring "+c.getDisplayName()+" for "+getDisplayName()); + Thread.currentThread().setName("Monitoring " + c.getDisplayName() + " for " + getDisplayName()); - if(c.getChannel()==null) - data.put(c,null); + if (c.getChannel() == null) + data.put(c, null); else - data.put(c,monitor(c)); + data.put(c, monitor(c)); } catch (RuntimeException | IOException e) { - LOGGER.log(Level.WARNING, "Failed to monitor "+c.getDisplayName()+" for "+getDisplayName(), e); + LOGGER.log(Level.WARNING, "Failed to monitor " + c.getDisplayName() + " for " + getDisplayName(), e); } catch (InterruptedException e) { - throw (InterruptedException)new InterruptedException("Node monitoring "+c.getDisplayName()+" for "+getDisplayName()+" aborted.").initCause(e); + throw (InterruptedException) new InterruptedException("Node monitoring " + c.getDisplayName() + " for " + getDisplayName() + " aborted.").initCause(e); } } return data; @@ -168,7 +169,7 @@ public abstract class AbstractNodeMonitorDescriptor extends Descriptor extends Descriptor extends Descriptor extends Descriptor extends Descriptor extends Descriptor data = Collections.emptyMap(); + private /*final*/ Map data = Collections.emptyMap(); private long timestamp; Record() { - super("Monitoring thread for "+getDisplayName()+" started on "+new Date()); + super("Monitoring thread for " + getDisplayName() + " started on " + new Date()); } @Override @@ -301,20 +302,20 @@ public abstract class AbstractNodeMonitorDescriptor extends Descriptor { + private static class GetArchTask extends MasterToSlaveCallable { @Override public String call() { String os = System.getProperty("os.name"); String arch = System.getProperty("os.arch"); - return os+" ("+arch+')'; + return os + " (" + arch + ')'; } private static final long serialVersionUID = 1L; diff --git a/core/src/main/java/hudson/node_monitors/ClockMonitor.java b/core/src/main/java/hudson/node_monitors/ClockMonitor.java index fdbca6b751d749f1778b0d6d258017124ee2a019..6c7dc54f343d713da5b799ef6517d6997072b774 100644 --- a/core/src/main/java/hudson/node_monitors/ClockMonitor.java +++ b/core/src/main/java/hudson/node_monitors/ClockMonitor.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Thomas J. Black - * + * * 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 @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.node_monitors; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; @@ -65,9 +66,9 @@ public class ClockMonitor extends NodeMonitor { } @Override - protected Callable createCallable(Computer c) { + protected Callable createCallable(Computer c) { Node n = c.getNode(); - if(n==null) return null; + if (n == null) return null; return n.getClockDifferenceCallable(); } diff --git a/core/src/main/java/hudson/node_monitors/DiskSpaceMonitor.java b/core/src/main/java/hudson/node_monitors/DiskSpaceMonitor.java index 21d531a9796ba132599b577194d180f814fcf047..bcf96ba02704baecac6a6d11cda2cf7e3ac2b7cb 100644 --- a/core/src/main/java/hudson/node_monitors/DiskSpaceMonitor.java +++ b/core/src/main/java/hudson/node_monitors/DiskSpaceMonitor.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.node_monitors; import hudson.Extension; @@ -43,12 +44,12 @@ import org.kohsuke.stapler.DataBoundConstructor; */ public class DiskSpaceMonitor extends AbstractDiskSpaceMonitor { @DataBoundConstructor - public DiskSpaceMonitor(String freeSpaceThreshold) throws ParseException { + public DiskSpaceMonitor(String freeSpaceThreshold) throws ParseException { super(freeSpaceThreshold); - } + } public DiskSpaceMonitor() {} - + public DiskSpace getFreeSpace(Computer c) { return DESCRIPTOR.get(c); } @@ -69,9 +70,9 @@ public class DiskSpaceMonitor extends AbstractDiskSpaceMonitor { protected Callable createCallable(Computer c) { Node node = c.getNode(); if (node == null) return null; - + FilePath p = node.getRootPath(); - if(p==null) return null; + if (p == null) return null; return p.asCallableWith(new GetUsableSpace()); } diff --git a/core/src/main/java/hudson/node_monitors/DiskSpaceMonitorDescriptor.java b/core/src/main/java/hudson/node_monitors/DiskSpaceMonitorDescriptor.java index ed68ff4576ce64f209710eb57a183edbd406116c..076c2b281c7f1156cde52252b8f5bfbfd955ada8 100644 --- a/core/src/main/java/hudson/node_monitors/DiskSpaceMonitorDescriptor.java +++ b/core/src/main/java/hudson/node_monitors/DiskSpaceMonitorDescriptor.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.node_monitors; import hudson.Functions; @@ -54,7 +55,7 @@ public abstract class DiskSpaceMonitorDescriptor extends AbstractAsyncNodeMonito private final String path; @Exported public final long size; - + private boolean triggered; private Class trigger; @@ -69,12 +70,12 @@ public abstract class DiskSpaceMonitorDescriptor extends AbstractAsyncNodeMonito @Override public String toString() { - if(triggered) { + if (triggered) { return Messages.DiskSpaceMonitorDescriptor_DiskSpace_FreeSpaceTooLow(getGbLeft(), path); } return Messages.DiskSpaceMonitorDescriptor_DiskSpace_FreeSpace(getGbLeft(), path); } - + /** * The path that was checked */ @@ -96,8 +97,8 @@ public abstract class DiskSpaceMonitorDescriptor extends AbstractAsyncNodeMonito */ public String getGbLeft() { long space = size; - space/=1024L; // convert to KB - space/=1024L; // convert to MB + space /= 1024L; // convert to KB + space /= 1024L; // convert to MB return new BigDecimal(space).scaleByPowerOfTen(-3).toPlainString(); } @@ -107,33 +108,33 @@ public abstract class DiskSpaceMonitorDescriptor extends AbstractAsyncNodeMonito */ public String toHtml() { String humanReadableSpace = Functions.humanReadableByteSize(size); - if(triggered) { + if (triggered) { return Util.wrapToErrorSpan(humanReadableSpace); } return humanReadableSpace; } - + /** * Sets whether this disk space amount should be treated as outside * the acceptable conditions or not. */ protected void setTriggered(boolean triggered) { - this.triggered = triggered; + this.triggered = triggered; } - /** + /** * Same as {@link DiskSpace#setTriggered(boolean)}, also sets the trigger class which made the decision */ protected void setTriggered(Class trigger, boolean triggered) { this.trigger = trigger; this.triggered = triggered; } - + @Override public Class getTrigger() { return trigger; } - + /** * Parses a human readable size description like "1GB", "0.5m", etc. into {@link DiskSpace} * @@ -143,23 +144,23 @@ public abstract class DiskSpaceMonitorDescriptor extends AbstractAsyncNodeMonito public static DiskSpace parse(String size) throws ParseException { size = size.toUpperCase(Locale.ENGLISH).trim(); if (size.endsWith("B")) // cut off 'B' from KB, MB, etc. - size = size.substring(0,size.length()-1); + size = size.substring(0, size.length() - 1); - long multiplier=1; + long multiplier = 1; // look for the size suffix. The goal here isn't to detect all invalid size suffix, // so we ignore double suffix like "10gkb" or anything like that. String suffix = "KMGT"; - for (int i=0; i { public GetUsableSpace() {} + @Override public DiskSpace invoke(File f, VirtualChannel channel) throws IOException { long s = f.getUsableSpace(); - if(s<=0) return null; + if (s <= 0) return null; return new DiskSpace(f.getCanonicalPath(), s); } + private static final long serialVersionUID = 1L; } } diff --git a/core/src/main/java/hudson/node_monitors/MonitorMarkedNodeOffline.java b/core/src/main/java/hudson/node_monitors/MonitorMarkedNodeOffline.java index 21cec64d9a1e352a229f889ce4b13e9841f086eb..220774a458ed017f91445cc7923b93cffa9f3ac2 100644 --- a/core/src/main/java/hudson/node_monitors/MonitorMarkedNodeOffline.java +++ b/core/src/main/java/hudson/node_monitors/MonitorMarkedNodeOffline.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.node_monitors; import hudson.Extension; diff --git a/core/src/main/java/hudson/node_monitors/MonitorOfflineCause.java b/core/src/main/java/hudson/node_monitors/MonitorOfflineCause.java index 3c40df208aabe8a3874038a8d41130349a2723cc..7bb30048d872fc68eafbce1a129c403bcec208e4 100644 --- a/core/src/main/java/hudson/node_monitors/MonitorOfflineCause.java +++ b/core/src/main/java/hudson/node_monitors/MonitorOfflineCause.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.node_monitors; import edu.umd.cs.findbugs.annotations.NonNull; diff --git a/core/src/main/java/hudson/node_monitors/NodeMonitor.java b/core/src/main/java/hudson/node_monitors/NodeMonitor.java index 9b11988dc4f772c3a2fa1d6018b13952a93daeb6..eb5a9459c33d6b17b959cc830e938b814092f5eb 100644 --- a/core/src/main/java/hudson/node_monitors/NodeMonitor.java +++ b/core/src/main/java/hudson/node_monitors/NodeMonitor.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Thomas J. Black - * + * * 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 @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.node_monitors; import edu.umd.cs.findbugs.annotations.CheckForNull; @@ -53,7 +54,7 @@ import org.kohsuke.stapler.export.ExportedBean; *

    config.jelly (optional)
    *
    * Configuration fragment to be displayed in {@code http://server/hudson/computer/configure}. - * Used for configuring the threshold for taking nodes offline. + * Used for configuring the threshold for taking nodes offline. * * *

    Persistence

    @@ -144,7 +145,7 @@ public abstract class NodeMonitor implements ExtensionPoint, Describable> all() { + public static DescriptorExtensionList> all() { return Jenkins.get().getDescriptorList(NodeMonitor.class); } } diff --git a/core/src/main/java/hudson/node_monitors/NodeMonitorUpdater.java b/core/src/main/java/hudson/node_monitors/NodeMonitorUpdater.java index d0b36fb9789055ecd913a3145a7fe993dde9d776..10238deb3352a2e8a940571e1437c02427c09218 100644 --- a/core/src/main/java/hudson/node_monitors/NodeMonitorUpdater.java +++ b/core/src/main/java/hudson/node_monitors/NodeMonitorUpdater.java @@ -36,7 +36,7 @@ public class NodeMonitorUpdater extends ComputerListener { */ @Override public void onOnline(Computer c, TaskListener listener) throws IOException, InterruptedException { - synchronized(this) { + synchronized (this) { future.cancel(false); future = Timer.get().schedule(MONITOR_UPDATER, 5, TimeUnit.SECONDS); } diff --git a/core/src/main/java/hudson/node_monitors/ResponseTimeMonitor.java b/core/src/main/java/hudson/node_monitors/ResponseTimeMonitor.java index 3ecfabbdaac942e5699fac2f55e88daea34f2591..8932941432c1b55a784c582569cdad5455ad7177 100644 --- a/core/src/main/java/hudson/node_monitors/ResponseTimeMonitor.java +++ b/core/src/main/java/hudson/node_monitors/ResponseTimeMonitor.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Red Hat, Inc. - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.node_monitors; import hudson.Extension; @@ -46,7 +47,7 @@ public class ResponseTimeMonitor extends NodeMonitor { public static final AbstractNodeMonitorDescriptor DESCRIPTOR = new AbstractAsyncNodeMonitorDescriptor() { @Override - protected Callable createCallable(Computer c) { + protected Callable createCallable(Computer c) { return new Step1(get(c)); } @@ -62,12 +63,12 @@ public class ResponseTimeMonitor extends NodeMonitor { continue; } - if (d ==null) { + if (d == null) { // if we failed to monitor, put in the special value that indicates a failure - e.setValue(d=new Data(get(c),-1L)); + e.setValue(d = new Data(get(c), -1L)); } - if(d.hasTooManyTimeouts() && !isIgnored()) { + if (d.hasTooManyTimeouts() && !isIgnored()) { // unlike other monitors whose failure still allow us to communicate with the agent, // the failure in this monitor indicates that we are just unable to make any requests // to this agent. So we should severe the connection, as opposed to marking it temporarily @@ -90,7 +91,7 @@ public class ResponseTimeMonitor extends NodeMonitor { } }; - private static final class Step1 extends MasterToSlaveCallable { + private static final class Step1 extends MasterToSlaveCallable { private Data cur; private Step1(Data cur) { @@ -100,7 +101,7 @@ public class ResponseTimeMonitor extends NodeMonitor { @Override public Data call() { // this method must be being invoked locally, which means the roundtrip time is zero and zero forever - return new Data(cur,0); + return new Data(cur, 0); } private Object writeReplace() { @@ -110,7 +111,7 @@ public class ResponseTimeMonitor extends NodeMonitor { private static final long serialVersionUID = 1L; } - private static final class Step2 extends MasterToSlaveCallable { + private static final class Step2 extends MasterToSlaveCallable { private final Data cur; private final long start = System.currentTimeMillis(); @@ -121,7 +122,7 @@ public class ResponseTimeMonitor extends NodeMonitor { @Override public Step3 call() { // this method must be being invoked locally, which means the roundtrip time is zero and zero forever - return new Step3(cur,start); + return new Step3(cur, start); } private static final long serialVersionUID = 1L; @@ -156,13 +157,13 @@ public class ResponseTimeMonitor extends NodeMonitor { private final long[] past5; private Data(Data old, long newDataPoint) { - if(old==null) + if (old == null) past5 = new long[] {newDataPoint}; else { - past5 = new long[Math.min(5,old.past5.length+1)]; + past5 = new long[Math.min(5, old.past5.length + 1)]; int copyLen = past5.length - 1; - System.arraycopy(old.past5, old.past5.length-copyLen, this.past5, 0, copyLen); - past5[past5.length-1] = newDataPoint; + System.arraycopy(old.past5, old.past5.length - copyLen, this.past5, 0, copyLen); + past5[past5.length - 1] = newDataPoint; } } @@ -170,9 +171,9 @@ public class ResponseTimeMonitor extends NodeMonitor { * Computes the recurrence of the time out */ private int failureCount() { - int cnt=0; + int cnt = 0; //noinspection StatementWithEmptyBody - for(int i=past5.length-1; i>=0 && past5[i]<0; i--, cnt++) + for (int i = past5.length - 1; i >= 0 && past5[i] < 0; i--, cnt++) ; return cnt; } @@ -182,16 +183,16 @@ public class ResponseTimeMonitor extends NodeMonitor { */ @Exported public long getAverage() { - long total=0; + long total = 0; for (long l : past5) { - if(l<0) total += TIMEOUT; + if (l < 0) total += TIMEOUT; else total += l; } - return total/past5.length; + return total / past5.length; } public boolean hasTooManyTimeouts() { - return failureCount()>=5; + return failureCount() >= 5; } /** @@ -200,9 +201,9 @@ public class ResponseTimeMonitor extends NodeMonitor { @Override public String toString() { int fc = failureCount(); - if(fc>0) + if (fc > 0) return Messages.ResponseTimeMonitor_TimeOut(fc); - return getAverage()+"ms"; + return getAverage() + "ms"; } @Override diff --git a/core/src/main/java/hudson/node_monitors/SwapSpaceMonitor.java b/core/src/main/java/hudson/node_monitors/SwapSpaceMonitor.java index 65b0083c754c961bb868dd6338ecc12b5cb2cb3d..286274b42fe5821ae81c81f9c36cfdab31765c30 100644 --- a/core/src/main/java/hudson/node_monitors/SwapSpaceMonitor.java +++ b/core/src/main/java/hudson/node_monitors/SwapSpaceMonitor.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Seiji Sogabe - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.node_monitors; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; @@ -50,15 +51,15 @@ public class SwapSpaceMonitor extends NodeMonitor { * Returns the HTML representation of the space. */ public String toHtml(MemoryUsage usage) { - if(usage.availableSwapSpace==-1) + if (usage.availableSwapSpace == -1) return "N/A"; String humanReadableSpace = Functions.humanReadableByteSize(usage.availableSwapSpace); - + long free = usage.availableSwapSpace; - free/=1024L; // convert to KB - free/=1024L; // convert to MB - if(free>256 || usage.totalSwapSpace 256 || usage.totalSwapSpace < usage.availableSwapSpace * 5) return humanReadableSpace; // if we have more than 256MB free or less than 80% filled up, it's OK // Otherwise considered dangerously low. @@ -66,12 +67,12 @@ public class SwapSpaceMonitor extends NodeMonitor { } public long toMB(MemoryUsage usage) { - if(usage.availableSwapSpace==-1) + if (usage.availableSwapSpace == -1) return -1; long free = usage.availableSwapSpace; - free/=1024L; // convert to KB - free/=1024L; // convert to MB + free /= 1024L; // convert to KB + free /= 1024L; // convert to MB return free; } @@ -114,7 +115,7 @@ public class SwapSpaceMonitor extends NodeMonitor { /** * Obtains the string that represents the architecture. */ - private static class MonitorTask extends MasterToSlaveCallable { + private static class MonitorTask extends MasterToSlaveCallable { @Override public MemoryUsage call() throws IOException { MemoryMonitor mm; diff --git a/core/src/main/java/hudson/node_monitors/TemporarySpaceMonitor.java b/core/src/main/java/hudson/node_monitors/TemporarySpaceMonitor.java index db814f99bed99fba865399a78bcda6e98427fe9e..d6b8a4f23359e4e6433bda970eed0a7f86164e19 100644 --- a/core/src/main/java/hudson/node_monitors/TemporarySpaceMonitor.java +++ b/core/src/main/java/hudson/node_monitors/TemporarySpaceMonitor.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.node_monitors; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; @@ -46,9 +47,9 @@ import org.kohsuke.stapler.DataBoundConstructor; */ public class TemporarySpaceMonitor extends AbstractDiskSpaceMonitor { @DataBoundConstructor - public TemporarySpaceMonitor(String freeSpaceThreshold) throws ParseException { + public TemporarySpaceMonitor(String freeSpaceThreshold) throws ParseException { super(freeSpaceThreshold); - } + } public TemporarySpaceMonitor() {} @@ -83,12 +84,12 @@ public class TemporarySpaceMonitor extends AbstractDiskSpaceMonitor { } @Override - protected Callable createCallable(Computer c) { + protected Callable createCallable(Computer c) { Node node = c.getNode(); if (node == null) return null; - + FilePath p = node.getRootPath(); - if(p==null) return null; + if (p == null) return null; return p.asCallableWith(new GetTempSpace()); } @@ -101,7 +102,7 @@ public class TemporarySpaceMonitor extends AbstractDiskSpaceMonitor { public static DiskSpaceMonitorDescriptor install() { return DESCRIPTOR; } - + protected static final class GetTempSpace extends MasterToSlaveFileCallable { @Override public DiskSpace invoke(File f, VirtualChannel channel) throws IOException { @@ -109,9 +110,10 @@ public class TemporarySpaceMonitor extends AbstractDiskSpaceMonitor { // so calling File.createTempFile and figuring out the directory won't reliably work. f = new File(System.getProperty("java.io.tmpdir")); long s = f.getUsableSpace(); - if(s<=0) return null; + if (s <= 0) return null; return new DiskSpace(f.getCanonicalPath(), s); } + private static final long serialVersionUID = 1L; } } diff --git a/core/src/main/java/hudson/os/PosixAPI.java b/core/src/main/java/hudson/os/PosixAPI.java index c9f40ac31b207559610fc137d250aad62efb00c0..ba1c9aecb957854aedb9c89fb1160c3a45e257cd 100644 --- a/core/src/main/java/hudson/os/PosixAPI.java +++ b/core/src/main/java/hudson/os/PosixAPI.java @@ -12,7 +12,7 @@ import jnr.posix.util.DefaultPOSIXHandler; public class PosixAPI { private static POSIX posix; - + /** * Load the JNR implementation of the POSIX APIs for the current platform. * Runtime exceptions will be of type {@link PosixException}. @@ -26,6 +26,7 @@ public class PosixAPI { @Override public void error(Errno error, String extraData) { throw new PosixException("native error " + error.description() + " " + extraData); } + @Override public void error(Errno error, String methodName, String extraData) { throw new PosixException("native error calling " + methodName + ": " + error.description() + " " + extraData); } diff --git a/core/src/main/java/hudson/os/SU.java b/core/src/main/java/hudson/os/SU.java index 6a373cd53e0438e2eb7d0f0c73a94d735568aaad..6ba5b055fd33ab0ac9767c0ca781120a7554d3a8 100644 --- a/core/src/main/java/hudson/os/SU.java +++ b/core/src/main/java/hudson/os/SU.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.os; import static hudson.util.jna.GNUCLibrary.LIBC; @@ -71,11 +72,11 @@ public abstract class SU { * Close this channel and the SU environment will be shut down. */ public static VirtualChannel start(final TaskListener listener, final String rootUsername, final String rootPassword) throws IOException, InterruptedException { - if(File.pathSeparatorChar==';') // on Windows + if (File.pathSeparatorChar == ';') // on Windows return newLocalChannel(); // TODO: perhaps use RunAs to run as an Administrator? String os = Util.fixNull(System.getProperty("os.name")); - if(os.equals("Linux")) + if (os.equals("Linux")) return new UnixSu() { @Override protected String sudoExe() { @@ -85,7 +86,7 @@ public abstract class SU { @SuppressFBWarnings(value = {"COMMAND_INJECTION", "DM_DEFAULT_ENCODING"}, justification = "TODO needs triage") @Override protected Process sudoWithPass(ArgumentListBuilder args) throws IOException { - args.prepend(sudoExe(),"-S"); + args.prepend(sudoExe(), "-S"); listener.getLogger().println("$ " + String.join(" ", args.toList())); ProcessBuilder pb = new ProcessBuilder(args.toCommandArray()); Process p = pb.start(); @@ -98,9 +99,9 @@ public abstract class SU { } return p; } - }.start(listener,rootPassword); + }.start(listener, rootPassword); - if(os.equals("SunOS")) + if (os.equals("SunOS")) return new UnixSu() { @Override protected String sudoExe() { @@ -116,7 +117,7 @@ public abstract class SU { } // in solaris, pfexec never asks for a password, so username==null means // we won't be using password. this helps disambiguate empty password - }.start(listener,rootUsername==null?null:rootPassword); + }.start(listener, rootUsername == null ? null : rootPassword); // TODO: Mac? @@ -131,7 +132,7 @@ public abstract class SU { /** * Starts a new privilege-escalated environment, execute a closure, and shut it down. */ - public static V execute(TaskListener listener, String rootUsername, String rootPassword, final Callable closure) throws T, IOException, InterruptedException { + public static V execute(TaskListener listener, String rootUsername, String rootPassword, final Callable closure) throws T, IOException, InterruptedException { VirtualChannel ch = start(listener, rootUsername, rootPassword); try { return ch.call(closure); @@ -150,14 +151,14 @@ public abstract class SU { VirtualChannel start(TaskListener listener, String rootPassword) throws IOException, InterruptedException { final int uid = LIBC.geteuid(); - if(uid==0) // already running as root + if (uid == 0) // already running as root return newLocalChannel(); String javaExe = System.getProperty("java.home") + "/bin/java"; File agentJar = Which.jarFile(Launcher.class); ArgumentListBuilder args = new ArgumentListBuilder().add(javaExe); - if(agentJar.isFile()) + if (agentJar.isFile()) args.add("-jar").add(agentJar); else // in production code this never happens, but during debugging this is convenient args.add("-cp").add(agentJar).add(hudson.remoting.Launcher.class.getName()); @@ -171,7 +172,7 @@ public abstract class SU { // try sudo with the given password. Also run in pfexec so that we can elevate the privileges Process proc = sudoWithPass(args); return Channels.forProcess(args.toStringWithQuote(), Computer.threadPoolForRemoting, proc, - listener.getLogger() ); + listener.getLogger()); } } } diff --git a/core/src/main/java/hudson/scheduler/BaseParser.java b/core/src/main/java/hudson/scheduler/BaseParser.java index e846636d6fed855fffa727cdb56e502f16f3d981..36a71310117731746c8b672ff815845be1ee8606 100644 --- a/core/src/main/java/hudson/scheduler/BaseParser.java +++ b/core/src/main/java/hudson/scheduler/BaseParser.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.scheduler; import antlr.ANTLRException; @@ -38,14 +39,14 @@ import jenkins.util.SystemProperties; */ abstract class BaseParser extends LLkParser { // lower/upper bounds of fields (inclusive) - static final int[] LOWER_BOUNDS = new int[] {0,0,1,1,0}; - static final int[] UPPER_BOUNDS = new int[] {59,23,31,12,7}; + static final int[] LOWER_BOUNDS = new int[] {0, 0, 1, 1, 0}; + static final int[] UPPER_BOUNDS = new int[] {59, 23, 31, 12, 7}; /** * Used to pick a value from within the range */ protected Hash hash = Hash.zero(); - + protected BaseParser(int i) { super(i); } @@ -63,7 +64,7 @@ abstract class BaseParser extends LLkParser { } public void setHash(Hash hash) { - if (hash==null) hash = Hash.zero(); + if (hash == null) hash = Hash.zero(); this.hash = hash; } @@ -72,8 +73,8 @@ abstract class BaseParser extends LLkParser { rangeCheck(end, field); if (step <= 0) error(Messages.BaseParser_MustBePositive(step)); - if (start>end) - error(Messages.BaseParser_StartEndReversed(end,start)); + if (start > end) + error(Messages.BaseParser_StartEndReversed(end, start)); long bits = 0; for (int i = start; i <= end; i += step) { @@ -82,8 +83,8 @@ abstract class BaseParser extends LLkParser { return bits; } - protected long doRange( int step, int field ) throws ANTLRException { - return doRange( LOWER_BOUNDS[field], UPPER_BOUNDS[field], step, field ); + protected long doRange(int step, int field) throws ANTLRException { + return doRange(LOWER_BOUNDS[field], UPPER_BOUNDS[field], step, field); } /** @@ -95,8 +96,8 @@ abstract class BaseParser extends LLkParser { */ protected long doHash(int step, int field) throws ANTLRException { int u = UPPER_BOUNDS[field]; - if (field==2) u = 28; // day of month can vary depending on month, so to make life simpler, just use [1,28] that's always safe - if (field==4) u = 6; // Both 0 and 7 of day of week are Sunday. For better distribution, limit upper bound to 6 + if (field == 2) u = 28; // day of month can vary depending on month, so to make life simpler, just use [1,28] that's always safe + if (field == 4) u = 6; // Both 0 and 7 of day of week are Sunday. For better distribution, limit upper bound to 6 return doHash(LOWER_BOUNDS[field], u, step, field); } @@ -113,19 +114,19 @@ abstract class BaseParser extends LLkParser { } assert bits != 0; return bits; - } else if (step <=0) { + } else if (step <= 0) { error(Messages.BaseParser_MustBePositive(step)); throw new AssertionError(); } else { - assert step==NO_STEP; + assert step == NO_STEP; // step=1 (i.e. omitted) in the case of hash is actually special; means pick one value, not step by 1 - return 1L << (s+hash.next(e+1-s)); + return 1L << (s + hash.next(e + 1 - s)); } } - + protected void rangeCheck(int value, int field) throws ANTLRException { - if( value60) return -1; + while ((bits | (1L << n)) != bits) { + if (n > 60) return -1; n++; } return n; @@ -233,20 +234,20 @@ public final class CronTab { * Given a bit mask, finds the first bit that's on, and return its index. */ private int first(CronTab c) { - return ceil(c,0); + return ceil(c, 0); } private int floor(CronTab c, int n) { long bits = bits(c); - while ((bits|(1L<= firstDayOfWeek) { // in crontab, the first DoW is always Sunday, but in Java, it can be Monday or in theory arbitrary other days. // When first DoW is 1/2 Monday, calendar points to 1/2 Monday, setting the DoW to Sunday makes // the calendar moves forward to 1/8 Sunday, instead of 1/1 Sunday. So we need to compensate that effect here. - addTo(c,-7); + addTo(c, -7); } else if (was < firstDayOfWeek && firstDayOfWeek <= v) { // If we wrap the other way around, we need to adjust in the opposite direction of above. addTo(c, 7); @@ -357,26 +363,26 @@ public final class CronTab { } for (CalendarField f : CalendarField.ADJUST_ORDER) { int cur = f.valueOf(cal); - int next = f.ceil(this,cur); - if (cur==next) continue; // this field is already in a good shape. move on to next + int next = f.ceil(this, cur); + if (cur == next) continue; // this field is already in a good shape. move on to next // we are modifying this field, so clear all the lower level fields - for (CalendarField l=f.lowerField; l!=null; l=l.lowerField) + for (CalendarField l = f.lowerField; l != null; l = l.lowerField) l.clear(cal); - if (next<0) { + if (next < 0) { // we need to roll over to the next field. f.rollUp(cal, 1); - f.setTo(cal,f.first(this)); + f.setTo(cal, f.first(this)); // since higher order field is affected by this, we need to restart from all over continue OUTER; } else { - f.setTo(cal,next); + f.setTo(cal, next); //check if value was actually set if (f.valueOf(cal) != next) { // we need to roll over to the next field. f.rollUp(cal, 1); - f.setTo(cal,f.first(this)); + f.setTo(cal, f.first(this)); // since higher order field is affected by this, we need to restart from all over continue OUTER; } @@ -427,30 +433,30 @@ public final class CronTab { } for (CalendarField f : CalendarField.ADJUST_ORDER) { int cur = f.valueOf(cal); - int next = f.floor(this,cur); - if (cur==next) continue; // this field is already in a good shape. move on to next + int next = f.floor(this, cur); + if (cur == next) continue; // this field is already in a good shape. move on to next // we are modifying this field, so clear all the lower level fields - for (CalendarField l=f.lowerField; l!=null; l=l.lowerField) + for (CalendarField l = f.lowerField; l != null; l = l.lowerField) l.clear(cal); - if (next<0) { + if (next < 0) { // we need to borrow from the next field. - f.rollUp(cal,-1); + f.rollUp(cal, -1); // the problem here, in contrast with the ceil method, is that // the maximum value of the field is not always a fixed value (that is, day of month) // so we zero-clear all the lower fields, set the desired value +1, - f.setTo(cal,f.last(this)); - f.addTo(cal,1); + f.setTo(cal, f.last(this)); + f.addTo(cal, 1); // then subtract a minute to achieve maximum values on all the lower fields, // with the desired value in 'f' - CalendarField.MINUTE.addTo(cal,-1); + CalendarField.MINUTE.addTo(cal, -1); // since higher order field is affected by this, we need to restart from all over continue OUTER; } else { - f.setTo(cal,next); - f.addTo(cal,1); - CalendarField.MINUTE.addTo(cal,-1); + f.setTo(cal, next); + f.addTo(cal, 1); + CalendarField.MINUTE.addTo(cal, -1); if (f.redoAdjustmentIfModified) continue OUTER; // when we modify DAY_OF_MONTH and DAY_OF_WEEK, do it all over from the top } @@ -460,28 +466,28 @@ public final class CronTab { } void set(String format, Hash hash) throws ANTLRException { - set(format,1,hash); + set(format, 1, hash); } /** * Returns true if n-th bit is on. */ private boolean checkBits(long bitMask, int n) { - return (bitMask|(1L<0) + if (i > 0) return Messages.CronTab_do_you_really_mean_every_minute_when_you(spec, "H " + spec.substring(spec.indexOf(' ') + 1)); // once we find a sparse rank, upper ranks don't matter break OUTER; @@ -536,9 +542,9 @@ public final class CronTab { if (spec.contains("H")) { // if someone is already using H, presumably he knows what it is, so a warning is likely false positive return null; - } else if (spec.startsWith("*/")) {// "*/15 ...." (every N minutes) to hash + } else if (spec.startsWith("*/")) { // "*/15 ...." (every N minutes) to hash return "H" + spec.substring(1); - } else if (spec.matches("\\d+ .+")) {// "0 ..." (certain minute) to hash + } else if (spec.matches("\\d+ .+")) { // "0 ..." (certain minute) to hash return "H " + spec.substring(spec.indexOf(' ') + 1); } else { Matcher m = Pattern.compile("0(,(\\d+)(,\\d+)*)( .+)").matcher(spec); diff --git a/core/src/main/java/hudson/scheduler/CronTabList.java b/core/src/main/java/hudson/scheduler/CronTabList.java index 5273629d8b353d8031ef788198fca1ead19050df..7a1b4760ff75108ace4b5b004df549a1fdcbf8a3 100644 --- a/core/src/main/java/hudson/scheduler/CronTabList.java +++ b/core/src/main/java/hudson/scheduler/CronTabList.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.scheduler; import antlr.ANTLRException; @@ -52,7 +53,7 @@ public final class CronTabList { */ public synchronized boolean check(Calendar cal) { for (CronTab tab : tabs) { - if(tab.check(cal)) + if (tab.check(cal)) return true; } return false; @@ -70,7 +71,7 @@ public final class CronTabList { public String checkSanity() { for (CronTab tab : tabs) { String s = tab.checkSanity(); - if(s!=null) return s; + if (s != null) return s; } return null; } @@ -91,7 +92,7 @@ public final class CronTabList { } public static CronTabList create(@NonNull String format) throws ANTLRException { - return create(format,null); + return create(format, null); } public static CronTabList create(@NonNull String format, Hash hash) throws ANTLRException { @@ -102,11 +103,11 @@ public final class CronTabList { for (String line : format.split("\\r?\\n")) { lineNumber++; line = line.trim(); - - if(lineNumber == 1 && line.startsWith("TZ=")) { + + if (lineNumber == 1 && line.startsWith("TZ=")) { final String timezoneString = line.replace("TZ=", ""); timezone = getValidTimezone(timezoneString); - if(timezone != null) { + if (timezone != null) { LOGGER.log(Level.CONFIG, "CRON with timezone {0}", timezone); } else { throw new ANTLRException("Invalid or unsupported timezone '" + timezoneString + "'"); @@ -114,15 +115,15 @@ public final class CronTabList { continue; } - if(line.length()==0 || line.startsWith("#")) + if (line.length() == 0 || line.startsWith("#")) continue; // ignorable line try { - r.add(new CronTab(line,lineNumber,hash,timezone)); + r.add(new CronTab(line, lineNumber, hash, timezone)); } catch (ANTLRException e) { - throw new ANTLRException(Messages.CronTabList_InvalidInput(line,e.toString()),e); + throw new ANTLRException(Messages.CronTabList_InvalidInput(line, e.toString()), e); } } - + return new CronTabList(r); } @@ -149,6 +150,6 @@ public final class CronTabList { } return nearest; } - + private static final Logger LOGGER = Logger.getLogger(CronTabList.class.getName()); } diff --git a/core/src/main/java/hudson/scheduler/Hash.java b/core/src/main/java/hudson/scheduler/Hash.java index 432d3b363069d6822a1eb15c658e9fae74778ce7..eb69cfda04fb5eb45c8158049628997bbb9ba296 100644 --- a/core/src/main/java/hudson/scheduler/Hash.java +++ b/core/src/main/java/hudson/scheduler/Hash.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2012, CloudBees, 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 @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.scheduler; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; @@ -53,19 +54,19 @@ public abstract class Hash { */ public abstract int next(int n); - @SuppressFBWarnings(value="PREDICTABLE_RANDOM", justification = "The random is just used for load distribution.") + @SuppressFBWarnings(value = "PREDICTABLE_RANDOM", justification = "The random is just used for load distribution.") public static Hash from(String seed) { try { MessageDigest md5 = getMd5(); md5.update(seed.getBytes(StandardCharsets.UTF_8)); byte[] digest = md5.digest(); - for (int i=8; i run; + private transient /*final*/ Run run; @Deprecated protected transient /*final*/ AbstractBuild build; /** * @since 1.568 */ - protected AbstractScmTagAction(Run run) { + protected AbstractScmTagAction(Run run) { this.run = run; this.build = run instanceof AbstractBuild ? (AbstractBuild) run : null; } @@ -81,7 +82,7 @@ public abstract class AbstractScmTagAction extends TaskAction implements BuildBa /** * @since 1.568 */ - public Run getRun() { + public Run getRun() { return run; } @@ -108,11 +109,11 @@ public abstract class AbstractScmTagAction extends TaskAction implements BuildBa } public void doIndex(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { - req.getView(this,chooseAction()).forward(req,rsp); + req.getView(this, chooseAction()).forward(req, rsp); } protected synchronized String chooseAction() { - if(workerThread!=null) + if (workerThread != null) return "inProgress.jelly"; return "tagForm.jelly"; } diff --git a/core/src/main/java/hudson/scm/AutoBrowserHolder.java b/core/src/main/java/hudson/scm/AutoBrowserHolder.java index cd14a15c2808c2b0844015fdd8eb03c5118f59a1..f851704ba25ded45e085b84da613df55753ba9a0 100644 --- a/core/src/main/java/hudson/scm/AutoBrowserHolder.java +++ b/core/src/main/java/hudson/scm/AutoBrowserHolder.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.scm; import hudson.model.AbstractProject; @@ -61,7 +62,7 @@ final class AutoBrowserHolder { return cache; } int g = d.getGeneration(); - if(g!=cacheGeneration) { + if (g != cacheGeneration) { cacheGeneration = g; cache = infer(); } @@ -76,10 +77,10 @@ final class AutoBrowserHolder { * null if no applicable configuration was found. */ private RepositoryBrowser infer() { - for( AbstractProject p : Jenkins.get().allItems(AbstractProject.class) ) { + for (AbstractProject p : Jenkins.get().allItems(AbstractProject.class)) { SCM scm = p.getScm(); - if (scm!=null && scm.getClass()==owner.getClass() && scm.getBrowser()!=null && - ((SCMDescriptor)scm.getDescriptor()).isBrowserReusable(scm,owner)) { + if (scm != null && scm.getClass() == owner.getClass() && scm.getBrowser() != null && + ((SCMDescriptor) scm.getDescriptor()).isBrowserReusable(scm, owner)) { return scm.getBrowser(); } } diff --git a/core/src/main/java/hudson/scm/ChangeLogAnnotator.java b/core/src/main/java/hudson/scm/ChangeLogAnnotator.java index daf129aa206fb26423c78f84e738690bc3ae0d86..c76b3f4d0d1584e416a8cbe11cf85834a9aa1e6e 100644 --- a/core/src/main/java/hudson/scm/ChangeLogAnnotator.java +++ b/core/src/main/java/hudson/scm/ChangeLogAnnotator.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.scm; import hudson.Extension; @@ -77,7 +78,7 @@ public abstract class ChangeLogAnnotator implements ExtensionPoint { * will return the same string as {@link ChangeLogSet.Entry#getMsgEscaped()}. * @since 1.568 */ - public void annotate(Run build, ChangeLogSet.Entry change, MarkupText text) { + public void annotate(Run build, ChangeLogSet.Entry change, MarkupText text) { if (build instanceof AbstractBuild && Util.isOverridden(ChangeLogAnnotator.class, getClass(), "annotate", AbstractBuild.class, ChangeLogSet.Entry.class, MarkupText.class)) { annotate((AbstractBuild) build, change, text); } else { @@ -86,7 +87,7 @@ public abstract class ChangeLogAnnotator implements ExtensionPoint { } @Deprecated - public void annotate(AbstractBuild build, ChangeLogSet.Entry change, MarkupText text) { + public void annotate(AbstractBuild build, ChangeLogSet.Entry change, MarkupText text) { annotate((Run) build, change, text); } diff --git a/core/src/main/java/hudson/scm/ChangeLogParser.java b/core/src/main/java/hudson/scm/ChangeLogParser.java index 57062a996bb03895df9b702182cc9a6a95cc8e5b..f38f83660715550cab3ace98c8df67b318ed6f01 100644 --- a/core/src/main/java/hudson/scm/ChangeLogParser.java +++ b/core/src/main/java/hudson/scm/ChangeLogParser.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.scm; import hudson.Util; diff --git a/core/src/main/java/hudson/scm/ChangeLogSet.java b/core/src/main/java/hudson/scm/ChangeLogSet.java index 0b0d9c1d0e9940afd7edf8ac88b0826c23ad093d..a0c4a4c9cd79c0608f07f973167ad3c23ff277c1 100644 --- a/core/src/main/java/hudson/scm/ChangeLogSet.java +++ b/core/src/main/java/hudson/scm/ChangeLogSet.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.scm; import hudson.MarkupText; @@ -50,21 +51,21 @@ import org.kohsuke.stapler.export.ExportedBean; * * @author Kohsuke Kawaguchi */ -@ExportedBean(defaultVisibility=999) +@ExportedBean(defaultVisibility = 999) public abstract class ChangeLogSet implements Iterable { /** * Build whose change log this object represents. */ - private final Run run; + private final Run run; @Deprecated - public final AbstractBuild build; + public final AbstractBuild build; private final RepositoryBrowser browser; /** * @since 1.568 */ - protected ChangeLogSet(Run run, RepositoryBrowser browser) { + protected ChangeLogSet(Run run, RepositoryBrowser browser) { this.run = run; build = run instanceof AbstractBuild ? (AbstractBuild) run : null; this.browser = browser; @@ -74,7 +75,8 @@ public abstract class ChangeLogSet implements Iter protected ChangeLogSet(AbstractBuild build) { this(build, browserFromBuild(build)); } - private static RepositoryBrowser browserFromBuild(AbstractBuild build) { + + private static RepositoryBrowser browserFromBuild(AbstractBuild build) { if (build == null) { // not generally allowed, but sometimes done in unit tests return null; } @@ -84,7 +86,7 @@ public abstract class ChangeLogSet implements Iter /** * @since 1.568 */ - public Run getRun() { + public Run getRun() { return run; } @@ -101,7 +103,7 @@ public abstract class ChangeLogSet implements Iter public abstract boolean isEmptySet(); /** - * All changes in this change set. + * All changes in this change set. */ // method for the remote API. @Exported @@ -135,7 +137,7 @@ public abstract class ChangeLogSet implements Iter return createEmpty((Run) build); } - @ExportedBean(defaultVisibility=999) + @ExportedBean(defaultVisibility = 999) public abstract static class Entry { private ChangeLogSet parent; @@ -216,29 +218,29 @@ public abstract class ChangeLogSet implements Iter */ @Exported public abstract Collection getAffectedPaths(); - + /** * Returns a set of paths in the workspace that was * affected by this change. *

    - * Noted: since this is a new interface, some of the SCMs may not have - * implemented this interface. The default implementation for this + * Noted: since this is a new interface, some of the SCMs may not have + * implemented this interface. The default implementation for this * interface is throw UnsupportedOperationException *

    - * It doesn't throw NoSuchMethodException because I rather to throw a + * It doesn't throw NoSuchMethodException because I rather to throw a * runtime exception * * @return AffectedFile never null. * @since 1.309 */ public Collection getAffectedFiles() { - String scm = "this SCM"; - ChangeLogSet parent = getParent(); - if ( null != parent ) { - String kind = parent.getKind(); - if ( null != kind && kind.trim().length() > 0 ) scm = kind; - } - throw new UnsupportedOperationException("getAffectedFiles() is not implemented by " + scm); + String scm = "this SCM"; + ChangeLogSet parent = getParent(); + if (null != parent) { + String kind = parent.getKind(); + if (null != kind && kind.trim().length() > 0) scm = kind; + } + throw new UnsupportedOperationException("getAffectedFiles() is not implemented by " + scm); } /** @@ -249,9 +251,9 @@ public abstract class ChangeLogSet implements Iter for (ChangeLogAnnotator a : ChangeLogAnnotator.all()) try { a.annotate(parent.run, this, markup); - } catch(RuntimeException e) { + } catch (RuntimeException e) { LOGGER.info("ChangeLogAnnotator " + a.toString() + " failed to annotate message '" + getMsg() + "'; " + e.getMessage()); - } catch(Error e) { + } catch (Error e) { LOGGER.severe("ChangeLogAnnotator " + a + " failed to annotate message '" + getMsg() + "'; " + e.getMessage()); } @@ -264,13 +266,13 @@ public abstract class ChangeLogSet implements Iter public String getMsgEscaped() { return Util.escape(getMsg()); } - + static final Logger LOGGER = Logger.getLogger(ChangeLogSet.Entry.class.getName()); } - + /** * Represents a file change. Contains filename, edit type, etc. - * + * * I checked the API names against some some major SCMs and most SCMs * can adapt to this interface with very little changes * @@ -286,8 +288,8 @@ public abstract class ChangeLogSet implements Iter * @return never null. */ String getPath(); - - + + /** * Return whether the file is new/modified/deleted */ diff --git a/core/src/main/java/hudson/scm/EditType.java b/core/src/main/java/hudson/scm/EditType.java index 178a39a008c22397e427d16c26ef8ca58bbc72ba..7672b09db2e4be1e78ce91579f2ac082c6d0f00a 100644 --- a/core/src/main/java/hudson/scm/EditType.java +++ b/core/src/main/java/hudson/scm/EditType.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.scm; import java.util.Arrays; @@ -55,9 +56,9 @@ public final class EditType implements CustomExportedBean { return name; } - public static final EditType ADD = new EditType("add","The file was added"); - public static final EditType EDIT = new EditType("edit","The file was modified"); - public static final EditType DELETE = new EditType("delete","The file was removed"); + public static final EditType ADD = new EditType("add", "The file was added"); + public static final EditType EDIT = new EditType("edit", "The file was modified"); + public static final EditType DELETE = new EditType("delete", "The file was removed"); - public static final List ALL = Collections.unmodifiableList(Arrays.asList(ADD,EDIT,DELETE)); + public static final List ALL = Collections.unmodifiableList(Arrays.asList(ADD, EDIT, DELETE)); } diff --git a/core/src/main/java/hudson/scm/NullChangeLogParser.java b/core/src/main/java/hudson/scm/NullChangeLogParser.java index 1ab09948bd909b64bc7ef7fb5b2f6543ae8123cb..2832ede7c4b01488f2226149fcf7ff9aa9771d84 100644 --- a/core/src/main/java/hudson/scm/NullChangeLogParser.java +++ b/core/src/main/java/hudson/scm/NullChangeLogParser.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.scm; import hudson.model.Run; @@ -33,13 +34,13 @@ import org.xml.sax.SAXException; * @author Kohsuke Kawaguchi */ public class NullChangeLogParser extends ChangeLogParser { - + public static final NullChangeLogParser INSTANCE = new NullChangeLogParser(); - + @Override public ChangeLogSet parse(Run build, RepositoryBrowser browser, File changelogFile) throws IOException, SAXException { return ChangeLogSet.createEmpty(build); } - + protected Object readResolve() { return INSTANCE; } diff --git a/core/src/main/java/hudson/scm/NullSCM.java b/core/src/main/java/hudson/scm/NullSCM.java index 777db3759e47442b2913f62e0a18076c780e2f69..8d77816886554126a61bf1394afc25a82efb33e3 100644 --- a/core/src/main/java/hudson/scm/NullSCM.java +++ b/core/src/main/java/hudson/scm/NullSCM.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.scm; import hudson.Extension; @@ -48,11 +49,11 @@ public class NullSCM extends SCM { return null; } - @Override public PollingResult compareRemoteRevisionWith(Job project, Launcher launcher, FilePath workspace, TaskListener listener, SCMRevisionState baseline) throws IOException, InterruptedException { + @Override public PollingResult compareRemoteRevisionWith(Job project, Launcher launcher, FilePath workspace, TaskListener listener, SCMRevisionState baseline) throws IOException, InterruptedException { return PollingResult.NO_CHANGES; } - @Override public void checkout(Run build, Launcher launcher, FilePath workspace, TaskListener listener, File changelogFile, SCMRevisionState baseline) throws IOException, InterruptedException { + @Override public void checkout(Run build, Launcher launcher, FilePath workspace, TaskListener listener, File changelogFile, SCMRevisionState baseline) throws IOException, InterruptedException { if (changelogFile != null) { createEmptyChangeLog(changelogFile, listener, "log"); } diff --git a/core/src/main/java/hudson/scm/PollingResult.java b/core/src/main/java/hudson/scm/PollingResult.java index 737851a25cb569f6fc36603cb57e4ad08396978f..bfcb135a63b941d43b9f3894fb9ac55e640e35be 100644 --- a/core/src/main/java/hudson/scm/PollingResult.java +++ b/core/src/main/java/hudson/scm/PollingResult.java @@ -79,14 +79,14 @@ public final class PollingResult implements SerializableOnlyOverRemoting { } public PollingResult(@CheckForNull SCMRevisionState baseline, @CheckForNull SCMRevisionState remote, @NonNull Change change) { - if (change==null) throw new IllegalArgumentException(); + if (change == null) throw new IllegalArgumentException(); this.baseline = baseline; this.remote = remote; this.change = change; } public PollingResult(@NonNull Change change) { - this(null,null,change); + this(null, null, change); } public boolean hasChanges() { diff --git a/core/src/main/java/hudson/scm/RepositoryBrowser.java b/core/src/main/java/hudson/scm/RepositoryBrowser.java index dbeb7390ba4a8d9450cacb7ea049e5c73f464df8..05b095b02bcebadadd8786644a4ccb53cb9ab711 100644 --- a/core/src/main/java/hudson/scm/RepositoryBrowser.java +++ b/core/src/main/java/hudson/scm/RepositoryBrowser.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.scm; import hudson.DescriptorExtensionList; @@ -37,7 +38,7 @@ import org.kohsuke.stapler.export.ExportedBean; /** * Connects Hudson to repository browsers like ViewCVS or FishEye, - * so that Hudson can generate links to them. + * so that Hudson can generate links to them. * *

    * {@link RepositoryBrowser} instance is normally created as @@ -70,24 +71,24 @@ public abstract class RepositoryBrowser extends Ab * If the given string starts with '/', return a string that removes it. */ protected static String trimHeadSlash(String s) { - if(s.startsWith("/")) return s.substring(1); + if (s.startsWith("/")) return s.substring(1); return s; } /** * Normalize the URL so that it ends with '/'. *

    - * An attention is paid to preserve the query parameters in URL if any. + * An attention is paid to preserve the query parameters in URL if any. */ protected static URL normalizeToEndWithSlash(URL url) { - if(url.getPath().endsWith("/")) + if (url.getPath().endsWith("/")) return url; // normalize String q = url.getQuery(); q = q != null ? '?' + q : ""; try { - return new URL(url,url.getPath()+'/'+q); + return new URL(url, url.getPath() + '/' + q); } catch (MalformedURLException e) { // impossible throw new Error(e); @@ -97,7 +98,7 @@ public abstract class RepositoryBrowser extends Ab /** * Returns all the registered {@link RepositoryBrowser} descriptors. */ - public static DescriptorExtensionList,Descriptor>> all() { + public static DescriptorExtensionList, Descriptor>> all() { return (DescriptorExtensionList) Jenkins.get().getDescriptorList(RepositoryBrowser.class); } diff --git a/core/src/main/java/hudson/scm/RepositoryBrowsers.java b/core/src/main/java/hudson/scm/RepositoryBrowsers.java index cc907e72f73e76904629c2a0531f5eaae7883845..0a1e28d1a152997755ebac3d2cbd90cb4fb41e9c 100644 --- a/core/src/main/java/hudson/scm/RepositoryBrowsers.java +++ b/core/src/main/java/hudson/scm/RepositoryBrowsers.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Daniel Dyer, Stephen Connolly - * + * * 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 @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.scm; import hudson.Extension; @@ -45,7 +46,7 @@ public class RepositoryBrowsers { * Use {@link RepositoryBrowser#all()} for read access and {@link Extension} for registration. */ @Deprecated - public static final List>> LIST = new DescriptorList>((Class)RepositoryBrowser.class); + public static final List>> LIST = new DescriptorList>((Class) RepositoryBrowser.class); /** * Only returns those {@link RepositoryBrowser} descriptors that extend from the given type. @@ -53,7 +54,7 @@ public class RepositoryBrowsers { public static List>> filter(Class t) { List>> r = new ArrayList<>(); for (Descriptor> d : RepositoryBrowser.all()) - if(d.isSubTypeOf(t)) + if (d.isSubTypeOf(t)) r.add(d); return r; } @@ -69,7 +70,7 @@ public class RepositoryBrowsers { T createInstance(Class type, StaplerRequest req, String fieldName) throws FormException { List>> list = filter(type); String value = req.getParameter(fieldName); - if(value==null || value.equals("auto")) + if (value == null || value.equals("auto")) return null; // TODO: There was a TODO in the original code, which presumes passing something meaningful to the newInstance() JSON param @@ -85,9 +86,9 @@ public class RepositoryBrowsers { */ public static T createInstance(Class type, StaplerRequest req, JSONObject parent, String fieldName) throws FormException { - JSONObject o = (JSONObject)parent.get(fieldName); - if(o==null) return null; + JSONObject o = (JSONObject) parent.get(fieldName); + if (o == null) return null; - return req.bindJSON(type,o); + return req.bindJSON(type, o); } } diff --git a/core/src/main/java/hudson/scm/SCM.java b/core/src/main/java/hudson/scm/SCM.java index 1e2fdde83ec83ab7f3769e8a3641bf2e7daa6c28..2cadc9344d5d6dbc2d406c476aa9718d3bd78da8 100644 --- a/core/src/main/java/hudson/scm/SCM.java +++ b/core/src/main/java/hudson/scm/SCM.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Stephen Connolly, InfraDNA, 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 @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.scm; import edu.umd.cs.findbugs.annotations.CheckForNull; @@ -139,10 +140,10 @@ public abstract class SCM implements Describable, ExtensionPoint { * @see #guessBrowser */ @SuppressWarnings("deprecation") - @Exported(name="browser") + @Exported(name = "browser") public final @CheckForNull RepositoryBrowser getEffectiveBrowser() { RepositoryBrowser b = getBrowser(); - if(b!=null) + if (b != null) return b; if (useAutoBrowserHolder) { if (autoBrowserHolder == null) { @@ -168,7 +169,7 @@ public abstract class SCM implements Describable, ExtensionPoint { public boolean supportsPolling() { return true; } - + /** * Returns true if this SCM requires a checked out workspace for doing polling. * @@ -192,7 +193,7 @@ public abstract class SCM implements Describable, ExtensionPoint { * @since 1.196 */ public boolean requiresWorkspaceForPolling() { - return true; + return true; } /** @@ -231,10 +232,10 @@ public abstract class SCM implements Describable, ExtensionPoint { * @return * true if {@link SCM} is OK to let Hudson proceed with deleting the workspace. * False to veto the workspace deletion. - * + * * @since 1.568 */ - public boolean processWorkspaceBeforeDeletion(@NonNull Job project, @NonNull FilePath workspace, @NonNull Node node) throws IOException, InterruptedException { + public boolean processWorkspaceBeforeDeletion(@NonNull Job project, @NonNull FilePath workspace, @NonNull Node node) throws IOException, InterruptedException { if (project instanceof AbstractProject) { return processWorkspaceBeforeDeletion((AbstractProject) project, workspace, node); } else { @@ -243,7 +244,7 @@ public abstract class SCM implements Describable, ExtensionPoint { } @Deprecated - public boolean processWorkspaceBeforeDeletion(AbstractProject project, FilePath workspace, Node node) throws IOException, InterruptedException { + public boolean processWorkspaceBeforeDeletion(AbstractProject project, FilePath workspace, Node node) throws IOException, InterruptedException { if (Util.isOverridden(SCM.class, getClass(), "processWorkspaceBeforeDeletion", Job.class, FilePath.class, Node.class)) { return processWorkspaceBeforeDeletion((Job) project, workspace, node); } else { @@ -291,7 +292,7 @@ public abstract class SCM implements Describable, ExtensionPoint { * Call {@link #poll(AbstractProject, Launcher, FilePath, TaskListener, SCMRevisionState)} for use instead. */ @Deprecated - public boolean pollChanges(AbstractProject project, Launcher launcher, FilePath workspace, TaskListener listener) throws IOException, InterruptedException { + public boolean pollChanges(AbstractProject project, Launcher launcher, FilePath workspace, TaskListener listener) throws IOException, InterruptedException { // up until 1.336, this method was abstract, so everyone should have overridden this method // without calling super.pollChanges. So the compatibility implementation is purely for // new implementations that doesn't override this method. @@ -313,7 +314,7 @@ public abstract class SCM implements Describable, ExtensionPoint { *

    * The obtained object is added to the build as an {@link Action} for later retrieval. As an optimization, * {@link SCM} implementation can choose to compute {@link SCMRevisionState} and add it as an action - * during check out, in which case this method will not called. + * during check out, in which case this method will not called. * * @param build * The calculated {@link SCMRevisionState} is for the files checked out in this build. @@ -328,10 +329,10 @@ public abstract class SCM implements Describable, ExtensionPoint { * * @throws InterruptedException * interruption is usually caused by the user aborting the computation. - * this exception should be simply propagated all the way up. + * this exception should be simply propagated all the way up. * @since 1.568 */ - public @CheckForNull SCMRevisionState calcRevisionsFromBuild(@NonNull Run build, @Nullable FilePath workspace, @Nullable Launcher launcher, @NonNull TaskListener listener) throws IOException, InterruptedException { + public @CheckForNull SCMRevisionState calcRevisionsFromBuild(@NonNull Run build, @Nullable FilePath workspace, @Nullable Launcher launcher, @NonNull TaskListener listener) throws IOException, InterruptedException { if (build instanceof AbstractBuild && Util.isOverridden(SCM.class, getClass(), "calcRevisionsFromBuild", AbstractBuild.class, Launcher.class, TaskListener.class)) { return calcRevisionsFromBuild((AbstractBuild) build, launcher, listener); } else { @@ -340,7 +341,7 @@ public abstract class SCM implements Describable, ExtensionPoint { } @Deprecated - public SCMRevisionState calcRevisionsFromBuild(AbstractBuild build, Launcher launcher, TaskListener listener) throws IOException, InterruptedException { + public SCMRevisionState calcRevisionsFromBuild(AbstractBuild build, Launcher launcher, TaskListener listener) throws IOException, InterruptedException { return calcRevisionsFromBuild(build, launcher != null ? build.getWorkspace() : null, launcher, listener); } @@ -348,7 +349,7 @@ public abstract class SCM implements Describable, ExtensionPoint { public SCMRevisionState _calcRevisionsFromBuild(AbstractBuild build, Launcher launcher, TaskListener listener) throws IOException, InterruptedException { return calcRevisionsFromBuild(build, launcher, listener); } - + /** * Compares the current state of the remote repository against the given baseline {@link SCMRevisionState}. * @@ -357,7 +358,7 @@ public abstract class SCM implements Describable, ExtensionPoint { * if there's any difference. In practice, however, comparing two arbitrary repository states is an expensive * operation, so in this abstraction, we chose to mix (1) the act of building up a repository state and * (2) the act of comparing it with the earlier state, so that SCM implementations can implement this - * more easily. + * more easily. * *

    * Multiple invocations of this method may happen over time to make sure that the remote repository @@ -414,19 +415,19 @@ public abstract class SCM implements Describable, ExtensionPoint { } @Deprecated - protected PollingResult compareRemoteRevisionWith(AbstractProject project, Launcher launcher, FilePath workspace, TaskListener listener, SCMRevisionState baseline) throws IOException, InterruptedException { + protected PollingResult compareRemoteRevisionWith(AbstractProject project, Launcher launcher, FilePath workspace, TaskListener listener, SCMRevisionState baseline) throws IOException, InterruptedException { return compareRemoteRevisionWith((Job) project, launcher, workspace, listener, baseline); } /** * Convenience method for the caller to handle the backward compatibility between pre 1.345 SCMs. */ - public final PollingResult poll(AbstractProject project, Launcher launcher, FilePath workspace, TaskListener listener, SCMRevisionState baseline) throws IOException, InterruptedException { + public final PollingResult poll(AbstractProject project, Launcher launcher, FilePath workspace, TaskListener listener, SCMRevisionState baseline) throws IOException, InterruptedException { if (is1_346OrLater()) { // This is to work around JENKINS-5827 in a general way. // don't let the SCM.compareRemoteRevisionWith(...) see SCMRevisionState that it didn't produce. SCMRevisionState baseline2; - if (baseline!=SCMRevisionState.NONE) { + if (baseline != SCMRevisionState.NONE) { baseline2 = baseline; } else { baseline2 = calcRevisionsFromBuild(project.getLastBuild(), launcher, listener); @@ -434,7 +435,7 @@ public abstract class SCM implements Describable, ExtensionPoint { return compareRemoteRevisionWith(project, launcher, workspace, listener, baseline2); } else { - return pollChanges(project,launcher,workspace,listener) ? PollingResult.SIGNIFICANT : PollingResult.NO_CHANGES; + return pollChanges(project, launcher, workspace, listener) ? PollingResult.SIGNIFICANT : PollingResult.NO_CHANGES; } } @@ -447,7 +448,7 @@ public abstract class SCM implements Describable, ExtensionPoint { try { c.getDeclaredMethod("compareRemoteRevisionWith", Job.class, Launcher.class, FilePath.class, TaskListener.class, SCMRevisionState.class); return true; - } catch (NoSuchMethodException e2) {} + } catch (NoSuchMethodException e2) { } } } return false; @@ -534,8 +535,8 @@ public abstract class SCM implements Describable, ExtensionPoint { } @Deprecated - public boolean checkout(AbstractBuild build, Launcher launcher, FilePath workspace, BuildListener listener, @NonNull File changelogFile) throws IOException, InterruptedException { - AbstractBuild prev = build.getPreviousBuild(); + public boolean checkout(AbstractBuild build, Launcher launcher, FilePath workspace, BuildListener listener, @NonNull File changelogFile) throws IOException, InterruptedException { + AbstractBuild prev = build.getPreviousBuild(); checkout((Run) build, launcher, workspace, listener, changelogFile, prev != null ? prev.getAction(SCMRevisionState.class) : null); return true; } @@ -544,14 +545,14 @@ public abstract class SCM implements Describable, ExtensionPoint { * Get a chance to do operations after the workspace i checked out and the changelog is written. * @since 1.568 */ - public void postCheckout(@NonNull Run build, @NonNull Launcher launcher, @NonNull FilePath workspace, @NonNull TaskListener listener) throws IOException, InterruptedException { + public void postCheckout(@NonNull Run build, @NonNull Launcher launcher, @NonNull FilePath workspace, @NonNull TaskListener listener) throws IOException, InterruptedException { if (build instanceof AbstractBuild && listener instanceof BuildListener) { postCheckout((AbstractBuild) build, launcher, workspace, (BuildListener) listener); } } @Deprecated - public void postCheckout(AbstractBuild build, Launcher launcher, FilePath workspace, BuildListener listener) throws IOException, InterruptedException { + public void postCheckout(AbstractBuild build, Launcher launcher, FilePath workspace, BuildListener listener) throws IOException, InterruptedException { if (Util.isOverridden(SCM.class, getClass(), "postCheckout", Run.class, Launcher.class, FilePath.class, TaskListener.class)) { postCheckout((Run) build, launcher, workspace, listener); } @@ -573,9 +574,9 @@ public abstract class SCM implements Describable, ExtensionPoint { * * @since 2.60 */ - public void buildEnvironment(@NonNull Run build, @NonNull Map env) { + public void buildEnvironment(@NonNull Run build, @NonNull Map env) { if (build instanceof AbstractBuild) { - buildEnvVars((AbstractBuild)build, env); + buildEnvVars((AbstractBuild) build, env); } } @@ -583,7 +584,7 @@ public abstract class SCM implements Describable, ExtensionPoint { * @deprecated in favor of {@link #buildEnvironment(Run, Map)}. */ @Deprecated - public void buildEnvVars(AbstractBuild build, Map env) { + public void buildEnvVars(AbstractBuild build, Map env) { if (Util.isOverridden(SCM.class, getClass(), "buildEnvironment", Run.class, Map.class)) { buildEnvironment(build, env); } @@ -642,16 +643,16 @@ public abstract class SCM implements Describable, ExtensionPoint { // For backwards compatibility, call the one argument version of the method. return getModuleRoot(workspace); } - + /** * @deprecated since 1.382 * Use/override {@link #getModuleRoot(FilePath, AbstractBuild)} instead. */ @Deprecated public FilePath getModuleRoot(FilePath workspace) { - if (Util.isOverridden(SCM.class,getClass(),"getModuleRoot", FilePath.class,AbstractBuild.class)) + if (Util.isOverridden(SCM.class, getClass(), "getModuleRoot", FilePath.class, AbstractBuild.class)) // if the subtype already implements newer getModuleRoot(FilePath,AbstractBuild), call that. - return getModuleRoot(workspace,null); + return getModuleRoot(workspace, null); return workspace; } @@ -690,23 +691,23 @@ public abstract class SCM implements Describable, ExtensionPoint { * @since 1.382 */ public FilePath[] getModuleRoots(FilePath workspace, AbstractBuild build) { - if (Util.isOverridden(SCM.class,getClass(),"getModuleRoots", FilePath.class)) + if (Util.isOverridden(SCM.class, getClass(), "getModuleRoots", FilePath.class)) // if the subtype derives legacy getModuleRoots(FilePath), delegate to it return getModuleRoots(workspace); // otherwise the default implementation - return new FilePath[]{getModuleRoot(workspace,build)}; + return new FilePath[]{getModuleRoot(workspace, build)}; } - + /** * @deprecated as of 1.382. * Use/derive from {@link #getModuleRoots(FilePath, AbstractBuild)} instead. */ @Deprecated public FilePath[] getModuleRoots(FilePath workspace) { - if (Util.isOverridden(SCM.class,getClass(),"getModuleRoots", FilePath.class, AbstractBuild.class)) + if (Util.isOverridden(SCM.class, getClass(), "getModuleRoots", FilePath.class, AbstractBuild.class)) // if the subtype already derives newer getModuleRoots(FilePath,AbstractBuild), delegate to it - return getModuleRoots(workspace,null); + return getModuleRoots(workspace, null); // otherwise the default implementation return new FilePath[] { getModuleRoot(workspace), }; @@ -742,13 +743,13 @@ public abstract class SCM implements Describable, ExtensionPoint { */ protected final void createEmptyChangeLog(@NonNull File changelogFile, @NonNull TaskListener listener, @NonNull String rootTag) throws IOException { try (Writer w = Files.newBufferedWriter(Util.fileToPath(changelogFile), Charset.defaultCharset())) { - w.write("<"+rootTag +"/>"); + w.write("<" + rootTag + "/>"); } } protected final String nullify(String s) { - if(s==null) return null; - if(s.trim().length()==0) return null; + if (s == null) return null; + if (s.trim().length() == 0) return null; return s; } @@ -757,12 +758,12 @@ public abstract class SCM implements Describable, ExtensionPoint { * Permission to create new tags. * @since 1.171 */ - public static final Permission TAG = new Permission(PERMISSIONS,"Tag",Messages._SCM_TagPermission_Description(),Permission.CREATE, PermissionScope.ITEM); + public static final Permission TAG = new Permission(PERMISSIONS, "Tag", Messages._SCM_TagPermission_Description(), Permission.CREATE, PermissionScope.ITEM); /** * Returns all the registered {@link SCMDescriptor}s. */ - public static DescriptorExtensionList> all() { + public static DescriptorExtensionList> all() { return Jenkins.get().getDescriptorList(SCM.class); } @@ -774,16 +775,16 @@ public abstract class SCM implements Describable, ExtensionPoint { * @since 1.568 */ public static List> _for(@CheckForNull final Job project) { - if(project==null) return all(); - + if (project == null) return all(); + final Descriptor pd = Jenkins.get().getDescriptor((Class) project.getClass()); List> r = new ArrayList<>(); for (SCMDescriptor scmDescriptor : all()) { - if(!scmDescriptor.isApplicable(project)) continue; + if (!scmDescriptor.isApplicable(project)) continue; if (pd instanceof TopLevelItemDescriptor) { TopLevelItemDescriptor apd = (TopLevelItemDescriptor) pd; - if(!apd.isApplicable(scmDescriptor)) continue; + if (!apd.isApplicable(scmDescriptor)) continue; } r.add(scmDescriptor); diff --git a/core/src/main/java/hudson/scm/SCMDescriptor.java b/core/src/main/java/hudson/scm/SCMDescriptor.java index f7d61f1f7323391dfacc6de6685c68f81ea6b759..b9a600a9a324584f8981c321248b8d91331dbe74 100644 --- a/core/src/main/java/hudson/scm/SCMDescriptor.java +++ b/core/src/main/java/hudson/scm/SCMDescriptor.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.scm; import static java.util.logging.Level.WARNING; @@ -101,13 +102,13 @@ public abstract class SCMDescriptor extends Descriptor { public void load() { Class rb = repositoryBrowser; super.load(); - if (repositoryBrowser!=rb) { // XStream may overwrite even the final field. + if (repositoryBrowser != rb) { // XStream may overwrite even the final field. try { Field f = SCMDescriptor.class.getDeclaredField("repositoryBrowser"); f.setAccessible(true); - f.set(this,rb); + f.set(this, rb); } catch (NoSuchFieldException | IllegalAccessException e) { - LOGGER.log(WARNING, "Failed to overwrite the repositoryBrowser field",e); + LOGGER.log(WARNING, "Failed to overwrite the repositoryBrowser field", e); } } } @@ -163,7 +164,7 @@ public abstract class SCMDescriptor extends Descriptor { * can be empty but never null. */ public List>> getBrowserDescriptors() { - if(repositoryBrowser==null) return Collections.emptyList(); + if (repositoryBrowser == null) return Collections.emptyList(); return RepositoryBrowsers.filter(repositoryBrowser); } diff --git a/core/src/main/java/hudson/scm/SCMS.java b/core/src/main/java/hudson/scm/SCMS.java index 56c9d405e4db8231b5b468efb9f489e0fafd6220..a8fd4ddc4dc11ff25c5f28a7acdb0a2943611a8b 100644 --- a/core/src/main/java/hudson/scm/SCMS.java +++ b/core/src/main/java/hudson/scm/SCMS.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.scm; import hudson.Extension; @@ -33,7 +34,7 @@ import org.kohsuke.stapler.StaplerRequest; /** * List of all installed SCMs. - * + * * @author Kohsuke Kawaguchi */ public class SCMS { @@ -67,7 +68,7 @@ public class SCMS { */ @Deprecated public static SCM parseSCM(StaplerRequest req) throws FormException, ServletException { - return parseSCM(req,null); + return parseSCM(req, null); } } diff --git a/core/src/main/java/hudson/scm/browsers/QueryBuilder.java b/core/src/main/java/hudson/scm/browsers/QueryBuilder.java index 04dffed3e15c6fe7ae2ce10fd2565334d7c8aaf3..06d933aa7ef346ed6ad22eaed54656b326035cdb 100644 --- a/core/src/main/java/hudson/scm/browsers/QueryBuilder.java +++ b/core/src/main/java/hudson/scm/browsers/QueryBuilder.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.scm.browsers; /** @@ -36,8 +37,8 @@ public final class QueryBuilder { } public QueryBuilder add(String s) { - if(s==null) return this; // nothing to add - if(buf.length()==0) buf.append('?'); + if (s == null) return this; // nothing to add + if (buf.length() == 0) buf.append('?'); else buf.append('&'); buf.append(s); return this; diff --git a/core/src/main/java/hudson/search/CollectionSearchIndex.java b/core/src/main/java/hudson/search/CollectionSearchIndex.java index 35c4e8f11ca1a63ad93ea14a44fedbb817fcff48..b6bb423d40f42b5fccd0568778862ed8e9b77b29 100644 --- a/core/src/main/java/hudson/search/CollectionSearchIndex.java +++ b/core/src/main/java/hudson/search/CollectionSearchIndex.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.search; import edu.umd.cs.findbugs.annotations.NonNull; @@ -31,7 +32,7 @@ import java.util.Map; /** * {@link SearchIndex} built on a {@link Map}. - * + * * @author Kohsuke Kawaguchi */ public abstract class CollectionSearchIndex implements SearchIndex { @@ -55,21 +56,21 @@ public abstract class CollectionSearchIndex i @Override public void find(String token, List result) { SearchItem p = get(token); - if(p!=null) + if (p != null) result.add(p); } @Override public void suggest(String token, List result) { boolean isCaseSensitive = UserSearchProperty.isCaseInsensitive(); - if(isCaseSensitive){ + if (isCaseSensitive) { token = token.toLowerCase(); } for (SMT o : allAsIterable()) { String name = getName(o); - if(isCaseSensitive) - name=name.toLowerCase(); - if(o!=null && name.contains(token)) + if (isCaseSensitive) + name = name.toLowerCase(); + if (o != null && name.contains(token)) result.add(o); } } diff --git a/core/src/main/java/hudson/search/FixedSet.java b/core/src/main/java/hudson/search/FixedSet.java index 7c44604251e88b8a17b170592dcf95f6940f19d4..dfe413fbf7377ae0b9f72762847b28ccfb19a934 100644 --- a/core/src/main/java/hudson/search/FixedSet.java +++ b/core/src/main/java/hudson/search/FixedSet.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.search; import java.util.Arrays; diff --git a/core/src/main/java/hudson/search/ParsedQuickSilver.java b/core/src/main/java/hudson/search/ParsedQuickSilver.java index dc40d30e788420fd8b4692aabe6d6ed3283ba367..dc214892ac008635772231a0f6bc4a72bb5d0a9c 100644 --- a/core/src/main/java/hudson/search/ParsedQuickSilver.java +++ b/core/src/main/java/hudson/search/ParsedQuickSilver.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.search; import java.beans.Introspector; @@ -39,12 +40,12 @@ import java.util.Map; * @author Kohsuke Kawaguchi */ final class ParsedQuickSilver { - private static final Map TABLE = new HashMap<>(); + private static final Map TABLE = new HashMap<>(); static synchronized ParsedQuickSilver get(Class clazz) { ParsedQuickSilver pqs = TABLE.get(clazz); - if(pqs==null) - TABLE.put(clazz,pqs = new ParsedQuickSilver(clazz)); + if (pqs == null) + TABLE.put(clazz, pqs = new ParsedQuickSilver(clazz)); return pqs; } @@ -55,24 +56,24 @@ final class ParsedQuickSilver { for (Method m : clazz.getMethods()) { qs = m.getAnnotation(QuickSilver.class); - if(qs!=null) { + if (qs != null) { String url = stripGetPrefix(m); - if(qs.value().length==0) - getters.add(new MethodGetter(url,splitName(url),m)); + if (qs.value().length == 0) + getters.add(new MethodGetter(url, splitName(url), m)); else { for (String name : qs.value()) - getters.add(new MethodGetter(url,name,m)); + getters.add(new MethodGetter(url, name, m)); } } } for (Field f : clazz.getFields()) { qs = f.getAnnotation(QuickSilver.class); - if(qs!=null) { - if(qs.value().length==0) - getters.add(new FieldGetter(f.getName(),splitName(f.getName()),f)); + if (qs != null) { + if (qs.value().length == 0) + getters.add(new FieldGetter(f.getName(), splitName(f.getName()), f)); else { for (String name : qs.value()) - getters.add(new FieldGetter(f.getName(),name,f)); + getters.add(new FieldGetter(f.getName(), name, f)); } } } @@ -82,9 +83,9 @@ final class ParsedQuickSilver { * Convert names like "abcDefGhi" to "abc def ghi". */ private String splitName(String url) { - StringBuilder buf = new StringBuilder(url.length()+5); - for(String token : url.split("(?<=[a-z])(?=[A-Z])")) { - if(buf.length()>0) buf.append(' '); + StringBuilder buf = new StringBuilder(url.length() + 5); + for (String token : url.split("(?<=[a-z])(?=[A-Z])")) { + if (buf.length() > 0) buf.append(' '); buf.append(Introspector.decapitalize(token)); } return buf.toString(); @@ -92,7 +93,7 @@ final class ParsedQuickSilver { private String stripGetPrefix(Method m) { String n = m.getName(); - if(n.startsWith("get")) + if (n.startsWith("get")) n = Introspector.decapitalize(n.substring(3)); return n; } @@ -175,7 +176,7 @@ final class ParsedQuickSilver { @Override public SearchIndex getSearchIndex() { Object child = getter.get(instance); - if(child==null) return SearchIndex.EMPTY; + if (child == null) return SearchIndex.EMPTY; return ((SearchableModelObject) child).getSearchIndex(); } }); diff --git a/core/src/main/java/hudson/search/QuickSilver.java b/core/src/main/java/hudson/search/QuickSilver.java index 43d71b9a61bd7431be16b5b10daf082005c31321..ad214694f5efc3ea8f09daa14f2d580a43aa3aeb 100644 --- a/core/src/main/java/hudson/search/QuickSilver.java +++ b/core/src/main/java/hudson/search/QuickSilver.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.search; import static java.lang.annotation.ElementType.FIELD; diff --git a/core/src/main/java/hudson/search/Search.java b/core/src/main/java/hudson/search/Search.java index 37971a7ee73138a316ba6f967d33aedee7abfdc1..9c9aac5e72d6dd0299e8399d8b7662043117b9b8 100644 --- a/core/src/main/java/hudson/search/Search.java +++ b/core/src/main/java/hudson/search/Search.java @@ -22,6 +22,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.search; import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND; @@ -69,21 +70,21 @@ public class Search implements StaplerProxy { public void doIndex(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { List l = req.getAncestors(); - for( int i=l.size()-1; i>=0; i-- ) { + for (int i = l.size() - 1; i >= 0; i--) { Ancestor a = l.get(i); if (a.getObject() instanceof SearchableModelObject) { SearchableModelObject smo = (SearchableModelObject) a.getObject(); - if(LOGGER.isLoggable(Level.FINE)){ - LOGGER.fine(String.format("smo.displayName=%s, searchName=%s",smo.getDisplayName(), smo.getSearchName())); + if (LOGGER.isLoggable(Level.FINE)) { + LOGGER.fine(String.format("smo.displayName=%s, searchName=%s", smo.getDisplayName(), smo.getSearchName())); } SearchIndex index = smo.getSearchIndex(); String query = req.getParameter("q"); - if(query!=null) { + if (query != null) { SuggestedItem target = find(index, query, smo); - if(target!=null) { + if (target != null) { // found - rsp.sendRedirect2(req.getContextPath()+target.getUrl()); + rsp.sendRedirect2(req.getContextPath() + target.getUrl()); return; } } @@ -92,7 +93,7 @@ public class Search implements StaplerProxy { // no exact match. show the suggestions rsp.setStatus(SC_NOT_FOUND); - req.getView(this,"search-failed.jelly").forward(req,rsp); + req.getView(this, "search-failed.jelly").forward(req, rsp); } /** @@ -125,7 +126,7 @@ public class Search implements StaplerProxy { for (SuggestedItem item : getSuggestions(req, query)) r.suggestions.add(new Item(item.getPath())); - rsp.serveExposedBean(req,r,Flavor.JSON); + rsp.serveExposedBean(req, r, Flavor.JSON); } /** @@ -141,11 +142,11 @@ public class Search implements StaplerProxy { int max = req.hasParameter("max") ? Integer.parseInt(req.getParameter("max")) : 100; SearchableModelObject smo = findClosestSearchableModelObject(req); for (SuggestedItem i : suggest(makeSuggestIndex(req), query, smo)) { - if(r.size()>=max) { + if (r.size() >= max) { r.hasMoreResults = true; break; } - if(paths.add(i.getPath())) + if (paths.add(i.getPath())) r.add(i); } return r; @@ -153,10 +154,10 @@ public class Search implements StaplerProxy { private @CheckForNull SearchableModelObject findClosestSearchableModelObject(StaplerRequest req) { List l = req.getAncestors(); - for( int i=l.size()-1; i>=0; i-- ) { + for (int i = l.size() - 1; i >= 0; i--) { Ancestor a = l.get(i); if (a.getObject() instanceof SearchableModelObject) { - return (SearchableModelObject)a.getObject(); + return (SearchableModelObject) a.getObject(); } } return null; @@ -192,7 +193,7 @@ public class Search implements StaplerProxy { public List suggestions = new ArrayList<>(); } - @ExportedBean(defaultVisibility=999) + @ExportedBean(defaultVisibility = 999) public static class Item { @Exported @SuppressFBWarnings(value = "URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD", justification = "read by Stapler") @@ -233,11 +234,11 @@ public class Search implements StaplerProxy { * SuggestedItem in the List is returned. */ static SuggestedItem findClosestSuggestedItem(List r, String query) { - for(SuggestedItem curItem : r) { - if(LOGGER.isLoggable(Level.FINE)) { + for (SuggestedItem curItem : r) { + if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(String.format("item's searchUrl:%s;query=%s", curItem.item.getSearchUrl(), query)); } - if(curItem.item.getSearchUrl().contains(Util.rawEncode(query))) { + if (curItem.item.getSearchUrl().contains(Util.rawEncode(query))) { return curItem; } } @@ -262,10 +263,10 @@ public class Search implements StaplerProxy { */ public static SuggestedItem find(SearchIndex index, String query, SearchableModelObject searchContext) { List r = find(Mode.FIND, index, query, searchContext); - if(r.isEmpty()){ + if (r.isEmpty()) { return null; } - else if(1==r.size()){ + else if (1 == r.size()) { return r.get(0); } else { @@ -289,7 +290,7 @@ public class Search implements StaplerProxy { */ public static List suggest(SearchIndex index, final String tokenList, SearchableModelObject searchContext) { - class Tag implements Comparable{ + class Tag implements Comparable { final SuggestedItem item; final int distance; /** If the path to this suggestion starts with the token list, 1. Otherwise 0. */ @@ -297,15 +298,15 @@ public class Search implements StaplerProxy { Tag(SuggestedItem i) { item = i; - distance = EditDistance.editDistance(i.getPath(),tokenList); - prefixMatch = i.getPath().startsWith(tokenList)?1:0; + distance = EditDistance.editDistance(i.getPath(), tokenList); + prefixMatch = i.getPath().startsWith(tokenList) ? 1 : 0; } @Override public int compareTo(Tag that) { - int r = this.prefixMatch -that.prefixMatch; - if(r!=0) return -r; // ones with head match should show up earlier - return this.distance-that.distance; + int r = this.prefixMatch - that.prefixMatch; + if (r != 0) return -r; // ones with head match should show up earlier + return this.distance - that.distance; } } @@ -313,7 +314,7 @@ public class Search implements StaplerProxy { List items = find(Mode.SUGGEST, index, tokenList, searchContext); // sort them - for( SuggestedItem i : items) + for (SuggestedItem i : items) buf.add(new Tag(i)); Collections.sort(buf); items.clear(); @@ -327,7 +328,7 @@ public class Search implements StaplerProxy { private final String[] tokens; TokenList(String tokenList) { - tokens = tokenList!=null ? tokenList.split("(?<=\\s)(?=\\S)") : MemoryReductionUtil.EMPTY_STRING_ARRAY; + tokens = tokenList != null ? tokenList.split("(?<=\\s)(?=\\S)") : MemoryReductionUtil.EMPTY_STRING_ARRAY; } public int length() { return tokens.length; } @@ -342,14 +343,14 @@ public class Search implements StaplerProxy { @Override public String get(int index) { StringBuilder buf = new StringBuilder(); - for(int i=start; i<=start+index; i++ ) + for (int i = start; i <= start + index; i++) buf.append(tokens[i]); return buf.toString().trim(); } @Override public int size() { - return tokens.length-start; + return tokens.length - start; } }; } @@ -358,7 +359,7 @@ public class Search implements StaplerProxy { @Override public String toString() { StringBuilder s = new StringBuilder("TokenList{"); - for(String token : tokens) { + for (String token : tokens) { s.append(token); s.append(","); } @@ -370,10 +371,10 @@ public class Search implements StaplerProxy { private static List find(Mode m, SearchIndex index, String tokenList, SearchableModelObject searchContext) { TokenList tokens = new TokenList(tokenList); - if(tokens.length()==0) return Collections.emptyList(); // no tokens given + if (tokens.length() == 0) return Collections.emptyList(); // no tokens given - List[] paths = new List[tokens.length()+1]; // we won't use [0]. - for(int i=1;i<=tokens.length();i++) + List[] paths = new List[tokens.length() + 1]; // we won't use [0]. + for (int i = 1; i <= tokens.length(); i++) paths[i] = new ArrayList<>(); List items = new ArrayList<>(); // items found in 1 step @@ -381,28 +382,28 @@ public class Search implements StaplerProxy { LOGGER.log(Level.FINE, "tokens={0}", tokens); // first token - int w=1; // width of token + int w = 1; // width of token for (String token : tokens.subSequence(0)) { items.clear(); - m.find(index,token,items); + m.find(index, token, items); for (SearchItem si : items) { - paths[w].add(SuggestedItem.build(searchContext ,si)); + paths[w].add(SuggestedItem.build(searchContext, si)); LOGGER.log(Level.FINE, "found search item: {0}", si.getSearchName()); } w++; } // successive tokens - for (int j=1; j result) { // no item to contribute } + @Override public void suggest(String token, List result) { // nothing to suggest diff --git a/core/src/main/java/hudson/search/SearchIndexBuilder.java b/core/src/main/java/hudson/search/SearchIndexBuilder.java index b907e02884077cefdcbea30b14b6ae05bebc4c3a..4cf082598b10278bc0e0cfb4de6d8d32b5fa441e 100644 --- a/core/src/main/java/hudson/search/SearchIndexBuilder.java +++ b/core/src/main/java/hudson/search/SearchIndexBuilder.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.search; import hudson.model.AbstractModelObject; @@ -45,7 +46,7 @@ public final class SearchIndexBuilder { * Adds all {@link QuickSilver}-annotated properties to the search index. */ public SearchIndexBuilder addAllAnnotations(SearchableModelObject o) { - ParsedQuickSilver.get(o.getClass()).addTo(this,o); + ParsedQuickSilver.get(o.getClass()).addTo(this, o); return this; } @@ -53,23 +54,23 @@ public final class SearchIndexBuilder { * Short for {@code add(urlAsWellAsName,urlAsWellAsName)} */ public SearchIndexBuilder add(String urlAsWellAsName) { - return add(urlAsWellAsName,urlAsWellAsName); + return add(urlAsWellAsName, urlAsWellAsName); } /** * Adds a search index under the keyword 'name' to the given URL. * * @param url - * Relative URL from the source of the search index. + * Relative URL from the source of the search index. */ public SearchIndexBuilder add(String url, String name) { - items.add(SearchItems.create(name,url)); + items.add(SearchItems.create(name, url)); return this; } public SearchIndexBuilder add(String url, String... names) { for (String name : names) - add(url,name); + add(url, name); return this; } @@ -79,13 +80,13 @@ public final class SearchIndexBuilder { } public SearchIndexBuilder add(String url, SearchableModelObject searchable, String name) { - items.add(SearchItems.create(name,url,searchable)); + items.add(SearchItems.create(name, url, searchable)); return this; } public SearchIndexBuilder add(String url, SearchableModelObject searchable, String... names) { for (String name : names) - add(url,searchable,name); + add(url, searchable, name); return this; } @@ -101,7 +102,7 @@ public final class SearchIndexBuilder { public SearchIndex make() { SearchIndex r = new FixedSet(items); for (SearchIndex index : indices) - r = new UnionSearchIndex(r,index); + r = new UnionSearchIndex(r, index); return r; } } diff --git a/core/src/main/java/hudson/search/SearchItem.java b/core/src/main/java/hudson/search/SearchItem.java index 3da63411ed06057d3454925083c76b5b7daecd39..02b2921b9741dfa03e81c4fb6673f3b4b7bcda72 100644 --- a/core/src/main/java/hudson/search/SearchItem.java +++ b/core/src/main/java/hudson/search/SearchItem.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.search; import hudson.model.Build; @@ -50,6 +51,7 @@ public interface SearchItem { * The path that starts with '/' will be interpreted as the absolute path * (within the context path of Jenkins.) */ + String getSearchUrl(); /** diff --git a/core/src/main/java/hudson/search/SearchItems.java b/core/src/main/java/hudson/search/SearchItems.java index 0f9a2d63dd3da397961b1c82cf9dc779d851430c..3afb24fc46fe3b980c54042be9b54d441c3f5fd8 100644 --- a/core/src/main/java/hudson/search/SearchItems.java +++ b/core/src/main/java/hudson/search/SearchItems.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.search; /** @@ -28,7 +29,7 @@ package hudson.search; */ public class SearchItems { public static SearchItem create(String searchName, String url) { - return create(searchName,url, SearchIndex.EMPTY); + return create(searchName, url, SearchIndex.EMPTY); } public static SearchItem create(final String searchName, final String url, final SearchIndex children) { diff --git a/core/src/main/java/hudson/search/SearchableModelObject.java b/core/src/main/java/hudson/search/SearchableModelObject.java index ebc16348d980e035f7eb6b93e1fe5a366bbac2e8..52bdcc47a587bb4e8ec4275ee34eed1d7b7fb10b 100644 --- a/core/src/main/java/hudson/search/SearchableModelObject.java +++ b/core/src/main/java/hudson/search/SearchableModelObject.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.search; import hudson.model.ModelObject; diff --git a/core/src/main/java/hudson/search/SuggestedItem.java b/core/src/main/java/hudson/search/SuggestedItem.java index 31e5956ce4ed707cdd737a7412e0e5b5282744c9..86dbc36b5fe34111d88bd5bfb21736ba16dbe332 100644 --- a/core/src/main/java/hudson/search/SuggestedItem.java +++ b/core/src/main/java/hudson/search/SuggestedItem.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.search; import hudson.model.Item; @@ -37,7 +38,7 @@ public class SuggestedItem { private String path; public SuggestedItem(SearchItem top) { - this(null,top); + this(null, top); } public SuggestedItem(SuggestedItem parent, SearchItem item) { @@ -46,18 +47,18 @@ public class SuggestedItem { } public String getPath() { - if(path!=null) return path; - if(parent==null) - return path=item.getSearchName(); + if (path != null) return path; + if (parent == null) + return path = item.getSearchName(); else { StringBuilder buf = new StringBuilder(); getPath(buf); - return path=buf.toString(); + return path = buf.toString(); } } private void getPath(StringBuilder buf) { - if(parent==null) + if (parent == null) buf.append(item.getSearchName()); else { parent.getPath(buf); @@ -71,23 +72,23 @@ public class SuggestedItem { * URL that starts with '/' but doesn't end with '/'. * The path is the combined path from the {@link SearchIndex} where the search started * to the final item found. Thus to convert to the actual URL, the caller would need - * to prepend the URL of the object where the search started. + * to prepend the URL of the object where the search started. */ public String getUrl() { StringBuilder buf = new StringBuilder(); getUrl(buf); return buf.toString(); } - + private static SuggestedItem build(SearchableModelObject searchContext, Item top) { ItemGroup parent = top.getParent(); if (parent instanceof Item) { - Item parentItem = (Item)parent; + Item parentItem = (Item) parent; return new SuggestedItem(build(searchContext, parentItem), top); } return new SuggestedItem(top); } - + /** * Given a SearchItem, builds a SuggestedItem hierarchy by looking up parent items (if applicable). * This allows search results for items not contained within the same {@link ItemGroup} to be distinguished. @@ -96,21 +97,21 @@ public class SuggestedItem { */ public static SuggestedItem build(SearchableModelObject searchContext, SearchItem si) { if (si instanceof Item) { - return build(searchContext, (Item)si); + return build(searchContext, (Item) si); } return new SuggestedItem(si); } private void getUrl(StringBuilder buf) { - if(parent!=null) { + if (parent != null) { parent.getUrl(buf); } String f = item.getSearchUrl(); - if(f.startsWith("/")) { + if (f.startsWith("/")) { buf.setLength(0); buf.append(f); } else { - if(buf.length()==0 || buf.charAt(buf.length()-1)!='/') + if (buf.length() == 0 || buf.charAt(buf.length() - 1) != '/') buf.append('/'); buf.append(f); } diff --git a/core/src/main/java/hudson/search/UnionSearchIndex.java b/core/src/main/java/hudson/search/UnionSearchIndex.java index 6a7a625924f29d9404d6cd2db460a46ed8025844..d32deb5edfe687ffacb4be7541a14f4ff0100ef1 100644 --- a/core/src/main/java/hudson/search/UnionSearchIndex.java +++ b/core/src/main/java/hudson/search/UnionSearchIndex.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.search; import java.util.List; @@ -32,7 +33,7 @@ import java.util.List; */ public class UnionSearchIndex implements SearchIndex { public static SearchIndex combine(SearchIndex... sets) { - SearchIndex p=EMPTY; + SearchIndex p = EMPTY; for (SearchIndex q : sets) { // allow some of the inputs to be null, // and also recognize EMPTY @@ -40,13 +41,13 @@ public class UnionSearchIndex implements SearchIndex { if (p == EMPTY) p = q; else - p = new UnionSearchIndex(p,q); + p = new UnionSearchIndex(p, q); } } return p; } - private final SearchIndex lhs,rhs; + private final SearchIndex lhs, rhs; public UnionSearchIndex(SearchIndex lhs, SearchIndex rhs) { this.lhs = lhs; @@ -55,13 +56,13 @@ public class UnionSearchIndex implements SearchIndex { @Override public void find(String token, List result) { - lhs.find(token,result); - rhs.find(token,result); + lhs.find(token, result); + rhs.find(token, result); } @Override public void suggest(String token, List result) { - lhs.suggest(token,result); - rhs.suggest(token,result); + lhs.suggest(token, result); + rhs.suggest(token, result); } } diff --git a/core/src/main/java/hudson/search/UserSearchProperty.java b/core/src/main/java/hudson/search/UserSearchProperty.java index 7e5d704fd7470b0b36a025e72416530f08198f20..50813ce3c79b49f19670e681329694eb5145c2a6 100644 --- a/core/src/main/java/hudson/search/UserSearchProperty.java +++ b/core/src/main/java/hudson/search/UserSearchProperty.java @@ -23,8 +23,8 @@ public class UserSearchProperty extends hudson.model.UserProperty { public boolean getInsensitiveSearch() { return insensitiveSearch; } - - public static boolean isCaseInsensitive(){ + + public static boolean isCaseInsensitive() { User user = User.current(); if (user == null) { @@ -33,7 +33,7 @@ public class UserSearchProperty extends hudson.model.UserProperty { return user.getProperty(UserSearchProperty.class).getInsensitiveSearch(); } - + @Extension @Symbol("search") public static final class DescriptorImpl extends UserPropertyDescriptor { diff --git a/core/src/main/java/hudson/security/ACL.java b/core/src/main/java/hudson/security/ACL.java index 97980fa0a578b63232b775038653ae7ac10f8a85..039820ef22f3a9091ffc49972a9fa8066f7c3685 100644 --- a/core/src/main/java/hudson/security/ACL.java +++ b/core/src/main/java/hudson/security/ACL.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.security; import edu.umd.cs.findbugs.annotations.CheckForNull; @@ -72,11 +73,11 @@ public abstract class ACL { if (a.equals(SYSTEM2)) { // perhaps redundant given check in AccessControlled return; } - if (!hasPermission2(a,p)) { + if (!hasPermission2(a, p)) { while (!p.enabled && p.impliedBy != null) { p = p.impliedBy; } - throw new AccessDeniedException3(a,p); + throw new AccessDeniedException3(a, p); } } @@ -236,7 +237,7 @@ public abstract class ACL { } if (!hasCreatePermission2(a, c, d)) { throw new AccessDeniedException(Messages.AccessDeniedException2_MissingPermission(a.getName(), - Item.CREATE.group.title+"/"+Item.CREATE.name + Item.CREATE + "/" + d.getDisplayName())); + Item.CREATE.group.title + "/" + Item.CREATE.name + Item.CREATE + "/" + d.getDisplayName())); } } /** @@ -251,6 +252,7 @@ public abstract class ACL { * if the user doesn't have the permission. * @since 2.266 */ + public boolean hasCreatePermission2(@NonNull Authentication a, @NonNull ItemGroup c, @NonNull TopLevelItemDescriptor d) { if (Util.isOverridden(ACL.class, getClass(), "hasCreatePermission", org.acegisecurity.Authentication.class, ItemGroup.class, TopLevelItemDescriptor.class)) { @@ -355,7 +357,7 @@ public abstract class ACL { */ public static final Sid ANONYMOUS = new PrincipalSid(ANONYMOUS_USERNAME); - static final Sid[] AUTOMATIC_SIDS = new Sid[]{EVERYONE,ANONYMOUS}; + static final Sid[] AUTOMATIC_SIDS = new Sid[]{EVERYONE, ANONYMOUS}; /** * The username for the system user @@ -370,7 +372,7 @@ public abstract class ACL { * of acting on behalf of an user, such as doing builds. * @since 2.266 */ - public static final Authentication SYSTEM2 = new UsernamePasswordAuthenticationToken(SYSTEM_USERNAME,"SYSTEM"); + public static final Authentication SYSTEM2 = new UsernamePasswordAuthenticationToken(SYSTEM_USERNAME, "SYSTEM"); /** * @deprecated use {@link #SYSTEM2} @@ -381,12 +383,12 @@ public abstract class ACL { /** * Changes the {@link Authentication} associated with the current thread * to the specified one, and returns the previous security context. - * + * *

    * When the impersonation is over, be sure to restore the previous authentication * via {@code SecurityContextHolder.setContext(returnValueFromThisMethod)}; * or just use {@link #impersonate2(Authentication, Runnable)}. - * + * *

    * We need to create a new {@link SecurityContext} instead of {@link SecurityContext#setAuthentication(Authentication)} * because the same {@link SecurityContext} object is reused for all the concurrent requests from the same session. @@ -443,7 +445,7 @@ public abstract class ACL { * @deprecated use try with resources and {@link #as2(Authentication)} */ @Deprecated - public static V impersonate2(Authentication auth, Callable body) throws T { + public static V impersonate2(Authentication auth, Callable body) throws T { SecurityContext old = impersonate2(auth); try { return body.call(); @@ -457,7 +459,7 @@ public abstract class ACL { * @since 1.587 */ @Deprecated - public static V impersonate(org.acegisecurity.Authentication auth, Callable body) throws T { + public static V impersonate(org.acegisecurity.Authentication auth, Callable body) throws T { return impersonate2(auth.toSpring(), body); } diff --git a/core/src/main/java/hudson/security/ACLContext.java b/core/src/main/java/hudson/security/ACLContext.java index e5b49ff324bee270996ee6d8b57227171a4e0750..9873e65f37629345401d6a353020f1e3aa7f992c 100644 --- a/core/src/main/java/hudson/security/ACLContext.java +++ b/core/src/main/java/hudson/security/ACLContext.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.security; import edu.umd.cs.findbugs.annotations.NonNull; diff --git a/core/src/main/java/hudson/security/AbstractPasswordBasedSecurityRealm.java b/core/src/main/java/hudson/security/AbstractPasswordBasedSecurityRealm.java index 64d579a8c4ab6f60470c3fd667b78989fa8a7964..055c7151a94a69e2a18acd14ddc7d6e5a059d51d 100644 --- a/core/src/main/java/hudson/security/AbstractPasswordBasedSecurityRealm.java +++ b/core/src/main/java/hudson/security/AbstractPasswordBasedSecurityRealm.java @@ -180,7 +180,7 @@ public abstract class AbstractPasswordBasedSecurityRealm extends SecurityRealm { @Override protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { - return doAuthenticate(username,authentication.getCredentials().toString()); + return doAuthenticate(username, authentication.getCredentials().toString()); } } diff --git a/core/src/main/java/hudson/security/AccessControlled.java b/core/src/main/java/hudson/security/AccessControlled.java index a8c8a93a8b57f02fc5ec52417e0aa50fa6cfd340..b0cb2c2a9b82b30fc42c9792ec958d432dd35e03 100644 --- a/core/src/main/java/hudson/security/AccessControlled.java +++ b/core/src/main/java/hudson/security/AccessControlled.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Tom Huybrechts - * + * * 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 @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.security; import edu.umd.cs.findbugs.annotations.NonNull; diff --git a/core/src/main/java/hudson/security/AccessDeniedException2.java b/core/src/main/java/hudson/security/AccessDeniedException2.java index cdb778473ab448a9adf528ee2e3e08b02adfc8ed..00daee721251b951c0b56efb052165ed292482d3 100644 --- a/core/src/main/java/hudson/security/AccessDeniedException2.java +++ b/core/src/main/java/hudson/security/AccessDeniedException2.java @@ -28,12 +28,12 @@ public class AccessDeniedException2 extends AccessDeniedException { public final Permission permission; public AccessDeniedException2(Authentication authentication, Permission permission) { - this(null,authentication,permission); + this(null, authentication, permission); } public AccessDeniedException2(Throwable t, Authentication authentication, Permission permission) { super(Messages.AccessDeniedException2_MissingPermission(authentication.getName(), - permission.group.title+"/"+permission.name), t); + permission.group.title + "/" + permission.name), t); this.authentication = authentication; this.permission = permission; } diff --git a/core/src/main/java/hudson/security/AccessDeniedException3.java b/core/src/main/java/hudson/security/AccessDeniedException3.java index 755def42aee6f903c36d64a8ec6676ed4ae51ec5..82f5d50428cec4179c7182fb8659a21fc6500aba 100644 --- a/core/src/main/java/hudson/security/AccessDeniedException3.java +++ b/core/src/main/java/hudson/security/AccessDeniedException3.java @@ -29,12 +29,12 @@ public class AccessDeniedException3 extends AccessDeniedException { public final Permission permission; public AccessDeniedException3(Authentication authentication, Permission permission) { - this(null,authentication,permission); + this(null, authentication, permission); } public AccessDeniedException3(Throwable t, Authentication authentication, Permission permission) { super(Messages.AccessDeniedException2_MissingPermission(authentication.getName(), - permission.group.title+"/"+permission.name), t); + permission.group.title + "/" + permission.name), t); this.authentication = authentication; this.permission = permission; } @@ -43,16 +43,16 @@ public class AccessDeniedException3 extends AccessDeniedException { * Reports the details of the access failure in HTTP headers to assist diagnosis. */ public void reportAsHeaders(HttpServletResponse rsp) { - rsp.addHeader("X-You-Are-Authenticated-As",authentication.getName()); + rsp.addHeader("X-You-Are-Authenticated-As", authentication.getName()); if (REPORT_GROUP_HEADERS) { for (GrantedAuthority auth : authentication.getAuthorities()) { - rsp.addHeader("X-You-Are-In-Group",auth.getAuthority()); + rsp.addHeader("X-You-Are-In-Group", auth.getAuthority()); } } else { rsp.addHeader("X-You-Are-In-Group-Disabled", "JENKINS-39402: use -Dhudson.security.AccessDeniedException2.REPORT_GROUP_HEADERS=true or use /whoAmI to diagnose"); } rsp.addHeader("X-Required-Permission", permission.getId()); - for (Permission p=permission.impliedBy; p!=null; p=p.impliedBy) { + for (Permission p = permission.impliedBy; p != null; p = p.impliedBy) { rsp.addHeader("X-Permission-Implied-By", p.getId()); } } @@ -63,15 +63,15 @@ public class AccessDeniedException3 extends AccessDeniedException { * but instead of using HTTP headers, this version is meant to go inside the payload. */ public void report(PrintWriter w) { - w.println("You are authenticated as: "+authentication.getName()); + w.println("You are authenticated as: " + authentication.getName()); w.println("Groups that you are in:"); for (GrantedAuthority auth : authentication.getAuthorities()) { - w.println(" "+auth.getAuthority()); + w.println(" " + auth.getAuthority()); } - w.println("Permission you need to have (but didn't): "+permission.getId()); - for (Permission p=permission.impliedBy; p!=null; p=p.impliedBy) { - w.println(" ... which is implied by: "+p.getId()); + w.println("Permission you need to have (but didn't): " + permission.getId()); + for (Permission p = permission.impliedBy; p != null; p = p.impliedBy) { + w.println(" ... which is implied by: " + p.getId()); } } } diff --git a/core/src/main/java/hudson/security/AccessDeniedHandlerImpl.java b/core/src/main/java/hudson/security/AccessDeniedHandlerImpl.java index 92c45b0f9fe94b685618c3642b87b718c12a4211..68843cfddd16dcf32c44c77c83951f70962b843e 100644 --- a/core/src/main/java/hudson/security/AccessDeniedHandlerImpl.java +++ b/core/src/main/java/hudson/security/AccessDeniedHandlerImpl.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.security; import java.io.IOException; @@ -46,13 +47,13 @@ public class AccessDeniedHandlerImpl implements AccessDeniedHandler { @Override public void handle(HttpServletRequest req, HttpServletResponse rsp, AccessDeniedException cause) throws IOException, ServletException { rsp.setStatus(HttpServletResponse.SC_FORBIDDEN); - req.setAttribute("exception",cause); + req.setAttribute("exception", cause); if (cause instanceof AccessDeniedException3) { - ((AccessDeniedException3)cause).reportAsHeaders(rsp); + ((AccessDeniedException3) cause).reportAsHeaders(rsp); } WebApp.get(Jenkins.get().servletContext).getSomeStapler() - .invoke(req,rsp, Jenkins.get(), "/accessDenied"); + .invoke(req, rsp, Jenkins.get(), "/accessDenied"); } } diff --git a/core/src/main/java/hudson/security/AuthenticationManagerProxy.java b/core/src/main/java/hudson/security/AuthenticationManagerProxy.java index 9e48891107780662703997aac90cfec422fb77b6..7de8cb39ab5ec665abe031ec5c0e8f6044733edf 100644 --- a/core/src/main/java/hudson/security/AuthenticationManagerProxy.java +++ b/core/src/main/java/hudson/security/AuthenticationManagerProxy.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.security; import org.kohsuke.accmod.Restricted; @@ -48,7 +49,7 @@ public class AuthenticationManagerProxy implements AuthenticationManager { public Authentication authenticate(Authentication authentication) throws AuthenticationException { AuthenticationManager m = delegate; // fix the reference we are working with - if(m ==null) + if (m == null) throw new DisabledException("Authentication service is still not ready yet"); else return m.authenticate(authentication); diff --git a/core/src/main/java/hudson/security/AuthenticationProcessingFilter2.java b/core/src/main/java/hudson/security/AuthenticationProcessingFilter2.java index 6764550ab722f7bae0e8f60a398780b0cea54bee..2714ec8eba635a49445395e7a66a1a2b71efa2b1 100644 --- a/core/src/main/java/hudson/security/AuthenticationProcessingFilter2.java +++ b/core/src/main/java/hudson/security/AuthenticationProcessingFilter2.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Matthew R. Harrah - * + * * 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 @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.security; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; @@ -47,7 +48,7 @@ import org.springframework.security.web.util.matcher.AntPathRequestMatcher; * Login filter with a change for Jenkins so that * we can pick up the hidden "from" form field defined in {@code login.jelly} * to send the user back to where he came from, after a successful authentication. - * + * * @author Kohsuke Kawaguchi */ @Restricted(NoExternalUse.class) diff --git a/core/src/main/java/hudson/security/AuthorizationStrategy.java b/core/src/main/java/hudson/security/AuthorizationStrategy.java index 84c8599abdf8af04546f4888a5b0fcad8f57f6f2..e1ce1596b74accee180f9d9a1aeb575adbc025b4 100644 --- a/core/src/main/java/hudson/security/AuthorizationStrategy.java +++ b/core/src/main/java/hudson/security/AuthorizationStrategy.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Seiji Sogabe, Tom Huybrechts - * + * * 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 @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.security; import edu.umd.cs.findbugs.annotations.NonNull; @@ -63,7 +64,7 @@ import org.kohsuke.stapler.StaplerRequest; * The corresponding {@link Describable} instance will be asked to create a new {@link AuthorizationStrategy} * every time the system configuration is updated. Implementations that keep more state in ACL beyond * the system configuration should use {@link jenkins.model.Jenkins#getAuthorizationStrategy()} to talk to the current - * instance to carry over the state. + * instance to carry over the state. * * @author Kohsuke Kawaguchi * @see SecurityRealm @@ -83,12 +84,12 @@ public abstract class AuthorizationStrategy extends AbstractDescribableImpl project) { - return getACL((Job)project); + public @NonNull ACL getACL(@NonNull AbstractProject project) { + return getACL((Job) project); } - public @NonNull ACL getACL(@NonNull Job project) { - return getRootACL(); + public @NonNull ACL getACL(@NonNull Job project) { + return getRootACL(); } /** @@ -107,13 +108,13 @@ public abstract class AuthorizationStrategy extends AbstractDescribableImpl> all() { + public static @NonNull DescriptorExtensionList> all() { return Jenkins.get().getDescriptorList(AuthorizationStrategy.class); } @@ -201,7 +202,7 @@ public abstract class AuthorizationStrategy extends AbstractDescribableImpl LIST = new DescriptorList<>(AuthorizationStrategy.class); - + /** * {@link AuthorizationStrategy} that implements the semantics * of unsecured Hudson where everyone has full control. diff --git a/core/src/main/java/hudson/security/BasicAuthenticationFilter.java b/core/src/main/java/hudson/security/BasicAuthenticationFilter.java index 5fd45efb0bb61037249c292534367e01076d5334..924c77e25cd5bd2e035c5717fbbbe941414fd677 100644 --- a/core/src/main/java/hudson/security/BasicAuthenticationFilter.java +++ b/core/src/main/java/hudson/security/BasicAuthenticationFilter.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.security; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; @@ -85,7 +86,7 @@ import org.springframework.security.core.userdetails.UserDetails; *

  • * This A → B → A redirect is a cyclic redirection, so we need to watch out for clients * that detect this as an error. - * + * * * @author Kohsuke Kawaguchi */ @@ -104,10 +105,10 @@ public class BasicAuthenticationFilter implements Filter { String authorization = req.getHeader("Authorization"); String path = req.getServletPath(); - if(authorization==null || req.getUserPrincipal() !=null || path.startsWith("/secured/") + if (authorization == null || req.getUserPrincipal() != null || path.startsWith("/secured/") || !Jenkins.get().isUseSecurity()) { // normal requests, or security not enabled - if(req.getUserPrincipal()!=null) { + if (req.getUserPrincipal() != null) { // before we route this request, integrate the container authentication // to Spring Security. For anonymous users that doesn't have user principal, // AnonymousProcessingFilter that follows this should create @@ -115,7 +116,7 @@ public class BasicAuthenticationFilter implements Filter { SecurityContextHolder.getContext().setAuthentication(new ContainerAuthentication(req)); } try { - chain.doFilter(request,response); + chain.doFilter(request, response); } finally { SecurityContextHolder.clearContext(); } @@ -129,18 +130,18 @@ public class BasicAuthenticationFilter implements Filter { int idx = uidpassword.indexOf(':'); if (idx >= 0) { username = uidpassword.substring(0, idx); - password = uidpassword.substring(idx+1); + password = uidpassword.substring(idx + 1); } - if(username==null) { + if (username == null) { rsp.setStatus(HttpServletResponse.SC_UNAUTHORIZED); - rsp.setHeader("WWW-Authenticate","Basic realm=\"Jenkins user\""); + rsp.setHeader("WWW-Authenticate", "Basic realm=\"Jenkins user\""); return; } { User u = BasicApiTokenHelper.isConnectingUsingApiToken(username, password); - if(u != null){ + if (u != null) { UserDetails userDetails = u.getUserDetailsForImpersonation2(); Authentication auth = u.impersonate(userDetails); @@ -148,7 +149,7 @@ public class BasicAuthenticationFilter implements Filter { SecurityContextHolder.getContext().setAuthentication(auth); try { - chain.doFilter(request,response); + chain.doFilter(request, response); } finally { SecurityContextHolder.clearContext(); } @@ -157,24 +158,24 @@ public class BasicAuthenticationFilter implements Filter { } - path = req.getContextPath()+"/secured"+path; + path = req.getContextPath() + "/secured" + path; String q = req.getQueryString(); - if(q!=null) - path += '?'+q; + if (q != null) + path += '?' + q; // prepare a redirect prepareRedirect(rsp, path); // ... but first let the container authenticate this request - RequestDispatcher d = servletContext.getRequestDispatcher("/j_security_check?j_username="+ - URLEncoder.encode(username,"UTF-8")+"&j_password="+URLEncoder.encode(password,"UTF-8")); - d.include(req,rsp); + RequestDispatcher d = servletContext.getRequestDispatcher("/j_security_check?j_username=" + + URLEncoder.encode(username, "UTF-8") + "&j_password=" + URLEncoder.encode(password, "UTF-8")); + d.include(req, rsp); } @SuppressFBWarnings(value = "UNVALIDATED_REDIRECT", justification = "Redirect is validated as processed.") private void prepareRedirect(HttpServletResponse rsp, String path) { rsp.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); - rsp.setHeader("Location",path); + rsp.setHeader("Location", path); } @Override diff --git a/core/src/main/java/hudson/security/ChainedServletFilter.java b/core/src/main/java/hudson/security/ChainedServletFilter.java index b717a314f117bacdc848c8b9e1d9ddd9f3b2feb2..faf9171300a78a2e4248cfa091f289e0e19eb65f 100644 --- a/core/src/main/java/hudson/security/ChainedServletFilter.java +++ b/core/src/main/java/hudson/security/ChainedServletFilter.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.security; import java.io.IOException; @@ -74,6 +75,7 @@ public class ChainedServletFilter implements Filter { } private static final Pattern UNINTERESTING_URIS = Pattern.compile("/(images|jsbundles|css|scripts|adjuncts)/|/favicon[.]ico|/ajax"); + @Override public void doFilter(ServletRequest request, ServletResponse response, final FilterChain chain) throws IOException, ServletException { String uri = request instanceof HttpServletRequest ? ((HttpServletRequest) request).getRequestURI() : "?"; @@ -81,20 +83,20 @@ public class ChainedServletFilter implements Filter { LOGGER.log(level, () -> "starting filter on " + uri); new FilterChain() { - private int position=0; + private int position = 0; // capture the array for thread-safety private final Filter[] filters = ChainedServletFilter.this.filters; @Override public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { - if(position==filters.length) { + if (position == filters.length) { LOGGER.log(level, () -> uri + " end: " + status()); - chain.doFilter(request,response); + chain.doFilter(request, response); } else { Filter next = filters[position++]; try { LOGGER.log(level, () -> uri + " @" + position + " " + next + " »"); - next.doFilter(request,response,this); + next.doFilter(request, response, this); LOGGER.log(level, () -> uri + " @" + position + " " + next + " « success: " + status()); } catch (IOException | ServletException | RuntimeException x) { LOGGER.log(level, () -> uri + " @" + position + " " + next + " « " + x + ": " + status()); @@ -106,7 +108,7 @@ public class ChainedServletFilter implements Filter { private int status() { return response instanceof HttpServletResponse ? ((HttpServletResponse) response).getStatus() : 0; } - }.doFilter(request,response); + }.doFilter(request, response); } diff --git a/core/src/main/java/hudson/security/CliAuthenticator.java b/core/src/main/java/hudson/security/CliAuthenticator.java index 1fd6d4c7400f9cdc262a5f355a787f25790fc727..3b64167c1401a6b29c5939627c4dafe9bcc2e85a 100644 --- a/core/src/main/java/hudson/security/CliAuthenticator.java +++ b/core/src/main/java/hudson/security/CliAuthenticator.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.security; import java.io.IOException; diff --git a/core/src/main/java/hudson/security/ContainerAuthentication.java b/core/src/main/java/hudson/security/ContainerAuthentication.java index 1a9c344af355c97d21a1424733530125853eadbc..be7bdc01ab62373c5767945a292d38a00c3261bf 100644 --- a/core/src/main/java/hudson/security/ContainerAuthentication.java +++ b/core/src/main/java/hudson/security/ContainerAuthentication.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.security; import java.security.Principal; @@ -58,14 +59,14 @@ public final class ContainerAuthentication implements Authentication { */ public ContainerAuthentication(HttpServletRequest request) { this.principal = request.getUserPrincipal(); - if (principal==null) - throw new IllegalStateException(); // for anonymous users, we just don't call SecurityContextHolder.getContext().setAuthentication. + if (principal == null) + throw new IllegalStateException(); // for anonymous users, we just don't call SecurityContextHolder.getContext().setAuthentication. // Servlet API doesn't provide a way to list up all roles the current user // has, so we need to ask AuthorizationStrategy what roles it is going to check against. List l = new ArrayList<>(); - for( String g : Jenkins.get().getAuthorizationStrategy().getGroups()) { - if(request.isUserInRole(g)) + for (String g : Jenkins.get().getAuthorizationStrategy().getGroups()) { + if (request.isUserInRole(g)) l.add(new SimpleGrantedAuthority(g)); } l.add(SecurityRealm.AUTHENTICATED_AUTHORITY2); diff --git a/core/src/main/java/hudson/security/FederatedLoginService.java b/core/src/main/java/hudson/security/FederatedLoginService.java index be1efda827a74ec5e266d3f2661a3375a6ffb890..2d176290d8beeb19599ef816cbfb6a84267823bf 100644 --- a/core/src/main/java/hudson/security/FederatedLoginService.java +++ b/core/src/main/java/hudson/security/FederatedLoginService.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.security; import edu.umd.cs.findbugs.annotations.CheckForNull; @@ -185,16 +186,16 @@ public abstract class FederatedLoginService implements ExtensionPoint { @NonNull public User signin() throws UnclaimedIdentityException { User u = locateUser(); - if (u!=null) { + if (u != null) { // login as this user UserDetails d = Jenkins.get().getSecurityRealm().loadUserByUsername2(u.getId()); - UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(d,"",d.getAuthorities()); + UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(d, "", d.getAuthorities()); token.setDetails(d); SecurityContextHolder.getContext().setAuthentication(token); return u; } else { - // Unassociated identity. + // Unassociated identity. throw new UnclaimedIdentityException(this); } } @@ -209,7 +210,7 @@ public abstract class FederatedLoginService implements ExtensionPoint { */ public void addToCurrentUser() throws IOException { User u = User.current(); - if (u==null) throw new IllegalStateException("Current request is unauthenticated"); + if (u == null) throw new IllegalStateException("Current request is unauthenticated"); addTo(u); } @@ -219,7 +220,7 @@ public abstract class FederatedLoginService implements ExtensionPoint { */ public void addTo(User u) throws IOException { FederatedLoginServiceUserProperty p = u.getProperty(getUserPropertyClass()); - if (p==null) { + if (p == null) { p = (FederatedLoginServiceUserProperty) UserProperty.all().find(getUserPropertyClass()).newInstance(u); u.addProperty(p); } @@ -248,7 +249,7 @@ public abstract class FederatedLoginService implements ExtensionPoint { SecurityRealm sr = Jenkins.get().getSecurityRealm(); if (sr.allowsSignup()) { try { - sr.commenceSignup(identity).generateResponse(req,rsp,node); + sr.commenceSignup(identity).generateResponse(req, rsp, node); return; } catch (UnsupportedOperationException e) { // fall through @@ -257,7 +258,7 @@ public abstract class FederatedLoginService implements ExtensionPoint { // this security realm doesn't support user registration. // just report an error - req.getView(this,"error").forward(req,rsp); + req.getView(this, "error").forward(req, rsp); } } diff --git a/core/src/main/java/hudson/security/FederatedLoginServiceUserProperty.java b/core/src/main/java/hudson/security/FederatedLoginServiceUserProperty.java index b7dfa881c3a924eabe9e4744860153637a4569e2..0961b3a2d8e03cc3d8979a894cffbf78ceee4be5 100644 --- a/core/src/main/java/hudson/security/FederatedLoginServiceUserProperty.java +++ b/core/src/main/java/hudson/security/FederatedLoginServiceUserProperty.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.security; import hudson.model.UserProperty; diff --git a/core/src/main/java/hudson/security/FullControlOnceLoggedInAuthorizationStrategy.java b/core/src/main/java/hudson/security/FullControlOnceLoggedInAuthorizationStrategy.java index b30153ce8f90f2a5f70eebfc716ad4e47cdacb34..7dbb0ab670216391444ef71252f895555983511a 100644 --- a/core/src/main/java/hudson/security/FullControlOnceLoggedInAuthorizationStrategy.java +++ b/core/src/main/java/hudson/security/FullControlOnceLoggedInAuthorizationStrategy.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Seiji Sogabe - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.security; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; @@ -48,7 +49,7 @@ public class FullControlOnceLoggedInAuthorizationStrategy extends AuthorizationS * default is to allow it */ private boolean denyAnonymousReadAccess = false; - + @DataBoundConstructor public FullControlOnceLoggedInAuthorizationStrategy() { } @@ -62,14 +63,14 @@ public class FullControlOnceLoggedInAuthorizationStrategy extends AuthorizationS public List getGroups() { return Collections.emptyList(); } - + /** * If true, anonymous read access will be allowed */ public boolean isAllowAnonymousRead() { return !denyAnonymousReadAccess; } - + @DataBoundSetter public void setAllowAnonymousRead(boolean allowAnonymousRead) { this.denyAnonymousReadAccess = !allowAnonymousRead; @@ -79,10 +80,10 @@ public class FullControlOnceLoggedInAuthorizationStrategy extends AuthorizationS private static final SparseACL ANONYMOUS_READ = new SparseACL(null); static { - ANONYMOUS_READ.add(ACL.EVERYONE, Jenkins.ADMINISTER,true); - ANONYMOUS_READ.add(ACL.ANONYMOUS, Jenkins.ADMINISTER,false); - ANONYMOUS_READ.add(ACL.ANONYMOUS, Permission.READ,true); - + ANONYMOUS_READ.add(ACL.EVERYONE, Jenkins.ADMINISTER, true); + ANONYMOUS_READ.add(ACL.ANONYMOUS, Jenkins.ADMINISTER, false); + ANONYMOUS_READ.add(ACL.ANONYMOUS, Permission.READ, true); + AUTHENTICATED_READ.add(ACL.EVERYONE, Jenkins.ADMINISTER, true); AUTHENTICATED_READ.add(ACL.ANONYMOUS, Jenkins.ADMINISTER, false); } diff --git a/core/src/main/java/hudson/security/GlobalSecurityConfiguration.java b/core/src/main/java/hudson/security/GlobalSecurityConfiguration.java index 17317d2dc61a827f95d044f4df6a550afd716e09..710bb38265ca1fd1079fe9c3e36d725b07219974 100644 --- a/core/src/main/java/hudson/security/GlobalSecurityConfiguration.java +++ b/core/src/main/java/hudson/security/GlobalSecurityConfiguration.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.security; import edu.umd.cs.findbugs.annotations.NonNull; @@ -62,7 +63,7 @@ import org.kohsuke.stapler.verb.POST; */ @Extension(ordinal = Integer.MAX_VALUE - 210) @Symbol("securityConfig") public class GlobalSecurityConfiguration extends ManagementLink implements Describable { - + private static final Logger LOGGER = Logger.getLogger(GlobalSecurityConfiguration.class.getName()); public MarkupFormatter getMarkupFormatter() { @@ -100,11 +101,11 @@ public class GlobalSecurityConfiguration extends ManagementLink implements Descr public synchronized void doConfigure(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException { // for compatibility reasons, the actual value is stored in Jenkins BulkChange bc = new BulkChange(Jenkins.get()); - try{ + try { boolean result = configure(req, req.getSubmittedForm()); - LOGGER.log(Level.FINE, "security saved: "+result); + LOGGER.log(Level.FINE, "security saved: " + result); Jenkins.get().save(); - FormApply.success(req.getContextPath()+"/manage").generateResponse(req, rsp, null); + FormApply.success(req.getContextPath() + "/manage").generateResponse(req, rsp, null); } finally { bc.commit(); } @@ -117,14 +118,14 @@ public class GlobalSecurityConfiguration extends ManagementLink implements Descr j.setDisableRememberMe(json.optBoolean("disableRememberMe", false)); j.setSecurityRealm(SecurityRealm.all().newInstanceFromRadioList(json, "realm")); - j.setAuthorizationStrategy(AuthorizationStrategy.all().newInstanceFromRadioList(json, "authorization")); + j.setAuthorizationStrategy(AuthorizationStrategy.all().newInstanceFromRadioList(json, "authorization")); if (json.has("markupFormatter")) { j.setMarkupFormatter(req.bindJSON(MarkupFormatter.class, json.getJSONObject("markupFormatter"))); } else { j.setMarkupFormatter(null); } - + // Agent settings if (!isSlaveAgentPortEnforced()) { try { @@ -148,26 +149,26 @@ public class GlobalSecurityConfiguration extends ManagementLink implements Descr // persist all the additional security configs boolean result = true; - for(Descriptor d : Functions.getSortedDescriptorsForGlobalConfigByDescriptor(FILTER)){ - result &= configureDescriptor(req,json,d); + for (Descriptor d : Functions.getSortedDescriptorsForGlobalConfigByDescriptor(FILTER)) { + result &= configureDescriptor(req, json, d); } - + return result; } - + private boolean configureDescriptor(StaplerRequest req, JSONObject json, Descriptor d) throws FormException { // collapse the structure to remain backward compatible with the JSON structure before 1. String name = d.getJsonSafeClassName(); JSONObject js = json.has(name) ? json.getJSONObject(name) : new JSONObject(); // if it doesn't have the property, the method returns invalid null object. json.putAll(js); return d.configure(req, js); - } + } @Override public String getDisplayName() { return getDescriptor().getDisplayName(); } - + @Override public String getDescription() { return Messages.GlobalSecurityConfiguration_Description(); @@ -182,7 +183,7 @@ public class GlobalSecurityConfiguration extends ManagementLink implements Descr public String getUrlName() { return "configureSecurity"; } - + @Override public Permission getRequiredPermission() { return Jenkins.SYSTEM_READ; @@ -200,7 +201,7 @@ public class GlobalSecurityConfiguration extends ManagementLink implements Descr public Descriptor getDescriptor() { return Jenkins.get().getDescriptorOrDie(getClass()); } - + @Extension @Symbol("security") public static final class DescriptorImpl extends Descriptor { @Override diff --git a/core/src/main/java/hudson/security/GroupDetails.java b/core/src/main/java/hudson/security/GroupDetails.java index 543074ef0e3ad1d31f06e019aa640baed4299a79..ae94f20a03927af6c8332d7a8f302bcf3c4bbc51 100644 --- a/core/src/main/java/hudson/security/GroupDetails.java +++ b/core/src/main/java/hudson/security/GroupDetails.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.security; import java.util.Set; diff --git a/core/src/main/java/hudson/security/HttpSessionContextIntegrationFilter2.java b/core/src/main/java/hudson/security/HttpSessionContextIntegrationFilter2.java index 51e3a980a9d36d70ad82158978ac2c3af20db782..786df5d72879b40b5cf5ea7ea79f7a35ef134882 100644 --- a/core/src/main/java/hudson/security/HttpSessionContextIntegrationFilter2.java +++ b/core/src/main/java/hudson/security/HttpSessionContextIntegrationFilter2.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.security; import hudson.model.User; diff --git a/core/src/main/java/hudson/security/HudsonAuthenticationEntryPoint.java b/core/src/main/java/hudson/security/HudsonAuthenticationEntryPoint.java index bc9e9a01b70d69f9d010484263040f057375138a..da1a9bb26b14c6e8065c490b660f57d00176d4ff 100644 --- a/core/src/main/java/hudson/security/HudsonAuthenticationEntryPoint.java +++ b/core/src/main/java/hudson/security/HudsonAuthenticationEntryPoint.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.security; import static javax.servlet.http.HttpServletResponse.SC_FORBIDDEN; @@ -70,7 +71,7 @@ public class HudsonAuthenticationEntryPoint implements AuthenticationEntryPoint @Override public void commence(HttpServletRequest req, HttpServletResponse rsp, AuthenticationException reason) throws IOException, ServletException { String requestedWith = req.getHeader("X-Requested-With"); - if("XMLHttpRequest".equals(requestedWith)) { + if ("XMLHttpRequest".equals(requestedWith)) { // container authentication normally relies on session attribute to // remember where the user came from, so concurrent AJAX requests // often ends up sending users back to AJAX pages after successful login. @@ -80,9 +81,9 @@ public class HudsonAuthenticationEntryPoint implements AuthenticationEntryPoint } else { // give the opportunity to include the target URL String uriFrom = req.getRequestURI(); - if(!StringUtils.isEmpty(req.getQueryString())) uriFrom += "?" + req.getQueryString(); + if (!StringUtils.isEmpty(req.getQueryString())) uriFrom += "?" + req.getQueryString(); String loginForm = req.getContextPath() + loginFormUrl; - loginForm = MessageFormat.format(loginForm, URLEncoder.encode(uriFrom,"UTF-8")); + loginForm = MessageFormat.format(loginForm, URLEncoder.encode(uriFrom, "UTF-8")); req.setAttribute("loginForm", loginForm); rsp.setStatus(SC_FORBIDDEN); @@ -107,15 +108,15 @@ public class HudsonAuthenticationEntryPoint implements AuthenticationEntryPoint } printResponse(loginForm, out); - if (cause!=null) + if (cause != null) cause.report(out); out.printf( - "-->%n%n"+ + "-->%n%n" + ""); // Turn Off "Show Friendly HTTP Error Messages" Feature on the Server Side. // See http://support.microsoft.com/kb/294807 - for (int i=0; i < 10; i++) + for (int i = 0; i < 10; i++) out.print(" "); out.close(); } @@ -129,8 +130,8 @@ public class HudsonAuthenticationEntryPoint implements AuthenticationEntryPoint "" + "" + "%n" + - "%n%n"+ - "Authentication required%n"+ - " \\?\UNC\server\share - path = "\\\\?\\UNC\\" + canonicalPath.substring(2); - } else { - // prefix, canonical path should be normalized and absolute so this should work. - path = "\\\\?\\" + canonicalPath; - } - return Kernel32.INSTANCE.GetFileAttributesW(new WString(path)); + // allow lookup of paths longer than MAX_PATH + // http://msdn.microsoft.com/en-us/library/aa365247(v=VS.85).aspx + String canonicalPath = file.getCanonicalPath(); + String path; + if (canonicalPath.length() < 260) { + // path is short, use as-is + path = canonicalPath; + } else if (canonicalPath.startsWith("\\\\")) { + // network share + // \\server\share --> \\?\UNC\server\share + path = "\\\\?\\UNC\\" + canonicalPath.substring(2); + } else { + // prefix, canonical path should be normalized and absolute so this should work. + path = "\\\\?\\" + canonicalPath; + } + return Kernel32.INSTANCE.GetFileAttributesW(new WString(path)); } /** @@ -98,8 +99,8 @@ public class Kernel32Utils { public static void createSymbolicLink(File symlink, String target, boolean dirLink) throws IOException { if (!Kernel32.INSTANCE.CreateSymbolicLinkW( new WString(symlink.getPath()), new WString(target), - dirLink?Kernel32.SYMBOLIC_LINK_FLAG_DIRECTORY:0)) { - throw new WinIOException("Failed to create a symlink "+symlink+" to "+target); + dirLink ? Kernel32.SYMBOLIC_LINK_FLAG_DIRECTORY : 0)) { + throw new WinIOException("Failed to create a symlink " + symlink + " to " + target); } } @@ -113,7 +114,7 @@ public class Kernel32Utils { public static File getTempDir() { Memory buf = new Memory(1024); - if (Kernel32.INSTANCE.GetTempPathW(512,buf)!=0) {// the first arg is number of wchar + if (Kernel32.INSTANCE.GetTempPathW(512, buf) != 0) { // the first arg is number of wchar return new File(buf.getWideString(0)); } else { return null; @@ -125,7 +126,7 @@ public class Kernel32Utils { return (Kernel32) Native.load("kernel32", Kernel32.class); } catch (Throwable e) { LOGGER.log(Level.SEVERE, "Failed to load Kernel32", e); - return InitializationErrorInvocationHandler.create(Kernel32.class,e); + return InitializationErrorInvocationHandler.create(Kernel32.class, e); } } diff --git a/core/src/main/java/hudson/util/jna/Options.java b/core/src/main/java/hudson/util/jna/Options.java index 6c1a20d2a5bc8c4196e1c3b178afcb957afbb520..2b75aac9f872bce242056879fbf9f1884f9ed55f 100644 --- a/core/src/main/java/hudson/util/jna/Options.java +++ b/core/src/main/java/hudson/util/jna/Options.java @@ -13,6 +13,7 @@ but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ + package hudson.util.jna; import static com.sun.jna.Library.OPTION_FUNCTION_MAPPER; diff --git a/core/src/main/java/hudson/util/jna/RegistryKey.java b/core/src/main/java/hudson/util/jna/RegistryKey.java index cae66d6b1087048c2fa14054b0eaee4f4a449e25..cd9e9c0a07bca1cf59c443aadc6564f1dae9ac72 100644 --- a/core/src/main/java/hudson/util/jna/RegistryKey.java +++ b/core/src/main/java/hudson/util/jna/RegistryKey.java @@ -13,6 +13,7 @@ but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ + package hudson.util.jna; import com.sun.jna.ptr.IntByReference; @@ -44,16 +45,16 @@ public class RegistryKey implements AutoCloseable { path = ""; } - private RegistryKey(RegistryKey ancestor, String path,int handle) { + private RegistryKey(RegistryKey ancestor, String path, int handle) { this.handle = handle; this.root = ancestor.root; - this.path = combine(ancestor.path,path); + this.path = combine(ancestor.path, path); } private static String combine(String a, String b) { - if(a.length()==0) return b; - if(b.length()==0) return a; - return a+'\\'+b; + if (a.length() == 0) return b; + if (b.length() == 0) return a; + return a + '\\' + b; } /** @@ -96,7 +97,7 @@ public class RegistryKey implements AutoCloseable { lpcbData = new IntByReference(); OUTER: - while(true) { + while (true) { int r = Advapi32.INSTANCE.RegQueryValueEx(handle, valueName, null, pType, lpData, lpcbData); switch (r) { case WINERROR.ERROR_MORE_DATA: @@ -126,7 +127,7 @@ public class RegistryKey implements AutoCloseable { */ public void setValue(String name, String value) { byte[] bytes = value.getBytes(StandardCharsets.UTF_16LE); - int newLength = bytes.length+2; // for 0 padding + int newLength = bytes.length + 2; // for 0 padding byte[] with0 = new byte[newLength]; System.arraycopy(bytes, 0, with0, 0, newLength); check(Advapi32.INSTANCE.RegSetValueEx(handle, name, 0, WINNT.REG_SZ, with0, with0.length)); @@ -156,9 +157,9 @@ public class RegistryKey implements AutoCloseable { lpcbData = new IntByReference(); OUTER: - while(true) { + while (true) { int r = Advapi32.INSTANCE.RegQueryValueEx(handle, name, null, pType, lpData, lpcbData); - switch(r) { + switch (r) { case WINERROR.ERROR_MORE_DATA: lpData = new byte[lpcbData.getValue()]; continue OUTER; @@ -204,17 +205,17 @@ public class RegistryKey implements AutoCloseable { } public RegistryKey open(String subKeyName) { - return open(subKeyName,0xF003F/*KEY_ALL_ACCESS*/); + return open(subKeyName, 0xF003F/*KEY_ALL_ACCESS*/); } public RegistryKey openReadonly(String subKeyName) { - return open(subKeyName,0x20019/*KEY_READ*/); + return open(subKeyName, 0x20019/*KEY_READ*/); } public RegistryKey open(String subKeyName, int access) { IntByReference pHandle = new IntByReference(); check(Advapi32.INSTANCE.RegOpenKeyEx(handle, subKeyName, 0, access, pHandle)); - return new RegistryKey(this,subKeyName,pHandle.getValue()); + return new RegistryKey(this, subKeyName, pHandle.getValue()); } /** @@ -266,7 +267,7 @@ public class RegistryKey implements AutoCloseable { break; // not supported yet } break; - + default: check(result); } @@ -283,7 +284,7 @@ public class RegistryKey implements AutoCloseable { } public void dispose() { - if(handle!=0) + if (handle != 0) Advapi32.INSTANCE.RegCloseKey(handle); handle = 0; } diff --git a/core/src/main/java/hudson/util/jna/SHELLEXECUTEINFO.java b/core/src/main/java/hudson/util/jna/SHELLEXECUTEINFO.java index 61302f8e5ddba20acf099f8722c0c725c880b228..bca03457306df415c66627d14f9943f25810d0d4 100644 --- a/core/src/main/java/hudson/util/jna/SHELLEXECUTEINFO.java +++ b/core/src/main/java/hudson/util/jna/SHELLEXECUTEINFO.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.util.jna; import com.sun.jna.Pointer; @@ -57,7 +58,7 @@ typedef struct _SHELLEXECUTEINFO { * @author Kohsuke Kawaguchi * @see MSDN: SHELLEXECUTEINFO */ -@SuppressFBWarnings(value = {"UUF_UNUSED_PUBLIC_OR_PROTECTED_FIELD", "URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD"}, +@SuppressFBWarnings(value = {"UUF_UNUSED_PUBLIC_OR_PROTECTED_FIELD", "URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD"}, justification = "JNA Data Structure") public class SHELLEXECUTEINFO extends Structure { public int cbSize = size(); @@ -88,7 +89,7 @@ public class SHELLEXECUTEINFO extends Structure { "hProcess"); } - @SuppressFBWarnings(value = {"UUF_UNUSED_PUBLIC_OR_PROTECTED_FIELD", "URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD"}, + @SuppressFBWarnings(value = {"UUF_UNUSED_PUBLIC_OR_PROTECTED_FIELD", "URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD"}, justification = "JNA Data Structure") public static class DUMMYUNIONNAME_union extends Union { public Pointer hIcon; @@ -103,11 +104,11 @@ public class SHELLEXECUTEINFO extends Structure { } public static class ByReference extends DUMMYUNIONNAME_union implements Structure.ByReference { - + } public static class ByValue extends DUMMYUNIONNAME_union implements Structure.ByValue { - + } } } diff --git a/core/src/main/java/hudson/util/jna/Shell32.java b/core/src/main/java/hudson/util/jna/Shell32.java index 8165a4f099ee5a22d4287ae25585f8eed2ff571e..2007167befa79e87c562072f178125879af2f120 100644 --- a/core/src/main/java/hudson/util/jna/Shell32.java +++ b/core/src/main/java/hudson/util/jna/Shell32.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.util.jna; import com.sun.jna.Native; diff --git a/core/src/main/java/hudson/util/jna/WINBASE.java b/core/src/main/java/hudson/util/jna/WINBASE.java index 9aa47e7d079ed3b48b51341162dc38959b38ce89..695976d521c88b98dc3f7ff009708c45cb6da255 100644 --- a/core/src/main/java/hudson/util/jna/WINBASE.java +++ b/core/src/main/java/hudson/util/jna/WINBASE.java @@ -13,6 +13,7 @@ but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ + package hudson.util.jna; import com.sun.jna.Pointer; diff --git a/core/src/main/java/hudson/util/jna/WINERROR.java b/core/src/main/java/hudson/util/jna/WINERROR.java index 0f9f134f721ab88198cd8e76ff8f63f54377b71d..027fa144642c7f708cb0adb4a7d40bdcf00382af 100644 --- a/core/src/main/java/hudson/util/jna/WINERROR.java +++ b/core/src/main/java/hudson/util/jna/WINERROR.java @@ -13,6 +13,7 @@ but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ + package hudson.util.jna; /** diff --git a/core/src/main/java/hudson/util/jna/WINNT.java b/core/src/main/java/hudson/util/jna/WINNT.java index bcfd651676250fc085da90bb2d1409f009aaaa1f..6935041796ff7694f6c9d73cade443fdb063565f 100644 --- a/core/src/main/java/hudson/util/jna/WINNT.java +++ b/core/src/main/java/hudson/util/jna/WINNT.java @@ -13,6 +13,7 @@ but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ + package hudson.util.jna; /** diff --git a/core/src/main/java/hudson/util/jna/WinIOException.java b/core/src/main/java/hudson/util/jna/WinIOException.java index c3de2ebbfa4da1496cc6ac2608f36f57c487a5e9..a5a14712fc32b389329bbabf3b19485dfd1b2ffb 100644 --- a/core/src/main/java/hudson/util/jna/WinIOException.java +++ b/core/src/main/java/hudson/util/jna/WinIOException.java @@ -30,7 +30,7 @@ public class WinIOException extends IOException { @Override public String getMessage() { - return super.getMessage()+" error="+errorCode+":"+ Util.getWin32ErrorMessage(errorCode); + return super.getMessage() + " error=" + errorCode + ":" + Util.getWin32ErrorMessage(errorCode); } public int getErrorCode() { diff --git a/core/src/main/java/hudson/util/xstream/ImmutableListConverter.java b/core/src/main/java/hudson/util/xstream/ImmutableListConverter.java index 0cd1184825f8c1dbec19a4981189b4ba0231e5ec..196e2289d0ebd0e66e4ef0d336b49ddb1238ad71 100644 --- a/core/src/main/java/hudson/util/xstream/ImmutableListConverter.java +++ b/core/src/main/java/hudson/util/xstream/ImmutableListConverter.java @@ -22,6 +22,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.util.xstream; import com.google.common.collect.ImmutableList; @@ -48,12 +49,12 @@ public class ImmutableListConverter extends CollectionConverter { private final SerializableConverter sc; public ImmutableListConverter(XStream xs) { - this(xs.getMapper(),xs.getReflectionProvider()); + this(xs.getMapper(), xs.getReflectionProvider()); } public ImmutableListConverter(Mapper mapper, ReflectionProvider reflectionProvider) { super(mapper); - sc = new SerializableConverter(mapper,reflectionProvider); + sc = new SerializableConverter(mapper, reflectionProvider); } @Override @@ -69,26 +70,26 @@ public class ImmutableListConverter extends CollectionConverter { List items = new ArrayList(); if (reader.hasMoreChildren()) { reader.moveDown(); - // read the individual items from xml into a list - while (reader.hasMoreChildren()) { - reader.moveDown(); - try { - Object item = readItem(reader, context, items); - items.add(item); - } catch (CriticalXStreamException e) { - throw e; - } catch (XStreamException | LinkageError e) { - RobustReflectionConverter.addErrorInContext(context, e); - } + // read the individual items from xml into a list + while (reader.hasMoreChildren()) { + reader.moveDown(); + try { + Object item = readItem(reader, context, items); + items.add(item); + } catch (CriticalXStreamException e) { + throw e; + } catch (XStreamException | LinkageError e) { + RobustReflectionConverter.addErrorInContext(context, e); + } reader.moveUp(); - } + } // move back up past the elements element. reader.moveUp(); } return ImmutableList.copyOf(items); } else { - return ImmutableList.copyOf((List)super.unmarshal(reader, context)); + return ImmutableList.copyOf((List) super.unmarshal(reader, context)); } } diff --git a/core/src/main/java/hudson/util/xstream/ImmutableMapConverter.java b/core/src/main/java/hudson/util/xstream/ImmutableMapConverter.java index c353cf672c51d40be663c0e4df8af6db8bdab32f..d5821a5c0c952d7800542f4521a96a7b9cea9691 100644 --- a/core/src/main/java/hudson/util/xstream/ImmutableMapConverter.java +++ b/core/src/main/java/hudson/util/xstream/ImmutableMapConverter.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.util.xstream; import com.google.common.collect.ImmutableMap; @@ -44,12 +45,12 @@ public class ImmutableMapConverter extends MapConverter { private final SerializableConverter sc; public ImmutableMapConverter(XStream xs) { - this(xs.getMapper(),xs.getReflectionProvider()); + this(xs.getMapper(), xs.getReflectionProvider()); } public ImmutableMapConverter(Mapper mapper, ReflectionProvider reflectionProvider) { super(mapper); - sc = new SerializableConverter(mapper,reflectionProvider); + sc = new SerializableConverter(mapper, reflectionProvider); } @Override @@ -59,7 +60,7 @@ public class ImmutableMapConverter extends MapConverter { @Override public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { - return ImmutableMap.copyOf((Map)super.unmarshal(reader, context)); + return ImmutableMap.copyOf((Map) super.unmarshal(reader, context)); } @Override diff --git a/core/src/main/java/hudson/util/xstream/ImmutableSetConverter.java b/core/src/main/java/hudson/util/xstream/ImmutableSetConverter.java index 08184ff50449015e523bba3a5983d5266aca8487..b8c3c183984efcb35b556213bbc4870cda6266ba 100644 --- a/core/src/main/java/hudson/util/xstream/ImmutableSetConverter.java +++ b/core/src/main/java/hudson/util/xstream/ImmutableSetConverter.java @@ -18,12 +18,12 @@ public class ImmutableSetConverter extends CollectionConverter { private final SerializableConverter sc; public ImmutableSetConverter(XStream xs) { - this(xs.getMapper(),xs.getReflectionProvider()); + this(xs.getMapper(), xs.getReflectionProvider()); } public ImmutableSetConverter(Mapper mapper, ReflectionProvider reflectionProvider) { super(mapper); - sc = new SerializableConverter(mapper,reflectionProvider); + sc = new SerializableConverter(mapper, reflectionProvider); } @Override diff --git a/core/src/main/java/hudson/util/xstream/ImmutableSortedSetConverter.java b/core/src/main/java/hudson/util/xstream/ImmutableSortedSetConverter.java index 09d55c489b7bd831a5e70745bf5793e8849e392b..6a1481f9e85afebd1399cddc892f2f83b8e457f6 100644 --- a/core/src/main/java/hudson/util/xstream/ImmutableSortedSetConverter.java +++ b/core/src/main/java/hudson/util/xstream/ImmutableSortedSetConverter.java @@ -18,12 +18,12 @@ public class ImmutableSortedSetConverter extends CollectionConverter { private final SerializableConverter sc; public ImmutableSortedSetConverter(XStream xs) { - this(xs.getMapper(),xs.getReflectionProvider()); + this(xs.getMapper(), xs.getReflectionProvider()); } public ImmutableSortedSetConverter(Mapper mapper, ReflectionProvider reflectionProvider) { super(mapper); - sc = new SerializableConverter(mapper,reflectionProvider); + sc = new SerializableConverter(mapper, reflectionProvider); } @Override diff --git a/core/src/main/java/hudson/util/xstream/MapperDelegate.java b/core/src/main/java/hudson/util/xstream/MapperDelegate.java index deea611a748b5443d879b9dcb3bac1210bad9657..78d045ca123ca3d065bdf199db65c74c8cfab7e5 100644 --- a/core/src/main/java/hudson/util/xstream/MapperDelegate.java +++ b/core/src/main/java/hudson/util/xstream/MapperDelegate.java @@ -9,6 +9,7 @@ * * Created on 22. January 2005 by Joe Walnes */ + package hudson.util.xstream; import com.thoughtworks.xstream.XStream; @@ -139,7 +140,7 @@ public class MapperDelegate extends MapperWrapper { @Override public SingleValueConverter getConverterFromItemType(String fieldName, Class type, Class definedIn) { - return delegate.getConverterFromItemType(fieldName, type, definedIn); + return delegate.getConverterFromItemType(fieldName, type, definedIn); } /** @@ -148,7 +149,7 @@ public class MapperDelegate extends MapperWrapper { @Deprecated @Override public String aliasForAttribute(Class definedIn, String fieldName) { - return delegate.aliasForAttribute(definedIn, fieldName); + return delegate.aliasForAttribute(definedIn, fieldName); } /** @@ -157,7 +158,7 @@ public class MapperDelegate extends MapperWrapper { @Deprecated @Override public String attributeForAlias(Class definedIn, String alias) { - return delegate.attributeForAlias(definedIn, alias); + return delegate.attributeForAlias(definedIn, alias); } /** @@ -166,7 +167,7 @@ public class MapperDelegate extends MapperWrapper { @Deprecated @Override public SingleValueConverter getConverterFromAttribute(Class type, String attribute) { - return delegate.getConverterFromAttribute(type, attribute); + return delegate.getConverterFromAttribute(type, attribute); } @Override diff --git a/core/src/main/java/hudson/views/BuildButtonColumn.java b/core/src/main/java/hudson/views/BuildButtonColumn.java index f0aa4436cfc6265cca83644f45b25b4420f5d1e3..5a48f0da6de81ab6dac12a55b91710bb6b811b92 100644 --- a/core/src/main/java/hudson/views/BuildButtonColumn.java +++ b/core/src/main/java/hudson/views/BuildButtonColumn.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Martin Eigenbrodt - * + * * 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 @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.views; import hudson.Extension; @@ -40,7 +41,7 @@ public class BuildButtonColumn extends ListViewColumn { return hudson.model.Messages.AbstractItem_TaskNoun(); } - @Extension(ordinal=DEFAULT_COLUMNS_ORDINAL_ACTIONS_START-1) @Symbol("buildButton") + @Extension(ordinal = DEFAULT_COLUMNS_ORDINAL_ACTIONS_START - 1) @Symbol("buildButton") public static class DescriptorImpl extends ListViewColumnDescriptor { @Override public String getDisplayName() { diff --git a/core/src/main/java/hudson/views/DefaultMyViewsTabBar.java b/core/src/main/java/hudson/views/DefaultMyViewsTabBar.java index 9ebc1e63599cfc4177efac47476fc78827f71d14..d697552a68570459d0475270fc37ae6b4d832a9c 100644 --- a/core/src/main/java/hudson/views/DefaultMyViewsTabBar.java +++ b/core/src/main/java/hudson/views/DefaultMyViewsTabBar.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2010, Winston.Prakash@Oracle.com - * + * * 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 @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.views; import hudson.Extension; diff --git a/core/src/main/java/hudson/views/DefaultViewsTabBar.java b/core/src/main/java/hudson/views/DefaultViewsTabBar.java index e9e9f56dbe1148c82d0218294ae291b1bbbd54dc..6f697f96a86e9b394654f6abd471251b083c53c9 100644 --- a/core/src/main/java/hudson/views/DefaultViewsTabBar.java +++ b/core/src/main/java/hudson/views/DefaultViewsTabBar.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2010, Winston.Prakash@Oracle.com - * + * * 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 @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.views; import hudson.Extension; diff --git a/core/src/main/java/hudson/views/GlobalDefaultViewConfiguration.java b/core/src/main/java/hudson/views/GlobalDefaultViewConfiguration.java index 89fe448d0e80e4ceadb806a44158c694f42ccad7..b60939aae5eec57057ab35ca465647df4ded6be8 100644 --- a/core/src/main/java/hudson/views/GlobalDefaultViewConfiguration.java +++ b/core/src/main/java/hudson/views/GlobalDefaultViewConfiguration.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.views; import hudson.Extension; @@ -36,7 +37,7 @@ import org.kohsuke.stapler.StaplerRequest; * * @author Kohsuke Kawaguchi */ -@Extension(ordinal=300) @Symbol("defaultView") +@Extension(ordinal = 300) @Symbol("defaultView") public class GlobalDefaultViewConfiguration extends GlobalConfiguration { @Override public boolean configure(StaplerRequest req, JSONObject json) throws FormException { @@ -53,7 +54,7 @@ public class GlobalDefaultViewConfiguration extends GlobalConfiguration { // Fallback if the view is not specified j.setPrimaryView(j.getViews().iterator().next()); } - + return true; } } diff --git a/core/src/main/java/hudson/views/JobColumn.java b/core/src/main/java/hudson/views/JobColumn.java index b6f581c154c2342d7214e43a674280a2cc512ce8..b2ec060f09c3bd3260306cb6a46596856d49544f 100644 --- a/core/src/main/java/hudson/views/JobColumn.java +++ b/core/src/main/java/hudson/views/JobColumn.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Martin Eigenbrodt - * + * * 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 @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.views; import hudson.Extension; @@ -37,7 +38,7 @@ public class JobColumn extends ListViewColumn { } // put this in the middle of icons and properties - @Extension(ordinal=DEFAULT_COLUMNS_ORDINAL_ICON_END+1) @Symbol("jobName") + @Extension(ordinal = DEFAULT_COLUMNS_ORDINAL_ICON_END + 1) @Symbol("jobName") public static class DescriptorImpl extends ListViewColumnDescriptor { @Override public String getDisplayName() { diff --git a/core/src/main/java/hudson/views/LastDurationColumn.java b/core/src/main/java/hudson/views/LastDurationColumn.java index 04696704a65ddde11fcc2ada920e8a15b3a15c52..f1d7258e5b956c74bbbd322bdce4e555ce94fb37 100644 --- a/core/src/main/java/hudson/views/LastDurationColumn.java +++ b/core/src/main/java/hudson/views/LastDurationColumn.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Martin Eigenbrodt - * + * * 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 @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.views; import hudson.Extension; @@ -32,7 +33,7 @@ public class LastDurationColumn extends ListViewColumn { public LastDurationColumn() { } - @Extension(ordinal=DEFAULT_COLUMNS_ORDINAL_PROPERTIES_START-4) @Symbol("lastDuration") + @Extension(ordinal = DEFAULT_COLUMNS_ORDINAL_PROPERTIES_START - 4) @Symbol("lastDuration") public static class DescriptorImpl extends ListViewColumnDescriptor { @Override public String getDisplayName() { diff --git a/core/src/main/java/hudson/views/LastFailureColumn.java b/core/src/main/java/hudson/views/LastFailureColumn.java index 1c272b855f8bb68dde9ba6d2879f0a8cfde9983c..c31f3f9590a037c2a1f332646d5157a666e31cc5 100644 --- a/core/src/main/java/hudson/views/LastFailureColumn.java +++ b/core/src/main/java/hudson/views/LastFailureColumn.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Martin Eigenbrodt - * + * * 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 @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.views; import hudson.Extension; @@ -32,7 +33,7 @@ public class LastFailureColumn extends ListViewColumn { public LastFailureColumn() { } - @Extension(ordinal=DEFAULT_COLUMNS_ORDINAL_PROPERTIES_START-2) @Symbol("lastFailure") + @Extension(ordinal = DEFAULT_COLUMNS_ORDINAL_PROPERTIES_START - 2) @Symbol("lastFailure") public static class DescriptorImpl extends ListViewColumnDescriptor { @Override public String getDisplayName() { diff --git a/core/src/main/java/hudson/views/LastStableColumn.java b/core/src/main/java/hudson/views/LastStableColumn.java index 0844121e5dcb4ea79d5d37555f5583d58f0d1cbc..7dfd482eaab31f1f77242f62ea2eed9bcdeab6bc 100644 --- a/core/src/main/java/hudson/views/LastStableColumn.java +++ b/core/src/main/java/hudson/views/LastStableColumn.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2009, Sun Microsystems, Inc., Jesse Glick - * + * * 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 @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.views; import hudson.Extension; @@ -32,7 +33,7 @@ public class LastStableColumn extends ListViewColumn { public LastStableColumn() { } - @Extension(ordinal=DEFAULT_COLUMNS_ORDINAL_PROPERTIES_START-3) @Symbol("lastStable") + @Extension(ordinal = DEFAULT_COLUMNS_ORDINAL_PROPERTIES_START - 3) @Symbol("lastStable") public static class DescriptorImpl extends ListViewColumnDescriptor { @Override public String getDisplayName() { diff --git a/core/src/main/java/hudson/views/LastSuccessColumn.java b/core/src/main/java/hudson/views/LastSuccessColumn.java index ebb5bc1bc94462c8a03ab2682bc35473c4769b91..98571e8e9bf37ccdc92de7f77072ae9f057f3218 100644 --- a/core/src/main/java/hudson/views/LastSuccessColumn.java +++ b/core/src/main/java/hudson/views/LastSuccessColumn.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Martin Eigenbrodt - * + * * 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 @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.views; import hudson.Extension; @@ -32,7 +33,7 @@ public class LastSuccessColumn extends ListViewColumn { public LastSuccessColumn() { } - @Extension(ordinal=DEFAULT_COLUMNS_ORDINAL_PROPERTIES_START-1) @Symbol("lastSuccess") + @Extension(ordinal = DEFAULT_COLUMNS_ORDINAL_PROPERTIES_START - 1) @Symbol("lastSuccess") public static class DescriptorImpl extends ListViewColumnDescriptor { @Override public String getDisplayName() { diff --git a/core/src/main/java/hudson/views/ListViewColumn.java b/core/src/main/java/hudson/views/ListViewColumn.java index dcf2dd9b0d36473bdb4a06c3997cc1f00f8cb33a..1796f4cc495c4ff3ad3572968d07e09f6a75fee3 100644 --- a/core/src/main/java/hudson/views/ListViewColumn.java +++ b/core/src/main/java/hudson/views/ListViewColumn.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Martin Eigenbrodt - * + * * 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 @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.views; import hudson.DescriptorExtensionList; @@ -169,7 +170,7 @@ public abstract class ListViewColumn implements ExtensionPoint, Describable filtered = new ArrayList<>(); for (TopLevelItem item : added) { if (!(item instanceof ParameterizedJobMixIn.ParameterizedJob) // TODO or better to call the more generic Job.isBuildable? - || ((ParameterizedJobMixIn.ParameterizedJob) item).isDisabled() ^ statusFilter) + || ((ParameterizedJobMixIn.ParameterizedJob) item).isDisabled() ^ statusFilter) filtered.add(item); } return filtered; diff --git a/core/src/main/java/hudson/views/ViewJobFilter.java b/core/src/main/java/hudson/views/ViewJobFilter.java index c00541c215ae6b3582cb63bcff4dc8bec258ed8a..576ec824d0c85a75988246613d0a5008c1a3e2c5 100644 --- a/core/src/main/java/hudson/views/ViewJobFilter.java +++ b/core/src/main/java/hudson/views/ViewJobFilter.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi, Martin Eigenbrodt - * + * * 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 @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.views; import hudson.DescriptorExtensionList; @@ -48,10 +49,10 @@ public abstract class ViewJobFilter implements ExtensionPoint, Describable getDescriptor() { + public Descriptor getDescriptor() { return Jenkins.get().getDescriptorOrDie(getClass()); } - + /** * Choose which jobs to show for a view. * @param added which jobs have been added so far. This JobFilter can remove or add to this list. diff --git a/core/src/main/java/hudson/views/ViewsTabBar.java b/core/src/main/java/hudson/views/ViewsTabBar.java index b8af8de198ae8590cb9ac1c0cbcaabf45c53c5ff..195f72104abaf71b61aa52f1d1ba977151e5a5de 100644 --- a/core/src/main/java/hudson/views/ViewsTabBar.java +++ b/core/src/main/java/hudson/views/ViewsTabBar.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2010, Winston.Prakash@oracle.com, CloudBees, 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 @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.views; import edu.umd.cs.findbugs.annotations.NonNull; @@ -68,7 +69,7 @@ public abstract class ViewsTabBar extends AbstractDescribableImpl i @Override public ViewsTabBarDescriptor getDescriptor() { - return (ViewsTabBarDescriptor)super.getDescriptor(); + return (ViewsTabBarDescriptor) super.getDescriptor(); } /** @@ -92,7 +93,7 @@ public abstract class ViewsTabBar extends AbstractDescribableImpl i * * @author Kohsuke Kawaguchi */ - @Extension(ordinal=310) @Symbol("viewsTabBar") + @Extension(ordinal = 310) @Symbol("viewsTabBar") public static class GlobalConfigurationImpl extends GlobalConfiguration { public ViewsTabBar getViewsTabBar() { return Jenkins.get().getViewsTabBar(); @@ -104,7 +105,7 @@ public abstract class ViewsTabBar extends AbstractDescribableImpl i Jenkins j = Jenkins.get(); if (json.has("viewsTabBar")) { - j.setViewsTabBar(req.bindJSON(ViewsTabBar.class,json.getJSONObject("viewsTabBar"))); + j.setViewsTabBar(req.bindJSON(ViewsTabBar.class, json.getJSONObject("viewsTabBar"))); } else { j.setViewsTabBar(new DefaultViewsTabBar()); } diff --git a/core/src/main/java/hudson/views/ViewsTabBarDescriptor.java b/core/src/main/java/hudson/views/ViewsTabBarDescriptor.java index 73f0c85b825ada84f10342a61963353612089774..012a43ed9dd81314d0b1a0d98eb326c10a089cd2 100644 --- a/core/src/main/java/hudson/views/ViewsTabBarDescriptor.java +++ b/core/src/main/java/hudson/views/ViewsTabBarDescriptor.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.views; import hudson.model.Descriptor; diff --git a/core/src/main/java/hudson/views/WeatherColumn.java b/core/src/main/java/hudson/views/WeatherColumn.java index d14e9ca5582bf678951f3966d13bd81a80fb3534..ee04f7c0f08b94a0987cb4238dc5d67985787a40 100644 --- a/core/src/main/java/hudson/views/WeatherColumn.java +++ b/core/src/main/java/hudson/views/WeatherColumn.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Martin Eigenbrodt - * + * * 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 @@ -33,7 +33,7 @@ public class WeatherColumn extends ListViewColumn { public WeatherColumn() { } - @Extension(ordinal=DEFAULT_COLUMNS_ORDINAL_ICON_START-2) @Symbol("weather") + @Extension(ordinal = DEFAULT_COLUMNS_ORDINAL_ICON_START - 2) @Symbol("weather") public static class DescriptorImpl extends ListViewColumnDescriptor { @Override public String getDisplayName() { diff --git a/core/src/main/java/hudson/widgets/BuildHistoryWidget.java b/core/src/main/java/hudson/widgets/BuildHistoryWidget.java index aa44599fbbcd402b69c1f29f3f485decb693cf5f..da3576771416fa4beaf1475f0909675d83ead0c5 100644 --- a/core/src/main/java/hudson/widgets/BuildHistoryWidget.java +++ b/core/src/main/java/hudson/widgets/BuildHistoryWidget.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.widgets; import hudson.model.Queue.Item; @@ -39,13 +40,13 @@ import jenkins.widgets.HistoryPageFilter; * * @author Kohsuke Kawaguchi */ -public class BuildHistoryWidget extends HistoryWidget { +public class BuildHistoryWidget extends HistoryWidget { /** * @param owner * The parent model object that owns this widget. */ - public BuildHistoryWidget(Task owner, Iterable baseList,Adapter adapter) { - super(owner,baseList, adapter); + public BuildHistoryWidget(Task owner, Iterable baseList, Adapter adapter) { + super(owner, baseList, adapter); } /** @@ -65,7 +66,7 @@ public class BuildHistoryWidget extends HistoryWidget { list.addFirst(item); } } - return list; + return list; } @Override diff --git a/core/src/main/java/hudson/widgets/HistoryWidget.java b/core/src/main/java/hudson/widgets/HistoryWidget.java index 4cae7eccfb392033fdf05b19a024a2ebcf10e59c..aba195ab7c7445a3b38cf3591a6a23e5d4ad1723 100644 --- a/core/src/main/java/hudson/widgets/HistoryWidget.java +++ b/core/src/main/java/hudson/widgets/HistoryWidget.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.widgets; import edu.umd.cs.findbugs.annotations.CheckForNull; @@ -50,7 +51,7 @@ import org.kohsuke.stapler.StaplerResponse; * Type individual record. * @author Kohsuke Kawaguchi */ -public class HistoryWidget extends Widget { +public class HistoryWidget extends Widget { /** * The given data model of records. Newer ones first. */ @@ -89,7 +90,7 @@ public class HistoryWidget extends Widget { StaplerRequest currentRequest = Stapler.getCurrentRequest(); this.adapter = adapter; this.baseList = baseList; - this.baseUrl = Functions.getNearestAncestorUrl(currentRequest,owner); + this.baseUrl = Functions.getNearestAncestorUrl(currentRequest, owner); this.owner = owner; this.newerThan = getPagingParam(currentRequest, "newer-than"); this.olderThan = getPagingParam(currentRequest, "older-than"); @@ -127,9 +128,9 @@ public class HistoryWidget extends Widget { } private Iterable> updateFirstTransientBuildKey(Iterable> source) { - String key=null; + String key = null; for (HistoryPageEntry t : source) { - if(adapter.isBuilding(t.getEntry())) { + if (adapter.isBuilding(t.getEntry())) { key = adapter.getKey(t.getEntry()); } } @@ -141,12 +142,12 @@ public class HistoryWidget extends Widget { * The records to be rendered this time. */ public Iterable> getRenderList() { - if(trimmed) { + if (trimmed) { List> pageEntries = toPageEntries(baseList); - if(pageEntries.size() > THRESHOLD) { - return updateFirstTransientBuildKey(pageEntries.subList(0,THRESHOLD)); + if (pageEntries.size() > THRESHOLD) { + return updateFirstTransientBuildKey(pageEntries.subList(0, THRESHOLD)); } else { - trimmed=false; + trimmed = false; return updateFirstTransientBuildKey(pageEntries); } } else { @@ -212,8 +213,8 @@ public class HistoryWidget extends Widget { * The build 'number' to fetch. This is string because various variants * uses non-numbers as the build key. */ - public void doAjax( StaplerRequest req, StaplerResponse rsp, - @Header("n") String n ) throws IOException, ServletException { + public void doAjax(StaplerRequest req, StaplerResponse rsp, + @Header("n") String n) throws IOException, ServletException { rsp.setContentType("text/html;charset=UTF-8"); @@ -221,39 +222,39 @@ public class HistoryWidget extends Widget { List items = new ArrayList<>(); if (n != null) { - String nn=null; // we'll compute next n here + String nn = null; // we'll compute next n here // list up all builds >=n. for (T t : baseList) { - if(adapter.compare(t,n)>=0) { + if (adapter.compare(t, n) >= 0) { items.add(t); - if(adapter.isBuilding(t)) + if (adapter.isBuilding(t)) nn = adapter.getKey(t); // the next fetch should start from youngest build in progress } else break; } - if (nn==null) { + if (nn == null) { if (items.isEmpty()) { // nothing to report back. next fetch should retry the same 'n' - nn=n; + nn = n; } else { // every record fetched this time is frozen. next fetch should start from the next build - nn=adapter.getNextKey(adapter.getKey(items.get(0))); + nn = adapter.getNextKey(adapter.getKey(items.get(0))); } } baseList = items; - rsp.setHeader("n",nn); + rsp.setHeader("n", nn); firstTransientBuildKey = nn; // all builds >= nn should be marked transient } HistoryPageFilter page = getHistoryPageFilter(); - req.getView(page,"ajaxBuildHistory.jelly").forward(req,rsp); + req.getView(page, "ajaxBuildHistory.jelly").forward(req, rsp); } - static final int THRESHOLD = SystemProperties.getInteger(HistoryWidget.class.getName()+".threshold",30); + static final int THRESHOLD = SystemProperties.getInteger(HistoryWidget.class.getName() + ".threshold", 30); public String getNextBuildNumberToFetch() { return nextBuildNumberToFetch; @@ -268,8 +269,11 @@ public class HistoryWidget extends Widget { * If record is newer than the key, return a positive number. */ int compare(T record, String key); + String getKey(T record); + boolean isBuilding(T record); + String getNextKey(String key); } diff --git a/core/src/main/java/hudson/widgets/RenderOnDemandClosure.java b/core/src/main/java/hudson/widgets/RenderOnDemandClosure.java index 6e9687793f94a0e8224087af7b439683f913eddc..9092526f109b1ff011023e4bcc2be253058b1825 100644 --- a/core/src/main/java/hudson/widgets/RenderOnDemandClosure.java +++ b/core/src/main/java/hudson/widgets/RenderOnDemandClosure.java @@ -21,6 +21,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.widgets; import hudson.Util; @@ -56,23 +57,23 @@ public class RenderOnDemandClosure { * Captures the recursive taglib call stack. */ private final Script[] bodyStack; - private final Map variables; + private final Map variables; private final String currentDescriptorByNameUrl; private final String[] adjuncts; public RenderOnDemandClosure(JellyContext context, String attributesToCapture) { List