Java Code Examples for hudson.model.TaskListener

The following examples show how to use hudson.model.TaskListener. 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: elasticsearch-jenkins   Source File: BuildListener.java    License: MIT License 6 votes vote down vote up
@Override
public void onCompleted(Run run, TaskListener listener) {
    loadConfig();

    final boolean validConfig = config != null && config.nonEmptyValues();
    if (validConfig) {
        final Build build = createBuild(run, listener);

        try {
            final Index index = new Index.Builder(build).index(config.getIndexName()).type(config.getTypeName()).build();

            final JestResult result = jestClient.execute(index);

            if (result.isSucceeded()) {
                LOG.fine("Sent build to Elasticsearch: " + build);
            } else {
                LOG.warning("Failed to index build, got error message: " + result.getErrorMessage());
            }
        } catch (Exception e) {
            LOG.log(Level.SEVERE, "Error when sending build data: " + build, e);
        }
    } else {
        LOG.fine("The configuration is not valid, can not index the build");
    }
}
 
Example 2
@Before
public void setup() throws IOException, InterruptedException {

  // Prepare site.
  when(envVarsMock.get("JIRA_SITE")).thenReturn("LOCAL");
  when(envVarsMock.get("BUILD_URL")).thenReturn("http://localhost:8080/jira-testing/job/01");

  PowerMockito.mockStatic(Site.class);
  Mockito.when(Site.get(any())).thenReturn(siteMock);
  when(siteMock.getService()).thenReturn(jiraServiceMock);

  when(runMock.getCauses()).thenReturn(null);
  when(taskListenerMock.getLogger()).thenReturn(printStreamMock);
  doNothing().when(printStreamMock).println();

  final ResponseDataBuilder<Object> builder = ResponseData.builder();
  when(jiraServiceMock
      .assignableUserSearch(any(), anyString(), anyString(), anyInt(), anyInt()))
      .thenReturn(builder.successful(true).code(200).message("Success").build());

  when(contextMock.get(Run.class)).thenReturn(runMock);
  when(contextMock.get(TaskListener.class)).thenReturn(taskListenerMock);
  when(contextMock.get(EnvVars.class)).thenReturn(envVarsMock);
}
 
Example 3
@Test
public void createChangeSetStackDoesNotExist() throws Exception {
	WorkflowJob job = this.jenkinsRule.jenkins.createProject(WorkflowJob.class, "cfnTest");
	Mockito.when(this.stack.exists()).thenReturn(false);
	Mockito.when(this.stack.describeChangeSet("bar")).thenReturn(new DescribeChangeSetResult()
			.withChanges(new Change())
			.withStatus(ChangeSetStatus.CREATE_COMPLETE)
	);
	job.setDefinition(new CpsFlowDefinition(""
			+ "node {\n"
			+ "  def changes = cfnCreateChangeSet(stack: 'foo', changeSet: 'bar')\n"
			+ "  echo \"changesCount=${changes.size()}\"\n"
			+ "}\n", true)
	);
	Run run = this.jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));
	this.jenkinsRule.assertLogContains("changesCount=1", run);

	PowerMockito.verifyNew(CloudFormationStack.class, Mockito.atLeastOnce()).withArguments(Mockito.any(AmazonCloudFormation.class), Mockito.eq("foo"), Mockito.any(TaskListener.class));
	Mockito.verify(this.stack).createChangeSet(Mockito.eq("bar"), Mockito.anyString(), Mockito.anyString(), Mockito.anyCollectionOf(Parameter.class), Mockito.anyCollectionOf(Tag.class),
											   Mockito.anyCollectionOf(String.class), Mockito.any(PollConfiguration.class), Mockito.eq(ChangeSetType.CREATE), Mockito.anyString(), Mockito.any());
}
 
Example 4
Source Project: github-integration-plugin   Source File: GitHubPRCloseEvent.java    License: MIT License 6 votes vote down vote up
@Override
public GitHubPRCause check(@Nonnull GitHubPRDecisionContext prDecisionContext) throws IOException {
    TaskListener listener = prDecisionContext.getListener();
    GHPullRequest remotePR = prDecisionContext.getRemotePR();
    final PrintStream logger = listener.getLogger();
    final GitHubPRPullRequest localPR = prDecisionContext.getLocalPR();

    if (isNull(localPR)) {
        return null;
    }

    GitHubPRCause cause = null;

    // must be closed once
    if (remotePR.getState().equals(GHIssueState.CLOSED)) {
        logger.println(DISPLAY_NAME + ": state has changed (PR was closed)");
        cause = prDecisionContext.newCause("PR was closed", false);
    }

    return cause;
}
 
