下面列出了怎么用hudson.model.AbstractProject的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Performs on-the-fly validation on the ant pattern for input files.
*
* @param project
* the project
* @param pattern
* the file pattern
*
* @return the validation result
*/
public FormValidation doCheckPattern(@AncestorInPath final AbstractProject<?, ?> project,
@QueryParameter final String pattern) {
if (project != null) { // there is no workspace in pipelines
try {
FilePath workspace = project.getSomeWorkspace();
if (workspace != null && workspace.exists()) {
return validatePatternInWorkspace(pattern, workspace);
}
}
catch (InterruptedException | IOException ignore) {
// ignore and return ok
}
}
return FormValidation.ok();
}
/**
* Performs on-the-fly validation on the source code directory.
*
* @param project
* the project
* @param sourceDirectory
* the file pattern
*
* @return the validation result
*/
public FormValidation doCheckSourceDirectory(@AncestorInPath final AbstractProject<?, ?> project,
@QueryParameter final String sourceDirectory) {
if (project != null) { // there is no workspace in pipelines
try {
FilePath workspace = project.getSomeWorkspace();
if (workspace != null && workspace.exists()) {
return validateRelativePath(sourceDirectory, workspace);
}
}
catch (InterruptedException | IOException ignore) {
// ignore and return ok
}
}
return FormValidation.ok();
}
/**
* support matrix plugin.
*
* @see JobInfoHelpers#triggerFrom(hudson.model.Job, java.lang.Class)
*/
@CheckForNull
public static <T extends Trigger> T triggerFrom(final Job<?, ?> job, Class<T> tClass) {
Job<?, ?> guessJob;
if (job instanceof MatrixConfiguration) {
guessJob = ((MatrixConfiguration) job).getParent();
} else {
guessJob = job;
}
if (guessJob instanceof AbstractProject<?, ?>) {
final AbstractProject<?, ?> abstractProject = (AbstractProject<?, ?>) guessJob;
return abstractProject.getTrigger(tClass);
} else if (guessJob instanceof ParameterizedJobMixIn.ParameterizedJob) {
ParameterizedJobMixIn.ParameterizedJob pJob = (ParameterizedJobMixIn.ParameterizedJob) guessJob;
for (Object candidate : pJob.getTriggers().values()) {
if (tClass.isInstance(candidate)) {
return tClass.cast(candidate);
}
}
}
return null;
}
@SuppressWarnings("deprecation") // calls getProject in constructor, so needs owner immediately
public TestResultAction(String jobs, boolean includeFailedBuilds, AbstractBuild<?,?> owner) {
super(owner);
this.includeFailedBuilds = includeFailedBuilds;
if(jobs==null) {
// resolve null as the transitive downstream jobs
StringBuilder buf = new StringBuilder();
for (AbstractProject p : getProject().getTransitiveDownstreamProjects()) {
if(buf.length()>0) buf.append(',');
buf.append(p.getFullName());
}
jobs = buf.toString();
}
this.jobs = jobs;
}
/**
* Returns the most recent build which contained an AWS Device Farm test run.
*
* @param project The Jenkins project which contains runs to examine.
* @return The previous Device Farm build.
*/
public static AbstractBuild<?, ?> previousAWSDeviceFarmBuild(AbstractProject<?, ?> project) {
AbstractBuild<?, ?> last = project.getLastBuild();
while (last != null) {
if (last.getAction(AWSDeviceFarmTestResultAction.class) != null) {
break;
}
last = last.getPreviousBuild();
}
return last;
}
public DockerSwarmComputerLauncher(final Queue.BuildableItem bi) {
super(DockerSwarmCloud.get().getTunnel(), null, new RemotingWorkDirSettings(false, "/tmp", null, false));
this.bi = bi;
this.label = bi.task.getAssignedLabel().getName();
this.jobName = bi.task instanceof AbstractProject ? ((AbstractProject) bi.task).getFullName()
: bi.task.getName();
}
@Deprecated
// Keeping this so we can more easily migrate from existing systems
public void restoreFromDb(final AbstractProject project, final Map<String, Object> input) {
this.id = (ObjectId) input.get("_id");
final String state = ((String) input.get("state"));
setField(getState(state), "state");
final Date date = ((Date) input.get("last_updated"));
setField(date.getTime(), "timestamp");
setField(project, "project");
super.onLoad();
}
@Override
public void onUpdated(Item item) {
TemplateProperty property = getTemplateProperty(item);
if (property != null) {
try {
TemplateUtils.handleTemplateSaved((AbstractProject) item, property);
} catch (Exception e) {
throw Throwables.propagate(e);
}
}
}
/**
* @param item A changed project
* @return null if this is not a template implementation project
*/
private static TemplateImplementationProperty getTemplateImplementationProperty(Item item) {
if (item instanceof AbstractProject) {
return (TemplateImplementationProperty) ((AbstractProject) item).getProperty(TemplateImplementationProperty.class);
}
return null;
}
public static Collection<AbstractProject> getImplementations(final String templateFullName) {
Collection<AbstractProject> projects = ProjectUtils.findProjectsWithProperty(TemplateImplementationProperty.class);
return Collections2.filter(projects, new Predicate<AbstractProject>() {
public boolean apply(AbstractProject abstractProject) {
TemplateImplementationProperty prop = (TemplateImplementationProperty) abstractProject.getProperty(TemplateImplementationProperty.class);
return templateFullName.equals(prop.getTemplateJobName());
}
});
}
@Override
public void start(AbstractProject project, boolean newInstance) {
this.job = project;
try {// reparse the tabs with the job as the hash
cronTabList = ParameterizedCronTabList.create(parameterizedSpecification, Hash.from(project.getFullName()));
} catch (ANTLRException e) {
// this shouldn't fail because we've already parsed stuff in the constructor,
// so if it fails, use whatever 'tabs' that we already have.
LOGGER.log(Level.FINE, "Failed to parse crontab spec: " + spec, e);
}
}
/**
* Jenkins-convention to populate the drop-down box with discovered templates
*/
@SuppressWarnings("UnusedDeclaration")
public ListBoxModel doFillTemplateJobNameItems() {
ListBoxModel items = new ListBoxModel();
// Add null as first option - dangerous to force an existing project onto a template in case
// a noob destroys their config
items.add(Messages.TemplateImplementationProperty_noTemplateSelected(), null);
// Add all discovered templates
for (AbstractProject project : ProjectUtils.findProjectsWithProperty(TemplateProperty.class)) {
// fullName includes any folder structure
items.add(project.getFullDisplayName(), project.getFullName());
}
return items;
}
@SuppressWarnings("unchecked")
FineGrainedNotifier getNotifier(AbstractProject project, TaskListener listener) {
Map<Descriptor<Publisher>, Publisher> map = project.getPublishersList().toMap();
for (Publisher publisher : map.values()) {
if (publisher instanceof MattermostNotifier) {
return new ActiveNotifier((MattermostNotifier) publisher, (BuildListener) listener, new JenkinsTokenExpander(listener));
}
}
return new DisabledNotifier();
}
/**
* Get a project by its fullName (including any folder structure if present).
* Temporarily also allows a match by name if one exists.
*/
public static AbstractProject findProject(String fullName) {
List<AbstractProject> projects = Jenkins.getInstance().getAllItems(AbstractProject.class);
AbstractProject nameOnlyMatch = null; // marc: 20140831, Remove compat patch for users upgrading
for (AbstractProject project : projects) {
if (fullName.equals(project.getFullName())) {
return project;
}
if (fullName.equals(project.getName())) {
nameOnlyMatch = project;
}
}
return nameOnlyMatch;
}
public static void makeDisabled(Object item, boolean b) throws IOException {
if (item instanceof AbstractFolder) {
Disabler.makeDisabled((AbstractFolder) item, b);
}
if (item instanceof AbstractProject) {
Disabler.makeDisabled((AbstractProject) item, b);
}
if (item instanceof ParameterizedJobMixIn.ParameterizedJob ) {
Disabler.makeDisabled((ParameterizedJobMixIn.ParameterizedJob ) item, b);
}
}
@SuppressFBWarnings(value = "NP_BOOLEAN_RETURN_NULL", justification = "isDisabled will return null if the job type doesn't support it")
public static Boolean isDisabled(Object item) {
if (item instanceof AbstractFolder) {
return Disabler.isDisabled((AbstractFolder) item);
}
if (item instanceof AbstractProject) {
return Disabler.isDisabled((AbstractProject) item);
}
if (item instanceof ParameterizedJobMixIn.ParameterizedJob ) {
return Disabler.isDisabled((ParameterizedJobMixIn.ParameterizedJob ) item);
}
return null;
}
@Override
public void onUpdated(Item item) {
TemplateImplementationProperty property = getTemplateImplementationProperty(item);
if (property != null) {
try {
TemplateUtils.handleTemplateImplementationSaved((AbstractProject) item, property);
} catch (Exception e) {
throw Throwables.propagate(e);
}
}
}
@Test(expected=InvalidInputException.class)
public void testNonExistentCreds() {
String credentialsId = "folder-creds";
String folder = "folder";
when(CredentialsMatchers.firstOrNull(any(Iterable.class), any(CredentialsMatcher.class))).thenReturn(null);
Jenkins mockInstance = mock(Jenkins.class);
Item mockFolder = mock(Item.class);
PowerMockito.mockStatic(Jenkins.class);
when(Jenkins.getInstance()).thenReturn(mockInstance);
when(mockInstance.getItemByFullName(credentialsId)).thenReturn(mockFolder);
PowerMockito.mockStatic(CredentialsProvider.class);
AbstractProject mockProject = mock(AbstractProject.class);
ItemGroup mockFolderItem = mock(ItemGroup.class);
when(build.getParent()).thenReturn(mockProject);
when(mockProject.getParent()).thenReturn(mockFolderItem);
when(mockFolder.getFullName()).thenReturn(folder);
try {
new AWSClientFactory("jenkins", credentialsId, "", "", "", null, "", REGION, build, null);
} catch (InvalidInputException e) {
assert(e.getMessage().contains(CodeBuilderValidation.invalidCredentialsIdError));
throw e;
}
}
static AbstractBuild mockSimpleBuild(String gitLabConnection, Result result, String... remoteUrls) {
AbstractBuild build = mock(AbstractBuild.class);
BuildData buildData = mock(BuildData.class);
when(buildData.getRemoteUrls()).thenReturn(new HashSet<>(Arrays.asList(remoteUrls)));
when(build.getAction(BuildData.class)).thenReturn(buildData);
when(build.getResult()).thenReturn(result);
when(build.getUrl()).thenReturn(BUILD_URL);
when(build.getResult()).thenReturn(result);
when(build.getNumber()).thenReturn(BUILD_NUMBER);
AbstractProject<?, ?> project = mock(AbstractProject.class);
when(project.getProperty(GitLabConnectionProperty.class)).thenReturn(new GitLabConnectionProperty(gitLabConnection));
when(build.getProject()).thenReturn(project);
return build;
}
@Override
public BuildStepDescriptor<Publisher> getDescriptor() {
return new BuildStepDescriptor<Publisher>() {
@Override
public boolean isApplicable(Class<? extends AbstractProject> jobType) {
return true;
}
};
}
@Override
protected PollingResult compareRemoteRevisionWith(
final AbstractProject<?, ?> project,
final Launcher launcher,
final FilePath filePath,
final TaskListener listener,
final SCMRevisionState revisionState)
throws IOException, InterruptedException {
final ActionTypeId actionTypeId = new ActionTypeId()
.withCategory(actionTypeCategory)
.withOwner(ActionOwner.Custom)
.withProvider(actionTypeProvider)
.withVersion(actionTypeVersion);
final String projectName = Validation.sanitize(project.getName().trim());
LoggingHelper.log(listener, "Polling for jobs for action type id: ["
+ "Owner: %s, Category: %s, Provider: %s, Version: %s, ProjectName: %s]",
actionTypeId.getOwner(),
actionTypeId.getCategory(),
actionTypeId.getProvider(),
actionTypeId.getVersion(),
project.getName());
return pollForJobs(projectName, actionTypeId, listener);
}
/**
* @param item A changed project
* @return null if this is not a template project
*/
private static TemplateProperty getTemplateProperty(Item item) {
if (item instanceof AbstractProject) {
return (TemplateProperty) ((AbstractProject) item).getProperty(TemplateProperty.class);
}
return null;
}
@Override
public boolean isApplicable(Class<? extends AbstractProject> aClass) {
return true;
}
@Override
public boolean isApplicable(Class<? extends AbstractProject> aClass) {
return true;
}
public boolean isApplicable(Class<? extends AbstractProject> aClass) {
return true;
}
public boolean isApplicable(Class<? extends AbstractProject> aClass) {
// Indicates that this builder can be used with all kinds of project types
return true;
}
@Override
public boolean isApplicable(Class<? extends AbstractProject> aClass) {
// Indicates that this builder can be used with all kinds of project
// types
return true;
}
@Override
public int compare(AbstractProject<?, ?> a, AbstractProject<?,?> b) {
return compareEstimatedDuration(a, b);
}
@Override
public boolean isApplicable(Class<? extends AbstractProject> aClass) {
return true;
}
@Override
public boolean isApplicable(
@SuppressWarnings("rawtypes") final Class<? extends AbstractProject> jobType) {
return true;
}