Java Code Examples for hudson.model.Cause

The following examples show how to use hudson.model.Cause. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: audit-log-plugin   Source File: BuildListener.java    License: MIT License 6 votes vote down vote up
/**
 * Fired when a build is started, event logged via Log4j-audit.
 *
 * @param run of type Run having the build information
 * @param listener of type TaskListener that the onStarted method expects
 */
@Override
public void onStarted(Run run, TaskListener listener) {
    BuildStart buildStart = LogEventFactory.getEvent(BuildStart.class);

    List causeObjects = run.getCauses();
    List<String> causes = new ArrayList<>(causeObjects.size());
    for (Object cause: causeObjects) {
        Cause c = (Cause)cause;
        causes.add(c.getShortDescription());
    }

    buildStart.setBuildNumber(run.getNumber());
    buildStart.setCause(causes);
    buildStart.setProjectName(run.getParent().getFullName());
    buildStart.setTimestamp(formatDateISO(run.getStartTimeInMillis()));
    User user = User.current();
    if(user != null)
        buildStart.setUserId(user.getId());
    else
        buildStart.setUserId(null);

    buildStart.logEvent();
}
 
Example 2
private static Run getUpstreamBuild(@Nonnull Run build) {
  CauseAction causeAction = build.getAction(CauseAction.class);
  if (causeAction == null) {
    return null;
  }
  for (Cause cause : causeAction.getCauses()) {
    if (cause instanceof Cause.UpstreamCause) {
      Cause.UpstreamCause upstreamCause = (Cause.UpstreamCause) cause;
      Job upstreamJob =
          Jenkins.getInstance().getItemByFullName(upstreamCause.getUpstreamProject(), Job.class);
      // We want to ignore rebuilds, rebuilds have the same parent as
      // original build, see BuildCache#updateCache().
      if (upstreamJob == null || build.getParent() == upstreamJob) {
        continue;
      }
      return upstreamJob.getBuildByNumber(upstreamCause.getUpstreamBuild());
    }
  }
  return null;
}
 
Example 3
Source Project: github-autostatus-plugin   Source File: InfluxDbNotifier.java    License: MIT License 6 votes vote down vote up
/**
 * Sends a state change to InfluxDB.
 *
 * @param jobName the name of the job
 * @param stageItem stage item describing the new state
 */
@Override
public void notifyBuildStageStatus(String jobName, BuildStage stageItem) {
    if (stageItem.getBuildState() == BuildStage.State.Pending) {
        return;
    }

    String buildUrl = stageItem.getRun().getUrl();
    int buildNumber = stageItem.getRun().getNumber();
    Cause cause = stageItem.getRun().getCause(Cause.class);
    String buildCause = cause == null ? BuildNotifierConstants.DEFAULT_STRING : cause.getShortDescription();

    String data = config.getSchema().formatStage(jobName,
            repoOwner,
            repoName,
            branchName,
            stageItem.getStageName(),
            stageItem.getBuildState().toString(),
            stageItem.getDuration(),
            stageItem.isPassed() ? 1 : 0,
            buildUrl,
            buildNumber,
            buildCause);

    postData(data);
}
 
Example 4
Source Project: github-autostatus-plugin   Source File: InfluxDbNotifier.java    License: MIT License 6 votes vote down vote up
private void notifyCoverage(String jobName, @Nullable CodeCoverage coverageInfo, Run<?, ?> run) {
    if (coverageInfo != null) {
        String buildUrl = run.getUrl();
        int buildNumber = run.getNumber();
        Cause cause = run.getCause(Cause.class);
        String buildCause = cause == null ? BuildNotifierConstants.DEFAULT_STRING : cause.getShortDescription();

        String data = config.getSchema().formatCoverage(jobName,
                repoOwner,
                repoName,
                branchName,
                coverageInfo.getClasses(),
                coverageInfo.getConditionals(),
                coverageInfo.getFiles(),
                coverageInfo.getLines(),
                coverageInfo.getMethods(),
                coverageInfo.getPackages(),
                coverageInfo.getInstructions(),
                buildUrl,
                buildNumber,
                buildCause);

        postData(data);
    }
}
 