Example 5
@Test
public void should_generate_simple_invocation() throws Exception {
    // Given
    Inventory inventory = new InventoryPath("/tmp/hosts");
    BuildListener listener = mock(BuildListener.class);
    CLIRunner runner = mock(CLIRunner.class);
    AbstractBuild<?,?> build = mock(AbstractBuild.class);
    when(build.getEnvironment(any(TaskListener.class))).thenReturn(new EnvVars());
    AnsibleAdHocCommandInvocation invocation = new AnsibleAdHocCommandInvocation("/usr/local/bin/ansible", build, listener);
    invocation.setHostPattern("localhost");
    invocation.setInventory(inventory);
    invocation.setModule("ping");
    invocation.setForks(5);
    // When
    invocation.execute(runner);
    // Then
    ArgumentCaptor<ArgumentListBuilder> argument = ArgumentCaptor.forClass(ArgumentListBuilder.class);
    verify(runner).execute(argument.capture(), anyMap());
    assertThat(argument.getValue().toString())
            .isEqualTo("/usr/local/bin/ansible localhost -i /tmp/hosts -m ping -f 5");
}
 
Example 6
Source Project: kubernetes-plugin   Source File: Reaper.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onEvent(@NonNull Action action, @NonNull KubernetesSlave node, @NonNull Pod pod) throws IOException, InterruptedException {
    List<ContainerStatus> backOffContainers = PodUtils.getContainers(pod, cs -> {
        ContainerStateWaiting waiting = cs.getState().getWaiting();
        return waiting != null && waiting.getMessage() != null && waiting.getMessage().contains("Back-off pulling image");
    });
    if (backOffContainers.isEmpty()) {
        return;
    }
    backOffContainers.forEach(cs -> {
        TaskListener runListener = node.getTemplate().getListener();
        runListener.error("Unable to pull Docker image \""+cs.getImage()+"\". Check if image tag name is spelled correctly.");
    });
    Queue q = Jenkins.get().getQueue();
    String runUrl = pod.getMetadata().getAnnotations().get("runUrl");
    for (Queue.Item item: q.getItems()) {
        if (item.task.getUrl().equals(runUrl)) {
            q.cancel(item);
            break;
        }
    }
    node.terminate();
}
 
Example 7
public void pollForLogs(TaskListener listener) {
    if(cwlStreamingDisabled) {
        return;
    } else if(this.logsLocation != null && this.logsLocation.getGroupName() != null && this.logsLocation.getStreamName() != null) {
        this.latestLogs = new ArrayList<>();
        GetLogEventsRequest logRequest = new GetLogEventsRequest()
            .withStartTime(lastPollTime)
            .withStartFromHead(true)
            .withLogGroupName(logsLocation.getGroupName())
            .withLogStreamName(logsLocation.getStreamName());
        try {
            GetLogEventsResult logsResult = logsClient.getLogEvents(logRequest);
            getAndFormatLogs(logsResult.getEvents(), listener);
        } catch (Exception e) {
            latestLogs = Arrays.asList(e.getMessage());
            return;
        }
    } else {
        latestLogs = Arrays.asList(noLogsMessage);
        return;
    }
}
 
Example 8
@Test
public void createChangeSetWithRawTemplate() throws Exception {
	WorkflowJob job = this.jenkinsRule.jenkins.createProject(WorkflowJob.class, "cfnTest");
	Mockito.when(this.stack.exists()).thenReturn(true);
	Mockito.when(this.stack.describeChangeSet("bar")).thenReturn(new DescribeChangeSetResult()
			.withChanges(new Change())
			.withStatus(ChangeSetStatus.CREATE_COMPLETE)
	);
	job.setDefinition(new CpsFlowDefinition(""
			+ "node {\n"
			+ "  def changes = cfnCreateChangeSet(stack: 'foo', changeSet: 'bar', template: 'foobaz')\n"
			+ "  echo \"changesCount=${changes.size()}\"\n"
			+ "}\n", true)
	);
	Run run = this.jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));
	this.jenkinsRule.assertLogContains("changesCount=1", run);

	PowerMockito.verifyNew(CloudFormationStack.class, Mockito.atLeastOnce()).withArguments(Mockito.any(AmazonCloudFormation.class), Mockito.eq("foo"), Mockito.any(TaskListener.class));
	Mockito.verify(this.stack).createChangeSet(Mockito.eq("bar"), Mockito.eq("foobaz"), Mockito.anyString(), Mockito.anyCollectionOf(Parameter.class), Mockito.anyCollectionOf(Tag.class),
											   Mockito.anyCollectionOf(String.class), Mockito.any(PollConfiguration.class), Mockito.eq(ChangeSetType.UPDATE), Mockito.anyString(), Mockito.any());
}
 
