AbstractProject.java 43.9 KB
Newer Older
K
kohsuke 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/*
 * The MIT License
 * 
 * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Brian Westrich, Erik Ramfelt, Ertan Deniz, Jean-Baptiste Quenot, Luca Domenico Milanesio, R. Tyler Ballance, Stephen Connolly, Tom Huybrechts, 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
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
24 25
package hudson.model;

K
kohsuke 已提交
26
import hudson.AbortException;
27
import hudson.FeedAdapter;
28
import hudson.FilePath;
29
import hudson.Launcher;
30
import hudson.Util;
31
import hudson.maven.MavenModule;
M
mdonohue 已提交
32
import hudson.model.Cause.LegacyCodeCause;
33
import hudson.model.Cause.UserCause;
34
import hudson.model.Cause.RemoteCause;
35 36 37
import hudson.model.Descriptor.FormException;
import hudson.model.Fingerprint.RangeSet;
import hudson.model.RunMap.Constructor;
K
kohsuke 已提交
38
import hudson.model.listeners.RunListener;
39
import hudson.remoting.AsyncFutureImpl;
K
kohsuke 已提交
40
import hudson.scm.ChangeLogSet;
K
kohsuke 已提交
41
import hudson.scm.ChangeLogSet.Entry;
42
import hudson.scm.NullSCM;
43
import hudson.scm.SCM;
K
kohsuke 已提交
44
import hudson.scm.SCMS;
J
jbq 已提交
45
import hudson.search.SearchIndexBuilder;
K
kohsuke 已提交
46
import hudson.security.Permission;
47
import hudson.tasks.BuildStep;
J
jbq 已提交
48
import hudson.tasks.BuildTrigger;
49
import hudson.tasks.Mailer;
50
import hudson.tasks.Publisher;
K
kohsuke 已提交
51
import hudson.triggers.SCMTrigger;
52
import hudson.triggers.Trigger;
53
import hudson.triggers.TriggerDescriptor;
54
import hudson.triggers.Triggers;
55
import hudson.util.DescribableList;
56
import hudson.util.EditDistance;
K
kohsuke 已提交
57 58 59 60 61 62
import hudson.widgets.BuildHistoryWidget;
import hudson.widgets.HistoryWidget;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.export.Exported;
63

K
kohsuke 已提交
64
import javax.servlet.ServletException;
65
import java.io.File;
66
import java.io.IOException;
K
kohsuke 已提交
67
import java.lang.reflect.InvocationTargetException;
K
kohsuke 已提交
68
import java.util.ArrayList;
69
import java.util.Arrays;
70
import java.util.Calendar;
71
import java.util.Collection;
J
jbq 已提交
72
import java.util.Collections;
73
import java.util.Comparator;
J
jbq 已提交
74
import java.util.HashSet;
75 76
import java.util.List;
import java.util.Map;
J
jbq 已提交
77
import java.util.Set;
78 79 80
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.Vector;
K
kohsuke 已提交
81
import java.util.concurrent.Future;
82 83
import java.util.logging.Level;
import java.util.logging.Logger;
84 85 86

/**
 * Base implementation of {@link Job}s that build software.
87 88 89
 *
 * For now this is primarily the common part of {@link Project} and {@link MavenModule}.
 *
90 91 92
 * @author Kohsuke Kawaguchi
 * @see AbstractBuild
 */
93
public abstract class AbstractProject<P extends AbstractProject<P,R>,R extends AbstractBuild<P,R>> extends Job<P,R> implements BuildableItem {
94

95
    /**
96 97 98
     * {@link SCM} associated with the project.
     * To allow derived classes to link {@link SCM} config to elsewhere,
     * access to this variable should always go through {@link #getScm()}.
99
     */
K
kohsuke 已提交
100
    private volatile SCM scm = new NullSCM();
101

102 103 104
    /**
     * All the builds keyed by their build number.
     */
105
    protected transient /*almost final*/ RunMap<R> builds = new RunMap<R>();
106 107 108 109

    /**
     * The quiet period. Null to delegate to the system default.
     */
K
kohsuke 已提交
110
    private volatile Integer quietPeriod = null;
111 112

    /**
113 114 115 116 117 118 119
     * If this project is configured to be only built on a certain label,
     * this value will be set to that label.
     *
     * For historical reasons, this is called 'assignedNode'. Also for
     * a historical reason, null to indicate the affinity
     * with the master node.
     *
120
     * @see #canRoam
121 122 123 124 125
     */
    private String assignedNode;

    /**
     * True if this project can be built on any node.
126
     *
127
     * <p>
128 129
     * This somewhat ugly flag combination is so that we can migrate
     * existing Hudson installations nicely.
130
     */
K
kohsuke 已提交
131
    private volatile boolean canRoam;
132 133 134 135

    /**
     * True to suspend new builds.
     */
K
kohsuke 已提交
136
    protected volatile boolean disabled;
137 138