Example 5
Source Project: github-autostatus-plugin   Source File: InfluxDbNotifier.java    License: MIT License 6 votes vote down vote up
private void notifyTestResults(String jobName, @Nullable TestResults testResults, Run<?, ?> run) {
    if (testResults != null) {
        String buildUrl = run.getUrl();
        int buildNumber = run.getNumber();
        Cause cause = run.getCause(Cause.class);
        String buildCause = cause == null ? BuildNotifierConstants.DEFAULT_STRING : cause.getShortDescription();

        String data = config.getSchema().formatTests(jobName,
                repoOwner,
                repoName,
                branchName,
                testResults.getPassedTestCaseCount(),
                testResults.getSkippedTestCaseCount(),
                testResults.getFailedTestCaseCount(),
                buildUrl,
                buildNumber,
                buildCause);

        postData(data);
 
        for (TestSuite testSuite : testResults.getTestSuites()) {
            notifyTestSuite(jobName, testSuite, run);
        }
    }
}
 
Example 6
Source Project: github-autostatus-plugin   Source File: InfluxDbNotifier.java    License: MIT License 6 votes vote down vote up
private String notifyTestCase(String jobName, String suiteName, TestCase testCase, Run<?, ?> run) {
       String buildUrl = run.getUrl();
       int buildNumber = run.getNumber();
       Cause cause = run.getCause(Cause.class);
       String buildCause = cause == null ? BuildNotifierConstants.DEFAULT_STRING : cause.getShortDescription();

       String data = config.getSchema().formatTestCase(jobName,
               repoOwner,
               repoName,
               branchName,
               suiteName,
               testCase.getName(),
               testCase.getPassedCount(),
               testCase.getSkippedCount(),
               testCase.getFailedCount(),
               buildUrl,
               buildNumber,
               buildCause);

return data;
   }
 
Example 7
Source Project: github-autostatus-plugin   Source File: HttpNotifier.java    License: MIT License 6 votes vote down vote up
private BuildStatus constructBuildStatus(BuildStage.State buildState, Map<String, Object> parameters) {
    Run<?, ?> run = (Run<?, ?>) parameters.get(BuildNotifierConstants.BUILD_OBJECT);
    String jobName = (String) parameters.getOrDefault(BuildNotifierConstants.JOB_NAME, BuildNotifierConstants.DEFAULT_STRING);
    long blockedDuration = BuildNotifierConstants.getLong(parameters, BuildNotifierConstants.BLOCKED_DURATION);
    String buildUrl = run.getUrl();
    int buildNumber = run.getNumber();
    long buildDuration = BuildNotifierConstants.getLong(parameters, BuildNotifierConstants.JOB_DURATION) - blockedDuration;
    Cause cause = run.getCause(Cause.class);
    String buildCause = cause == null ? BuildNotifierConstants.DEFAULT_STRING : cause.getShortDescription();
    BuildStatus result = new org.jenkinsci.plugins.githubautostatus.model.BuildStatus();
    result.setRepoOwner(repoOwner);
    result.setRepoName(repoName);
    result.setJobName(jobName);
    result.setBranch(branchName);
    result.setBuildUrl(buildUrl);
    result.setBuildNumber(buildNumber);
    result.setTrigger(buildCause);
    result.setBlocked(blockedDuration > 0);
    result.setBlockedTime(blockedDuration);
    result.setDuration(buildDuration);
    result.setPassed(buildState == BuildStage.State.CompletedSuccess);
    result.setResult(buildState);
    result.setTimestamp(Clock.system(TimeZone.getTimeZone("UTC").toZoneId()).millis() / 1000);
    return result;
}
 
Example 8
Source Project: hubot-steps-plugin   Source File: Common.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Return the current build user.
 *
 * @param causes build causes.
 * @param envVars environment variables.
 * @return user name.
 */
public static String prepareBuildUserName(List<Cause> causes, EnvVars envVars) {
  String buildUser = "anonymous";

  // For multi branch jobs, while PR building.
  if (Util.fixEmpty(envVars.get("CHANGE_AUTHOR")) != null) {
    return envVars.get("CHANGE_AUTHOR");
  }

  if (causes != null && causes.size() > 0) {
    if (causes.get(0) instanceof UserIdCause) {
      buildUser = ((UserIdCause) causes.get(0)).getUserName();
    } else if (causes.get(0) instanceof UpstreamCause) {
      List<Cause> upstreamCauses = ((UpstreamCause) causes.get(0)).getUpstreamCauses();
      buildUser = prepareBuildUserName(upstreamCauses, envVars);
    }
  }
  return buildUser;
}
 