Example 9
Source Project: warnings-ng-plugin   Source File: IssuesScanner.java    License: MIT License 6 votes vote down vote up
@SuppressWarnings("checkstyle:ParameterNumber")
IssuesScanner(final Tool tool, final List<RegexpFilter> filters, final Charset sourceCodeEncoding,
        final FilePath workspace, final String sourceDirectory, final Run<?, ?> run,
        final FilePath jenkinsRootDir, final TaskListener listener,
        final BlameMode blameMode, final ForensicsMode forensicsMode) {
    this.filters = new ArrayList<>(filters);
    this.sourceCodeEncoding = sourceCodeEncoding;
    this.tool = tool;
    this.workspace = workspace;
    this.sourceDirectory = sourceDirectory;
    this.run = run;
    this.jenkinsRootDir = jenkinsRootDir;
    this.listener = listener;
    this.blameMode = blameMode;
    this.forensicsMode = forensicsMode;
}
 
Example 10
Source Project: jenkins-plugin   Source File: IOpenShiftApiObjHandler.java    License: Apache License 2.0 6 votes vote down vote up
default ModelNode hydrateJsonYaml(String jsonyaml, TaskListener listener) {
    // construct json/yaml node
    ModelNode resources = null;
    try {
        resources = ModelNode.fromJSONString(jsonyaml);
    } catch (Exception e) {
        Yaml yaml = new Yaml(new SafeConstructor());
        Map<String, Object> map = (Map<String, Object>) yaml.load(jsonyaml);
        JSONObject jsonObj = JSONObject.fromObject(map);
        try {
            resources = ModelNode.fromJSONString(jsonObj.toString());
        } catch (Throwable t) {
            if (listener != null)
                t.printStackTrace(listener.getLogger());
        }
    }
    return resources;
}
 
Example 11
Source Project: ssh-steps-plugin   Source File: PutStepTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws IOException, InterruptedException {

  when(runMock.getCauses()).thenReturn(null);
  when(taskListenerMock.getLogger()).thenReturn(printStreamMock);
  doNothing().when(printStreamMock).println();
  when(launcherMock.getChannel()).thenReturn(new TestVirtualChannel());

  PowerMockito.mockStatic(SSHService.class);
  when(SSHService.create(any(), anyBoolean(), anyBoolean(), any())).thenReturn(sshServiceMock);

  when(filePathMock.child(any())).thenReturn(filePathMock);
  when(filePathMock.exists()).thenReturn(true);
  when(filePathMock.isDirectory()).thenReturn(false);
  when(filePathMock.getRemote()).thenReturn(path);

  when(contextMock.get(Run.class)).thenReturn(runMock);
  when(contextMock.get(TaskListener.class)).thenReturn(taskListenerMock);
  when(contextMock.get(EnvVars.class)).thenReturn(envVarsMock);
  when(contextMock.get(Launcher.class)).thenReturn(launcherMock);
  when(contextMock.get(FilePath.class)).thenReturn(filePathMock);

}
 
Example 12
Source Project: lockable-resources-plugin   Source File: LockRunListener.java    License: MIT License 6 votes vote down vote up
@Override
public void onCompleted(Run<?, ?> build, TaskListener listener) {
	// Skip unlocking for multiple configuration projects,
	// only the child jobs will actually unlock resources.
	if (build instanceof MatrixBuild)
		return;

	// obviously project name cannot be obtained here
	List<LockableResource> required = LockableResourcesManager.get()
			.getResourcesFromBuild(build);
	if (!required.isEmpty()) {
		LockableResourcesManager.get().unlock(required, build);
		listener.getLogger().printf("%s released lock on %s%n",
				LOG_PREFIX, required);
		LOGGER.fine(build.getFullDisplayName() + " released lock on "
				+ required);
	}

}
 