    /**
139 140 141
     * Identifies {@link JDK} to be used.
     * Null if no explicit configuration is required.
     *
142
     * <p>
143 144 145
     * Can't store {@link JDK} directly because {@link Hudson} and {@link Project}
     * are saved independently.
     *
146 147
     * @see Hudson#getJDK(String)
     */
K
kohsuke 已提交
148
    private volatile String jdk;
149

150 151 152 153
    /**
     * @deprecated
     */
    private transient boolean enableRemoteTrigger;
154

K
kohsuke 已提交
155
    private volatile BuildAuthorizationToken authToken = null;
156

157 158 159
    /**
     * List of all {@link Trigger}s for this project.
     */
160
    protected List<Trigger<?>> triggers = new Vector<Trigger<?>>();
161

162 163
    /**
     * {@link Action}s contributed from subsidiary objects associated with
164 165 166 167
     * {@link AbstractProject}, such as from triggers, builders, publishers, etc.
     *
     * We don't want to persist them separately, and these actions
     * come and go as configuration change, so it's kept separate.
168
     */
169
    protected transient /*final*/ List<Action> transientActions = new Vector<Action>();
170

171
    protected AbstractProject(ItemGroup parent, String name) {
172
        super(parent,name);
173

K
kohsuke 已提交
174
        if(!Hudson.getInstance().getNodes().isEmpty()) {
175
            // if a new job is configured with Hudson that already has slave nodes
176 177 178 179 180
            // make it roamable by default
            canRoam = true;
        }
    }

181
    @Override
182
    public void onLoad(ItemGroup<? extends Item> parent, String name) throws IOException {
183
        super.onLoad(parent, name);
184 185

        this.builds = new RunMap<R>();
186
        this.builds.load(this,new Constructor<R>() {
187 188 189 190 191
            public R create(File dir) throws IOException {
                return loadBuild(dir);
            }
        });

192
        if(triggers==null)
193
            // it didn't exist in < 1.28
194
            triggers = new Vector<Trigger<?>>();
195
        for (Trigger t : triggers)
196
            t.start(this,false);
197

198 199
        if(transientActions==null)
            transientActions = new Vector<Action>();    // happens when loaded from disk
200
        updateTransientActions();
201 202
    }

203
    protected void performDelete() throws IOException, InterruptedException {
K
kohsuke 已提交
204 205
        // prevent a new build while a delete operation is in progress
        makeDisabled(true);
206
        FilePath ws = getWorkspace();
207
        if(ws!=null) {
K
NPE fix  
kohsuke 已提交
208 209 210 211
            Node on = getLastBuiltOn();
            getScm().processWorkspaceBeforeDeletion(this, ws, on);
            if(on!=null)
                on.getFileSystemProvisioner().discardWorkspace(this,ws);
212
        }
K
kohsuke 已提交
213 214 215
        super.performDelete();
    }

216
    /**
217 218
     * If this project is configured to be always built on this node,
     * return that {@link Node}. Otherwise null.
219
     */
220
    public Label getAssignedLabel() {
221
        if(canRoam)
222 223
            return null;

224
        if(assignedNode==null)
225 226
            return Hudson.getInstance().getSelfLabel();
        return Hudson.getInstance().getLabel(assignedNode);
227 228
    }

K
kohsuke 已提交
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
    /**
     * Sets the assigned label.
     */
    public void setAssignedLabel(Label l) throws IOException {
        if(l==null) {
            canRoam = true;
            assignedNode = null;
        } else {
            canRoam = false;
            if(l==Hudson.getInstance().getSelfLabel())  assignedNode = null;
            else                                        assignedNode = l.getName();
        }
        save();
    }

244
    /**
245 246
     * Get the term used in the UI to represent this kind of {@link AbstractProject}.
     * Must start with a capital letter.
247 248 249
     */
    @Override
    public String getPronoun() {
250
        return Messages.AbstractProject_Pronoun();
251 252
    }

253 254 255 256 257 258 259 260 261 262 263 264 265
    /**
     * Returns the root project value.
     *
     * @return the root project value.
     */
	public AbstractProject getRootProject() {
        if (this.getParent() instanceof Hudson) {
            return this;
        } else {
            return ((AbstractProject) this.getParent()).getRootProject();
        }
    }

266 267
    /**
     * Gets the directory where the module is checked out.
268 269 270
     *
     * @return
     *      null if the workspace is on a slave that's not connected.
271
     */
272
    public abstract FilePath getWorkspace();
273

274 275 276
    /**
     * Returns the root directory of the checked-out module.
     * <p>
277 278
     * This is usually where <tt>pom.xml</tt>, <tt>build.xml</tt>
     * and so on exists.
279 280
     */
    public FilePath getModuleRoot() {
K
kohsuke 已提交
281
        FilePath ws = getWorkspace();
282
        if(ws==null)    return null;
K
kohsuke 已提交
283
        return getScm().getModuleRoot(ws);
284 285
    }

S
stephenconnolly 已提交
286 287 288 289 290 291 292 293 294 295 296
    /**
     * Returns the root directories of all checked-out modules.
     * <p>
     * Some SCMs support checking out multiple modules into the same workspace.
     * In these cases, the returned array will have a length greater than one.
     * @return The roots of all modules checked out from the SCM.
     */
    public FilePath[] getModuleRoots() {
        return getScm().getModuleRoots(getWorkspace());
    }

297
    public int getQuietPeriod() {
298
        return quietPeriod!=null ? quietPeriod : Hudson.getInstance().getQuietPeriod();
299 300 301 302
    }

    // ugly name because of EL
    public boolean getHasCustomQuietPeriod() {
303
        return quietPeriod!=null;
304 305 306
    }

    public final boolean isBuildable() {
K
kohsuke 已提交
307
        return !isDisabled();
308 309
    }

310
    /**
311 312
     * Used in <tt>sidepanel.jelly</tt> to decide whether to display
     * the config/delete/build links.
313 314 315 316 317
     */
    public boolean isConfigurable() {
        return true;
    }

318 319 320 321
    public boolean isDisabled() {
        return disabled;
    }

322 323 324 325
    /**
     * Marks the build as disabled.
     */
    public void makeDisabled(boolean b) throws IOException {
326
        if(disabled==b)     return; // noop
327
        this.disabled = b;
K
bug fix  
kohsuke 已提交
328 329
        if(b)
            Hudson.getInstance().getQueue().cancel(this);
330 331 332
        save();
    }

K
kohsuke 已提交
333 334
    @Override
    public BallColor getIconColor() {
335
        if(isDisabled())
336
            return BallColor.DISABLED;
K
kohsuke 已提交
337 338 339
        else
            return super.getIconColor();
    }
340

341
    protected void updateTransientActions() {
342
        synchronized(transientActions) {
343
            transientActions.clear();
344

345
            for (JobProperty<? super P> p : properties) {
346 347
                Action a = p.getJobAction((P)this);
                if(a!=null)
348 349 350 351 352
                    transientActions.add(a);
            }
        }
    }

353
    /**
354 355
     * Returns the live list of all {@link Publisher}s configured for this project.
     *
356
     * <p>
357 358
     * This method couldn't be called <tt>getPublishers()</tt> because existing methods
     * in sub-classes return different inconsistent types.
359
     */
360
    public abstract DescribableList<Publisher,Descriptor<Publisher>> getPublishersList();
361

K
kohsuke 已提交
362 363 364 365 366 367
    @Override
    public void addProperty(JobProperty<? super P> jobProp) throws IOException {
        super.addProperty(jobProp);
        updateTransientActions();
    }

368 369 370 371
    public List<ProminentProjectAction> getProminentActions() {
        List<Action> a = getActions();
        List<ProminentProjectAction> pa = new Vector<ProminentProjectAction>();
        for (Action action : a) {
372
            if(action instanceof ProminentProjectAction)
373 374 375 376 377
                pa.add((ProminentProjectAction) action);
        }
        return pa;
    }

378
    @Override
379 380
    public void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
        super.doConfigSubmit(req,rsp);
381 382

