Java 类hudson.model.AbstractBuild 实例源码

项目:sonar-quality-gates-plugin    文件:JobConfigurationService.java   
public JobConfigData checkProjectKeyIfVariable(JobConfigData jobConfigData, AbstractBuild build, BuildListener listener) throws QGException {

        String projectKey = jobConfigData.getProjectKey();

        if (projectKey.isEmpty()) {
            throw new QGException("Empty project key.");
        }

        final JobConfigData envVariableJobConfigData = new JobConfigData();
        envVariableJobConfigData.setSonarInstanceName(jobConfigData.getSonarInstanceName());

        try {
            envVariableJobConfigData.setProjectKey(getProjectKey(projectKey, build.getEnvironment(listener)));
        } catch (IOException | InterruptedException e) {
            throw new QGException(e);
        }

        envVariableJobConfigData.setSonarInstanceName(jobConfigData.getSonarInstanceName());

        return envVariableJobConfigData;
    }
项目:envinject-api-plugin    文件:EnvVarsResolver.java   
@Nonnull
public static Map<String, String> getEnVars(@Nonnull Run<?, ?> run) throws EnvInjectException {
    Action envInjectAction = EnvInjectActionRetriever.getEnvInjectAction(run);
    if (envInjectAction != null) {
        try {
            Method method = envInjectAction.getClass().getMethod("getEnvMap");
            return (Map<String, String>) method.invoke(envInjectAction);
        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException | ClassCastException e) {
            throw new EnvInjectException(e);
        }
    }

    // Retrieve node used for this build
    Node builtOn = (run instanceof AbstractBuild) ? ((AbstractBuild)run).getBuiltOn() : null;

    // Check if node is always on. Otherwise, gather master env vars
    if (builtOn == null) {
        return getFallBackMasterNode(run.getParent());
    }
    if (builtOn.getRootPath() == null) {
        return getFallBackMasterNode(run.getParent());
    }

    // Get envVars from the node of the last build
    return getDefaultEnvVarsJob(run.getParent(), builtOn);
}
项目:vsts-jenkins-build-integration-sample    文件:TfsBuildFacadeImpl.java   
/**
 * Update TFS Build status to finished with Jenkins status
 */
public void finishBuild() {
    Build b = queryTfsBuild();
    b.setFinishTime(new Date());

    AbstractBuild jenkinsBuild = getJenkinsBuild();
    BuildResult tfsResult = convertToTfsBuildResult(jenkinsBuild.getResult());

    b.setResult(tfsResult);
    b.setStatus(BuildStatus.COMPLETED);

    String commitSha1 =  getSourceCommit();
    logger.info("Setting TFS build sourceVersion to: " + commitSha1);
    b.setSourceVersion(commitSha1);

    getClient().getBuildClient().updateBuild(b, b.getProject().getId(), b.getId());
}
项目:run-selector-plugin    文件:RunSelectorContext.java   
/**
 * Constructs the environment variables for the current build.
 *
 * @return the current build environment variables
 * @throws IOException
 * @throws InterruptedException
 */
