Java Examples for hudson.model.Project

The following java examples will help you to understand the usage of hudson.model.Project. These source code samples are taken from different open source projects.

Example 1
Project: analysis-core-plugin-master  File: HealthAwareRecorder.java View source code
/**
     * Returns whether the current build uses maven.
     *
     * @param build
     *            the current build
     * @return <code>true</code> if the current build uses maven,
     *         <code>false</code> otherwise
     * @deprecated use {@link #isMavenBuild(Run)} instead
     */
@Deprecated
protected boolean isMavenBuild(final AbstractBuild<?, ?> build) {
    if (build.getProject() instanceof Project) {
        Project<?, ?> project = (Project<?, ?>) build.getProject();
        for (Builder builder : project.getBuilders()) {
            if (builder instanceof Maven) {
                return true;
            }
        }
    }
    return false;
}
Example 2
Project: hudson_plugins-master  File: HealthAwarePublisher.java View source code
/**
     * Returns whether the current build uses maven.
     *
     * @param build
     *            the current build
     * @return <code>true</code> if the current build uses maven,
     *         <code>false</code> otherwise
     */
protected boolean isMavenBuild(final AbstractBuild<?, ?> build) {
    if (build.getProject() instanceof Project) {
        Project<?, ?> project = (Project<?, ?>) build.getProject();
        for (Builder builder : project.getBuilders()) {
            if (builder instanceof Maven) {
                return true;
            }
        }
    }
    return false;
}
Example 3
Project: parameterized-trigger-plugin-master  File: FileBuildTriggerConfigTest.java View source code
@Test
public void test() throws Exception {
    Project projectA = r.createFreeStyleProject("projectA");
    String properties = "KEY=value";
    projectA.setScm(new SingleFileSCM("properties.txt", properties));
    projectA.getPublishersList().add(new BuildTrigger(new BuildTriggerConfig("projectB", ResultCondition.SUCCESS, new FileBuildParameters("properties.txt"))));
    CaptureEnvironmentBuilder builder = new CaptureEnvironmentBuilder();
    Project projectB = r.createFreeStyleProject("projectB");
    projectB.getBuildersList().add(builder);
    projectB.setQuietPeriod(1);
    // SECURITY-170: must define parameters in subjobs
    List<ParameterDefinition> definition = new ArrayList<ParameterDefinition>();
    definition.add(new StringParameterDefinition("KEY", "key"));
    projectB.addProperty(new ParametersDefinitionProperty(definition));
    r.jenkins.rebuildDependencyGraph();
    projectA.scheduleBuild2(0).get();
    r.jenkins.getQueue().getItem(projectB).getFuture().get();
    assertNotNull("builder should record environment", builder.getEnvVars());
    assertEquals("value", builder.getEnvVars().get("KEY"));
}
Example 4
Project: docker-plugin-master  File: DockerQueueListener.java View source code
/**
     * Helper method to determine the template from a given item.
     * 
     * @param item Item which includes a template.
     * @return If the item includes a template then the template will be returned. Otherwise <code>null</code>.
     */
private DockerJobTemplateProperty getJobTemplate(Item item) {
    if (item.task instanceof Project) {
        Project<?, ?> project = (Project<?, ?>) item.task;
        if (project != null) {
            DockerJobProperty property = project.getProperty(DockerJobProperty.class);
            if (property != null) {
                return property.getDockerJobTemplate();
            }
        }
    }
    return null;
}
Example 5
Project: jenkow-plugin-master  File: JenkinsTaskDelegate.java View source code
@Override
public final void execute(ActivityExecution exec) throws Exception {
    LOG.finer("JenkinsTaskDelegate.execute()");
    String aid = exec.getActivity().getId();
    System.out.println("execution.id                       = " + exec.getId());
    System.out.println("execution.activity.id              = " + aid);
    System.out.println("execution.activity.procDef.id      = " + exec.getActivity().getProcessDefinition().getId());
    System.out.println("execution.activity.processDef.name = " + exec.getActivity().getProcessDefinition().getName());
    System.out.println("execution variables:");
    for (String vn : exec.getVariableNames()) {
        System.out.println("  " + vn + "=" + exec.getVariable(vn));
    }
    Integer loopCounter = (Integer) exec.getVariable("loopCounter");
    String jn = (jobName == null) ? null : jobName.getValue(exec).toString();
    LOG.finer("jobName=" + jn);
    boolean isManual = (isManualJobLaunchMode != null && Boolean.parseBoolean(isManualJobLaunchMode.getValue(exec).toString()));
    LOG.finer("isManual=" + isManual);
    JenkowAction ja = new JenkowAction(aid, exec.getId(), jn);
    LOG.finer("ja=" + ja);
    if (isManual) {
        // TODO 9: move jenkow variables into JenkowProcessData
        Object jbp = exec.getVariable("jenkow_build_parent");
        JenkowAction.setDeferredAction((jbp == null) ? null : jbp.toString(), ja);
        // TODO 9: log to build console "awaiting completion of job xyz"
        return;
    }
    if (jn != null) {
        Jenkins jenkins = Jenkins.getInstance();
        TopLevelItem it = jenkins.getItem(jn);
        if (it == null) {
            LOG.info("unable to launch job " + jn + ", it=null");
        } else if (!(it instanceof Project)) {
            LOG.info("unable to launch job " + jn + ", because it's not a Project, but just " + it.getClass());
        } else {
            // TODO 8: would like to have AbstractProject here, but it doesn't have BuildWrappers.
            Project p = (Project) it;
            DescribableList wrappers = p.getBuildWrappersList();
            JenkowBuildWrapper wrapper = new JenkowBuildWrapper();
            if (!wrappers.contains(wrapper.getDescriptor()))
                wrappers.add(wrapper);
            p.scheduleBuild2(jenkins.getQuietPeriod(), new WorkflowCause("triggered by workflow"), ja);
            return;
        }
    }
    // TODO 9: need test for Jenkins task with empty / non-existing job name
    leave(exec);
}
Example 6
Project: SCM-master  File: AccurevPlugin.java View source code
/**
     * We need ensure that migrator will run after jobs are loaded
     * Launches migration after plugin and jobs already initialized.
     * Expected milestone: @Initializer(after = JOB_LOADED)
     *
     * @throws Exception Exceptions
     */