Example 13
Source Project: kubernetes-plugin   Source File: KubernetesSlave.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Launcher createLauncher(TaskListener listener) {
    Launcher launcher = super.createLauncher(listener);
    if (template != null) {
        Executor executor = Executor.currentExecutor();
        if (executor != null) {
            Queue.Executable currentExecutable = executor.getCurrentExecutable();
            if (currentExecutable != null && executables.add(currentExecutable)) {
                listener.getLogger().println(Messages.KubernetesSlave_AgentIsProvisionedFromTemplate(
                        ModelHyperlinkNote.encodeTo("/computer/" + getNodeName(), getNodeName()),
                        getTemplate().getName())
                );
                printAgentDescription(listener);
                checkHomeAndWarnIfNeeded(listener);
            }
        }
    }
    return launcher;
}
 
Example 14
/**
 * {@inheritDoc}
 */
@Override
public boolean isAutomaticBuild(@NonNull SCMSource source, @NonNull SCMHead head, @NonNull SCMRevision currRevision,
                                @CheckForNull SCMRevision lastBuiltRevision, @CheckForNull SCMRevision lastSeenRevision, @NonNull TaskListener taskListener) {

    if(strategies.isEmpty()){
        return false;
    }

    for (BranchBuildStrategy strategy: strategies) {
        if(strategy.automaticBuild(
            source,
            head,
            currRevision,
            lastBuiltRevision,
            lastSeenRevision,
            taskListener
        )){
            return true;
        };

    }
    return false;
}
 
Example 15
Source Project: kubernetes-plugin   Source File: KubernetesLauncher.java    License: Apache License 2.0 5 votes vote down vote up
private Watch eventWatch(KubernetesClient client, String podName, String namespace, TaskListener runListener) {
    try {
        return client.events().inNamespace(namespace).withField("involvedObject.name", podName).watch(new TaskListenerEventWatcher(podName, runListener));
    } catch (KubernetesClientException e) {
        LOGGER.log(Level.INFO, e, () -> "Cannot watch events on " + namespace + "/" +podName);
    }
    return () -> {};
}
 
Example 16
public PullRequestToCauseConverter(@Nonnull GitHubPRRepository localRepo,
                                   @Nonnull TaskListener listener,
                                   @Nonnull GitHubSCMSource source,
                                   @Nonnull GitHubPRHandler prHandler) {
    this.localRepo = localRepo;
    this.listener = listener;
    this.source = source;
    this.prHandler = prHandler;
    trigger = null;
}
 
Example 17
@Override
protected JiraSendInfoResponse run() throws Exception {
    final TaskListener taskListener = getContext().get(TaskListener.class);
    final WorkflowRun workflowRun = getContext().get(WorkflowRun.class);

    final JiraBuildInfoRequest request =
            new JiraBuildInfoRequest(step.getSite(), step.getBranch(), workflowRun);

    final JiraSendInfoResponse response =
            JiraSenderFactory.getInstance().getJiraBuildInfoSender().sendBuildInfo(request);

    logResult(taskListener, response);

    return response;
}
 
Example 18
@SuppressFBWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE") // No idea why this is needed
private void archiveArtifacts(Run<?, ?> build, FilePath workspace, Launcher launcher, TaskListener listener)
		throws java.lang.InterruptedException {
	ArtifactArchiver artifactArchiver = new ArtifactArchiver("scanout*");
	artifactArchiver.perform(build, workspace, launcher, listener);
	ArtifactArchiver styleArtifactArchiver = new ArtifactArchiver("styles.css");
	styleArtifactArchiver.perform(build, workspace, launcher, listener);
}
 
Example 19
@Test
public void testStep() throws Exception {
    // given
    final WorkflowRun mockWorkflowRun = mockWorkflowRun();
    final TaskListener mockTaskListener = mockTaskListener();
    when(mockTaskListener.getLogger()).thenReturn(mock(PrintStream.class));

    final Map<String, Object> r = new HashMap<>();
    r.put("site", SITE);
    r.put("environment", ENVIRONMENT_NAME);
    r.put("environmentType", ENVIRONMENT_TYPE);
    final JiraSendDeploymentInfoStep step =
            (JiraSendDeploymentInfoStep) descriptor.newInstance(r);

    final StepContext ctx = mock(StepContext.class);
    when(ctx.get(Node.class)).thenReturn(jenkinsRule.getInstance());
    when(ctx.get(WorkflowRun.class)).thenReturn(mockWorkflowRun);
    when(ctx.get(TaskListener.class)).thenReturn(mockTaskListener);

    final JiraSendDeploymentInfoStep.JiraSendDeploymentInfoStepExecution start =
            (JiraSendDeploymentInfoStep.JiraSendDeploymentInfoStepExecution) step.start(ctx);

    // when
    final JiraSendInfoResponse response = start.run();

    // then
    assertThat(response.getStatus()).isEqualTo(SUCCESS_DEPLOYMENT_ACCEPTED);
}
 