private EnvVars constructEnvVars() throws IOException, InterruptedException {
    EnvVars envVars = build.getEnvironment(listener);
    if (build instanceof AbstractBuild) {
        envVars.putAll(((AbstractBuild<?, ?>) build).getBuildVariables()); // Add in matrix axes..
    } else {
        // Abstract#getEnvironment(TaskListener) put build parameters to
        // environments, but Run#getEnvironment(TaskListener) doesn't.
        // That means we can't retrieve build parameters from WorkflowRun
        // as it is a subclass of Run, not of AbstractBuild.
        // We need expand build parameters manually.
        // See JENKINS-26694, JENKINS-30357 for details.
        for (ParametersAction pa : build.getActions(ParametersAction.class)) {
            // We have to extract parameters manually as ParametersAction#buildEnvVars
            // (overrides EnvironmentContributingAction#buildEnvVars)
            // is applicable only for AbstractBuild.
            for (ParameterValue pv : pa.getParameters()) {
                pv.buildEnvironment(build, envVars);
            }
        }
    }

    return envVars;
}
项目:run-selector-plugin    文件:FileWriteBuilder.java   
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher,
        BuildListener listener) throws InterruptedException, IOException {
    EnvVars envVars = build.getEnvironment(listener);
    String expandedFilename = envVars.expand(filename);
    String expandedContent = envVars.expand(content);

    FilePath file = build.getWorkspace().child(expandedFilename);
    file.write(expandedContent, encoding);
    return true;
}
项目:run-selector-plugin    文件:RemoveUpstreamBuilder.java   
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
        throws InterruptedException, IOException {
    for (Cause.UpstreamCause c: Util.filter(build.getCauses(), Cause.UpstreamCause.class)) {
        Job<?,?> upstreamProject = Jenkins.getInstance().getItemByFullName(c.getUpstreamProject(), Job.class);
        if (upstreamProject == null) {
            listener.getLogger().println(String.format("Not Found: %s", c.getUpstreamProject()));
            continue;
        }

        Run<?,?> upstreamBuild = upstreamProject.getBuildByNumber(c.getUpstreamBuild());
        if (upstreamBuild == null) {
            listener.getLogger().println(String.format("Not Found: %s - %d", upstreamProject.getFullName(), c.getUpstreamBuild()));
            continue;
        }

        listener.getLogger().println(String.format("Removed: %s - %s", upstreamProject.getFullName(), upstreamBuild.getFullDisplayName()));
        upstreamBuild.delete();
    }
    return true;
}
项目:SlackUploader    文件:SlackUploader.java   
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
    //To change body of generated methods, choose Tools | Templates.
    LogOutput log = new LogOutput();
    Runtime runtime = Runtime.getRuntime();
    Process process = null;

    try {
        String script = generateScript();

        process = runScript(runtime, script);

        log.logOutput(listener, process);
    } catch (Throwable cause) {
        log.logOutput(listener, process);
    }
    return true;
}
项目:jagger-jaas-jenkins-plugin    文件:JaggerTestExecutionBuilder.java   
public void startTestExecution(AbstractBuild<?, ?> build, TaskListener listener) throws InterruptedException, IOException {
    final RestTemplate restTemplate = new RestTemplate();
    final PrintStream logger = listener.getLogger();

    logger.println("\n\nJagger JaaS Jenkins Plugin Step 1: Creating TestExecution request...");
    TestExecutionEntity testExecutionEntity = createTestExecution(logger);

    logger.println("\n\nJagger JaaS Jenkins Plugin Step 2: Sending request to JaaS...");
    TestExecutionEntity sentExecution = sendTestExecutionToJaas(logger, testExecutionEntity, restTemplate);

    logger.println("\n\nJagger JaaS Jenkins Plugin Step 3: Waiting test to start execution...");
    waitTestExecutionStarted(logger, sentExecution.getId(), restTemplate);

    logger.println("\n\nJagger JaaS Jenkins Plugin Step 4: Waiting test to finish execution...");
    TestExecutionEntity executionFinished = waitTestExecutionFinished(logger, sentExecution.getId(), restTemplate);

    logger.println("\n\nJagger JaaS Jenkins Plugin Step 5: Publishing Test execution results...");
    publishReportLink(logger, build, executionFinished);

    checkDecision(logger, build, executionFinished.getSessionId(), restTemplate);
}
项目:jenkins-telegram-plugin    文件:TelegramNotifier.java   
public TelegramService newTelegramService(AbstractBuild r, BuildListener listener) {


        String authToken = this.authToken;
        if (StringUtils.isEmpty(authToken)) {
            authToken = getDescriptor().getToken();
        }
        String chatId = this.chatId;
        if (StringUtils.isEmpty(chatId)) {
            chatId = getDescriptor().getChatId();
        }

        EnvVars env = null;
        try {
            env = r.getEnvironment(listener);
        } catch (Exception e) {
            listener.getLogger().println("Error retrieving environment vars: " + e.getMessage());
            env = new EnvVars();
        }
        authToken = env.expand(authToken);
        chatId = env.expand(chatId);

        return new StandardTelegramService(authToken, chatId);
    }
项目:jira-ext-plugin    文件:AddCommentTest.java   
/**
 * An exception adding the first label add should not disrupt the next label
 */