@Initializer(after = JOB_LOADED, before = COMPLETED)
public static void migrateJobsToServerUUID() throws Exception {
    final Jenkins jenkins = Jenkins.getInstance();
    boolean changed = false;
    AccurevSCMDescriptor descriptor = jenkins.getDescriptorByType(AccurevSCMDescriptor.class);
    for (Project<?, ?> p : jenkins.getAllItems(Project.class)) {
        if (p.getScm() instanceof AccurevSCM) {
            AccurevSCM scm = (AccurevSCM) p.getScm();
            String serverUUID = scm.getServerUUID();
            if (UUIDUtils.isNotValid(serverUUID) || descriptor.getServer(serverUUID) == null) {
                AccurevServer server = descriptor.getServer(scm.getServerName());
                if (server == null) {
                    LOGGER.warning("No server found with that name, Project: " + p.getName() + " Server Name: " + scm.getServerName());
                } else {
                    changed = true;
                    String uuid = server.getUuid();
                    scm.setServerUUID(uuid);
                    p.save();
                }
            }
        }
    }
    if (changed)
        descriptor.save();
}
Example 7
Project: performance-plugin-master  File: TestSuiteReportDetailTest.java View source code
@Test
@SuppressWarnings("UnnecessaryBoxing")
public void chartDatasetHasAverageOfSamples() throws Exception {
    run.number = 1;
    when(run.getAction(PerformanceBuildAction.class)).thenReturn(buildAction);
    when(buildAction.getPerformanceReportMap()).thenReturn(reportMap);
    when(reportMap.getPerformanceReport(FILENAME)).thenReturn(report);
    when(report.getUriReportMap()).thenReturn(uriReportMap);
    final TestSuiteReportDetail reportDetail = new TestSuiteReportDetail(mock(Project.class), FILENAME, alwaysInRangeMock());
    final CategoryDataset dataset = reportDetail.getChartDatasetBuilderForBuilds(TEST_URI, RunList.fromRuns(Collections.singletonList(run))).build();
    assertEquals(dataset.getValue(TEST_URI, new ChartUtil.NumberOnlyBuildLabel((Run<?, ?>) run)), new Long(550L));
}
Example 8
Project: template-project-plugin-master  File: ProxyBuildEnvironment.java View source code
public List<BuildWrapper> getProjectBuildWrappers(AbstractBuild<?, ?> build) {
    AbstractProject p = TemplateUtils.getProject(getProjectName(), build);
    if (p instanceof Project) {
        return ((Project) p).getBuildWrappersList();
    } else if (p instanceof MatrixProject) {
        return ((MatrixProject) p).getBuildWrappersList();
    } else {
        return Collections.emptyList();
    }
}
Example 9
Project: branch-api-plugin-master  File: BranchProjectFactory.java View source code
/**
     * Decorates the project in with all the {@link JobDecorator} instances.
     * NOTE: This method should suppress saving the project and only affect the in-memory state.
     * NOTE: Override if the default strategy is not appropriate for the specific project type.
     *
     * @param project the project.
     * @return the project for nicer method chaining
     */
@SuppressWarnings({ "ConstantConditions", "unchecked" })
public P decorate(P project) {
    if (!isProject(project)) {
        return project;
    }
    Branch branch = getBranch(project);
    // HACK ALERT
    // ==========
    // We don't want to trigger a save, so we will do some trickery to inject the new values
    // it would be better if Core gave us some hooks to do this
    BulkChange bc = new BulkChange(project);
    try {
        List<BranchProperty> properties = new ArrayList<BranchProperty>(branch.getProperties());
        Collections.sort(properties, DescriptorOrder.reverse(BranchProperty.class));
        for (BranchProperty property : properties) {
            JobDecorator<P, R> decorator = property.jobDecorator(project.getClass());
            if (decorator != null) {
                // if Project then we can feed the publishers and build wrappers
                if (project instanceof Project && decorator instanceof ProjectDecorator) {
                    DescribableList<Publisher, Descriptor<Publisher>> publishersList = ((Project) project).getPublishersList();
                    DescribableList<BuildWrapper, Descriptor<BuildWrapper>> buildWrappersList = ((Project) project).getBuildWrappersList();
                    List<Publisher> publishers = ((ProjectDecorator) decorator).publishers(publishersList.toList());
                    List<BuildWrapper> buildWrappers = ((ProjectDecorator) decorator).buildWrappers(buildWrappersList.toList());
                    publishersList.replaceBy(publishers);
                    buildWrappersList.replaceBy(buildWrappers);
                }
                // we can always feed the job properties... but just not as easily as we'd like
                List<JobProperty<? super P>> jobProperties = decorator.jobProperties(project.getAllProperties());
                // both removal and addition
                for (JobProperty<? super P> p : project.getAllProperties()) {
                    project.removeProperty(p);
                }
                for (JobProperty<? super P> p : jobProperties) {
                    project.addProperty(p);
                }
                // now apply the final layer
                decorator.project(project);
            }
        }
    } catch (IOException e) {
    } finally {
        bc.abort();
    }
    return project;
}
Example 10
Project: dockerhub-notification-plugin-master  File: DockerPullImageBuilder.java View source code
@Nonnull
@Override
public Collection<String> getDockerImagesUsedByJob(@Nonnull Job<?, ?> job) {
    if (job instanceof Project) {
        Project<? extends Project, ? extends Build> project = (Project<?, ? extends Build>) job;
        Set<String> images = new HashSet<String>();
        // check DockerHub build step for matching image ID
        for (Builder b : project.getBuilders()) {
            if (b instanceof DockerPullImageBuilder) {
                images.add(((DockerPullImageBuilder) b).getImage());
            }
        }
        return images;
    } else {
        return Collections.emptySet();
    }
}
Example 11
Project: hudson-main-master  File: BuildTrigger.java View source code
/**
     * Convenience method to trigger downstream builds.
     *
     * @param build
     *      The current build. Its downstreams will be triggered.
     * @param listener
     *      Receives the progress report.
     */