Example 9
Source Project: hubot-steps-plugin   Source File: Common.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Retrun the build cause.
 *
 * @return build cause.
 */
public static String prepareBuildCause(List<Cause> causes) {
  String buildCause = null;

  if (causes != null && causes.size() > 0) {
    for (Cause cause : causes) {

      if (cause instanceof UserIdCause) {
        buildCause = ((UserIdCause) causes.get(0)).getUserName();
      } else if (cause instanceof UpstreamCause) {
        List<Cause> upstreamCauses = ((UpstreamCause) cause).getUpstreamCauses();
        buildCause = prepareBuildCause(upstreamCauses);
      } else {
        buildCause = cause.getClass().getSimpleName();
      }
    }
  }
  return buildCause == null ? buildCause : buildCause.replace("Cause", "");
}
 
Example 10
Source Project: blueocean-plugin   Source File: PipelineApiTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testPipelineQueue() throws Exception {
    FreeStyleProject p1 = j.createFreeStyleProject("pipeline1");

    p1.setConcurrentBuild(true);
    p1.addProperty(new ParametersDefinitionProperty(new StringParameterDefinition("test","test")));
    p1.getBuildersList().add(new Shell("echo hello!\nsleep 300"));

    p1.scheduleBuild2(0).waitForStart();
    p1.scheduleBuild2(0).waitForStart();
    Jenkins.getInstance().getQueue().schedule(p1, 0, new ParametersAction(new StringParameterValue("test","test1")), new CauseAction(new Cause.UserIdCause()));
    Jenkins.getInstance().getQueue().schedule(p1, 0, new ParametersAction(new StringParameterValue("test","test2")), new CauseAction(new Cause.UserIdCause()));

    List queue = request().get("/organizations/jenkins/pipelines/pipeline1/queue").build(List.class);
    Assert.assertEquals(2, queue.size());
    Assert.assertEquals(4, ((Map) queue.get(0)).get("expectedBuildNumber"));
    Assert.assertEquals(3, ((Map) queue.get(1)).get("expectedBuildNumber"));
    Assert.assertEquals("Waiting for next available executor", ((Map) queue.get(0)).get("causeOfBlockage"));
    Assert.assertEquals("Waiting for next available executor", ((Map) queue.get(1)).get("causeOfBlockage"));

    Run r = QueueUtil.getRun(p1, Long.parseLong((String)((Map)queue.get(0)).get("id")));
    assertNull(r); //its not moved out of queue yet
}
 
Example 11
@Override
@SuppressWarnings("unchecked")
public BluePipeline create(@Nonnull BlueOrganization organization, @Nonnull Reachable parent) throws IOException {
    validateInternal(getName(), scmConfig, organization);
    MultiBranchProject project = createMultiBranchProject(organization);
    assignCredentialToProject(scmConfig, project);
    SCMSource source = createSource(project, scmConfig).withId("blueocean");
    project.setSourcesList(ImmutableList.of(new BranchSource(source)));
    source.afterSave();
    project.save();
    final boolean hasJenkinsfile = repoHasJenkinsFile(source);
    if(!hasJenkinsfile){
        sendMultibranchIndexingCompleteEvent(project, 5);
        AbstractScmSourceEvent scmSourceEvent = getScmSourceEvent(project, source);
        if(scmSourceEvent != null) {
            SCMSourceEvent.fireNow(scmSourceEvent);
        }
    }else{
        project.scheduleBuild(new Cause.UserIdCause());
    }
    return BluePipelineFactory.getPipelineInstance(project, OrganizationFactory.getInstance().getContainingOrg(project.getItemGroup()));
}
 
Example 12
@Test
public void testDataCompatibility() throws Exception {

    // given
    FreeStyleProject foo = (FreeStyleProject) rule.jenkins.createProjectFromXML(
            "bar",
            getClass().getResourceAsStream("WebhookJobProperty/freestyleold1.xml")
    );

    // when
    WebhookJobProperty webhookJobProperty = foo.getProperty(WebhookJobProperty.class);
    assertThat(webhookJobProperty.getWebhooks()).isNotEmpty();

    // then
    rule.assertBuildStatusSuccess(foo.scheduleBuild2(0, new Cause.UserIdCause()).get());
}
 
