提交 bb7c8fce 编写于 作者: S Stephen Connolly

Jenkins.getInstance() should be non-null

- It is never too late to do the right thing.
- The vast majority of usages of `Jenkins.getInstance()` in core currently assume that its return value is non-null
- This commit changes those that are written to correctly check for non-null values will call `Jenkins.getInstanceOrNull()`
- We deprecate the `Jenkins.getActiveInstance()` madness
- I checked with @kohsuke who said not to bother with a PR and just commit this strongly opinionated change direct to master as a PR will just degrade into a bikeshedding.
上级 7597c98a
......@@ -390,14 +390,14 @@ public class ExtensionList<T> extends AbstractList<T> {
/**
* Gets the extension list for a given type.
* Normally calls {@link Jenkins#getExtensionList(Class)} but falls back to an empty list
* in case {@link Jenkins#getInstance} is null.
* in case {@link Jenkins#getInstanceOrNull()} is null.
* Thus it is useful to call from {@code all()} methods which need to behave gracefully during startup or shutdown.
* @param type the extension point type
* @return some list
* @since 1.572
*/
public static @Nonnull <T> ExtensionList<T> lookup(Class<T> type) {
Jenkins j = Jenkins.getInstance();
Jenkins j = Jenkins.getInstanceOrNull();
return j == null ? create((Jenkins) null, type) : j.getExtensionList(type);
}
......
......@@ -1133,7 +1133,7 @@ public final class FilePath implements Serializable {
* @since 1.571
*/
public @CheckForNull Computer toComputer() {
Jenkins j = Jenkins.getInstance();
Jenkins j = Jenkins.getInstanceOrNull();
if (j != null) {
for (Computer c : j.getComputers()) {
if (getChannel()==c.getChannel()) {
......
......@@ -219,7 +219,7 @@ public class Functions {
* @since 1.607
*/
public static boolean isExtensionsAvailable() {
final Jenkins jenkins = Jenkins.getInstance();
final Jenkins jenkins = Jenkins.getInstanceOrNull();
return jenkins != null && jenkins.getInitLevel().compareTo(InitMilestone.EXTENSIONS_AUGMENTED) >= 0;
}
......@@ -1649,7 +1649,7 @@ public class Functions {
*/
public static List<PageDecorator> getPageDecorators() {
// this method may be called to render start up errors, at which point Hudson doesn't exist yet. see HUDSON-3608
if(Jenkins.getInstance()==null) return Collections.emptyList();
if(Jenkins.getInstanceOrNull()==null) return Collections.emptyList();
return PageDecorator.all();
}
......@@ -1671,13 +1671,13 @@ public class Functions {
}
public static String getCrumb(StaplerRequest req) {
Jenkins h = Jenkins.getInstance();
Jenkins h = Jenkins.getInstanceOrNull();
CrumbIssuer issuer = h != null ? h.getCrumbIssuer() : null;
return issuer != null ? issuer.getCrumb(req) : "";
}
public static String getCrumbRequestField() {
Jenkins h = Jenkins.getInstance();
Jenkins h = Jenkins.getInstanceOrNull();
CrumbIssuer issuer = h != null ? h.getCrumbIssuer() : null;
return issuer != null ? issuer.getDescriptor().getCrumbRequestField() : "";
}
......@@ -1907,7 +1907,7 @@ public class Functions {
* discovery of Jenkins.
*/
public static void advertiseHeaders(HttpServletResponse rsp) {
Jenkins j = Jenkins.getInstance();
Jenkins j = Jenkins.getInstanceOrNull();
if (j!=null) {
rsp.setHeader("X-Hudson","1.395");
rsp.setHeader("X-Jenkins", Jenkins.VERSION);
......
......@@ -215,7 +215,7 @@ public final class ProxyConfiguration extends AbstractDescribableImpl<ProxyConfi
* This method should be used wherever {@link URL#openConnection()} to internet URLs is invoked directly.
*/
public static URLConnection open(URL url) throws IOException {
Jenkins h = Jenkins.getInstance(); // this code might run on slaves
Jenkins h = Jenkins.getInstanceOrNull(); // this code might run on slaves
ProxyConfiguration p = h!=null ? h.proxy : null;
if(p==null)
return url.openConnection();
......@@ -241,7 +241,7 @@ public final class ProxyConfiguration extends AbstractDescribableImpl<ProxyConfi
}
public static InputStream getInputStream(URL url) throws IOException {
Jenkins h = Jenkins.getInstance(); // this code might run on slaves
Jenkins h = Jenkins.getInstanceOrNull(); // this code might run on slaves
final ProxyConfiguration p = (h != null) ? h.proxy : null;
if (p == null)
return new RetryableHttpStream(url);
......
......@@ -236,7 +236,7 @@ public class WebAppMain implements ServletContextListener {
} catch (Exception e) {
new HudsonFailedToLoad(e).publish(context,_home);
} finally {
Jenkins instance = Jenkins.getInstance();
Jenkins instance = Jenkins.getInstanceOrNull();
if(!success && instance!=null)
instance.cleanUp();
}
......@@ -392,7 +392,7 @@ public class WebAppMain implements ServletContextListener {
public void contextDestroyed(ServletContextEvent event) {
terminated = true;
Jenkins instance = Jenkins.getInstance();
Jenkins instance = Jenkins.getInstanceOrNull();
if(instance!=null)
instance.cleanUp();
Thread t = initThread;
......
......@@ -61,7 +61,7 @@ public class NullIdDescriptorMonitor extends AdministrativeMonitor {
}
private void verify() {
Jenkins h = Jenkins.getInstance();
Jenkins h = Jenkins.getInstanceOrNull();
if (h == null) {
return;
}
......
......@@ -105,7 +105,7 @@ public class OldDataMonitor extends AdministrativeMonitor {
}
private static void remove(Saveable obj, boolean isDelete) {
Jenkins j = Jenkins.getInstance();
Jenkins j = Jenkins.getInstanceOrNull();
if (j != null) {
OldDataMonitor odm = get(j);
SecurityContext oldContext = ACL.impersonate(ACL.SYSTEM);
......@@ -206,7 +206,7 @@ public class OldDataMonitor extends AdministrativeMonitor {
}
}
if (buf.length() == 0) return;
Jenkins j = Jenkins.getInstance();
Jenkins j = Jenkins.getInstanceOrNull();
if (j == null) {
// Startup failed, something is very broken, so report what we can.
for (Throwable t : errors) {
......
......@@ -62,7 +62,6 @@ public class ReverseProxySetupMonitor extends AdministrativeMonitor {
public HttpResponse doTest() {
String referer = Stapler.getCurrentRequest().getReferer();
Jenkins j = Jenkins.getInstance();
assert j != null;
// May need to send an absolute URL, since handling of HttpRedirect with a relative URL does not currently honor X-Forwarded-Proto/Port at all.
String redirect = j.getRootUrl() + "administrativeMonitor/" + id + "/testForReverseProxySetup/" + (referer != null ? Util.rawEncode(referer) : "NO-REFERER") + "/";
LOGGER.log(Level.FINE, "coming from {0} and redirecting to {1}", new Object[] {referer, redirect});
......@@ -71,7 +70,6 @@ public class ReverseProxySetupMonitor extends AdministrativeMonitor {
public void getTestForReverseProxySetup(String rest) {
Jenkins j = Jenkins.getInstance();
assert j != null;
String inferred = j.getRootUrlFromRequest() + "manage";
// TODO this could also verify that j.getRootUrl() has been properly configured, and send a different message if not
if (rest.startsWith(inferred)) { // not using equals due to JENKINS-24014
......
......@@ -116,8 +116,8 @@ abstract class TaskMethodFinder<T extends Annotation> extends TaskBuilder {
*/
private Object lookUp(Class<?> type) {
if (type==Jenkins.class || type==Hudson.class)
return Jenkins.getInstance();
Jenkins j = Jenkins.getInstance();
return Jenkins.getInstanceOrNull();
Jenkins j = Jenkins.getInstanceOrNull();
if (j!=null) {
Injector i = j.getInjector();
if (i!=null)
......
......@@ -38,7 +38,7 @@ public class SolarisSMFLifecycle extends Lifecycle {
*/
@Override
public void restart() throws IOException, InterruptedException {
Jenkins h = Jenkins.getInstance();
Jenkins h = Jenkins.getInstanceOrNull();
if (h != null)
h.cleanUp();
System.exit(0);
......
......@@ -65,7 +65,7 @@ public class UnixLifecycle extends Lifecycle {
@Override
public void restart() throws IOException, InterruptedException {
Jenkins h = Jenkins.getInstance();
Jenkins h = Jenkins.getInstanceOrNull();
if (h != null)
h.cleanUp();
......
......@@ -2077,7 +2077,7 @@ public abstract class AbstractProject<P extends AbstractProject<P,R>,R extends A
return FormValidation.error(e,
Messages.AbstractProject_AssignedLabelString_InvalidBooleanExpression(e.getMessage()));
}
Jenkins j = Jenkins.getInstance();
Jenkins j = Jenkins.getInstanceOrNull();
if (j == null) {
return FormValidation.ok(); // ?
}
......
......@@ -564,8 +564,9 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces
* null if the configuration has changed and the node is removed, yet the corresponding {@link Computer}
* is not yet gone.
*/
public @CheckForNull Node getNode() {
Jenkins j = Jenkins.getInstance();
@CheckForNull
public Node getNode() {
Jenkins j = Jenkins.getInstanceOrNull();
if (j == null) {
return null;
}
......@@ -1011,7 +1012,7 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces
executors.remove(e);
addNewExecutorIfNecessary();
if (!isAlive()) {
AbstractCIBase ciBase = Jenkins.getInstance();
AbstractCIBase ciBase = Jenkins.getInstanceOrNull();
if (ciBase != null) {
ciBase.removeComputer(Computer.this);
}
......
......@@ -958,8 +958,9 @@ public class Executor extends Thread implements ModelObject {
* or null if it could not be found (for example because the execution has already completed)
* @since 1.607
*/
public static @CheckForNull Executor of(Executable executable) {
Jenkins jenkins = Jenkins.getInstance();
@CheckForNull
public static Executor of(Executable executable) {
Jenkins jenkins = Jenkins.getInstanceOrNull();
if (jenkins == null) {
return null;
}
......
......@@ -128,7 +128,7 @@ public class Fingerprint implements ModelObject, Saveable {
private boolean hasPermissionToDiscoverBuild() {
// We expose the data to Jenkins administrators in order to
// let them manage the data for deleted jobs (also works for SYSTEM)
final Jenkins instance = Jenkins.getInstance();
final Jenkins instance = Jenkins.getInstanceOrNull();
if (instance != null && instance.hasPermission(Jenkins.ADMINISTER)) {
return true;
}
......@@ -941,7 +941,7 @@ public class Fingerprint implements ModelObject, Saveable {
@Exported(name="usage")
public @Nonnull List<RangeItem> _getUsages() {
List<RangeItem> r = new ArrayList<RangeItem>();
final Jenkins instance = Jenkins.getInstance();
final Jenkins instance = Jenkins.getInstanceOrNull();
if (instance == null) {
return r;
}
......@@ -1368,7 +1368,7 @@ public class Fingerprint implements ModelObject, Saveable {
* @return {@code true} if the user can discover the item
*/
private static boolean canDiscoverItem(@Nonnull final String fullName) {
final Jenkins jenkins = Jenkins.getInstance();
final Jenkins jenkins = Jenkins.getInstanceOrNull();
if (jenkins == null) {
return false;
}
......
......@@ -34,6 +34,7 @@ import hudson.model.listeners.ItemListener;
import hudson.slaves.ComputerListener;
import hudson.util.CopyOnWriteList;
import hudson.util.FormValidation;
import javax.annotation.Nonnull;
import jenkins.model.Jenkins;
import org.jvnet.hudson.reactor.ReactorException;
import org.kohsuke.stapler.QueryParameter;
......@@ -71,7 +72,8 @@ public class Hudson extends Jenkins {
/** @deprecated Here only for compatibility. Use {@link Jenkins#getInstance} instead. */
@Deprecated
@CLIResolver
public static @CheckForNull Hudson getInstance() {
@Nonnull
public static Hudson getInstance() {
return (Hudson)Jenkins.getInstance();
}
......
......@@ -848,7 +848,7 @@ public abstract class Job<JobT extends Job<JobT, RunT>, RunT extends Run<JobT, R
* @see RunMap
*/
public File getBuildDir() {
Jenkins j = Jenkins.getInstance();
Jenkins j = Jenkins.getInstanceOrNull();
if (j == null) {
return new File(getRootDir(), "builds");
}
......
......@@ -128,7 +128,7 @@ public abstract class Node extends AbstractModelObject implements Reconfigurable
// so either path results in the same behaviour: the node instance is only saved if it is in the list of nodes
// for all other cases we do not know where to persist the node record and hence we follow the default
// no-op of a Saveable.NOOP
final Jenkins jenkins = Jenkins.getInstance();
final Jenkins jenkins = Jenkins.getInstanceOrNull();
if (jenkins != null) {
jenkins.updateNode(this);
}
......@@ -141,7 +141,8 @@ public abstract class Node extends AbstractModelObject implements Reconfigurable
* "" if this is master
*/
@Exported(visibility=999)
public abstract @Nonnull String getNodeName();
@Nonnull
public abstract String getNodeName();
/**
* When the user clones a {@link Node}, Hudson uses this method to change the node name right after
......@@ -194,7 +195,8 @@ public abstract class Node extends AbstractModelObject implements Reconfigurable
* this method can return null if there's no {@link Computer} object for this node,
* such as when this node has no executors at all.
*/
public final @CheckForNull Computer toComputer() {
@CheckForNull
public final Computer toComputer() {
AbstractCIBase ciBase = Jenkins.getInstance();
return ciBase.getComputer(this);
}
......@@ -204,7 +206,8 @@ public abstract class Node extends AbstractModelObject implements Reconfigurable
*
* This is just a convenience method for {@link Computer#getChannel()} with null check.
*/
public final @CheckForNull VirtualChannel getChannel() {
@CheckForNull
public final VirtualChannel getChannel() {
Computer c = toComputer();
return c==null ? null : c.getChannel();
}
......
......@@ -1181,7 +1181,7 @@ public class Queue extends ResourceController implements Saveable {
* @since 1.592
*/
public static void withLock(Runnable runnable) {
final Jenkins jenkins = Jenkins.getInstance();
final Jenkins jenkins = Jenkins.getInstanceOrNull();
final Queue queue = jenkins == null ? null : jenkins.getQueue();
if (queue == null) {
runnable.run();
......@@ -1202,7 +1202,7 @@ public class Queue extends ResourceController implements Saveable {
* @since 1.592
*/
public static <V, T extends Throwable> V withLock(hudson.remoting.Callable<V, T> callable) throws T {
final Jenkins jenkins = Jenkins.getInstance();
final Jenkins jenkins = Jenkins.getInstanceOrNull();
final Queue queue = jenkins == null ? null : jenkins.getQueue();
if (queue == null) {
return callable.call();
......@@ -1222,7 +1222,7 @@ public class Queue extends ResourceController implements Saveable {
* @since 1.592
*/
public static <V> V withLock(java.util.concurrent.Callable<V> callable) throws Exception {
final Jenkins jenkins = Jenkins.getInstance();
final Jenkins jenkins = Jenkins.getInstanceOrNull();
final Queue queue = jenkins == null ? null : jenkins.getQueue();
if (queue == null) {
return callable.call();
......@@ -1239,7 +1239,7 @@ public class Queue extends ResourceController implements Saveable {
* @since 1.618
*/
public static boolean tryWithLock(Runnable runnable) {
final Jenkins jenkins = Jenkins.getInstance();
final Jenkins jenkins = Jenkins.getInstanceOrNull();
final Queue queue = jenkins == null ? null : jenkins.getQueue();
if (queue == null) {
runnable.run();
......@@ -1255,7 +1255,7 @@ public class Queue extends ResourceController implements Saveable {
* @since 1.618
*/
public static Runnable wrapWithLock(Runnable runnable) {
final Jenkins jenkins = Jenkins.getInstance();
final Jenkins jenkins = Jenkins.getInstanceOrNull();
final Queue queue = jenkins == null ? null : jenkins.getQueue();
return queue == null ? runnable : new LockedRunnable(runnable);
}
......@@ -1267,7 +1267,7 @@ public class Queue extends ResourceController implements Saveable {
* @since 1.618
*/
public static <V, T extends Throwable> hudson.remoting.Callable<V, T> wrapWithLock(hudson.remoting.Callable<V, T> callable) {
final Jenkins jenkins = Jenkins.getInstance();
final Jenkins jenkins = Jenkins.getInstanceOrNull();
final Queue queue = jenkins == null ? null : jenkins.getQueue();
return queue == null ? callable : new LockedHRCallable<>(callable);
}
......@@ -1279,7 +1279,7 @@ public class Queue extends ResourceController implements Saveable {
* @since 1.618
*/
public static <V> java.util.concurrent.Callable<V> wrapWithLock(java.util.concurrent.Callable<V> callable) {
final Jenkins jenkins = Jenkins.getInstance();
final Jenkins jenkins = Jenkins.getInstanceOrNull();
final Queue queue = jenkins == null ? null : jenkins.getQueue();
return queue == null ? callable : new LockedJUCCallable<V>(callable);
}
......
......@@ -2275,7 +2275,7 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
} catch (NumberFormatException x) {
throw new IllegalArgumentException(x);
}
Jenkins j = Jenkins.getInstance();
Jenkins j = Jenkins.getInstanceOrNull();
if (j == null) {
return null;
}
......
......@@ -96,7 +96,7 @@ public class UsageStatistics extends PageDecorator {
* Returns true if it's time for us to check for new version.
*/
public boolean isDue() {
final Jenkins j = Jenkins.getInstance();
final Jenkins j = Jenkins.getInstanceOrNull();
// user opted out or Jenkins not fully initialized. no data collection.
if (j == null || j.isUsageStatisticsCollected() || DISABLED || COMPLETED.compareTo(j.getInitLevel()) > 0) {
return false;
......
......@@ -150,7 +150,7 @@ public class User extends AbstractModelObject implements AccessControlled, Descr
*/
@Nonnull
public static IdStrategy idStrategy() {
Jenkins j = Jenkins.getInstance();
Jenkins j = Jenkins.getInstanceOrNull();
if (j == null) {
return IdStrategy.CASE_INSENSITIVE;
}
......
......@@ -223,7 +223,7 @@ public abstract class RunListener<R extends Run> implements ExtensionPoint {
* Fires the {@link #onFinalized(Run)} event.
*/
public static void fireFinalized(Run r) {
if (Jenkins.getInstance() == null) {
if (Jenkins.getInstanceOrNull() == null) {
return;
}
for (RunListener l : all()) {
......
......@@ -126,7 +126,7 @@ public abstract class SCMListener implements ExtensionPoint {
*/
@SuppressWarnings("deprecation")
public static Collection<? extends SCMListener> all() {
Jenkins j = Jenkins.getInstance();
Jenkins j = Jenkins.getInstanceOrNull();
if (j == null) {
return Collections.emptySet();
}
......@@ -140,7 +140,7 @@ public abstract class SCMListener implements ExtensionPoint {
/** @deprecated Use {@link Extension} instead. */
@Deprecated
public final void register() {
Jenkins j = Jenkins.getInstance();
Jenkins j = Jenkins.getInstanceOrNull();
if (j != null) {
j.getSCMListeners().add(this);
}
......@@ -149,7 +149,7 @@ public abstract class SCMListener implements ExtensionPoint {
/** @deprecated Use {@link Extension} instead. */
@Deprecated
public final boolean unregister() {
Jenkins j = Jenkins.getInstance();
Jenkins j = Jenkins.getInstanceOrNull();
if (j != null) {
return j.getSCMListeners().remove(this);
} else {
......
......@@ -104,7 +104,7 @@ public class HudsonFilter implements Filter {
// this is how we make us available to the rest of Hudson.
filterConfig.getServletContext().setAttribute(HudsonFilter.class.getName(),this);
try {
Jenkins hudson = Jenkins.getInstance();
Jenkins hudson = Jenkins.getInstanceOrNull();
if (hudson != null) {
// looks like we are initialized after Hudson came into being. initialize it now. See #3069
LOGGER.fine("Security wasn't initialized; Initializing it...");
......
......@@ -93,7 +93,7 @@ public class TokenBasedRememberMeServices2 extends TokenBasedRememberMeServices
return;
}
Jenkins j = Jenkins.getInstance();
Jenkins j = Jenkins.getInstanceOrNull();
if (j != null && j.isDisableRememberMe()) {
if (logger.isDebugEnabled()) {
logger.debug("Did not send remember-me cookie because 'Remember Me' is disabled in " +
......
......@@ -35,7 +35,7 @@ public class CrumbFilter implements Filter {
* we cannot use Hudson to the CrumbIssuer into CrumbFilter eagerly.
*/
public CrumbIssuer getCrumbIssuer() {
Jenkins h = Jenkins.getInstance();
Jenkins h = Jenkins.getInstanceOrNull();
if(h==null) return null; // before Jenkins is initialized?
return h.getCrumbIssuer();
}
......
......@@ -835,7 +835,7 @@ public class SlaveComputer extends Computer {
* @since 1.362
*/
public static VirtualChannel getChannelToMaster() {
if (Jenkins.getInstance()!=null)
if (Jenkins.getInstanceOrNull()!=null)
return FilePath.localChannel;
// if this method is called from within the slave computation thread, this should work
......
......@@ -448,7 +448,7 @@ public class JDKInstaller extends ToolInstaller {
HttpClient hc = new HttpClient();
hc.getParams().setParameter("http.useragent","Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)");
Jenkins j = Jenkins.getInstance();
Jenkins j = Jenkins.getInstanceOrNull();
ProxyConfiguration jpc = j!=null ? j.proxy : null;
if(jpc != null) {
hc.getHostConfiguration().setProxy(jpc.name, jpc.port);
......
......@@ -93,7 +93,7 @@ public class PluginServletFilter implements Filter, ExtensionPoint {
}
public static void addFilter(Filter filter) throws ServletException {
Jenkins j = Jenkins.getInstance();
Jenkins j = Jenkins.getInstanceOrNull();
PluginServletFilter container = null;
if(j != null) {
......@@ -111,7 +111,7 @@ public class PluginServletFilter implements Filter, ExtensionPoint {
}
public static void removeFilter(Filter filter) throws ServletException {
Jenkins j = Jenkins.getInstance();
Jenkins j = Jenkins.getInstanceOrNull();
if (j==null || getInstance(j.servletContext) == null) {
LEGACY.remove(filter);
} else {
......
......@@ -74,7 +74,7 @@ public abstract class ProcessKillingVeto implements ExtensionPoint {
* list if Jenkins is not available, never null.
*/
public static List<ProcessKillingVeto> all() {
Jenkins jenkins = Jenkins.getInstance();
Jenkins jenkins = Jenkins.getInstanceOrNull();
if (jenkins == null)
return Collections.emptyList();
return jenkins.getExtensionList(ProcessKillingVeto.class);
......
......@@ -76,7 +76,7 @@ public class SubClassGenerator extends ClassLoader {
Class<? extends T> c = defineClass(name, image, 0, image.length).asSubclass(base);
Jenkins h = Jenkins.getInstance();
Jenkins h = Jenkins.getInstanceOrNull();
if (h!=null) // null only during tests.
((UberClassLoader)h.pluginManager.uberClassLoader).addNamedClass(name,c); // can't change the field type as it breaks binary compatibility
......
......@@ -106,7 +106,7 @@ public class XStream2 extends XStream {
public Object unmarshal(HierarchicalStreamReader reader, Object root, DataHolder dataHolder) {
// init() is too early to do this
// defensive because some use of XStream happens before plugins are initialized.
Jenkins h = Jenkins.getInstance();
Jenkins h = Jenkins.getInstanceOrNull();
if(h!=null && h.pluginManager!=null && h.pluginManager.uberClassLoader!=null) {
setClassLoader(h.pluginManager.uberClassLoader);
}
......@@ -421,7 +421,7 @@ public class XStream2 extends XStream {
return classOwnership.ownerOf(clazz);
}
if (pm == null) {
Jenkins j = Jenkins.getInstance();
Jenkins j = Jenkins.getInstanceOrNull();
if (j != null) {
pm = j.getPluginManager();
}
......
......@@ -75,7 +75,7 @@ public abstract class ParserConfigurator implements ExtensionPoint, Serializable
public static void applyConfiguration(SAXReader reader, Object context) throws IOException, InterruptedException {
Collection<ParserConfigurator> all = Collections.emptyList();
if (Jenkins.getInstance()==null) {
if (Jenkins.getInstanceOrNull()==null) {
Channel ch = Channel.current();
if (ch!=null)
all = ch.call(new SlaveToMasterCallable<Collection<ParserConfigurator>, IOException>() {
......
......@@ -688,12 +688,15 @@ public class Jenkins extends AbstractCIBase implements DirectlyModifiableTopLeve
/**
* Gets the {@link Jenkins} singleton.
* {@link #getInstance()} provides the unchecked versions of the method.
* {@link #getInstanceOrNull()} provides the unchecked versions of the method.
* @return {@link Jenkins} instance
* @throws IllegalStateException {@link Jenkins} has not been started, or was already shut down
* @since 1.590
* @deprecated use {@link #getInstance()}
*/
public static @Nonnull Jenkins getActiveInstance() throws IllegalStateException {
@Deprecated
@Nonnull
public static Jenkins getActiveInstance() throws IllegalStateException {
Jenkins instance = HOLDER.getInstance();
if (instance == null) {
throw new IllegalStateException("Jenkins has not been started, or was already shut down");
......@@ -706,13 +709,29 @@ public class Jenkins extends AbstractCIBase implements DirectlyModifiableTopLeve
* {@link #getActiveInstance()} provides the checked versions of the method.
* @return The instance. Null if the {@link Jenkins} instance has not been started,
* or was already shut down
* @since 1.653
*/
@CLIResolver
@CheckForNull
public static Jenkins getInstance() {
public static Jenkins getInstanceOrNull() {
return HOLDER.getInstance();
}
/**
* Gets the {@link Jenkins} singleton. In certain rare cases you may have code that is intended to run before
* Jenkins starts or while Jenkins is being shut-down. For those rare cases use {@link #getInstanceOrNull()}.
* @return The instance.
* @throws IllegalStateException {@link Jenkins} has not been started, or was already shut down
*/
@CLIResolver
@Nonnull
public static Jenkins getInstance() {
Jenkins instance = HOLDER.getInstance();
if (instance == null) {
throw new IllegalStateException("Jenkins has not been started, or was already shut down");
}
return instance;
}
/**
* Secret key generated once and used for a long time, beyond
* container start/stop. Persisted outside <tt>config.xml</tt> to avoid
......@@ -4115,7 +4134,7 @@ public class Jenkins extends AbstractCIBase implements DirectlyModifiableTopLeve
* Shortcut for {@code Jenkins.getInstance().lookup.get(type)}
*/
public static @CheckForNull <T> T lookup(Class<T> type) {
Jenkins j = Jenkins.getInstance();
Jenkins j = Jenkins.getInstanceOrNull();
return j != null ? j.lookup.get(type) : null;
}
......
......@@ -78,7 +78,7 @@ public class UnlabeledLoadStatistics extends LoadStatistics {
@Override
public int computeQueueLength() {
final Jenkins j = Jenkins.getInstance();
final Jenkins j = Jenkins.getInstanceOrNull();
if (j == null) { // Consider queue as empty when Jenkins is inactive
return 0;
}
......
......@@ -118,7 +118,7 @@ public class ApiTokenProperty extends UserProperty {
}
private boolean hasPermissionToSeeToken() {
final Jenkins jenkins = Jenkins.getInstance();
final Jenkins jenkins = Jenkins.getInstanceOrNull();
if (jenkins == null) {
return false; // Should not happen - we don't display UIs in this stage
}
......
......@@ -62,9 +62,6 @@ public abstract class ConfidentialStore {
if (TEST!=null) return TEST.get();
Jenkins j = Jenkins.getInstance();
if (j == null) {
throw new IllegalStateException("cannot initialize confidential key store until Jenkins has started");
}
Lookup lookup = j.lookup;
ConfidentialStore cs = lookup.get(ConfidentialStore.class);
if (cs==null) {
......
......@@ -32,7 +32,7 @@ public abstract class QueueItemAuthenticatorProvider implements ExtensionPoint {
private Iterator<QueueItemAuthenticator> delegate = null;
private IteratorImpl() {
final Jenkins jenkins = Jenkins.getInstance();
final Jenkins jenkins = Jenkins.getInstanceOrNull();
providers = new ArrayList<QueueItemAuthenticatorProvider>(jenkins == null
? Collections.<QueueItemAuthenticatorProvider>emptyList()
: jenkins.getExtensionList(QueueItemAuthenticatorProvider.class)).iterator();
......
......@@ -106,7 +106,7 @@ public final class ReverseBuildTrigger extends Trigger<Job> implements Dependenc
}
private boolean shouldTrigger(Run upstreamBuild, TaskListener listener) {
Jenkins jenkins = Jenkins.getInstance();
Jenkins jenkins = Jenkins.getInstanceOrNull();
if (jenkins == null || job == null) {
return false;
}
......@@ -202,7 +202,7 @@ public final class ReverseBuildTrigger extends Trigger<Job> implements Dependenc
while(tokens.hasMoreTokens()) {
String projectName = tokens.nextToken().trim();
if (StringUtils.isNotBlank(projectName)) {
Jenkins jenkins = Jenkins.getInstance();
Jenkins jenkins = Jenkins.getInstanceOrNull();
if (jenkins == null) {
return FormValidation.ok();
}
......@@ -253,7 +253,7 @@ public final class ReverseBuildTrigger extends Trigger<Job> implements Dependenc
@Extension public static class ItemListenerImpl extends ItemListener {
@Override public void onLocationChanged(Item item, String oldFullName, String newFullName) {
Jenkins jenkins = Jenkins.getInstance();
Jenkins jenkins = Jenkins.getInstanceOrNull();
if (jenkins == null) {
return;
}
......
......@@ -134,7 +134,7 @@ public class JSONSignatureValidator {
// if we trust default root CAs, we end up trusting anyone who has a valid certificate,
// which isn't useful at all
Set<TrustAnchor> anchors = new HashSet<TrustAnchor>(); // CertificateUtil.getDefaultRootCAs();
Jenkins j = Jenkins.getInstance();
Jenkins j = Jenkins.getInstanceOrNull();
if (j == null) {
return anchors;
}
......
......@@ -74,7 +74,7 @@ public class BootFailureTest {
@After
public void tearDown() {
Jenkins j = Jenkins.getInstance();
Jenkins j = Jenkins.getInstanceOrNull();
if (j != null) {
j.cleanUp();
}
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册