未验证 提交 eeb1ebe2 编写于 作者: O Oleg Nenashev 提交者: GitHub

Merge pull request #3975 from jsoref/java-cleanup

Java cleanup
......@@ -120,6 +120,7 @@ public class EnvVars extends TreeMap<String,String> {
}
}
@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);
......
......@@ -2730,12 +2730,12 @@ public final class FilePath implements SerializableOnlyOverRemoting {
//
// this is not a very efficient/clever way to do it, but it's relatively simple
String prefix="";
StringBuilder prefix = new StringBuilder();
while(true) {
int idx = findSeparator(f);
if(idx==-1) break;
prefix+=f.substring(0,idx)+'/';
prefix.append(f.substring(0, idx)).append('/');
f=f.substring(idx+1);
if(hasMatch(dir,prefix+fileMask,caseSensitive))
return Messages.FilePath_validateAntFileMask_doesntMatchAndSuggest(fileMask, prefix+fileMask);
......
......@@ -42,6 +42,7 @@ public class AddJobToViewCommand extends CLICommand {
@Argument(usage="Name of the view", required=true, index=0)
private View view;
@SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
@Argument(usage="Job names", required=true, index=1)
private List<TopLevelItem> jobs;
......
......@@ -44,6 +44,7 @@ import java.util.logging.Logger;
@Extension
public class ConnectNodeCommand extends CLICommand {
@SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
@Argument(metaVar="NAME", usage="Slave name, or empty string for master; comma-separated list is supported", required=true, multiValued=true)
private List<String> nodes;
......@@ -62,8 +63,7 @@ public class ConnectNodeCommand extends CLICommand {
boolean errorOccurred = false;
final Jenkins jenkins = Jenkins.getActiveInstance();
final HashSet<String> hs = new HashSet<>();
hs.addAll(nodes);
final HashSet<String> hs = new HashSet<>(nodes);
List<String> names = null;
......
......@@ -40,6 +40,7 @@ import java.util.HashSet;
@Extension
public class DeleteJobCommand extends CLICommand {
@SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
@Argument(usage="Name of the job(s) to delete", required=true, multiValued=true)
private List<String> jobs;
......@@ -55,8 +56,7 @@ public class DeleteJobCommand extends CLICommand {
boolean errorOccurred = false;
final Jenkins jenkins = Jenkins.getActiveInstance();
final HashSet<String> hs = new HashSet<>();
hs.addAll(jobs);
final HashSet<String> hs = new HashSet<>(jobs);
for (String job_s: hs) {
AbstractItem job = null;
......
......@@ -40,6 +40,7 @@ import java.util.List;
@Extension
public class DeleteNodeCommand extends CLICommand {
@SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
@Argument(usage="Names of nodes to delete", required=true, multiValued=true)
private List<String> nodes;
......@@ -55,8 +56,7 @@ public class DeleteNodeCommand extends CLICommand {
boolean errorOccurred = false;
final Jenkins jenkins = Jenkins.getActiveInstance();
final HashSet<String> hs = new HashSet<>();
hs.addAll(nodes);
final HashSet<String> hs = new HashSet<>(nodes);
for (String node_s : hs) {
Node node = null;
......
......@@ -41,6 +41,7 @@ import java.util.List;
@Extension
public class DeleteViewCommand extends CLICommand {
@SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
@Argument(usage="View names to delete", required=true, multiValued=true)
private List<String> views;
......@@ -56,8 +57,7 @@ public class DeleteViewCommand extends CLICommand {
boolean errorOccurred = false;
// Remove duplicates
final HashSet<String> hs = new HashSet<>();
hs.addAll(views);
final HashSet<String> hs = new HashSet<>(views);
ViewOptionHandler voh = new ViewOptionHandler(null, null, null);
......
......@@ -61,8 +61,7 @@ public class DisconnectNodeCommand extends CLICommand {
boolean errorOccurred = false;
final Jenkins jenkins = Jenkins.getActiveInstance();
final HashSet<String> hs = new HashSet<>();
hs.addAll(nodes);
final HashSet<String> hs = new HashSet<>(nodes);
List<String> names = null;
......
......@@ -62,8 +62,7 @@ public class ReloadJobCommand extends CLICommand {
boolean errorOccurred = false;
final Jenkins jenkins = Jenkins.getActiveInstance();
final HashSet<String> hs = new HashSet<>();
hs.addAll(jobs);
final HashSet<String> hs = new HashSet<>(jobs);
for (String job_s: hs) {
AbstractItem job = null;
......
......@@ -287,9 +287,7 @@ public class WindowsInstallerLink extends ManagementLink {
try {
return new LocalLauncher(out).launch().cmds(jenkinsExe, command).stdout(out).pwd(pwd).join();
} catch (IOException e) {
if (e.getMessage().contains("CreateProcess") && e.getMessage().contains("=740")) {
// fall through
} else {
if (!e.getMessage().contains("CreateProcess") || !e.getMessage().contains("=740")) {
throw e;
}
}
......
......@@ -56,8 +56,8 @@ public class CauseAction implements FoldableAction, RunAction2 {
private Map<Cause,Integer> causeBag = new LinkedHashMap<>();
public CauseAction(Cause c) {
this.causeBag.put(c, 1);
}
this.causeBag.put(c, 1);
}
private void addCause(Cause c) {
synchronized (causeBag) {
......@@ -72,16 +72,17 @@ public class CauseAction implements FoldableAction, RunAction2 {
}
public CauseAction(Cause... c) {
this(Arrays.asList(c));
}
this(Arrays.asList(c));
}
@SuppressWarnings("CopyConstructorMissesField") // does not initialize the deprecated #cause field
public CauseAction(Collection<? extends Cause> causes) {
addCauses(causes);
}
addCauses(causes);
}
public CauseAction(CauseAction ca) {
addCauses(ca.getCauses());
}
public CauseAction(CauseAction ca) {
addCauses(ca.getCauses());
}
/**
* Lists all causes of this build.
......@@ -90,14 +91,14 @@ public class CauseAction implements FoldableAction, RunAction2 {
* to create an action with multiple causes use either of the constructors that support this;
* to append causes retroactively to a build you must create a new {@link CauseAction} and replace the old
*/
@Exported(visibility=2)
public List<Cause> getCauses() {
List<Cause> r = new ArrayList<>();
@Exported(visibility=2)
public List<Cause> getCauses() {
List<Cause> r = new ArrayList<>();
for (Map.Entry<Cause,Integer> entry : causeBag.entrySet()) {
r.addAll(Collections.nCopies(entry.getValue(), entry.getKey()));
}
return Collections.unmodifiableList(r);
}
}
/**
* Finds the cause of the specific type.
......@@ -108,19 +109,19 @@ public class CauseAction implements FoldableAction, RunAction2 {
return type.cast(c);
return null;
}
public String getDisplayName() {
return "Cause";
}
public String getIconFileName() {
// no icon
return null;
}
public String getDisplayName() {
return "Cause";
}
public String getUrlName() {
return "cause";
}
public String getIconFileName() {
// no icon
return null;
}
public String getUrlName() {
return "cause";
}
/**
* Get list of causes with duplicates combined into counters.
......
......@@ -259,15 +259,14 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces
*/
@SuppressWarnings("deprecation")
public List<Action> getActions() {
List<Action> result = new ArrayList<>();
result.addAll(super.getActions());
synchronized (this) {
if (transientActions == null) {
transientActions = TransientComputerActionFactory.createAllFor(this);
}
result.addAll(transientActions);
}
return Collections.unmodifiableList(result);
List<Action> result = new ArrayList<>(super.getActions());
synchronized (this) {
if (transientActions == null) {
transientActions = TransientComputerActionFactory.createAllFor(this);
}
result.addAll(transientActions);
}
return Collections.unmodifiableList(result);
}
@SuppressWarnings({"ConstantConditions","deprecation"})
......@@ -423,8 +422,8 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces
* make much sense because as soon as {@link Computer} is connected it can be disconnected by some other threads.)
*/
public final Future<?> connect(boolean forceReconnect) {
connectTime = System.currentTimeMillis();
return _connect(forceReconnect);
connectTime = System.currentTimeMillis();
return _connect(forceReconnect);
}
/**
......@@ -466,7 +465,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces
* @return The time in ms since epoch when this computer last connected.
*/
public final long getConnectTime() {
return connectTime;
return connectTime;
}
/**
......@@ -725,9 +724,9 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces
/**
* Returns the icon for this computer.
*
*
* It is both the recommended and default implementation to serve different icons based on {@link #isOffline}
*
*
* @see #getIconClassName()
*/
@Exported
......@@ -740,13 +739,13 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces
/**
* Returns the class name that will be used to lookup the icon.
*
*
* This class name will be added as a class tag to the html img tags where the icon should
* show up followed by a size specifier given by {@link Icon#toNormalizedIconSizeClass(String)}
* The conversion of class tag to src tag is registered through {@link IconSet#addIcon(Icon)}
*
*
* It is both the recommended and default implementation to serve different icons based on {@link #isOffline}
*
*
* @see #getIcon()
*/
@Exported
......@@ -1321,7 +1320,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces
* other classes from being transferred over remoting.
*/
private static final Logger LOGGER = Logger.getLogger(ListPossibleNames.class.getName());
public List<String> call() throws IOException {
List<String> names = new ArrayList<>();
......@@ -1695,12 +1694,11 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("DisplayExecutor{");
sb.append("displayName='").append(displayName).append('\'');
sb.append(", url='").append(url).append('\'');
sb.append(", executor=").append(executor);
sb.append('}');
return sb.toString();
String sb = "DisplayExecutor{" + "displayName='" + displayName + '\'' +
", url='" + url + '\'' +
", executor=" + executor +
'}';
return sb;
}
@Override
......
......@@ -100,7 +100,7 @@ public class DownloadService extends PageDecorator {
.append(',')
.append(QuotedStringTokenizer.quote(mapHttps(d.getUrl())))
.append(',')
.append("{version:"+QuotedStringTokenizer.quote(Jenkins.VERSION)+'}')
.append("{version:").append(QuotedStringTokenizer.quote(Jenkins.VERSION)).append('}')
.append(',')
.append(QuotedStringTokenizer.quote(Stapler.getCurrentRequest().getContextPath()+'/'+getUrl()+"/byId/"+d.getId()+"/postBack"))
.append(',')
......
......@@ -967,8 +967,7 @@ public class Fingerprint implements ModelObject, Saveable {
* Gets the sorted list of job names where this jar is used.
*/
public @Nonnull List<String> getJobs() {
List<String> r = new ArrayList<>();
r.addAll(usages.keySet());
List<String> r = new ArrayList<>(usages.keySet());
Collections.sort(r);
return r;
}
......
......@@ -754,8 +754,7 @@ public abstract class View extends AbstractModelObject implements AccessControll
}
private List<UserInfo> toList(Map<User,UserInfo> users) {
ArrayList<UserInfo> list = new ArrayList<>();
list.addAll(users.values());
ArrayList<UserInfo> list = new ArrayList<>(users.values());
Collections.sort(list);
return Collections.unmodifiableList(list);
}
......
......@@ -276,9 +276,11 @@ public class TokenBasedRememberMeServices2 extends TokenBasedRememberMeServices
* @return the decoded base64 of the cookie or {@code null} if the value was not correctly encoded
*/
private @CheckForNull String decodeCookieBase64(@Nonnull String base64EncodedValue){
for (int j = 0; j < base64EncodedValue.length() % 4; j++) {
base64EncodedValue = base64EncodedValue + "=";
StringBuilder base64EncodedValueBuilder = new StringBuilder(base64EncodedValue);
for (int j = 0; j < base64EncodedValueBuilder.length() % 4; j++) {
base64EncodedValueBuilder.append("=");
}
base64EncodedValue = base64EncodedValueBuilder.toString();
try {
// any charset should be fine but better safe than sorry
......
......@@ -598,13 +598,12 @@ public class NodeProvisioner {
*/
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("StrategyState{");
sb.append("label=").append(label);
sb.append(", snapshot=").append(snapshot);
sb.append(", plannedCapacitySnapshot=").append(plannedCapacitySnapshot);
sb.append(", additionalPlannedCapacity=").append(additionalPlannedCapacity);
sb.append('}');
return sb.toString();
String sb = "StrategyState{" + "label=" + label +
", snapshot=" + snapshot +
", plannedCapacitySnapshot=" + plannedCapacitySnapshot +
", additionalPlannedCapacity=" + additionalPlannedCapacity +
'}';
return sb;
}
}
......
......@@ -88,8 +88,7 @@ public class Shell extends CommandInterpreter {
// interpreter override
int end = command.indexOf('\n');
if(end<0) end=command.length();
List<String> args = new ArrayList<>();
args.addAll(Arrays.asList(Util.tokenize(command.substring(0,end).trim())));
List<String> args = new ArrayList<>(Arrays.asList(Util.tokenize(command.substring(0, end).trim())));
args.add(script.getRemote());
args.set(0,args.get(0).substring(2)); // trim off "#!"
return args.toArray(new String[0]);
......
......@@ -540,18 +540,19 @@ public abstract class FormFieldValidator {
} else {
// look in PATH
String path = EnvVars.masterEnvVars.get("PATH");
String tokenizedPath = "";
String tokenizedPath;
String delimiter = null;
if(path!=null) {
StringBuilder tokenizedPathBuilder = new StringBuilder();
for (String _dir : Util.tokenize(path.replace("\\", "\\\\"),File.pathSeparator)) {
if (delimiter == null) {
delimiter = ", ";
}
else {
tokenizedPath += delimiter;
tokenizedPathBuilder.append(delimiter);
}
tokenizedPath += _dir.replace('\\', '/');
tokenizedPathBuilder.append(_dir.replace('\\', '/'));
File dir = new File(_dir);
......@@ -567,8 +568,8 @@ public abstract class FormFieldValidator {
return;
}
}
tokenizedPath += ".";
tokenizedPathBuilder.append('.');
tokenizedPath = tokenizedPathBuilder.toString();
}
else {
tokenizedPath = "unavailable.";
......
......@@ -351,18 +351,19 @@ public abstract class FormValidation extends IOException implements HttpResponse
// look in PATH
String path = EnvVars.masterEnvVars.get("PATH");
String tokenizedPath = "";
String tokenizedPath;
String delimiter = null;
if(path!=null) {
StringBuilder tokenizedPathBuilder = new StringBuilder();
for (String _dir : Util.tokenize(path.replace("\\", "\\\\"),File.pathSeparator)) {
if (delimiter == null) {
delimiter = ", ";
}
else {
tokenizedPath += delimiter;
tokenizedPathBuilder.append(delimiter);
}
tokenizedPath += _dir.replace('\\', '/');
tokenizedPathBuilder.append(_dir.replace('\\', '/'));
File dir = new File(_dir);
......@@ -372,8 +373,9 @@ public abstract class FormValidation extends IOException implements HttpResponse
File fexe = new File(dir,exe+".exe");
if(fexe.exists()) return exeValidator.validate(fexe);
}
tokenizedPathBuilder.append('.');
tokenizedPath += ".";
tokenizedPath = tokenizedPathBuilder.toString();
} else {
tokenizedPath = "unavailable.";
}
......@@ -646,7 +648,7 @@ public abstract class FormValidation extends IOException implements HttpResponse
buf.append("+qs(this).addThis()");
for (String name : names) {
buf.append(".nearBy('"+name+"')");
buf.append(".nearBy('").append(name).append("')");
}
buf.append(".toString()");
}
......
......@@ -122,7 +122,6 @@ public class TableNestChecker extends XMLFilterImpl {
CHECKERS.put("TABLE",new InList("TR","THEAD","TBODY"));
InList rows = new InList("TR");
CHECKERS.put("THEAD",rows);
CHECKERS.put("THEAD",rows);
CHECKERS.put("TR", new InList("TD","TH"));
}
}
......@@ -4160,6 +4160,7 @@ public class Jenkins extends AbstractCIBase implements DirectlyModifiableTopLeve
* Simulates OutOfMemoryError.
* Useful to make sure OutOfMemoryHeapDump setting.
*/
@SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
@RequirePOST
public void doSimulateOutOfMemory() throws IOException {
checkPermission(ADMINISTER);
......
......@@ -160,19 +160,19 @@ public class AdminWhitelistRule implements StaplerProxy {
@RequirePOST
public HttpResponse doSubmit(StaplerRequest req) throws IOException {
String whitelist = Util.fixNull(req.getParameter("whitelist"));
if (!whitelist.endsWith("\n"))
whitelist+="\n";
StringBuilder whitelist = new StringBuilder(Util.fixNull(req.getParameter("whitelist")));
if (whitelist.charAt(whitelist.length() - 1) != '\n')
whitelist.append("\n");
Enumeration e = req.getParameterNames();
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
if (name.startsWith("class:")) {
whitelist += name.substring(6)+"\n";
whitelist.append(name.substring(6)).append("\n");
}
}
whitelisted.set(whitelist);
whitelisted.set(whitelist.toString());
String newRules = Util.fixNull(req.getParameter("filePathRules"));
filePathRules.parseTest(newRules); // test first before writing a potentially broken rules
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册