Example 13
@Test
public void addRemarks_AddsFact() {

    // given
    FactsBuilder factBuilder = new FactsBuilder(run, taskListener);
    List<Cause> causes = CauseBuilder.sampleCauses();
    when(run.getCauses()).thenReturn(causes);

    // when
    factBuilder.addRemarks();

    // then
    FactAssertion.assertThat(factBuilder.collect())
            .hasName(FactsBuilder.NAME_REMARKS)
            .hasValue(causes.get(0).getShortDescription() + ". " + causes.get(1).getShortDescription() + ".");
}
 
Example 14
Source Project: kubernetes-pipeline-plugin   Source File: CauseDTO.java    License: Apache License 2.0 6 votes vote down vote up
public CauseDTO(Cause cause) {
    this.shortDescription = cause.getShortDescription();
    if (cause instanceof Cause.UserIdCause) {
        Cause.UserIdCause userIdCause = (Cause.UserIdCause) cause;
        this.userId = userIdCause.getUserId();
        this.userName = userIdCause.getUserName();
    } else if (cause instanceof Cause.RemoteCause) {
        Cause.RemoteCause remoteCause = (Cause.RemoteCause) cause;
        this.remoteAddr = remoteCause.getAddr();
        this.remoteNote = remoteCause.getNote();
    } else if (cause instanceof Cause.UpstreamCause) {
        Cause.UpstreamCause upstreamCause = (Cause.UpstreamCause) cause;
        this.upstreamProject = upstreamCause.getUpstreamProject();
        this.upstreamUrl = upstreamCause.getUpstreamUrl();

    }
}
 
Example 15
Source Project: pipeline-maven-plugin   Source File: PipelineTriggerService.java    License: MIT License 6 votes vote down vote up
/**
 * Check NO infinite loop of job triggers caused by {@link hudson.model.Cause.UpstreamCause}.
 *
 * @param initialBuild
 * @throws IllegalStateException if an infinite loop is detected
 */
public void checkNoInfiniteLoopOfUpstreamCause(@Nonnull Run initialBuild) throws IllegalStateException {
    java.util.Queue<Run> builds = new LinkedList<>(Collections.singleton(initialBuild));
    Run currentBuild;
    while ((currentBuild = builds.poll()) != null) {
        for (Cause cause : ((List<Cause>) currentBuild.getCauses())) {
            if (cause instanceof Cause.UpstreamCause) {
                Cause.UpstreamCause upstreamCause = (Cause.UpstreamCause) cause;
                Run<?, ?> upstreamBuild = upstreamCause.getUpstreamRun();
                if (upstreamBuild == null) {
                    // Can be Authorization, build deleted on the file system...
                } else if (Objects.equals(upstreamBuild.getParent().getFullName(), initialBuild.getParent().getFullName())) {
                    throw new IllegalStateException("Infinite loop of job triggers ");
                } else {
                    builds.add(upstreamBuild);
                }
            }
        }
    }
}
 
Example 16
Source Project: jira-ext-plugin   Source File: UpstreamBuildUtil.java    License: Apache License 2.0 6 votes vote down vote up
private static Cause.UpstreamCause getUpstreamCause(Run run)
{
    if (run == null)
    {
        return null;
    }
    List<Cause> causes = run.getCauses();
    for (Cause cause : causes)
    {
        if (cause instanceof Cause.UpstreamCause)
        {
            return (Cause.UpstreamCause)cause;
        }
    }
    return null;
}
 
Example 17
@Override
public boolean isUnblocked(Queue.Item item) {
    final List<Cause> causes = item.getCauses();
    for (Cause cause : causes) {
        if (cause instanceof GitHubPRCause) {
            final GitHubPRCause gitHubPRCause = (GitHubPRCause) cause;
            final Set<String> causeLabels = gitHubPRCause.getLabels();
            if (getLabel() != null) {
                if (causeLabels.containsAll(label.getLabelsSet())) {
                    if (item.task instanceof Job<?, ?>) {
                        final Job<?, ?> job = (Job<?, ?>) item.task;
                        LOGGER.debug("Unblocking job item {} with matched labels {}",
                                job.getFullName(), label.getLabelsSet());
                    }

                    return true;
                }
            }
        }
    }

    return false;
}
 
