Java Code Examples for org.jenkinsci.plugins.workflow.steps.StepContext#get()

The following examples show how to use org.jenkinsci.plugins.workflow.steps.StepContext#get() . 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 File: GerritApiBuilder.java    From gerrit-code-review-plugin with Apache License 2.0 6 votes vote down vote up
public GerritApiBuilder stepContext(StepContext context)
    throws URISyntaxException, IOException, InterruptedException {
  EnvVars envVars = context.get(EnvVars.class);
  logger(context.get(TaskListener.class).getLogger());
  if (StringUtils.isNotEmpty(envVars.get("GERRIT_API_URL"))) {
    gerritApiUrl(envVars.get("GERRIT_API_URL"));
  } else if (StringUtils.isNotEmpty(envVars.get("GERRIT_CHANGE_URL"))) {
    gerritApiUrl(new GerritURI(new URIish(envVars.get("GERRIT_CHANGE_URL"))).getApiURI());
  }
  insecureHttps(Boolean.parseBoolean(envVars.get("GERRIT_API_INSECURE_HTTPS")));
  String credentialsId = StringUtils.defaultIfEmpty(envVars.get("GERRIT_CREDENTIALS_ID"), null);
  if (credentialsId != null) {
    credentials(
        CredentialsProvider.findCredentialById(
            credentialsId, StandardUsernamePasswordCredentials.class, context.get(Run.class)));
  }
  return this;
}
 
Example 2
Source File: GitChangelogStep.java    From git-changelog-plugin with MIT License 6 votes vote down vote up
@Override
public StepExecution start(final StepContext context) {
  return new SynchronousNonBlockingStepExecution<Object>(context) {

    private static final long serialVersionUID = 1L;

    @Override
    protected Object run() throws Exception {
      final FilePath workspace = context.get(FilePath.class);

      final MasterToSlaveCallable<Object, Exception> callable =
          new MasterToSlaveCallable<Object, Exception>() {
            private static final long serialVersionUID = 1L;

            @Override
            public Object call() throws Exception {
              return perform(workspace);
            }
          };

      return workspace.act(callable);
    }
  };
}
 