        Set<AbstractProject> upstream = Collections.emptySet();
383 384
        if(req.getParameter("pseudoUpstreamTrigger")!=null) {
            upstream = new HashSet<AbstractProject>(Items.fromNameList(req.getParameter("upstreamProjects"),AbstractProject.class));
385 386 387 388 389 390 391 392 393
        }

        // dependency setting might have been changed by the user, so rebuild.
        Hudson.getInstance().rebuildDependencyGraph();

        // reflect the submission of the pseudo 'upstream build trriger'.
        // this needs to be done after we release the lock on 'this',
        // or otherwise we could dead-lock

394
        for (AbstractProject<?,?> p : Hudson.getInstance().getAllItems(AbstractProject.class)) {
395
            boolean isUpstream = upstream.contains(p);
396 397 398 399 400 401 402
            synchronized(p) {
                // does 'p' include us in its BuildTrigger? 
                DescribableList<Publisher,Descriptor<Publisher>> pl = p.getPublishersList();
                BuildTrigger trigger = (BuildTrigger) pl.get(BuildTrigger.DESCRIPTOR);
                List<AbstractProject> newChildProjects = trigger == null ? new ArrayList<AbstractProject>():trigger.getChildProjects();
                if(isUpstream) {
                    if(!newChildProjects.contains(this))
403 404 405 406 407
                        newChildProjects.add(this);
                } else {
                    newChildProjects.remove(this);
                }

408
                if(newChildProjects.isEmpty()) {
409
                    pl.remove(BuildTrigger.DESCRIPTOR);
410
                } else {
411 412 413
                    BuildTrigger existing = (BuildTrigger)pl.get(BuildTrigger.DESCRIPTOR);
                    if(existing!=null && existing.hasSame(newChildProjects))
                        continue;   // no need to touch
414
                    pl.add(new BuildTrigger(newChildProjects,
415
                        existing==null?Result.SUCCESS:existing.getThreshold()));
416 417 418 419 420 421 422 423 424 425 426
                }
            }
        }

        // notify the queue as the project might be now tied to different node
        Hudson.getInstance().getQueue().scheduleMaintenance();

        // this is to reflect the upstream build adjustments done above
        Hudson.getInstance().rebuildDependencyGraph();
    }

M
mdonohue 已提交
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
	/**
	 * @deprecated
	 *    Use {@link #scheduleBuild(Cause)}.  Since 1.283
	 */
    public boolean scheduleBuild() {
    	return scheduleBuild(new LegacyCodeCause());
    }
    
	/**
	 * @deprecated
	 *    Use {@link #scheduleBuild(int, Cause)}.  Since 1.283
	 */
    public boolean scheduleBuild(int quietPeriod) {
    	return scheduleBuild(quietPeriod, new LegacyCodeCause());
    }
    
443 444
    /**
     * Schedules a build of this project.
445 446 447 448 449
     *
     * @return
     *      true if the project is actually added to the queue.
     *      false if the queue contained it and therefore the add()
     *      was noop
450
     */
M
mdonohue 已提交
451 452
    public boolean scheduleBuild(Cause c) {
        return scheduleBuild(getQuietPeriod(), c);
K
kohsuke 已提交
453 454
    }

M
mdonohue 已提交
455
    public boolean scheduleBuild(int quietPeriod, Cause c) {
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
        return scheduleBuild(quietPeriod, c, new Action[0]);
    }

    /**
     * Schedules a build.
     *
     * Important: the actions should be persistable without outside references (e.g. don't store
     * references to this project). To provide parameters for a parameterized project, add a ParametersAction. If
     * no ParametersAction is provided for such a project, one will be created with the default parameter values.
     *
     * @param quietPeriod the quiet period to observer
     * @param c the cause for this build which should be recorded
     * @param actions a list of Actions that will be added to the build
     * @return whether the build was actually scheduled
     */
    public boolean scheduleBuild(int quietPeriod, Cause c, Action... actions) {
472 473 474
        if (isDisabled())
            return false;

475 476 477 478 479 480 481 482 483
        List<Action> queueActions = new ArrayList(Arrays.asList(actions));
        if (isParameterized() && Util.filter(queueActions, ParametersAction.class).isEmpty()) {
            queueActions.add(new ParametersAction(getDefaultParametersValues()));
        }

        return Hudson.getInstance().getQueue().add(
                this,
                quietPeriod,
                queueActions.toArray(new Action[queueActions.size()]));
484 485 486 487 488 489
    }

    private List<ParameterValue> getDefaultParametersValues() {
        ParametersDefinitionProperty paramDefProp = getProperty(ParametersDefinitionProperty.class);
        ArrayList<ParameterValue> defValues = new ArrayList<ParameterValue>();
        
M
mindless 已提交
490 491 492
        /*
         * This check is made ONLY if someone will call this method even if isParametrized() is false.
         */
493 494 495 496 497 498 499 500 501 502 503 504 505
        if(paramDefProp == null)
            return defValues;
        
        /* Scan for all parameter with an associated default values */
        for(ParameterDefinition paramDefinition : paramDefProp.getParameterDefinitions())
        {
           ParameterValue defaultValue  = paramDefinition.getDefaultParameterValue();
            
            if(defaultValue != null)
                defValues.add(defaultValue);           
        }
        
        return defValues;
K
kohsuke 已提交
506 507
    }

M
mdonohue 已提交
508 509 510 511 512 513 514 515
	/**
	 * @deprecated
	 *    Use {@link #scheduleBuild2(int, Cause)}.  Since 1.283
	 */
    public Future<R> scheduleBuild2(int quietPeriod) {
    	return scheduleBuild2(quietPeriod, new LegacyCodeCause());
    }
    
