Java Code Examples for hudson.model.ParametersDefinitionProperty

The following examples show how to use hudson.model.ParametersDefinitionProperty. 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: audit-log-plugin   Source File: SaveableChangeListenerTest.java    License: MIT License 6 votes vote down vote up
@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 Project: blueocean-plugin   Source File: PipelineApiTest.java    License: MIT License 6 votes vote down vote up
@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 3
Source Project: blueocean-plugin   Source File: PipelineApiTest.java    License: MIT License 6 votes vote down vote up
@Test
public void parameterizedFreestyleTest() throws Exception {
    FreeStyleProject p = j.createFreeStyleProject("pp");
    p.addProperty(new ParametersDefinitionProperty(new StringParameterDefinition("version", "1.0", "version number")));
    p.getBuildersList().add(new Shell("echo hello!"));

    Map resp = get("/organizations/jenkins/pipelines/pp/");

    List<Map<String,Object>> parameters = (List<Map<String, Object>>) resp.get("parameters");
    assertEquals(1, parameters.size());
    assertEquals("version", parameters.get(0).get("name"));
    assertEquals("StringParameterDefinition", parameters.get(0).get("type"));
    assertEquals("version number", parameters.get(0).get("description"));
    assertEquals("1.0", ((Map)parameters.get(0).get("defaultParameterValue")).get("value"));
    validatePipeline(p, resp);

    resp = post("/organizations/jenkins/pipelines/pp/runs/",
            ImmutableMap.of("parameters",
                    ImmutableList.of(ImmutableMap.of("name", "version", "value", "2.0"))
            ), 200);
    assertEquals("pp", resp.get("pipeline"));
    Thread.sleep(1000);
    resp = get("/organizations/jenkins/pipelines/pp/runs/1/");
    assertEquals("SUCCESS", resp.get("result"));
    assertEquals("FINISHED", resp.get("state"));
}
 
Example 4
Source Project: blueocean-plugin   Source File: PipelineApiTest.java    License: MIT License 6 votes vote down vote up
@Test
public void parameterizedFreestyleTestWithoutDefaultParam() throws Exception {
    FreeStyleProject p = j.createFreeStyleProject("pp");
    p.addProperty(new ParametersDefinitionProperty(new TestStringParameterDefinition("version", null, "version number")));
    p.getBuildersList().add(new Shell("echo hello!"));

    Map resp = get("/organizations/jenkins/pipelines/pp/");

    List<Map<String,Object>> parameters = (List<Map<String, Object>>) resp.get("parameters");
    assertEquals(1, parameters.size());
    assertEquals("version", parameters.get(0).get("name"));
    assertEquals("TestStringParameterDefinition", parameters.get(0).get("type"));
    assertEquals("version number", parameters.get(0).get("description"));
    assertNull(parameters.get(0).get("defaultParameterValue"));
    validatePipeline(p, resp);

    resp = post("/organizations/jenkins/pipelines/pp/runs/",
            ImmutableMap.of("parameters",
                    ImmutableList.of()
            ), 400);
}
 
Example 5
Source Project: github-integration-plugin   Source File: JobHelper.java    License: MIT License 6 votes vote down vote up
/**
 * @see jenkins.model.ParameterizedJobMixIn#getDefaultParametersValues()
 */
public static List<ParameterValue> getDefaultParametersValues(Job<?, ?> job) {
    ParametersDefinitionProperty paramDefProp = job.getProperty(ParametersDefinitionProperty.class);
    List<ParameterValue> defValues = new ArrayList<>();

    /*
     * This check is made ONLY if someone will call this method even if isParametrized() is false.
     */
    if (isNull(paramDefProp)) {
        return defValues;
    }

    /* Scan for all parameter with an associated default values */
    for (ParameterDefinition paramDefinition : paramDefProp.getParameterDefinitions()) {
        ParameterValue defaultValue = paramDefinition.getDefaultParameterValue();

        if (defaultValue != null) {
            defValues.add(defaultValue);
        }
    }

    return defValues;
}
 
Example 6
Source Project: DotCi   Source File: ParametersDefinitionPropertyCoverter.java    License: MIT License 6 votes vote down vote up
@Override
public Object decode(Class targetClass, Object fromDBObject, MappedField optionalExtraInfo) {
    if (fromDBObject == null) return null;

    List<DBObject> list = (List) fromDBObject;

    List<ParameterDefinition> parameterDefinitions = new ArrayList<ParameterDefinition>();

    // TODO parsing checks
    for (DBObject dbObject : list) {
        ParameterDefinition definition = (ParameterDefinition) getMapper()
            .fromDBObject(ParameterDefinition.class, dbObject, getMapper().createEntityCache());

        parameterDefinitions.add(definition);
    }

    return new ParametersDefinitionProperty(parameterDefinitions);
}
 
Example 7
Source Project: DotCi   Source File: GithubWebhook.java    License: MIT License 6 votes vote down vote up
private List<ParameterValue> getParametersValues(final Job job, final String branch) {
    final ParametersDefinitionProperty paramDefProp = (ParametersDefinitionProperty) job.getProperty(ParametersDefinitionProperty.class);
    final ArrayList<ParameterValue> defValues = new ArrayList<>();

    for (final ParameterDefinition paramDefinition : paramDefProp.getParameterDefinitions()) {
        if ("BRANCH".equals(paramDefinition.getName())) {
            final StringParameterValue branchParam = new StringParameterValue("BRANCH", branch);
            defValues.add(branchParam);
        } else {
            final ParameterValue defaultValue = paramDefinition.getDefaultParameterValue();
            if (defaultValue != null)
                defValues.add(defaultValue);
        }
    }

    return defValues;
}
 