public static boolean execute(AbstractBuild build, BuildListener listener) {
    PrintStream logger = listener.getLogger();
    // Check all downstream Project of the project, not just those defined by BuildTrigger
    final DependencyGraph graph = Hudson.getInstance().getDependencyGraph();
    List<Dependency> downstreamProjects = new ArrayList<Dependency>(graph.getDownstreamDependencies(build.getProject()));
    // Sort topologically
    Collections.sort(downstreamProjects, new Comparator<Dependency>() {

        public int compare(Dependency lhs, Dependency rhs) {
            // Swapping lhs/rhs to get reverse sort:
            return graph.compare(rhs.getDownstreamProject(), lhs.getDownstreamProject());
        }
    });
    for (Dependency dep : downstreamProjects) {
        AbstractProject p = dep.getDownstreamProject();
        if (p.isDisabled()) {
            logger.println(Messages.BuildTrigger_Disabled(p.getName()));
            continue;
        }
        List<Action> buildActions = new ArrayList<Action>();
        if (dep.shouldTriggerBuild(build, listener, buildActions)) {
            // this is not completely accurate, as a new build might be triggered
            // between these calls
            String name = p.getName() + " #" + p.getNextBuildNumber();
            if (p.scheduleBuild(p.getQuietPeriod(), new UpstreamCause((Run) build), buildActions.toArray(new Action[buildActions.size()]))) {
                logger.println(Messages.BuildTrigger_Triggering(name));
            } else {
                logger.println(Messages.BuildTrigger_InQueue(name));
            }
        }
    }
    return true;
}
Example 12
Project: hudson-test-harness-master  File: TestResultPublishingTest.java View source code
/**
     * Verify that we can successfully parse and display test results in the
     * open junit test result publishing toolchain. Ensure that we meet this
     * compatibility requirement:
     * From users' point of view, Hudson core JUnit should continue
     * to work as if nothing has changed
     * - Old testReport URLs should still work
     */
@LocalData
public void testOpenJUnitPublishing() throws IOException, SAXException {
    List<Project> projects = this.hudson.getProjects();
    // Make sure there's a project named TEST_PROJECT_WITH_HISTORY
    Project proj = null;
    for (Project p : projects) {
        if (p.getName().equals(TEST_PROJECT_WITH_HISTORY))
            proj = p;
    }
    assertNotNull("We should have a project named " + TEST_PROJECT_WITH_HISTORY, proj);
    // Validate that there are test results where I expect them to be:
    HudsonTestCase.WebClient wc = new HudsonTestCase.WebClient();
    // On the project page:
    HtmlPage projectPage = wc.getPage(proj);
    //      we should have a link that reads "Latest Test Result"
    //      that link should go to http://localhost:8080/job/breakable/lastBuild/testReport/
    assertXPath(projectPage, "//a[@href='lastCompletedBuild/testReport/']");
    //TODO fix it
    // assertXPathValue(projectPage, "//a[@href='lastCompletedBuild/testReport/']", "Latest Test Result");
    //assertXPathValueContains(projectPage, "//a[@href='lastCompletedBuild/testReport/']", "Latest Test Result");
    //      after "Latest Test Result" it should say "no failures"
    assertXPathResultsContainText(projectPage, "//td", "(no failures)");
    //      there should be a test result trend graph
    assertXPath(projectPage, "//img[@src='test/trend']");
    // the trend graph should be served up with a good http status
    Page trendGraphPage = wc.goTo(proj.getUrl() + "/test/trend", "image/png");
    assertGoodStatus(trendGraphPage);
    // The trend graph should be clickable and take us to a run details page
    Object imageNode = projectPage.getFirstByXPath("//img[@src='test/trend']");
    assertNotNull("couldn't find any matching nodes", imageNode);
    assertTrue("image node should be an HtmlImage object", imageNode instanceof HtmlImage);
    // TODO: Check that we can click on the graph and get to a particular run. How do I do this with HtmlUnit?
    XmlPage xmlProjectPage = wc.goToXml(proj.getUrl() + "/lastBuild/testReport/api/xml");
    assertXPath(xmlProjectPage, "/testResult");
    assertXPath(xmlProjectPage, "/testResult/suite");
    assertXPath(xmlProjectPage, "/testResult/failCount");
    assertXPathValue(xmlProjectPage, "/testResult/failCount", "0");
    assertXPathValue(xmlProjectPage, "/testResult/passCount", "4");
    assertXPathValue(xmlProjectPage, "/testResult/skipCount", "0");
    String[] packages = { "org.jvnet.hudson.examples.small.AppTest", "org.jvnet.hudson.examples.small.MiscTest", "org.jvnet.hudson.examples.small.deep.DeepTest" };
    for (String packageName : packages) {
        assertXPath(xmlProjectPage, "/testResult/suite/case/className[text()='" + packageName + "']");
    }
    // Go to a page that we know has a failure
    HtmlPage buildPage = wc.getPage(proj.getBuildByNumber(3));
    assertGoodStatus(buildPage);
    // We expect to see one failure, for com.yahoo.breakable.misc.UglyTest.becomeUglier
    // which should link to http://localhost:8080/job/wonky/3/testReport/org.jvnet.hudson.examples.small/MiscTest/testEleanor/
    assertXPathResultsContainText(buildPage, "//a", "org.jvnet.hudson.examples.small.MiscTest.testEleanor");
    HtmlAnchor failingTestLink = buildPage.getFirstAnchorByText("org.jvnet.hudson.examples.small.MiscTest.testEleanor");
    assertNotNull(failingTestLink);
    Page failingTestPage = failingTestLink.click();
    assertGoodStatus(failingTestPage);
    // Go to the xml page for a build we know has failures
    XmlPage xmlBuildPage = wc.goToXml(proj.getBuildByNumber(3).getUrl() + "/api/xml");
    assertXPathValue(xmlBuildPage, "//failCount", "2");
    assertXPathValue(xmlBuildPage, "//skipCount", "0");
    assertXPathValue(xmlBuildPage, "//totalCount", "4");
    assertXPathValue(xmlBuildPage, "//result", "FAILURE");
    // Check overall test result counts
    XmlPage xmlTestReportPage = wc.goToXml(proj.getBuildByNumber(3).getUrl() + "/testReport/api/xml");
    assertXPathValue(xmlTestReportPage, "/testResult/failCount", "2");
    assertXPathValue(xmlTestReportPage, "/testResult/passCount", "2");
    assertXPathValue(xmlTestReportPage, "/testResult/skipCount", "0");
    // Make sure the right tests passed and failed
    assertXPathValue(xmlTestReportPage, "/testResult/suite/case[className/text()='org.jvnet.hudson.examples.small.AppTest']/status", "PASSED");
    assertXPathValue(xmlTestReportPage, "/testResult/suite/case[name/text()='testEleanor']/status", "FAILED");
    // TODO: implement more of these tests
    // On the lastBuild/testReport page:
    //      Breadcrumbs should read #6 > Test Result  where Test Result is a link to this page
    //      inside of div id="main-panel" we should find the text "0 failures (-1)"
    //      we should have a blue bar which is blue all the way across: div style="width: 100%; height: 1em; background-color: rgb(114, 159, 207);
    //      we should find the words "7 tests (?0)"
    //      we should find the words "All Tests"
    //      we should find a table
    //      Inside that table, there should be the following rows:
    //           org.jvnet.hudson.examples.small 	0ms   0 -1 0   3
    //          org.jvnet.hudson.examples.small.deep 	4ms 0 0 0  1
    Run theRun = proj.getBuildByNumber(7);
    assertTestResultsAsExpected(wc, theRun, "/testReport", "org.jvnet.hudson.examples.small", "0 ms", "SUCCESS", /* total tests expected, diff */
    3, 0, /* fail count expected, diff */
    0, -1, /* skip count expected, diff */
    0, 0);
    assertTestResultsAsExpected(wc, theRun, "/testReport", "org.jvnet.hudson.examples.small.deep", "4 ms", "SUCCESS", /* total tests expected, diff */
    1, 0, /* fail count expected, diff */
    0, 0, /* skip count expected, diff */
    0, 0);
// TODO: more, more, more.
// TODO: test report history by package
}
Example 13
Project: tap-plugin-master  File: PublishersCombinationTest.java View source code
@Issue("JENKINS-29649")
@LocalData
@Test
public void combinedWithJunitBasic() throws Exception {
    Project project = (Project) rule.jenkins.getItem("multiPublish");
    // Validate that there are test results where I expect them to be:
    JenkinsRule.WebClient wc = rule.createWebClient();
    // On the project page:
    HtmlPage projectPage = wc.getPage(project);
    assertJunitPart(projectPage, 3, 4);
    assertTapPart(projectPage, 3);
}
Example 14
Project: gearman-plugin-master  File: ExecutorWorkerThreadTest.java View source code
/*
     * This test verifies that gearman functions are correctly registered for a
     * project that contains a single label matching a label on the slave node
     */
