下面列出了java.lang.InterruptedException#hudson.model.BuildListener 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public boolean perform(AbstractBuild<?, ?> build,
Launcher launcher, BuildListener listener)
throws InterruptedException, IOException {
System.out.println("in perform...");
// First touch all the files, so they will be recently modified
for (FilePath f : build.getWorkspace().list()) {
f.touch(System.currentTimeMillis());
}
System.out.println("...touched everything");
hudson.tasks.junit.TestResult result = (new JUnitParser()).parseResult(testResultLocation, build,
null, build.getWorkspace(), launcher, listener);
System.out.println("back from parse");
assertNotNull("we should have a non-null result", result);
assertTrue("result should be a TestResult", result instanceof hudson.tasks.junit.TestResult);
System.out.println("We passed some assertions in the JUnitParserTestBuilder");
theResult = result;
return result != null;
}
@Override
public boolean perform(DynamicBuild dynamicBuild, Launcher launcher, BuildListener listener) {
if (!(options instanceof Map)) {
throw new InvalidBuildConfigurationException("Invalid format specified for " + getName() + " . Expecting a Map.");
}
Map<String, Object> jobOptions = (Map<String, Object>) options;
if (shouldKickOffJob(dynamicBuild, jobOptions)) {
String jobName = getJobName(jobOptions);
DynamicProject job = findJob(jobName);
Map<String, String> jobParams = new HashMap<String, String>((Map<String, String>) jobOptions.get(jobName));
jobParams.put("SOURCE_BUILD", getSourceBuildNumber(dynamicBuild));
listener.getLogger().println("Lauching dowstream job :" + job.getFullName());
return job.scheduleBuild(0, getCause(dynamicBuild, job, jobOptions.get(jobName)), getParamsAction(jobParams));
}
return true;
}
/**
* set up script based authentication method for the created context
* @author Abdellah AZOUGARH
* @param listener the listener to display log during the job execution in jenkins
* @param zapClientAPI the ZAP API client
* @param scriptName the name of the authentication script used to authenticate the user
* @param scriptLoggedInIndicator the indication that the user is logged in
* @throws UnsupportedEncodingException
* @throws ClientApiException
*/
private void setUpScriptBasedAuthenticationMethod( BuildListener listener, ClientApi zapClientAPI,String scriptName , String contextId, String scriptLoggedInIndicator) throws UnsupportedEncodingException, ClientApiException {
// set script based authentication method
// Prepare the configuration in a format similar to how URL parameters are formed. This
// means that any value we add for the configuration values has to be URL encoded.
StringBuilder scriptBasedConfig = new StringBuilder();
scriptBasedConfig.append("scriptName=").append(URLEncoder.encode(scriptName, "UTF-8"));
listener.getLogger().println("Setting Script based authentication configuration as: " + scriptBasedConfig.toString());
zapClientAPI.authentication.setAuthenticationMethod(API_KEY, contextId, "scriptBasedAuthentication",scriptBasedConfig.toString());
listener.getLogger().println("Authentication config: " + zapClientAPI.authentication.getAuthenticationMethod(contextId).toString(0));
//add logged in idicator
if (!scriptLoggedInIndicator.equals("")) {
listener.getLogger().println("---------------------------------------");
zapClientAPI.authentication.setLoggedInIndicator(API_KEY,contextId, scriptLoggedInIndicator );
}
}
@Override
public void perform(List<JiraCommit> commits, AbstractBuild build, Launcher launcher, BuildListener listener)
{
for (JiraCommit commit : JiraCommit.filterDuplicateIssues(commits))
{
try
{
String expandedValue = build.getEnvironment(listener).expand(fieldValue);
getJiraClientSvc().updateStringField(commit.getJiraTicket(), fieldName, expandedValue);
}
catch (Throwable t)
{
listener.getLogger().println("Error updating ticket, continuing");
t.printStackTrace(listener.getLogger());
}
}
}
/**
* Set up all authentication details
* @author thilina27
* @param username user name to be used in authentication
* @param password password for the authentication user
* @param usernameParameter parameter define in passing username
* @param passwordParameter parameter that define in passing password for the user
* @param extraPostData other post data than credentials
* @param loginUrl login page url
* @param loggedInIdicator indication for know its logged in
* @throws ClientApiException
* @throws InterruptedException
* @throws UnsupportedEncodingException
*/
private void setUpAuthentication( String authenticationMethod,BuildListener listener, ClientApi zapClientAPI,
String username, String password, String usernameParameter,
String passwordParameter, String extraPostData, String loginUrl, String loggedInIndicator,String scriptName)
throws ClientApiException, UnsupportedEncodingException {
//setup context
//this.contextId=setUpContext(listener,url,zapClientAPI);
//set up authentication method
if(authenticationMethod.equals("FORMBASED")){
setUpFormBasedAuthenticationMethod(listener,zapClientAPI,loggedInIndicator,usernameParameter,
passwordParameter,extraPostData,contextId,loginUrl);
}
else if(authenticationMethod.equals("SCRIPTBASED")){
setUpScriptBasedAuthenticationMethod(listener, zapClientAPI, scriptName , contextId, loggedInIndicator);
}
//set up user
this.userId=setUpUser(listener,zapClientAPI,username,password,contextId);
}
public static void compressZipFile(
final File temporaryZipFile,
final Path pathToCompress,
final BuildListener listener)
throws IOException {
try (final ZipArchiveOutputStream zipArchiveOutputStream =
new ZipArchiveOutputStream(
new BufferedOutputStream(
new FileOutputStream(temporaryZipFile)))) {
compressArchive(
pathToCompress,
zipArchiveOutputStream,
new ArchiveEntryFactory(CompressionType.Zip),
CompressionType.Zip,
listener);
}
}
/**
* Search for all links and pages on the URL and raised passives alerts
* @author thilina27
* @param url the url to investigate
* @param listener the listener to display log during the job execution in jenkins
* @param zapClientAPI the client API to use ZAP API methods
* @throws ClientApiException
* @throws InterruptedException
*/
private void ajaxSpiderURL(final String url, BuildListener listener, ClientApi zapClientAPI)
throws ClientApiException, InterruptedException{
//Method signature : scan(String apikey,String url,String inscope)
zapClientAPI.ajaxSpider.scan(API_KEY, url, "false");
// Wait for complete spidering (equal to status complete)
// Method signature : status(String scanId)
while ("running".equalsIgnoreCase(statusToString(zapClientAPI.ajaxSpider.status()))) {
listener.getLogger().println("Status spider = " + statusToString(zapClientAPI.ajaxSpider.status()));
listener.getLogger().println("Alerts number = " + zapClientAPI.core.numberOfAlerts("").toString(2));
Thread.sleep(2500);
}
}
@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));
}
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
throws InterruptedException, IOException {
final PrintStream llogger = listener.getLogger();
final String dockerImage = dockerTemplate.getDockerTemplateBase().getImage();
// Job must run as Admin as we are changing global cloud configuration here.
build.getACL().checkPermission(Jenkins.ADMINISTER);
for (Cloud c : Jenkins.getInstance().clouds) {
if (c instanceof DockerCloud && dockerImage != null) {
DockerCloud dockerCloud = (DockerCloud) c;
if (dockerCloud.getTemplate(dockerImage) == null) {
LOGGER.info("Adding new template: '{}', to cloud: '{}'", dockerImage, dockerCloud.name);
llogger.println("Adding new template: '" + dockerImage + "', to cloud: '" + dockerCloud.name + "'");
dockerCloud.addTemplate(dockerTemplate);
}
}
}
return true;
}
/**
* Scan all pages found at url and raised actives alerts
*
* @author abdellah.azougarh
* @param url the url to scan
* @param listener the listener to display log during the job execution in jenkins
* @param zapClientAPI the client API to use ZAP API methods
* @param contextId the id number of the contexte created for this scan
* @param userId the id number of the user created for this scan
* @throws ClientApiException
* @throws InterruptedException
*/
private void scanURLAsUser(final String url, BuildListener listener, ClientApi zapClientAPI, String contextId, String userId)
throws ClientApiException, InterruptedException {
if(chosenPolicy == null || chosenPolicy.isEmpty()) {
listener.getLogger().println("Scan url [" + url + "] with the policy by default");
} else {
listener.getLogger().println("Scan url [" + url + "] with the following policy ["
+ chosenPolicy + "]");
}
// Method signature : scan(String apikey, String url, String recurse, String inscopeonly, String scanpolicyname, String method, String postdata)
// Use a default policy if chosenPolicy is null or empty
zapClientAPI.ascan.scanAsUser(API_KEY, url, contextId, userId,"true", chosenPolicy, null, null);//arg2, arg3, arg4, arg5, arg6, arg7)scan(API_KEY, url, "true", "false", chosenPolicy, null, null);
// Wait for complete scanning (equal to 100)
// Method signature : status(String scanId)
while (statusToInt(zapClientAPI.ascan.status("")) < 100) {
listener.getLogger().println("Status scan = " + statusToInt(zapClientAPI.ascan.status("")) + "%");
listener.getLogger().println("Alerts number = " + zapClientAPI.core.numberOfAlerts("").toString(2));
listener.getLogger().println("Messages number = " + zapClientAPI.core.numberOfMessages("").toString(2));
Thread.sleep(5000);
}
}
/**
* Search for all links and pages on the URL and raised passives alerts
* @author thilina27
* @param url the url to investigate
* @param listener the listener to display log during the job execution in jenkins
* @param zapClientAPI the client API to use ZAP API methods
* @param contextId the id number of the contexte created for this scan
* @param userId the id number of the user created for this scan
* @throws ClientApiException
* @throws InterruptedException
*/
private void spiderURLAsUser(final String url, BuildListener listener, ClientApi zapClientAPI,
String contextId, String userId)
throws ClientApiException, InterruptedException {
// Start spider as user
zapClientAPI.spider.scanAsUser(API_KEY, url, contextId, userId, "0", "");
// Wait for complete spidering (equal to 100)
// Method signature : status(String scanId)
while (statusToInt(zapClientAPI.spider.status("")) < 100) {
listener.getLogger().println("Status spider = " + statusToInt(zapClientAPI.spider.status("")) + "%");
listener.getLogger().println("Alerts number = " + zapClientAPI.core.numberOfAlerts("").toString(2));
Thread.sleep(1000);
}
}
@Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
FilePath ws = build.getWorkspace();
OutputStream os = ws.child(name + ".xml").write();
try {
PrintWriter pw = new PrintWriter(os);
pw.println("<testsuite failures=\"" + fail + "\" errors=\"0\" skipped=\"0\" tests=\"" + (pass + fail) + "\" name=\"" + name + "\">");
for (int i = 0; i < pass; i++) {
pw.println("<testcase classname=\"" + name + "\" name=\"passing" + i + "\"/>");
}
for (int i = 0; i < fail; i++) {
pw.println("<testcase classname=\"" + name + "\" name=\"failing" + i + "\"><error message=\"failure\"/></testcase>");
}
pw.println("</testsuite>");
pw.flush();
} finally {
os.close();
}
new JUnitResultArchiver(name + ".xml").perform(build, ws, launcher, listener);
return true;
}
@Override
public boolean perform(final AbstractBuild<?, ?> build, final Launcher launcher, final BuildListener listener)
throws InterruptedException, IOException {
FilePath workspace = build.getWorkspace();
if (workspace == null) {
throw new IOException("No workspace found for " + build);
}
perform(build, workspace, listener, new RunResultHandler(build));
return true;
}
@Override
public MatrixAggregator createAggregator(final MatrixBuild build, final Launcher launcher, final BuildListener listener) {
IssuesRecorder recorder = build.getParent().getPublishersList().get(IssuesRecorder.class);
if (recorder == null) {
return null;
}
return new IssuesAggregator(build, launcher, listener, recorder);
}
@Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
throws InterruptedException, IOException {
if (OS.indexOf("win") >= 0) {
return new BatchFile(marathonHome + "marathon.bat " + getCommand()).perform(build, launcher, listener);
} else if (OS.indexOf("mac") >= 0 || OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0 || OS.indexOf("aix") > 0) {
return new Shell(marathonHome + "marathon " + getCommand()).perform(build, launcher, listener);
} else {
listener.getLogger().println("Your system is not supported");
return false;
}
}
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) {
Result result = build.getResult();
if (Result.SUCCESS != result) {
listener.getLogger().println("Previous steps failed the build.\nResult is: " + result);
return false;
}
boolean buildHasPassed = false;
try {
JobConfigData checkedJobConfigData = jobConfigurationService.checkProjectKeyIfVariable(jobConfigData, build, listener);
buildHasPassed = buildDecision.getStatus(globalConfigDataForSonarInstance, checkedJobConfigData, listener);
if ("".equals(jobConfigData.getSonarInstanceName())) {
listener.getLogger().println(JobExecutionService.DEFAULT_CONFIGURATION_WARNING);
}
listener.getLogger().println("PostBuild-Step: Quality Gates plugin build passed: " + String.valueOf(buildHasPassed).toUpperCase());
if (!buildHasPassed && BuildStatusEnum.UNSTABLE.equals(checkedJobConfigData.getBuildStatus())) {
build.setResult(Result.UNSTABLE);
return true;
}
} catch (QGException e) {
e.printStackTrace(listener.getLogger());
}
return buildHasPassed;
}
public boolean getStatus(GlobalConfigDataForSonarInstance globalConfigDataForSonarInstance, JobConfigData jobConfigData, BuildListener listener) throws QGException {
try {
return qualityGatesProvider.getAPIResultsForQualityGates(jobConfigData, globalConfigDataForSonarInstance, listener).hasStatusGreen();
} catch (JSONException | InterruptedException e) {
throw new QGException("Please check your credentials or your Project Key", e);
}
}
@Test
public void testPerformShouldCatchQGException() throws Exception {
setGlobalConfigDataAndJobConfigDataNames(TEST_NAME, TEST_NAME);
jobConfigData.setProjectKey("projectKey");
QGException exception = new QGException("TestException");
doReturn(globalConfigDataForSonarInstance).when(buildDecision).chooseSonarInstance(globalConfig, jobConfigData);
doThrow(exception).when(buildDecision).getStatus(any(GlobalConfigDataForSonarInstance.class), any(JobConfigData.class), any(BuildListener.class));
jenkinsRule.assertBuildStatus(Result.FAILURE, buildProject(freeStyleProject));
Run lastRun = freeStyleProject._getRuns().newestValue();
jenkinsRule.assertLogContains("QGException", lastRun);
}
public Result runSubBuilds(final Iterable<Combination> subBuildCombinations, final BuildListener listener) throws InterruptedException, IOException {
final Iterable<DynamicSubProject> subProjects = getRunSubProjects(subBuildCombinations);
scheduleSubBuilds(subBuildCombinations, this.subBuildFinishListener, listener);
Result r = Result.SUCCESS;
for (final DynamicSubProject c : subProjects) {
final CurrentBuildState runState = waitForCompletion(c, listener);
final Result runResult = getResult(runState);
r = r.combine(runResult);
listener.getLogger().println("Run " + c.getName() + " finished with : " + runResult);
// subBuildFinishListener.runFinished(c.getBuildByNumber(dynamicBuild.getNumber()) );
}
return r;
}
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
FilePath f = new FilePath(build.getWorkspace(), path);
f.mkdirs();
for (int i = 0; i < numberOfFiles; i++) {
new FilePath(f, i + ".txt").touch(System.currentTimeMillis());
}
return true;
}
@Test
public void testArtifactsRunApi() throws Exception {
FreeStyleProject p = j.createFreeStyleProject("pipeline1");
p.getBuildersList().add(new TestBuilder() {
@Override public boolean perform(AbstractBuild<?,?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
FilePath ws = build.getWorkspace();
if (ws == null) {
return false;
}
FilePath dir = ws.child("dir");
dir.mkdirs();
dir.child("fizz").write("contents", null);
dir.child("lodge").symlinkTo("fizz", listener);
return true;
}
});
ArtifactArchiver aa = new ArtifactArchiver("dir/fizz");
aa.setAllowEmptyArchive(true);
p.getPublishersList().add(aa);
FreeStyleBuild b = j.assertBuildStatusSuccess(p.scheduleBuild2(0));
List artifacts = get("/organizations/jenkins/pipelines/pipeline1/runs/"+b.getId()+"/artifacts", List.class);
assertEquals(1, artifacts.size());
assertEquals("fizz", ((Map) artifacts.get(0)).get("name"));
String artifactId = (String) ((Map) artifacts.get(0)).get("id");
ArtifactContainerImpl container = new ArtifactContainerImpl(b, new Reachable() {
@Override
public Link getLink() {
return new Link("/blue/rest/organizations/jenkins/pipelines/pipeline1/runs/1/artifacts/");
}
});
BlueArtifact blueArtifact = container.get(artifactId);
assertNotNull(blueArtifact);
}
@Test
public void interoperability() throws Exception {
final Semaphore semaphore = new Semaphore(1);
LockableResourcesManager.get().createResource("resource1");
WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p");
p.setDefinition(
new CpsFlowDefinition(
"lock('resource1') {\n" + " echo 'Locked'\n" + "}\n" + "echo 'Finish'", true));
FreeStyleProject f = j.createFreeStyleProject("f");
f.addProperty(new RequiredResourcesProperty("resource1", null, null, null, null));
f.getBuildersList()
.add(
new TestBuilder() {
@Override
public boolean perform(
AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
throws InterruptedException, IOException {
semaphore.acquire();
return true;
}
});
semaphore.acquire();
FreeStyleBuild f1 = f.scheduleBuild2(0).waitForStart();
WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
j.waitForMessage("[resource1] is locked by " + f1.getFullDisplayName() + ", waiting...", b1);
isPaused(b1, 1, 1);
semaphore.release();
// Wait for lock after the freestyle finishes
j.waitForMessage("Lock released on resource [resource1]", b1);
isPaused(b1, 1, 0);
}
public static BuildListener mockListener() {
BuildListener listener = mock(BuildListener.class);
PrintStream stream = mock(PrintStream.class);
when(listener.getLogger()).thenReturn(stream);
return listener;
}
@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());
}
});
}
/**
* set up form based authentication method for the created context
* @param listener the listener to display log during the job execution in jenkins
* @param zapClientAPI the client API to use ZAP API methods
* @param loggedInIdicator indication for know its logged in
* @param usernameParameter parameter define in passing username
* @param passwordParameter parameter that define in passing password for the user
* @param extraPostData other post data than credentials
* @param contextId id of the creted context
* @param loginUrl login page url
* @throws ClientApiException
* @throws UnsupportedEncodingException
*/
private void setUpFormBasedAuthenticationMethod(BuildListener listener, ClientApi zapClientAPI,
String loggedInIndicator, String usernameParameter, String passwordParameter,String extraPostData,
String contextId, String loginUrl)
throws ClientApiException, UnsupportedEncodingException{
String loginRequestData = usernameParameter+"={%username%}&"+passwordParameter+"={%password%}&"+extraPostData;
// set form based authentication method
// Prepare the configuration in a format similar to how URL parameters are formed. This
// means that any value we add for the configuration values has to be URL encoded.
StringBuilder formBasedConfig = new StringBuilder();
formBasedConfig.append("loginUrl=").append(URLEncoder.encode(loginUrl, "UTF-8"));
formBasedConfig.append("&loginRequestData=").append(URLEncoder.encode(loginRequestData, "UTF-8"));
zapClientAPI.authentication.setAuthenticationMethod(API_KEY, contextId, "formBasedAuthentication",formBasedConfig.toString());
listener.getLogger().println("Authentication config: " + zapClientAPI.authentication.getAuthenticationMethod(contextId).toString(0));
//end set auth method
listener.getLogger().println("Form Based Authentication added to context");
//add logged in idicator
if (!loggedInIndicator.equals("")) {
zapClientAPI.authentication.setLoggedInIndicator(API_KEY, contextId, loggedInIndicator);
listener.getLogger().println("Logged in indicator "+loggedInIndicator+" added to context ");
}
}
public void printAllEnv(AbstractBuild build,BuildListener listener) throws IOException,InterruptedException{
System.out.println("-----------Printing Env----------");
final EnvVars env = build.getEnvironment(listener);
for(String key : env.keySet()) {
System.out.println(key + ":" + env.get(key));
}
System.out.println("---------------------------------");
}
@Override
public boolean notify(DynamicBuild build, BuildListener listener) {
debug(listener.getLogger(), "Sending email notifications");
if (needsEmail(build, listener)) {
sendMail(listener, build);
}
return true;
}
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
throws InterruptedException, IOException
{
listener.getLogger().println("Updating JIRA tickets");
List<JiraCommit> commits = issueStrategy.getJiraCommits(build, listener);
for (JiraOperationExtension extension : extensions)
{
listener.getLogger().println("Operation: " + extension.getDescriptor().getDisplayName());
extension.perform(commits, build, launcher, listener);
}
listener.getLogger().println("Finish updating JIRA tickets");
return true;
}
private Builder echoBuilder(final String fileName, final String content) {
return new TestBuilder() {
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws
InterruptedException, IOException {
build.getWorkspace().child(fileName).write(content, "UTF-8");
return true;
}
};
}
@Test
public void testErrorInExpansion()
throws Exception
{
AbstractBuild mockBuild = mock(AbstractBuild.class);
SingleTicketStrategy strategy = new SingleTicketStrategy("$FOO");
when(mockBuild.getEnvironment(any(BuildListener.class))).thenThrow(new IOException());
List<JiraCommit> commits = strategy.getJiraCommits(mockBuild,
new StreamBuildListener(System.out, Charset.defaultCharset()));
assertEquals(1, commits.size());
assertEquals("$FOO", commits.get(0).getJiraTicket());
}