K
kohsuke 已提交
516
    /**
517 518
     * Schedules a build of this project, and returns a {@link Future} object
     * to wait for the completion of the build.
K
kohsuke 已提交
519
     */
M
mdonohue 已提交
520
    public Future<R> scheduleBuild2(int quietPeriod, Cause c) {
521 522 523 524 525 526 527 528
        return scheduleBuild2(quietPeriod, c, new Action[0]);
    }

    /**
     * Schedules a build of this project, and returns a {@link Future} object
     * to wait for the completion of the build.
     */
    public Future<R> scheduleBuild2(int quietPeriod, Cause c, Action... actions) {
K
kohsuke 已提交
529 530
        R lastBuild = getLastBuild();
        final int n;
531 532
        if(lastBuild!=null) n = lastBuild.getNumber();
        else                n = -1;
K
kohsuke 已提交
533 534

        Future<R> f = new AsyncFutureImpl<R>() {
535
            final RunListener r = new RunListener<AbstractBuild>(AbstractBuild.class) {
536
                public void onFinalized(AbstractBuild r) {
537 538
                    if(r.getProject()==AbstractProject.this && r.getNumber()>n) {
                        set((R)r);
K
kohsuke 已提交
539 540 541 542 543
                        unregister();
                    }
                }
            };

544
            { r.register(); }
K
kohsuke 已提交
545 546
        };

547
        scheduleBuild(quietPeriod, c, actions);
K
kohsuke 已提交
548 549

        return f;
550 551
    }

552 553 554 555
    /**
     * Schedules a polling of this project.
     */
    public boolean schedulePolling() {
556
        if(isDisabled())    return false;
557
        SCMTrigger scmt = getTrigger(SCMTrigger.class);
558
        if(scmt==null)      return false;
559 560 561 562
        scmt.run();
        return true;
    }

563 564 565 566 567
    /**
     * Returns true if the build is in the queue.
     */
    @Override
    public boolean isInQueue() {
568
        return Hudson.getInstance().getQueue().contains(this);
569 570
    }

K
kohsuke 已提交
571 572 573 574 575
    @Override
    public Queue.Item getQueueItem() {
        return Hudson.getInstance().getQueue().getItem(this);
    }

576 577 578 579 580
    /**
     * Returns true if a build of this project is in progress.
     */
    public boolean isBuilding() {
        R b = getLastBuild();
581
        return b!=null && b.isBuilding();
582 583
    }

K
kohsuke 已提交
584 585 586
    /**
     * Gets the JDK that this project is configured with, or null.
     */
587
    public JDK getJDK() {
588
        return Hudson.getInstance().getJDK(jdk);
589 590 591 592 593
    }

    /**
     * Overwrites the JDK setting.
     */
K
kohsuke 已提交
594
    public void setJDK(JDK jdk) throws IOException {
595 596 597 598
        this.jdk = jdk.getName();
        save();
    }

599 600
    public BuildAuthorizationToken getAuthToken() {
        return authToken;
601 602 603 604 605 606 607 608 609 610
    }

    public SortedMap<Integer, ? extends R> _getRuns() {
        return builds.getView();
    }

    public void removeRun(R run) {
        this.builds.remove(run);
    }

611 612 613 614 615
    /**
     * Determines Class&lt;R>.
     */
    protected abstract Class<R> getBuildClass();

H
huybrechts 已提交
616
    // keep track of the previous time we started a build
617
    private transient long lastBuildStartTime;
H
huybrechts 已提交
618
    
619 620 621
    /**
     * Creates a new build of this project for immediate execution.
     */
H
huybrechts 已提交
622 623 624 625 626 627 628 629 630 631 632
    protected synchronized R newBuild() throws IOException {
    	// make sure we don't start two builds in the same second
    	// so the build directories will be different too
    	long timeSinceLast = System.currentTimeMillis() - lastBuildStartTime;
    	if (timeSinceLast < 1000) {
    		try {
				Thread.sleep(1000 - timeSinceLast);
			} catch (InterruptedException e) {
			}
    	}
    	lastBuildStartTime = System.currentTimeMillis();
633
        try {
634
            R lastBuild = getBuildClass().getConstructor(getClass()).newInstance(this);
635 636 637 638 639 640 641
            builds.put(lastBuild);
            return lastBuild;
        } catch (InstantiationException e) {
            throw new Error(e);
        } catch (IllegalAccessException e) {
            throw new Error(e);
        } catch (InvocationTargetException e) {
642
            throw handleInvocationTargetException(e);
643 644 645 646
        } catch (NoSuchMethodException e) {
            throw new Error(e);
        }
    }
647

648
    private IOException handleInvocationTargetException(InvocationTargetException e) {
649
        Throwable t = e.getTargetException();
650 651 652
        if(t instanceof Error)  throw (Error)t;
        if(t instanceof RuntimeException)   throw (RuntimeException)t;
        if(t instanceof IOException)    return (IOException)t;
653 654 655
        throw new Error(t);
    }

656 657 658
    /**
     * Loads an existing build record from disk.
     */
659 660
    protected R loadBuild(File dir) throws IOException {
        try {
661
            return getBuildClass().getConstructor(getClass(),File.class).newInstance(this,dir);
662 663 664 665 666
        } catch (InstantiationException e) {
            throw new Error(e);
        } catch (IllegalAccessException e) {
            throw new Error(e);
        } catch (InvocationTargetException e) {
667
            throw handleInvocationTargetException(e);
668 669 670 671
        } catch (NoSuchMethodException e) {
            throw new Error(e);
        }
    }
672

K
kohsuke 已提交
673 674
    /**
     * {@inheritDoc}
675
     *
K
kohsuke 已提交
676 677
     * <p>
     * Note that this method returns a read-only view of {@link Action}s.
678 679
     * {@link BuildStep}s and others who want to add a project action
     * should do so by implementing {@link BuildStep#getProjectAction(AbstractProject)}.
K
kohsuke 已提交
680
     */
681 682 683 684
    public synchronized List<Action> getActions() {
        // add all the transient actions, too
        List<Action> actions = new Vector<Action>(super.getActions());
        actions.addAll(transientActions);
685
        // return the read only list to cause a failure on plugins who try to add an action here
K
kohsuke 已提交
686
        return Collections.unmodifiableList(actions);
687 688
    }