@Test
public void testResiliency()
        throws Exception
{
    AddComment addComment = new AddComment(false, "Test Comment");
    addComment.setJiraClientSvc(jiraClientSvc);

    AbstractBuild mockBuild = mock(AbstractBuild.class);
    when(mockBuild.getEnvironment(any(TaskListener.class))).thenReturn(new EnvVars());
    List<JiraCommit> jiraCommits = new ArrayList<>();
    jiraCommits.add(new JiraCommit("SSD-101", MockChangeLogUtil.mockChangeLogSetEntry("Test Comment")));
    jiraCommits.add(new JiraCommit("SSD-102", MockChangeLogUtil.mockChangeLogSetEntry("Test Comment")));
    doThrow(new RuntimeException("Issue is invalid"))
            .when(jiraClientSvc).addCommentToTicket("SSD-101", "Test Comment");
    addComment.perform(jiraCommits, mockBuild, mock(Launcher.class), new StreamBuildListener(System.out, Charset.defaultCharset()));
    verify(jiraClientSvc, times(1)).addCommentToTicket("SSD-101", "Test Comment");
    verify(jiraClientSvc, times(1)).addCommentToTicket("SSD-102", "Test Comment");
}
项目:jenkins-telegram-plugin    文件:ActiveNotifier.java   
public void started(AbstractBuild build) {



        CauseAction causeAction = build.getAction(CauseAction.class);

        if (causeAction != null) {
            Cause scmCause = causeAction.findCause(SCMTrigger.SCMTriggerCause.class);
            if (scmCause == null) {
                MessageBuilder message = new MessageBuilder(notifier, build);
                message.append(causeAction.getShortDescription());
                notifyStart(build, message.appendOpenLink().toString());
                // Cause was found, exit early to prevent double-message
                return;
            }
        }

        String changes = getChanges(build, notifier.includeCustomMessage());
        if (changes != null) {
            notifyStart(build, changes);
        } else {
            notifyStart(build, getBuildStatusMessage(build, false, false,notifier.includeCustomMessage()));
        }
    }
项目:jenkins-telegram-plugin    文件:ActiveNotifier.java   
String getBuildStatusMessage(AbstractBuild r, boolean includeTestSummary,boolean includeFailedTests, boolean includeCustomMessage) {
    MessageBuilder message = new MessageBuilder(notifier, r);
    message.appendStatusMessage();
    message.appendDuration();
    message.appendOpenLink();
    if (includeTestSummary) {
        message.appendTestSummary(includeFailedTests);
    }
    if (includeCustomMessage) {
        message.appendCustomMessage();
    }
    if (notifier.getCommitInfoChoice().showAnything()){
        message.appendCommitMessage(r);
    }
    return message.toString();
}
项目:jenkins-telegram-plugin    文件:ActiveNotifier.java   
@SuppressWarnings("Duplicates")
static String getStatusMessage(AbstractBuild r) {
    MessageStatus status = getBuildStatus(r);
    switch (status){

        case STARTING:
            return STARTING_STATUS_MESSAGE;
        case BACK_TO_NORMAL:
            return BACK_TO_NORMAL_STATUS_MESSAGE;
        case STILL_FAILING:
            return STILL_FAILING_STATUS_MESSAGE;
        case SUCCESS:
            return SUCCESS_STATUS_MESSAGE;
        case FAILURE:
            return FAILURE_STATUS_MESSAGE;
        case ABORTED:
            return ABORTED_STATUS_MESSAGE;
        case UNSTABLE:
            return UNSTABLE_STATUS_MESSAGE;
        case NOT_BUILT:
            return NOT_BUILT_STATUS_MESSAGE;
        default:return UNKNOWN_STATUS_MESSAGE;
    }
}
项目:jenkins-telegram-plugin    文件:ActiveNotifier.java   
@SuppressWarnings("Duplicates")
static String getStatusEmoticon(AbstractBuild r){
    MessageStatus status = getBuildStatus(r);
    switch (status){

        case STARTING:
            return STARTING_STATUS_EMOTICON;
        case BACK_TO_NORMAL:
            return BACK_TO_NORMAL_STATUS_EMOTICON;
        case STILL_FAILING:
            return STILL_FAILING_STATUS_EMOTICON;
        case SUCCESS:
            return SUCCESS_STATUS_EMOTICON;
        case FAILURE:
            return FAILURE_STATUS_EMOTICON;
        case ABORTED:
            return ABORTED_STATUS_EMOTICON;
        case UNSTABLE:
            return UNSTABLE_STATUS_EMOTICON;
        case NOT_BUILT:
            return NOT_BUILT_STATUS_EMOTICON;
        default:return UNKNOWN_STATUS_EMOTICON;
    }
}
项目:starwars-plugin    文件:StarWarsRecorderTest.java   
public void testPerformWithFailureResultAddsStarWarsActionWithFailResultAndExpectedQuote() throws Exception {
    List<Action> actions = new ArrayList<Action>();
    Quote expectedQuote = generateQuote(StarWarsResult.FAIL);

    AbstractBuild mockBuild = mock(AbstractBuild.class);
    when(mockBuild.getResult()).thenReturn(Result.FAILURE);
    when(mockBuild.getActions()).thenReturn(actions);

    mockQuotesGenerator.add(expectedQuote);
    when(mockQuotesGenerator.generate(StarWarsResult.FAIL)).thenReturn(expectedQuote);
    assertEquals(0, actions.size());

    Launcher mockLauncher = mock(Launcher.class); 
    BuildListener mockBuildListener = mock(BuildListener.class);
    recorder.perform(mockBuild, mockLauncher, mockBuildListener);

    assertEquals(1, actions.size());
    assertTrue(actions.get(0) instanceof StarWarsAction);

    StarWarsAction action = (StarWarsAction) actions.get(0);
    assertEquals(StarWarsResult.FAIL, action.getResult());
    assertEquals(expectedQuote, action.getQuote());
}
项目:jenkins-plugin-google-driver-uploader    文件:GoogleDriveUploader.java   
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
        throws InterruptedException, IOException {

    try {
        GoogleRobotCredentials credentials = GoogleRobotCredentials.getById(getCredentialsId());
        GoogleDriveManager driveManager = new GoogleDriveManager(authorize(credentials));

        String pattern = Util.replaceMacro(getPattern(), build.getEnvironment(listener));
        String workspace = build.getWorkspace().getRemote();
        String[] filesToUpload = listFiles(workspace, pattern);
        for (String file : filesToUpload) {
            listener.getLogger().println("Uploading file: " + file);
            driveManager.store(file, getDriveLocation());
        }
    } catch (GeneralSecurityException e) {
        build.setResult(Result.FAILURE);
        return false;
    }
    return true;
}
项目:browserstack-integration-plugin    文件:BrowserStackBuildWrapper.java   
@Override
public Environment setUp(final AbstractBuild build, final Launcher launcher,
                         final BuildListener listener) throws IOException, InterruptedException {
    final PrintStream logger = listener.getLogger();

    final BrowserStackCredentials credentials = BrowserStackCredentials.getCredentials(build.getProject(), credentialsId);
    if (credentials != null) {
        this.username = credentials.getUsername();
        this.accesskey = credentials.getDecryptedAccesskey();
    }

    AutomateBuildEnvironment buildEnv = new AutomateBuildEnvironment(credentials, launcher, logger);
    if (accesskey != null && this.localConfig != null) {
        try {
            buildEnv.startBrowserStackLocal(build.getFullDisplayName());
        } catch (Exception e) {
            listener.fatalError(e.getMessage());
            throw new IOException(e.getCause());
        }
    }

    recordBuildStats();
    return buildEnv;
}
项目:browserstack-integration-plugin    文件:CopyResourceFileToWorkspaceTarget.java   
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
    FilePath workspace = build.getWorkspace();
    workspace.child(this.finalReportDir).mkdirs();
    OutputStream outputStream = null;
    InputStream inputStream = null;
    try {
        outputStream = workspace.child(this.finalReportDir + this.resourceFileToCopy).write();
        inputStream = this.getClass().getClassLoader().getResourceAsStream(this.resourceFileToCopy);
        IOUtils.copy(inputStream, outputStream);
    } finally {
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(outputStream);
    }
    return true;
}
项目:jenkins-deployment-manager-plugin    文件:GoogleCloudManagerBuildWrapper.java   
/**
 * {@inheritDoc}
 */