@Test
public void testRegisterJobs_ProjectSingleLabel() throws Exception {
    Project<?, ?> lemon = createFreeStyleProject("lemon");
    lemon.setAssignedLabel(new LabelAtom("linux"));
    AbstractWorkerThread oneiric = new ExecutorWorkerThread("GearmanServer", 4730, "MyWorker", slave.toComputer(), "master", new NoopAvailabilityMonitor());
    oneiric.testInitWorker();
    oneiric.registerJobs();
    Set<String> functions = oneiric.worker.getRegisteredFunctions();
    assertEquals(2, functions.size());
    assertTrue(functions.contains("build:lemon"));
    assertTrue(functions.contains("build:lemon:linux"));
}
Example 15
Project: jobConfigHistory-plugin-master  File: JobConfigBadgeActionTest.java View source code
@Test
public void testListenerOnStarted() {
    final JobConfigBadgeAction.Listener psut = createListenerSut();
    when(mockedProject.getNextBuildNumber()).thenReturn(3);
    when(mockedProject.getLastBuild()).thenReturn(mockedBuild);
    // when(mockedHistoryDao.getRevisions(any(XmlFile.class))).thenReturn(null)
    final GregorianCalendar calendar = new GregorianCalendar(2013, 9, 30, 23, 0, 5);
    final Build<?, ?> previousBuild = new Build(mockedProject, calendar) {

        @Override
        public Project<?, ?> getParent() {
            return mockedProject;
        }
    };
    when(mockedBuild.getPreviousBuild()).thenReturn(previousBuild);
    psut.onStarted(mockedBuild, TaskListener.NULL);
}
Example 16
Project: qc-plugin-master  File: QualityCenterResultArchiver.java View source code
@Override
public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
    TestResultAction action;
    List<Builder> builders = ((Project) build.getProject()).getBuilders();
    final List<String> names = new ArrayList<String>();
    // Get the TestSet report files names of the current build
    for (Builder builder : builders) {
        if (builder instanceof QualityCenter) {
            List<String> files = ((QualityCenter) builder).getTestSetLogFiles();
            if (files != null && files.size() > 0) {
                // log files may not have been generated
                names.addAll(((QualityCenter) builder).getTestSetLogFiles());
            }
        }
    }
    // Has any QualityCenter builder been set up?
    if (names.isEmpty()) {
        listener.getLogger().println(Messages.QualityCenterResultArchiver_NoBuilderSet());
        return true;
    }
    try {
        final long buildTime = build.getTimestamp().getTimeInMillis();
        final long nowMaster = System.currentTimeMillis();
        TestResult result = build.getWorkspace().act(new FileCallable<TestResult>() {

            public TestResult invoke(File ws, VirtualChannel channel) throws IOException {
                final long nowSlave = System.currentTimeMillis();
                List<String> files = new ArrayList<String>();
                DirectoryScanner ds = new DirectoryScanner();
                ds.setBasedir(ws);
                // and add it to the DirectoryScanner includes set
                for (String name : names) {
                    if (name != null) {
                        // JENKINS-12389
                        File file = new File(ws, name);
                        if (file.exists()) {
                            files.add(file.getName());
                        }
                    }
                }
                Object[] objectArray = new String[files.size()];
                files.toArray(objectArray);
                ds.setIncludes((String[]) objectArray);
                ds.scan();
                if (ds.getIncludedFilesCount() == 0) {
                    // no test result. Most likely a configuration error or fatal problem
                    throw new AbortException("Report not found");
                }
                return new TestResult(buildTime + (nowSlave - nowMaster), ds, true);
            }
        });
        action = new TestResultAction(build, result, listener);
        if (result.getPassCount() == 0 && result.getFailCount() == 0) {
            throw new AbortException("Result is empty");
        }
    } catch (AbortException e) {
        if (build.getResult() == Result.FAILURE) {
            return true;
        }
        listener.getLogger().println(e.getMessage());
        build.setResult(Result.FAILURE);
        return true;
    } catch (IOException e) {
        e.printStackTrace(listener.error("Failed to archive QC reports"));
        build.setResult(Result.FAILURE);
        return true;
    }
    build.getActions().add(action);
    if (action.getResult().getFailCount() > 0) {
        build.setResult(Result.UNSTABLE);
    }
    return true;
}
Example 17
Project: Templating-master  File: ScaffoldAction.java View source code
public Map<String, String> getVariablesForImplementation(String jobName) {
    AbstractProject nearest = Project.findNearest(jobName);
    ImplementationBuildWrapper buildWrapper = BuildWrapperUtils.findBuildWrapper(ImplementationBuildWrapper.class, nearest);
    if (buildWrapper != null) {
        String variables = buildWrapper.getVariables();
        return CollectionUtils.expandToMap(variables);
    }
    return null;
}
Example 18
Project: uno-choice-plugin-master  File: AbstractScriptableParameter.java View source code
/**
     * Helper parameters used to render the parameter definition.
     * @return Map with helper parameters
     */