689 690
    /**
     * Gets the {@link Node} where this project was last built on.
691 692 693 694
     *
     * @return
     *      null if no information is available (for example,
     *      if no build was done yet.)
695 696 697 698
     */
    public Node getLastBuiltOn() {
        // where was it built on?
        AbstractBuild b = getLastBuild();
699
        if(b==null)
700 701 702 703 704
            return null;
        else
            return b.getBuiltOn();
    }

705
    /**
706
     * {@inheritDoc}
707
     *
708
     * <p>
709 710
     * A project must be blocked if its own previous build is in progress,
     * but derived classes can also check other conditions.
711
     */
712
    public boolean isBuildBlocked() {
713 714 715
        return isBuilding();
    }

716 717 718
    public String getWhyBlocked() {
        AbstractBuild<?, ?> build = getLastBuild();
        Executor e = build.getExecutor();
719 720
        String eta="";
        if(e!=null)
K
i18n  
kohsuke 已提交
721
            eta = Messages.AbstractProject_ETA(e.getEstimatedRemainingTime());
722
        int lbn = build.getNumber();
723
        return Messages.AbstractProject_BuildInProgress(lbn,eta);
724 725 726 727
    }

    public final long getEstimatedDuration() {
        AbstractBuild b = getLastSuccessfulBuild();
728
        if(b==null)     return -1;
729 730

        long duration = b.getDuration();
731
        if(duration==0) return -1;
732 733 734 735

        return duration;
    }

736
    public R createExecutable() throws IOException {
737
        if(isDisabled())    return null;
738
        return newBuild();
739 740
    }

741 742 743 744
    public void checkAbortPermission() {
        checkPermission(AbstractProject.ABORT);
    }

K
kohsuke 已提交
745 746 747 748
    public boolean hasAbortPermission() {
        return hasPermission(AbstractProject.ABORT);
    }

749 750
    /**
     * Gets the {@link Resource} that represents the workspace of this project.
751
     * Useful for locking and mutual exclusion control.
752 753
     */
    public Resource getWorkspaceResource() {
754
        return new Resource(getFullDisplayName()+" workspace");
755 756 757 758 759 760
    }

    /**
     * List of necessary resources to perform the build of this project.
     */
    public ResourceList getResourceList() {
761
        final Set<ResourceActivity> resourceActivities = getResourceActivities();
762
        final List<ResourceList> resourceLists = new ArrayList<ResourceList>(1 + resourceActivities.size());
763 764 765 766 767 768 769 770 771 772 773
        for (ResourceActivity activity : resourceActivities) {
            if (activity != this && activity != null) {
                // defensive infinite recursion and null check
                resourceLists.add(activity.getResourceList());
            }
        }
        resourceLists.add(new ResourceList().w(getWorkspaceResource()));
        return ResourceList.union(resourceLists);
    }

    /**
774 775
     * Set of child resource activities of the build of this project (override in child projects).
     * @return The set of child resource activities of the build of this project.
776 777
     */
    protected Set<ResourceActivity> getResourceActivities() {
K
kohsuke 已提交
778
        return Collections.emptySet();
779 780
    }

781
    public boolean checkout(AbstractBuild build, Launcher launcher, BuildListener listener, File changelogFile) throws IOException {
782
        SCM scm = getScm();
783 784
        if(scm==null)
            return true;    // no SCM
785

786 787 788
        // Acquire lock for SCMTrigger so poll won't run while we checkout/update
        SCMTrigger scmt = getTrigger(SCMTrigger.class);
        boolean locked = false;
789
        try {
790 791 792 793 794
            if (scmt!=null) {
                scmt.getLock().lockInterruptibly();
                locked = true;
            }

795 796 797
            FilePath workspace = getWorkspace();
            workspace.mkdirs();

798
            return scm.checkout(build, launcher, workspace, listener, changelogFile);
799
        } catch (InterruptedException e) {
K
i18n  
kohsuke 已提交
800
            listener.getLogger().println(Messages.AbstractProject_ScmAborted());
801
            LOGGER.log(Level.INFO,build.toString()+" aborted",e);
802
            return false;
803 804 805
        } finally {
            if (locked)
                scmt.getLock().unlock();
806 807 808 809 810
        }
    }

    /**
     * Checks if there's any update in SCM, and returns true if any is found.
811
     *
812
     * <p>
813 814
     * The caller is responsible for coordinating the mutual exclusion between
     * a build and polling, as both touches the workspace.
815
     */
816
    public boolean pollSCMChanges( TaskListener listener ) {
817
        SCM scm = getScm();
818
        if(scm==null) {
K
i18n  
kohsuke 已提交
819
            listener.getLogger().println(Messages.AbstractProject_NoSCM());
820 821
            return false;
        }
822
        if(isDisabled()) {
K
i18n  
kohsuke 已提交
823
            listener.getLogger().println(Messages.AbstractProject_Disabled());
824
            return false;
825 826 827
        }

        try {
K
kohsuke 已提交
828
            FilePath workspace = getWorkspace();
829
            if (scm.requiresWorkspaceForPolling() && (workspace == null || !workspace.exists())) {
K
kohsuke 已提交
830
                // workspace offline. build now, or nothing will ever be built
K
kohsuke 已提交
831
                Label label = getAssignedLabel();
K
kohsuke 已提交
832
                if (label != null && label.isSelfLabel()) {
833
                    // if the build is fixed on a node, then attempting a build will do us
K
kohsuke 已提交
834
                    // no good. We should just wait for the slave to come back.
835
                    listener.getLogger().println(Messages.AbstractProject_NoWorkspace());
K
kohsuke 已提交
836 837
                    return false;
                }
K
kohsuke 已提交
838
                if (workspace == null)
839
                    listener.getLogger().println(Messages.AbstractProject_WorkspaceOffline());
K
kohsuke 已提交
840
                else
841 842
                    listener.getLogger().println(Messages.AbstractProject_NoWorkspace());
                listener.getLogger().println(Messages.AbstractProject_NewBuildForWorkspace());
K
kohsuke 已提交
843 844
                return true;
            }
K
kohsuke 已提交
845

846
            Launcher launcher = workspace != null ? workspace.createLauncher(listener) : null;
K
kohsuke 已提交
847 848
            LOGGER.fine("Polling SCM changes of " + getName());
            return scm.pollChanges(this, launcher, workspace, listener);
849
        } catch (AbortException e) {
K
i18n  
kohsuke 已提交
850
            listener.fatalError(Messages.AbstractProject_Aborted());
851
            return false;
852 853 854 855
        } catch (IOException e) {
            e.printStackTrace(listener.fatalError(e.getMessage()));
            return false;
        } catch (InterruptedException e) {
856
            e.printStackTrace(listener.fatalError(Messages.AbstractProject_PollingABorted()));
857 858 859 860
            return false;
        }
    }