@Override
public EphemeralDeployment setUp(AbstractBuild build, Launcher launcher, BuildListener listener)
    throws IOException, InterruptedException {
  EnvVars environment = build.getEnvironment(listener);
  FilePath workspace = requireNonNull(build.getWorkspace());

  try {
    synchronized (deployment) {
      deployment.insert(workspace, environment, listener.getLogger());
    }
  } catch (CloudManagementException e) {
    e.printStackTrace(listener.error(e.getMessage()));
    return null; // Build must be aborted
  }

  return new EphemeralDeployment(environment);
}
项目:jenkins-deployment-manager-plugin    文件:GoogleCloudManagerDeployerTest.java   
@Test
public void getEnvironmentExceptionTest() throws Exception {
  GoogleCloudManagerDeployer deployer =
      new GoogleCloudManagerDeployer(getNewTestingTemplatedCloudDeployment(credentials.getId(),
          DEPLOYMENT_NAME, CONFIG_FILE, PathUtils.toRemotePaths(importPaths), null));

  BuildListener listener = mock(BuildListener.class);
  PrintStream printStream = new PrintStream(new ByteArrayOutputStream());
  when(listener.getLogger()).thenReturn(printStream);
  when(listener.error(any(String.class))).thenReturn(new PrintWriter(printStream));

  AbstractBuild build = mock(AbstractBuild.class);
  when(build.getResult()).thenReturn(Result.SUCCESS);
  when(build.getEnvironment(listener)).thenThrow(new IOException("test"));

  // Check that we failed the build step due to a failure to retrieve
  // the environment.
  assertFalse(deployer.perform(build, null, listener));
}
项目:jira-ext-plugin    文件:AddLabel.java   
@Override
public void perform(List<JiraCommit> jiraCommitList,
                    AbstractBuild build, Launcher launcher, BuildListener listener)
{
    for (JiraCommit jiraCommit : JiraCommit.filterDuplicateIssues(jiraCommitList))
    {
        listener.getLogger().println("Add label to ticket: " + jiraCommit.getJiraTicket());
        listener.getLogger().println("Label: " + labelName);
        try
        {
            String expandedName = build.getEnvironment(listener).expand(labelName);
            getJiraClientSvc().addLabelToTicket(jiraCommit.getJiraTicket(), expandedName);
        }
        catch (Throwable t)
        {
            listener.getLogger().println("ERROR Updating jira notifications");
            t.printStackTrace(listener.getLogger());
        }
    }
}
项目:jira-ext-plugin    文件:SingleTicketStrategy.java   
@Override
public List<JiraCommit> getJiraCommits(AbstractBuild build,
                                       BuildListener listener)
{
    List<JiraCommit> jiraCommits = new ArrayList<>();
    String expandedIssueKey = issueKey;
    try
    {
        expandedIssueKey = build.getEnvironment(listener).expand(issueKey);
    }
    catch (IOException|InterruptedException e)
    {
        e.printStackTrace(listener.getLogger());
    }
    jiraCommits.add(new JiraCommit(expandedIssueKey, null));
    return jiraCommits;
}
项目:jira-ext-plugin    文件:AddFixVersion.java   
@Override
public void perform(List<JiraCommit> commits, AbstractBuild build, Launcher launcher, BuildListener listener)
{
    for (JiraCommit commit : JiraCommit.filterDuplicateIssues(commits))
    {
        try
        {
            String expandedFixVersion = build.getEnvironment(listener).expand(fixVersion);
            getJiraClientSvc().addFixVersion(commit.getJiraTicket(), expandedFixVersion);
        }
        catch (Throwable t)
        {
            listener.getLogger().println("ERROR Updating fix versions, skipping");
            t.printStackTrace(listener.getLogger());
        }
    }
}
项目:jira-ext-plugin    文件:AddFixVersionTest.java   
@Test
public void testExpandValues()
        throws Exception
{
    AddFixVersion addFixVersion = new AddFixVersion("Beta Release $FOO");
    addFixVersion.setJiraClientSvc(jiraClientSvc);
    AbstractBuild mockBuild = mock(AbstractBuild.class);
    EnvVars envVars = new EnvVars();
    envVars.put("FOO", "BAR");
    when(mockBuild.getEnvironment(any(TaskListener.class))).thenReturn(envVars);
    List<JiraCommit> jiraCommits = new ArrayList<>();
    jiraCommits.add(new JiraCommit("SSD-101"));
    jiraCommits.add(new JiraCommit("SSD-101"));

    addFixVersion.perform(jiraCommits, mockBuild, mock(Launcher.class), new StreamBuildListener(System.out, Charset.defaultCharset()));
    verify(jiraClientSvc, times(1)).addFixVersion(eq("SSD-101"), eq("Beta Release BAR"));

}
项目:jira-ext-plugin    文件:AddFixVersionTest.java   
/**
 * An exception updating a ticket should not impact other issues being updated
 */