Example 18
/**
 * Cancel previous builds for specified PR id.
 */
private static boolean cancelQueuedBuildByBranchName(final String branch) {
    Queue queue = getJenkinsInstance().getQueue();

    for (Queue.Item item : queue.getItems()) {
        Optional<Cause> cause = from(item.getAllActions())
                .filter(instanceOf(CauseAction.class))
                .transformAndConcat(new CausesFromAction())
                .filter(instanceOf(GitHubBranchCause.class))
                .firstMatch(new CauseHasBranch(branch));

        if (cause.isPresent()) {
            queue.cancel(item);
            return true;
        }
    }

    return false;
}
 
Example 19
Source Project: DotCi   Source File: CauseActionConverterTest.java    License: MIT License 6 votes vote down vote up
@Test
public void should_get_cause_from_dbObject() throws Exception {
    BasicDBObject cause1DbObject = new BasicDBObject("cause1", "cause1");
    DBObject causes = new BasicDBObjectBuilder().add("causes", Arrays.asList(cause1DbObject)).get();

    Mapper mapper = Mockito.mock(Mapper.class);
    Cause cause1 = new NullBuildCause();
    when(mapper.fromDBObject(null, cause1DbObject, null)).thenReturn(cause1);

    CauseActionConverter converter = new CauseActionConverter();
    converter.setMapper(mapper);
    CauseAction action = converter.decode(CauseAction.class, causes, Mockito.mock(MappedField.class));

    Assert.assertEquals(1, action.getCauses().size());
    Assert.assertEquals(cause1, action.getCauses().get(0));

}
 
Example 20
Source Project: DotCi   Source File: CauseActionConverterTest.java    License: MIT License 6 votes vote down vote up
@Test
public void should_convert_cause_action_to_old_format() throws Exception {
    Cause cause1 = new NullBuildCause();
    Mapper mapper = Mockito.mock(Mapper.class);
    when(mapper.toDBObject(cause1)).thenReturn(new BasicDBObject("cause1", "cause1"));

    CauseAction causeAction = new CauseAction(cause1);
    CauseActionConverter converter = new CauseActionConverter();
    converter.setMapper(mapper);

    DBObject dbObject = (DBObject) converter.encode(causeAction, null);

    Assert.assertEquals(dbObject.get("className"), CauseAction.class.getName());
    Assert.assertNotNull(dbObject.get("causes"));
    List dbCauses = ((List) dbObject.get("causes"));
    Assert.assertEquals(1, dbCauses.size());
    Assert.assertEquals("cause1", ((BasicDBObject) dbCauses.get(0)).get("cause1"));
}
 
Example 21
Source Project: audit-log-plugin   Source File: BuildListener.java    License: MIT License 5 votes vote down vote up
/**
 * Fired when a build is completed, event logged via Log4j-audit.
 *
 * @param run of type Run having the build information
 * @param listener of type TaskListener that the onCompleted method expects
 */
@Override
public void onCompleted(Run run, TaskListener listener) {
    BuildFinish buildFinish = LogEventFactory.getEvent(BuildFinish.class);

    List causeObjects = run.getCauses();
    List<String> causes = new ArrayList<>(causeObjects.size());
    for (Object cause: causeObjects) {
        Cause c = (Cause)cause;
        causes.add(c.getShortDescription());
    }
    buildFinish.setBuildNumber(run.getNumber());
    buildFinish.setCause(causes);
    buildFinish.setProjectName(run.getParent().getFullName());

    Instant start = Instant.ofEpochMilli(run.getStartTimeInMillis());
    Instant finish = start.plusMillis(run.getDuration());
    buildFinish.setTimestamp(formatDateISO(finish.toEpochMilli()));

    User user = User.current();
    if(user != null)
        buildFinish.setUserId(user.getId());
    else
        buildFinish.setUserId(null);

    buildFinish.logEvent();
}
 
Example 22
Source Project: github-autostatus-plugin   Source File: InfluxDbNotifier.java    License: MIT License 5 votes vote down vote up
/**
 * Sends the final build status to InfluxDB.
 *
 * @param buildState the new state
 * @param parameters build parameters
 */