861 862
    /**
     * Returns true if this user has made a commit to this project.
863
     *
864 865 866
     * @since 1.191
     */
    public boolean hasParticipant(User user) {
867 868
        for( R build = getLastBuild(); build!=null; build=build.getPreviousBuild())
            if(build.hasParticipant(user))
869 870 871 872
                return true;
        return false;
    }

873 874 875 876 877 878 879 880
    public SCM getScm() {
        return scm;
    }

    public void setScm(SCM scm) {
        this.scm = scm;
    }

881 882 883
    /**
     * Adds a new {@link Trigger} to this {@link Project} if not active yet.
     */
884
    public void addTrigger(Trigger<?> trigger) throws IOException {
885
        addToList(trigger,triggers);
886 887
    }

888
    public void removeTrigger(TriggerDescriptor trigger) throws IOException {
889
        removeFromList(trigger,triggers);
890 891
    }

892 893 894 895
    protected final synchronized <T extends Describable<T>>
    void addToList( T item, List<T> collection ) throws IOException {
        for( int i=0; i<collection.size(); i++ ) {
            if(collection.get(i).getDescriptor()==item.getDescriptor()) {
896
                // replace
897
                collection.set(i,item);
898 899 900 901 902 903 904 905 906
                save();
                return;
            }
        }
        // add
        collection.add(item);
        save();
    }

907 908 909 910
    protected final synchronized <T extends Describable<T>>
    void removeFromList(Descriptor<T> item, List<T> collection) throws IOException {
        for( int i=0; i< collection.size(); i++ ) {
            if(collection.get(i).getDescriptor()==item) {
911 912 913 914 915 916 917 918
                // found it
                collection.remove(i);
                save();
                return;
            }
        }
    }

919 920
    public synchronized Map<TriggerDescriptor,Trigger> getTriggers() {
        return (Map)Descriptor.toMap(triggers);
921 922
    }

923
    /**
924
     * Gets the specific trigger, or null if the propert is not configured for this job.
925 926 927
     */
    public <T extends Trigger> T getTrigger(Class<T> clazz) {
        for (Trigger p : triggers) {
928
            if(clazz.isInstance(p))
929 930 931 932 933
                return clazz.cast(p);
        }
        return null;
    }

934 935 936 937 938
//
//
// fingerprint related
//
//
939 940 941 942 943 944
    /**
     * True if the builds of this project produces {@link Fingerprint} records.
     */
    public abstract boolean isFingerprintConfigured();

    /**
945 946
     * Gets the other {@link AbstractProject}s that should be built
     * when a build of this project is completed.
947
     */
K
kohsuke 已提交
948
    @Exported
949 950 951
    public final List<AbstractProject> getDownstreamProjects() {
        return Hudson.getInstance().getDependencyGraph().getDownstream(this);
    }
952

K
kohsuke 已提交
953
    @Exported
954 955
    public final List<AbstractProject> getUpstreamProjects() {
        return Hudson.getInstance().getDependencyGraph().getUpstream(this);
K
kohsuke 已提交
956 957
    }

K
kohsuke 已提交
958
    /**
959 960 961 962
     * Returns only those upstream projects that defines {@link BuildTrigger} to this project.
     * This is a subset of {@link #getUpstreamProjects()}
     *
     * @return A List of upstream projects that has a {@link BuildTrigger} to this project.
K
kohsuke 已提交
963 964 965 966
     */
    public final List<AbstractProject> getBuildTriggerUpstreamProjects() {
        ArrayList<AbstractProject> result = new ArrayList<AbstractProject>();
        for (AbstractProject ap : getUpstreamProjects()) {
967 968 969 970
            BuildTrigger buildTrigger = (BuildTrigger)ap.getPublishersList().get(BuildTrigger.DESCRIPTOR);
            if (buildTrigger != null)
                if (buildTrigger.getChildProjects().contains(this))
                    result.add(ap);
971
        }        
K
kohsuke 已提交
972
        return result;
973 974
    }    
    
K
kohsuke 已提交
975 976
    /**
     * Gets all the upstream projects including transitive upstream projects.
977
     *
K
kohsuke 已提交
978 979 980
     * @since 1.138
     */
    public final Set<AbstractProject> getTransitiveUpstreamProjects() {
981
        return Hudson.getInstance().getDependencyGraph().getTransitiveUpstream(this);
K
kohsuke 已提交
982 983 984
    }

    /**
985 986
     * Gets all the downstream projects including transitive downstream projects.
     *
K
kohsuke 已提交
987 988 989
     * @since 1.138
     */
    public final Set<AbstractProject> getTransitiveDownstreamProjects() {
990
        return Hudson.getInstance().getDependencyGraph().getTransitiveDownstream(this);
991 992 993 994 995
    }

    /**
     * Gets the dependency relationship map between this project (as the source)
     * and that project (as the sink.)
996 997 998 999
     *
     * @return
     *      can be empty but not null. build number of this project to the build
     *      numbers of that project.
1000 1001
     */
    public SortedMap<Integer, RangeSet> getRelationship(AbstractProject that) {
1002
        TreeMap<Integer,RangeSet> r = new TreeMap<Integer,RangeSet>(REVERSE_INTEGER_COMPARATOR);
1003 1004 1005 1006 1007 1008 1009 1010 1011

        checkAndRecord(that, r, this.getBuilds());
        // checkAndRecord(that, r, that.getBuilds());

        return r;
    }

    /**
     * Helper method for getDownstreamRelationship.
1012 1013
     *
     * For each given build, find the build number range of the given project and put that into the map.
1014
     */