@Test
public void testResiliency()
        throws Exception
{
    AddFixVersion addFixVersion = new AddFixVersion("Beta Release");
    addFixVersion.setJiraClientSvc(jiraClientSvc);
    AbstractBuild mockBuild = mock(AbstractBuild.class);
    when(mockBuild.getEnvironment(any(TaskListener.class))).thenReturn(new EnvVars());
    List<JiraCommit> jiraCommits = new ArrayList<>();
    jiraCommits.add(new JiraCommit("SSD-101"));
    jiraCommits.add(new JiraCommit("SSD-102"));

    doThrow(new RuntimeException("Issue is invalid"))
            .when(jiraClientSvc).addFixVersion("SSD-101", "Beta Release");
    addFixVersion.perform(jiraCommits, mockBuild, mock(Launcher.class), new StreamBuildListener(System.out, Charset.defaultCharset()));
    // no exception - good!

    verify(jiraClientSvc, times(1)).addFixVersion("SSD-101", "Beta Release");
    verify(jiraClientSvc, times(1)).addFixVersion("SSD-102", "Beta Release");
}
项目:jira-ext-plugin    文件:TransitionTest.java   
/**
 * An exception adding the first label add should not disrupt the next label
 */
@Test
public void testResiliency()
        throws Exception
{
    Transition transition = new Transition("Resolve");
    transition.setJiraClientSvc(jiraClientSvc);

    AbstractBuild mockBuild = mock(AbstractBuild.class);
    when(mockBuild.getEnvironment(any(TaskListener.class))).thenReturn(new EnvVars());
    List<JiraCommit> jiraCommits = new ArrayList<>();
    jiraCommits.add(new JiraCommit("SSD-101", MockChangeLogUtil.mockChangeLogSetEntry("Test Comment")));
    jiraCommits.add(new JiraCommit("SSD-102", MockChangeLogUtil.mockChangeLogSetEntry("Test Comment")));
    doThrow(new RuntimeException("Issue is invalid"))
            .when(jiraClientSvc).changeWorkflowOfTicket("SSD-101", "Test Comment");
    transition.perform(jiraCommits, mockBuild, mock(Launcher.class), new StreamBuildListener(System.out, Charset.defaultCharset()));
    verify(jiraClientSvc, times(1)).changeWorkflowOfTicket(eq("SSD-101"), eq("Resolve"));
    verify(jiraClientSvc, times(1)).changeWorkflowOfTicket(eq("SSD-102"), eq("Resolve"));
}
项目:jira-ext-plugin    文件:JiraPublisherStepTest.java   
@Test
public void testInvokeOperations()
        throws Exception
{
    IssueStrategyExtension mockStrategy = mock(IssueStrategyExtension.class);
    JiraOperationExtension mockOperation = mock(JiraOperationExtension.class);
    Descriptor mockDescriptor = mock(Descriptor.class);
    when(mockDescriptor.getDisplayName()).thenReturn("Mock descriptor");
    when(mockOperation.getDescriptor()).thenReturn(mockDescriptor);
    JiraExtPublisherStep publisher = new JiraExtPublisherStep(mockStrategy,
            Arrays.asList(mockOperation));
    List<JiraCommit> commits = Arrays.asList(new JiraCommit("JENKINS-101",
            MockChangeLogUtil.mockChangeLogSetEntry("example ticket")));

    when(mockStrategy.getJiraCommits(any(AbstractBuild.class), any(BuildListener.class)))
            .thenReturn(commits);

    assertTrue(publisher.perform(mock(AbstractBuild.class), mock(Launcher.class),
            new StreamBuildListener(System.out, Charset.defaultCharset())));
    verify(mockOperation).perform(eq(commits), any(AbstractBuild.class), any(Launcher.class), any(BuildListener.class));
}
项目:jira-ext-plugin    文件:AddLabelTest.java   
@Test
public void testAddLabel()
        throws Exception
{
    AddLabel addLabel = new AddLabel("Test Label");
    addLabel.setJiraClientSvc(jiraClientSvc);

    AbstractBuild mockBuild = mock(AbstractBuild.class);
    when(mockBuild.getEnvironment(any(TaskListener.class))).thenReturn(new EnvVars());
    List<JiraCommit> jiraCommits = new ArrayList<>();
    jiraCommits.add(new JiraCommit("SSD-101", MockChangeLogUtil.mockChangeLogSetEntry("Test Comment")));
    jiraCommits.add(new JiraCommit("SSD-101", MockChangeLogUtil.mockChangeLogSetEntry("Test Comment")));

    addLabel.perform(jiraCommits, mockBuild, mock(Launcher.class), new StreamBuildListener(System.out, Charset.defaultCharset()));
    verify(jiraClientSvc, times(1)).addLabelToTicket(eq("SSD-101"), eq("Test Label"));
}
项目:jira-ext-plugin    文件:AddLabelTest.java   
@Test
public void testExpandValues()
        throws Exception
{
    AddLabel addLabel = new AddLabel("Test Label $FOO");
    addLabel.setJiraClientSvc(jiraClientSvc);

    AbstractBuild mockBuild = mock(AbstractBuild.class);
    EnvVars envVars = new EnvVars();
    envVars.put("FOO", "BAR");
    when(mockBuild.getEnvironment(any(TaskListener.class))).thenReturn(envVars);
    List<JiraCommit> jiraCommits = new ArrayList<>();
    jiraCommits.add(new JiraCommit("SSD-101", MockChangeLogUtil.mockChangeLogSetEntry("Test Comment")));

    addLabel.perform(jiraCommits, mockBuild, mock(Launcher.class), new StreamBuildListener(System.out, Charset.defaultCharset()));
    verify(jiraClientSvc, times(1)).addLabelToTicket(eq("SSD-101"), eq("Test Label BAR"));
}
项目:jira-ext-plugin    文件:AddLabelTest.java   
/**
 * An exception adding the first label add should not disrupt the next label
 */