private Map<Object, Object> getHelperParameters() {
    // map with parameters
    final Map<Object, Object> helperParameters = new LinkedHashMap<Object, Object>();
    // First, if the project name is set, we then find the project by its name, and inject into the map
    Project<?, ?> project = null;
    if (StringUtils.isNotBlank(this.projectName)) {
        // first we try to get the item given its name, which is more efficient
        project = Utils.getProjectByName(this.projectName);
    } else {
        // otherwise, in case we don't have the item name, we iterate looking for a job that uses this UUID
        project = Utils.findProjectByParameterUUID(this.getRandomName());
    }
    if (project != null) {
        helperParameters.put(JENKINS_PROJECT_VARIABLE_NAME, project);
        AbstractBuild<?, ?> build = project.getLastBuild();
        if (build != null && build.getHasArtifacts()) {
            helperParameters.put(JENKINS_BUILD_VARIABLE_NAME, build);
        }
    }
    // Here we inject the global node properties
    final Map<String, Object> globalNodeProperties = Utils.getGlobalNodeProperties();
    helperParameters.putAll(globalNodeProperties);
    return helperParameters;
}
Example 19
Project: debian-package-builder-plugin-master  File: DebianPackageBuilder.java View source code
/**
	 * @param build
	 * @return all the {@link DebianPackageBuilder}s participating in this build
	 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static Collection<DebianPackageBuilder> getDPBuilders(AbstractBuild<?, ?> build) {
    ArrayList<DebianPackageBuilder> result = new ArrayList<DebianPackageBuilder>();
    if (build.getProject() instanceof Project) {
        DescribableList<Builder, Descriptor<Builder>> builders = ((Project) build.getProject()).getBuildersList();
        for (Builder builder : builders) {
            if (builder instanceof DebianPackageBuilder) {
                result.add((DebianPackageBuilder) builder);
            }
        }
    }
    return result;
}
Example 20
Project: hudson-2.x-master  File: BuildTrigger.java View source code
/**
     * Convenience method to trigger downstream builds.
     *
     * @param build
     *      The current build. Its downstreams will be triggered.
     * @param listener
     *      Receives the progress report.
     */
public static boolean execute(AbstractBuild build, BuildListener listener) {
    PrintStream logger = listener.getLogger();
    // Check all downstream Project of the project, not just those defined by BuildTrigger
    final DependencyGraph graph = Hudson.getInstance().getDependencyGraph();
    List<Dependency> downstreamProjects = new ArrayList<Dependency>(graph.getDownstreamDependencies(build.getProject()));
    // Sort topologically
    Collections.sort(downstreamProjects, new Comparator<Dependency>() {

        public int compare(Dependency lhs, Dependency rhs) {
            // Swapping lhs/rhs to get reverse sort:
            return graph.compare(rhs.getDownstreamProject(), lhs.getDownstreamProject());
        }
    });
    for (Dependency dep : downstreamProjects) {
        AbstractProject p = dep.getDownstreamProject();
        if (p.isDisabled()) {
            logger.println(Messages.BuildTrigger_Disabled(p.getName()));
            continue;
        }
        List<Action> buildActions = new ArrayList<Action>();
        if (dep.shouldTriggerBuild(build, listener, buildActions)) {
            // this is not completely accurate, as a new build might be triggered
            // between these calls
            String name = p.getName() + " #" + p.getNextBuildNumber();
            if (p.scheduleBuild(p.getQuietPeriod(), new UpstreamCause((Run) build), buildActions.toArray(new Action[buildActions.size()]))) {
                logger.println(Messages.BuildTrigger_Triggering(name));
            } else {
                logger.println(Messages.BuildTrigger_InQueue(name));
            }
        }
    }
    return true;
}
Example 21
Project: hudson.core-master  File: LegacyProjectTest.java View source code
/**
     * Tests unmarshalls FreeStyleProject configuration and checks whether Builders
     * from Project are configured
     *
     * @throws Exception if any.
     */