1015
    private void checkAndRecord(AbstractProject that, TreeMap<Integer, RangeSet> r, Collection<R> builds) {
1016 1017
        for (R build : builds) {
            RangeSet rs = build.getDownstreamRelationship(that);
1018
            if(rs==null || rs.isEmpty())
1019 1020 1021 1022 1023
                continue;

            int n = build.getNumber();

            RangeSet value = r.get(n);
1024 1025
            if(value==null)
                r.put(n,rs);
1026 1027 1028 1029 1030
            else
                value.add(rs);
        }
    }

1031 1032 1033 1034 1035 1036
    /**
     * Builds the dependency graph.
     * @see DependencyGraph
     */
    protected abstract void buildDependencyGraph(DependencyGraph graph);

K
kohsuke 已提交
1037 1038
    protected SearchIndexBuilder makeSearchIndex() {
        SearchIndexBuilder sib = super.makeSearchIndex();
1039 1040
        if(isBuildable() && Hudson.isAdmin())
            sib.add("build","build");
K
kohsuke 已提交
1041 1042 1043
        return sib;
    }

1044 1045
    @Override
    protected HistoryWidget createHistoryWidget() {
1046
        return new BuildHistoryWidget<R>(this,getBuilds(),HISTORY_ADAPTER);
1047
    }
1048
    
K
kohsuke 已提交
1049
    public boolean isParameterized() {
1050
        return getProperty(ParametersDefinitionProperty.class) != null;
K
kohsuke 已提交
1051
    }
1052

1053 1054 1055 1056 1057
//
//
// actions
//
//
1058 1059 1060
    /**
     * Schedules a new build command.
     */
1061
    public void doBuild( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
1062
        BuildAuthorizationToken.checkPermission(this, authToken, req, rsp);
1063

K
kohsuke 已提交
1064 1065 1066
        // if a build is parameterized, let that take over
        ParametersDefinitionProperty pp = getProperty(ParametersDefinitionProperty.class);
        if (pp != null) {
1067
            pp._doBuild(req,rsp);
K
kohsuke 已提交
1068 1069 1070
            return;
        }

1071 1072 1073 1074 1075 1076 1077
        Cause cause;
        if (authToken != null && authToken.getToken() != null && req.getParameter("token") != null) {
            cause = new RemoteCause(req.getRemoteAddr());
        } else {
            cause = new UserCause();
        }

1078
        String delay = req.getParameter("delay");
1079
        if (delay!=null) {
M
mindless 已提交
1080 1081 1082 1083 1084
            if (!isDisabled()) {
                try {
                    // TODO: more unit handling
                    if(delay.endsWith("sec"))   delay=delay.substring(0,delay.length()-3);
                    if(delay.endsWith("secs"))  delay=delay.substring(0,delay.length()-4);
1085
                    Hudson.getInstance().getQueue().add(this, Integer.parseInt(delay), 
1086
                    		new CauseAction(cause));
M
mindless 已提交
1087 1088 1089 1090 1091
                } catch (NumberFormatException e) {
                    throw new ServletException("Invalid delay parameter value: "+delay);
                }
            }
        } else {
1092
            scheduleBuild(cause);
1093
        }
1094 1095
        rsp.forwardToPreviousPage(req);
    }
1096

1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
    /**
     * Supports build trigger with parameters via an HTTP GET or POST.
     * Currently only String parameters are supported.
     */
    public void doBuildWithParameters(StaplerRequest req, StaplerResponse rsp) throws IOException {
        BuildAuthorizationToken.checkPermission(this, authToken, req, rsp);

        ParametersDefinitionProperty pp = getProperty(ParametersDefinitionProperty.class);
        if (pp != null) {
            pp.buildWithParameters(req,rsp);
            return;
        } else {
        	throw new IllegalStateException("This build is not parameterized!");
        }
    	
    }
1113 1114 1115 1116

    /**
     * Schedules a new SCM polling command.
     */
1117
    public void doPolling( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
1118 1119 1120
        BuildAuthorizationToken.checkPermission(this, authToken, req, rsp);
        schedulePolling();
        rsp.forwardToPreviousPage(req);
1121 1122 1123 1124 1125
    }

    /**
     * Cancels a scheduled build.
     */
1126
    public void doCancelQueue( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
1127
        checkPermission(BUILD);
1128

1129
        Hudson.getInstance().getQueue().cancel(this);
1130 1131 1132
        rsp.forwardToPreviousPage(req);
    }

1133
    @Override
1134 1135
    protected void submit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException {
        super.submit(req,rsp);
1136

1137
        makeDisabled(req.getParameter("disable")!=null);
1138 1139

        jdk = req.getParameter("jdk");
1140
        if(req.getParameter("hasCustomQuietPeriod")!=null) {
1141 1142 1143 1144 1145
            quietPeriod = Integer.parseInt(req.getParameter("quiet_period"));
        } else {
            quietPeriod = null;
        }

1146
        if(req.getParameter("hasSlaveAffinity")!=null) {
1147 1148
            canRoam = false;
            assignedNode = req.getParameter("slave");
1149 1150 1151
            if(assignedNode !=null) {
                if(Hudson.getInstance().getLabel(assignedNode).isEmpty())
                    assignedNode = null;   // no such label
1152 1153 1154 1155 1156 1157
            }
        } else {
            canRoam = true;
            assignedNode = null;
        }

1158
        authToken = BuildAuthorizationToken.create(req);
1159

1160 1161 1162 1163
        setScm(SCMS.parseSCM(req));

        for (Trigger t : triggers)
            t.stop();
K
kohsuke 已提交
1164
        triggers = buildDescribable(req, Triggers.getApplicableTriggers(this));
1165
        for (Trigger t : triggers)
1166
            t.start(this,true);
1167 1168

        updateTransientActions();
1169 1170
    }

K
kohsuke 已提交
1171 1172 1173 1174 1175 1176 1177 1178 1179
    /**
     * @deprecated
     *      As of 1.261. Use {@link #buildDescribable(StaplerRequest, List)} instead.
     */
    protected final <T extends Describable<T>> List<T> buildDescribable(StaplerRequest req, List<? extends Descriptor<T>> descriptors, String prefix) throws FormException, ServletException {
        return buildDescribable(req,descriptors);
    }

    protected final <T extends Describable<T>> List<T> buildDescribable(StaplerRequest req, List<? extends Descriptor<T>> descriptors)