@Test
public void testResiliency()
    throws Exception
{
    AddLabel addLabel = new AddLabel("Test Label");
    addLabel.setJiraClientSvc(jiraClientSvc);

    AbstractBuild mockBuild = mock(AbstractBuild.class);
    when(mockBuild.getEnvironment(any(TaskListener.class))).thenReturn(new EnvVars());
    List<JiraCommit> jiraCommits = new ArrayList<>();
    jiraCommits.add(new JiraCommit("SSD-101", MockChangeLogUtil.mockChangeLogSetEntry("Test Comment")));
    jiraCommits.add(new JiraCommit("SSD-102", MockChangeLogUtil.mockChangeLogSetEntry("Test Comment")));
    doThrow(new RuntimeException("Issue is invalid"))
            .when(jiraClientSvc).addLabelToTicket("SSD-101", "Test Label");
    addLabel.perform(jiraCommits, mockBuild, mock(Launcher.class), new StreamBuildListener(System.out, Charset.defaultCharset()));
    verify(jiraClientSvc, times(1)).addLabelToTicket(eq("SSD-101"), eq("Test Label"));
    verify(jiraClientSvc, times(1)).addLabelToTicket(eq("SSD-102"), eq("Test Label"));
}
项目:jira-ext-plugin    文件:JiraBuildStepPublisherTest.java   
@Test
public void testInvokeOperations()
{
    IssueStrategyExtension mockStrategy = mock(IssueStrategyExtension.class);
    JiraOperationExtension mockOperation = mock(JiraOperationExtension.class);
    Descriptor mockDescriptor = mock(Descriptor.class);
    when(mockDescriptor.getDisplayName()).thenReturn("Mock descriptor");
    when(mockOperation.getDescriptor()).thenReturn(mockDescriptor);
    JiraExtBuildStep builder = new JiraExtBuildStep(mockStrategy,
            Arrays.asList(mockOperation));
    List<JiraCommit> commits = Arrays.asList(new JiraCommit("JENKINS-101",
                    MockChangeLogUtil.mockChangeLogSetEntry("example ticket")));

    when(mockStrategy.getJiraCommits(any(AbstractBuild.class), any(BuildListener.class)))
                .thenReturn(commits);

    assertTrue(builder.perform(mock(AbstractBuild.class), mock(Launcher.class), new StreamBuildListener(System.out)));
    verify(mockOperation).perform(eq(commits), any(AbstractBuild.class), any(Launcher.class), any(BuildListener.class));
}
项目:jira-ext-plugin    文件:FirstWordOfCommitStrategyTest.java   
@Test
public void testFirstWordOfCommit()
        throws Exception
{
    FirstWordOfCommitStrategy strategy = new FirstWordOfCommitStrategy();

    ChangeLogSet mockChangeSet = MockChangeLogUtil.mockChangeLogSet(
            new MockChangeLogUtil.MockChangeLog("FOO-101 first", "dalvizu"),
            new MockChangeLogUtil.MockChangeLog("BAR-102 again", "jsmith"),
            new MockChangeLogUtil.MockChangeLog("No Valid Ticket", "build robot"));
    AbstractBuild mockBuild = mock(AbstractBuild.class);
    when(mockBuild.getChangeSet()).thenReturn(mockChangeSet);
    List<JiraCommit> commits = strategy.getJiraCommits(mockBuild,
            new StreamBuildListener(System.out, Charset.defaultCharset()));
    assertEquals(commits.size(), 2);

    assertThat(commits, hasItem(Matchers.<JiraCommit>hasProperty("jiraTicket", equalTo("FOO-101"))));
    assertThat(commits, hasItem(Matchers.<JiraCommit>hasProperty("jiraTicket", equalTo("BAR-102"))));
}
项目:jira-ext-plugin    文件:UpdateFieldTest.java   
@Test
public void testExpandValues()
        throws Exception
{
    UpdateField updateField = new UpdateField("CustomField_123", "Completed $FOO");
    updateField.setJiraClientSvc(jiraClientSvc);
    AbstractBuild mockBuild = mock(AbstractBuild.class);
    EnvVars envVars = new EnvVars();
    envVars.put("FOO", "BAR");
    when(mockBuild.getEnvironment(any(TaskListener.class))).thenReturn(envVars);
    List<JiraCommit> jiraCommits = new ArrayList<>();
    jiraCommits.add(new JiraCommit("SSD-101", MockChangeLogUtil.mockChangeLogSetEntry("Test Comment")));

    updateField.perform(jiraCommits, mockBuild, mock(Launcher.class), new StreamBuildListener(System.out, Charset.defaultCharset()));
    verify(jiraClientSvc, times(1)).updateStringField(eq("SSD-101"), eq("CustomField_123"), eq("Completed BAR"));
}
项目:Jenkins-Ranorex-Plugin    文件:RanorexRunnerBuilder.java   
/**
 * Separates string into substrings
 *
 * @param build
 * @param env Environmental variables to be used for launching processes for
 * this build.
 * @param values string containing either parameters or arguments
 * @param isParam true if the string 'values' contains parameters, otherwise
 * false
 * @return a list of strings containing parameters or arguments
 * @throws InterruptedException
 * @throws IOException
 */