@Test
public void testConvertLegacyBuildersProperty() throws Exception {
    Project project = (Project) Items.getConfigFile(config).read();
    project.setAllowSave(false);
    project.initProjectProperties();
    //Property should be null, because of legacy implementation. Version < 2.2.0
    assertNull(project.getProperty(Project.BUILDERS_PROPERTY_NAME));
    project.convertBuildersProjectProperty();
    //Verify builders
    assertNotNull(project.getProperty(Project.BUILDERS_PROPERTY_NAME));
    assertFalse(project.getBuildersList().isEmpty());
    assertEquals(1, project.getBuildersList().size());
    assertTrue(project.getBuildersList().get(0) instanceof Maven);
}
Example 22
Project: jenkins-master  File: BuildTrigger.java View source code
/**
     * Convenience method to trigger downstream builds.
     *
     * @param build
     *      The current build. Its downstreams will be triggered.
     * @param listener
     *      Receives the progress report.
     */
public static boolean execute(AbstractBuild build, BuildListener listener) {
    PrintStream logger = listener.getLogger();
    // Check all downstream Project of the project, not just those defined by BuildTrigger
    // TODO this may not yet be up to date if rebuildDependencyGraphAsync has been used; need a method to wait for the last call made before now to finish
    final DependencyGraph graph = Jenkins.getInstance().getDependencyGraph();
    List<Dependency> downstreamProjects = new ArrayList<Dependency>(graph.getDownstreamDependencies(build.getProject()));
    // Sort topologically
    Collections.sort(downstreamProjects, new Comparator<Dependency>() {

        public int compare(Dependency lhs, Dependency rhs) {
            // Swapping lhs/rhs to get reverse sort:
            return graph.compare(rhs.getDownstreamProject(), lhs.getDownstreamProject());
        }
    });
    // from build
    Authentication auth = Jenkins.getAuthentication();
    if (auth.equals(ACL.SYSTEM)) {
        // i.e., unspecified
        if (QueueItemAuthenticatorDescriptor.all().isEmpty()) {
            if (downstreamProjects.isEmpty()) {
                return true;
            }
            logger.println(Messages.BuildTrigger_warning_you_have_no_plugins_providing_ac());
        } else if (QueueItemAuthenticatorConfiguration.get().getAuthenticators().isEmpty()) {
            if (downstreamProjects.isEmpty()) {
                return true;
            }
            logger.println(Messages.BuildTrigger_warning_access_control_for_builds_in_glo());
        } else {
            // This warning must be printed even if downstreamProjects is empty.
            // Otherwise you could effectively escalate DISCOVER to READ just by trying different project names and checking whether a warning was printed or not.
            // If there were an API to determine whether any DependencyDeclarer’s in this project requested downstream project names,
            // then we could suppress the warnings in case none did; but if any do, yet Items.fromNameList etc. ignore unknown projects,
            // that has to be treated the same as if there really are downstream projects but the anonymous user cannot see them.
            // For the above two cases, it is OK to suppress the warning when there are no downstream projects, since running as SYSTEM we would be able to see them anyway.
            logger.println(Messages.BuildTrigger_warning_this_build_has_no_associated_aut());
            auth = Jenkins.ANONYMOUS;
        }
    }
    for (Dependency dep : downstreamProjects) {
        List<Action> buildActions = new ArrayList<Action>();
        SecurityContext orig = ACL.impersonate(auth);
        try {
            if (dep.shouldTriggerBuild(build, listener, buildActions)) {
                AbstractProject p = dep.getDownstreamProject();
                // Allow shouldTriggerBuild to return false first, in case it is skipping because of a lack of Item.READ/DISCOVER permission:
                if (p.isDisabled()) {
                    logger.println(Messages.BuildTrigger_Disabled(ModelHyperlinkNote.encodeTo(p)));
                    continue;
                }
                boolean scheduled = p.scheduleBuild(p.getQuietPeriod(), new UpstreamCause((Run) build), buildActions.toArray(new Action[buildActions.size()]));
                if (Jenkins.getInstance().getItemByFullName(p.getFullName()) == p) {
                    String name = ModelHyperlinkNote.encodeTo(p);
                    if (scheduled) {
                        logger.println(Messages.BuildTrigger_Triggering(name));
                    } else {
                        logger.println(Messages.BuildTrigger_InQueue(name));
                    }
                }
            // otherwise upstream users should not know that it happened
            }
        } finally {
            SecurityContextHolder.setContext(orig);
        }
    }
    return true;
}
Example 23
Project: pipeline-sink-trigger-plugin-master  File: BuildGraphPipelineSinkTrigger.java View source code
@Override
public void onDeleted(Item item) {
    for (Project<?, ?> p : Hudson.getInstance().getProjects()) {
        final BuildGraphPipelineSinkTrigger trigger = p.getTrigger(BuildGraphPipelineSinkTrigger.class);
        if (trigger != null) {
            if (trigger.onJobDeleted(item.getName())) {
                try {
                    p.save();
                } catch (IOException e) {
                    LOGGER.log(Level.WARNING, String.format("Failed to persist project setting during deletion of %s", item.getName()), e);
                }
            }
        }
    }
}
Example 24
Project: rebuild-plugin-master  File: RebuildValidatorTest.java View source code
/**
	 * Tests with an extension returning isApplicable true.
	 *
	 * @throws IOException
	 *             IOException
	 * @throws InterruptedException
	 *             InterruptedException
	 * @throws ExecutionException
	 *             ExecutionException
	 */
