hudson.model.ParametersAction Java Examples
The following examples show how to use
hudson.model.ParametersAction.
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: SaveableChangeListenerTest.java From audit-log-plugin with MIT License | 6 votes |
@Issue("ISSUE-35") @Test public void testOnCredentialsUsage() throws Exception { UsernamePasswordCredentialsImpl credentials = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "secret-id", "test credentials", "bob","secret"); CredentialsProvider.lookupStores(j.jenkins).iterator().next().addCredentials(Domain.global(), credentials); JenkinsRule.WebClient wc = j.createWebClient(); FreeStyleProject job = j.createFreeStyleProject(); job.addProperty(new ParametersDefinitionProperty( new CredentialsParameterDefinition( "SECRET", "The secret", "secret-id", Credentials.class.getName(), false ))); job.getBuildersList().add(new CaptureEnvironmentBuilder()); job.scheduleBuild2(0, new ParametersAction(new CredentialsParameterValue("SECRET", "secret-id", "The secret", true))).get(); List<LogEvent> events = app.getEvents(); assertThat(events).hasSize(4); assertThat(events).extracting(event -> ((AuditMessage) event.getMessage()).getId().toString()).containsSequence("createItem", "buildStart", "useCredentials", "buildFinish"); }
Example #2
Source File: GithubWebhookTest.java From DotCi with MIT License | 6 votes |
@Test public void should_trigger_build_with_default_parameter_values() throws IOException, InterruptedException { final StaplerRequest request = mock(StaplerRequest.class); when(request.getParameter("payload")).thenReturn("payload"); final DynamicProject project = mock(DynamicProject.class); final ParameterDefinition branchParameter = mock(ParameterDefinition.class); when(branchParameter.getName()).thenReturn("BRANCH"); final ParameterDefinition secondParameter = mock(ParameterDefinition.class); when(branchParameter.getName()).thenReturn("PARAM"); when(secondParameter.getDefaultParameterValue()).thenReturn(new StringParameterValue("PARAM", "meow")); final ParametersDefinitionProperty paramDefinition = mock(ParametersDefinitionProperty.class); when(paramDefinition.getParameterDefinitions()).thenReturn(Arrays.asList(branchParameter, secondParameter)); when(project.getProperty(ParametersDefinitionProperty.class)).thenReturn(paramDefinition); kickOffBuildTrigger(request, project); final ArgumentCaptor<ParametersAction> parametersCaptor = ArgumentCaptor.forClass(ParametersAction.class); verify(project).scheduleBuild(eq(0), any(GithubPushPullWebhookCause.class), parametersCaptor.capture()); final ParametersAction parametersAction = parametersCaptor.getValue(); Assert.assertTrue(parametersAction.getParameter("PARAM") instanceof StringParameterValue); Assert.assertEquals("meow", ((StringParameterValue) parametersAction.getParameter("PARAM")).value); }
Example #3
Source File: PipelineApiTest.java From blueocean-plugin with MIT License | 6 votes |
@Test public void testPipelineQueue() throws Exception { FreeStyleProject p1 = j.createFreeStyleProject("pipeline1"); p1.setConcurrentBuild(true); p1.addProperty(new ParametersDefinitionProperty(new StringParameterDefinition("test","test"))); p1.getBuildersList().add(new Shell("echo hello!\nsleep 300")); p1.scheduleBuild2(0).waitForStart(); p1.scheduleBuild2(0).waitForStart(); Jenkins.getInstance().getQueue().schedule(p1, 0, new ParametersAction(new StringParameterValue("test","test1")), new CauseAction(new Cause.UserIdCause())); Jenkins.getInstance().getQueue().schedule(p1, 0, new ParametersAction(new StringParameterValue("test","test2")), new CauseAction(new Cause.UserIdCause())); List queue = request().get("/organizations/jenkins/pipelines/pipeline1/queue").build(List.class); Assert.assertEquals(2, queue.size()); Assert.assertEquals(4, ((Map) queue.get(0)).get("expectedBuildNumber")); Assert.assertEquals(3, ((Map) queue.get(1)).get("expectedBuildNumber")); Assert.assertEquals("Waiting for next available executor", ((Map) queue.get(0)).get("causeOfBlockage")); Assert.assertEquals("Waiting for next available executor", ((Map) queue.get(1)).get("causeOfBlockage")); Run r = QueueUtil.getRun(p1, Long.parseLong((String)((Map)queue.get(0)).get("id"))); assertNull(r); //its not moved out of queue yet }
Example #4
Source File: EnvironmentTagBuilder.java From jenkins-deployment-dashboard-plugin with MIT License | 6 votes |
private DeployJobVariables extractDeployJobVariables(AbstractBuild build) { String environment = DeployJobVariablesBuilder.UNDEFINED; String version = DeployJobVariablesBuilder.UNDEFINED; List<ParametersAction> actionList = Util.filter(build.getAllActions(), ParametersAction.class); for (ParametersAction parametersAction : actionList) { List<ParameterValue> params = parametersAction.getParameters(); for (ParameterValue parameterValue : params) { if (DashboardView.PARAM_ENVIRONMENT.equalsIgnoreCase((String) parameterValue.getName())) { environment = (String) parameterValue.getValue(); } if (DashboardView.PARAM_VERSION.equalsIgnoreCase((String) parameterValue.getName())) { version = (String) parameterValue.getValue(); } } } return DeployJobVariablesBuilder.createBuilder().version(version).environment(environment).build(); }
Example #5
Source File: NoteBuildActionTest.java From gitlab-plugin with GNU General Public License v2.0 | 5 votes |
@Test public void build_alreadyBuiltMR_alreadyBuiltMR() throws IOException, ExecutionException, InterruptedException { FreeStyleProject testProject = jenkins.createFreeStyleProject(); testProject.addTrigger(trigger); testProject.setScm(new GitSCM(gitRepoUrl)); QueueTaskFuture<?> future = testProject.scheduleBuild2(0, new ParametersAction(new StringParameterValue("gitlabTargetBranch", "master"))); future.get(); exception.expect(HttpResponses.HttpResponseException.class); new NoteBuildAction(testProject, getJson("NoteEvent_alreadyBuiltMR.json"), null).execute(response); verify(trigger).onPost(any(NoteHook.class)); }
Example #6
Source File: GithubWebhookTest.java From DotCi with MIT License | 5 votes |
@Test public void should_trigger_builds_for_payload() throws IOException, InterruptedException { final StaplerRequest request = mock(StaplerRequest.class); when(request.getParameter("payload")).thenReturn("payload"); final DynamicProject project = mock(DynamicProject.class); final ParametersDefinitionProperty paramDefinition = mock(ParametersDefinitionProperty.class); when(project.getProperty(ParametersDefinitionProperty.class)).thenReturn(paramDefinition); kickOffBuildTrigger(request, project); verify(project).scheduleBuild(eq(0), any(GithubPushPullWebhookCause.class), any(ParametersAction.class)); }
Example #7
Source File: GithubWebhookTest.java From DotCi with MIT License | 5 votes |
@Test public void should_get_payload_from_post_if_post() throws IOException, InterruptedException { final StaplerRequest request = mock(StaplerRequest.class); when(request.getParameter("payload")).thenReturn("{repository: { url: 'git@repo' },deleted: false}"); when(request.getHeader("X-GitHub-Event")).thenReturn(GHEvent.PUSH.toString()); when(request.getMethod()).thenReturn("POST"); final DynamicProject project = mock(DynamicProject.class); final ParametersDefinitionProperty paramDefinition = mock(ParametersDefinitionProperty.class); when(project.getProperty(ParametersDefinitionProperty.class)).thenReturn(paramDefinition); kickOffBuildTrigger(request, project); verify(project).scheduleBuild(eq(0), any(GithubPushPullWebhookCause.class), any(ParametersAction.class)); }
Example #8
Source File: DownstreamJobPlugin.java From DotCi with MIT License | 5 votes |
private String getSourceBuildNumber(DynamicBuild dynamicBuild) { if (dynamicBuild.getCause() instanceof DotCiUpstreamTriggerCause) { List<ParameterValue> params = dynamicBuild.getAction(ParametersAction.class).getParameters(); for (ParameterValue param : params) { if (param.getName().equals("SOURCE_BUILD")) { return (String) param.getValue(); } } } return "" + dynamicBuild.getNumber(); }
Example #9
Source File: SubBuildScheduler.java From DotCi with MIT License | 5 votes |
protected void scheduleSubBuilds(final Iterable<Combination> subBuildCombinations, final SubBuildFinishListener subBuildFinishListener, final TaskListener listener) { for (final Combination subBuildCombination : subBuildCombinations) { final DynamicSubProject c = this.dynamicBuild.getSubProject(subBuildCombination); listener.getLogger().println(Messages.MatrixBuild_Triggering(ModelHyperlinkNote.encodeTo(c))); final List<Action> childActions = new ArrayList<>(); childActions.addAll(Util.filter(this.dynamicBuild.getActions(), ParametersAction.class)); childActions.add(new SubBuildExecutionAction(this.subBuildRunner, subBuildFinishListener)); childActions.add(new ParentBuildAction(this.dynamicBuild)); c.scheduleBuild(childActions, this.dynamicBuild.getCause()); } }
Example #10
Source File: BuildEnvironment.java From DotCi with MIT License | 5 votes |
public boolean initialize() throws IOException, InterruptedException { final List<BuildWrapper> wrappers = new ArrayList<>(getProject().getBuildWrappers().values()); final ParametersAction parameters = getAction(ParametersAction.class); if (parameters != null) { parameters.createBuildWrappers(this.build, wrappers); } return setupWrappers(wrappers); }
Example #11
Source File: ProcessedBuild.java From DotCi with MIT License | 5 votes |
@Override public List<ParameterValue> getParameters() { if (this.build.getAction(ParametersAction.class) != null) { return this.build.getAction(ParametersAction.class).getParameters(); } return Lists.newArrayList(); }
Example #12
Source File: BuildBeginInfo.java From qy-wechat-notification-plugin with Apache License 2.0 | 5 votes |
public BuildBeginInfo(String projectName, AbstractBuild<?, ?> build, NotificationConfig config){ //获取请求参数 List<ParametersAction> parameterList = build.getActions(ParametersAction.class); if(parameterList!=null && parameterList.size()>0){ for(ParametersAction p : parameterList){ for(ParameterValue pv : p.getParameters()){ this.params.put(pv.getName(), pv.getValue()); } } } //预计时间 if(build.getProject().getEstimatedDuration()>0){ this.durationTime = build.getProject().getEstimatedDuration(); } //控制台地址 StringBuilder urlBuilder = new StringBuilder(); String jenkinsUrl = NotificationUtil.getJenkinsUrl(); if(StringUtils.isNotEmpty(jenkinsUrl)){ String buildUrl = build.getUrl(); urlBuilder.append(jenkinsUrl); if(!jenkinsUrl.endsWith("/")){ urlBuilder.append("/"); } urlBuilder.append(buildUrl); if(!buildUrl.endsWith("/")){ urlBuilder.append("/"); } urlBuilder.append("console"); } this.consoleUrl = urlBuilder.toString(); //工程名称 this.projectName = projectName; //环境名称 if(config.topicName!=null){ topicName = config.topicName; } }
Example #13
Source File: JobRunnerForCauseTest.java From github-integration-plugin with MIT License | 5 votes |
public static QueueTaskFuture schedule(Job<?, ?> job, int number, String param, int queuetPeriod) { ParameterizedJobMixIn jobMixIn = JobInfoHelpers.asParameterizedJobMixIn(job); GitHubPRCause cause = newGitHubPRCause().withNumber(number); ParametersAction parametersAction = new ParametersAction( Collections.<ParameterValue>singletonList(new StringParameterValue("value", param)) ); return jobMixIn.scheduleBuild2(queuetPeriod, new CauseAction(cause), parametersAction); }
Example #14
Source File: JobHelper.java From github-integration-plugin with MIT License | 5 votes |
public static boolean rebuild(Run<?, ?> run) { final QueueTaskFuture queueTaskFuture = asParameterizedJobMixIn(run.getParent()) .scheduleBuild2( 0, run.getAction(ParametersAction.class), run.getAction(CauseAction.class), run.getAction(BuildBadgeAction.class) ); return queueTaskFuture != null; }
Example #15
Source File: PhabricatorBuildWrapperTest.java From phabricator-jenkins-plugin with MIT License | 5 votes |
@Test public void getAbortOnRevisionIdIfAvailable() throws Exception { FreeStyleBuild build = buildWithConduit(getFetchDiffResponse(), null, null, true); assertNull(PhabricatorBuildWrapper.getAbortOnRevisionId(build)); List<ParameterValue> parameters = Lists.newArrayList(); parameters.add(new ParameterValue("ABORT_ON_REVISION_ID") { @Override public Object getValue() { return "test"; } }); build.addAction(new ParametersAction(parameters)); assertEquals("test", PhabricatorBuildWrapper.getAbortOnRevisionId(build)); }
Example #16
Source File: PhabricatorBuildWrapper.java From phabricator-jenkins-plugin with MIT License | 5 votes |
@VisibleForTesting static String getAbortOnRevisionId(AbstractBuild build) { ParametersAction parameters = build.getAction(ParametersAction.class); if (parameters != null) { ParameterValue parameterValue = parameters.getParameter( PhabricatorPlugin.ABORT_ON_REVISION_ID_FIELD); if (parameterValue != null) { return (String) parameterValue.getValue(); } } return null; }
Example #17
Source File: RunContainerImpl.java From blueocean-plugin with MIT License | 5 votes |
/** * Schedules a build. If build already exists in the queue and the pipeline does not * support running multiple builds at the same time, return a reference to the existing * build. * * @return Queue item. */ @Override public BlueRun create(StaplerRequest request) { job.checkPermission(Item.BUILD); if (job instanceof Queue.Task) { ScheduleResult scheduleResult; List<ParameterValue> parameterValues = getParameterValue(request); int expectedBuildNumber = job.getNextBuildNumber(); if(parameterValues.size() > 0) { scheduleResult = Jenkins.getInstance() .getQueue() .schedule2((Queue.Task) job, 0, new ParametersAction(parameterValues), new CauseAction(new Cause.UserIdCause())); }else { scheduleResult = Jenkins.getInstance() .getQueue() .schedule2((Queue.Task) job, 0, new CauseAction(new Cause.UserIdCause())); } // Keep FB happy. // scheduleResult.getItem() will always return non-null if scheduleResult.isAccepted() is true final Queue.Item item = scheduleResult.getItem(); if(scheduleResult.isAccepted() && item != null) { return new QueueItemImpl( pipeline.getOrganization(), item, pipeline, expectedBuildNumber, pipeline.getLink().rel("queue").rel(Long.toString(item.getId())), pipeline.getLink() ).toRun(); } else { throw new ServiceException.UnexpectedErrorException("Queue item request was not accepted"); } } else { throw new ServiceException.NotImplementedException("This pipeline type does not support being queued."); } }
Example #18
Source File: DashboardView.java From jenkins-deployment-dashboard-plugin with MIT License | 4 votes |
@JavaScriptMethod public String deploy(String version, String environment) { LOGGER.info("Deploy version " + version + " to environment " + environment); // Get the environment with corresponding build-job Environment buildEnvironment = null; for (Environment env : environments) { if (env.getAwsInstance().equals(environment)) { buildEnvironment = env; break; } } final AbstractProject buildJob = Jenkins.getInstance().getItemByFullName(buildEnvironment.getBuildJob(), AbstractProject.class); LOGGER.info("Executing job: " + buildJob); if (buildJob == null) { return String.format(Messages.DashboardView_buildJobNotFound(), buildEnvironment.getName()); } if ((!buildJob.isBuildable()) || (!buildJob.isParameterized())) { return Messages.DashboardView_deploymentCannotBeExecuted(); } final ParametersAction versionParam = new ParametersAction(new StringParameterValue(PARAM_VERSION, version)); final ParametersAction environmentParam = new ParametersAction(new StringParameterValue(PARAM_ENVIRONMENT, environment)); final ParametersAction ec2RegionParam = new ParametersAction(new StringParameterValue(PARAM_EC2_REGION, environment)); final ParametersAction awsKeyParam = new ParametersAction(new StringParameterValue(PARAM_AWS_KEY, environment)); List<ParametersAction> actions = Arrays.asList(versionParam, environmentParam, ec2RegionParam, awsKeyParam); QueueTaskFuture<AbstractBuild> scheduledBuild = buildJob.scheduleBuild2(2, new Cause.UserIdCause(), actions); Result result = Result.FAILURE; try { AbstractBuild finishedBuild = scheduledBuild.get(); result = finishedBuild.getResult(); LOGGER.info("Build finished with result: " + result + " completed in: " + finishedBuild.getDurationString() + ". "); } catch (Exception e) { LOGGER.severe("Error while waiting for build " + scheduledBuild.toString() + "."); LOGGER.severe(e.getMessage()); LOGGER.severe(ExceptionUtils.getFullStackTrace(e)); return String.format(Messages.DashboardView_buildJobFailed(), buildJob.getName()); } if (result == Result.SUCCESS) { return String.format(Messages.DashboardView_buildJobScheduledSuccessfully(), buildJob.getName()); } return String.format(Messages.DashboardView_buildJobSchedulingFailed(), buildJob.getName()); }
Example #19
Source File: BuildEnvironment.java From DotCi with MIT License | 4 votes |
private ParametersAction getAction(final Class<ParametersAction> clazz) { return this.build.getAction(clazz); }
Example #20
Source File: AutoResubmitIntegrationTest.java From ec2-spot-jenkins-plugin with Apache License 2.0 | 4 votes |
@Test public void should_successfully_resubmit_parametrized_task() throws Exception { EC2FleetCloud cloud = new EC2FleetCloud(null, null, "credId", null, "region", null, "fId", "momo", null, new LocalComputerConnector(j), false, false, 0, 0, 10, 1, false, false, false, 0, 0, false, 10, false); j.jenkins.clouds.add(cloud); List<QueueTaskFuture> rs = new ArrayList<>(); final FreeStyleProject project = j.createFreeStyleProject(); project.setAssignedLabel(new LabelAtom("momo")); project.addProperty(new ParametersDefinitionProperty(new StringParameterDefinition("number", "opa"))); /* example of actions for project actions = {CopyOnWriteArrayList@14845} size = 2 0 = {ParametersAction@14853} safeParameters = {TreeSet@14855} size = 0 parameters = {ArrayList@14856} size = 1 0 = {StringParameterValue@14862} "(StringParameterValue) number='1'" value = "1" name = "number" description = "" parameterDefinitionNames = {ArrayList@14857} size = 1 0 = "number" build = null run = {FreeStyleBuild@14834} "parameter #14" */ project.getBuildersList().add(Functions.isWindows() ? new BatchFile("Ping -n %number% 127.0.0.1 > nul") : new Shell("sleep ${number}")); rs.add(project.scheduleBuild2(0, new ParametersAction(new StringParameterValue("number", "30")))); System.out.println("check if zero nodes!"); Assert.assertEquals(0, j.jenkins.getNodes().size()); assertAtLeastOneNode(); final Node node = j.jenkins.getNodes().get(0); assertQueueIsEmpty(); System.out.println("disconnect node"); node.toComputer().disconnect(new OfflineCause.ChannelTermination(new UnsupportedOperationException("Test"))); assertLastBuildResult(Result.FAILURE, Result.ABORTED); node.toComputer().connect(true); assertNodeIsOnline(node); assertQueueAndNodesIdle(node); Assert.assertEquals(1, j.jenkins.getProjects().size()); Assert.assertEquals(Result.SUCCESS, j.jenkins.getProjects().get(0).getLastBuild().getResult()); Assert.assertEquals(2, j.jenkins.getProjects().get(0).getBuilds().size()); cancelTasks(rs); }
Example #21
Source File: UsernamePasswordBindingTest.java From credentials-binding-plugin with MIT License | 4 votes |
@Test public void theSecretBuildWrapperTracksUsage() throws Exception { SystemCredentialsProvider.getInstance().setDomainCredentialsMap( Collections.singletonMap(Domain.global(), Collections.<Credentials>emptyList())); for (CredentialsStore s : CredentialsProvider.lookupStores(Jenkins.getInstance())) { if (s.getProvider() instanceof SystemCredentialsProvider.ProviderImpl) { store = s; break; } } assertThat("The system credentials provider is enabled", store, notNullValue()); UsernamePasswordCredentialsImpl credentials = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "secret-id", "test credentials", "bob", "secret"); store.addCredentials(Domain.global(), credentials); Fingerprint fingerprint = CredentialsProvider.getFingerprintOf(credentials); assertThat("No fingerprint created until first use", fingerprint, nullValue()); JenkinsRule.WebClient wc = r.createWebClient(); HtmlPage page = wc.goTo("credentials/store/system/domain/_/credentials/secret-id"); assertThat("Have usage tracking reported", page.getElementById("usage"), notNullValue()); assertThat("No fingerprint created until first use", page.getElementById("usage-missing"), notNullValue()); assertThat("No fingerprint created until first use", page.getElementById("usage-present"), nullValue()); FreeStyleProject job = r.createFreeStyleProject(); // add a parameter job.addProperty(new ParametersDefinitionProperty( new CredentialsParameterDefinition( "SECRET", "The secret", "secret-id", Credentials.class.getName(), false ))); r.assertBuildStatusSuccess((Future) job.scheduleBuild2(0, new ParametersAction(new CredentialsParameterValue("SECRET", "secret-id", "The secret", true)))); fingerprint = CredentialsProvider.getFingerprintOf(credentials); assertThat("A job that does nothing does not use parameterized credentials", fingerprint, nullValue()); page = wc.goTo("credentials/store/system/domain/_/credentials/secret-id"); assertThat("Have usage tracking reported", page.getElementById("usage"), notNullValue()); assertThat("No fingerprint created until first use", page.getElementById("usage-missing"), notNullValue()); assertThat("No fingerprint created until first use", page.getElementById("usage-present"), nullValue()); // check that the wrapper works as expected job.getBuildWrappersList().add(new SecretBuildWrapper(Collections.<Binding<?>>singletonList(new UsernamePasswordBinding("AUTH", credentials.getId())))); r.assertBuildStatusSuccess((Future) job.scheduleBuild2(0, new ParametersAction(new CredentialsParameterValue("SECRET", "secret-id", "The secret", true)))); fingerprint = CredentialsProvider.getFingerprintOf(credentials); assertThat(fingerprint, notNullValue()); assertThat(fingerprint.getJobs(), hasItem(is(job.getFullName()))); Fingerprint.RangeSet rangeSet = fingerprint.getRangeSet(job); assertThat(rangeSet, notNullValue()); assertThat(rangeSet.includes(job.getLastBuild().getNumber()), is(true)); page = wc.goTo("credentials/store/system/domain/_/credentials/secret-id"); assertThat(page.getElementById("usage-missing"), nullValue()); assertThat(page.getElementById("usage-present"), notNullValue()); assertThat(page.getAnchorByText(job.getFullDisplayName()), notNullValue()); // check the API WebResponse response = wc.goTo( "credentials/store/system/domain/_/credentials/secret-id/api/xml?depth=1&xpath=*/fingerprint/usage", "application/xml").getWebResponse(); assertThat(response.getContentAsString(), CompareMatcher.isSimilarTo("<usage>" + "<name>"+ Util.xmlEscape(job.getFullName())+"</name>" + "<ranges>" + "<range>" + "<end>"+(job.getLastBuild().getNumber()+1)+"</end>" + "<start>" + job.getLastBuild().getNumber()+"</start>" + "</range>" + "</ranges>" + "</usage>").ignoreWhitespace().ignoreComments()); }
Example #22
Source File: DynamicSubProject.java From DotCi with MIT License | 2 votes |
public boolean scheduleBuild(final ParametersAction parameters, final Cause c) { return scheduleBuild(Collections.singletonList(parameters), c); }