diff --git a/bom/pom.xml b/bom/pom.xml index 2fe8f8bfd9b3a..44220df8b8afa 100644 --- a/bom/pom.xml +++ b/bom/pom.xml @@ -40,7 +40,7 @@ THE SOFTWARE. 9.2 1.7.32 - 1627.v5c244c19f85f + 1638.v229a_24fa_b_17c 2.4.21 @@ -221,7 +221,7 @@ THE SOFTWARE. com.github.jnr jnr-posix - 3.1.14 + 3.1.15 org.kohsuke diff --git a/cli/pom.xml b/cli/pom.xml index 34a47850a8b22..8772f2658fc25 100644 --- a/cli/pom.xml +++ b/cli/pom.xml @@ -149,6 +149,14 @@ net io.jenkins.cli.shaded.net + + com + io.jenkins.cli.shaded.com + + + jakarta + io.jenkins.cli.shaded.jakarta + diff --git a/cli/src/main/java/hudson/cli/CLI.java b/cli/src/main/java/hudson/cli/CLI.java index 862847df96731..a6a33c6f800e9 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 @@ private 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 static void main(final String[] _args) throws Exception { } } - 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 static int _main(String[] _args) throws Exception { 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 static int _main(String[] _args) throws Exception { 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 boolean verify(String s, SSLSession sslSession) { 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 boolean verify(String s, SSLSession sslSession) { 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 boolean verify(String s, SSLSession sslSession) { break; } - if(url==null) { + if (url == null) { printUsage(Messages.CLI_NoURL()); return -1; } @@ -263,7 +266,7 @@ public boolean verify(String s, SSLSession sslSession) { url += '/'; } - if(args.isEmpty()) + if (args.isEmpty()) args = Collections.singletonList("help"); // default to help if (mode == null) { @@ -338,6 +341,7 @@ class CLIEndpoint extends Endpoint { @Override public void onOpen(Session session, EndpointConfig config) {} } + class Authenticator extends ClientEndpointConfig.Configurator { @Override public void beforeRequest(Map> headers) { @@ -346,6 +350,7 @@ public void beforeRequest(Map> headers) { } } } + 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 void beforeRequest(Map> headers) { 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 @@ private static String computeVersion() { 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 @@ private static String computeVersion() { } 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 @@ static String usage() { } 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 0553dd215de57..9b4295b07cb34 100644 --- a/cli/src/main/java/hudson/cli/CLIConnectionFactory.java +++ b/cli/src/main/java/hudson/cli/CLIConnectionFactory.java @@ -5,7 +5,7 @@ /** * Fluent-API to instantiate {@link CLI}. - * + * * @author Kohsuke Kawaguchi */ public class CLIConnectionFactory { @@ -26,7 +26,7 @@ public CLIConnectionFactory authorization(String value) { * 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 4708b425dbb77..a701cb3033474 100644 --- a/cli/src/main/java/hudson/cli/DiagnosedStreamCorruptionException.java +++ b/cli/src/main/java/hudson/cli/DiagnosedStreamCorruptionException.java @@ -41,14 +41,14 @@ public String toString() { 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 4dc9700e9371e..5a1167c4fdc5d 100644 --- a/cli/src/main/java/hudson/cli/FlightRecorderInputStream.java +++ b/cli/src/main/java/hudson/cli/FlightRecorderInputStream.java @@ -52,13 +52,13 @@ public DiagnosedStreamCorruptionException analyzeCrash(Exception problem, String 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 @@ public void run() { 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 @@ public int read() throws IOException { @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 @@ public int read(@NonNull byte[] b, int off, int len) throws IOException { */ @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 @@ public synchronized byte[] toByteArray() { 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 fec9d7d3b9d3c..ae8917ab3aa6d 100644 --- a/cli/src/main/java/hudson/cli/FullDuplexHttpStream.java +++ b/cli/src/main/java/hudson/cli/FullDuplexHttpStream.java @@ -18,7 +18,7 @@ */ public class FullDuplexHttpStream { private final URL base; - + private final OutputStream output; private final InputStream input; @@ -65,7 +65,7 @@ public FullDuplexHttpStream(URL base, String relativeTarget, String authorizatio 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 FullDuplexHttpStream(URL base, String relativeTarget, String authorizatio 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 @@ private URL tryToResolveRedirects(URL base, String authorization) { 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 ad37158bc16d0..0132f47f130da 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 @@ public static String toHex(byte[] buf, int start, int len) { 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 0c14433d10196..ac1f9dbfe10bb 100644 --- a/cli/src/main/java/hudson/cli/PlainCLIProtocol.java +++ b/cli/src/main/java/hudson/cli/PlainCLIProtocol.java @@ -233,10 +233,12 @@ protected final OutputStream stream(final Op op) { 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 f283053f9cb59..64c84fc2074de 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 void readFrom(File keyFile) throws IOException, GeneralSecurityException 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 static KeyPair loadKey(File f, String passwd) throws IOException, General 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 d9fa4911df84c..5badd296fbf0e 100644 --- a/cli/src/main/java/hudson/cli/SSHCLI.java +++ b/cli/src/main/java/hudson/cli/SSHCLI.java @@ -85,7 +85,7 @@ static int sshConnection(String jenkinsUrl, String user, List args, Priv command.append(' '); } - try(SshClient client = SshClient.setUpDefaultClient()) { + try (SshClient client = SshClient.setUpDefaultClient()) { KnownHostsServerKeyVerifier verifier = new DefaultKnownHostsServerKeyVerifier(new ServerKeyVerifier() { @Override @@ -116,7 +116,7 @@ public boolean verifyServerKey(ClientSession clientSession, SocketAddress remote 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 6b8a6f43f7811..6f77b758bc1f3 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 @@ 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 QuotedStringTokenizer(String str, 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 QuotedStringTokenizer(String str, 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 boolean hasMoreTokens() 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 @@ else if (c=='\\') 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 @@ else if (c=='\\') 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 @@ else if (c=='\\') 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 String nextToken() 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 int countTokens() */ 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 static String quote(String s, String delim) */ 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 static String quote(String s) */ 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 static byte convertHexDigit( byte b ) * * 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 52b6c2e631f41..9e15de1453cbc 100644 --- a/cli/src/test/java/hudson/cli/HexDumpTest.java +++ b/cli/src/test/java/hudson/cli/HexDumpTest.java @@ -24,9 +24,9 @@ public void testToHex1(String expected, byte[] buf) { 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 void testToHex2(String expected, byte[] buf, int start, int len) { 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 3eb29728fd71b..98a4fefd8001f 100644 --- a/cli/src/test/java/hudson/cli/PlainCLIProtocolTest.java +++ b/cli/src/test/java/hudson/cli/PlainCLIProtocolTest.java @@ -31,6 +31,7 @@ import java.io.IOException; import java.io.PipedInputStream; import java.io.PipedOutputStream; +import java.nio.charset.Charset; import org.junit.jupiter.api.Test; public class PlainCLIProtocolTest { @@ -42,27 +43,34 @@ public void ignoreUnknownOperations() throws Exception { 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()); + streamStdin().write("hello".getBytes(Charset.defaultCharset())); } + void newop() throws IOException { DataOutputStream dos = new DataOutputStream(upload); dos.writeInt(0); @@ -70,26 +78,33 @@ void newop() throws IOException { 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 +116,18 @@ protected void onStdin(byte[] chunk) throws IOException { */ stdin.write(chunk); } + @Override protected void onEndStdin() throws IOException {} + @Override protected void handleClose() {} + void send() throws IOException { - streamStdout().write("goodbye".getBytes()); + streamStdout().write("goodbye".getBytes(Charset.defaultCharset())); sendExit(2); } + void newop() throws IOException { DataOutputStream dos = new DataOutputStream(download); dos.writeInt(0); @@ -116,6 +135,7 @@ void newop() throws IOException { dos.flush(); } } + Client client = new Client(); Server server = new Server(); new PlainCLIProtocol.FramedReader(client, new PipedInputStream(download)).start(); @@ -137,9 +157,9 @@ void newop() throws IOException { while (server.stdin.size() == 0) { Thread.sleep(100); } - assertEquals("hello", server.stdin.toString()); + assertEquals("hello", server.stdin.toString(Charset.defaultCharset().name())); assertEquals("command", server.arg); - assertEquals("goodbye", client.stdout.toString()); + assertEquals("goodbye", client.stdout.toString(Charset.defaultCharset().name())); assertEquals(2, client.code); } diff --git a/cli/src/test/java/hudson/util/QuotedStringTokenizerTest.java b/cli/src/test/java/hudson/util/QuotedStringTokenizerTest.java index 9af792ca7b2fb..e5c546d11c3ee 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 void test5() { @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 b68276e8eec12..d3d58122c87ee 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 04847d28853e0..56f463da1db1e 100644 --- a/core/src/main/java/hudson/AboutJenkins.java +++ b/core/src/main/java/hudson/AboutJenkins.java @@ -11,7 +11,7 @@ /** * 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 59e65e9bcba02..b13eeaad3edd0 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 final int length() { * 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 void addHyperlink( int startPos, int endPos, String url ) { * * @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 MarkupText.SubText findToken(Pattern pattern) { String text = getText(); Matcher m = pattern.matcher(text); - if(m.find()) + if (m.find()) return createSubText(m); return null; @@ -142,17 +143,17 @@ public List findTokens(Pattern pattern) { 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 optionalDepende String pluginName = atts.getValue("Short-Name"); String jenkinsVersion = atts.getValue("Jenkins-Version"); - if (jenkinsVersion==null) + if (jenkinsVersion == null) jenkinsVersion = atts.getValue("Hudson-Version"); for (Dependency d : DetachedPluginsUtil.getImpliedDependencies(pluginName, jenkinsVersion)) { @@ -278,7 +279,7 @@ public static List getImpliedDependencies(String plugi @Deprecated protected ClassLoader createClassLoader(List paths, ClassLoader parent) throws IOException { - return createClassLoader( paths, parent, null ); + return createClassLoader(paths, parent, null); } /** @@ -322,7 +323,7 @@ protected ClassLoader createClassLoader(List paths, ClassLoader parent, At */ 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 void initializeComponents(PluginWrapper plugin) { 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 List> findComponents(Class type, Hudson huds * 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 List> findComponents(Class type, Hudson huds 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 void load(PluginWrapper wrapper) throws IOException { 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 void load(PluginWrapper wrapper) throws IOException { 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 @@ private DependencyClassLoader findAncestorDependencyClassLoader(ClassLoader clas { 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 @@ private DependencyClassLoader findAncestorDependencyClassLoader(ClassLoader clas @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 @@ private static void explode(File archive, File destDir) throws IOException { 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 @@ private static void explode(File archive, File destDir) throws IOException { 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 @@ private static void createClassJarFromWebInfClasses(File archive, File destDir, 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 @@ protected void zipDir(Resource dir, ZipOutputStream zOut, String vPath, 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 @@ protected List getEdges(PluginWrapper pw) { 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 @@ protected List getEdges(PluginWrapper pw) { 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 @@ protected Class findClass(String name) throws ClassNotFoundException { } 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 @@ protected Enumeration findResources(String name) throws IOException { } 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 @@ protected URL findResource(String name) { 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 5a9090e79cc40..0fc4aee48a5ce 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 a36dbaf4e9f91..04e737964a801 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 914be79ffa6f7..b7db91fb94164 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 @@ 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 void run() { } 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 25f1191706509..7c9fbbddccacc 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 @@ DescriptorExtensionList createDescriptorList(Jenkins jenkins, Class desc * 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 @@ DescriptorExtensionList createDescriptorList(Hudson hudson, Class descri */ @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 @@ protected DescriptorExtensionList(Jenkins jenkins, Class describableType) { */ @Deprecated public D find(String fqcn) { - return Descriptor.find(this,fqcn); + return Descriptor.find(this, fqcn); } /** @@ -126,7 +127,7 @@ public D find(String fqcn) { */ 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 D find(Class type) { */ @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 T newInstanceFromRadioList(@NonNull JSONObject parent, @NonNull String na */ 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 @@ protected Collection> load(ExtensionComponentSet delta) { 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 static Iterable listLegacyInstances() { 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 673396061a6c3..cce69ede9ee84 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 @@ * * @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 EnvVars(@NonNull Map m) { @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 EnvVars(@NonNull EnvVars m) { */ 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; i0) { - 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 void override(String key, String value) { * 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 @@ static class OverrideOrderCalculator { 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 @@ protected Iterable getEdges(String n) { } 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 @@ private void cutCycleAt(String referee, List cycle) { 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 @@ private void cutCycle(List cycle) { // 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 void scan() { } 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 void scan() { } 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 void scan() { 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 EnvVars overrideExpandingAll(@NonNull Map all) { /** * 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 static void resolve(Map env) { **/ 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 String put(String key, String value) { * @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 void putAllNonNull(Map map) { 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 static EnvVars createCookie() { * 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 EnvVars call() { * 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 e71202f4552b1..7fcec22e76047 100644 --- a/core/src/main/java/hudson/ExpressionFactory2.java +++ b/core/src/main/java/hudson/ExpressionFactory2.java @@ -72,14 +72,14 @@ public String getExpressionText() { 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 @@ static final class JellyJexlContext implements JexlContext { 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 @@ static final class JellyMap implements Map { @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 0bcffcefbe294..b240e37f87db1 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 e80eb8edc1d63..4ef48d08008d0 100644 --- a/core/src/main/java/hudson/ExtensionComponent.java +++ b/core/src/main/java/hudson/ExtensionComponent.java @@ -50,11 +50,11 @@ public ExtensionComponent(T instance, double ordinal) { } 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 T getInstance() { * 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 10ca19bef5016..5bddd008f5f08 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; @@ -38,6 +39,7 @@ import hudson.init.InitMilestone; import hudson.model.Descriptor; import hudson.model.Hudson; +import jakarta.annotation.PostConstruct; import java.lang.annotation.Annotation; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Field; @@ -55,7 +57,6 @@ import java.util.logging.Logger; import java.util.stream.Collectors; import java.util.stream.StreamSupport; -import javax.annotation.PostConstruct; import jenkins.ExtensionComponentSet; import jenkins.ExtensionFilter; import jenkins.ExtensionRefreshException; @@ -98,7 +99,7 @@ public Collection findExtensions(Class type, Hudson hudson) { */ 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 Collection> _find(Class type, Hudson hudson) } /** - * 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 @@ protected GuiceExtensionAnnotation(Class annotationType) { protected abstract boolean isOptional(T annotation); } - + /** * Discovers components via sezpoz but instantiates them by using Guice. */ @@ -246,15 +247,15 @@ public static class GuiceFinder extends ExtensionFinder { * 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 @@ protected void configure() { 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 @@ protected Injector resolve() { 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 synchronized ExtensionComponentSet refresh() throws ExtensionRefreshExcep // 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 Collection> find(Class type) { } }; } 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 @@ private boolean isActive(Annotation annotation, AnnotatedElement e) { 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 @@ private void _find(Class type, List> result, Inject 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 void scout(Class extensionType, Hudson hudson) { */ 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 T get() { 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 @@ void error(Key key, Throwable x) { * 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 @@ private class SezpozModule extends AbstractModule implements ProvisionListener { 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 @@ private void resolve(Class c, Set> encountered) { } 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 @@ protected void configure() { 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 @@ protected void configure() { // 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); } } } @@ -575,7 +580,7 @@ public void onProvision(ProvisionInvocation provision) { Arrays.stream(c.getDeclaredMethods()) .map(m -> getMethodAndInterfaceDeclarations(m, interfaces)) .flatMap(Collection::stream) - .filter(m -> m.getAnnotation(PostConstruct.class) != null) + .filter(m -> m.getAnnotation(PostConstruct.class) != null || m.getAnnotation(javax.annotation.PostConstruct.class) != null) .findFirst() .ifPresent(method -> methods.add(0, method)); c = c.getSuperclass(); @@ -623,7 +628,7 @@ Collection getMethodAndInterfaceDeclarations(Method method, Collection> indices; + private volatile List> indices; /** * Loads indices (ideally once but as few times as possible), then reuse them later. @@ -631,14 +636,14 @@ public static final class Sezpoz extends ExtensionFinder { * {@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 @@ private List> getIndices() { */ @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 @@ static List> listDelta(Class annot @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 @@ private Collection> _find(Class type, List 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 void scout(Class extensionType, Hudson hudson) { // 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 89098e86ea280..7bae8ff5d83b1 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 @@ * 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 @@ protected ExtensionList(Jenkins jenkins, Class extensionType) { */ @Deprecated protected ExtensionList(Hudson hudson, Class extensionType, CopyOnWriteArrayList> legacyStore) { - this((Jenkins)hudson,extensionType,legacyStore); + this((Jenkins) hudson, extensionType, legacyStore); } /** @@ -120,10 +121,10 @@ protected ExtensionList(Hudson hudson, Class extensionType, CopyOnWriteArrayL * @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 void addListener(@NonNull ExtensionListListener listener) { */ 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 void addListener(@NonNull ExtensionListListener listener) { /** * 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 List> getComponents() { public T get(int index) { return ensureLoaded().get(index).getInstance(); } - + @Override public int size() { return ensureLoaded().size(); @@ -200,7 +201,7 @@ public List reverseView() { 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 boolean remove(Object o) { try { return removeSync(o); } finally { - if(extensions!=null) { + if (extensions != null) { fireOnChangeListeners(); } } @@ -238,9 +239,9 @@ public boolean removeAll(Collection c) { 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 boolean add(T t) { try { return addSync(t); } finally { - if(extensions!=null) { + if (extensions != null) { fireOnChangeListeners(); } } @@ -283,7 +284,7 @@ public boolean add(T t) { 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 T getDynamic(String className) { } 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 @@ private List> ensureLoaded() { * 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 @@ protected Object getLoadLock() { 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 @@ protected List> sort(List> r) { */ @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 6a29da2d465d6..af3c0e18b7f48 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 3655085bb9513..0127752e46bd1 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 426aa52b05a31..e04581798fc62 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 981c5cfe8816f..632001ae360ae 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 a3eb22406c32c..8d0faa9334539 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; @@ -69,7 +70,6 @@ import java.io.BufferedOutputStream; import java.io.File; import java.io.FileFilter; -import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InterruptedIOException; @@ -278,14 +278,14 @@ private Object readResolve() { } 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 +327,7 @@ public static String normalize(@NonNull String path) { 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 +350,7 @@ public static String normalize(@NonNull String path) { // 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 +367,14 @@ public static String normalize(@NonNull String path) { */ 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 +403,7 @@ public void createZipArchive(OutputStream os) throws IOException, InterruptedExc * 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 +422,7 @@ public void zip(FilePath dst) throws IOException, InterruptedException { * @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 +438,7 @@ public void zip(OutputStream os, FileFilter filter) throws IOException, Interrup */ @Deprecated public void createZipArchive(OutputStream os, final String glob) throws IOException, InterruptedException { - archive(ArchiverFactory.ZIP,os,glob); + archive(ArchiverFactory.ZIP, os, glob); } /** @@ -451,7 +451,7 @@ public void createZipArchive(OutputStream os, final String glob) throws IOExcept * @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 +514,7 @@ public int archive(final ArchiverFactory factory, OutputStream os, final DirScan 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 +529,7 @@ private static class Archive extends MasterToSlaveFileCallable { this.verificationRoot = verificationRoot; this.noFollowLinks = noFollowLinks; } + @Override public Integer invoke(File f, VirtualChannel channel) throws IOException { Archiver a = factory.create(out); @@ -543,11 +545,11 @@ public Integer invoke(File f, VirtualChannel channel) throws IOException { } 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 +562,30 @@ public int archive(final ArchiverFactory factory, OutputStream os, final String */ 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 +602,7 @@ public Void invoke(File dir, VirtualChannel channel) throws IOException, Interru unzip(dir, new File(this.filePath.getRemote())); // shortcut to local file return null; } + private static final long serialVersionUID = 1L; } @@ -611,29 +619,34 @@ public Void invoke(File dir, VirtualChannel channel) throws IOException, Interru 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 +655,13 @@ private static class UntarLocal extends MasterToSlaveFileCallable { 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 +677,20 @@ public void unzipFrom(InputStream _in) throws IOException, InterruptedException 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 +699,7 @@ private static void unzip(File dir, InputStream in) throws IOException { 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 +732,7 @@ private static void unzip(File dir, File zipFile) throws IOException { 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 +751,10 @@ private static void unzip(File dir, File zipFile) throws IOException { 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 +765,7 @@ public String invoke(File f, VirtualChannel channel) throws IOException { 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 +801,7 @@ private static class SymlinkRetainingFileFilter implements FileFilter, Serializa public boolean accept(File file) { return isSymlink(file, verificationRoot, noFollowLinks); } + private static final long serialVersionUID = 1L; } @@ -794,14 +817,18 @@ public boolean accept(File file) { 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 +846,10 @@ public Void invoke(File f, VirtualChannel channel) throws IOException, Interrupt 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 +882,7 @@ public enum TarCompression { public InputStream extract(InputStream in) { return new BufferedInputStream(in); } + @Override public OutputStream compress(OutputStream out) { return new BufferedOutputStream(out); @@ -861,15 +891,16 @@ public OutputStream compress(OutputStream out) { 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 +908,7 @@ public OutputStream compress(OutputStream out) throws IOException { }; public abstract InputStream extract(InputStream in) throws IOException; + public abstract OutputStream compress(OutputStream in) throws IOException; } @@ -897,18 +929,22 @@ public void untarFrom(InputStream _in, final TarCompression compression) throws _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 +1030,7 @@ private boolean installIfNecessaryFrom(@NonNull URL archive, @NonNull TaskListen 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 +1055,29 @@ private boolean installIfNecessaryFrom(@NonNull URL archive, @NonNull TaskListen 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 +1132,7 @@ public void copyFrom(FilePath src) throws IOException, InterruptedException { * 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 +1143,7 @@ public void copyFrom(FileItem file) throws IOException, InterruptedException { } 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 +1180,20 @@ public interface FileCallable extends Serializable, RoleSensitive { * 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 +1212,7 @@ private T act(final FileCallable callable, ClassLoader cl) throws IOExcep */ public abstract static class FileCallableWrapperFactory implements ExtensionPoint { - public abstract DelegatingCallable wrap(DelegatingCallable callable); + public abstract DelegatingCallable wrap(DelegatingCallable callable); } @@ -1225,15 +1263,15 @@ protected void after() {} */ 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 +1279,8 @@ public Future actAsync(final FileCallable callable) throws IOException * 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 +1296,23 @@ public V act(Callable callable) throws IOException, * * @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 +1331,10 @@ public void checkRoles(RoleChecker checker) throws SecurityException { 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 +1359,7 @@ public VirtualFile toVirtualFile() { Jenkins j = Jenkins.getInstanceOrNull(); if (j != null) { for (Computer c : j.getComputers()) { - if (getChannel()==c.getChannel()) { + if (getChannel() == c.getChannel()) { return c; } } @@ -1332,11 +1375,13 @@ public void mkdirs() throws IOException, InterruptedException { 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 +1435,10 @@ private static File[] listParentFiles(File f) { 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 +1452,10 @@ public Void invoke(File f, VirtualChannel channel) throws IOException { 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 +1471,29 @@ public Void invoke(File f, VirtualChannel channel) throws IOException { 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 +1510,7 @@ public FilePath sibling(String rel) { * 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 +1519,7 @@ public FilePath withSuffix(String suffix) { * @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 +1531,11 @@ public FilePath getParent() { 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 +1555,21 @@ public FilePath createTempFile(final String prefix, final String suffix) throws 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 +1594,7 @@ public String invoke(File dir, VirtualChannel channel) throws IOException { * @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 +1623,27 @@ public FilePath createTextTempFile(final String prefix, final String suffix, fin 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,10 +1652,10 @@ public String invoke(File dir, VirtualChannel channel) throws IOException { 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)) { + try (Writer w = Files.newBufferedWriter(Util.fileToPath(f), Charset.defaultCharset())) { w.write(contents); } @@ -1631,15 +1688,19 @@ public FilePath createTempDir(final String prefix, final String suffix) throws I 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 +1730,10 @@ public boolean delete() throws IOException, InterruptedException { 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 +1747,10 @@ public Void invoke(File f, VirtualChannel channel) throws IOException { 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 +1767,10 @@ public Boolean invoke(File f, VirtualChannel channel) throws IOException { 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 +1785,23 @@ public Long invoke(File f, VirtualChannel channel) throws IOException { 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 +1809,29 @@ public Void invoke(File f, VirtualChannel channel) throws IOException { 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 +1844,10 @@ public String invoke(File f, VirtualChannel channel) throws IOException { 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 +1862,10 @@ public Boolean invoke(File f, VirtualChannel channel) throws IOException { 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 +1879,10 @@ public Long invoke(File f, VirtualChannel channel) throws IOException { 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 +1896,10 @@ public Long invoke(File f, VirtualChannel channel) throws IOException { 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 +1913,10 @@ public Long invoke(File f, VirtualChannel channel) throws IOException { 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 +1944,18 @@ public Long invoke(File f, VirtualChannel channel) throws IOException { * @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 +1970,7 @@ public Void invoke(File f, VirtualChannel channel) throws IOException { 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 +1986,13 @@ private static void _chmod(File f, int mask) throws IOException { * @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 +2007,7 @@ public Integer invoke(File f, VirtualChannel channel) throws IOException { */ @NonNull public List list() throws IOException, InterruptedException { - return list((FileFilter)null); + return list((FileFilter) null); } /** @@ -1952,6 +2042,7 @@ private static final class DirectoryFilter implements FileFilter, Serializable { public boolean accept(File f) { return f.isDirectory(); } + private static final long serialVersionUID = 1L; } @@ -1971,12 +2062,16 @@ public List list(final FileFilter filter) throws IOException, Interrup } 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 +2132,27 @@ public FilePath[] list(final String includes, final String excludes) throws IOEx 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 { this.verificationRoot = verificationRoot; this.noFollowLinks = noFollowLinks; } + @Override public Void invoke(File f, VirtualChannel channel) throws IOException, InterruptedException { try (InputStream fis = newInputStreamDenyingSymlinkAsNeeded(f, verificationRoot, noFollowLinks); OutputStream out = p.getOut()) { @@ -2203,7 +2303,7 @@ public Void invoke(File f, VirtualChannel channel) throws IOException, Interrupt * @since 1.586 */ public InputStream readFromOffset(final long offset) throws IOException, InterruptedException { - if(channel ==null) { + if (channel == null) { final RandomAccessFile raf = new RandomAccessFile(new File(remote), "r"); try { raf.seek(offset); @@ -2276,8 +2376,10 @@ public Void invoke(File f, VirtualChannel channel) throws IOException { public String readToString() throws IOException, InterruptedException { return act(new ReadToString()); } + private static class ReadToString extends MasterToSlaveFileCallable { 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 +2399,7 @@ public String invoke(File f, VirtualChannel channel) throws IOException, Interru * 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 +2407,10 @@ public OutputStream write() throws IOException, InterruptedException { 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 +2429,17 @@ public OutputStream invoke(File f, VirtualChannel channel) throws IOException, I 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 +2458,10 @@ public Void invoke(File f, VirtualChannel channel) throws IOException { 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 +2473,21 @@ public String invoke(File f, VirtualChannel channel) throws IOException { * 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 +2501,35 @@ public Void invoke(File f, VirtualChannel channel) throws IOException { * @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 +2545,7 @@ public void copyTo(FilePath target) throws IOException, InterruptedException { 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 +2565,14 @@ public void copyToWithPermission(FilePath target) throws IOException, Interrupte 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 +2595,15 @@ public void copyTo(OutputStream os) throws IOException, InterruptedException { // 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 +2622,12 @@ public Void invoke(File f, VirtualChannel channel) throws IOException { */ 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 +2653,9 @@ interface RemoteCopier { * 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 +2667,7 @@ interface RemoteCopier { * @since 1.312 */ public int copyRecursiveTo(FilePath target) throws IOException, InterruptedException { - return copyRecursiveTo("**/*",target); + return copyRecursiveTo("**/*", target); } /** @@ -2557,7 +2682,7 @@ public int copyRecursiveTo(FilePath target) throws IOException, InterruptedExcep * 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 +2724,11 @@ public int copyRecursiveTo(final DirScanner scanner, final FilePath target, fina * @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 +2747,10 @@ public int copyRecursiveTo(final DirScanner scanner, final FilePath target, fina 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 +2781,14 @@ private IOException ioWithCause(ExecutionException e) { 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 +2822,7 @@ public void visit(File f, String relativePath) throws IOException { count.incrementAndGet(); } } + private boolean tryCopyWithAttributes(File f, Path targetPath) { try { Files.copy(fileToPath(f), targetPath, @@ -2704,10 +2833,12 @@ private boolean tryCopyWithAttributes(File f, Path targetPath) { } 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 +2854,7 @@ public void visitSymlink(File link, String target, String relativePath) throws I return count.get(); } } + private static class ReadFromTar extends MasterToSlaveFileCallable { private final Pipe pipe; private final String description; @@ -2735,7 +2867,9 @@ private static class ReadFromTar extends MasterToSlaveFileCallable { 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 +2878,38 @@ public Void invoke(File f, VirtualChannel channel) throws IOException { } } } + 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 +2948,7 @@ public int tar(OutputStream out, DirScanner scanner) throws IOException, Interru 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 +3002,19 @@ private static void readFromTar(String name, File baseDir, InputStream in) throw * @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 +3079,30 @@ public String validateAntFileMask(final String fileMasks, final boolean caseSens 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 +3113,11 @@ public String invoke(File dir, VirtualChannel channel) throws IOException, Inter // 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 +3125,28 @@ public String invoke(File dir, VirtualChannel channel) throws IOException, Inter // 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 +3154,43 @@ public String invoke(File dir, VirtualChannel channel) throws IOException, Inter // 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 +3200,7 @@ public String invoke(File dir, VirtualChannel channel) throws IOException, Inter 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 +3221,13 @@ class Cancel extends RuntimeException {} 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 +3236,9 @@ class Cancel extends RuntimeException {} 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 +3278,7 @@ public static FormValidation validateFileMask(@CheckForNull FilePath path, Strin * 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 +3311,15 @@ public FormValidation validateFileMask(String value, boolean errorIfNotExist, bo 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 +3349,24 @@ public FormValidation validateRelativePath(String value, boolean errorIfNotExist 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 +3375,7 @@ public FormValidation validateRelativePath(String value, boolean errorIfNotExist 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 +3394,11 @@ private static void checkPermissionForValidate() { * 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 +3408,7 @@ public String toString() { } public VirtualChannel getChannel() { - if(channel!=null) return channel; + if (channel != null) return channel; else return localChannel; } @@ -3269,7 +3416,7 @@ public VirtualChannel getChannel() { * 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 +3426,7 @@ private void writeObject(ObjectOutputStream oos) throws IOException { } oos.defaultWriteObject(); - oos.writeBoolean(channel==null); + oos.writeBoolean(channel == null); } private Channel _getChannelForSerialization() { @@ -3295,7 +3442,7 @@ private void readObject(ObjectInputStream ois) throws IOException, ClassNotFound Channel channel = _getChannelForSerialization(); ois.defaultReadObject(); - if(ois.readBoolean()) { + if (ois.readBoolean()) { this.channel = channel; } else { this.channel = null; @@ -3317,7 +3464,7 @@ private void readObject(ObjectInputStream ois) throws IOException, ClassNotFound /** * 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 +3518,7 @@ private static class TunneledInterruptedException extends IOException { private TunneledInterruptedException(InterruptedException cause) { super(cause); } + private static final long serialVersionUID = 1L; } @@ -3383,6 +3531,7 @@ private TunneledInterruptedException(InterruptedException cause) { 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 +3547,18 @@ public static final class ExplicitlySpecifiedDirScanner extends DirScanner { 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 +3631,7 @@ private static class IsDescendant extends MasterToSlaveFileCallable { private static final long serialVersionUID = 1L; private String potentialChildRelativePath; - private IsDescendant(@NonNull String potentialChildRelativePath){ + private IsDescendant(@NonNull String potentialChildRelativePath) { this.potentialChildRelativePath = potentialChildRelativePath; } @@ -3531,7 +3680,7 @@ public Boolean invoke(@NonNull File parentFile, @NonNull VirtualChannel channel) } 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 +3694,7 @@ public Boolean invoke(@NonNull File parentFile, @NonNull VirtualChannel channel) 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 +3703,7 @@ public Boolean invoke(@NonNull File parentFile, @NonNull VirtualChannel channel) 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 +3760,7 @@ private static class SymlinkDiscardingFileFilter implements FileFilter, Serializ 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 e2dbb4480ff85..d93f2c8e8b76e 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 @@ */ @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 2d54d3358f923..b41fb8cd2164e 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 static boolean isModelWithContextMenu(Object o) { 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 static void initPageVariables(JellyContext context) { 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 static void initPageVariables(JellyContext context) { * 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 JDK.DescriptorImpl getJDKDescriptor() { * 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 static String getDiffString(int i) { * {@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 static String getDiffString2(int i) { * 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 static String getDiffString2(String prefix, int i, String suffix) { 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 static RunUrl decompose(StaplerRequest req) { 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 static RunUrl decompose(StaplerRequest req) { // 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 static RunUrl decompose(StaplerRequest req) { * @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 String getPreviousBuildUrl() { } 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 static Map getSystemProperties() { /** * Gets the system property indicated by the specified key. - * + * * Delegates to {@link SystemProperties#getString(String)}. */ @Restricted(DoNotUse.class) @@ -533,14 +534,14 @@ public static Map getEnvVars() { } 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 static String[] printLogRecordHtml(LogRecord r, LogRecord prior) { * @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 static Iterable reverse(Collection collection) { 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 static Cookie getCookie(HttpServletRequest req,String name) { 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 static String getYuiSuffix() { /** * 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 static boolean isAutoRefresh(HttpServletRequest request) { } public static boolean isCollapsed(String paneId) { - return PaneStatusProperties.forCurrentUser().isCollapsed(paneId); + return PaneStatusProperties.forCurrentUser().isCollapsed(paneId); } @Restricted(NoExternalUse.class) @@ -713,11 +716,11 @@ public static String getUserTimeZonePostfix() { * 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 static String getNearestAncestorUrl(StaplerRequest req,Object it) { */ 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 static String getWin32ErrorMessage(IOException e) { } 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 static String xmlEscape(String s) { } 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 static String htmlAttributeEscape(String text) { } 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 static void checkPermission(AccessControlled object, Permission permissio 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 static void checkPermission(Object object, Permission permission) throws * 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 static boolean hasPermission(Object object, Permission permission) throws 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 static boolean hasPermission(Object object, Permission permission) throws 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 static void adminCheck(StaplerRequest req, StaplerResponse rsp, Object re } // 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 static void adminCheck(StaplerRequest req, StaplerResponse rsp, Object re */ 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 static String inferHudsonURL(StaplerRequest req) { * 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 static List getJobPropertyDescriptors(Job job) { 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 static List> getAuthorizationStrategyDe 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 static Collection getSortedDescriptorsForGlobalConfig(com.goo 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 static Collection getSortedDescriptorsForGlobalConfig(com.goo 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 static Collection getSortedDescriptorsForGlobalConfigByDescri 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 static Collection getSortedDescriptorsForGlobalConfigByDescri 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 static boolean hasAnyPermission(Object object, Permission[] permissions) if (ac != null) { return hasAnyPermission(ac, permissions); } - + return hasAnyPermission(Jenkins.get(), permissions); } } @@ -1219,7 +1223,7 @@ public static void checkAnyPermission(Object object, Permission[] permissions) t 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 @@ private static class Tag implements Comparable { 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 int compareTo(Tag that) { * 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 static String getIconFilePath(Action a) { * 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 static String getRelativeNameFrom(@CheckForNull Item p, @CheckForNull Ite 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 static String getRelativeNameFrom(@CheckForNull Item p, @CheckForNull Ite @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 static String getRelativeDisplayNameFrom(@CheckForNull Item p, @CheckForN 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 static ThreadGroupMap sortThreadsAndGetGroupMap(ThreadInfo[] list) { // 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 @@ private static class ThreadSorterBase { 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 static String dumpThreadInfo(ThreadInfo ti, ThreadGroupMap map) { } 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 static Collection emptyList() { 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 static T defaulted(T value, T defaultValue) { 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 static void printStackTrace(@CheckForNull Throwable t, @NonNull PrintStre * 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 static boolean isAnonymous() { */ public static JellyContext getCurrentJellyContext() { JellyContext context = ExpressionFactory2.CURRENT_CONTEXT.get(); - assert context!=null; + assert context != null; return context; } @@ -1796,8 +1802,8 @@ public static String runScript(Script script) throws JellyTagException { * Warning: do not call this with a {@link RunList}, or you will break lazy loading! */ public static List subList(List base, int maxSize) { - if(maxSize List subList(List base, int maxSize) { public static String joinPath(String... components) { StringBuilder buf = new StringBuilder(); for (String s : components) { - if (s.length()==0) continue; + if (s.length() == 0) continue; - if (buf.length()>0) { - 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 static String joinPath(String... components) { * * @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 static String joinPath(String... components) { 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 static String joinPath(String... components) { 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 String getServerName() { // 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 String getServerName() { */ @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 String getCheckUrl(String userDefined, Object descriptor, String field) { * @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 void calcCheckUrl(Map attributes, String userDefined, Object descriptor, 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 List singletonList(T t) { */ 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 static List> getCloudDescriptors() { * 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 static Date getCurrentTime() { } 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 static String generateConsoleAnnotationScriptAndStylesheet() { 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 @@ private String getJellyViewsInformationForCurrentRequest() { } 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 static boolean isWipeOutPermissionEnabled() { } 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 static List getRequestHeaders(String name) { * 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 static String getAvatar(User user, String avatarSize) { */ @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 static String breakableString(final String plain) { */ 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 aa4348b57a9bb..90a1d403e2259 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 5b67208c5c937..6ea7375ff5a95 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 @@ protected Launcher(@NonNull Launcher 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 TaskListener getListener() { @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 ProcStarter writeStdin() { * @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 final ProcStarter launch() { * 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 final Proc launch(String[] cmd, boolean[] mask, Map env, * 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 Proc launch(String[] cmd, boolean[] mask, String[] env, InputStream in, O * 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 @@ protected final void printCommandLine(@NonNull String[] cmd, @CheckForNull FileP 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 @@ protected final void printCommandLine(@NonNull String[] cmd, @CheckForNull FileP 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 @@ protected final void printCommandLine(@NonNull String[] cmd, @CheckForNull FileP * @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 @@ protected final void maskedPrintCommandLine(@NonNull List cmd, @CheckFor } 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 @@ protected final void maskedPrintCommandLine(@NonNull String[] cmd, @NonNull bool 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 boolean isUnix() { @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 Proc launch(ProcStarter starter) throws IOException { @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 void kill(Map modelEnvVars) throws IOException, Interrupt } 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 boolean isUnix() { @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 Proc launch(ProcStarter starter) throws IOException { 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 Proc launch(ProcStarter ps) throws IOException { // 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 Channel launchChannel(OutputStream out, ProcessBuilder pb) throws IOExcep 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 synchronized void terminate(IOException e) { 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 VirtualChannel getChannel() { @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 Proc launch(ProcStarter ps) throws IOException { 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 boolean isUnix() { } @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 String toString() { 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 Launcher getInner() { 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 static class IOTriplet implements Serializable { /** * 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 RemoteProcess call() throws IOException { } 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 IOTriplet getIOtriplet() { 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 @@ private static class RemoteChannelLaunchCallable extends MasterToSlaveCallable 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 OutputStream call() throws IOException { 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 OutputStream call() throws IOException { 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 @@ private static EnvVars inherit(@CheckForNull String[] env) { /** * 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 ede9554f5f488..d1fcfd678e3ad 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 b0b40ba89151d..ba051f72a633c 100644 --- a/core/src/main/java/hudson/Lookup.java +++ b/core/src/main/java/hudson/Lookup.java @@ -32,14 +32,14 @@ * @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 T set(Class type, T instance) { */ 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 8ae8dfcd76ed1..625fef0c52ee8 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 static void main(String[] args) { /** @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 static int run(String[] args) throws Exception { 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 static int remotePost(String[] args) throws Exception { 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 static int remotePost(String[] args) throws Exception { 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 static int remotePost(String[] args) throws Exception { } // 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 static int remotePost(String[] args) throws Exception { } 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 static int remotePost(String[] args) throws Exception { 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 static int remotePost(String[] args) throws Exception { * 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 @@ private static HttpURLConnection open(URL url) throws IOException { * 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 0317a7e1b0164..182565205ecfa 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 @@ private static final class Tag implements Comparable { @Override public int compareTo(Tag that) { - return this.pos-that.pos; + return this.pos - that.pos; } } @@ -74,7 +75,7 @@ public int compareTo(Tag that) { * 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 SubText(Matcher m, int textOffset) { 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 void href(String url) { * 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 int start() { * 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 int end() { * 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 int groupCount() { 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 String replace(String s) { @Override protected SubText createSubText(Matcher m) { - return new SubText(m,start); + return new SubText(m, start); } } @@ -252,29 +253,29 @@ public String getText() { */ @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 String toString() { * 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 String toString(boolean preEscape) { int copied = 0; // # of chars already copied from text to buf for (Tag tag : tags) { - if (copied findTokens(Pattern pattern) { @Override protected SubText createSubText(Matcher m) { - return new SubText(m,0); + return new SubText(m, 0); } } diff --git a/core/src/main/java/hudson/PermalinkList.java b/core/src/main/java/hudson/PermalinkList.java index 4b165d66747f1..6c97c54a00b2c 100644 --- a/core/src/main/java/hudson/PermalinkList.java +++ b/core/src/main/java/hudson/PermalinkList.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.PermalinkProjectAction.Permalink; @@ -50,7 +51,7 @@ public PermalinkList() { */ 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 Permalink findNearest(String id) { 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 2195f571aceec..23ab0caa6653a 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 @@ * @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 static boolean isDarwin() { */ 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 0942db8fd90d7..41eafeabf5455 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 void doDynamic(StaplerRequest req, StaplerResponse rsp) throws IOExceptio */ protected void load() throws IOException { XmlFile xml = getConfigXml(); - if(xml.exists()) + if (xml.exists()) xml.unmarshal(this); } @@ -277,7 +278,7 @@ protected void load() throws IOException { */ @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 void save() throws IOException { */ 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 8aee057e7b39c..a990ea329e5a5 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 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 9b9f381465274..e13fb0605666f 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 @@ PluginManager doCreate(@NonNull Class klass, @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 @@ PluginManager doCreate(@NonNull Class klass, } } 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 @@ protected PluginManager(ServletContext context, File rootDir) { } 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 void run(Reactor session) throws Exception { } }); - 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 void run(Reactor session1) throws Exception { 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 void run(Reactor session1) throws Exception { 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 @@ protected void reactOnCycle(PluginWrapper q, List cycle) { // 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 @@ void considerDetachedPlugin(String shortName) { 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 @@ void considerDetachedPlugin(String shortName) { 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 @@ private String normalisePluginName(@NonNull String name) { * 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 void dynamicLoad(File arc, boolean removeExisting, @CheckForNull List 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 void dynamicLoad(File arc, boolean removeExisting, @CheckForNull List plugins) throws Exception { 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 synchronized void resolveDependentPlugins() { 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 synchronized void resolveDependentPlugins() { */ 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 @@ protected void copyBundledPlugin(URL src, String fileName) throws IOException { } /*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 @@ protected void copyBundledPlugin(URL src, String fileName) throws IOException { 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 @@ protected void copyBundledPlugin(URL src, String fileName) throws IOException { 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 List getFailedPlugins() { @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 PluginWrapper getPlugin(String shortName) { @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 PluginWrapper getPlugin(Class pluginClazz) { 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 String getSearchUrl() { * @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 PluginWrapper whichPlugin(Class c) { 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 HttpResponse doPluginsSearch(@QueryParameter String query, @QueryParamete 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 HttpResponse doPlugins() { 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 void doInstall(StaplerRequest req, StaplerResponse rsp) throws IOExceptio 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 void run() { 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 void run() { break; } updateCenter.persistInstallStatus(); - if(!failures) { + if (!failures) { try (ACLContext acl = ACL.as2(currentAuth)) { InstallUtil.proceedToNextStateFrom(InstallState.INITIAL_PLUGINS_INSTALLING); } @@ -1737,7 +1738,7 @@ public HttpResponse doProxyConfigure(StaplerRequest req) throws IOException, Ser 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 HttpResponse doProxyConfigure(StaplerRequest req) throws IOException, Ser interface PluginCopier { void copy(File target) throws Exception; + void cleanup(); } @@ -1779,9 +1781,9 @@ static class UrlPluginCopier implements PluginCopier { @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 HttpResponse doUploadPlugin(StaplerRequest req) throws IOException, Servl 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 HttpResponse doUploadPlugin(StaplerRequest req) throws IOException, Servl 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 HttpResponse doUploadPlugin(StaplerRequest req) throws IOException, Servl .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 HttpResponse doUploadPlugin(StaplerRequest req) throws IOException, Servl @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 HttpResponse doUploadPlugin(StaplerRequest req) throws IOException, Servl .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 @@ protected String identifyPluginShortName(File t) { 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 List> prevalidateConfig(InputStream 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 JSONArray doPrevalidateConfig(StaplerRequest req) throws IOException { 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 HttpResponse doInstallNecessaryPlugins(StaplerRequest req) throws IOExcep /** * 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 Map parseRequestedPlugins(InputStream configXml) th }); } 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 MetadataCache createCache() { @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 String toString() { 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 String getExceptionString() { * Stores {@link Plugin} instances. */ /*package*/ static final class PluginInstanceStore { - final Map store = new ConcurrentHashMap<>(); + final Map store = new ConcurrentHashMap<>(); } /** @@ -2326,10 +2330,10 @@ public String getDisplayName() { @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 static PluginUpdateMonitor getInstance() { * @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 Collection getPluginsToBeUpdated() { 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 5dfc8136573aa..2b237931c038e 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 @@ */ 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 @@ PluginWrapper createPluginWrapper(File archive) */ @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 5e0f24a12e971..a42596726cdbd 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 static final class Dependency { 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 String toString() { * @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 @@ static String computeShortName(Manifest manifest, String fileName) { // 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 String toString() { @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 String getLongName() { @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 String getVersion() { 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 @@ private String getVersionOf(Manifest manifest) { @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 void releaseClassLoader() { 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 void enable() throws IOException { 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 boolean isActive() { 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 Manifest getManifest() { } 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 String getPluginClass() { 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 @@ static boolean isSnapshot(@NonNull String version) { 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 @@ private List getInfoFromAllSites() { */ @Exported public boolean hasUpdate() { - return getUpdateInfo()!=null; + return getUpdateInfo() != null; } @Exported @@ -1165,7 +1166,7 @@ public boolean isDowngradable() { * 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 PluginWrapper getPlugin(String shortName) { * 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 24cd16552295f..6bcb6d416819a 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 @@ protected 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 void run() { 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 LocalProc(String[] cmd,String[] env,InputStream in,OutputStream out, File * 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 @@ private LocalProc( String name, ProcessBuilder procBuilder, InputStream in, Outp 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 @@ private LocalProc( String name, ProcessBuilder procBuilder, InputStream in, Outp 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 @@ private LocalProc( String name, ProcessBuilder procBuilder, InputStream in, Outp // 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 OutputStream getStdin() { @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 int join() throws InterruptedException, IOException { // 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 void kill() throws InterruptedException, IOException { * 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 int join() throws IOException, InterruptedException { 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 OutputStream getStdin() { */ @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 cecd40f979a0f..c087c00ceb8c8 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 Proxy createProxy(String host) { } public static Proxy createProxy(String host, String name, int port, String noProxyHost) { - if (host!=null && noProxyHost!=null) { + if (host != null && noProxyHost != null) { for (Pattern p : getNoProxyHostPatterns(noProxyHost)) { if (p.matcher(host).matches()) return Proxy.NO_PROXY; } } - return new Proxy(Proxy.Type.HTTP, new InetSocketAddress(name,port)); + return new Proxy(Proxy.Type.HTTP, new InetSocketAddress(name, port)); } @Override public void save() throws IOException { - if(BulkChange.contains(this)) return; + if (BulkChange.contains(this)) return; XmlFile config = getXmlFile(); config.write(this); SaveableListener.fireOnChange(this, config); @@ -289,7 +290,7 @@ public static XmlFile getXmlFile() { public static ProxyConfiguration load() throws IOException { XmlFile f = getXmlFile(); - if(f.exists()) + if (f.exists()) return (ProxyConfiguration) f.read(); else return null; @@ -300,24 +301,24 @@ public static ProxyConfiguration load() throws IOException { */ public static URLConnection open(URL url) throws IOException { final ProxyConfiguration p = get(); - + URLConnection con; - if(p==null) { + if (p == null) { con = url.openConnection(); } else { Proxy proxy = p.createProxy(url.getHost()); con = url.openConnection(proxy); - if(p.getUserName()!=null) { + if (p.getUserName() != null) { // Add an authenticator which provides the credentials for proxy authentication Authenticator.setDefault(p.authenticator); p.jenkins48775workaround(proxy, url); } } - - if(DEFAULT_CONNECT_TIMEOUT_MILLIS > 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 @@ private void jenkins48775workaround(Proxy proxy, URL url) { } } authCacheSeeded = true; - } else if ("https".equals(url.getProtocol())){ + } else if ("https".equals(url.getProtocol())) { // if we access any http url using a proxy then the auth cache will have been seeded authCacheSeeded = authCacheSeeded || proxy != Proxy.NO_PROXY; } @@ -445,8 +446,8 @@ public FormValidation doValidateProxy( GetMethod method = null; try { method = new GetMethod(testUrl); - method.getParams().setParameter("http.socket.timeout", DEFAULT_CONNECT_TIMEOUT_MILLIS > 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 FormValidation doValidateProxy( AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT); client.getState().setProxyCredentials(scope, credentials); } - + int code = client.executeMethod(method); if (code != HttpURLConnection.HTTP_OK) { return FormValidation.error(Messages.ProxyConfiguration_FailedToConnect(testUrl, code)); @@ -466,12 +467,12 @@ public FormValidation doValidateProxy( method.releaseConnection(); } } - + return FormValidation.ok(Messages.ProxyConfiguration_Success()); } private boolean isNoProxyHost(String host, String noProxyHost) { - if (host!=null && noProxyHost!=null) { + if (host != null && noProxyHost != null) { for (Pattern p : getNoProxyHostPatterns(noProxyHost)) { if (p.matcher(host).matches()) { return true; @@ -482,7 +483,7 @@ private boolean isNoProxyHost(String host, String noProxyHost) { } private Credentials createCredentials(String userName, String password) { - if (userName.indexOf('\\') >= 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 4460208a733db..90fb0be87d37a 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 @@ * 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 5d0e28dc5c6ef..708d0120dc9df 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 static JSONObject get(StaplerRequest req) throws ServletException { * 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 717c1df919531..eb6358f7a3f31 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 void run(Throwable cause) { }).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 void shutdown() { 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 @@ private final class ConnectionHandler 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 void run() { 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 void run() { 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 @@ private void respondHello(String header, Socket s) throws IOException { 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 @@ protected void doAperiodicRun() { } 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 String toString() { } } - 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 String toString() { */ @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 String toString() { */ @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 f3794f4e33ea0..95c8a4e6bd349 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 e66820214612d..66d2d262b4421 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 static List filter( @NonNull Iterable base, @NonNull Class t * 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 static List filter( @NonNull List base, @NonNull Class type * */ @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 static String replaceMacro( @CheckForNull String s, @NonNull Map 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 static File createTempDir() throws IOException { * 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 static String getWin32ErrorMessage(@NonNull IOException e) { @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 static String getWin32ErrorMessage(Throwable e) { 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 static String getHostName() { * @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 static void copyStreamAndClose(@NonNull Reader in, @NonNull Writer out) t */ @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 static String[] mapToEnv(@NonNull Map m) { public static int min(int x, @NonNull int... values) { for (int i : values) { - if(i 0) else if (seconds >= 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 static String getPastTimeString(long duration) { @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 static String combine(long n, @NonNull String suffix) { * 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 static String encode(@NonNull String s) { 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 static String encode(@NonNull String s) { } private static final boolean[] uriMap = new boolean[123]; + static { String raw = "! $ &'()*+,-. 0123456789 = @ABCDEFGHIJKLMNOPQRSTUVWXYZ _ abcdefghijklmnopqrstuvwxyz"; @@ -888,6 +890,7 @@ public static String encode(@NonNull String s) { } private static final boolean[] fullUriMap = new boolean[123]; + static { String raw = " 0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz"; // !"#$%&'()*+,-./0123456789:;<=>?@ [\]^_` {|}~ @@ -924,11 +927,11 @@ public static String rawEncode(@NonNull String s) { * 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 @@ private static String encode(String s, boolean[] map){ 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 @@ private static String encode(String s, boolean[] map){ out.append(toDigit(aByte & 0xF)); } - if(Character.charCount(codePoint) > 1) { + if (Character.charCount(codePoint) > 1) { i++; // we processed two characters } } @@ -987,14 +990,14 @@ private static String encode(String s, boolean[] map){ } 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 static String singleQuote(String s) { */ @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 static String escape(@CheckForNull String text) { @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 static T fixNull(@CheckForNull T s, @NonNull T defaultValue) { */ @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 static String fixEmpty(@CheckForNull String s) { */ @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 static Iterable fixNull(@CheckForNull Iterable l) { @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 static String getFileName(@NonNull String filePath) { @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 static FileSet createFileSet(@NonNull File baseDir, @NonNull String inclu 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 static FileSet createFileSet(@NonNull File baseDir, @NonNull String inclu @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 static void createSymlink(@NonNull File baseDir, @NonNull String targetPa } 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 static String resolveSymlink(File link, TaskListener listener) throws Int @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 static String resolveSymlink(@NonNull File link) throws IOException { @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 static String encodeRFC2396(String url) { */ @NonNull public static String wrapToErrorSpan(@NonNull String s) { - s = ""+s+""; + s = "" + s + ""; return s; } @@ -1596,8 +1600,8 @@ private static Method getMethod(@NonNull Class clazz, @Nullable Class base 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 static File changeExtension(@NonNull File dst, @NonNull String ext) { */ @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 static String intern(@CheckForNull String s) { @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 static boolean isSafeToRedirectTo(@NonNull String uri) { */ 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 static Properties loadProperties(@NonNull String properties) throws IOExc 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 static Properties loadProperties(@NonNull String properties) throws IOExc * @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 static Set modeToPermissions(int mode) throws IOExce throw new IOException(e); } } - + /** * Create a directory by creating all nonexistent parent directories first. * @@ -1791,21 +1795,21 @@ public static Path createDirectories(@NonNull Path dir, FileAttribute... attr * 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 static long daysElapsedSince(@NonNull Date date){ 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 static long daysElapsedSince(@NonNull Date date){ /** * 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 82aee9f2f9acc..b4b24f858fd6c 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 void contextInitialized(ServletContextEvent event) { 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 Locale get() { 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 Locale get() { 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 Locale get() { 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 void run() { 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 void run() { } 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 void joinInit() throws InterruptedException { * @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 @@ private void installLogger() { 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 FileAndDescription getHomeDir(ServletContextEvent event) { // 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 @@ private static void _setJenkinsJVM(boolean jenkinsJVM) { } } - 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 25938f580f05c..19d536700f8a3 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 c9f0478f0bb45..f624104df673e 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 XStream getXStream() { */ 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 Object read() throws IOException { * 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 @@ private Object unmarshal(Object o, boolean nullOut) throws IOException { 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 void write( Object o ) throws IOException { writing.set(null); } w.commit(); - } catch(RuntimeException e) { + } catch (RuntimeException e) { throw new IOException(e); } finally { w.abort(); @@ -250,7 +251,7 @@ public boolean exists() { 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 void writeRawTo(Writer w) throws IOException { public String sniffEncoding() throws IOException { class Eureka extends SAXException { final String encoding; + Eureka(String encoding) { this.encoding = encoding; } @@ -345,11 +347,11 @@ public void startElement(String uri, String localName, String qName, Attributes } 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 @@ private void attempt() throws Eureka { // 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 8d966dc924d96..ead7f267ff608 100644 --- a/core/src/main/java/hudson/cli/AbstractBuildRangeCommand.java +++ b/core/src/main/java/hudson/cli/AbstractBuildRangeCommand.java @@ -15,18 +15,18 @@ */ @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 116ab82adf28b..6bab9deeb7d1a 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 @@ @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 @@ protected int run() throws Exception { 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 bb84871a7f1c9..b4f7ae15e0a1e 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 String getShortDescription() { 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 @@ protected int run() throws Exception { 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 @@ protected int run() throws Exception { 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 @@ protected int run() throws Exception { } 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 @@ protected int run() throws Exception { 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 @@ protected int run() throws Exception { 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 @@ protected int run() throws Exception { // 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 @@ protected int run() throws Exception { } } 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 @@ protected void printUsageSummary(PrintStream stderr) { 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 a5583b874c972..d42e974452a2c 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 void send(byte[] data) throws IOException { sentBytes += data.length; sentCount++; } + @Override public void close() throws IOException { doClose(); } } + private void doClose() { close(); } + @Override protected void opened() { try { @@ -156,6 +160,7 @@ protected void opened() { } }, "CLI handler for " + authentication.getName()).start(); } + @Override protected void binary(byte[] payload, int offset, int len) { try { @@ -166,10 +171,12 @@ protected void binary(byte[] payload, int offset, int len) { 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 @@ protected void closed(int statusCode, String reason) { @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 @@ static class ServerSideImpl extends PlainCLIProtocol.ServerSide { 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 @@ protected void onLocale(String text) { } LOGGER.log(Level.WARNING, "unknown client locale {0}", text); } + @Override protected void onEncoding(String text) { try { @@ -231,18 +242,22 @@ protected void onEncoding(String text) { 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 @@ protected void handleClose() { 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 d27d0b6beff5f..913003a8aefc2 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 String getName() { /** * 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 int main(List args, Locale locale, InputStream stdin, PrintStream Functions.printStackTrace(e, stderr); return 1; } finally { - if(sc != null) + if (sc != null) sc.setAuthentication(old); // restore } } @@ -335,8 +336,8 @@ public Channel checkChannel() throws AbortException { * @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 void setTransportAuth(org.acegisecurity.Authentication transportAuth) { /** * 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)} @@ -432,7 +433,12 @@ public final String getUsage() { @Restricted(NoExternalUse.class) public final String getLongDescription() { ByteArrayOutputStream out = new ByteArrayOutputStream(); - PrintStream ps = new PrintStream(out); + PrintStream ps; + try { + ps = new PrintStream(out, false, getClientCharset().name()); + } catch (UnsupportedEncodingException e) { + throw new AssertionError(e); + } printUsageSummary(ps); ps.close(); @@ -446,7 +452,7 @@ public final String getLongDescription() { /** * 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 +511,9 @@ protected CLICommand createClone() { */ 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 +532,7 @@ public static ExtensionList all() { */ 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 +566,10 @@ public static CLICommand getCurrent() { 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 f965477886107..4e3064f431782 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 f6a4c60b02c12..74d789179f5f8 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 6968bb274f77c..0d3e9049205ad 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 @@ 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 fb2568717532c..eb97d996ff01f 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 void writeObject(Object o) throws IOException { 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 byte[] readByteArray() throws IOException { * 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 Connection encryptConnection(SecretKey sessionKey, String algorithm) thro 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 @@ private IvParameterSpec createIv(SecretKey sessionKey) { */ 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 @@ private String detectKeyAlgorithm(KeyPair kp) { 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 void proveIdentity(byte[] sharedSecret, KeyPair key) throws IOException, 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 PublicKey verifyIdentity(byte[] sharedSecret) throws IOException, General 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 771a40b8c9f74..12d9ef1dff2d3 100644 --- a/core/src/main/java/hudson/cli/ConsoleCommand.java +++ b/core/src/main/java/hudson/cli/ConsoleCommand.java @@ -27,36 +27,36 @@ public String getShortDescription() { 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 @@ protected int run() throws Exception { 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 @@ protected int run() throws Exception { 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 41aa8836b704e..021d34d761672 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 @@ /** * Copies a job from CLI. - * + * * @author Kohsuke Kawaguchi */ @Extension @@ -42,18 +43,18 @@ public String getShortDescription() { 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 @@ protected int run() throws Exception { 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 859d3e060c137..4b3dc23d98579 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 @@ /** * Creates a new job by reading stdin as a configuration XML file. - * + * * @author Kohsuke Kawaguchi */ @Extension @@ -41,15 +42,15 @@ public String getShortDescription() { 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 81b91af89986a..24aa9256e0067 100644 --- a/core/src/main/java/hudson/cli/CreateNodeCommand.java +++ b/core/src/main/java/hudson/cli/CreateNodeCommand.java @@ -37,7 +37,7 @@ @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 0506c3a002376..db61aa5912767 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 @@ @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 c0a86ad3cbc4f..6d62eb9db937f 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 @@ protected int act(List> builds) throws IOException { } } - 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 f3c4924968f1e..b203fc59c1c25 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 @@ 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 @@ protected int run() throws Exception { 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 1b77a8e20eabe..5989aa247b672 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 @@ 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 @@ protected int run() throws Exception { 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 436bf34f30d35..33a1743464b43 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 @@ 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 @@ protected int run() throws Exception { ViewOptionHandler voh = new ViewOptionHandler(null, null, null); - for(String view_s : hs) { + for (String view_s : hs) { View view; try { @@ -80,7 +81,7 @@ protected int run() throws Exception { 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 79d3a09f82501..53af28828ddb6 100644 --- a/core/src/main/java/hudson/cli/DisablePluginCommand.java +++ b/core/src/main/java/hudson/cli/DisablePluginCommand.java @@ -221,13 +221,13 @@ private int getResultCode(List results) { */ 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 4ae3b057532d2..eb080cf1eb987 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 f26ad48bdb3a4..d94044ef461c2 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 @@ */ @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 d508a59407593..62dd21826029e 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 @@ @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 1486d324ebc82..e94bb7947a812 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 @@ @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 bb894bf5389c3..0d7e45e6ca18c 100644 --- a/core/src/main/java/hudson/cli/GroovyCommand.java +++ b/core/src/main/java/hudson/cli/GroovyCommand.java @@ -21,12 +21,14 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + package hudson.cli; import groovy.lang.Binding; import groovy.lang.GroovyShell; import hudson.Extension; import java.io.IOException; +import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; @@ -47,13 +49,13 @@ public String getShortDescription() { 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 +64,13 @@ protected int run() throws Exception { 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(new OutputStreamWriter(stdout, getClientCharset()), 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 +78,7 @@ protected int run() throws Exception { * 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 d7eb47453be3a..f25a2544aa02c 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; @@ -29,6 +30,7 @@ import hudson.Extension; import java.io.BufferedInputStream; import java.io.InputStream; +import java.io.OutputStreamWriter; import java.io.PrintStream; import java.io.PrintWriter; import java.util.ArrayList; @@ -54,7 +56,7 @@ public String getShortDescription() { 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 +85,23 @@ protected Groovysh createShell(InputStream stdin, PrintStream stdout, Binding binding = new Binding(); // redirect "println" to the CLI - binding.setProperty("out", new PrintWriter(stdout,true)); + binding.setProperty("out", new PrintWriter(new OutputStreamWriter(stdout, getClientCharset()), 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 0743dc8e4d840..9e606102894b6 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 @@ @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 @@ protected int run() throws Exception { } 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 @@ private int showCommandDetails() throws Exception { } 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 d39c13f6a8c8b..cc9d3b59f91d4 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 @@ /** * Installs a plugin either from a file, an URL, or from update center. - * + * * @author Kohsuke Kawaguchi * @since 1.331 */ @@ -60,7 +61,7 @@ public String getShortDescription() { 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 String getShortDescription() { @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 @@ protected int run() throws Exception { } 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 @@ protected int run() throws Exception { 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 618e4d93346ce..59c5b8c78904e 100644 --- a/core/src/main/java/hudson/cli/ListChangesCommand.java +++ b/core/src/main/java/hudson/cli/ListChangesCommand.java @@ -5,6 +5,7 @@ import hudson.scm.ChangeLogSet; import hudson.util.QuotedStringTokenizer; import java.io.IOException; +import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.List; import jenkins.scm.RunWithSCM; @@ -37,7 +38,7 @@ enum Format { 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 @@ -46,7 +47,7 @@ protected int act(List> builds) throws IOException { // No other permission check needed. switch (format) { case XML: - PrintWriter w = new PrintWriter(stdout); + PrintWriter w = new PrintWriter(new OutputStreamWriter(stdout, getClientCharset())); w.println(""); for (Run build : builds) { if (build instanceof RunWithSCM) { diff --git a/core/src/main/java/hudson/cli/ListJobsCommand.java b/core/src/main/java/hudson/cli/ListJobsCommand.java index 67207ba3ebccd..1a366227ddbc6 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 @@ /** * Lists all jobs (in a specific view). - * + * * @author Michael Koch */ @Extension @@ -44,7 +45,7 @@ public String getShortDescription() { 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 1b3b657d8ac3d..9312bedb10ff2 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 String getShortDescription() { 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 eaaf2a50e92e3..e4a37fa74c6ed 100644 --- a/core/src/main/java/hudson/cli/OnlineNodeCommand.java +++ b/core/src/main/java/hudson/cli/OnlineNodeCommand.java @@ -68,7 +68,7 @@ protected int run() throws Exception { } } - 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 6df018abddbdd..c4cd7e02a97fc 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 b2bac818f409c..cea8823144bc9 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 @@ @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 @@ protected int run() throws Exception { final HashSet hs = new HashSet<>(jobs); - for (String job_s: hs) { + for (String job_s : hs) { AbstractItem job = null; try { @@ -73,7 +74,7 @@ protected int run() throws Exception { 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 @@ protected int run() throws Exception { 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 1da9f978d11c3..416796b82e464 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 @@ @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 @@ protected int run() throws Exception { 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 a7cee1eb7c1f8..6d6afe11caa11 100644 --- a/core/src/main/java/hudson/cli/RunRangeCommand.java +++ b/core/src/main/java/hudson/cli/RunRangeCommand.java @@ -12,18 +12,18 @@ * @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 6560479f22f42..458e22419369f 100644 --- a/core/src/main/java/hudson/cli/SetBuildDescriptionCommand.java +++ b/core/src/main/java/hudson/cli/SetBuildDescriptionCommand.java @@ -18,30 +18,30 @@ public String getShortDescription() { 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 e07a115f4f63a..08befa394684c 100644 --- a/core/src/main/java/hudson/cli/SetBuildDisplayNameCommand.java +++ b/core/src/main/java/hudson/cli/SetBuildDisplayNameCommand.java @@ -16,13 +16,13 @@ public String getShortDescription() { 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 77649867ec812..396d2d229cc2b 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 @@ */ @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 String getShortDescription() { @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 1d311908cb5f1..c9210f89cc689 100644 --- a/core/src/main/java/hudson/cli/UpdateNodeCommand.java +++ b/core/src/main/java/hudson/cli/UpdateNodeCommand.java @@ -37,7 +37,7 @@ @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 d952ae5d03441..36561f34f3f0c 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 @@ @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 17b9cc1d4ad8a..8b77c417d187c 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 319e4424a9e44..fee99ef6bf1a0 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 @@ @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 2e9713ad6f4cd..95a621b087b03 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 @@ @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 19db3787c3034..a4ecc4af79d06 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 String getShortDescription() { @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 13ddffbf5d2fb..7b9c35202bb90 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 13b2841db0948..8b2f2348c577a 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 ExtensionComponentSet refresh() throws ExtensionRefreshException { @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 Collection> find(Class type, Hudson jenkins) */ 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 @@ private List> discover(@NonNull final Jenkins jen 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 @@ protected int run() throws Exception { } })); } 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 71c3cf4e23888..80f1d19edff4e 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 08438aac9d870..91dfd11da7f09 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 @@ public AnnotatedElement asAnnotatedElement() { } }; 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 @@ public AnnotatedElement asAnnotatedElement() { 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 @@ public Class handler() { @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 405ce2fcc32d9..ab7402de65aec 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 bcbbb404a891e..5192931503413 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 3b2a985f4d3e5..45bd0f4e679b1 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 5776c221433e4..a37dbf1790f11 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 @@ @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 7a68946c16515..65656c15e33c8 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 View getView(final String name) { 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 d3f8aa3301bd3..e074044e806da 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 AnnotatedLargeText(ByteBuffer memory, Charset charset, boolean completed, } 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 void doProgressiveText(StaplerRequest req, StaplerResponse rsp) throws IO */ 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 @@ protected void setContentType(StaplerResponse rsp) { 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 long writeLogTo(long start, Writer w) throws IOException { if (isHtml()) return writeHtmlTo(start, w); else - return super.writeLogTo(start,w); + return super.writeLogTo(start, w); } /** @@ -176,16 +177,16 @@ public long writeRawLogTo(long start, OutputStream out) throws IOException { 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 long writeHtmlTo(long start, Writer w) throws IOException { /** * 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 3f9a17d143178..e13d65ea46273 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 String getDisplayName() { * Returns true if this descriptor has a JavaScript to be inserted on applicable console page. */ public boolean hasScript() { - return hasResource("/script.js") !=null; + return hasResource("/script.js") != null; } /** * Returns true if this descriptor has a stylesheet to be inserted on applicable console page. */ public boolean hasStylesheet() { - return hasResource("/style.css") !=null; + return hasResource("/style.css") != null; } private URL hasResource(String name) { - return clazz.getClassLoader().getResource(clazz.getName().replace('.','/').replace('$','/')+ name); + return clazz.getClassLoader().getResource(clazz.getName().replace('.', '/').replace('$', '/') + name); } - @WebMethod(name="script.js") + @WebMethod(name = "script.js") public void doScriptJs(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { rsp.serveFile(req, hasResource("/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, hasResource("/style.css"), TimeUnit.DAYS.toMillis(1)); } @@ -90,7 +91,7 @@ public void doStyleCss(StaplerRequest req, StaplerResponse rsp) throws IOExcepti /** * Returns all the registered {@link ConsoleAnnotationDescriptor} descriptors. */ - public static DescriptorExtensionList,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 6e70a743d8241..d2ac95da65bd7 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 ConsoleAnnotationOutputStream(Writer out, ConsoleAnnotator ann 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 @@ protected void eol(byte[] in, int sz) throws IOException { 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 @@ protected void eol(byte[] in, int sz) throws IOException { 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 ConsoleAnnotator annotate(T context, MarkupText text) { 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 @@ private LineBuffer(int initialSize) { 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 9761439320fee..8f289fd70cb91 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 ConsoleAnnotator annotate(T context, MarkupText text) { 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 static List> _for(T context) { 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 538b97359105f..b2f6948fd155f 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 @@ * 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 Class type() { * 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 3f54674477db4..3523fce8e9d25 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 62a9349c02c0c..8183934aedcec 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 removeNotes(Collection logLines) { public static String removeNotes(String line) { while (true) { int idx = line.indexOf(PREAMBLE_STR); - if (idx<0) return line; - int e = line.indexOf(POSTAMBLE_STR,idx); - if (e<0) return line; - line = line.substring(0,idx)+line.substring(e+POSTAMBLE_STR.length()); + if (idx < 0) return line; + int e = line.indexOf(POSTAMBLE_STR, idx); + if (e < 0) return line; + line = line.substring(0, idx) + line.substring(e + POSTAMBLE_STR.length()); } } } diff --git a/core/src/main/java/hudson/console/ExpandableDetailsNote.java b/core/src/main/java/hudson/console/ExpandableDetailsNote.java index f9a86a8d53de1..57ed88e06e22d 100644 --- a/core/src/main/java/hudson/console/ExpandableDetailsNote.java +++ b/core/src/main/java/hudson/console/ExpandableDetailsNote.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; @@ -50,7 +51,7 @@ public ExpandableDetailsNote(String caption, String html) { @Override public ConsoleAnnotator annotate(Object context, MarkupText text, int charPos) { text.addMarkup(charPos, - "

"+html+"
"); + "
" + html + "
"); return null; } @@ -59,7 +60,7 @@ public static String encodeTo(String buttonCaption, String html) { 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 38464ceecc9d1..f8e7e65208383 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 ConsoleAnnotator annotate(Object context, MarkupText text, int charPos) { 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 @@ static String encodeTo(String url, String text, BiFunction4096) + if (buf.size() > 4096) buf = new ByteArrayOutputStream2(); else buf.reset(); @@ -68,9 +69,9 @@ private void eol() throws IOException { @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 void forceEol() throws IOException { 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 86d8b044833f4..51f4135016344 100644 --- a/core/src/main/java/hudson/console/ModelHyperlinkNote.java +++ b/core/src/main/java/hudson/console/ModelHyperlinkNote.java @@ -31,23 +31,23 @@ protected String extraAttributes() { } 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 String getDisplayName() { 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 9b94490f3a312..f3b5bd8adf7e6 100644 --- a/core/src/main/java/hudson/console/PlainTextConsoleOutputStream.java +++ b/core/src/main/java/hudson/console/PlainTextConsoleOutputStream.java @@ -49,16 +49,16 @@ public PlainTextConsoleOutputStream(OutputStream out) { @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 @@ protected void eol(byte[] in, int sz) throws IOException { 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 f9cc1fc550505..7422faee4b2c1 100644 --- a/core/src/main/java/hudson/console/UrlAnnotator.java +++ b/core/src/main/java/hudson/console/UrlAnnotator.java @@ -23,10 +23,10 @@ private static class UrlConsoleAnnotator extends ConsoleAnnotator { 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 ConsoleAnnotator annotate(Object context, MarkupText text) { 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 4e3cf6b95febf..8b38c3e5a7766 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 long getRecurrencePeriod() { 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 @@ protected void doRun() { */ @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 9562952408d80..b3ba5d34e9fa1 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 HudsonHomeDiskUsageMonitor() { public boolean isActivated() { return activated; } - + @Override public String getDisplayName() { - return Messages.HudsonHomeDiskUsageMonitor_DisplayName(); + return Messages.HudsonHomeDiskUsageMonitor_DisplayName(); } /** @@ -67,7 +68,7 @@ public String getDisplayName() { */ @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 List getSolutions() { * 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 @@ protected Solution() { * 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 06ed43cb1a78e..797ee03d6b21e 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 @@ @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 static final class MemoryGroup { * 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 @@ private void update() { 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 @@ private void update() { */ 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 ac9ead6692926..43a1505aa606a 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 List getProblems() { 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 void verify() { 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 283fe73e48a6d..6bce4ae05f0b4 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 @@ 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 boolean isActivated() { 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 static void report(UnmarshallingContext context, String version) { private static class ReportException extends Exception { private String version; + private ReportException(String version) { this.version = version; } @@ -206,7 +208,7 @@ public static void report(Saveable obj, Collection errors) { 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 VersionRange(VersionRange previous, String version, String extra) { @Override public String toString() { - return min==null ? "" : min + (single ? "" : " - " + max.toString()); + return min == null ? "" : min + (single ? "" : " - " + max.toString()); } /** @@ -357,7 +359,7 @@ private void saveAndRemoveEntries(Predicate 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 @@ private static SaveableReference referTo(Saveable s) { 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 @@ private static final class SimpleSaveableReference implements SaveableReference 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 @@ private static final class RunSaveableReference implements SaveableReference { 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 10c72113ddbea..af7b2579db745 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 Permission getRequiredPermission() { @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 ee1e1566c3b70..6412ac63bcb2a 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 @@ * 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 boolean isActivated() { @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 4ee9fa26f418d..5e8c03c3e0554 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 @@ *

  • 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 List listPluginArchives(PluginManager pm) throws IOException { 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 @@ protected void getBundledPluginsFromProperty(final List r) { /** * 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 61b1c272be7c3..8248cabbde04f 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 8b11b5740c509..938cbd5d78e39 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 @@ 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 9925ca41900f1..b15869ba8831f 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 @@ public Collection discoverTasks(Reactor session) throws IOException { 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 @@ protected boolean filter(Method e) { 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 @@ protected void invoke(Method e) { try { Class[] pt = e.getParameterTypes(); Object[] args = new Object[pt.length]; - for (int i=0; i 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 @@ private Collection toMilestones(String[] tokens, Milestone m) { 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 85efd8d5eab71..5146e2dbb4eb7 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 69a36cc18e3ee..17f6a4702c940 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 @@ * @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 810bcdcce7d4c..81cc279eb909e 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 @@ * @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 eea0f4eea857a..e09237bef9185 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 @@ private static void handleException(Jenkins j, Throwable e, HttpServletRequest r 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 01855e1e225e0..f8fcc3abefbf8 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 04123c797ef0b..8e84179b5a0fb 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 static synchronized Lifecycle get() { } } } else { - if(Functions.isWindows()) { + if (Functions.isWindows()) { instance = new Lifecycle() { @Override public void verifyRestartable() throws RestartNotSupportedException { @@ -103,7 +104,7 @@ public void verifyRestartable() throws RestartNotSupportedException { "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 void verifyRestartable() throws RestartNotSupportedException { 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 void verifyRestartable() throws RestartNotSupportedException { */ 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 void rewriteHudsonWar(File by) throws IOException { 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 void rewriteHudsonWar(File by) throws IOException { 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 void restart() throws IOException, InterruptedException { */ 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 eecc28ea26de4..2dd3629365993 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 498db2c0e9845..ca8f50b9f589d 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 void restart() throws IOException, InterruptedException { // close all files upon exec, except stdin, stdout, and stderr int sz = LIBC.getdtablesize(); - for(int i=3; i' + getHudsonWar().getAbsolutePath() + '\n'); } } @@ -133,14 +137,14 @@ public void restart() throws IOException, InterruptedException { 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 9c54a8e0db3bd..db0fe5be09e50 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 LogRecorder(String name) { 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 static final class Target { 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 Target(String name, int level) { @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 int hashCode() { @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 Boolean matches(LogRecord r) { 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 Logger getLogger() { */ 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 int compare(Target left, Target right) { } } - 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 LogRecorderManager getParent() { * 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 synchronized void doConfigSubmit( StaplerRequest req, StaplerResponse rsp setLoggers(newTargets); save(); - if (oldFile!=null) oldFile.delete(); + if (oldFile != null) oldFile.delete(); rsp.sendRedirect2(redirect); } @@ -455,7 +459,7 @@ public synchronized void load() throws IOException { */ @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 synchronized void doDoDelete(StaplerResponse rsp) throws IOException, Ser /** * 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 List getLogRecords() { * @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 int compare(Computer c1, Computer c2) { 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 8a13849f3f891..0ea3a58267adf 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 void setRecorders(List recorders) { Map values = recorders.stream() .collect(toMap(LogRecorder::getName, Function.identity())); - ((CopyOnWriteMap) logRecorders).replaceBy(values); + ((CopyOnWriteMap) logRecorders).replaceBy(values); } @Override @@ -133,11 +134,11 @@ static File configDir() { 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 HttpResponse doNewLogRecorder(@QueryParameter String name) { 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 ContextMenu doChildrenContextMenu(StaplerRequest request, StaplerResponse 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 HttpResponse doConfigLogger(@QueryParameter String name, @QueryParameter /** * 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 void doRss( StaplerRequest req, StaplerResponse rsp ) throws IOException, // 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 Calendar getEntryTimestamp(LogRecord entry) { 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 21fd6bdfe2cc9..bc0cb1c349a47 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 WeakLogHandler(Handler target, Logger logger) { @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 @@ private Handler resolve() { 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 void setFormatter(Formatter newFormatter) throws SecurityException { 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 void setEncoding(String encoding) throws SecurityException, UnsupportedEn 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 void setFilter(Filter newFilter) throws SecurityException { 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 void setErrorManager(ErrorManager em) { 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 338eea2652fe7..de83afabce6ce 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 14a293790e3a7..e588e0cfcc8e7 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 @@ * 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 a6ea4845b0db6..4c02e525904d5 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 @@ * @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 final P getProject() { return getParent(); } - @Override public final LazyBuildMixIn.RunMixIn getRunMixIn() { + @Override public final LazyBuildMixIn.RunMixIn getRunMixIn() { return runMixIn; } @@ -208,7 +209,7 @@ public R getNextBuild() { * 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 R getNextBuild() { * 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 String getBuiltOnStr() { * * @since 1.429 */ - protected void setBuiltOnStr( String builtOn ) { + protected void setBuiltOnStr(String builtOn) { this.builtOn = builtOn; } @@ -248,7 +249,7 @@ protected void setBuiltOnStr( String builtOn ) { * @since 1.421 * @see AbstractProject#getRootProject() */ - public AbstractBuild getRootBuild() { + public AbstractBuild getRootBuild() { return this; } @@ -271,7 +272,7 @@ public Queue.Executable getParentExecutable() { * {@link #getDisplayName()}. */ public String getUpUrl() { - return Functions.getNearestAncestorUrl(Stapler.getCurrentRequest(),getParent())+'/'; + return Functions.getNearestAncestorUrl(Stapler.getCurrentRequest(), getParent()) + '/'; } /** @@ -288,9 +289,9 @@ public String getUpUrl() { * @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 @@ protected void setWorkspace(@NonNull FilePath ws) { */ 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 final FilePath getModuleRoot() { */ 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 boolean shouldCalculateCulprits() { 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 @@ protected Lease decideWorkspace(@NonNull Node n, WorkspaceList wsl) throws Inter 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 Result run(@NonNull BuildListener listener) throws Exception { 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 Result run(@NonNull BuildListener listener) throws Exception { // 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 @@ private Result tearDownBuildEnvironments(@NonNull BuildListener listener) throws } } 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 @@ protected Launcher createLauncher(@NonNull BuildListener listener) throws IOExce 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 @@ protected Launcher createLauncher(@NonNull BuildListener listener) throws IOExce } 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 void defaultCheckout() throws IOException, InterruptedException { 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 final void post(BuildListener listener) throws Exception { @Override public void cleanUp(BuildListener listener) throws Exception { - if (lease!=null) { + if (lease != null) { lease.release(); lease = null; } @@ -729,12 +730,12 @@ public void cleanUp(BuildListener listener) throws Exception { * 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 @@ protected final boolean performAllBuildSteps(BuildListener listener, Map buildSteps, boolean phase) throws InterruptedException, IOException { - performAllBuildSteps(listener,buildSteps,phase); + performAllBuildSteps(listener, buildSteps, phase); } /** @@ -757,9 +758,9 @@ protected final void performAllBuildStep(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 @@ private String getBuildStepName(BuildStep bs) { } } - 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 @@ protected final boolean preBuild(BuildListener listener,Iterable 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 @@ private ChangeLogSet calcChangeSet() { 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 EnvVars getEnvironment(TaskListener log) throws IOException, InterruptedE } } - 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 EnvVars getEnvironment(TaskListener log) throws IOException, InterruptedE */ 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 Calendar due() { } @SuppressWarnings("deprecation") - public List getPersistentActions(){ + public List getPersistentActions() { return super.getActions(); } @@ -1055,26 +1057,26 @@ public Set getSensitiveBuildVariables() { * @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 String getWhyKeepLog() { // 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 RangeSet getDownstreamRelationship(AbstractProject that) { 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 RangeSet getDownstreamRelationship(AbstractProject that) { 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 RangeSet getDownstreamRelationship(AbstractProject that) { * 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 Iterable> getDownstreamBuilds(final AbstractProject 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 AbstractBuild getUpstreamRelationshipBuild(AbstractProject that * 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 Map getDownstreamBuilds() { * @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 Map getUpstreamBuilds() { * 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 @@ private Map _getUpstreamBuilds(Collection 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 static final class DependencyChange { 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 DependencyChange(AbstractProject project, int fromId, int toId) { 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 List getBuilds() { @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 void doStop(StaplerRequest req, StaplerResponse rsp) throws IOException, @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 13fb0b563580f..cb2332cbb0a32 100644 --- a/core/src/main/java/hudson/model/AbstractCIBase.java +++ b/core/src/main/java/hudson/model/AbstractCIBase.java @@ -86,6 +86,7 @@ protected void resetLabel(Label l) { protected void setViewOwner(View v) { v.owner = this; } + protected void interruptReloadThread() { ViewJob.interruptReloadThread(); } @@ -101,7 +102,7 @@ protected void killComputer(Computer c) { * * @since 2.230 */ - public Set getDisabledAdministrativeMonitors(){ + public Set getDisabledAdministrativeMonitors() { synchronized (this.disabledAdministrativeMonitors) { return new HashSet<>(disabledAdministrativeMonitors); } @@ -131,15 +132,15 @@ public void setDisabledAdministrativeMonitors(Set disabledAdministrative public abstract Queue getQueue(); - protected abstract Map 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 @@ private void updateComputer(Node n, Map byNameMap, Set 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 @@ private Computer createNewComputerForNode(Node n, boolean automaticAgentLaunch) Queue.withLock(new Runnable() { @Override public void run() { - Map computers = getComputerMap(); + Map computers = getComputerMap(); for (Map.Entry e : computers.entrySet()) { if (e.getValue() == computer) { computers.remove(e.getKey()); @@ -207,7 +208,7 @@ public void run() { } /*package*/ @CheckForNull Computer getComputer(Node n) { - Map computers = getComputerMap(); + Map computers = getComputerMap(); return computers.get(n); } @@ -231,18 +232,18 @@ protected void updateNewComputer(final Node n, boolean automaticAgentLaunch) { * so that we won't upset {@link Executor}s running in it. */ protected void updateComputerList(final boolean automaticAgentLaunch) { - final Map 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 b1ac6dd8477f2..2e339875b940d 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 47a715a0aa122..458718e89aff7 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 @@ protected AbstractItem(ItemGroup parent, String name) { } @Override - @Exported(visibility=999) + @Exported(visibility = 999) public String getName() { return name; } @@ -162,7 +163,7 @@ public String getTaskNoun() { @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 File getRootDir() { /** * 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 HttpResponse doConfirmRename(@QueryParameter String newName) throws IOExc // 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 @@ private void checkIfNameIsUsed(@NonNull String newName) throws Failure { 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 @@ protected void renameTo(final String newName) throws IOException { boolean success = false; - try {// rename data files + try { // rename data files boolean interrupted = false; boolean renamed = false; @@ -477,16 +478,16 @@ public void movedTo(DirectlyModifiableTopLevelItemGroup destination, AbstractIte @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 final String getUrl() { 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 String getSearchUrl() { } @Override - @Exported(visibility=999,name="url") + @Exported(visibility = 999, name = "url") public final String getAbsoluteUrl() { return Item.super.getAbsoluteUrl(); } @@ -615,7 +616,7 @@ public ACL getACL() { */ @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 final XmlFile getConfigFile() { 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 @@ private Object readResolve() { * 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 synchronized void doSubmitDescription( StaplerRequest req, StaplerRespons * 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 void doDoDelete( StaplerRequest req, StaplerResponse rsp ) throws IOExcep } @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 void doConfigDotXml(StaplerRequest req, StaplerResponse rsp) } if (req.getMethod().equals("POST")) { // submission - updateByXml((Source)new StreamSource(req.getReader())); + updateByXml((Source) new StreamSource(req.getReader())); return; } @@ -839,6 +843,7 @@ public void doConfigDotXml(StaplerRequest req, StaplerResponse rsp) * 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 void writeConfigDotXml(OutputStream os) throws IOException { */ @Deprecated public void updateByXml(StreamSource source) throws IOException { - updateByXml((Source)source); + updateByXml((Source) source); } /** @@ -890,13 +895,13 @@ public void updateByXml(Source source) throws IOException { // 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 Object getTarget() { */ @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 0d1d6982db800..f6c7104f8e428 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 @@ /** * {@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 @@ protected final void sendError(String message, StaplerRequest req, StaplerRespon * 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 final SearchIndex getSearchIndex() { 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 cd669b8bb4942..9dfaf72e21d75 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 @@ * @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 @@ protected AbstractProject(ItemGroup parent, String name) { } } - 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 void onLoad(ItemGroup parent, String name) throws IOExcep 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 @@ protected void performDelete() throws IOException, InterruptedException { // 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 void setConcurrentBuild(boolean b) throws IOException { */ @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 Set

    * 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 @@ * @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 String getImage() { @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 String toString() { * 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 4b7dae08aac01..d4958d9ea297c 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 ParameterValue createValue(StaplerRequest req, JSONObject jo) { @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 c48cad87a69e0..d449623301cc9 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 @@ * {@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 Boolean getValue() { * 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 int hashCode() { @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 7daa7b4cf0b03..49d126b8e8481 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 @@ * * @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 @@ protected Build(P job, Calendar timestamp) { * 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 @@ deprecated class here. @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 @@ protected Result doRun(@NonNull BuildListener listener) throws Exception { 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 void cleanUp(@NonNull BuildListener listener) throws Exception { } 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 43563b6f4611f..48aea15b0897c 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 BuildAuthorizationToken(String token) { 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 String getToken() { 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 Object fromString(String str) { @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 4cdeffaaa5d79..da848424eeafa 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 10043b633b22c..0f8fc060f27e5 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 43a37a082a014..563f8a18823a5 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 BuildTimelineWidget(RunList builds) { 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 67cdc4d965e09..5054e10f48cd1 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 0d65214e43785..52fbeb97df782 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 @@ * @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 c79daa2ca2350..74f39b2928aa3 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 b58129f19ae1c..6990dd2b39e08 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 void onAddedTo(AbstractBuild build) { * 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 void print(TaskListener listener) { 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 static class UpstreamCause extends 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 @@ private UpstreamCause(String upstreamProject, int upstreamBuild, String upstream } @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 int hashCode() { /** * 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 int getUpstreamBuild() { /** * @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 String getUpstreamUrl() { public List getUpstreamCauses() { return upstreamCauses; } - + @Override public String getShortDescription() { return Messages.Cause_UpstreamCause_ShortDescription(upstreamProject, upstreamBuild); @@ -311,7 +313,7 @@ private void print(TaskListener listener, int depth) { 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 @@ private void print(TaskListener listener, int depth) { 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 static class DeeplyNestedUpstreamCause extends 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 static class DeeplyNestedUpstreamCause extends Cause { @Deprecated public static class UserCause extends Cause { private String authenticationName; + public UserCause() { this.authenticationName = Jenkins.getAuthentication2().getName(); } @@ -372,10 +378,10 @@ public UserCause() { * @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 String getShortDescription() { @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 UserIdCause(@CheckForNull String userId) { public String getUserId() { return userId; } - + @NonNull private String getUserIdOrUnknown() { return userId != null ? userId : User.getUnknown().getId(); @@ -485,17 +491,17 @@ public RemoteCause(String host, String note) { @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 fc225f3140af3..eca42ffb69994 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 @@ private void addCause(Cause c) { causeBag.put(c, cnt == null ? 1 : cnt + 1); } } + private void addCauses(Collection causes) { for (Cause cause : causes) { addCause(cause); @@ -90,10 +92,10 @@ public CauseAction(CauseAction ca) { * 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 String getUrlName() { * 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 String getShortDescription() { 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 String getShortDescription() { /** * 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 String getShortDescription() { @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 void foldIntoExisting(hudson.model.Queue.Item item, Task owner, List { 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 773421a17eb83..b7a7fdb9da905 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 @@ * 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 CheckPoint(String internalName) { @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 int hashCode() { @Override public String toString() { - return "Check point "+internalName; + return "Check point " + internalName; } /** @@ -140,7 +141,7 @@ public void report() { * 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 79570bd99511e..a2ac42447b027 100644 --- a/core/src/main/java/hudson/model/ChoiceParameterDefinition.java +++ b/core/src/main/java/hudson/model/ChoiceParameterDefinition.java @@ -202,7 +202,7 @@ public boolean equals(Object obj) { 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 8c1ce41e1aae0..b143a93877867 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 @@ protected Computer(Node node) { /** * Returns list of all boxes {@link ComputerPanelBox}s. */ - public List getComputerPanelBoxs(){ + public List getComputerPanelBoxs() { return ComputerPanelBox.all(this); } @@ -281,7 +282,7 @@ public List getActions() { 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 void addAction(@NonNull Action a) { * @see #relocateOldLogs() */ public @NonNull File getLogFile() { - return new File(getLogDir(),"slave.log"); + return new File(getLogDir(), "slave.log"); } /** @@ -310,7 +311,7 @@ public void addAction(@NonNull Action a) { * @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 String getOfflineCauseReason() { 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 String getOfflineCauseReason() { /** * 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 final long getConnectTime() { 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 Future disconnect(OfflineCause cause) { @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 BuildTimelineWidget getTimeline() { @Exported public boolean isOffline() { - return temporarilyOffline || getChannel()==null; + return temporarilyOffline || getChannel() == null; } public final boolean isOnline() { @@ -688,7 +689,7 @@ public boolean isTemporarilyOffline() { */ @Deprecated public void setTemporarilyOffline(boolean temporarilyOffline) { - setTemporarilyOffline(temporarilyOffline,null); + setTemporarilyOffline(temporarilyOffline, null); } /** @@ -788,7 +789,7 @@ public List getTiedJobs() { } 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 RunList getBuilds() { * 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 @@ protected void onRemoved(){ @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 @@ private void setNumExecutors(int n) { }); } - if (diff<0) { + if (diff < 0) { // if the number is increased, add new ones addNewExecutorIfNecessary(); } @@ -930,7 +931,7 @@ Extra executors will call removeExecutor(...) and that public int countIdle() { int n = 0; for (Executor e : executors) { - if(e.isIdle()) + if (e.isIdle()) n++; } return n; @@ -940,7 +941,7 @@ public int countIdle() { * 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 List getDisplayExecutors() { // 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 final boolean isIdle() { if (!oneOffExecutors.isEmpty()) return false; for (Executor e : executors) - if(!e.isIdle()) + if (!e.isIdle()) return false; return true; } @@ -1028,7 +1029,7 @@ public final boolean isIdle() { */ public final boolean isPartiallyIdle() { for (Executor e : executors) - if(e.isIdle()) + if (e.isIdle()) return true; return false; } @@ -1141,9 +1142,9 @@ public String getSearchUrl() { /** * 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 String getSearchUrl() { * 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 Map getSystemProperties() throws IOException, InterruptedE * Use {@link #getEnvironment()} instead. */ @Deprecated - public Map getEnvVars() throws IOException, InterruptedException { + public Map getEnvVars() throws IOException, InterruptedException { return getEnvironment(); } @@ -1193,19 +1194,19 @@ public EnvVars getEnvironment() throws IOException, InterruptedException { 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 EnvVars getEnvironment() throws IOException, InterruptedException { * @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 Map getThreadDump() throws IOException, InterruptedExcepti * Obtains the heap dump. */ public HeapDump getHeapDump() throws IOException { - return new HeapDump(this,getChannel()); + return new HeapDump(this, getChannel()); } /** @@ -1252,21 +1253,21 @@ public HeapDump getHeapDump() throws IOException { * 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 String getHostName() throws IOException, InterruptedException { 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 List call() throws IOException { 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 List call() throws IOException { } 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 String call() throws IOException { // // @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 void doRssFailed(StaplerRequest req, StaplerResponse rsp ) throws IOExcep * @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 void doRssLatest( StaplerRequest req, StaplerResponse rsp ) throws IOExce @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 Api getApi() { /** * 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 void doDumpExportTable( StaplerRequest req, StaplerResponse rsp ) throws } } - 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 @@ protected void _doScript(StaplerRequest req, StaplerResponse rsp, String view) t * 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 void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOE } 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 void updateByXml(final InputStream source) throws IOException, ServletExc 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 void waitUntilOffline() throws InterruptedException { /** * 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 boolean isAcceptingTasks() { */ @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 static void relocateOldLogs() { /*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 static void relocateOldLogs() { 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 int hashCode() { */ 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 long getWhen() { } } - 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 d5e7e45cba50e..f75fde52d79e4 100644 --- a/core/src/main/java/hudson/model/ComputerPanelBox.java +++ b/core/src/main/java/hudson/model/ComputerPanelBox.java @@ -15,19 +15,19 @@ * @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 Computer getComputer(){ */ 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 38894a2d5edc2..8aaf47a843eaf 100644 --- a/core/src/main/java/hudson/model/ComputerPinger.java +++ b/core/src/main/java/hudson/model/ComputerPinger.java @@ -48,7 +48,7 @@ public static boolean checkIsReachable(InetAddress ia, int timeout) throws IOExc 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 static boolean checkIsReachable(InetAddress ia, int timeout) throws IOExc 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 770e25814c3ef..ecef09a90fc30 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 void save() throws IOException { } }; - private static final DescribableList> monitors + private static final DescribableList> monitors = new DescribableList<>(MONITORS_OWNER); @Override @@ -104,7 +105,7 @@ public static List get_monitors() { 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 ContextMenu doChildrenContextMenu(StaplerRequest request, StaplerResponse /** * 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 int size() { */ @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 int getTotalExecutors() { */ @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 int getBusyExecutors() { * {@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 Computer getDynamic(String token, StaplerRequest req, StaplerResponse rsp 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 void do_launchAll(StaplerRequest req, StaplerResponse rsp) throws IOExcep * 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 void doUpdateNow( StaplerRequest req, StaplerResponse rsp ) throws IOExce * 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 synchronized void doCreateItem( StaplerRequest req, StaplerResponse rsp, 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 synchronized void doCreateItem( StaplerRequest req, StaplerResponse rsp, 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 synchronized void doCreateItem( StaplerRequest req, StaplerResponse rsp, * 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 synchronized void doDoCreateItem( StaplerRequest req, StaplerResponse rsp * @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 String checkName(String name) throws Failure { 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 FormValidation doCheckName(@QueryParameter String value) throws IOExcepti * 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 synchronized HttpResponse doConfigSubmit( StaplerRequest req) throws IOEx * {@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 AutoCompletionCandidates doAutoCompleteCopyNewItemFrom(@QueryParameter fi */ 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 static List getComputerNames() { 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 static List getComputerNames() { // 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 @@ private static NodeMonitor createDefaultInstance(Descriptor d, bool 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 79c8ed7fbf9b8..3788e2aefddca 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 @@ protected Collection forward(AbstractProject node) { 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 T getComputationalData(Class key) { * 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 List getDownstream(AbstractProject p) { * 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 @@ private List get(Map> ma * @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 @@ private List get(Map> map, Ab */ @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 void addDependency(Dependency dep) { @Deprecated public void addDependency(AbstractProject upstream, Collection downstream) { for (AbstractProject p : downstream) - addDependency(upstream,p); + addDependency(upstream, p); } /** @@ -249,7 +250,7 @@ public void addDependency(AbstractProject upstream, Collection upstream, AbstractProject downstream) { for (AbstractProject p : upstream) - addDependency(p,downstream); + addDependency(p, downstream); } /** @@ -259,7 +260,7 @@ public void addDependencyDeclarers(AbstractProject upstream, Collection possi 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 boolean hasIndirectDependencies(AbstractProject src, AbstractProject dst) 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 boolean hasIndirectDependencies(AbstractProject src, AbstractProject dst) * 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 @@ private Set getTransitive(Map> map, AbstractProjec 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 int compare(DependencyGroup lhs, DependencyGroup rhs) { */ @Override public int compare(AbstractProject o1, AbstractProject o2) { - return topologicalOrder.compare(o1,o2); + return topologicalOrder.compare(o1, o2); } /** @@ -367,7 +368,7 @@ public int compare(AbstractProject o1, AbstractProject o2) { * * @since 1.521 */ - public List> getTopologicallySorted() { + public List> getTopologicallySorted() { return topologicallySorted; } @@ -413,7 +414,7 @@ public boolean shouldTriggerBuild(AbstractBuild build, TaskListener listener, * Does this method point to itself? */ public boolean pointsItself() { - return upstream==downstream; + return upstream == downstream; } @Override @@ -446,7 +447,7 @@ private static class DependencyGroup { 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 e1331510d7e17..d770540072335 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 b1066e7428e3e..3c9c466acdd23 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 static final class PropertyType { } 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 Descriptor getItemTypeDescriptorOrDie() { 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 List getApplicableItemDescriptors() { * * @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 @@ private String resolve() { * (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 @@ protected Descriptor(Class clazz) { * @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 @@ protected Descriptor() { 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 String getId() { 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 Class getT() { * 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 String getDescriptorUrl() { * @since 1.406 */ public final String getDescriptorFullUrl() { - return getCurrentDescriptorByNameUrl()+'/'+getDescriptorUrl(); + return getCurrentDescriptorByNameUrl() + '/' + getDescriptorUrl(); } /** @@ -382,7 +383,7 @@ public static String getCurrentDescriptorByNameUrl() { // 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 String getCheckUrl(String fieldName) { */ 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 CheckMethod getCheckMethod(String fieldName) { * 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 void calcFillSettings(String field, Map attributes) { 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 @@ private List buildFillDependencies(Method method, List depends) /** * 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 void calcAutoCompleteSettings(String field, Map attributes */ 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 void calcAutoCompleteSettings(String field, Map attributes * 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 PropertyType getPropertyType(String field) { * 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 PropertyType getGlobalPropertyType(String field) { 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 @@ private Map buildPropertyTypes(Class clazz) { * 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 final String getJsonSafeClassName() { */ @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 T newInstance(@Nullable StaplerRequest req, @NonNull JSONObject formData) 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 T newInstance(@Nullable StaplerRequest req, @NonNull JSONObject formData) } } } 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 T newInstance(@Nullable StaplerRequest req, @NonNull JSONObject formData) 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 Object onConvert(Type targetType, Class targetTypeErasure, Object jsonSou * 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 String getHelpFile() { * 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 String getHelpFile(Klass clazz, String fieldName) { * @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 final boolean isSubTypeOf(Class type) { * 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 boolean configure( StaplerRequest req ) throws FormException { * @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 @@ Permission getRequiredGlobalConfigPagePermission() { } 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 @@ protected final String getViewPage(Class clazz, String pageName) { // 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 @@ protected List getPossibleViewNames(String baseName) { 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 @@ protected List getPossibleViewNames(String baseName) { */ @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 synchronized void save() { */ 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 @@ protected PluginWrapper getPlugin() { */ 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 void doHelp(StaplerRequest req, StaplerResponse rsp) throws IOException, 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 @@ private URL getStaticHelpUrl(Klass c, String suffix) { // 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 @@ Map,T> toMap(Iterable describables) { 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 @@ List newInstancesFromHeteroList(StaplerRequest req, Object formData, 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 @@ List newInstancesFromHeteroList(StaplerRequest req, Object formData, */ 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 @@ List newInstancesFromHeteroList(StaplerRequest req, Object formData, */ 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 @@ List newInstancesFromHeteroList(StaplerRequest req, Object formData, */ 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 @@ List newInstancesFromHeteroList(StaplerRequest req, Object formData, */ @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 String getFormField() { @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 e36f61df4d003..6dab3573d95a6 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 ffb0b1b2a7b2e..61362272c248c 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 cc4c13f14dff2..c6c595becdc5e 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 @@ * *

    * 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 DirectoryBrowserSupport(ModelObject owner, String title) { * @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 void generateResponse(StaplerRequest req, StaplerResponse rsp, Object nod } 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 void serveFile(StaplerRequest req, StaplerResponse rsp, FilePath root, St 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 @@ private void serveFile(StaplerRequest req, StaplerResponse rsp, VirtualFile root // 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 @@ private void serveFile(StaplerRequest req, StaplerResponse rsp, VirtualFile root 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 @@ private void serveFile(StaplerRequest req, StaplerResponse rsp, VirtualFile root 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 @@ private void serveFile(StaplerRequest req, StaplerResponse rsp, VirtualFile root 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 @@ private void serveFile(StaplerRequest req, StaplerResponse rsp, VirtualFile root } //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 @@ private void serveFile(StaplerRequest req, StaplerResponse rsp, VirtualFile root 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 @@ private static final class IsAbsolute extends MasterToSlaveCallable> 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 @@ private List> keepReadabilityOnlyOnDescendants(VirtualFile root, bool } 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 @@ private List> keepReadabilityOnlyOnDescendants(VirtualFile root, bool } 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 @@ private boolean isDescendant(VirtualFile root, String relativePath){ private String getPath(StaplerRequest req) { String path = req.getRestOfPath(); - if(path.length()==0) + if (path.length() == 0) path = "/"; return path; } @@ -495,19 +496,19 @@ private List buildParentPath(String pathList, int restSize) { 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 static final class Path implements Serializable { * 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 Path(String href, String title, boolean isFolder, long size, boolean isRe public boolean isFolder() { return isFolder; } - + public boolean isReadable() { return isReadable; } @@ -658,16 +659,16 @@ public String getTitle() { 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 Calendar getLastModifiedAsCalendar() { 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 @@ private static final class FileComparator implements Comparator { @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 @@ private int dirRank(VirtualFile f) { } } - 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 @@ private static final class BuildChildPaths extends MasterToSlaveCallable> 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 @@ private static List> buildChildPaths(VirtualFile cur, Locale locale) 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 c8c0cc6d72322..2aee0c035c17b 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 void onCopied(Item src, Item item) { @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 void onRenamed(Item item, String oldName, String newName) { 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 92713f0cf9b15..000ef9f48d2f3 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 String generateFragment() { */ 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 static class Downloadable implements ExtensionPoint { 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 String getId() { */ @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 long getInterval() { * 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 long getDue() { */ 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 @@ private FormValidation load(String json, long dataTimestamp) throws IOException 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 FormValidation updateNow() throws IOException { 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 JSONObject reduce(List jsonList) { * @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 static boolean hasDuplicates (List genericList, String comparator) 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 static Downloadable get(@NonNull Class clazz) { @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 static Downloadable get(String id) { 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 889116cdc9da2..987d74e7d6d22 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 @@ * @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 1df68de4c37f4..0de322014c235 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 926ec551060fb..0fa5a96c70af0 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 1c1b07a205731..0e11a1c51ccc8 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 32663e721491c..53e127e671e53 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 @@ /** * Represents any concept that can be adapted for a certain environment. - * + * * Mainly for documentation purposes. * * @since 1.286 @@ -37,8 +38,8 @@ * @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 f719b65c52ebc..e7b14b72aebfa 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 @@ void interruptForShutdown() { * * @since 1.417 */ + public void interrupt(Result result) { interrupt(result, false); } @@ -269,7 +271,7 @@ public Result abortResult() { * * @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 SubTask call() throws Exception { 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 SubTask call() throws Exception { 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 SubTask call() throws Exception { 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 SubTask call() throws Exception { } } } 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 void completedAsynchronous(@CheckForNull Throwable error) { /** * 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 FilePath getCurrentWorkspace() { */ @Override public String getDisplayName() { - return "Executor #"+getNumber(); + return "Executor #" + getNumber(); } /** @@ -846,8 +848,8 @@ public void start() { */ @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 HttpResponse doStopBuild(@CheckForNull @QueryParameter(fixEmpty = true) S 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 boolean hasStopPermission() { 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 @@ protected Object call(Object o, Method m, Object[] args) throws Throwable { 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 eb4a8cdb26818..6500e6acc2ecc 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 1931d505eb262..71318dd0464b5 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 @@ *

    * 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 void generateResponse(StaplerRequest req, StaplerResponse rsp, Object nod @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 bc4690928597e..dcaf022b20fa1 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 FileParameterValue createValue(StaplerRequest req, JSONObject jo) { 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 String getHelpFile() { } } - @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 ParameterValue createValue(StaplerRequest req) { 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 @@ private String getFileName(String possiblyPathName) { @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 cc9f39faefee0..974f76b2f4577 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 Object getValue() { * 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 FileItem getFile() { } @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 Environment setUp(AbstractBuild build, Launcher launcher, BuildListener l 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 String toString() { * 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 @@ private File getLocationUnderBuild(AbstractBuild build) { 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 fbdb97f7722ac..d4b57badaefcc 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 BuildPtr(String name, int number) { } 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 BuildPtr(Run run) { 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 @@ private boolean hasPermissionToDiscoverBuild() { 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 int getNumber() { */ 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 boolean is(Job job) { * *

    * 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 boolean belongsTo(Job job) { /** * 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 Iterable listNumbers() { 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 Iterable listNumbersReverse() { 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 synchronized List getRanges() { * 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 synchronized int min() { * 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 synchronized int max() { * 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 static RangeSet fromString(String list, boolean skipError) { 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 static RangeSet fromString(String list, boolean skipError) { 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 static RangeSet fromString(String list, boolean skipError) { // 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 static RangeSet fromString(String list, boolean skipError) { // 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 void onLocationChanged(final Item item, final String oldName, final Strin 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 @@ private void locationChanged(Item item, String oldName, String newName) { } private static final DateConverter DATE_CONVERTER = new DateConverter(); - + /** * Time when the fingerprint has been captured. */ @@ -861,7 +863,7 @@ private void locationChanged(Item item, String oldName, String newName) { /** * 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 @@ private void locationChanged(Item item, String oldName, String newName) { 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 Fingerprint(@CheckForNull Run build, @NonNull String fileName, @NonNull b /** * Gets the MD5 hash string. */ - @Exported(name="hash") + @Exported(name = "hash") public @NonNull String getHashString() { return Util.toHexString(md5sum); } @@ -938,7 +940,7 @@ public Fingerprint(@CheckForNull Run build, @NonNull String fileName, @NonNull b * 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 Fingerprint(@CheckForNull Run build, @NonNull String fileName, @NonNull b */ 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 synchronized List getJobs() { 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 RangeItem(String name, RangeSet ranges) { } // 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 @@ protected Object readResolve() { } 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 @@ void addWithoutSaving(@NonNull String jobFullName, int n) { * 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 synchronized boolean isAlive() { * * @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 synchronized boolean trim() throws IOException { // 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 synchronized boolean trim() throws IOException { * @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 boolean contains(Object o) { @Override public int size() { - return facets.size()+transientFacets.size(); + return facets.size() + transientFacets.size(); } }; } @@ -1202,7 +1204,7 @@ public int size() { /** * 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 int compare(FingerprintFacet o1, FingerprintFacet o2) { */ @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 synchronized void save() throws IOException { 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 synchronized void rename(String oldName, String newName) throws IOExcepti touched = true; } } - + if (usages != null) { RangeSet r = usages.get(oldName); if (r != null) { @@ -1317,12 +1319,12 @@ public synchronized void rename(String oldName, String newName) throws IOExcepti touched = true; } } - + if (touched) { save(); } } - + public Api getApi() { return new Api(this); } @@ -1337,8 +1339,8 @@ public Api getApi() { * 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 Api getApi() { 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 @@ private static void initFacets(@CheckForNull Fingerprint fingerprint) { + 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 @@ private static boolean canDiscoverItem(@NonNull final String fullName) { 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 static XStream2 getXStream() { } 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 @@ protected Object createCollection(Class type) { 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 f7720bb78fc41..6ac6a361e8f72 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 7679b384e39a0..b41edbb9f703d 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 @@ * @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 boolean isReady() { * @throws IOException Loading error */ public @NonNull Fingerprint getOrCreate(@CheckForNull AbstractBuild build, @NonNull String fileName, @NonNull byte[] md5sum) throws IOException { - return getOrCreate(build,fileName, Util.toHexString(md5sum)); + return getOrCreate(build, fileName, Util.toHexString(md5sum)); } public @NonNull Fingerprint getOrCreate(@CheckForNull AbstractBuild build, @NonNull String fileName, @NonNull String md5sum) throws IOException { - return super.getOrCreate(md5sum, new FingerprintParams(build,fileName)); + return super.getOrCreate(md5sum, new FingerprintParams(build, fileName)); } public @NonNull Fingerprint getOrCreate(@CheckForNull Run build, @NonNull String fileName, @NonNull String md5sum) throws IOException { - return super.getOrCreate(md5sum, new FingerprintParams(build,fileName)); + return super.getOrCreate(md5sum, new FingerprintParams(build, fileName)); } @Override protected Fingerprint get(String md5sum, boolean createIfNotExist, FingerprintParams createParams) throws IOException { // sanity check - if(md5sum.length()!=32) + if (md5sum.length() != 32) return null; // illegal input md5sum = md5sum.toLowerCase(Locale.ENGLISH); - return super.get(md5sum,createIfNotExist,createParams); + return super.get(md5sum, createIfNotExist, createParams); } @Override @@ -102,7 +103,7 @@ static class FingerprintParams { this.build = build; this.fileName = fileName; - assert fileName!=null; + assert fileName != null; } } } diff --git a/core/src/main/java/hudson/model/FreeStyleBuild.java b/core/src/main/java/hudson/model/FreeStyleBuild.java index f64e152102b15..d2871dc8da797 100644 --- a/core/src/main/java/hudson/model/FreeStyleBuild.java +++ b/core/src/main/java/hudson/model/FreeStyleBuild.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; @@ -29,7 +30,7 @@ /** * @author Kohsuke Kawaguchi */ -public class FreeStyleBuild extends Build { +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 73234b815683c..814f2cf7e8a74 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 @@ /** * 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 @@ protected Class getBuildClass() { @Override public DescriptorImpl getDescriptor() { - return (DescriptorImpl)Jenkins.get().getDescriptorOrDie(getClass()); + return (DescriptorImpl) Jenkins.get().getDescriptorOrDie(getClass()); } /** @@ -74,7 +75,7 @@ public DescriptorImpl getDescriptor() { @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 String getDisplayName() { @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 6251bddec8423..64e2428f6a71d 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 de3cd5e028eb0..e5bb11319aa81 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 static HealthReport max(HealthReport a, HealthReport b) { */ 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 c5fa8f0e88948..b26277cc5143f 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 f8b80787dfad8..784fa47da20e9 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 CopyOnWriteList getComputerListeners() { 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 Slave getSlave(String name) { */ @Deprecated public List getSlaves() { - return (List)getNodes(); + return (List) getNodes(); } /** @@ -158,8 +159,8 @@ public TopLevelItem getJob(String name) { @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 synchronized void doQuietDown(StaplerResponse rsp) throws IOException, Se * 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 void doFieldCheck(StaplerRequest req, StaplerResponse rsp) throws IOExcep 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 void doFieldCheck(StaplerRequest req, StaplerResponse rsp) throws IOExcep * 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 FormValidation doFieldCheck(@QueryParameter(fixEmpty=true) String value, */ @Deprecated public static boolean isWindows() { - return File.pathSeparatorChar==';'; + return File.pathSeparatorChar == ';'; } /** @@ -278,7 +279,7 @@ public static boolean adminCheck() throws IOException { * 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 static boolean isAdmin(StaplerRequest req) { } 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 d921cd12f8d9e..2f5ce02426323 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 d9ba493dc02bf..a57011579b154 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 @@ default String getRelativeNameFrom(@NonNull Item item) { @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 @@ default void onCreatedFromScratch() { */ 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 61989b1711c7b..6404e82626e1e 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 54798d497868d..748a13cc6ec4e 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 @@ protected ItemGroupMixIn(ItemGroup parent, AccessControlled acl) { * @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 static Map loadChildren(ItemGroup parent, File mo } 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 static Map loadChildren(ItemGroup parent, File mo /** * {@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 synchronized TopLevelItem createTopLevelItem( StaplerRequest req, Stapler || 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 synchronized TopLevelItem createTopLevelItem( StaplerRequest req, Stapler * 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 synchronized T copy(T src, String name) throws I 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 synchronized T copy(T src, String name) throws I // 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 synchronized T copy(T src, String name) throws I result.onCopiedFrom(src); add(result); - ItemListener.fireOnCopied(src,result); + ItemListener.fireOnCopied(src, result); Jenkins.get().rebuildDependencyGraphAsync(); return result; @@ -277,7 +278,7 @@ public synchronized TopLevelItem createProjectFromXML(String name, InputStream x 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 synchronized TopLevelItem createProjectFromXML(String name, InputStream x } } - 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 e33a6849b0eda..98e26c8023aa4 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 void onItemGroup(ItemGroup group) { * 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 ddb33a4e85050..1d0c607ad979b 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 @@ /** * Convenience methods related to {@link Item}. - * + * * @author Kohsuke Kawaguchi */ public class Items { @@ -126,7 +127,7 @@ String name(Item i) { * @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 static boolean currentlyUpdatingByXml() { /** * 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 static List all2(Authentication a, ItemGroup c) { // 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 static TopLevelItemDescriptor getDescriptor(String fqcn) { 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 static String toNameList(Collection 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 static List fromNameList(String list, Class type) */ 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 static String getCanonicalName(ItemGroup context, String path) { 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 @@ static String getRelativeNameFrom(String itemFullName, String groupFullName) { * 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 static Item load(ItemGroup parent, File dir) throws IOException { * 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 static XmlFile getConfigFile(File dir) { 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 static XmlFile getConfigFile(Item item) { * @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 static List getAllItems(final ItemGroup root, Class 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 static Iterable allItems(org.acegisecurity.Authentica */ 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 @@ static void verifyItemDoesNotAlreadyExist(@NonNull ItemGroup parent, @NonNull /** * 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 1eeafbbc66829..0c9bcbda493d6 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 String getJavaHome() { * 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 boolean getExists() { * @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 void buildEnvVars(Map env) { */ @Override public void buildEnvVars(EnvVars env) { - buildEnvVars((Map)env); + buildEnvVars((Map) env); } @Override @@ -163,7 +165,7 @@ public static boolean isDefaultJDKValid(Node n) { 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 List getDefaultInstallers() { * 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 List getDefaultInstallers() { 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 2658ce50c20ff..59956a91b9fa1 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 Queue.Item getQueueItem() { */ public boolean isBuilding() { RunT b = getLastBuild(); - return b!=null && b.isBuilding(); + return b != null && b.isBuilding(); } /** @@ -310,7 +311,7 @@ public boolean isBuilding() { */ public boolean isLogUpdated() { RunT b = getLastBuild(); - return b!=null && b.isLogUpdated(); + return b != null && b.isLogUpdated(); } @Override @@ -358,9 +359,9 @@ public int getNextBuildNumber() { */ public EnvVars getCharacteristicEnvVars() { EnvVars env = new EnvVars(); - env.put("JENKINS_SERVER_COOKIE",SERVER_COOKIE.get()); - env.put("HUDSON_SERVER_COOKIE",SERVER_COOKIE.get()); // Legacy compatibility - env.put("JOB_NAME",getFullName()); + env.put("JENKINS_SERVER_COOKIE", SERVER_COOKIE.get()); + env.put("HUDSON_SERVER_COOKIE", SERVER_COOKIE.get()); // Legacy compatibility + env.put("JOB_NAME", getFullName()); env.put("JOB_BASE_NAME", getName()); return env; } @@ -393,11 +394,11 @@ public EnvVars getCharacteristicEnvVars() { // servlet container may have set CLASSPATH in its launch script, // so don't let that inherit to the new child process. // see http://www.nabble.com/Run-Job-with-JDK-1.4.2-tf4468601.html - env.put("CLASSPATH",""); + env.put("CLASSPATH", ""); // apply them in a reverse order so that higher ordinal ones can modify values added by lower ordinal ones for (EnvironmentContributor ec : EnvironmentContributor.all().reverseView()) - ec.buildEnvironmentFor(this,env,listener); + ec.buildEnvironmentFor(this, env, listener); return env; @@ -415,7 +416,7 @@ public EnvVars getCharacteristicEnvVars() { */ public synchronized void updateNextBuildNumber(int next) throws IOException { RunT lb = getLastBuild(); - if (lb!=null ? next>lb.getNumber() : next>0) { + if (lb != null ? next > lb.getNumber() : next > 0) { this.nextBuildNumber = next; saveNextBuildNumber(); } @@ -504,7 +505,7 @@ public void suggest(String token, List result) { @Override public Collection getAllJobs() { - return Collections. singleton(this); + return Collections.singleton(this); } /** @@ -513,7 +514,7 @@ public Collection getAllJobs() { * @since 1.188 */ public void addProperty(JobProperty jobProp) throws IOException { - ((JobProperty)jobProp).setOwner(this); + ((JobProperty) jobProp).setOwner(this); properties.add(jobProp); save(); } @@ -561,7 +562,7 @@ public Map> getProperties() { * List of all {@link JobProperty} exposed primarily for the remoting API. * @since 1.282 */ - @Exported(name="property",inline=true) + @Exported(name = "property", inline = true) public List> getAllProperties() { return properties.getView(); } @@ -690,7 +691,7 @@ public static class SubItemBuildsLocationImpl extends ItemListener { public void onLocationChanged(Item item, String oldFullName, String newFullName) { final Jenkins jenkins = Jenkins.get(); if (!jenkins.isDefaultBuildDir() && item instanceof Job) { - File newBuildDir = ((Job)item).getBuildDir(); + File newBuildDir = ((Job) item).getBuildDir(); try { if (!Util.isDescendant(item.getRootDir(), newBuildDir)) { //OK builds are stored somewhere outside of the item's root, so none of the other move operations has probably moved it. @@ -728,7 +729,7 @@ public void onLocationChanged(Item item, String oldFullName, String newFullName) * * @return never null. The first entry is the latest build. */ - @Exported(name="allBuilds",visibility=-2) + @Exported(name = "allBuilds", visibility = -2) @WithBridgeMethods(List.class) public RunList getBuilds() { return RunList.fromRuns(_getRuns().values()); @@ -739,7 +740,7 @@ public RunList getBuilds() { * * @since 1.485 */ - @Exported(name="builds") + @Exported(name = "builds") public RunList getNewBuilds() { return getBuilds().limit(100); } @@ -751,7 +752,7 @@ public synchronized List getBuilds(RangeSet rs) { List builds = new ArrayList<>(); for (Range r : rs.getRanges()) { - for (RunT b = getNearestBuild(r.start); b!=null && b.getNumber() 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 Object getDynamic(String token, StaplerRequest req, // is this a permalink? for (Permalink p : getPermalinks()) { - if(p.getId().equals(token)) + if (p.getId().equals(token)) return p.resolve(this); } @@ -942,7 +943,7 @@ public RunT getFirstBuild() { @Exported @QuickSilver public RunT getLastSuccessfulBuild() { - return (RunT)Permalink.LAST_SUCCESSFUL_BUILD.resolve(this); + return (RunT) Permalink.LAST_SUCCESSFUL_BUILD.resolve(this); } /** @@ -952,7 +953,7 @@ public RunT getLastSuccessfulBuild() { @Exported @QuickSilver public RunT getLastUnsuccessfulBuild() { - return (RunT)Permalink.LAST_UNSUCCESSFUL_BUILD.resolve(this); + return (RunT) Permalink.LAST_UNSUCCESSFUL_BUILD.resolve(this); } /** @@ -962,7 +963,7 @@ public RunT getLastUnsuccessfulBuild() { @Exported @QuickSilver public RunT getLastUnstableBuild() { - return (RunT)Permalink.LAST_UNSTABLE_BUILD.resolve(this); + return (RunT) Permalink.LAST_UNSTABLE_BUILD.resolve(this); } /** @@ -972,7 +973,7 @@ public RunT getLastUnstableBuild() { @Exported @QuickSilver public RunT getLastStableBuild() { - return (RunT)Permalink.LAST_STABLE_BUILD.resolve(this); + return (RunT) Permalink.LAST_STABLE_BUILD.resolve(this); } /** @@ -981,7 +982,7 @@ public RunT getLastStableBuild() { @Exported @QuickSilver public RunT getLastFailedBuild() { - return (RunT)Permalink.LAST_FAILED_BUILD.resolve(this); + return (RunT) Permalink.LAST_FAILED_BUILD.resolve(this); } /** @@ -990,7 +991,7 @@ public RunT getLastFailedBuild() { @Exported @QuickSilver public RunT getLastCompletedBuild() { - return (RunT)Permalink.LAST_COMPLETED_BUILD.resolve(this); + return (RunT) Permalink.LAST_COMPLETED_BUILD.resolve(this); } /** @@ -1050,15 +1051,15 @@ protected List getEstimatedDurationCandidates() { public long getEstimatedDuration() { List 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 @@ class FeedItem { for (RunT r = getLastBuild(); r != null; r = r.getPreviousBuild()) { int idx = 0; if (r instanceof RunWithSCM) { - for (ChangeLogSet 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 synchronized void doConfigSubmit(StaplerRequest req, DescribableList, 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 synchronized void doConfigSubmit(StaplerRequest req, ItemListener.fireOnUpdated(this); final ProjectNamingStrategy namingStrategy = Jenkins.get().getProjectNamingStrategy(); - if(namingStrategy.isForceExistingJobs()){ + if (namingStrategy.isForceExistingJobs()) { namingStrategy.checkName(name); } FormApply.success(".").generateResponse(req, rsp, null); @@ -1425,7 +1426,7 @@ public int compareTo(ChartLabel that) { public boolean equals(Object o) { // JENKINS-2682 workaround for Eclipse compilation bug // on (c instanceof ChartLabel) - if (o == null || !ChartLabel.class.isAssignableFrom( o.getClass() )) { + if (o == null || !ChartLabel.class.isAssignableFrom(o.getClass())) { return false; } ChartLabel that = (ChartLabel) o; @@ -1550,7 +1551,7 @@ protected JFreeChart createGraph() { private Calendar getLastBuildTime() { final RunT lastBuild = getLastBuild(); - if (lastBuild ==null) { + if (lastBuild == null) { final GregorianCalendar neverBuiltCalendar = new GregorianCalendar(); neverBuiltCalendar.setTimeInMillis(0); return neverBuiltCalendar; @@ -1602,5 +1603,5 @@ public BuildTimelineWidget getTimeline() { return new BuildTimelineWidget(getBuilds()); } - private static final HexStringConfidentialKey SERVER_COOKIE = new HexStringConfidentialKey(Job.class,"serverCookie",16); + private static final HexStringConfidentialKey SERVER_COOKIE = new HexStringConfidentialKey(Job.class, "serverCookie", 16); } diff --git a/core/src/main/java/hudson/model/JobProperty.java b/core/src/main/java/hudson/model/JobProperty.java index b4d5772cc3235..fe02891987e9f 100644 --- a/core/src/main/java/hudson/model/JobProperty.java +++ b/core/src/main/java/hudson/model/JobProperty.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 edu.umd.cs.findbugs.annotations.NonNull; @@ -67,14 +68,14 @@ * @param * 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 Action getJobAction(J job) { 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 Collection getJobActions(J job) { // @Override - public boolean prebuild(AbstractBuild build, BuildListener listener) { + public boolean prebuild(AbstractBuild build, BuildListener listener) { return true; } @@ -152,7 +153,7 @@ public boolean prebuild(AbstractBuild build, BuildListener listener) { * 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 BuildStepMonitor getRequiredMonitorService() { } @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 Collection getJobOverrides() { @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 36f781b67ba18..1f1c3aa7e6f07 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 @@ /** * {@link Descriptor} for {@link JobProperty}. - * + * * @author Kohsuke Kawaguchi * @since 1.72 */ @@ -62,8 +63,8 @@ protected JobPropertyDescriptor() { @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 JobProperty newInstance(StaplerRequest req, JSONObject formData) throw /** * 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 boolean isApplicable(Class jobType) { 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 boolean isApplicable(Class jobType) { 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 63117247d2260..a9452f68d8a92 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 @@ /** * 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 0e38b876f8a70..11418515075e7 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 Label getAssignedLabel(SubTask task) { 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 boolean shouldSchedule(List actions) { } 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 boolean shouldSchedule(List actions) { */ @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 ParametersAction createUpdated(Collection overr 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 7470330c7a018..e09131c268a31 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 @@ *

    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 @@ private Object readResolve() { } @Deprecated - public AbstractProject getOwner() { + public AbstractProject getOwner() { return (AbstractProject) owner; } @@ -137,8 +138,8 @@ public void _doBuild(StaplerRequest req, StaplerResponse rsp) throws IOException * 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 void _doBuild(StaplerRequest req, StaplerResponse rsp, @QueryParameter Ti 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 void _doBuild(StaplerRequest req, StaplerResponse rsp, @QueryParameter Ti 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 void _doBuild(StaplerRequest req, StaplerResponse rsp, @QueryParameter Ti /** @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 ParameterDefinition getParameterDefinition(String name) { 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 ff424d159c696..58846ac4a2b56 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 a69b3e40317c5..4f761587a370e 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 PasswordParameterValue(String name, Secret value, String description) { } @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 9a4e7279a9df5..3a5bb3b4f01f7 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 @@ * @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 static ExtensionList all() { 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 @@ private static void schedulePeriodicWork(PeriodicWork p) { } // 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 301c966777104..9013ddd5efc58 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 @@ abstract class Permalink { * @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 String getId() { } @Override - public Run resolve(Job job) { + public Run resolve(Job job) { return job.getLastBuild(); } }; @@ -123,7 +124,7 @@ public String getId() { @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 String getId() { @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 String getId() { @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 String getId() { @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 4e417d0539631..759094428f34c 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/PersistentDescriptor.java b/core/src/main/java/hudson/model/PersistentDescriptor.java index 80a2f829e491d..908752151279c 100644 --- a/core/src/main/java/hudson/model/PersistentDescriptor.java +++ b/core/src/main/java/hudson/model/PersistentDescriptor.java @@ -1,6 +1,6 @@ package hudson.model; -import javax.annotation.PostConstruct; +import jakarta.annotation.PostConstruct; /** * Marker interface for Descriptors which use xml persistent data, and as such need to load from disk when instantiated. diff --git a/core/src/main/java/hudson/model/Project.java b/core/src/main/java/hudson/model/Project.java index 3ed33d9bcd1a4..7dc8b692d9401 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 @@ * * @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 List getBuilders() { * 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 @@ protected Set getResourceActivities() { 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 void removePublisher(Descriptor descriptor) throws IOException 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 Publisher getPublisher(Descriptor descriptor) { @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 MavenInstallation inferMavenInstallation() { // // @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 082f87580ed3a..6d3e48aef31dc 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 e78c864947614..3f33302744dc8 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 @@ /** * 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 FormValidation doViewExistsCheck(@QueryParameter String value) { 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 static class DescriptorImpl extends ViewDescriptor { 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 d0dbb990c87ce..e0abed68ccd5e 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 boolean isNotExclusive() { @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 void load() { 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 void load() { 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 void load() { */ @Override public void save() { - if(BulkChange.contains(this)) return; + if (BulkChange.contains(this)) return; if (Jenkins.getInstanceOrNull() == null) { return; } @@ -460,8 +461,8 @@ public void save() { 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 void clear() { */ @Deprecated public boolean add(AbstractProject p) { - return schedule(p)!=null; + return schedule(p) != null; } /** @@ -528,7 +529,7 @@ public boolean add(AbstractProject p) { */ @Deprecated public boolean add(AbstractProject p, int quietPeriod) { - return schedule(p, quietPeriod)!=null; + return schedule(p, quietPeriod) != null; } /** @@ -665,7 +666,7 @@ public WaitingItem schedule(Task p, int quietPeriod, List actions) { */ @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 boolean add(Task p, int quietPeriod) { */ @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 HttpResponse doCancelItem(@QueryParameter long id) throws IOException, Se 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 @@ private WaitingItem peek() { * 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 @@ private static boolean hasReadPermission(Queue.Task t, boolean valueIfNotAccessC * 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 List getItems(Task t) { * 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 @@ private CauseOfBlockage getCauseOfBlockageForItem(Item i) { 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 static boolean tryWithLock(Runnable runnable) { * @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 void maintain() { // 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 void maintain() { } } // 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 void maintain() { 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 void maintain() { // 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 void maintain() { 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 void maintain() { * @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 @@ private Runnable makeFlyWeightTaskBuildable(final BuildableItem p){ 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 String getInQueueForString() { 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 Label getAssignedLabel() { 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 Label getAssignedLabel() { */ 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 @@ protected Item(Task task, List actions, long id, FutureImpl future) { 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 @@ protected Item(Task task, List actions, long id, FutureImpl future, long 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 @@ protected Item(Item item) { */ @Exported public String getUrl() { - return "queue/item/"+id+'/'; + return "queue/item/" + id + '/'; } /** @@ -2294,7 +2296,7 @@ public String getUrl() { @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 String getSearchUrl() { @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 HttpResponse doCancelQueue() { 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 BuildableItem(NotWaitingItem ni) { @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 CauseOfBlockage getCauseOfBlockage() { @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 CauseOfBlockage getCauseOfBlockage() { */ @Exported public @CheckForNull Executable getExecutable() { - return outcome!=null ? outcome.getPrimaryWorkUnit().getExecutable() : null; + return outcome != null ? outcome.getPrimaryWorkUnit().getExecutable() : null; } /** @@ -2785,12 +2787,12 @@ public CauseOfBlockage getCauseOfBlockage() { */ @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 boolean canConvert(Class klazz) { @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 Object fromString(String string) { 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 @@ protected void doRun() { */ 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 T get(Task task) { 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 ItemList values() { */ 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 V call() throws Exception { } } - 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 static Queue getInstance() { /** * 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 4b95c28d937f5..19727656e729e 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 static void forwardToRss(String title, String url, Collection 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 int size() { * @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 Resource call() { 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 @@ protected V _withLock(java.util.concurrent.Callable callable) throws Exce } } - 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 eb57076c9a9d3..e94a91996a13e 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 @@ * 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 static ResourceList union(ResourceList... lists) { * 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 static ResourceList union(Collection lists) { 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 ResourceList r(Resource r) { */ 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 ResourceList w(Resource r) { * 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 @@ private Resource _getConflict(ResourceList lhs, ResourceList rhs) { @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 String toString() { * {@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 2160abc9fbdd9..828eeb0d2e2e9 100644 --- a/core/src/main/java/hudson/model/RestartListener.java +++ b/core/src/main/java/hudson/model/RestartListener.java @@ -63,6 +63,7 @@ public boolean isReadyToRestart() throws IOException, InterruptedException { } 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 72b7a87f86836..b56867e37ed01 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 @@ private Result(@NonNull String name, @NonNull BallColor color, /*@java.annotatio * 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 boolean isBetterThan(@NonNull Result that) { 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 boolean isCompleteBuild() { 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 boolean isCompleteBuild() { // 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 OptionHandlerImpl(CmdLineParser parser, OptionDef option, Setter 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 static ResultTrend getResultTrend(Run run) { 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 static ResultTrend getResultTrend(Run run) { 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 static ResultTrend getResultTrend(Run run) { 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 static ResultTrend getResultTrend(Run run) { } return previousBuild; } - + /** * Returns true if this build represents a 'fix'. * I.e. it is the first successful build after previous @@ -182,7 +183,7 @@ private static boolean isFix(Run build) { 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 54bb86699c698..9c431ee635ffc 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 fa8500367c71d..85629405de80b 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 @@ * @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 @@ protected Run(@NonNull JobT job) throws IOException { * so that the {@link #timestamp} as well as {@link #number} are shared with the parent build. */ protected Run(@NonNull JobT job, @NonNull Calendar timestamp) { - this(job,timestamp.getTimeInMillis()); + this(job, timestamp.getTimeInMillis()); } /** @see #Run(Job, Calendar) */ @@ -406,7 +407,7 @@ protected void onLoad() { @Deprecated public List 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 void addAction(@NonNull Action a) { */ @SuppressWarnings("unchecked") protected @NonNull RunT _this() { - return (RunT)this; + return (RunT) this; } /** @@ -503,7 +504,7 @@ public void setResult(@NonNull Result r) { } // result can only get worse - if (result==null || r.isWorseThan(result)) { + if (result == null || r.isWorseThan(result)) { result = r; LOGGER.log(FINE, this + " in " + getRootDir() + ": result is set to " + r, LOGGER.isLoggable(Level.FINER) ? new Exception() : null); } @@ -514,7 +515,7 @@ public void setResult(@NonNull Result r) { */ public @NonNull List getBadgeActions() { List r = getActions(BuildBadgeAction.class); - if(isKeepLog()) { + if (isKeepLog()) { r = new ArrayList<>(r); r.add(new KeepLogBuildBadge()); } @@ -567,9 +568,9 @@ public boolean isLogUpdated() { * @since 1.433 */ public @CheckForNull Executor getOneOffExecutor() { - for( Computer c : Jenkins.get().getComputers() ) { + for (Computer c : Jenkins.get().getComputers()) { for (Executor e : c.getOneOffExecutors()) { - if(e.getCurrentExecutable()==this) + if (e.getCurrentExecutable() == this) return e; } } @@ -582,7 +583,7 @@ public boolean isLogUpdated() { * @since 1.257 */ public final @NonNull Charset getCharset() { - if(charset==null) return Charset.defaultCharset(); + if (charset == null) return Charset.defaultCharset(); return Charset.forName(charset); } @@ -599,7 +600,7 @@ public boolean isLogUpdated() { */ public @NonNull List 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 boolean isLogUpdated() { */ @Exported public final boolean isKeepLog() { - return getWhyKeepLog()!=null; + return getWhyKeepLog() != null; } /** @@ -630,7 +631,7 @@ public final boolean isKeepLog() { * sentence that explains why it's being kept. */ public @CheckForNull String getWhyKeepLog() { - if(keepLog) + if (keepLog) return Messages.Run_MarkedExplicitly(); return null; // not marked at all } @@ -677,7 +678,7 @@ public final long getTimeInMillis() { * @see #getTimestamp() */ public final long getStartTimeInMillis() { - if (startTime==0) return timestamp; // fallback: approximate by the queuing time + if (startTime == 0) return timestamp; // fallback: approximate by the queuing time return startTime; } @@ -717,9 +718,9 @@ public String getDescription() { int displayChars = 0; int lastTruncatablePoint = -1; - for (int i=0; i') { inTag = false; @@ -756,7 +757,7 @@ public String getDescription() { * string like "3 minutes" "1 day" etc. */ public @NonNull String getTimestampString() { - long duration = new GregorianCalendar().getTimeInMillis()-timestamp; + long duration = new GregorianCalendar().getTimeInMillis() - timestamp; return Util.getTimeSpanString(duration); } @@ -775,7 +776,7 @@ public String getDescription() { return Messages.Run_NotStartedYet(); } else if (isBuilding()) { return Messages.Run_InProgressDuration( - Util.getTimeSpanString(System.currentTimeMillis()-startTime)); + Util.getTimeSpanString(System.currentTimeMillis() - startTime)); } return Util.getTimeSpanString(duration); } @@ -792,7 +793,7 @@ public long getDuration() { * Gets the icon color for display. */ public @NonNull BallColor getIconColor() { - if(!isBuilding()) { + if (!isBuilding()) { // already built return getResult().color; } @@ -800,7 +801,7 @@ public long getDuration() { // a new build is in progress BallColor baseColor; RunT pb = getPreviousBuild(); - if(pb==null) + if (pb == null) baseColor = BallColor.NOTBUILT; else baseColor = pb.getIconColor(); @@ -812,7 +813,7 @@ public long getDuration() { * Returns true if the build is still queued and hasn't started yet. */ public boolean hasntStartedYet() { - return state ==State.NOT_STARTED; + return state == State.NOT_STARTED; } @SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", justification = "see JENKINS-45892") @@ -826,17 +827,17 @@ public String toString() { @Exported public String getFullDisplayName() { - return project.getFullDisplayName()+' '+getDisplayName(); + return project.getFullDisplayName() + ' ' + getDisplayName(); } @Override @Exported public String getDisplayName() { - return displayName!=null ? displayName : "#"+number; + return displayName != null ? displayName : "#" + number; } public boolean hasCustomDisplayName() { - return displayName!=null; + return displayName != null; } /** @@ -849,7 +850,7 @@ public void setDisplayName(String value) throws IOException { save(); } - @Exported(visibility=2) + @Exported(visibility = 2) public int getNumber() { return number; } @@ -871,9 +872,9 @@ public int getNumber() { * @since 1.556 */ protected void dropLinks() { - if(nextBuild!=null) + if (nextBuild != null) nextBuild.previousBuild = previousBuild; - if(previousBuild!=null) + if (previousBuild != null) previousBuild.nextBuild = nextBuild; } @@ -888,9 +889,9 @@ protected void dropLinks() { * Gets the most recent {@linkplain #isBuilding() completed} build excluding 'this' Run itself. */ public final @CheckForNull RunT getPreviousCompletedBuild() { - RunT r=getPreviousBuild(); - while (r!=null && r.isBuilding()) - r=r.getPreviousBuild(); + RunT r = getPreviousBuild(); + while (r != null && r.isBuilding()) + r = r.getPreviousBuild(); return r; } @@ -903,18 +904,18 @@ protected void dropLinks() { * in 'fixUp' and update them later. */ public final @CheckForNull RunT getPreviousBuildInProgress() { - if(previousBuildInProgress==this) return null; // the most common case + if (previousBuildInProgress == this) return null; // the most common case List 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 @@ protected void dropLinks() { // fix up so that the next look up will run faster for (RunT f : fixUp) - f.previousBuildInProgress = answer==null ? f : answer; + f.previousBuildInProgress = answer == null ? f : answer; return answer; } @@ -939,10 +940,10 @@ protected void dropLinks() { * Returns the last build that was actually built - i.e., skipping any with Result.NOT_BUILT */ public @CheckForNull RunT getPreviousBuiltBuild() { - RunT r=getPreviousBuild(); + RunT r = getPreviousBuild(); // in certain situations (aborted m2 builds) r.getResult() can still be null, although it should theoretically never happen - while( r!=null && (r.getResult() == null || r.getResult()==Result.NOT_BUILT) ) - r=r.getPreviousBuild(); + while (r != null && (r.getResult() == null || r.getResult() == Result.NOT_BUILT)) + r = r.getPreviousBuild(); return r; } @@ -950,9 +951,9 @@ protected void dropLinks() { * Returns the last build that didn't fail before this build. */ public @CheckForNull RunT getPreviousNotFailedBuild() { - RunT r=getPreviousBuild(); - while( r!=null && r.getResult()==Result.FAILURE ) - r=r.getPreviousBuild(); + RunT r = getPreviousBuild(); + while (r != null && r.getResult() == Result.FAILURE) + r = r.getPreviousBuild(); return r; } @@ -960,9 +961,9 @@ protected void dropLinks() { * Returns the last failed build before this build. */ public @CheckForNull RunT getPreviousFailedBuild() { - RunT r=getPreviousBuild(); - while( r!=null && r.getResult()!=Result.FAILURE ) - r=r.getPreviousBuild(); + RunT r = getPreviousBuild(); + while (r != null && r.getResult() != Result.FAILURE) + r = r.getPreviousBuild(); return r; } @@ -971,9 +972,9 @@ protected void dropLinks() { * @since 1.383 */ public @CheckForNull RunT getPreviousSuccessfulBuild() { - RunT r=getPreviousBuild(); - while( r!=null && r.getResult()!=Result.SUCCESS ) - r=r.getPreviousBuild(); + RunT r = getPreviousBuild(); + while (r != null && r.getResult() != Result.SUCCESS) + r = r.getPreviousBuild(); return r; } @@ -1042,14 +1043,14 @@ protected void dropLinks() { // @see also {@link AbstractItem#getUrl} StaplerRequest req = Stapler.getCurrentRequest(); if (req != null) { - String seed = Functions.getNearestAncestorUrl(req,this); - if(seed!=null) { + String seed = Functions.getNearestAncestorUrl(req, this); + 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) + '/'; } } - return project.getUrl()+getNumber()+'/'; + return project.getUrl() + getNumber() + '/'; } /** @@ -1060,15 +1061,15 @@ protected void dropLinks() { * misconfiguration to break this value, with network set up like Apache reverse proxy. * This method is only intended for the remote API clients who cannot resolve relative references. */ - @Exported(visibility=2,name="url") + @Exported(visibility = 2, name = "url") @Deprecated public final @NonNull String getAbsoluteUrl() { - return project.getAbsoluteUrl()+getNumber()+'/'; + return project.getAbsoluteUrl() + getNumber() + '/'; } @Override public final @NonNull String getSearchUrl() { - return getNumber()+"/"; + return getNumber() + "/"; } /** @@ -1138,7 +1139,7 @@ protected void dropLinks() { */ @Deprecated public File getArtifactsDir() { - return new File(getRootDir(),"archive"); + return new File(getRootDir(), "archive"); } /** @@ -1182,10 +1183,12 @@ private static final class AddArtifacts extends MasterToSlaveCallable=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 @@ private static final class SerializableArtifact implements Serializable { final String href; final String length; final String treeNodeId; + SerializableArtifact(String name, String relativePath, String href, String length, String treeNodeId) { this.name = name; this.relativePath = relativePath; @@ -1275,7 +1279,7 @@ public final class ArtifactList extends ArrayList { * Map of Artifact to treeNodeId of parent node in tree view. * Contains Artifact objects for directories and files (the ArrayList contains only files). */ - private LinkedHashMap 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 @@ void updateFrom(SerializableArtifactList clone) { } } - public Map 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++0) 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 class Artifact { /** * Relative path name from artifacts root. */ - @Exported(visibility=3) + @Exported(visibility = 3) public final String relativePath; /** @@ -1404,18 +1408,18 @@ public class Artifact { */ @Deprecated public @NonNull File getFile() { - return new File(getArtifactsDir(),relativePath); + return new File(getArtifactsDir(), relativePath); } /** * Returns just the file name portion, without the path. */ - @Exported(visibility=3) + @Exported(visibility = 3) public String getFileName() { return name; } - @Exported(visibility=3) + @Exported(visibility = 3) public String getDisplayPath() { return displayPath; } @@ -1428,7 +1432,7 @@ public String getLength() { return length; } - public long getFileSize(){ + public long getFileSize() { try { return Long.decode(length); } @@ -1494,7 +1498,7 @@ public Collection getBuildFingerprints() { public @NonNull InputStream getLogInputStream() throws IOException { File logFile = getLogFile(); - if (logFile.exists() ) { + if (logFile.exists()) { // Checking if a ".gz" file was return try { InputStream fis = Files.newInputStream(logFile.toPath()); @@ -1513,8 +1517,8 @@ public Collection getBuildFingerprints() { } public @NonNull Reader getLogReader() throws IOException { - if (charset==null) return new InputStreamReader(getLogInputStream(),Charset.defaultCharset()); - else return new InputStreamReader(getLogInputStream(),charset); + if (charset == null) return new InputStreamReader(getLogInputStream(), Charset.defaultCharset()); + else return new InputStreamReader(getLogInputStream(), charset); } /** @@ -1567,7 +1571,7 @@ public void writeWholeLogTo(@NonNull OutputStream out) throws IOException, Inter * @return A {@link Run} log with annotations */ public @NonNull AnnotatedLargeText getLogText() { - return new AnnotatedLargeText(getLogFile(),getCharset(),!isLogUpdated(),this); + return new AnnotatedLargeText(getLogFile(), getCharset(), !isLogUpdated(), this); } @Override @@ -1576,7 +1580,7 @@ public void writeWholeLogTo(@NonNull OutputStream out) throws IOException, Inter .add("console") .add("changes"); for (Action a : getAllActions()) { - if(a.getIconFileName()!=null) + if (a.getIconFileName() != null) builder.add(a.getUrlName()); } return builder; @@ -1648,7 +1652,7 @@ public void delete() throws IOException { } // for StandardArtifactManager, deleting the whole build dir suffices synchronized (this) { // avoid holding a lock while calling plugin impls of onDeleted - File tmp = new File(rootDir.getParentFile(),'.'+rootDir.getName()); + File tmp = new File(rootDir.getParentFile(), '.' + rootDir.getName()); if (tmp.exists()) { Util.deleteRecursive(tmp); @@ -1676,7 +1680,7 @@ public void delete() throws IOException { @SuppressWarnings("unchecked") // seems this is too clever for Java's type system? private void removeRunFromParent() { - getParent().removeRun((RunT)this); + getParent().removeRun((RunT) this); } @@ -1684,7 +1688,7 @@ private void removeRunFromParent() { * @see CheckPoint#report() */ /*package*/ static void reportCheckpoint(@NonNull CheckPoint id) { - Run.RunExecution exec = RunnerStack.INSTANCE.peek(); + Run.RunExecution exec = RunnerStack.INSTANCE.peek(); if (exec == null) { return; } @@ -1695,20 +1699,20 @@ private void removeRunFromParent() { * @see CheckPoint#block() */ /*package*/ static void waitForCheckpoint(@NonNull CheckPoint id, @CheckForNull BuildListener listener, @CheckForNull String waiter) throws InterruptedException { - while(true) { - 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 @@ private synchronized void allDone() { private final CheckpointSet checkpoints = new CheckpointSet(); - private final Map attributes = new HashMap<>(); + private final Map attributes = new HashMap<>(); /** * Performs the main build and returns the status code. @@ -1783,7 +1787,7 @@ private synchronized void allDone() { * @throws Exception * exception will be recorded and the build will be considered a failure. */ - public abstract @NonNull Result run(@NonNull BuildListener listener ) throws Exception; + public abstract @NonNull Result run(@NonNull BuildListener listener) throws Exception; /** * Performs the post-build action. @@ -1795,7 +1799,7 @@ private synchronized void allDone() { * even if the build is successful, this build still won't be picked up * by {@link Job#getLastSuccessfulBuild()}. */ - public abstract void post(@NonNull BuildListener listener ) throws Exception; + public abstract void post(@NonNull BuildListener listener) throws Exception; /** * Performs final clean up action. @@ -1823,7 +1827,7 @@ private synchronized void allDone() { * * @since 1.473 */ - public @NonNull Map getAttributes() { + public @NonNull Map getAttributes() { return attributes; } } @@ -1847,11 +1851,11 @@ protected final void run(@NonNull Runner job) { } protected final void execute(@NonNull RunExecution job) { - if(result!=null) + if (result != null) return; // already built. OutputStream logger = null; - StreamBuildListener listener=null; + StreamBuildListener listener = null; runner = job; onStartBuilding(); @@ -1887,7 +1891,7 @@ protected final void execute(@NonNull RunExecution job) { listener.getLogger().println(Messages.Run_running_as_(id)); } - RunListener.fireStarted(this,listener); + RunListener.fireStarted(this, listener); setResult(job.run(listener)); @@ -1895,21 +1899,21 @@ protected final void execute(@NonNull RunExecution job) { CheckPoint.MAIN_COMPLETED.report(); } catch (ThreadDeath t) { throw t; - } catch( AbortException e ) {// orderly abortion. + } catch (AbortException e) { // orderly abortion. result = Result.FAILURE; listener.error(e.getMessage()); - LOGGER.log(FINE, "Build "+this+" aborted",e); - } catch( RunnerAbortedException e ) {// orderly abortion. + LOGGER.log(FINE, "Build " + this + " aborted", e); + } catch (RunnerAbortedException e) { // orderly abortion. result = Result.FAILURE; - LOGGER.log(FINE, "Build "+this+" aborted",e); - } catch( InterruptedException e) { + LOGGER.log(FINE, "Build " + this + " aborted", e); + } catch (InterruptedException e) { // aborted result = Executor.currentExecutor().abortResult(); listener.getLogger().println(Messages.Run_BuildAborted()); - Executor.currentExecutor().recordCauseOfInterruption(Run.this,listener); + Executor.currentExecutor().recordCauseOfInterruption(Run.this, listener); LOGGER.log(Level.INFO, this + " aborted", e); - } catch( Throwable e ) { - handleFatalBuildProblem(listener,e); + } catch (Throwable e) { + handleFatalBuildProblem(listener, e); result = Result.FAILURE; } @@ -1918,8 +1922,8 @@ protected final void execute(@NonNull RunExecution job) { } catch (ThreadDeath t) { throw t; - } catch( Throwable e ) { - handleFatalBuildProblem(listener,e); + } catch (Throwable e) { + handleFatalBuildProblem(listener, e); result = Result.FAILURE; } finally { long end = System.currentTimeMillis(); @@ -1934,11 +1938,11 @@ protected final void execute(@NonNull RunExecution job) { state = State.POST_PRODUCTION; if (listener != null) { - RunListener.fireCompleted(this,listener); + RunListener.fireCompleted(this, listener); try { job.cleanUp(listener); } catch (Exception e) { - handleFatalBuildProblem(listener,e); + handleFatalBuildProblem(listener, e); // too late to update the result now } listener.finished(result); @@ -1948,14 +1952,14 @@ protected final void execute(@NonNull RunExecution job) { try { save(); } catch (IOException e) { - LOGGER.log(Level.SEVERE, "Failed to save build record",e); + LOGGER.log(Level.SEVERE, "Failed to save build record", e); } } try { getParent().logRotate(); } catch (Exception e) { - LOGGER.log(Level.SEVERE, "Failed to rotate log",e); + LOGGER.log(Level.SEVERE, "Failed to rotate log", e); } } finally { onEndBuilding(); @@ -1996,7 +2000,7 @@ private StreamBuildListener createBuildListener(@NonNull RunExecution job, Outpu } } - return new StreamBuildListener(logger,charset); + return new StreamBuildListener(logger, charset); } /** @@ -2009,15 +2013,15 @@ public final void updateSymlinks(@NonNull TaskListener listener) throws Interrup * Handles a fatal build problem (exception) that occurred during the build. */ private void handleFatalBuildProblem(@NonNull BuildListener listener, @NonNull Throwable e) { - if(listener!=null) { - LOGGER.log(FINE, getDisplayName()+" failed to build",e); + if (listener != null) { + LOGGER.log(FINE, getDisplayName() + " failed to build", e); - if(e instanceof IOException) - Util.displayIOException((IOException)e,listener); + if (e instanceof IOException) + Util.displayIOException((IOException) e, listener); Functions.printStackTrace(e, listener.fatalError(e.getMessage())); } else { - LOGGER.log(SEVERE, getDisplayName()+" failed to build and we don't even have a listener",e); + LOGGER.log(SEVERE, getDisplayName() + " failed to build and we don't even have a listener", e); } } @@ -2028,7 +2032,7 @@ protected void onStartBuilding() { LOGGER.log(FINER, "moving to BUILDING on {0}", this); state = State.BUILDING; startTime = System.currentTimeMillis(); - if (runner!=null) + if (runner != null) RunnerStack.INSTANCE.push(runner); RunListener.fireInitialize(this); } @@ -2040,7 +2044,7 @@ protected void onEndBuilding() { // signal that we've finished building. state = State.COMPLETED; LOGGER.log(FINER, "moving to COMPLETED on {0}", this); - if (runner!=null) { + if (runner != null) { // MavenBuilds may be created without their corresponding runners. runner.checkpoints.allDone(); runner = null; @@ -2059,23 +2063,26 @@ protected void onEndBuilding() { */ @Override public synchronized void save() throws IOException { - if(BulkChange.contains(this)) return; + if (BulkChange.contains(this)) return; getDataFile().write(this); SaveableListener.fireOnChange(this, getDataFile()); } private @NonNull XmlFile getDataFile() { - return new XmlFile(XSTREAM,new File(getRootDir(),"build.xml")); + return new XmlFile(XSTREAM, new File(getRootDir(), "build.xml")); } protected Object writeReplace() { return XmlFile.replaceIfNotAtTopLevel(this, () -> 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 @@ private Object readResolve() { */ @Deprecated public @NonNull String getLog() throws IOException { - return Util.loadFile(getLogFile(),getCharset()); + return Util.loadFile(getLogFile(), getCharset()); } /** @@ -2141,7 +2148,7 @@ private Object readResolve() { // Use set (replaces the first element) rather than add so that // the list doesn't grow beyond the specified maximum number of lines. if (lines == maxLines) { - lastLines.set(0, "[...truncated " + Functions.humanReadableByteSize(filePointer)+ "...]"); + lastLines.set(0, "[...truncated " + Functions.humanReadableByteSize(filePointer) + "...]"); } return ConsoleNote.removeNotes(lastLines); @@ -2153,8 +2160,8 @@ private String convertBytesToString(List bytes) { return new String(ArrayUtils.toPrimitive(byteArray), getCharset()); } - public void doBuildStatus( StaplerRequest req, StaplerResponse rsp ) throws IOException { - rsp.sendRedirect2(req.getContextPath()+"/images/48x48/"+getBuildStatusUrl()); + public void doBuildStatus(StaplerRequest req, StaplerResponse rsp) throws IOException { + rsp.sendRedirect2(req.getContextPath() + "/images/48x48/" + getBuildStatusUrl()); } public @NonNull String getBuildStatusUrl() { @@ -2189,7 +2196,7 @@ public abstract static class StatusSummarizer implements ExtensionPoint { * @param trend the result of {@link ResultTrend#getResultTrend(hudson.model.Run)} on {@code run} (precomputed for efficiency) * @return a summary, or null to fall back to other summarizers or built-in behavior */ - public abstract @CheckForNull Summary summarize(@NonNull Run run, @NonNull ResultTrend trend); + public abstract @CheckForNull Summary summarize(@NonNull Run run, @NonNull ResultTrend trend); } /** @@ -2212,29 +2219,29 @@ public abstract static class StatusSummarizer implements ExtensionPoint { } switch (trend) { - case ABORTED : return new Summary(false, Messages.Run_Summary_Aborted()); + case ABORTED: return new Summary(false, Messages.Run_Summary_Aborted()); - case NOT_BUILT : return new Summary(false, Messages.Run_Summary_NotBuilt()); + case NOT_BUILT: return new Summary(false, Messages.Run_Summary_NotBuilt()); - case FAILURE : return new Summary(true, Messages.Run_Summary_BrokenSinceThisBuild()); + case FAILURE: return new Summary(true, Messages.Run_Summary_BrokenSinceThisBuild()); - case STILL_FAILING : + case STILL_FAILING: RunT since = getPreviousNotFailedBuild(); - if(since==null) + if (since == null) return new Summary(false, Messages.Run_Summary_BrokenForALongTime()); RunT failedBuild = since.getNextBuild(); return new Summary(false, Messages.Run_Summary_BrokenSince(failedBuild.getDisplayName())); case NOW_UNSTABLE: - case STILL_UNSTABLE : + case STILL_UNSTABLE: return new Summary(false, Messages.Run_Summary_Unstable()); - case UNSTABLE : + case UNSTABLE: return new Summary(true, Messages.Run_Summary_Unstable()); - case SUCCESS : + case SUCCESS: return new Summary(false, Messages.Run_Summary_Stable()); - case FIXED : + case FIXED: return new Summary(false, Messages.Run_Summary_BackToNormal()); default: @@ -2247,7 +2254,7 @@ public abstract static class StatusSummarizer implements ExtensionPoint { * @throws AccessDeniedException Access denied */ public @NonNull DirectoryBrowserSupport doArtifact() { - if(Functions.isArtifactsPermissionEnabled()) { + if (Functions.isArtifactsPermissionEnabled()) { checkPermission(ARTIFACTS); } return new DirectoryBrowserSupport(this, getArtifactManager().root(), Messages.Run_ArtifactsBrowserTitle(project.getDisplayName(), getDisplayName()), "package.png", true); @@ -2266,13 +2273,13 @@ public void doBuildNumber(StaplerResponse rsp) throws IOException { /** * Returns the build time stamp in the body. */ - public void doBuildTimestamp( StaplerRequest req, StaplerResponse rsp, @QueryParameter String format) throws IOException { + public void doBuildTimestamp(StaplerRequest req, StaplerResponse rsp, @QueryParameter String format) throws IOException { rsp.setContentType("text/plain"); rsp.setCharacterEncoding("US-ASCII"); rsp.setStatus(HttpServletResponse.SC_OK); - DateFormat df = format==null ? - DateFormat.getDateTimeInstance(DateFormat.SHORT,DateFormat.SHORT, Locale.ENGLISH) : - new SimpleDateFormat(format,req.getLocale()); + DateFormat df = format == null ? + DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.ENGLISH) : + new SimpleDateFormat(format, req.getLocale()); rsp.getWriter().print(df.format(getTime())); } @@ -2294,8 +2301,8 @@ public void doConsoleText(StaplerRequest req, StaplerResponse rsp) throws IOExce * Use {@code getLogText().doProgressiveText(req,rsp)} */ @Deprecated - public void doProgressiveLog( StaplerRequest req, StaplerResponse rsp) throws IOException { - getLogText().doProgressText(req,rsp); + public void doProgressiveLog(StaplerRequest req, StaplerResponse rsp) throws IOException { + getLogText().doProgressText(req, rsp); } /** @@ -2316,7 +2323,7 @@ public boolean canToggleLogKeep() { } @RequirePOST - public void doToggleLogKeep( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { + public void doToggleLogKeep(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { keepLog(!keepLog); rsp.forwardToPreviousPage(req); } @@ -2324,7 +2331,7 @@ public void doToggleLogKeep( StaplerRequest req, StaplerResponse rsp ) throws IO /** * Marks this build to be kept. */ - @CLIMethod(name="keep-build") + @CLIMethod(name = "keep-build") public final void keepLog() throws IOException { keepLog(true); } @@ -2339,27 +2346,27 @@ public void keepLog(boolean newValue) throws IOException { * Deletes the build when the button is pressed. */ @RequirePOST - public void doDoDelete( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { + public void doDoDelete(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { checkPermission(DELETE); // We should not simply delete the build if it has been explicitly // marked to be preserved, or if the build should not be deleted // due to dependencies! String why = getWhyKeepLog(); - if (why!=null) { + if (why != null) { sendError(Messages.Run_UnableToDelete(getFullDisplayName(), why), req, rsp); return; } - try{ + try { delete(); } - catch(IOException ex){ + catch (IOException ex) { req.setAttribute("stackTraces", Functions.printThrowable(ex)); req.getView(this, "delete-retry.jelly").forward(req, rsp); return; } - rsp.sendRedirect2(req.getContextPath()+'/' + getParent().getUrl()); + rsp.sendRedirect2(req.getContextPath() + '/' + getParent().getUrl()); } public void setDescription(String description) throws IOException { @@ -2372,7 +2379,7 @@ public void setDescription(String description) throws IOException { * 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 { setDescription(req.getParameter("description")); rsp.sendRedirect("."); // go to the top page } @@ -2382,7 +2389,7 @@ public synchronized void doSubmitDescription( StaplerRequest req, StaplerRespons * Use {@link #getEnvironment(TaskListener)} instead. */ @Deprecated - public Map 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 EnvVars getEnvironment() throws IOException, InterruptedException { */ public @NonNull EnvVars getEnvironment(@NonNull TaskListener listener) throws IOException, InterruptedException { Computer c = Computer.currentComputer(); - Node n = c==null ? null : c.getNode(); + Node n = c == null ? null : c.getNode(); - EnvVars env = getParent().getEnvironment(n,listener); + EnvVars env = getParent().getEnvironment(n, listener); env.putAll(getCharacteristicEnvVars()); // apply them in a reverse order so that higher ordinal ones can modify values added by lower ordinal ones for (EnvironmentContributor ec : EnvironmentContributor.all().reverseView()) - ec.buildEnvironmentFor(this,env,listener); + ec.buildEnvironmentFor(this, env, listener); if (!(this instanceof AbstractBuild)) { for (EnvironmentContributingAction a : getActions(EnvironmentContributingAction.class)) { @@ -2442,9 +2449,9 @@ public EnvVars getEnvironment() throws IOException, InterruptedException { */ public @NonNull final EnvVars getCharacteristicEnvVars() { EnvVars env = getParent().getCharacteristicEnvVars(); - env.put("BUILD_NUMBER",String.valueOf(number)); - env.put("BUILD_ID",getId()); - env.put("BUILD_TAG","jenkins-"+getParent().getFullName().replace('/', '-')+"-"+number); + env.put("BUILD_NUMBER", String.valueOf(number)); + env.put("BUILD_ID", getId()); + env.put("BUILD_TAG", "jenkins-" + getParent().getFullName().replace('/', '-') + "-" + number); return env; } @@ -2464,7 +2471,7 @@ public EnvVars getEnvironment() throws IOException, InterruptedException { * @throws IllegalArgumentException if the ID is malformed * @throws AccessDeniedException as per {@link ItemGroup#getItem} */ - public @CheckForNull static 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 EnvVars getEnvironment() throws IOException, InterruptedException { if (j == null) { return null; } - Job job = j.getItemByFullName(jobName, Job.class); + Job job = j.getItemByFullName(jobName, Job.class); if (job == null) { return null; } @@ -2501,7 +2508,7 @@ public long getEstimatedDuration() { } @POST - public @NonNull HttpResponse doConfigSubmit( StaplerRequest req ) throws IOException, ServletException, FormException { + public @NonNull HttpResponse doConfigSubmit(StaplerRequest req) throws IOException, ServletException, FormException { checkPermission(UPDATE); try (BulkChange bc = new BulkChange(this)) { JSONObject json = req.getSubmittedForm(); @@ -2521,10 +2528,10 @@ protected void submit(JSONObject json) throws IOException { /** * 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("build",FreeStyleBuild.class); + XSTREAM.alias("build", FreeStyleBuild.class); XSTREAM.registerConverter(Result.conv); } @@ -2558,7 +2565,7 @@ public int compare(@NonNull Run lhs, @NonNull Run rhs) { @Override public String getEntryID(Run e) { // can't use a meaningful year field unless we remember when the job was created. - return "tag:hudson.dev.java.net,2008:"+e.getParent().getAbsoluteUrl(); + return "tag:hudson.dev.java.net,2008:" + e.getParent().getAbsoluteUrl(); } }; @@ -2568,24 +2575,27 @@ public String getEntryID(Run e) { public final class KeepLogBuildBadge implements BuildBadgeAction { @Override public @CheckForNull String getIconFileName() { return null; } + @Override public @CheckForNull String getDisplayName() { return null; } + @Override public @CheckForNull String getUrlName() { return null; } + public @CheckForNull String getWhyKeepLog() { return Run.this.getWhyKeepLog(); } } - public static final PermissionGroup PERMISSIONS = new PermissionGroup(Run.class,Messages._Run_Permissions_Title()); - public static final Permission DELETE = new Permission(PERMISSIONS,"Delete",Messages._Run_DeletePermission_Description(),Permission.DELETE, PermissionScope.RUN); - public static final Permission UPDATE = new Permission(PERMISSIONS,"Update",Messages._Run_UpdatePermission_Description(),Permission.UPDATE, PermissionScope.RUN); + public static final PermissionGroup PERMISSIONS = new PermissionGroup(Run.class, Messages._Run_Permissions_Title()); + public static final Permission DELETE = new Permission(PERMISSIONS, "Delete", Messages._Run_DeletePermission_Description(), Permission.DELETE, PermissionScope.RUN); + public static final Permission UPDATE = new Permission(PERMISSIONS, "Update", Messages._Run_UpdatePermission_Description(), Permission.UPDATE, PermissionScope.RUN); /** See {@link hudson.Functions#isArtifactsPermissionEnabled} */ - public static final Permission ARTIFACTS = new Permission(PERMISSIONS,"Artifacts",Messages._Run_ArtifactsPermission_Description(), null, + public static final Permission ARTIFACTS = new Permission(PERMISSIONS, "Artifacts", Messages._Run_ArtifactsPermission_Description(), null, Functions.isArtifactsPermissionEnabled(), new PermissionScope[]{PermissionScope.RUN}); private static class DefaultFeedAdapter implements FeedAdapter { @Override public String getEntryTitle(Run entry) { - return entry.getFullDisplayName()+" ("+entry.getBuildStatusSummary().message+")"; + return entry.getFullDisplayName() + " (" + entry.getBuildStatusSummary().message + ")"; } @Override @@ -2597,7 +2607,7 @@ public String getEntryUrl(Run entry) { public String getEntryID(Run entry) { return "tag:" + "hudson.dev.java.net," + entry.getTimestamp().get(Calendar.YEAR) + ":" - + entry.getParent().getFullName()+':'+entry.getId(); + + entry.getParent().getFullName() + ':' + entry.getId(); } @Override @@ -2619,9 +2629,9 @@ public String getEntryAuthor(Run entry) { @Override public Object getDynamic(String token, StaplerRequest req, StaplerResponse rsp) { Object returnedResult = super.getDynamic(token, req, rsp); - if (returnedResult == null){ + if (returnedResult == null) { //check transient actions too - for(Action action: getTransientActions()){ + for (Action action : getTransientActions()) { String urlName = action.getUrlName(); if (urlName == null) { continue; diff --git a/core/src/main/java/hudson/model/RunAction.java b/core/src/main/java/hudson/model/RunAction.java index 995a12d52e2b3..f02008bb5077c 100644 --- a/core/src/main/java/hudson/model/RunAction.java +++ b/core/src/main/java/hudson/model/RunAction.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.RunAction2; @@ -32,7 +33,7 @@ public interface RunAction extends Action { /** * Called after the build is loaded and the object is added to the build list. - * + * * Because {@link RunAction}s are persisted with {@link Run}, the implementation * can keep a reference to {@link Run} in a field (which is set via {@link #onAttached(Run)}) */ diff --git a/core/src/main/java/hudson/model/RunMap.java b/core/src/main/java/hudson/model/RunMap.java index 88f8da4f8127e..1d2047c2445e8 100644 --- a/core/src/main/java/hudson/model/RunMap.java +++ b/core/src/main/java/hudson/model/RunMap.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.FINEST; @@ -58,11 +59,11 @@ * * @author Kohsuke Kawaguchi */ -public final class RunMap> 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 Iterator iterator() { @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 R next() { @Override public void remove() { - if (last==null) + if (last == null) throw new UnsupportedOperationException(); removeValue(last); } @@ -139,7 +140,7 @@ public boolean removeValue(R run) { /** * Gets the read-only view of this map. */ - public SortedMap getView() { + public SortedMap getView() { return view; } @@ -167,7 +168,7 @@ public R oldestValue() { /** * {@link Run} factory. */ - public interface Constructor> { + public interface Constructor> { R create(File dir) throws IOException; } @@ -226,7 +227,7 @@ protected BuildReference createReference(R r) { @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 b24e588f976e8..3ac138a8761c8 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 String getName() { 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 RunParameterDefinition(@NonNull String name, String projectName, @CheckFo /** * @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 Job getProject() { */ @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 RunList getBuilds() { 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 String getHelpFile() { 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 ParameterValue getDefaultParameterValue() { return createValue(runId); } - Run lastBuild; + Run lastBuild; Job project = getProject(); if (project == null) { @@ -184,7 +185,7 @@ public ParameterValue getDefaultParameterValue() { case SUCCESSFUL: lastBuild = project.getLastSuccessfulBuild(); break; - case STABLE : + case STABLE: lastBuild = project.getLastStableBuild(); break; default: @@ -193,9 +194,9 @@ public ParameterValue getDefaultParameterValue() { } 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 1edc798366eef..23e94f66746c3 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 @@ private static String check(String runId) { public String getRunId() { return runId; } - + private String[] split() { if (runId == null) { return null; @@ -78,13 +79,13 @@ private String[] split() { @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 Run getValue() { * 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 ddca4e94016e8..6f4c57b242bfd 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 @@ * @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 @@ synchronized void pop() { 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 142e4f51535d2..2cfd0dde7079a 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 a2e8b8f9a4344..c98900d99d644 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 90b36b2c2b640..0ae31abe1db5e 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 @@ * *

    * 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 @@ * @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 @@ protected Slave(String name, String nodeDescription, String remoteFS, String num @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 @@ protected Slave(@NonNull String name, String nodeDescription, String remoteFS, i 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 void setMode(Mode mode) { @Override public DescribableList, NodePropertyDescriptor> getNodeProperties() { assert nodeProperties != null; - return nodeProperties; + return nodeProperties; } @DataBoundSetter @@ -336,7 +337,7 @@ public void setLabelString(String labelString) throws IOException { } @Override - public Callable getClockDifferenceCallable() { + public Callable getClockDifferenceCallable() { return new GetClockDifference1(); } @@ -355,7 +356,7 @@ public FilePath getWorkspaceFor(TopLevelItem item) { } 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 FilePath getRootPath() { */ 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 JnlpJar(String fileName) { 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 void doIndex( StaplerRequest req, StaplerResponse rsp) throws IOException @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 @@ private URLConnection connect() throws IOException { 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 URL getURL() throws IOException { } } } - + 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 Launcher createLauncher(TaskListener listener) { 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 Launcher createLauncher(TaskListener listener) { } 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 Launcher createLauncher(TaskListener listener) { // 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 @@ private void reportLauncherCreateError(@NonNull String humanReadableMsg, @CheckF */ @CheckForNull public SlaveComputer getComputer() { - return (SlaveComputer)toComputer(); + return (SlaveComputer) toComputer(); } @Override @@ -574,7 +575,7 @@ public int hashCode() { * 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 SlaveDescriptor getDescriptor() { 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 FormValidation doCheckNumExecutors(@QueryParameter String value) { * 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 final List nodePropertyDescriptors(@CheckForNull *

  • 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 @@ private Object writeReplace() { 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 @@ private static final class GetClockDifference3 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 458955c2bec80..b4c4bc7496284 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 2ad5192653e8a..efa1204fe11f4 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 @@ * {@link BuildListener} that writes to an {@link OutputStream}. * * This class is remotable. - * + * * @author Kohsuke Kawaguchi */ public class StreamBuildListener extends StreamTaskListener implements BuildListener { @@ -46,6 +47,12 @@ public StreamBuildListener(File out, Charset charset) throws IOException { super(out, charset); } + /** + * @deprecated as of TODO + * The caller should use {@link #StreamBuildListener(OutputStream, Charset)} to pass in + * the charset and output stream separately, so that this class can handle encoding correctly. + */ + @Deprecated public StreamBuildListener(OutputStream w) { super(w); } @@ -61,7 +68,7 @@ public StreamBuildListener(PrintStream w) { } 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 b65504cedddb6..8a5dfa9f1b048 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 StringParameterDefinition(@NonNull String name, @CheckForNull String defa setDefaultValue(defaultValue); setDescription(description); } - + public StringParameterDefinition(@NonNull String name, @CheckForNull String defaultValue) { this(name); setDefaultValue(defaultValue); @@ -87,7 +88,7 @@ public String getDefaultValue() { } /** - * + * * @return original or trimmed defaultValue (depending on trim) */ @Restricted(DoNotUse.class) // Jelly @@ -104,7 +105,7 @@ public void setDefaultValue(@CheckForNull String defaultValue) { } /** - * + * * @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 boolean isTrim() { public void setTrim(boolean trim) { this.trim = trim; } - + @Override public StringParameterValue getDefaultParameterValue() { StringParameterValue value = new StringParameterValue(getName(), defaultValue, getDescription()); @@ -131,7 +132,7 @@ public StringParameterValue getDefaultParameterValue() { 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 ad7e528ac07fb..f5e0583ed5629 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 @@ * {@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 StringParameterValue(String name, String value, String description) { * 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 VariableResolver createVariableResolver(AbstractBuild build 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 575f35efab5c4..60ca66ac05368 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 LargeText getLog() { */ public AnnotatedLargeText obtainLog() { WeakReference l = log; - if(l==null) return null; + if (l == null) return null; return l.get(); } @@ -112,10 +113,10 @@ public TaskThread getWorkerThread() { /** * 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 void doProgressiveLog( StaplerRequest req, StaplerResponse rsp) throws IO /** * 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 void doProgressiveHtml( StaplerRequest req, StaplerResponse rsp) throws I 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 a466613d027f7..17269432f9553 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 @@ default PrintWriter error(String msg) { */ @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 60456f333fab1..2991da6211b06 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 @@ *

    * 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 final void run() { 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 static ListenerAndText forMemory() { */ @Deprecated public static ListenerAndText forFile(File f) throws IOException { - return forFile(f,null); + return forFile(f, null); } /** @@ -192,7 +193,7 @@ public static ListenerAndText forMemory(TaskAction context) { } /** - * 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 da13fd7f7e412..4db836a7b7e51 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 TextParameterDefinition(@NonNull String name, @CheckForNull String defaul 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 1e2227e303c0c..2830e9128eadd 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 ddc1a644905b6..bcf524b428126 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 TimeSeries(float initialValue, float decay, int historySize) { * 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 7af3a732b3f0d..66f3bc7d4a2e8 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 202e9b79014f3..00a2633df6309 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 dfac20cb07808..c4084b83b4bd2 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 d95ac4a680e11..5e7b16ee66df1 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 static ExtensionList all() { /** * 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 55f28f74b5e69..0d8979437646d 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 ecf3ff26402f5..273a6903efb29 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 498c33c39d355..c1af0fe387d89 100644 --- a/core/src/main/java/hudson/model/TransientViewActionFactory.java +++ b/core/src/main/java/hudson/model/TransientViewActionFactory.java @@ -12,27 +12,27 @@ */ 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 bb5a7b6b5f175..b3ebdc2c3bc49 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 2a9302b9081e8..27900962d1a76 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 UpdateCenter() { */ @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 static UpdateCenter createUpdateCenter(@CheckForNull UpdateCenterConfigur 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 Api getApi() { * @see UpdateCenterConfiguration */ public void configure(UpdateCenterConfiguration config) { - if (config!=null) { + if (config != null) { this.config = config; } } @@ -354,7 +355,7 @@ public List getJobs() { 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 InstallationJob getJob(Plugin plugin) { 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 HttpResponse doConnectionStatus(StaplerRequest request) { 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 HttpResponse doConnectionStatus(StaplerRequest request) { 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 HttpResponse doConnectionStatus(StaplerRequest request) { @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 synchronized void persistInstallStatus() { 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 synchronized void persistInstallStatus() { 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 HudsonUpgradeJob getHudsonJob() { Collections.reverse(jobList); for (UpdateCenterJob job : jobList) if (job instanceof HudsonUpgradeJob) - return (HudsonUpgradeJob)job; + return (HudsonUpgradeJob) job; return null; } @@ -570,7 +571,7 @@ public boolean isSiteDataReady() { /** * 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 UpdateSite getSite(String id) { 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 UpdateSite getById(String id) { 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 String getDefaultBaseUrl() { 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 @@ private boolean checkMinVersion(@CheckForNull Plugin p, @CheckForNull VersionNum 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 boolean isDowngradable() { @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 String getBackupVersion() { } } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to read backup version ", e); - return null;} + return null; + } } @@ -924,12 +926,12 @@ public String getSearchUrl() { */ @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 synchronized void save() { */ 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 @@ protected UpdateSite createDefaultUpdateSite() { } 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 List getAvailables() { 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 PluginEntry[] getCategorizedAvailables() { @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 static String getCategoryDisplayName(String category) { } 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 List getUpdates() { @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 List getPluginsWithUnavailableUpdates() { * @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 boolean isActivated() { 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 File download(DownloadJob job, URL src) throws IOException { 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 File download(DownloadJob job, URL src) throws IOException { 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 File download(DownloadJob job, URL src) throws IOException { 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 File download(DownloadJob job, URL src) throws IOException { } } } 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 File download(DownloadJob job, URL src) throws IOException { // 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 @@ private void testConnection(URL url) throws IOException { 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 @@ private void testConnection(URL url) throws IOException { } 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 String getType() { * {@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 RestartJenkinsJob extends UpdateCenterJob { /** * Immutable state of this job. */ - @Exported(inline=true) + @Exported(inline = true) public volatile RestartJenkinsJobStatus status = new RestartJenkinsJob.Pending(); /** @@ -1599,7 +1601,7 @@ public class Canceled extends RestartJenkinsJobStatus { * 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 void run() { 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 void run() { 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 void run() { error = e; } - if(internetCheck != null) { + if (internetCheck != null) { try { // Wait for internet check to complete internetCheck.get(); @@ -1675,7 +1677,7 @@ public void run() { } 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 Plugin getPlugin() { public void run() { try { PluginWrapper installed = plugin.getInstalled(); - synchronized(installed) { + synchronized (installed) { if (!installed.isEnabled()) { try { installed.enable(); @@ -1728,13 +1730,13 @@ public void run() { } } } - } 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 NoOpJob extends EnableJob { 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 void run() { @Restricted(NoExternalUse.class) /*package*/ interface WithComputedChecksums { String getComputedSHA1(); + String getComputedSHA256(); + String getComputedSHA512(); } @@ -1768,7 +1773,7 @@ public abstract class DownloadJob extends UpdateCenterJob implements WithCompute /** * 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 @@ protected DownloadJob(UpdateSite site, Authentication authentication) { @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 void run() { 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 @@ protected void _run() throws IOException, InstallationStatus { * 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 long getContentLength() { @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 InstallationJob extends DownloadJob { */ @Deprecated public InstallationJob(Plugin plugin, UpdateSite site, Authentication auth) { - this(plugin,site,auth,false); + this(plugin, site, auth, false); } /** @@ -2199,7 +2206,7 @@ public void _run() throws IOException, InstallationStatus { // 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 void _run() throws IOException, InstallationStatus { } 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 void _run() throws IOException, InstallationStatus { * @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 @@ protected boolean wasInstalled() { 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 @@ protected void onSuccess() { @Override public String toString() { - return super.toString()+"[plugin="+plugin.title+"]"; + return super.toString() + "[plugin=" + plugin.title + "]"; } /** @@ -2352,6 +2359,7 @@ public class Failure extends CompleteBatchJobStatus { Failure(Throwable problemStackTrace) { this.problemStackTrace = problemStackTrace; } + public final Throwable problemStackTrace; } @@ -2391,7 +2399,7 @@ protected URL getURL() throws MalformedURLException { 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 String getDisplayName() { @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 @@ protected void onSuccess() { @Override public String toString() { - return super.toString()+"[plugin="+plugin.title+"]"; + return super.toString() + "[plugin=" + plugin.title + "]"; } } @@ -2538,22 +2546,24 @@ protected File getDestination() { 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 @@ protected void replace(File dst, File src) throws IOException { 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 @@ private PluginEntry(Plugin p, String c) { @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 int hashCode() { * * 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 Object getTarget() { * 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 53865761eb163..e5b7bb3f12283 100644 --- a/core/src/main/java/hudson/model/UpdateSite.java +++ b/core/src/main/java/hudson/model/UpdateSite.java @@ -238,7 +238,7 @@ private FormValidation updateData(String json, boolean signatureCheck) 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 @@ protected JSONSignatureValidator getJsonSignatureValidator(@CheckForNull String * 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 @@ boolean hasUnparsedData() { */ 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 JSONObject getJSONObject() { 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 List getAvailables() { @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 Api getApi() { @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 String getConnectionCheckUrl() { */ private TextFile getDataFile() { return new TextFile(new File(Jenkins.get().getRootDir(), - "updates/" + getId()+".json")); + "updates/" + getId() + ".json")); } /** @@ -457,12 +457,12 @@ private TextFile getDataFile() { @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 List getUpdates() { @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 final class Data { /** * 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 final class Data { 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 final class Data { } } - 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 final class Data { } } - connectionCheckUrl = (String)o.get("connectionCheckUrl"); + connectionCheckUrl = (String) o.get("connectionCheckUrl"); } /** @@ -879,6 +879,7 @@ public static final class Deprecation { * 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 boolean isRelevantToVersion(@NonNull VersionNumber version) { } 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 final class Plugin extends Entry { * 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 final class Plugin extends Entry { @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 Plugin(String sourceId, JSONObject o) { } 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 UpdateSite.Deprecation getDeprecation() { public String getDisplayName() { String displayName; - if(title!=null) + if (title != null) displayName = title; else displayName = name; @@ -1337,7 +1338,7 @@ public boolean isCompatibleWithInstalledVersion() { 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 List getNeededDependencies() { // 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 @@ else if (!current.isEnabled()) { } } - 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 @@ else if (!current.isEnabled()) { 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 VersionNumber getNeededDependenciesRequiredCore() { } 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 VersionNumber getNeededDependenciesMinimumJavaVersion() { } 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 boolean isNeededDependenciesForNewerJenkins(PluginManager.MetadataCache c * @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 Set getWarnings() { 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 Future deploy(boolean dynamicLoad, @CheckForNull UUID co } } 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 Future deployBackup() { /** * Making the installation web bound. */ + @RequirePOST public HttpResponse doInstall() throws IOException { deploy(false); @@ -1725,6 +1727,6 @@ public HttpResponse doDowngrade() throws IOException { // 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 1b57d72824034..0a13c0983b160 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 UsageStatistics(String keyImage) { */ 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 @@ private RSAPublicKey getKey() { 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 String getStatData() throws IOException { 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 String getStatData() throws IOException { 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 boolean configure(StaplerRequest req, JSONObject json) throws FormExcepti 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 CombinedCipherOutputStream(OutputStream out, Cipher asym, String algorith // 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 CombinedCipherInputStream(InputStream in, Cipher asym, String algorithm, 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 @@ private static String getKeyAlgorithm(String algorithm) { 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 @@ private static Cipher toCipher(RSAKey key, int mode) throws GeneralSecurityExcep 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 f88be4dd7ba23..bc2a86138d1ae 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 @@ private void removeNullsThatFailedToLoad() { 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 static void clear() { 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 d84042a589066..93e6a03fd0f5c 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 b3e42d394ef6e..4af152b6acb48 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 2f521b31f401d..cb840e40752da 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 f0d7ce5b3ed74..a9b9dbae7acd9 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 UserPropertyDescriptor getDescriptor() { /** * Returns all the registered {@link UserPropertyDescriptor}s. */ - public static DescriptorExtensionList 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 a29ab777c8806..22e05ea59afff 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 b743d91834e48..c2c2c6b73bfa7 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 @@ protected View(String name, ViewGroup owner) { * 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 Collection getAllItems() { 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 final TopLevelItem getJob(String name) { * * @see #rename(String) */ - @Exported(visibility=2,name="name") + @Exported(visibility = 2, name = "name") @NonNull public String getViewName() { return name; @@ -252,13 +253,13 @@ public String getViewName() { * 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 synchronized void setDescription(String description) { * 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 void save() throws IOException { * 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 Indenter getIndenter() { * 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 @@ private boolean filterQueueItemTest(Queue.Item item, Collection vi } // 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 List getApproximateQueueItemsQuickly() { * 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 String getUrl() { * 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 void updateTransientActions() {} 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 Object getDynamic(String token) { /** * 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 ACL getACL() { @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 static final class UserInfo implements Comparable { /** * 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 Calendar getLastChange() { @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 Job getJob() { * 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 int compareTo(UserInfo that) { } private long ordinal() { - if(lastChange==null) return 0; + if (lastChange == null) return 0; return lastChange.getTimeInMillis(); } } @@ -732,12 +733,12 @@ public static final class People { 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 People(View parent) { 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 @@ else if (info.getLastChange().before(r.getTimestamp())) { 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 static boolean isApplicable(Collection items) { 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 static final class AsynchPeople extends ProgressiveRendering { // JENKINS 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 AsynchPeople(View parent) { @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 AsynchPeople(View parent) { 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 final class People { } 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 @@ void addDisplayNamesToSearchIndex(SearchIndexBuilder sib, Collection() {// 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 SearchIndexBuilder makeSearchIndex() { * 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 synchronized void doSubmitDescription( StaplerRequest req, StaplerRespons * 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 final synchronized void doConfigSubmit( StaplerRequest req, StaplerRespon save(); - FormApply.success("../" + Util.rawEncode(name)).generateResponse(req,rsp,this); + FormApply.success("../" + Util.rawEncode(name)).generateResponse(req, rsp, this); } /** @@ -1049,7 +1052,7 @@ public synchronized void doDoDelete(StaplerRequest req, StaplerResponse rsp) thr owner.deleteView(this); - rsp.sendRedirect2(req.getContextPath()+"/" + owner.getUrl()); + rsp.sendRedirect2(req.getContextPath() + "/" + owner.getUrl()); } @@ -1063,7 +1066,7 @@ public synchronized void doDoDelete(StaplerRequest req, StaplerResponse rsp) thr * @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 Categories doItemCategories(StaplerRequest req, StaplerResponse rsp, @Que 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 BuildTimelineWidget getTimeline() { 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 void updateByXml(Source source) throws IOException { // 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 void updateByXml(Source source) throws IOException { 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 void updateByXml(Source source) throws IOException { 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 ModelObjectWithContextMenu.ContextMenu doChildrenContextMenu(StaplerReque /** * 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 static List allInstantiable() { 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 static View create(StaplerRequest req, StaplerResponse rsp, ViewGroup own 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 static View create(StaplerRequest req, StaplerResponse rsp, ViewGroup own 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 @@ private static View copy(StaplerRequest req, ViewGroup owner, String name) throw 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 static View createViewFromXML(String name, InputStream xml) throws IOExce 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 PropertyList() {// needed for XStream deserialization } 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 3b31a2f710635..7a77f4e553544 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 boolean isInstantiable() { * 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 @@ protected FormValidation checkDisplayName(@NonNull View view, @CheckForNull Stri // 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 d0e9f95cdbb9d..1072f394322be 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 @@ default ItemGroup getItemGroup() { 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 9505e47cb5c6f..0494758071528 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 View getView(@CheckForNull String name) { // 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 Collection getViews() { @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 1a69809e154b6..5e8227450bde5 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 @@ * * @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 @@ static synchronized void interruptReloadThread() { */ @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 void onLoad(ItemGroup parent, String name) throws IOExcep } @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 _getRuns() { } reloadQueue = reloadThread.reloadQueue; } - synchronized(reloadQueue) { + synchronized (reloadQueue) { reloadQueue.add(this); reloadQueue.notify(); } @@ -150,7 +151,7 @@ private void _reload() { 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 @@ private void _reload() { 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 @@ private ReloadThread() { } 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 void 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 04d3fc4fd7674..31ad3078d449e 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 ViewPropertyDescriptor getDescriptor() { 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 da0e0bbb516c5..a8d9b40082a05 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 e73d1976a47cf..00ef65c4a92e9 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 @@ private boolean shouldBeDeleted(@NonNull TopLevelItem item, FilePath dir, @NonNu // 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 @@ private boolean shouldBeDeleted(@NonNull TopLevelItem item, FilePath dir, @NonNu * 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 1fce5b907d177..4a6089164a16b 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.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 cca9b29ed753d..5c56d296a3acb 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 @@ /** * 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 boolean matches(VariableResolver resolver) { @Override public V accept(LabelVisitor visitor, P param) { - return visitor.onAtom(this,param); + return visitor.onAtom(this, param); } @Override @@ -176,7 +177,7 @@ public LabelOperatorPrecedence precedence() { } /*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 void save() throws IOException { 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 List getApplicablePropertyDescriptors() { * 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 @@ private boolean isInvalidName() { */ @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 static boolean needsEscape(String name) { try { Jenkins.checkGoodName(name); // additional restricted chars - for( int i=0; i getActions(LabelAtom atom) { /** * Lists up all the registered {@link LabelAtomPropertyDescriptor}s in the system. */ - public static DescriptorExtensionList 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 b9b9312939f1c..3c45b2e0a76e4 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 @@ * *

    * 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 00a81c2715557..55a34a010e14f 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 @@ /** * Boolean expression of labels. - * + * * @author Kohsuke Kawaguchi * @since 1.372 */ @@ -62,7 +63,7 @@ public static class Not extends LabelExpression { 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 static class Paren extends LabelExpression { public final Label base; public Paren(Label base) { - super('('+base.getExpression()+')'); + super('(' + base.getExpression() + ')'); this.base = base; } @@ -113,13 +114,13 @@ public LabelOperatorPrecedence precedence() { * 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 @@ protected Binary(Label lhs, Label rhs, LabelOperatorPrecedence op) { } 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 @@ private static String combine(Label lhs, Label rhs, LabelOperatorPrecedence op) */ @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 a917d97b0563c..b70f0036af76e 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 fcb2f9b58eab6..0fb8114f32c0c 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 @@ * @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 13522ef500a65..aef431c3207b4 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 static void fireLocationChange(final Item rootItem, final String oldFullN } 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 148f419908399..0ecbf725c792d 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 @@ * *

    * 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 @@ protected RunListener(Class targetType) { 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 void onStarted(R r, TaskListener listener) {} * 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 02cd62e34038e..afb93bf2c7ab9 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 @@ * 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 void onCheckout(Run build, SCM scm, FilePath workspace, TaskListener *

    * 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 void onCheckout(Run build, SCM scm, FilePath workspace, TaskListener * * @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 48fa919117909..341f91ac79b88 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 void onBeforePolling( AbstractProject project, TaskListener listene * @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 void onPollingSuccess( AbstractProject project, TaskListener listen * 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 5df4f298284d8..51cac4861a578 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 void unregister() { 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 486bd4c96b3a9..99ac92828bb5e 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 void sortBuildableItems(List buildables) { */ @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 b8de10e02ce1e..8888eaab72c93 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 9aad22d4ddc64..a991948830851 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 String getShortDescription() { 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 String getShortDescription() { 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 3da70ed2aab4c..396133fe4d336 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 @@ * @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 dff6a610a283b..4b368a2b9d15d 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 6009b2fe700ce..f6bba013f2cc4 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 Executable waitForStart() throws InterruptedException, ExecutionException 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 a46ef6f223294..1d3046d09288c 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 FutureLoad(long startTime, long duration, int numExecutors) { @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 c8b3619589405..3479c0599c387 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 @@ */ 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 @@ public synchronized void synchronize() throws InterruptedException { 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 Iterable predict(MappingWorksheet plan, final Computer comput 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 f6f5edb35df90..54829ec0dac20 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 @@ private ExecutorChunk(List base, int index) { * 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() base, int index) { Node lbo = base.get(0).getLastBuiltOn(); for (ExecutorChunk ec : executors) { - if (ec.node==lbo) { + if (ec.node == lbo) { lastBuiltOn = ec; return; } @@ -206,7 +207,7 @@ private WorkChunk(List base, int index) { private Label getAssignedLabel(SubTask task) { for (LabelAssignmentAction laa : item.getActions(LabelAssignmentAction.class)) { Label l = laa.getAssignedLabel(task); - if (l!=null) return l; + if (l != null) return l; } return task.getAssignedLabel(); } @@ -263,10 +264,10 @@ public int size() { /** * Returns the assignment as a map. */ - public Map 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 Map toMap() { */ public boolean isPartiallyValid() { int[] used = new int[executors.size()]; - for (int i=0; i ec.capacity()) @@ -291,7 +292,7 @@ public boolean isPartiallyValid() { */ 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 void execute(WorkUnitContext wuc) { 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 MappingWorksheet(BuildableItem item, List offers, 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 offers, for (List 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 MappingWorksheet(BuildableItem item, List offers, // 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 a6cd487a767c1..939d1c6fdff5a 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 static ExtensionList all() { * * {@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 eaa0ec18f34ba..9b51bedb36a8d 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 91ef54ddb17a9..ed43b651917e1 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 final boolean isAccepted() { 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 80d4528efcc36..98c9e0bacbafe 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 ccd92ec79a45b..72bfb80a397a4 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 @@ * @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 5fdadcfb2f746..fe007200f1b4f 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 static hudson.model.Item getItemOf(@NonNull SubTask t) { } 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 1d70c03e26de1..ee7c4d54deef2 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 @@ Long fit(long start, long duration, int n) { 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 8aed254e31eeb..8c2924b49ba5c 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 void setExecutable(Executable executable) { * 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 1b534855270f2..31829ba7dd1f2 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 @@ protected void onCriteriaMet() { // 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 void synchronizeEnd(Queue.Executable executable, Throwable problems, long */ @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 void synchronizeEnd(Executor e, Queue.Executable executable, Throwable pr * 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 synchronized void abort(Throwable cause) { 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 842c9bed0ea76..8e46a37057187 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 @@ protected AbstractAsyncNodeMonitorDescriptor(Class clazz, /** * 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 @@ protected Map monitor() throws InterruptedException { * 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 @@ protected Map monitor() throws InterruptedException { 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 dce9ca3e14e1d..38230dd80f915 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 @@ protected AbstractDiskSpaceMonitor() { } 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 long getThresholdBytes() { @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 Object data(Computer c) { @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 11b11f55a33d6..4a2386c2a1b17 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 void doRun() { * whereas {@link IOException} is useful for indicating a hard error that needs to be * corrected. */ - protected abstract T monitor(Computer c) throws IOException,InterruptedException; + protected abstract T monitor(Computer c) throws IOException, InterruptedException; /** * Performs monitoring across the board. @@ -142,20 +143,20 @@ public void doRun() { * @return * For all the computers, report the monitored values. */ - protected Map 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 @@ protected Map monitor() throws InterruptedException { * If no data is available, a background task to collect data will be started. */ public T get(Computer c) { - if(record==null || !record.data.containsKey(c)) { + if (record == null || !record.data.containsKey(c)) { // if we don't have the data, schedule the check now triggerUpdate(); return null; @@ -180,20 +181,20 @@ public T get(Computer c) { * Is the monitoring activity currently in progress? */ private synchronized boolean isInProgress() { - return inProgress !=null && inProgress.isAlive(); + return inProgress != null && inProgress.isAlive(); } /** * The timestamp that indicates when the last round of the monitoring has completed. */ public long getTimestamp() { - return record==null ? 0L : record.timestamp; + return record == null ? 0L : record.timestamp; } public String getTimestampString() { - if (record==null) + if (record == null) return Messages.AbstractNodeMonitorDescriptor_NoDataYet(); - return Util.getTimeSpanString(System.currentTimeMillis()-record.timestamp); + return Util.getTimeSpanString(System.currentTimeMillis() - record.timestamp); } /** @@ -201,22 +202,22 @@ public String getTimestampString() { */ public boolean isIgnored() { NodeMonitor m = ComputerSet.getMonitors().get(this); - return m==null || m.isIgnored(); + return m == null || m.isIgnored(); } /** * Utility method to mark the computer online for derived classes. - * - * @return true + * + * @return true * if the node was actually taken online by this act (as opposed to us deciding not to do it, * or the computer was already online.) */ protected boolean markOnline(Computer c) { - if(isIgnored() || c.isOnline()) return false; // noop - c.setTemporarilyOffline(false,null); + if (isIgnored() || c.isOnline()) return false; // noop + c.setTemporarilyOffline(false, null); return true; } - + /** * Utility method to mark the computer offline for derived classes. * @@ -225,13 +226,13 @@ protected boolean markOnline(Computer c) { * or the computer already marked offline.) */ protected boolean markOffline(Computer c, OfflineCause oc) { - if(isIgnored() || c.isTemporarilyOffline()) return false; // noop + if (isIgnored() || c.isTemporarilyOffline()) return false; // noop c.setTemporarilyOffline(true, oc); // notify the admin MonitorMarkedNodeOffline no = AdministrativeMonitor.all().get(MonitorMarkedNodeOffline.class); - if(no!=null) + if (no != null) no.active = true; return true; } @@ -242,7 +243,7 @@ protected boolean markOffline(Computer c, OfflineCause oc) { */ @Deprecated protected boolean markOffline(Computer c) { - return markOffline(c,null); + return markOffline(c, null); } /** @@ -288,12 +289,12 @@ private final class Record extends Thread { /** * Last computed monitoring result. */ - private /*final*/ Map 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 void run() { try { long startTime = System.currentTimeMillis(); String oldName = getName(); - data=monitor(); + data = monitor(); setName(oldName); timestamp = System.currentTimeMillis(); record = this; - LOGGER.log(Level.FINE, "Node monitoring {0} completed in {1}ms", new Object[] {getDisplayName(), System.currentTimeMillis()-startTime}); + LOGGER.log(Level.FINE, "Node monitoring {0} completed in {1}ms", new Object[] {getDisplayName(), System.currentTimeMillis() - startTime}); } catch (InterruptedException x) { // interrupted by new one, fine } catch (Throwable t) { - LOGGER.log(Level.WARNING, "Unexpected node monitoring termination: "+getDisplayName(),t); + LOGGER.log(Level.WARNING, "Unexpected node monitoring termination: " + getDisplayName(), t); } finally { - synchronized(AbstractNodeMonitorDescriptor.this) { - if (inProgress==this) + synchronized (AbstractNodeMonitorDescriptor.this) { + if (inProgress == this) inProgress = null; } } diff --git a/core/src/main/java/hudson/node_monitors/ArchitectureMonitor.java b/core/src/main/java/hudson/node_monitors/ArchitectureMonitor.java index fe96c807bc1c9..b7e88d8e0eefc 100644 --- a/core/src/main/java/hudson/node_monitors/ArchitectureMonitor.java +++ b/core/src/main/java/hudson/node_monitors/ArchitectureMonitor.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; @@ -59,12 +60,12 @@ public NodeMonitor newInstance(StaplerRequest req, JSONObject formData) throws F /** * Obtains the string that represents the architecture. */ - private static class GetArchTask extends MasterToSlaveCallable { + 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 fdbca6b751d74..6c7dc54f343d7 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 DescriptorImpl() { } @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 21d531a9796ba..bcf96ba02704b 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 @@ */ 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 String getDisplayName() { 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 ed68ff4576ce6..076c2b281c7f1 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 static final class DiskSpace extends MonitorOfflineCause implements Seria private final String path; @Exported public final long size; - + private boolean triggered; private Class trigger; @@ -69,12 +70,12 @@ public DiskSpace(String path, long size) { @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 long getFreeSize() { */ 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 String getGbLeft() { */ 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 Class getTrigger() { 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 21cec64d9a1e3..220774a458ed0 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 3c40df208aabe..7bb30048d872f 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 9b11988dc4f77..eb5a9459c33d6 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 @@ *

    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 void setIgnored(boolean ignored) { /** * Returns all the registered {@link NodeMonitor} descriptors. */ - public static DescriptorExtensionList> 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 d0b36fb978905..10238deb3352a 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 void run() { */ @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 3ecfabbdaac94..8932941432c1b 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 @@ protected Map monitor() throws InterruptedException { 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 NodeMonitor newInstance(StaplerRequest req, JSONObject formData) throws F } }; - 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 @@ private Step1(Data cur) { @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 @@ private Object writeReplace() { 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 @@ private static final class Step2 extends MasterToSlaveCallable=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 @@ private int failureCount() { */ @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 boolean hasTooManyTimeouts() { @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 65b0083c754c9..286274b42fe58 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 String toHtml(MemoryUsage usage) { } 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 NodeMonitor newInstance(StaplerRequest req, JSONObject formData) throws F /** * 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 db814f99bed99..d6b8a4f23359e 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 @@ */ 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 String getDisplayName() { } @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 @@ protected Callable createCallable(Computer c) { 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 DiskSpace invoke(File f, VirtualChannel channel) throws IOException { // 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 c9f40ac31b207..ba1c9aecb9578 100644 --- a/core/src/main/java/hudson/os/PosixAPI.java +++ b/core/src/main/java/hudson/os/PosixAPI.java @@ -12,7 +12,7 @@ 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 static synchronized POSIX jnr() { @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 6a373cd53e043..185110d83781d 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; @@ -42,6 +43,7 @@ import java.io.File; import java.io.IOException; import java.io.PrintStream; +import java.nio.charset.Charset; import java.util.Collections; /** @@ -71,36 +73,36 @@ private SU() { // not meant to be instantiated * 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() { return "sudo"; } - @SuppressFBWarnings(value = {"COMMAND_INJECTION", "DM_DEFAULT_ENCODING"}, justification = "TODO needs triage") + @SuppressFBWarnings(value = "COMMAND_INJECTION", 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(); // TODO: use -p to detect prompt // TODO: detect if the password didn't work - try (PrintStream ps = new PrintStream(p.getOutputStream())) { + try (PrintStream ps = new PrintStream(p.getOutputStream(), false, Charset.defaultCharset().name())) { ps.println(rootPassword); ps.println(rootPassword); ps.println(rootPassword); } 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 +118,7 @@ protected Process sudoWithPass(ArgumentListBuilder args) throws IOException { } // 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 +133,7 @@ private static LocalChannel newLocalChannel() { /** * 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 +152,14 @@ private abstract static class UnixSu { 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 +173,7 @@ VirtualChannel start(TaskListener listener, String rootPassword) throws IOExcept // 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 e846636d6fed8..36a7131011773 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 @@ */ 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 @@ protected BaseParser(TokenStream tokenStream, int i) { } public void setHash(Hash hash) { - if (hash==null) hash = Hash.zero(); + if (hash == null) hash = Hash.zero(); this.hash = hash; } @@ -72,8 +73,8 @@ protected long doRange(int start, int end, int step, int field) throws ANTLRExce 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 @@ protected long doRange(int start, int end, int step, int field) throws ANTLRExce 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 @@ protected long doRange( int step, int field ) throws ANTLRException { */ 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 @@ protected long doHash(int s, int e, int step, int field) throws ANTLRException { } 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 @@ private int ceil(CronTab c, int n) { * 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 Calendar ceil(Calendar cal) { } 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 Calendar floor(Calendar cal) { } 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 Calendar floor(Calendar cal) { } 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 @@ private String toString(String key, long bit) { 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 5273629d8b353..7a1b4760ff751 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 CronTabList(Collection tabs) { */ 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 synchronized boolean check(Calendar cal) { 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 String checkSanity() { } 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 static CronTabList create(@NonNull String format, Hash hash) throws ANTLR 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 static CronTabList create(@NonNull String format, Hash hash) throws ANTLR 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 static CronTabList create(@NonNull String format, Hash hash) throws ANTLR } 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 432d3b363069d..eb69cfda04fb5 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 @@ protected Permission getPermission() { /** * @since 1.568 */ - public Run getRun() { + public Run getRun() { return run; } @@ -108,11 +109,11 @@ protected ACL getACL() { } 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 cd14a15c2808c..f851704ba25de 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 @@ public RepositoryBrowser get() { return cache; } int g = d.getGeneration(); - if(g!=cacheGeneration) { + if (g != cacheGeneration) { cacheGeneration = g; cache = infer(); } @@ -76,10 +77,10 @@ public RepositoryBrowser get() { * 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 daf129aa206fb..c76b3f4d0d158 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 void annotate(Run build, ChangeLogSet.Entry change, MarkupText text) } @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 57062a996bb03..f38f836607155 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 0b0d9c1d0e994..a0c4a4c9cd79c 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 @@ * * @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 @@ protected ChangeLogSet(Run run, RepositoryBrowser browser) { 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 @@ private static RepositoryBrowser browserFromBuild(AbstractBuild build) { /** * @since 1.568 */ - public Run getRun() { + public Run getRun() { return run; } @@ -101,7 +103,7 @@ public RepositoryBrowser getBrowser() { 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 static ChangeLogSet createEmpty(AbstractBui return createEmpty((Run) build); } - @ExportedBean(defaultVisibility=999) + @ExportedBean(defaultVisibility = 999) public abstract static class Entry { private ChangeLogSet parent; @@ -216,29 +218,29 @@ public long getTimestamp() { */ @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 String getMsgAnnotated() { 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 String getMsgAnnotated() { 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 interface AffectedFile { * @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 178a39a008c22..7672b09db2e4b 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 String toExportedObject() { 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 1ab09948bd909..2832ede7c4b01 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 @@ * @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 777db3759e474..8d77816886554 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 NullSCM() {} 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 7939fb579b7a2..bfcb135a63b94 100644 --- a/core/src/main/java/hudson/scm/PollingResult.java +++ b/core/src/main/java/hudson/scm/PollingResult.java @@ -6,7 +6,7 @@ import hudson.Launcher; import hudson.model.AbstractProject; import hudson.model.TaskListener; -import java.io.Serializable; +import org.jenkinsci.remoting.SerializableOnlyOverRemoting; /** * Immutable object that represents the result of {@linkplain SCM#poll(AbstractProject, Launcher, FilePath, TaskListener, SCMRevisionState) SCM polling}. @@ -18,7 +18,7 @@ * @author Kohsuke Kawaguchi * @since 1.345 */ -public final class PollingResult implements Serializable { +public final class PollingResult implements SerializableOnlyOverRemoting { /** * Baseline of the comparison. * (This comes from either the workspace, or from the remote repository as of the last polling. @@ -79,14 +79,14 @@ public enum Change { } 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 dbeb7390ba4a8..05b095b02bceb 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 @@ /** * 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 @@ protected static URL normalizeToEndWithSlash(URL url) { /** * 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 cc907e72f73e7..0a1e28d1a1529 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 static List>> filter(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 @@ T createInstance(Class type, StaplerRequest req, String fieldName) throws For */ 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 1e2fdde83ec83..2cadc9344d5d6 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 String getType() { * @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 String getType() { public boolean supportsPolling() { return true; } - + /** * Returns true if this SCM requires a checked out workspace for doing polling. * @@ -192,7 +193,7 @@ public boolean supportsPolling() { * @since 1.196 */ public boolean requiresWorkspaceForPolling() { - return true; + return true; } /** @@ -231,10 +232,10 @@ public boolean requiresWorkspaceForPolling() { * @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 boolean processWorkspaceBeforeDeletion(@NonNull Job project, @NonNul } @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 boolean processWorkspaceBeforeDeletion(AbstractProject project, File * 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 boolean pollChanges(AbstractProject project, Launcher launcher, File *

    * 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 boolean pollChanges(AbstractProject project, Launcher launcher, File * * @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 boolean pollChanges(AbstractProject project, Launcher launcher, File } @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 SCMRevisionState calcRevisionsFromBuild(AbstractBuild build, Launche 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 SCMRevisionState _calcRevisionsFromBuild(AbstractBuild build, Launc * 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 PollingResult compareRemoteRevisionWith( } @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 final PollingResult poll(AbstractProject project, Launcher launcher, 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 @@ private boolean is1_346OrLater() { 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 void checkout( } @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 boolean checkout(AbstractBuild build, Launcher launcher, FilePath wo * 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 void postCheckout(AbstractBuild build, Launcher launcher, FilePath w * * @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 void buildEnvironment(@NonNull Run build, @NonNull Map 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 FilePath getModuleRoot(FilePath workspace, AbstractBuild build) { // 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 FilePath getModuleRoot(FilePath workspace) { * @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 @@ protected final boolean createEmptyChangeLog(File changelogFile, BuildListener l */ 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 @@ protected final String nullify(String s) { * 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 static DescriptorExtensionList> all() { * @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 f7d61f1f73233..b9a600a9a3245 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 void incrementGeneration() { 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 boolean isApplicable(AbstractProject project) { * 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 56c9d405e4db8..a8fd4ddc4dc11 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 @@ /** * List of all installed SCMs. - * + * * @author Kohsuke Kawaguchi */ public class SCMS { @@ -67,7 +68,7 @@ public static SCM parseSCM(StaplerRequest req, AbstractProject target) throws Fo */ @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 04dffed3e15c6..06d933aa7ef34 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 QueryBuilder(String s) { } 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 35c4e8f11ca1a..b6bb423d40f42 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 @@ /** * {@link SearchIndex} built on a {@link Map}. - * + * * @author Kohsuke Kawaguchi */ public abstract class CollectionSearchIndex implements SearchIndex { @@ -55,21 +56,21 @@ protected Iterable allAsIterable() { @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 7c44604251e88..dfe413fbf7377 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 dc40d30e78842..dc214892ac008 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 @@ * @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 @@ private ParsedQuickSilver(Class clazz) { 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 @@ private ParsedQuickSilver(Class clazz) { * 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 @@ private String splitName(String url) { 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 @@ public String getSearchUrl() { @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 43d71b9a61bd7..ad214694f5efc 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 37971a7ee7313..9c9aac5e72d6d 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 void doIndex(StaplerRequest req, StaplerResponse rsp) throws IOException, // 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 void doSuggest(StaplerRequest req, StaplerResponse rsp, @QueryParameter S 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 SearchResult getSuggestions(StaplerRequest req, String query) { 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 SearchResult getSuggestions(StaplerRequest req, String query) { 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 static class Result { 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 @@ void find(SearchIndex index, String token, List result) { * 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 static SuggestedItem find(SearchIndex index, String query) { */ 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 static List suggest(SearchIndex index, final String tokenL */ 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 @@ class Tag implements Comparable{ 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 int compareTo(Tag that) { 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 @@ static final class TokenList { 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 List subSequence(final int start) { @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 int size() { @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 String toString() { 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 @@ private static List find(Mode m, SearchIndex index, String tokenL 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 b907e02884077..4cf082598b102 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 SearchIndexBuilder addAllAnnotations(SearchableModelObject o) { * 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 SearchIndexBuilder add(SearchItem item) { } 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 SearchIndexBuilder add(SearchIndexBuilder index) { 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 3da63411ed060..02b2921b9741d 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 0f9a2d63dd3da..3afb24fc46fe3 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 @@ */ 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 ebc16348d980e..52bdcc47a587b 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 31e5956ce4ed7..86dbc36b5fe34 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 SuggestedItem(SuggestedItem parent, SearchItem item) { } 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 @@ private void getPath(StringBuilder buf) { * 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 @@ private static SuggestedItem build(SearchableModelObject searchContext, Item top */ 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 6a7a625924f29..d32deb5edfe68 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 @@ */ 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 static SearchIndex combine(SearchIndex... sets) { 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 UnionSearchIndex(SearchIndex lhs, SearchIndex rhs) { @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 7e5d704fd7470..50813ce3c79b4 100644 --- a/core/src/main/java/hudson/search/UserSearchProperty.java +++ b/core/src/main/java/hudson/search/UserSearchProperty.java @@ -23,8 +23,8 @@ public UserSearchProperty(boolean insensitiveSearch) { 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 static boolean isCaseInsensitive(){ 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 97980fa0a578b..039820ef22f3a 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 final void checkPermission(@NonNull Permission p) { 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 final void checkCreatePermission(@NonNull ItemGroup c, } 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 final void checkCreatePermission(@NonNull ItemGroup c, * 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 String toString() { */ 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 String toString() { * 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 String toString() { /** * 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 static void impersonate(@NonNull org.acegisecurity.Authentication auth, @ * @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 static V impersonate2(Authentication auth, Callab * @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 e5b49ff324bee..9873e65f37629 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 64d579a8c4ab6..055c7151a94a6 100644 --- a/core/src/main/java/hudson/security/AbstractPasswordBasedSecurityRealm.java +++ b/core/src/main/java/hudson/security/AbstractPasswordBasedSecurityRealm.java @@ -180,7 +180,7 @@ protected void additionalAuthenticationChecks(UserDetails userDetails, UsernameP @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 a8c8a93a8b57f..b0cb2c2a9b82b 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 cdb778473ab44..00daee721251b 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 755def42aee6f..82f5d50428cec 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 AccessDeniedException3(Throwable t, Authentication authentication, Permis * 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 void reportAsHeaders(HttpServletResponse rsp) { * 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 92c45b0f9fe94..68843cfddd16d 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 9e48891107780..7de8cb39ab5ec 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 6764550ab722f..2714ec8eba635 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 @@ * 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 84c8599abdf8a..e1ce1596b74ac 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 @@ * 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 5fd45efb0bb61..924c77e25cd5b 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 @@ *

  • * 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 void doFilter(ServletRequest request, ServletResponse response, FilterCha 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 void doFilter(ServletRequest request, ServletResponse response, FilterCha SecurityContextHolder.getContext().setAuthentication(new ContainerAuthentication(req)); } try { - chain.doFilter(request,response); + chain.doFilter(request, response); } finally { SecurityContextHolder.clearContext(); } @@ -129,18 +130,18 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha 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 void doFilter(ServletRequest request, ServletResponse response, FilterCha SecurityContextHolder.getContext().setAuthentication(auth); try { - chain.doFilter(request,response); + chain.doFilter(request, response); } finally { SecurityContextHolder.clearContext(); } @@ -157,24 +158,24 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha } - 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 b717a314f117b..faf9171300a78 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 void init(FilterConfig filterConfig) throws ServletException { } 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 void doFilter(ServletRequest request, ServletResponse response, final Fil 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 void doFilter(ServletRequest request, ServletResponse response) throws IO 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 1fd6d4c7400f9..3b64167c1401a 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 1a9c344af355c..be7bdc01ab623 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 be1efda827a74..2d176290d8bee 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 final User locateUser() { @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 User signin() throws UnclaimedIdentityException { */ 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 void addToCurrentUser() throws IOException { */ 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 void generateResponse(StaplerRequest req, StaplerResponse rsp, Object nod 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 void generateResponse(StaplerRequest req, StaplerResponse rsp, Object nod // 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 b7dfa881c3a92..0961b3a2d8e03 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 b30153ce8f90f..7dbb0ab670216 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 ACL getRootACL() { 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 void setAllowAnonymousRead(boolean allowAnonymousRead) { 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 17317d2dc61a8..710bb38265ca1 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 @@ */ @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 Category getCategory() { 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 boolean configure(StaplerRequest req, JSONObject json) throws FormExcepti 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 boolean configure(StaplerRequest req, JSONObject json) throws FormExcepti // 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 String getIconFileName() { public String getUrlName() { return "configureSecurity"; } - + @Override public Permission getRequiredPermission() { return Jenkins.SYSTEM_READ; @@ -200,7 +201,7 @@ public Permission getRequiredPermission() { 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 543074ef0e3ad..ae94f20a03927 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 51e3a980a9d36..786df5d72879b 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 bc9e9a01b70d6..da1a9bb26b14c 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 HudsonAuthenticationEntryPoint(String loginFormUrl) { @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 void commence(HttpServletRequest req, HttpServletResponse rsp, Authentica } 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 void commence(HttpServletRequest req, HttpServletResponse rsp, Authentica } 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 @@ private void printResponse(String loginForm, PrintWriter out) { "" + "" + "%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 static int getWin32FileAttributes(File file) throws IOException { 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 static boolean isJunctionOrSymlink(File file) throws IOException { 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 static File getTempDir() { 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 6c1a20d2a5bc8..2b75aac9f872b 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 @@ 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 cae66d6b10870..cd9e9c0a07bca 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 @@ 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 @@ private RegistryKey(int handle) { 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 @@ private byte[] getValue(String valueName) { 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 @@ private void check(int r) { */ 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 boolean valueExists(String name) { 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 Collection getSubKeys() { } 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 TreeMap getValues() { break; // not supported yet } break; - + default: check(result); } @@ -283,7 +284,7 @@ protected void finalize() throws Throwable { } 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 61302f8e5ddba..bca03457306df 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 @@ * @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 @@ protected List getFieldOrder() { "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 DUMMYUNIONNAME_union(Pointer hIcon_or_hMonitor) { } 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 8165a4f099ee5..2007167befa79 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 9aa47e7d079ed..695976d521c88 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 @@ 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 0f9f134f721ab..027fa144642c7 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 @@ 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 bcfd651676250..6935041796ff7 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 @@ 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 c3de2ebbfa4da..a5a14712fc32b 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 WinIOException(Throwable cause) { @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 0cd1184825f8c..196e2289d0ebd 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 Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext co 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 c353cf672c51d..d5821a5c0c952 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 boolean canConvert(Class type) { @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 08184ff504490..b8c3c183984ef 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 09d55c489b7bd..6a1481f9e85af 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 deea611a748b5..78d045ca123ca 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 Mapper lookupMapperOfType(Class type) { @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 SingleValueConverter getConverterFromItemType(String fieldName, Class typ @Deprecated @Override public String aliasForAttribute(Class definedIn, String fieldName) { - return delegate.aliasForAttribute(definedIn, fieldName); + return delegate.aliasForAttribute(definedIn, fieldName); } /** @@ -157,7 +158,7 @@ public String aliasForAttribute(Class definedIn, String fieldName) { @Deprecated @Override public String attributeForAlias(Class definedIn, String alias) { - return delegate.attributeForAlias(definedIn, alias); + return delegate.attributeForAlias(definedIn, alias); } /** @@ -166,7 +167,7 @@ public String attributeForAlias(Class definedIn, String alias) { @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 f0aa4436cfc62..5a48f0da6de81 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 String taskNoun(Object job) { 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 9ebc1e63599cf..d697552a68570 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 e9e9f56dbe114..6f697f96a86e9 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 89fe448d0e80e..b60939aae5eec 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 @@ * * @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 boolean configure(StaplerRequest req, JSONObject json) throws FormExcepti // 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 b6f581c154c23..b2ec060f09c3b 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 JobColumn() { } // 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 04696704a65dd..f1d7258e5b956 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 1c272b855f8bb..c31f3f9590a03 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 0844121e5dcb4..7dfd482eaab31 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 ebb5bc1bc9446..98571e8e9bf37 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 dcf2dd9b0d364..1796f4cc495c4 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 @@ private static List createDefaultInitialColumnList(List> @Override public MyViewsTabBarDescriptor getDescriptor() { - return (MyViewsTabBarDescriptor)super.getDescriptor(); + return (MyViewsTabBarDescriptor) super.getDescriptor(); } /** @@ -92,7 +93,7 @@ public List sort(@NonNull List views) { * * @author Kohsuke Kawaguchi */ - @Extension(ordinal=305) @Symbol("myView") + @Extension(ordinal = 305) @Symbol("myView") public static class GlobalConfigurationImpl extends GlobalConfiguration { public MyViewsTabBar getMyViewsTabBar() { return Jenkins.get().getMyViewsTabBar(); @@ -104,7 +105,7 @@ public boolean configure(StaplerRequest req, JSONObject json) throws FormExcepti Jenkins j = Jenkins.get(); if (json.has("myViewsTabBar")) { - j.setMyViewsTabBar(req.bindJSON(MyViewsTabBar.class,json.getJSONObject("myViewsTabBar"))); + j.setMyViewsTabBar(req.bindJSON(MyViewsTabBar.class, json.getJSONObject("myViewsTabBar"))); } else { j.setMyViewsTabBar(new DefaultMyViewsTabBar()); } diff --git a/core/src/main/java/hudson/views/MyViewsTabBarDescriptor.java b/core/src/main/java/hudson/views/MyViewsTabBarDescriptor.java index c98391e6b000a..f191f05d1bd16 100644 --- a/core/src/main/java/hudson/views/MyViewsTabBarDescriptor.java +++ b/core/src/main/java/hudson/views/MyViewsTabBarDescriptor.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/StatusColumn.java b/core/src/main/java/hudson/views/StatusColumn.java index 80813e00ea206..9d9e92d3dfdd1 100644 --- a/core/src/main/java/hudson/views/StatusColumn.java +++ b/core/src/main/java/hudson/views/StatusColumn.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; @@ -38,7 +39,7 @@ public class StatusColumn extends ListViewColumn { public StatusColumn() { } - @Extension(ordinal=DEFAULT_COLUMNS_ORDINAL_ICON_START-1) @Symbol("status") + @Extension(ordinal = DEFAULT_COLUMNS_ORDINAL_ICON_START - 1) @Symbol("status") public static class DescriptorImpl extends ListViewColumnDescriptor { @Override public String getDisplayName() { diff --git a/core/src/main/java/hudson/views/StatusFilter.java b/core/src/main/java/hudson/views/StatusFilter.java index a2789b8b8fa32..f15132145017e 100644 --- a/core/src/main/java/hudson/views/StatusFilter.java +++ b/core/src/main/java/hudson/views/StatusFilter.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 edu.umd.cs.findbugs.annotations.NonNull; @@ -60,7 +61,7 @@ public List filter(List added, List al List 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 c00541c215ae6..576ec824d0c85 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 static DescriptorExtensionList> @Override @SuppressWarnings("unchecked") - public Descriptor 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 b8af8de198ae8..195f72104abaf 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 static DescriptorExtensionList> all( @Override public ViewsTabBarDescriptor getDescriptor() { - return (ViewsTabBarDescriptor)super.getDescriptor(); + return (ViewsTabBarDescriptor) super.getDescriptor(); } /** @@ -92,7 +93,7 @@ public List sort(@NonNull List views) { * * @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 boolean configure(StaplerRequest req, JSONObject json) throws FormExcepti 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 73f0c85b825ad..012a43ed9dd81 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 d14e9ca5582bf..ee04f7c0f08b9 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 aa44599fbbcd4..da3576771416f 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 @@ * * @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 List getQueuedItems() { 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 4cae7eccfb392..aba195ab7c744 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 @@ * 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 HistoryWidget(O owner, Iterable baseList, Adapter adapter) 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 @@ protected HistoryPageFilter updateFirstTransientBuildKey(HistoryPageFilter histo } 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 @@ private Iterable> updateFirstTransientBuildKey(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 void setTrimmed(boolean trimmed) { * 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 void doAjax( StaplerRequest req, StaplerResponse rsp, 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 interface Adapter { * 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 6e9687793f94a..9092526f109b1 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