Example 8
Source Project: DotCi   Source File: GithubWebhookTest.java    License: MIT License 6 votes vote down vote up
@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 9
Source Project: blueocean-plugin   Source File: AbstractPipelineImpl.java    License: MIT License 5 votes vote down vote up
public static List<Object> getParameterDefinitions(Job job){
    ParametersDefinitionProperty pp = (ParametersDefinitionProperty) job.getProperty(ParametersDefinitionProperty.class);
    List<Object> pds = new ArrayList<>();
    if(pp != null){
        for(ParameterDefinition pd : pp.getParameterDefinitions()){
            pds.add(pd);
        }
    }
    return pds;
}
 
Example 10
Source Project: DotCi   Source File: ParametersDefinitionPropertyCoverter.java    License: MIT License 5 votes vote down vote up
@Override
public Object encode(Object value, MappedField optionalExtraInfo) {
    if (value == null) return null;

    ParametersDefinitionProperty parametersDefinitionProperty = (ParametersDefinitionProperty) value;

    BasicDBList parameters = new BasicDBList();
    for (ParameterDefinition definition : parametersDefinitionProperty.getParameterDefinitions()) {
        parameters.add(getMapper().toDBObject(definition));
    }

    return parameters;
}
 
Example 11
Source Project: DotCi   Source File: DynamicProjectRepository.java    License: MIT License 5 votes vote down vote up
public DynamicProject createNewProject(final GHRepository githubRepository, final String accessToken, final String user) {
    try {
        new GithubRepositoryService(githubRepository).linkProjectToCi(accessToken, user);

        final OrganizationContainer folder = this.organizationRepository.getOrCreateContainer(githubRepository.getOwner().getLogin());
        final String projectName = githubRepository.getName();
        final DynamicProject project = folder.createProject(DynamicProject.class, projectName);

        project.setDescription(format("<a href=\"%s\">%s</a>", githubRepository.getUrl(), githubRepository.getUrl()));
        project.setConcurrentBuild(true);
        if (StringUtils.isNotEmpty(SetupConfig.get().getLabel())) {
            project.setAssignedLabel(Jenkins.getInstance().getLabel(SetupConfig.get().getLabel()));
        }
        project.addProperty(new ParametersDefinitionProperty(new GithubBranchParameterDefinition("BRANCH", "master", githubRepository.getHtmlUrl().toString())));
        project.addProperty(new GithubRepoProperty(githubRepository.getHtmlUrl().toExternalForm()));
        project.addProperty(new BuildTypeProperty(SetupConfig.get().getDefaultBuildType()));
        project.addProperty(new DynamicProjectBranchTabsProperty("master"));
        project.addProperty(new RebuildSettings(true, false));
        project.addProperty(new JobUiProperty(SetupConfig.get().isDefaultToNewUi()));
        project.save();
        folder.addItem(project);
        folder.save();
        return project;
    } catch (final IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 12
Source Project: DotCi   Source File: GithubWebhookTest.java    License: MIT License 5 votes vote down vote up
@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: '[email protected]' },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 13
Source Project: DotCi   Source File: GithubWebhookTest.java    License: MIT License 5 votes vote down vote up
@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 14
@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 = {[email protected]}  size = 2
        0 = {[email protected]}
        safeParameters = {[email protected]}  size = 0
        parameters = {[email protected]}  size = 1
        0 = {[email protected]} "(StringParameterValue) number='1'"
        value = "1"
        name = "number"
        description = ""
        parameterDefinitionNames = {[email protected]}  size = 1
        0 = "number"
        build = null
        run = {[email protected]} "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 15
Source Project: jenkins-plugin   Source File: IOpenShiftPluginDescriptor.java    License: Apache License 2.0 4 votes vote down vote up
default EnvVars buildEnvVars() {
    EnvVars allOverrides = new EnvVars(EnvVars.masterEnvVars);
    // when running outside of an openshift pod, global env vars like
    // SKIP_TLS will not exist in master env vars
    if (Jenkins.getInstance().getGlobalNodeProperties() != null) {
        if (Jenkins.getInstance().getGlobalNodeProperties()
                .get(hudson.slaves.EnvironmentVariablesNodeProperty.class) != null) {
            if (Jenkins
                    .getInstance()
                    .getGlobalNodeProperties()
                    .get(hudson.slaves.EnvironmentVariablesNodeProperty.class)
                    .getEnvVars() != null) {
                allOverrides
                        .putAll(Jenkins
                                .getInstance()
                                .getGlobalNodeProperties()
                                .get(hudson.slaves.EnvironmentVariablesNodeProperty.class)
                                .getEnvVars());
            }
        }
    }
    String[] reqPieces = Stapler.getCurrentRequest().getRequestURI()
            .split("/");
    if (reqPieces != null && reqPieces.length > 2) {
        for (Job j : Jenkins.getInstance().getAllItems(Job.class)) {
            if (j.getName().equals(reqPieces[2])) {
                List<JobProperty> jps = j.getAllProperties();
                for (JobProperty jp : jps) {
                    if (jp instanceof ParametersDefinitionProperty) {
                        ParametersDefinitionProperty prop = (ParametersDefinitionProperty) jp;
                        for (ParameterDefinition param : prop
                                .getParameterDefinitions()) {
                            allOverrides.put(param.getName(), param
                                    .getDefaultParameterValue().getValue()
                                    .toString());
                        }
                    }
                }
            }
        }
    }
    return allOverrides;
}
 
Example 16
Source Project: DotCi   Source File: ParametersDefinitionPropertyCoverter.java    License: MIT License 4 votes vote down vote up
public ParametersDefinitionPropertyCoverter() {
    super(ParametersDefinitionProperty.class);
}
 
Example 17
@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());
}