Example 20
Source Project: jenkins-datadog-plugin   Source File: DatadogComputerListener.java    License: MIT License 5 votes vote down vote up
@Override
public void onLaunchFailure(Computer computer, TaskListener taskListener) throws IOException, InterruptedException {
    try {
        final boolean emitSystemEvents = DatadogUtilities.getDatadogGlobalDescriptor().isEmitSystemEvents();
        if (!emitSystemEvents) {
            return;
        }
        logger.fine("Start DatadogComputerListener#onLaunchFailure");

        // Get Datadog Client Instance
        DatadogClient client = ClientFactory.getClient();

        // Get the list of tags to apply
        Map<String, Set<String>> tags = TagsUtil.merge(
                DatadogUtilities.getTagsFromGlobalTags(),
                DatadogUtilities.getComputerTags(computer));

        // Send event
        DatadogEvent event = new ComputerLaunchFailedEventImpl(computer, taskListener, tags);
        client.event(event);

        // Submit counter
        String hostname = DatadogUtilities.getHostname("null");
        client.incrementCounter("jenkins.computer.launch_failure", hostname, tags);

        logger.fine("End DatadogComputerListener#onLaunchFailure");
    } catch (Exception e) {
        logger.warning("Unexpected exception occurred - " + e.getMessage());
    }
}
 
Example 21
@Override
public void buildEnvironmentFor(Run r, EnvVars envs, TaskListener listener)
		throws IOException, InterruptedException {
	ResourceVariableNameAction a = r.getAction(ResourceVariableNameAction.class);
	if (a != null && a.getParameter() != null && a.getParameter().getValue() != null) {
		envs.put(a.getParameter().getName(), String.valueOf(a.getParameter().getValue()));
	}
}
 
Example 22
Source Project: docker-plugin   Source File: DockerJobProperty.java    License: MIT License 5 votes vote down vote up
private String getAdditionalTag(AbstractBuild build, TaskListener listener) {
    // Do a macro expansion on the addJenkinsAction token

    // Job property
    String tagToken = additionalTag;

    // Do any macro expansions
    try {
        if (!Strings.isNullOrEmpty(tagToken))
            tagToken = TokenMacro.expandAll(build, listener, tagToken);
    } catch (Exception e) {
        LOGGER.warn("can't expand macro", e);
    }
    return tagToken;
}
 
Example 23
@Override
public GitHubPRCause check(@Nonnull GitHubPRDecisionContext prDecisionContext) throws IOException {
    TaskListener listener = prDecisionContext.getListener();
    GitHubPRPullRequest localPR = prDecisionContext.getLocalPR();
    GHPullRequest remotePR = prDecisionContext.getRemotePR();

    if (remotePR.getState().equals(GHIssueState.CLOSED)) {
        return null; // already closed, skip check?
    }

    if (isNull(label)) {
        LOG.error("Label is null. Bad configured event: {}", getDescriptor().getDisplayName());
        throw new IllegalStateException("Label is null. Bad configured event: " + getDescriptor().getDisplayName());
    }

    //localPR exists before, checking for changes
    if (localPR != null && localPR.getLabels().containsAll(label.getLabelsSet())) {
        return null; // label existed before exiting
    }

    GitHubPRCause cause = null;

    Collection<GHLabel> labels = remotePR.getRepository().getIssue(remotePR.getNumber()).getLabels();
    Set<String> existingLabels = new HashSet<String>();

    for (GHLabel curLabel : labels) {
        existingLabels.add(curLabel.getName());
    }

    if (existingLabels.containsAll(label.getLabelsSet())) {
        final PrintStream logger = listener.getLogger();
        logger.println(DISPLAY_NAME + ": state has changed (" + label.getLabelsSet() + " labels were added");
        cause = prDecisionContext.newCause(label.getLabelsSet() + " labels were added", false);
    }

    return cause;
}
 