public void testRebuildValidatorExtensionIsApplicableTrue() throws IOException, InterruptedException, ExecutionException {
    hudson.getExtensionList(RebuildValidator.class).add(0, new ValidatorAlwaysApplicable());
    Project projectA = createFreeStyleProject("testFreeStyleB");
    Build buildA = (Build) projectA.scheduleBuild2(0, new Cause.UserIdCause(), new ParametersAction(new StringParameterValue("party", "megaparty"))).get();
    assertNull(buildA.getAction(RebuildAction.class));
}
Example 25
Project: viola-master  File: ViolationsReport.java View source code
/**
     * get the configuration for this job.
     *
     * @return the configuration of the job.
     */
public ViolationsConfig getLiveConfig() {
    AbstractProject<?, ?> abstractProject = build.getProject();
    if (abstractProject instanceof Project) {
        Project project = (Project) abstractProject;
        ViolationsPublisher publisher = (ViolationsPublisher) project.getPublisher(ViolationsPublisher.DESCRIPTOR);
        return publisher == null ? null : publisher.getConfig();
    }
    return null;
}
Example 26
Project: violations-plugin-master  File: ViolationsReport.java View source code
/**
     * get the configuration for this job.
     *
     * @return the configuration of the job.
     */
public ViolationsConfig getLiveConfig() {
    AbstractProject<?, ?> abstractProject = build.getProject();
    if (abstractProject instanceof Project) {
        Project project = (Project) abstractProject;
        ViolationsPublisher publisher = (ViolationsPublisher) project.getPublisher(ViolationsPublisher.DESCRIPTOR);
        return publisher == null ? null : publisher.getConfig();
    }
    return null;
}
Example 27
Project: ivy-plugin-master  File: IvyBuildTrigger.java View source code
/**
     * Force the creation of the module descriptor.  This should only get
     * called if the node that last built this project is offline, then
     * we just use the backup ivy file if it is available
     *
     * @param  b  a project this trigger belongs to
     */
private ModuleDescriptor recomputeModuleDescriptor(AbstractProject b) {
    LOGGER.fine("Recomputing Moduledescriptor for Project " + b.getFullDisplayName() + " using backup files");
    final File destDir = b.getRootDir();
    String propertyFileToLoadIntoIvy = null;
    String propertyFile = getIvyPropertiesFile();
    File ivyP = new File(destDir, BACKUP_IVY_PROPERTIES_NAME);
    if (propertyFile != null && !propertyFile.trim().isEmpty()) {
        if (ivyP.canRead()) {
            propertyFileToLoadIntoIvy = BACKUP_IVY_PROPERTIES_NAME;
        }
    }
    Ivy ivy = getIvy(destDir, propertyFileToLoadIntoIvy);
    if (ivy == null) {
        return null;
    }
    versionMatcher = ivy.getSettings().getVersionMatcher();
    String ivyDesc = getIvyFile();
    File ivyF = null;
    if (ivyDesc != null && !ivyDesc.trim().isEmpty()) {
        ivyF = new File(destDir, BACKUP_IVY_FILE_NAME);
    }
    final File fivyF = ivyF;
    // Calculate ModuleDescriptor from the backup copy 
    if (fivyF == null || !fivyF.canRead()) {
        LOGGER.log(Level.WARNING, "Cannot read ivy file backup...removing ModuleDescriptor");
        return null;
    }
    if (moduleDescriptor == null || fivyF.lastModified() > lastmodified) {
        lastmodified = fivyF.lastModified();
        return (ModuleDescriptor) ivy.execute(new IvyCallback() {

            public Object doInIvyContext(Ivy ivy, IvyContext context) {
                try {
                    return ModuleDescriptorParserRegistry.getInstance().parseDescriptor(ivy.getSettings(), fivyF.toURI().toURL(), ivy.getSettings().doValidate());
                } catch (MalformedURLException e) {
                    LOGGER.log(Level.WARNING, "The URL is malformed : " + fivyF, e);
                    return null;
                } catch (ParseException e) {
                    LOGGER.log(Level.WARNING, "Parsing error while reading the ivy file " + fivyF, e);
                    return null;
                } catch (IOException e) {
                    LOGGER.log(Level.WARNING, "I/O error while reading the ivy file " + fivyF, e);
                    return null;
                }
            }
        });
    }
    return null;
}
Example 28
Project: plugin-ivy-master  File: IvyBuildTrigger.java View source code
/**
     * Force the creation of the module descriptor.  This should only get
     * called if the node that last built this project is offline, then
     * we just use the backup ivy file if it is available
     *
     * @param  b  a project this trigger belongs to
     */
private ModuleDescriptor recomputeModuleDescriptor(AbstractProject b) {
    LOGGER.fine("Recomputing Moduledescriptor for Project " + b.getFullDisplayName() + " using backup files");
    final File destDir = b.getRootDir();
    String propertyFileToLoadIntoIvy = null;
    String propertyFile = getIvyPropertiesFile();
    File ivyP = new File(destDir, BACKUP_IVY_PROPERTIES_NAME);
    if (propertyFile != null && !propertyFile.trim().isEmpty()) {
        if (ivyP.canRead()) {
            propertyFileToLoadIntoIvy = BACKUP_IVY_PROPERTIES_NAME;
        }
    }
    Ivy ivy = getIvy(destDir, propertyFileToLoadIntoIvy);
    if (ivy == null) {
        return null;
    }
    versionMatcher = ivy.getSettings().getVersionMatcher();
    String ivyDesc = getIvyFile();
    File ivyF = null;
    if (ivyDesc != null && !ivyDesc.trim().isEmpty()) {
        ivyF = new File(destDir, BACKUP_IVY_FILE_NAME);
    }
    final File fivyF = ivyF;
    // Calculate ModuleDescriptor from the backup copy 
    if (fivyF == null || !fivyF.canRead()) {
        LOGGER.log(Level.WARNING, "Cannot read ivy file backup...removing ModuleDescriptor");
        return null;
    }
    if (moduleDescriptor == null || fivyF.lastModified() > lastmodified) {
        lastmodified = fivyF.lastModified();
        return (ModuleDescriptor) ivy.execute(new IvyCallback() {

            public Object doInIvyContext(Ivy ivy, IvyContext context) {
                try {
                    return ModuleDescriptorParserRegistry.getInstance().parseDescriptor(ivy.getSettings(), fivyF.toURI().toURL(), ivy.getSettings().doValidate());
                } catch (MalformedURLException e) {
                    LOGGER.log(Level.WARNING, "The URL is malformed : " + fivyF, e);
                    return null;
                } catch (ParseException e) {
                    LOGGER.log(Level.WARNING, "Parsing error while reading the ivy file " + fivyF, e);
                    return null;
                } catch (IOException e) {
                    LOGGER.log(Level.WARNING, "I/O error while reading the ivy file " + fivyF, e);
                    return null;
                }
            }
        });
    }
    return null;
}
Example 29
Project: role-strategy-plugin-master  File: RoleBasedAuthorizationStrategy.java View source code
/**
     * Get the needed permissions groups.
     */