1180
        throws FormException, ServletException {
1181

1182
        JSONObject data = req.getSubmittedForm();
1183
        List<T> r = new Vector<T>();
1184 1185 1186 1187
        for (Descriptor<T> d : descriptors) {
            String name = d.getJsonSafeClassName();
            if (req.getParameter(name) != null) {
                T instance = d.newInstance(req, data.getJSONObject(name));
1188
                r.add(instance);
1189 1190
            }
        }
1191
        return r;
1192 1193 1194 1195 1196
    }

    /**
     * Serves the workspace files.
     */
1197
    public void doWs( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, InterruptedException {
1198
        checkPermission(AbstractProject.WORKSPACE);
1199
        FilePath ws = getWorkspace();
1200
        if ((ws == null) || (!ws.exists())) {
1201
            // if there's no workspace, report a nice error message
1202 1203 1204 1205
            // Would be good if when asked for *plain*, do something else!
            // (E.g. return 404, or send empty doc.)
            // Not critical; client can just check if content type is not text/plain,
            // which also serves to detect old versions of Hudson.
1206
            req.getView(this,"noWorkspace.jelly").forward(req,rsp);
1207
        } else {
1208
            new DirectoryBrowserSupport(this,getDisplayName()+" workspace").serveFile(req, rsp, ws, "folder.gif", true);
1209 1210
        }
    }
1211

1212 1213 1214
    /**
     * Wipes out the workspace.
     */
1215
    public void doDoWipeOutWorkspace(StaplerResponse rsp) throws IOException, InterruptedException {
1216
        checkPermission(BUILD);
1217 1218 1219 1220
        getWorkspace().deleteRecursive();
        rsp.sendRedirect2(".");
    }

1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
    public void doDisable(StaplerResponse rsp) throws IOException, ServletException {
        requirePOST();
        checkPermission(CONFIGURE);
        makeDisabled(true);
        rsp.sendRedirect2(".");
    }

    public void doEnable(StaplerResponse rsp) throws IOException, ServletException {
        checkPermission(CONFIGURE);
        makeDisabled(false);
        rsp.sendRedirect2(".");
    }

K
kohsuke 已提交
1234 1235 1236
    /**
     * RSS feed for changes in this project.
     */
1237
    public void doRssChangelog(  StaplerRequest req, StaplerResponse rsp  ) throws IOException, ServletException {
K
kohsuke 已提交
1238 1239 1240 1241 1242 1243 1244 1245 1246
        class FeedItem {
            ChangeLogSet.Entry e;
            int idx;

            public FeedItem(Entry e, int idx) {
                this.e = e;
                this.idx = idx;
            }

1247
            AbstractBuild<?,?> getBuild() {
K
kohsuke 已提交
1248 1249 1250 1251 1252 1253
                return e.getParent().build;
            }
        }

        List<FeedItem> entries = new ArrayList<FeedItem>();

1254 1255 1256 1257
        for(R r=getLastBuild(); r!=null; r=r.getPreviousBuild()) {
            int idx=0;
            for( ChangeLogSet.Entry e : r.getChangeSet())
                entries.add(new FeedItem(e,idx++));
K
kohsuke 已提交
1258 1259
        }

1260 1261 1262 1263 1264 1265 1266
        RSS.forwardToRss(
            getDisplayName()+' '+getScm().getDescriptor().getDisplayName()+" changes",
            getUrl()+"changes",
            entries, new FeedAdapter<FeedItem>() {
                public String getEntryTitle(FeedItem item) {
                    return "#"+item.getBuild().number+' '+item.e.getMsg()+" ("+item.e.getAuthor()+")";
                }
K
kohsuke 已提交
1267

1268 1269 1270
                public String getEntryUrl(FeedItem item) {
                    return item.getBuild().getUrl()+"changes#detail"+item.idx;
                }
K
kohsuke 已提交
1271

1272 1273 1274
                public String getEntryID(FeedItem item) {
                    return getEntryUrl(item);
                }
K
kohsuke 已提交
1275

1276 1277 1278 1279 1280 1281
                public String getEntryDescription(FeedItem item) {
                    StringBuilder buf = new StringBuilder();
                    for(String path : item.e.getAffectedPaths())
                        buf.append(path).append('\n');
                    return buf.toString();
                }
1282

1283 1284 1285
                public Calendar getEntryTimestamp(FeedItem item) {
                    return item.getBuild().getTimestamp();
                }
1286

1287 1288 1289 1290 1291
                public String getEntryAuthor(FeedItem entry) {
                    return Mailer.DESCRIPTOR.getAdminAddress();
                }
            },
            req, rsp );
K
kohsuke 已提交
1292 1293
    }

1294
    /**
1295
     * Finds a {@link AbstractProject} that has the name closest to the given name.
1296 1297
     */
    public static AbstractProject findNearest(String name) {
1298
        List<AbstractProject> projects = Hudson.getInstance().getItems(AbstractProject.class);
1299
        String[] names = new String[projects.size()];
1300
        for( int i=0; i<projects.size(); i++ )
1301 1302 1303
            names[i] = projects.get(i).getName();

        String nearest = EditDistance.findNearest(name, names);
1304
        return (AbstractProject)Hudson.getInstance().getItem(nearest);
1305
    }
1306 1307 1308

    private static final Comparator<Integer> REVERSE_INTEGER_COMPARATOR = new Comparator<Integer>() {
        public int compare(Integer o1, Integer o2) {
1309
            return o2-o1;
1310 1311
        }
    };
1312

1313
    private static final Logger LOGGER = Logger.getLogger(AbstractProject.class.getName());
1314

K
kohsuke 已提交
1315 1316
    public static final Permission BUILD = new Permission(PERMISSIONS, "Build", Messages._AbstractProject_BuildPermission_Description(),  Permission.UPDATE);
    public static final Permission WORKSPACE = new Permission(PERMISSIONS, "Workspace", Messages._AbstractProject_WorkspacePermission_Description(), Permission.READ);
1317
    /**
1318
     * Permission to abort a build. For now, let's make it the same as {@link #BUILD}
1319 1320
     */
    public static final Permission ABORT = BUILD;
1321
}
1322