Example 24
Source Project: pipeline-aws-plugin   Source File: CFNDescribeStep.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Map<String, String> run() throws Exception {
	final String stack = this.step.getStack();
	final TaskListener listener = this.getContext().get(TaskListener.class);

	Preconditions.checkArgument(stack != null && !stack.isEmpty(), "Stack must not be null or empty");

	listener.getLogger().format("Getting outputs of CloudFormation stack %s %n", stack);
	AmazonCloudFormation client = AWSClientFactory.create(AmazonCloudFormationClientBuilder.standard(), Execution.this.getContext());
	CloudFormationStack cfnStack = new CloudFormationStack(client, stack, listener);
	return cfnStack.describeOutputs();
}
 
Example 25
Source Project: DotCi   Source File: GitCloneEnvContributor.java    License: MIT License 5 votes vote down vote up
@Override
public void buildEnvironmentFor(Job job, EnvVars envs, TaskListener listener) throws IOException, InterruptedException {
    if (job instanceof DynamicProject) {
        DynamicProject dynamicJob = ((DynamicProject) job);
        GitUrl gitUrl = new GitUrl(dynamicJob.getGithubRepoUrl());
        envs.put("DOTCI_DOCKER_COMPOSE_GIT_CLONE_URL", getCloneUrl(gitUrl));
    }
}
 
Example 26
@Override
public void buildEnvironmentFor(@Nonnull Run r, @Nonnull EnvVars envs, @Nonnull TaskListener listener) throws IOException, InterruptedException {
    GitLabWebHookCause cause = null;
    if (r instanceof MatrixRun) {
        MatrixBuild parent = ((MatrixRun)r).getParentBuild();
        if (parent != null) {
            cause = (GitLabWebHookCause) parent.getCause(GitLabWebHookCause.class);
        }
    } else {
        cause = (GitLabWebHookCause) r.getCause(GitLabWebHookCause.class);
    }
    if (cause != null) {
        envs.overrideAll(cause.getData().getBuildVariables());
    }
}
 
Example 27
@Override
protected void perform(Run<?, ?> build, TaskListener listener, GitLabClient client, MergeRequest mergeRequest) {
    try {
        if (build.getResult() == Result.SUCCESS) {
            client.acceptMergeRequest(mergeRequest, "Merge Request accepted by jenkins build success", false);
        }
    } catch (WebApplicationException | ProcessingException e) {
        listener.getLogger().printf("Failed to accept merge request for project '%s': %s%n", mergeRequest.getProjectId(), e.getMessage());
        LOGGER.log(Level.SEVERE, String.format("Failed to accept merge request for project '%s'", mergeRequest.getProjectId()), e);
    }
}
 
Example 28
Source Project: gitlab-branch-source-plugin   Source File: GitLabSCMSource.java    License: MIT License 5 votes vote down vote up
@Override
protected SCMRevision retrieve(@NonNull String thingName, @NonNull TaskListener listener)
        throws IOException, InterruptedException {
    SCMHeadObserver.Named baptist = SCMHeadObserver.named(thingName);
    retrieve(null, baptist, null, listener);
    return baptist.result();
}
 
Example 29
@Before
public void setUp() throws IOException, InterruptedException, ReflectiveOperationException {
    super.setUp();

    descriptor = new AWSCodePipelineSCM.DescriptorImpl(false);

    when(mockBuild.getEnvironment(any(TaskListener.class))).thenReturn(envVars);
    when(envVars.get(any(String.class))).thenReturn("Project");
    when(model.getJob()).thenReturn(mockJob);
    when(mockJob.getId()).thenReturn(jobId);

    CodePipelineStateService.setModel(model);
}
 
Example 30
Source Project: pipeline-aws-plugin   Source File: AWSIdentityStep.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Map<String, String> run() throws Exception {
	AWSSecurityTokenService sts = AWSClientFactory.create(AWSSecurityTokenServiceClientBuilder.standard(), this.getContext());
	GetCallerIdentityResult identity = sts.getCallerIdentity(new GetCallerIdentityRequest());

	this.getContext().get(TaskListener.class).getLogger().format("Current AWS identity: %s - %s - %s %n", identity.getAccount(), identity.getUserId(), identity.getArn());

	Map<String, String> info = new HashMap<>();
	info.put("account", identity.getAccount());
	info.put("user", identity.getUserId());
	info.put("arn", identity.getArn());
	return info;
}