@Override
public void notifyFinalBuildStatus(BuildStage.State buildState, Map<String, Object> parameters) {
    Run<?, ?> run = (Run<?, ?>) parameters.get(BuildNotifierConstants.BUILD_OBJECT);
    String jobName = (String) parameters.getOrDefault(BuildNotifierConstants.JOB_NAME, BuildNotifierConstants.DEFAULT_STRING);
    int passed = buildState == BuildStage.State.CompletedSuccess ? 1 : 0;
    long blockedDuration = BuildNotifierConstants.getLong(parameters, BuildNotifierConstants.BLOCKED_DURATION);
    int blocked = blockedDuration > 0 ? 1 : 0;
    String buildUrl = run.getUrl();
    int buildNumber = run.getNumber();
    Cause cause = run.getCause(Cause.class);
    String buildCause = cause == null ? BuildNotifierConstants.DEFAULT_STRING : cause.getShortDescription();

    String data = config.getSchema().formatJob(jobName,
            repoOwner,
            repoName,
            branchName,
            buildState.toString(),
            blocked,
            BuildNotifierConstants.getLong(parameters, BuildNotifierConstants.JOB_DURATION) - blockedDuration,
            blockedDuration,
            passed,
            buildUrl,
            buildNumber,
            buildCause);

    postData(data);

    if (!this.config.getIgnoreSendingTestResultsToInflux()) {
        notifyTestResults(jobName, (TestResults) parameters.get(BuildNotifierConstants.TEST_CASE_INFO), run);
    }
    if (!this.config.getIgnoreSendingTestCoverageToInflux()) {
        notifyCoverage(jobName, (CodeCoverage) parameters.get(BuildNotifierConstants.COVERAGE_INFO), run);
    }
}
 
Example 23
Source Project: github-autostatus-plugin   Source File: InfluxDbNotifier.java    License: MIT License 5 votes vote down vote up
private void notifyTestSuite(String jobName, TestSuite testSuite, Run<?, ?> run) {
       String suiteName = testSuite.getName();
       String buildUrl = run.getUrl();
       int buildNumber = run.getNumber();
       Cause cause = run.getCause(Cause.class);
       String buildCause = cause == null ? BuildNotifierConstants.DEFAULT_STRING : cause.getShortDescription();
List<String> testSuiteQuery = new ArrayList<>();

       String data = config.getSchema().formatTestSuite(jobName,
               repoOwner,
               repoName,
               branchName,
               suiteName,
               testSuite.getDuration(),
               testSuite.getPassedTestCaseCount(),
               testSuite.getSkippedTestCaseCount(),
               testSuite.getFailedTestCaseCount(),
               buildUrl,
               buildNumber,
               buildCause);

testSuiteQuery.add(data);
       for (TestCase testCase : testSuite.getTestCases()) {
           testSuiteQuery.add(notifyTestCase(jobName, suiteName, testCase, run));
       }
postData(String.join("\\n", testSuiteQuery));

   }
 
Example 24
private void startJob() {
    Cause cause = new Cause.RemoteCause("SQSTrigger", String.format("User invoked: %s", this.userarns));

    //Job Build can be triggered by 1+ SQS messages because of quiet-period in Jenkins, @see https://jenkins.io/blog/2010/08/11/quiet-period-feature/
    boolean scheduled = job.scheduleBuild(cause);
    this.log.info("The build is scheduled? %s by Message: %s", scheduled, this.messageId);
}
 
Example 25
Source Project: aws-codecommit-trigger-plugin   Source File: Issue46IT.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldPassIt() throws Exception {
    this.mockAwsSqs.sendMessage(this.fixture.getSqsMessage());
    this.submitAndAssertFixture(this.fixture);
    Cause cause = this.fixture.getLastBuild().getCauses().get(0);
    Assertions.assertThat(cause).isNotNull();
    Assertions.assertThat(cause.getShortDescription()).contains("User invoked:");
}
 
Example 26
Source Project: jira-steps-plugin   Source File: JiraStepExecution.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Return the current build user.
 *
 * @param causes build causes.
 * @return user name.
 */