public List<PermissionGroup> getGroups(String type) {
    List<PermissionGroup> groups;
    if (type.equals(GLOBAL)) {
        groups = new ArrayList<PermissionGroup>(PermissionGroup.getAll());
        groups.remove(PermissionGroup.get(Permission.class));
    } else if (type.equals(PROJECT)) {
        groups = new ArrayList<PermissionGroup>(PermissionGroup.getAll());
        groups.remove(PermissionGroup.get(Permission.class));
        groups.remove(PermissionGroup.get(Hudson.class));
        groups.remove(PermissionGroup.get(Computer.class));
        groups.remove(PermissionGroup.get(View.class));
    } else if (type.equals(SLAVE)) {
        groups = new ArrayList<PermissionGroup>(PermissionGroup.getAll());
        groups.remove(PermissionGroup.get(Permission.class));
        groups.remove(PermissionGroup.get(Hudson.class));
        groups.remove(PermissionGroup.get(View.class));
        // Project, SCM and Run permissions 
        groups.remove(PermissionGroup.get(Item.class));
        groups.remove(PermissionGroup.get(SCM.class));
        groups.remove(PermissionGroup.get(Run.class));
    } else {
        groups = null;
    }
    return groups;
}
Example 30
Project: tfs-plugin-master  File: FunctionalTest.java View source code
/**
     * Runs the project's {@link SCMTrigger} to poll for changes, which may schedule a build.
     *
     * If it does schedule a build, we'll wait for that build to complete and return it;
     * otherwise we return {@code null}.
     *
     * This assumes Jenkins (or the project/job) was configured with a quietPeriod, to give us
     * time to retrieve the item from the queue (especially when execution is paused in the debugger)
     * so we can wait on it.
     *
     * @param project The {@link Project} for which to poll and build.
     * @return The {@link AbstractBuild} that resulted from the build, if applicable; otherwise {@code null}.
     */
public static AbstractBuild runScmPollTrigger(final Project project) throws InterruptedException, ExecutionException {
    final SCMTrigger scmTrigger = (SCMTrigger) project.getTrigger(SCMTrigger.class);
    // This is a roundabout way of calling SCMTrigger#run(),
    // because if we set SCMTrigger#synchronousPolling to true
    // Trigger#checkTriggers() unconditionally runs the trigger,
    // even if we set its schedule (spec) to an empty string
    // (which normally disables the schedule).
    // Having synchronous polling (& building!) in our tests
    // is more important than skipping the usual method call chain.
    // http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
    final SCMTrigger.Runner runner = scmTrigger.new Runner();
    runner.run();
    final AbstractBuild build = waitForQueuedBuild(project);
    return build;
}
Example 31
Project: ansible-plugin-master  File: AbstractAnsibleBuilderDescriptor.java View source code
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Project project) {
    return new StandardListBoxModel().withEmptySelection().withMatching(anyOf(instanceOf(SSHUserPrivateKey.class), instanceOf(UsernamePasswordCredentials.class)), CredentialsProvider.lookupCredentials(StandardUsernameCredentials.class, project));
}
Example 32
Project: hudson.plugins.maven3-master  File: DependencyTrigger.java View source code
@Override
public boolean isApplicable(final Item item) {
    return item instanceof Project || item instanceof MatrixProject;
}
Example 33
Project: lyo.server-master  File: OslcAutomationProviderTest.java View source code
protected String getJobURI(Project<?, ?> project) throws IOException {
    return getJobURI(project.getName());
}
Example 34
Project: jenkins-metricfu-plugin-master  File: RubyMetricsPublisher.java View source code
private void copyMetricsToBuildDir(Build<?, ?> build) throws IOException, InterruptedException {
    final Project<?, ?> project = build.getParent();
    final FilePath workspace = project.getModuleRoot();
    final FilePath metricfuReports = workspace.child("tmp/metric_fu/");
    metricfuReports.copyRecursiveTo("**/*", new FilePath(build.getRootDir()));
}
Example 35
Project: jenkins-publish-over-ftp-plugin-master  File: LegacyConfigurationTest.java View source code
private BapFtpPublisherPlugin getConfiguredPlugin() {
    for (Project project : hudson.getProjects()) {
        if (project.getPublisher(getPublisherPluginDescriptor()) != null)
            return (BapFtpPublisherPlugin) project.getPublisher(getPublisherPluginDescriptor());
    }
    fail();
    return null;
}
Example 36
Project: jenkins.py-master  File: BuilderPW.java View source code
@Override
public Action getProjectAction(Project<?, ?> project) {
    initPython();
    if (pexec.isImplemented(8)) {
        return (Action) pexec.execPython("get_project_action", project);
    } else {
        return super.getProjectAction(project);
    }
}
Example 37
Project: build-failure-analyzer-plugin-master  File: ScanOnDemandBaseAction.java View source code
/**
     * Checks if the current user has {@link Item#CONFIGURE} or {@link Project#BUILD} permission.
     *
     * @return true if so.
     */
public boolean hasPermission() {
    return project.hasPermission(Item.CONFIGURE) || project.hasPermission(Project.BUILD);
}