private List<String> getParamArgs(AbstractBuild<?, ?> build, EnvVars env, String values, boolean isParam) throws InterruptedException, IOException
{
    ArrayList<String> args = new ArrayList<>();
    StringTokenizer valuesToknzr = new StringTokenizer(values, "\t\r\n;");
    String argumentToAdd;
    while (valuesToknzr.hasMoreTokens())
    {
        String value = valuesToknzr.nextToken();
        value = Util.replaceMacro(value, env);
        value = Util.replaceMacro(value, build.getBuildVariables());
        if (!StringUtil.isNullOrSpace(value))
        {
            if (isParam)
            {
                if (!value.contains(("/pa:")))
                {
                    argumentToAdd = "/pa:" + value;
                }
                else
                {
                    argumentToAdd = value;
                }
            }
            else
            {
                argumentToAdd = value;
            }
            args.add(argumentToAdd.trim());
        }
    }
    return args;
}
项目:BuildSlackNotifier    文件:BuildSlackNotifier.java   
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) {
  for (SlackURL url : urls) {
    try {
      sendNotificationToSlack(build, listener, url.getUrl());
      listener.getLogger().println("[SUCCESS]: Slack notification sent to: " + url.getUrl());
    } catch (Exception ex) {
      listener.getLogger().println("[ERROR]: Could not send Slack notification");
    }
  }

  return true;
}
项目:BuildSlackNotifier    文件:BuildSlackNotifier.java   
private void sendNotificationToSlack(AbstractBuild<?, ?> build, BuildListener listener, String url) throws Exception {
  HttpClient httpClient = HttpClientBuilder.create().build();

  EnvVars envVars = build.getEnvironment(listener);
  Request payload = new Request(Attachment.build(envVars, build.getResult()));

  HttpPost request = new HttpPost(url);
  StringEntity params = new StringEntity(GsonHelper.getCommonParser().toJson(payload));
  request.addHeader("content-type", "application/json");
  request.setEntity(params);

  httpClient.execute(request);
}
项目:jenkins-client-plugin    文件:RawStep.java   
@Override
public boolean perform(final AbstractBuild build, Launcher launcher,
        final BuildListener listener) throws IOException,
        InterruptedException {
    final Map<String, String> overrides = consolidateEnvVars(listener, build, launcher);
    return withTempInput("markup", getCommand(overrides), new WithTempInputRunnable() {
        @Override
        public boolean perform(String markupFilename) throws IOException,
                InterruptedException {
            return standardRunOcCommand(build, listener, getCommand(overrides),
                    toList(getArguments(overrides)), toList(), toList());
        }
    });
}
项目:jenkins-client-plugin    文件:CreateStep.java   
@Override
public boolean perform(final AbstractBuild build, Launcher launcher,
        final BuildListener listener) throws IOException,
        InterruptedException {
    final Map<String, String> overrides = consolidateEnvVars(listener, build, launcher);
    return withTempInput("markup", getJsonyaml(overrides), new WithTempInputRunnable() {
        @Override
        public boolean perform(String markupFilename) throws IOException,
                InterruptedException {
            return standardRunOcCommand(build, listener, "create",
                    toList("-f", markupFilename), toList(), toList());
        }
    });
}
项目:jenkins-client-plugin    文件:DeleteStep.java   
@Override
public boolean perform(AbstractBuild build, Launcher launcher,
        BuildListener listener) throws IOException, InterruptedException {
    final Map<String, String> overrides = consolidateEnvVars(listener, build, null);
    List<String> base = selector.asSelectionArgs(overrides);
    if (isIgnoreNotFound()) {
        base.add("--ignore-not-found");
    }
    return standardRunOcCommand(build, listener, "delete", base, toList(),
            toList());
}
项目:ibm-cloud-devops    文件:EventHandler.java   
public static OTCNotifier findPublisher(AbstractBuild r){
    List<Publisher> publisherList = r.getProject().getPublishersList().toList();

    //ensure that there is an OTCNotifier in the project
    for(Publisher publisher: publisherList){
        if(publisher instanceof OTCNotifier){
            return (OTCNotifier) publisher;
        }
    }

    return null;
}