protected static String prepareBuildUserId(List<Cause> causes) {
  String buildUser = "anonymous";
  if (causes != null && causes.size() > 0) {
    if (causes.get(0) instanceof UserIdCause) {
      buildUser = ((UserIdCause) causes.get(0)).getUserId();
    } else if (causes.get(0) instanceof UpstreamCause) {
      List<Cause> upstreamCauses = ((UpstreamCause) causes.get(0)).getUpstreamCauses();
      buildUser = prepareBuildUserId(upstreamCauses);
    }
  }
  return Util.fixEmpty(buildUser) == null ? "anonymous" : buildUser;
}
 
Example 27
Source Project: hubot-steps-plugin   Source File: Common.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Return the current build user Id.
 *
 * @param causes build causes.
 * @param envVars environment variables.
 * @return user name.
 */
public static String prepareBuildUserId(List<Cause> causes, EnvVars envVars) {
  String buildUserId = null;

  if (causes != null && causes.size() > 0) {
    if (causes.get(0) instanceof UserIdCause) {
      buildUserId = ((UserIdCause) causes.get(0)).getUserId();
    } else if (causes.get(0) instanceof UpstreamCause) {
      List<Cause> upstreamCauses = ((UpstreamCause) causes.get(0)).getUpstreamCauses();
      buildUserId = prepareBuildUserId(upstreamCauses, envVars);
    }
  }
  return buildUserId;
}
 
Example 28
Source Project: blueocean-plugin   Source File: RunContainerImpl.java    License: MIT License 5 votes vote down vote up
/**
 * Schedules a build. If build already exists in the queue and the pipeline does not
 * support running multiple builds at the same time, return a reference to the existing
 * build.
 *
 * @return Queue item.
 */
@Override
public BlueRun create(StaplerRequest request) {
    job.checkPermission(Item.BUILD);
    if (job instanceof Queue.Task) {
        ScheduleResult scheduleResult;

        List<ParameterValue> parameterValues = getParameterValue(request);
        int expectedBuildNumber = job.getNextBuildNumber();
        if(parameterValues.size() > 0) {
            scheduleResult = Jenkins.getInstance()
                    .getQueue()
                    .schedule2((Queue.Task) job, 0, new ParametersAction(parameterValues),
                            new CauseAction(new Cause.UserIdCause()));
        }else {
            scheduleResult = Jenkins.getInstance()
                    .getQueue()
                    .schedule2((Queue.Task) job, 0, new CauseAction(new Cause.UserIdCause()));
        }
        // Keep FB happy.
        // scheduleResult.getItem() will always return non-null if scheduleResult.isAccepted() is true
        final Queue.Item item = scheduleResult.getItem();
        if(scheduleResult.isAccepted() && item != null) {
            return new QueueItemImpl(
                pipeline.getOrganization(),
                item,
                pipeline,
                expectedBuildNumber, pipeline.getLink().rel("queue").rel(Long.toString(item.getId())),
                pipeline.getLink()
            ).toRun();
        } else {
            throw new ServiceException.UnexpectedErrorException("Queue item request was not accepted");
        }
    } else {
        throw new ServiceException.NotImplementedException("This pipeline type does not support being queued.");
    }
}
 
Example 29
Source Project: blueocean-plugin   Source File: MultibranchPipelineRunContainer.java    License: MIT License 5 votes vote down vote up
@Override
public BlueRun create(StaplerRequest request) {
    blueMbPipeline.mbp.checkPermission(Item.BUILD);
    Queue.Item queueItem = blueMbPipeline.mbp.scheduleBuild2(0, new CauseAction(new Cause.UserIdCause()));
    if(queueItem == null){ // possible mbp.isBuildable() was false due to no sources fetched yet
        return null;
    }
    return new QueueItemImpl(
            blueMbPipeline.getOrganization(),
            queueItem,
            blueMbPipeline,
            1
    ).toRun();
}
 
Example 30
@Override
public BlueRun create(StaplerRequest request) {
    pipeline.folder.checkPermission(Item.BUILD);
    Queue.Item queueItem = pipeline.folder.scheduleBuild2(0, new CauseAction(new Cause.UserIdCause()));
    if(queueItem == null){ // possible folder.isBuildable() was false due to no repo fetched yet
        return null;
    }
    return new QueueItemImpl(
            pipeline.getOrganization(),
            queueItem,
            pipeline,
            1
    ).toRun();
}