Example 3
Source File: WithMavenStepExecution2.java    From pipeline-maven-plugin with MIT License 6 votes vote down vote up
@Override
protected void finished(StepContext context) throws Exception {
    mavenSpyLogProcessor.processMavenSpyLogs(context, tempBinDir, options, mavenPublisherStrategy);

    try {
        tempBinDir.deleteRecursive();
    } catch (IOException | InterruptedException e) {
        BuildListener listener = context.get(BuildListener.class);
        try {
            if (e instanceof IOException) {
                Util.displayIOException((IOException) e, listener); // Better IOException display on windows
            }
            e.printStackTrace(listener.fatalError("Error deleting temporary files"));
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
}
 
Example 4
Source File: PipelineGraphPublisher.java    From pipeline-maven-plugin with MIT License 6 votes vote down vote up
@Override
public void process(@Nonnull StepContext context, @Nonnull Element mavenSpyLogsElt) throws IOException, InterruptedException {
    Run run = context.get(Run.class);
    TaskListener listener = context.get(TaskListener.class);

    PipelineMavenPluginDao dao = GlobalPipelineMavenConfig.get().getDao();

    List<MavenArtifact> parentProjects = listParentProjects(mavenSpyLogsElt, LOGGER);
    List<MavenDependency> dependencies = listDependencies(mavenSpyLogsElt, LOGGER);
    List<MavenArtifact> generatedArtifacts = XmlUtils.listGeneratedArtifacts(mavenSpyLogsElt, true);
    List<String> executedLifecyclePhases = XmlUtils.getExecutedLifecyclePhases(mavenSpyLogsElt);
    
    recordParentProject(parentProjects, run,listener, dao);
    recordDependencies(dependencies, generatedArtifacts, run, listener, dao);
    recordGeneratedArtifacts(generatedArtifacts, executedLifecyclePhases, run, listener, dao);
}
 
Example 5
Source File: JenkinsMavenEventSpyLogsPublisher.java    From pipeline-maven-plugin with MIT License 6 votes vote down vote up
public void process(@Nonnull StepContext context, @Nonnull FilePath mavenSpyLogs) throws IOException, InterruptedException {

        Run run = context.get(Run.class);
        ArtifactManager artifactManager = run.pickArtifactManager();
        Launcher launcher = context.get(Launcher.class);
        TaskListener listener = context.get(TaskListener.class);
        FilePath workspace = context.get(FilePath.class);

        // ARCHIVE MAVEN BUILD LOGS
        FilePath tmpFile = new FilePath(workspace, "." + mavenSpyLogs.getName());
        try {
            mavenSpyLogs.copyTo(tmpFile);
            listener.getLogger().println("[withMaven] Archive " + mavenSpyLogs.getRemote() + " as " + mavenSpyLogs.getName());
            // filePathInArchiveZone -> filePathInWorkspace
            Map<String, String> mavenBuildLogs = Collections.singletonMap(mavenSpyLogs.getName(), tmpFile.getName());
            artifactManager.archive(workspace, launcher, new BuildListenerAdapter(listener), mavenBuildLogs);
        } catch (Exception e) {
            PrintWriter errorWriter = listener.error("[withMaven] WARNING Exception archiving Maven build logs " + mavenSpyLogs + ", skip file. ");
            e.printStackTrace(errorWriter);
        } finally {
            boolean deleted = tmpFile.delete();
            if (!deleted) {
                listener.error("[withMaven] WARNING Failure to delete temporary file " + tmpFile);
            }
        }
    }
 
Example 6
Source File: GitLabBuildsStep.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
private TaskListener getTaskListener(StepContext context) {
    if (!context.isReady()) {
        return null;
    }
    try {
        return context.get(TaskListener.class);
    } catch (Exception x) {
        return null;
    }
}
 
Example 7
Source File: SSHStepExecution.java    From ssh-steps-plugin with Apache License 2.0 5 votes vote down vote up
protected SSHStepExecution(BasicSSHStep step, @Nonnull StepContext context)
    throws IOException, InterruptedException {
  super(context);
  listener = context.get(TaskListener.class);
  launcher = context.get(Launcher.class);
  this.step = step;
}
 
Example 8
Source File: GitLabCommitStatusStep.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
private TaskListener getTaskListener(StepContext context) {
    try {
        if (!context.isReady()) {
            return null;
        }
        return context.get(TaskListener.class);
    } catch (Exception x) {
        return null;
    }
}
 
Example 9
Source File: WithMavenStepExecution2.java    From pipeline-maven-plugin with MIT License 5 votes vote down vote up
WithMavenStepExecution2(StepContext context, WithMavenStep step) throws Exception {
    super(context);
    this.step = step;
    // Or just delete these fields and inline:
    listener = context.get(TaskListener.class);
    ws = context.get(FilePath.class);
    launcher = context.get(Launcher.class);
    env = context.get(EnvVars.class);
    build = context.get(Run.class);
}
 
Example 10
Source File: MavenLinkerPublisher2.java    From pipeline-maven-plugin with MIT License 5 votes vote down vote up
/**
 * Synchronize because {@link Run#addOrReplaceAction(hudson.model.Action)} is not thread safe
 */
@Override
public synchronized void process(StepContext context, Element mavenSpyLogsElt) throws IOException, InterruptedException {
    Run<?, ?> run = context.get(Run.class);
    // we replace instead of because we want to refresh the cache org.jenkinsci.plugins.pipeline.maven.publishers.MavenReport.getGeneratedArtifacts()
    run.addOrReplaceAction(new MavenReport(run));
}
 
Example 11
Source File: AddGitLabMergeRequestCommentStep.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
private TaskListener getTaskListener() {
    StepContext context = getContext();
    if (!context.isReady()) {
        return null;
    }
    try {
        return context.get(TaskListener.class);
    } catch (Exception x) {
        return null;
    }
}
 
Example 12
Source File: WithAWSStep.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
public Execution(WithAWSStep step, StepContext context) {
	super(context);
	this.step = step;
	try {
		this.envVars = context.get(EnvVars.class);
	} catch (Exception e) {
		throw new IllegalStateException(e);
	}
}
 
Example 13
Source File: DockerNodeStepExecution.java    From docker-plugin with MIT License 5 votes vote down vote up
@Override
protected void finished(StepContext context) throws Exception {
    final DockerTransientNode node = (DockerTransientNode) Jenkins.getInstance().getNode(nodeName);
    if (node != null) {
        TaskListener listener = context.get(TaskListener.class);
        listener.getLogger().println("Terminating docker node ...");
        node.terminate(listener);
        Jenkins.getInstance().removeNode(node);
    }
}
 
Example 14
Source File: AWSClientFactory.java    From aws-codebuild-jenkins-plugin with Apache License 2.0 4 votes vote down vote up
public AWSClientFactory(String credentialsType, String credentialsId, String proxyHost, String proxyPort, String awsAccessKey, Secret awsSecretKey, String awsSessionToken,
                   String region, Run<?, ?> build, StepContext stepContext) {

    this.awsAccessKey = sanitize(awsAccessKey);
    this.awsSecretKey = awsSecretKey;
    this.awsSessionToken = sanitize(awsSessionToken);
    this.region = sanitize(region);
    this.properties = new Properties();

    CodeBuilderValidation.checkAWSClientFactoryRegionConfig(this.region);
    this.credentialsDescriptor = "";

    if(credentialsType.equals(CredentialsType.Jenkins.toString())) {
        credentialsId = sanitize(credentialsId);
        CodeBuilderValidation.checkAWSClientFactoryJenkinsCredentialsConfig(credentialsId);
        com.amazonaws.codebuild.jenkinsplugin.CodeBuildBaseCredentials codeBuildCredentials;

        codeBuildCredentials = (CodeBuildBaseCredentials) CredentialsMatchers.firstOrNull(SystemCredentialsProvider.getInstance().getCredentials(),
                CredentialsMatchers.allOf(CredentialsMatchers.withId(credentialsId)));

        if(codeBuildCredentials == null) {
            Item folder;
            Jenkins instance = Jenkins.getInstance();
            if(instance != null) {
                folder = instance.getItemByFullName(build.getParent().getParent().getFullName());
                codeBuildCredentials = (CodeBuildBaseCredentials) CredentialsMatchers.firstOrNull(CredentialsProvider.lookupCredentials(Credentials.class, folder),
                        CredentialsMatchers.allOf(CredentialsMatchers.withId(credentialsId)));
            }
        }

        if(codeBuildCredentials != null) {
            this.awsCredentialsProvider = codeBuildCredentials;
            this.proxyHost = codeBuildCredentials.getProxyHost();
            this.proxyPort = parseInt(codeBuildCredentials.getProxyPort());
            this.credentialsDescriptor = codeBuildCredentials.getCredentialsDescriptor() + " (provided from Jenkins credentials " + credentialsId + ")";
        } else {
            throw new InvalidInputException(CodeBuilderValidation.invalidCredentialsIdError);
        }
    } else if(credentialsType.equals(CredentialsType.Keys.toString())) {
        if(this.awsSecretKey == null) {
            throw new InvalidInputException(invalidSecretKeyError);
        }

        if(stepContext != null && awsAccessKey.isEmpty() && awsSecretKey.getPlainText().isEmpty()) {
            try {
                EnvVars stepEnvVars = stepContext.get(EnvVars.class);
                awsCredentialsProvider = getStepCreds(stepEnvVars);
            } catch (IOException|InterruptedException e) {}
        }

        if(awsCredentialsProvider == null) {
            awsCredentialsProvider = getBasicCredentialsOrDefaultChain(sanitize(awsAccessKey), awsSecretKey.getPlainText(), sanitize(awsSessionToken));
        }
        this.proxyHost = sanitize(proxyHost);
        this.proxyPort = parseInt(proxyPort);
    } else {
        throw new InvalidInputException(invalidCredTypeError);
    }
}
 
Example 15
Source File: DependenciesFingerprintPublisher.java    From pipeline-maven-plugin with MIT License 4 votes vote down vote up
@Override
public void process(@Nonnull StepContext context, @Nonnull Element mavenSpyLogsElt) throws IOException, InterruptedException {
    Run run = context.get(Run.class);
    TaskListener listener = context.get(TaskListener.class);

    FilePath workspace = context.get(FilePath.class);

    List<MavenDependency> dependencies = listDependencies(mavenSpyLogsElt, LOGGER);

    if (LOGGER.isLoggable(Level.FINE)) {
        listener.getLogger().println("[withMaven] dependenciesFingerprintPublisher - filter: " +
                "versions[snapshot: " + isIncludeSnapshotVersions() + ", release: " + isIncludeReleaseVersions() + "], " +
                "scopes:" + getIncludedScopes());
    }

    Map<String, String> artifactsToFingerPrint = new HashMap<>(); // artifactPathInFingerprintZone -> artifactMd5
    for (MavenDependency dependency : dependencies) {
        if (dependency.isSnapshot()) {
            if (!includeSnapshotVersions) {
                if (LOGGER.isLoggable(Level.FINER)) {
                    listener.getLogger().println("[withMaven] Skip fingerprinting snapshot dependency: " + dependency);
                }
                continue;
            }
        } else {
            if (!includeReleaseVersions) {
                if (LOGGER.isLoggable(Level.FINER)) {
                    listener.getLogger().println("[withMaven] Skip fingerprinting release dependency: " + dependency);
                }
                continue;
            }
        }
        if (!getIncludedScopes().contains(dependency.getScope())) {
            if (LOGGER.isLoggable(Level.FINER)) {
                listener.getLogger().println("[withMaven] Skip fingerprinting dependency with ignored scope: " + dependency);
            }
            continue;
        }

        try {
            if (StringUtils.isEmpty(dependency.getFile())) {
                if (LOGGER.isLoggable(Level.FINER)) {
                    listener.getLogger().println("[withMaven] Can't fingerprint maven dependency with no file attached: " + dependency);
                }
                continue;
            }

            FilePath dependencyFilePath = new FilePath(workspace, dependency.getFile());

            if (!(dependency.getFile().endsWith("." + dependency.getExtension()))) {
                if (dependencyFilePath.isDirectory()) {
                    if (LOGGER.isLoggable(Level.FINE)) {
                        listener.getLogger().println("[withMaven] Skip fingerprinting of maven dependency of type directory " + dependency);
                    }
                    continue;
                }
            }

            String dependencyMavenRepoStyleFilePath =
                    dependency.getGroupId().replace('.', '/') + "/" +
                            dependency.getArtifactId() + "/" +
                            dependency.getBaseVersion() + "/" +
                            dependency.getFileNameWithBaseVersion();


            if (dependencyFilePath.exists()) {
                // the subsequent call to digest could test the existence but we don't want to prematurely optimize performances
                if (LOGGER.isLoggable(Level.FINE)) {
                    listener.getLogger().println("[withMaven] Fingerprint dependency " + dependencyMavenRepoStyleFilePath);
                }
                String artifactDigest = dependencyFilePath.digest();
                artifactsToFingerPrint.put(dependencyMavenRepoStyleFilePath, artifactDigest);
            } else {
                listener.getLogger().println("[withMaven] FAILURE to fingerprint " + dependencyMavenRepoStyleFilePath + ", file not found");
            }

        } catch (IOException | RuntimeException e) {
            listener.error("[withMaven] WARNING: Exception fingerprinting " + dependency + ", skip");
            e.printStackTrace(listener.getLogger());
            listener.getLogger().flush();
        }
    }
    LOGGER.log(Level.FINER, "Fingerprint {0}", artifactsToFingerPrint);

    // FINGERPRINT GENERATED MAVEN ARTIFACT
    FingerprintMap fingerprintMap = Jenkins.getInstance().getFingerprintMap();
    for (Map.Entry<String, String> artifactToFingerprint : artifactsToFingerPrint.entrySet()) {
        String artifactPathInFingerprintZone = artifactToFingerprint.getKey();
        String artifactMd5 = artifactToFingerprint.getValue();
        fingerprintMap.getOrCreate(null, artifactPathInFingerprintZone, artifactMd5).addFor(run);
    }

    // add action
    Fingerprinter.FingerprintAction fingerprintAction = run.getAction(Fingerprinter.FingerprintAction.class);
    if (fingerprintAction == null) {
        run.addAction(new Fingerprinter.FingerprintAction(run, artifactsToFingerPrint));
    } else {
        fingerprintAction.add(artifactsToFingerPrint);
    }
}
 
Example 16
Source File: HubotStepExecution.java    From hubot-steps-plugin with Apache License 2.0 4 votes vote down vote up
protected HubotStepExecution(StepContext context) throws IOException, InterruptedException {
  super(context);
  run = context.get(Run.class);
  listener = context.get(TaskListener.class);
  envVars = context.get(EnvVars.class);
}
 
Example 17
Source File: AddGitLabMergeRequestCommentStep.java    From gitlab-plugin with GNU General Public License v2.0 4 votes vote down vote up
AddGitLabMergeRequestCommentStepExecution(StepContext context, AddGitLabMergeRequestCommentStep step) throws Exception {
    super(context);
    this.step = step;
    run = context.get(Run.class);
}
 
Example 18
Source File: JiraStepExecution.java    From jira-steps-plugin with Apache License 2.0 4 votes vote down vote up
protected JiraStepExecution(final StepContext context) throws IOException, InterruptedException {
  super(context);
  run = context.get(Run.class);
  listener = context.get(TaskListener.class);
  envVars = context.get(EnvVars.class);
}
 
Example 19
Source File: GitLabBuildsStep.java    From gitlab-plugin with GNU General Public License v2.0 4 votes vote down vote up
GitLabBuildStepExecution(StepContext context, GitLabBuildsStep step) throws Exception {
    super(context);
    this.step = step;
    run = context.get(Run.class);
}
 
Example 20
Source File: GerritChange.java    From gerrit-code-review-plugin with Apache License 2.0 4 votes vote down vote up
public GerritChange(StepContext context) throws IOException, InterruptedException {
  this(context.get(EnvVars.class), context.get(TaskListener.class).getLogger());
}