Java 类hudson.model.ParametersDefinitionProperty 实例源码

项目:run-selector-plugin    文件:ParameterizedRunSelectorTest.java   
/**
 * Also applicable for workflow jobs.
 */
@Issue("JENKINS-30357")
@Test
public void testWorkflow() throws Exception {
    FreeStyleProject jobToSelect = j.createFreeStyleProject();
    Run runToSelect = j.assertBuildStatusSuccess(jobToSelect.scheduleBuild2(0));

    WorkflowJob selecter = createWorkflowJob();

    ParameterDefinition paramDef = new StringParameterDefinition(
            "SELECTOR", "<StatusRunSelector><buildStatus>STABLE</buildStatus></StatusRunSelector>"
    );
    selecter.addProperty(new ParametersDefinitionProperty(paramDef));

    selecter.setDefinition(new CpsFlowDefinition(String.format("" +
            "def runWrapper = selectRun job: '%s', " +
            " selector: [$class: 'ParameterizedRunSelector', parameterName: '${SELECTOR}'] \n" +
            "assert(runWrapper.id == '%s')", jobToSelect.getFullName(), runToSelect.getId())));

    j.assertBuildStatusSuccess(selecter.scheduleBuild2(0));
}
项目:run-selector-plugin    文件:ParameterizedRunFilterTest.java   
@Test
public void testConfigureBuildFilterParameter() throws Exception {
    RunFilterParameter param = new RunFilterParameter(
        "PARAM",
        "description",
        new AndRunFilter(
            new ParametersRunFilter("PARAM1=VALUE1"),
            new SavedRunFilter()
        )
    );
    WorkflowJob job = j.jenkins.createProject(
            WorkflowJob.class,
            RandomStringUtils.randomAlphanumeric(7)
    );
    job.addProperty(new ParametersDefinitionProperty(param));
    j.configRoundtrip((Item)job);
    j.assertEqualDataBoundBeans(
        param,
        job.getProperty(ParametersDefinitionProperty.class)
            .getParameterDefinition("PARAM")
    );
}
项目:run-selector-plugin    文件:ParameterizedRunFilterTest.java   
@Test
public void testIsSelectableWithDefault() throws Exception {
    WorkflowJob selecter = j.jenkins.createProject(
        WorkflowJob.class,
        RandomStringUtils.randomAlphanumeric(7)
    );
    selecter.addProperty(new ParametersDefinitionProperty(
        new RunFilterParameter(
            "FILTER",
            "description",
            new SavedRunFilter()
        )
    ));
    selecter.setDefinition(new CpsFlowDefinition(String.format(
        "def runWrapper = selectRun"
        + " job: '%s',"
        + " filter: [$class: 'ParameterizedRunFilter', parameter: '${FILTER}'],"
        + " verbose: true;"
        + "assert(runWrapper.id == '%s')",
        jobToSelect.getFullName(),
        runToSelect1.getId()
    )));

    j.assertBuildStatusSuccess(selecter.scheduleBuild2(0));
}
项目:run-selector-plugin    文件:ParameterizedRunFilterTest.java   
@Test
public void testIsSelectableEmptyParameter() throws Exception {
    WorkflowJob selecter = j.jenkins.createProject(
        WorkflowJob.class,
        RandomStringUtils.randomAlphanumeric(7)
    );
    selecter.addProperty(new ParametersDefinitionProperty(
        new StringParameterDefinition(
            "FILTER",
            "",
            "description"
        )
    ));
    selecter.setDefinition(new CpsFlowDefinition(String.format(
        "def runWrapper = selectRun"
        + " job: '%s',"
        + " filter: [$class: 'ParameterizedRunFilter', parameter: '${FILTER}'],"
        + " verbose: true;"
        + "assert(runWrapper.id == '%s')",
        jobToSelect.getFullName(),
        runToSelect2.getId()
    )));

    j.assertBuildStatusSuccess(selecter.scheduleBuild2(0));
}
项目:github-integration-plugin    文件:JobHelper.java   
/**
 * @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 (paramDefProp == null) {
        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;
}
项目:yaml-project-plugin    文件:YamlBuild.java   
/** Get the default parameter values for the given delegate */
private ParametersAction getDefaultParametersValues(
    AbstractProject delegate) {
  final ParametersDefinitionProperty property =
      (ParametersDefinitionProperty) delegate.getProperty(
          ParametersDefinitionProperty.class);
  if (property == null) {
    return null;
  }

  final List<ParameterValue> result = Lists.newArrayList();
  for (ParameterDefinition def : property.getParameterDefinitions()) {
    ParameterValue value = def.getDefaultParameterValue();
    if (value != null) {
      result.add(value);
    }
  }

  return new ParametersAction(result);
}
项目:DotCi    文件:ParametersDefinitionPropertyCoverter.java   
@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);
}
项目:DotCi    文件:GithubWebhook.java   
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;
}
项目:DotCi    文件:GithubWebhookTest.java   
@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);

}
项目:jenkins-inheritance-plugin    文件:InheritanceProject.java   
/**
 * This method will fetch all properties defined for the current project
 * and only those defined on it.
 * <p>
 * There are two complications though:
 * <ol>
 * <li>
 *      {@link ParametersDefinitionProperty} instances need to be replaced
 *      with {@link InheritanceParametersDefinitionProperty} instances,
 *      to make sure that versioning details are correctly stored.
 *      Also, we wish to make sure that the more advanced Jelly-files from
 *      the latter class are used for build-purposes.
 * </li>
 * <li>
 *      Variances define additional properties; so that we can make sure
 *      to splice-in those additional properties if a request for
 *      parameters comes from a direct child with the correct variance.
 * </li>
 * </ol>
 * <p>
 * Also note, that Jenkins does not allow direct access to the properties
 * list. So clearing or modifying this list will not work.
 * 
 * @return the local list of properties.
 */
public List<JobProperty<? super InheritanceProject>> getRawAllProperties() {
    LinkedList<JobProperty<? super InheritanceProject>> out =
            new LinkedList<JobProperty<? super InheritanceProject>>();

    //First, we add the global properties defined for this project
    List<JobProperty<? super InheritanceProject>> origProps =
            super.getAllProperties();

    //Filling the output list with the adjusted original properties
    for (JobProperty<? super InheritanceProject> prop : origProps) {
        if (!(prop instanceof ParametersDefinitionProperty)) {
            out.add(prop);
            continue;
        }
        //Converting a PDP to an IPDP
        ParametersDefinitionProperty pdp = (ParametersDefinitionProperty) prop;
        InheritanceParametersDefinitionProperty ipdp =
                new InheritanceParametersDefinitionProperty(
                        pdp.getOwner(),
                        pdp
                );
        out.add(ipdp);
    }
    return out;
}
项目:jenkins-inheritance-plugin    文件:ParameterSelector.java   
@Override
public JobProperty<?> merge(
        JobProperty<?> prior,
        JobProperty<?> latter,
        InheritanceProject caller) {
    if (!(prior instanceof ParametersDefinitionProperty) ||
            !(latter instanceof ParametersDefinitionProperty)) {
        return latter;
    }

    InheritanceParametersDefinitionProperty ipdp =
            InheritanceParametersDefinitionProperty
            .createMerged(
                    (ParametersDefinitionProperty) prior,
                    (ParametersDefinitionProperty) latter
            );
    return ipdp;
}
项目:delivery-pipeline-plugin    文件:PipelineVersionContributorTest.java   
@Test
@Issue("JENKINS-28848")
public void testWithBuildNameSetterPluginAndAdditionalParameters() throws Exception {
    FreeStyleProject a = jenkins.createFreeStyleProject("a");
    FreeStyleProject b = jenkins.createFreeStyleProject("b");

    a.addProperty(new ParametersDefinitionProperty(new StringParameterDefinition("BUILD_VERSION", "DEFAULT_VALUE")));
    a.getPublishersList().add(new BuildTrigger("b", false));
    a.getBuildWrappersList().add(new PipelineVersionContributor(true, "1.0.0.$BUILD_NUMBER"));
    b.getBuildWrappersList().add(new BuildNameSetter("$PIPELINE_VERSION"));


    jenkins.getInstance().rebuildDependencyGraph();
    jenkins.setQuietPeriod(0);

    jenkins.buildAndAssertSuccess(a);
    jenkins.waitUntilNoActivity();

    assertEquals("1.0.0.1", a.getLastBuild().getDisplayName());
    assertEquals("1.0.0.1", b.getLastBuild().getDisplayName());
    assertEquals("1.0.0.1", a.getLastBuild().getBuildVariableResolver().resolve(PIPELINE_VERSION));
    assertEquals("1.0.0.1", b.getLastBuild().getBuildVariableResolver().resolve(PIPELINE_VERSION));
}
项目:run-selector-plugin    文件:RunSelectorParameterTest.java   
@Test
public void testConfiguration() throws Exception {
    RunSelectorParameter expected = new RunSelectorParameter("SELECTOR", new StatusRunSelector(StatusRunSelector.BuildStatus.STABLE), "foo");
    FreeStyleProject job = rule.createFreeStyleProject();
    job.addProperty(new ParametersDefinitionProperty(expected));
    job.save();

    job = rule.configRoundtrip(job);
    RunSelectorParameter actual = (RunSelectorParameter) job.getProperty(ParametersDefinitionProperty.class).getParameterDefinition("SELECTOR");
    rule.assertEqualDataBoundBeans(expected, actual);
}
项目:run-selector-plugin    文件:ParameterizedRunFilterTest.java   
@Test
public void testIsSelectableWithParameter() throws Exception {
    WorkflowJob selecter = j.jenkins.createProject(
        WorkflowJob.class,
        RandomStringUtils.randomAlphanumeric(7)
    );
    selecter.addProperty(new ParametersDefinitionProperty(
        new RunFilterParameter(
            "FILTER",
            "description",
            new NoRunFilter()
        )
    ));
    selecter.setDefinition(new CpsFlowDefinition(String.format(
        "def runWrapper = selectRun"
        + " job: '%s',"
        + " filter: [$class: 'ParameterizedRunFilter', parameter: '${FILTER}'],"
        + " verbose: true;"
        + "assert(runWrapper.id == '%s')",
        jobToSelect.getFullName(),
        runToSelect1.getId()
    )));

    j.assertBuildStatusSuccess(selecter.scheduleBuild2(
        0,
        new ParametersAction(
            new StringParameterValue("FILTER", "<SavedRunFilter />")
        )
    ));
}
项目:run-selector-plugin    文件:ParameterizedRunFilterTest.java   
@Test
public void testIsSelectableWithUI() throws Exception {
    WorkflowJob selecter = j.jenkins.createProject(
        WorkflowJob.class,
        RandomStringUtils.randomAlphanumeric(7)
    );
    selecter.addProperty(new ParametersDefinitionProperty(
        new RunFilterParameter(
            "FILTER",
            "description",
            new SavedRunFilter()
        )
    ));
    selecter.setDefinition(new CpsFlowDefinition(String.format(
        "def runWrapper = selectRun"
        + " job: '%s',"
        + " filter: [$class: 'ParameterizedRunFilter', parameter: '${FILTER}'],"
        + " verbose: true;"
        + "assert(runWrapper.id == '%s')",
        jobToSelect.getFullName(),
        runToSelect1.getId()
    )));

    WebClient wc = j.createWebClient();
    // Jenkins sends 405 response for GET of build page.. deal with that:
    wc.getOptions().setThrowExceptionOnFailingStatusCode(false);
    wc.getOptions().setPrintContentOnFailingStatusCode(false);
    j.submit(wc.getPage(selecter, "build").getFormByName("parameters"));
    j.waitUntilNoActivity();
    j.assertBuildStatusSuccess(selecter.getLastBuild());
}
项目:run-selector-plugin    文件:ParameterizedRunFilterTest.java   
@Test
public void testIsSelectableBadParameter() throws Exception {
    WorkflowJob selecter = j.jenkins.createProject(
        WorkflowJob.class,
        RandomStringUtils.randomAlphanumeric(7)
    );
    selecter.addProperty(new ParametersDefinitionProperty(
        new RunFilterParameter(
            "FILTER",
            "description",
            new NoRunFilter()
        )
    ));
    selecter.setDefinition(new CpsFlowDefinition(String.format(
        "def runWrapper = selectRun"
        + " job: '%s',"
        + " filter: [$class: 'ParameterizedRunFilter', parameter: '${FILTER}'],"
        + " verbose: true;",
        jobToSelect.getFullName()
    )));

    j.assertBuildStatus(
        Result.FAILURE,
        selecter.scheduleBuild2(
            0,
            new ParametersAction(
                new StringParameterValue("FILTER", "Bad Parameter")
            )
        ).get()
    );
}
项目:jenkins-github-pull-request-comments    文件:GhprcTrigger.java   
private ArrayList<ParameterValue> getDefaultParameters() {
    ArrayList<ParameterValue> values = new ArrayList<ParameterValue>();
    ParametersDefinitionProperty pdp = this.job.getProperty(ParametersDefinitionProperty.class);
    if (pdp != null) {
        for (ParameterDefinition pd : pdp.getParameterDefinitions()) {
            if (pd.getName().equals("sha1"))
                continue;
            values.add(pd.getDefaultParameterValue());
        }
    }
    return values;
}
项目:yaml-project-plugin    文件:YamlDecoratorTest.java   
@Before
public void setUp() throws Exception {
  MockitoAnnotations.initMocks(this);

  project = jenkins.createFreeStyleProject("test");

  project.getBuildersList().add(new hudson.tasks.Shell("echo $foo"));
  // Make sure we don't clobber pre-existing properties when we workaround the
  // missing null check.
  project.addProperty(new ParametersDefinitionProperty(
      new StringParameterDefinition("foo", "bar")));
}
项目:ghprb-copy    文件:GhprbTrigger.java   
private ArrayList<ParameterValue> getDefaultParameters() {
    ArrayList<ParameterValue> values = new ArrayList<ParameterValue>();
    ParametersDefinitionProperty pdp = this.job.getProperty(ParametersDefinitionProperty.class);
    if (pdp != null) {
        for(ParameterDefinition pd :  pdp.getParameterDefinitions()) {
            if (pd.getName().equals("sha1"))
                continue;
            values.add(pd.getDefaultParameterValue());
        }
    }
    return values;
}
项目:uno-choice-plugin    文件:Utils.java   
/**
 * Get the parameter definitions for the given project.
 *
 * @since 1.3
 * @author dynamic-parameter-plugin
 * @param project the project for which the parameter definitions should be found
 * @return parameter definitions or an empty list
 */
public static @Nonnull List<ParameterDefinition> getProjectParameterDefinitions(@Nonnull Project<?, ?> project) {
    ParametersDefinitionProperty parametersDefinitionProperty = project.getProperty(ParametersDefinitionProperty.class);
    if (parametersDefinitionProperty != null) {
        List<ParameterDefinition> parameterDefinitions = parametersDefinitionProperty.getParameterDefinitions();
        if (parameterDefinitions != null) {
            return parameterDefinitions;
        }
    }
    return Collections.emptyList();
}
项目:DotCi    文件:ParametersDefinitionPropertyCoverter.java   
@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;
}
项目:DotCi    文件:DynamicProjectRepository.java   
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);
    }
}
项目:DotCi    文件:GithubWebhookTest.java   
@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));
}
项目:jenkins-inheritance-plugin    文件:InheritanceProject.java   
public List<ParameterDefinition> getParameters(IMode mode) {
    ParametersDefinitionProperty pdp =
            this.getProperty(ParametersDefinitionProperty.class, mode);
    if (pdp == null) {
        return new LinkedList<ParameterDefinition>();
    }
    return pdp.getParameterDefinitions();
}
项目:jenkins-inheritance-plugin    文件:InheritanceProject.java   
private List<ScopeEntry> getFullParameterScope() {
    //Fetching the correct definition property
    ParametersDefinitionProperty pdp = this.getProperty(
            ParametersDefinitionProperty.class, IMode.INHERIT_FORCED
    );
    if (pdp == null) {
        //No parameters set, so we return an empty list
        return Collections.emptyList();
    }

    //Checking if it is a fully scoped inheritance-aware one; if yes, we
    //fetch the full scope of parameters.
    List<ScopeEntry> fullScope = null;
    if (pdp instanceof InheritanceParametersDefinitionProperty) {
        InheritanceParametersDefinitionProperty ipdp =
                (InheritanceParametersDefinitionProperty) pdp;
        fullScope = ipdp.getAllScopedParameterDefinitions();
    } else {
        String ownerName = (pdp.getOwner() != null)
                ? pdp.getOwner().getFullName() : "";
        fullScope = new LinkedList<ScopeEntry>();
        for (ParameterDefinition pd : pdp.getParameterDefinitions()) {
            fullScope.add(new ScopeEntry(ownerName, pd));
        }
    }

    if (fullScope != null) {
        return fullScope;
    } else {
        return Collections.emptyList();
    }
}
项目:jenkins-inheritance-plugin    文件:ParameterSelector.java   
@Override
public MODE getModeFor(
        Class<?> clazz) {
    if (ParametersDefinitionProperty.class.isAssignableFrom(clazz)) {
        return MODE.MERGE;
    }
    return MODE.NOT_RESPONSIBLE;
}
项目:jenkins-inheritance-plugin    文件:ParameterSelector.java   
@Override
public String getObjectIdentifier(JobProperty<?> obj) {
    //All regular and inheritable parameter definitions are the same, as
    //there should be only one!
    if (obj.getClass() == ParametersDefinitionProperty.class ||
            obj.getClass() == InheritanceParametersDefinitionProperty.class) {
        return "SINGLETON";
    } else {
        return null;
    }
}
项目:jenkins-inheritance-plugin    文件:ParameterSelector.java   
/**
 * This method makes sure that only
 * {@link InheritanceParametersDefinitionProperty} objects are stored in
 * the list returned to Jenkins and that they are all owned by the caller.
 * This means that it will convert+copy objects that do not match this
 * and will make sure that the correct scoping is set for each new
 * {@link InheritanceParametersDefinitionProperty} object.
 */
@Override
public JobProperty<?> handleSingleton(
        JobProperty<?> jp,
        InheritanceProject caller) {
    boolean needsCopy = false;

    if (!(jp instanceof ParametersDefinitionProperty)) {
        return jp;
    }
    ParametersDefinitionProperty pdp = (ParametersDefinitionProperty) jp;

    //Checking if we already deal with an IPDP
    if (pdp instanceof InheritanceParametersDefinitionProperty) {
        //Checking if the caller already owns the IPDP; if not we copy
        if (pdp.getOwner() != caller) {
            needsCopy = true;
        }
    } else {
        needsCopy = true;
    }

    if (needsCopy) {
        InheritanceParametersDefinitionProperty ipdp =
                new InheritanceParametersDefinitionProperty(
                        (caller != null) ? caller : pdp.getOwner(),
                        pdp
                );
        return ipdp;
    } else {
        return pdp;
    }
}
项目:jenkins-inheritance-plugin    文件:TestParameterInheritance.java   
private void addParameters(
        InheritanceProject ip, List<StringParameterValue> values) throws IOException {
    List<ParameterDefinition> pDefs = new LinkedList<>();
    for (StringParameterValue pv : values) {
        pDefs.add(new StringParameterDefinition(pv.getName(), pv.value));
    }
    ParametersDefinitionProperty pdp =
            new ParametersDefinitionProperty(pDefs);
    ip.addProperty(pdp);
}
项目:git-param    文件:GitParameterDefinition.java   
private AbstractProject<?, ?> getCurrentProject() {
    AbstractProject<?, ?> context = null;
    List<AbstractProject> jobs = Hudson.getInstance().getItems(
            AbstractProject.class);

    for (AbstractProject<?, ?> project : jobs) {
        ParametersDefinitionProperty property = (ParametersDefinitionProperty) project
                .getProperty(ParametersDefinitionProperty.class);

        if (property != null) {
            List<ParameterDefinition> parameterDefinitions = property
                    .getParameterDefinitions();

            if (parameterDefinitions != null) {
                for (ParameterDefinition pd : parameterDefinitions) {

                    if (pd instanceof GitParameterDefinition
                            && ((GitParameterDefinition) pd)
                                    .compareTo(this) == 0) {

                        context = project;
                        break;
                    }
                }
            }
        }
    }

    return context;
}
项目:delivery-pipeline-plugin    文件:DeliveryPipelineViewTest.java   
@Test
public void testRebuild() throws Exception {
    FreeStyleProject projectA = jenkins.createFreeStyleProject("A");
    FreeStyleProject projectB = jenkins.createFreeStyleProject("B");
    projectB.addProperty(new ParametersDefinitionProperty(
            new StringParameterDefinition("BUILD_VERSION", "DEFAULT_VALUE")));
    projectA.getPublishersList().add(
            new hudson.plugins.parameterizedtrigger.BuildTrigger(
                    new BuildTriggerConfig("b", ResultCondition.SUCCESS,
                            new PredefinedBuildParameters("VERSION=$BUILD_NUMBER"))));

    jenkins.getInstance().rebuildDependencyGraph();

    DeliveryPipelineView view = new DeliveryPipelineView("Pipeline");
    jenkins.getInstance().addView(view);

    jenkins.buildAndAssertSuccess(projectA);
    jenkins.waitUntilNoActivity();

    assertNotNull(projectA.getLastBuild());
    assertNotNull(projectB.getLastBuild());

    final AbstractBuild<?, ?> b1 = projectB.getLastBuild();

    view.triggerRebuild("B", "1");
    jenkins.waitUntilNoActivity();
    assertEquals(2, projectB.getLastBuild().getNumber());
    assertEqualsList(b1.getActions(ParametersAction.class),
            projectB.getLastBuild().getActions(ParametersAction.class));
}
项目:delivery-pipeline-plugin    文件:GuiFunctionalIT.java   
@Test
public void testTriggerNewParameterizedPipeline() throws Exception {

    FreeStyleProject start = jenkins.createFreeStyleProject("Start");
    start.addProperty(new ParametersDefinitionProperty(
            new StringParameterDefinition("key2", "value2")
            ));
    jenkins.createFreeStyleProject("End");
    start.getPublishersList().add(new BuildTrigger("End", true));

    jenkins.getInstance().rebuildDependencyGraph();

    DeliveryPipelineView view = new DeliveryPipelineView("Pipeline");
    List<DeliveryPipelineView.ComponentSpec> specs = new ArrayList<>();
    specs.add(new DeliveryPipelineView.ComponentSpec("Component", "Start", NONE, DO_NOT_SHOW_UPSTREAM));
    view.setComponentSpecs(specs);
    view.setAllowPipelineStart(true);

    jenkins.getInstance().addView(view);

    DeliveryPipelinePage page =
            new DeliveryPipelinePage(webDriver, jenkins.getURL().toExternalForm(), "view/Pipeline");
    page.open();
    page.triggerNewParameterizedPipelineBuild("0");

    jenkins.waitUntilNoActivity();

    assertNotNull(start.getLastBuild());
}
项目:run-selector-plugin    文件:RunSelectorParameterTest.java   
/**
 * Verify RunSelectorParameter works via HTML form, http POST and CLI.
 */
@Test
public void testParameter() throws Exception {
    FreeStyleProject job = rule.createFreeStyleProject();
    job.addProperty(new ParametersDefinitionProperty(
            new RunSelectorParameter("SELECTOR", new StatusRunSelector(StatusRunSelector.BuildStatus.SUCCESSFUL), "foo")));
    CaptureEnvironmentBuilder ceb = new CaptureEnvironmentBuilder();
    job.getBuildersList().add(ceb);

    // Run via UI (HTML form)
    WebClient wc = rule.createWebClient();
    WebClientOptions wco = wc.getOptions();
    // Jenkins sends 405 response for GET of build page.. deal with that:
    wco.setThrowExceptionOnFailingStatusCode(false);
    wco.setPrintContentOnFailingStatusCode(false);
    HtmlForm form = wc.getPage(job, "build").getFormByName("parameters");
    form.getSelectByName("").getOptionByText("Specified by build number").setSelected(true);
    wc.waitForBackgroundJavaScript(10000);
    form.getInputByName("_.buildNumber").setValueAttribute("6");
    rule.submit(form);
    Queue.Item q = rule.jenkins.getQueue().getItem(job);
    if (q != null) q.getFuture().get();
    while (job.getLastBuild().isBuilding()) Thread.sleep(100);
    assertEquals("<BuildNumberRunSelector><buildNumber>6</buildNumber></BuildNumberRunSelector>",
            ceb.getEnvVars().get("SELECTOR").replaceAll("\\s+", ""));
    job.getBuildersList().replace(ceb = new CaptureEnvironmentBuilder());

    // Run via HTTP POST (buildWithParameters)
    WebRequest post = new WebRequest(
            new URL(rule.getURL(), job.getUrl() + "/buildWithParameters"), HttpMethod.POST);
    wc.addCrumb(post);
    String xml = "<StatusRunSelector><buildStatus>STABLE</buildStatus></StatusRunSelector>";
    post.setRequestParameters(Arrays.asList(new NameValuePair("SELECTOR", xml),
            post.getRequestParameters().get(0)));
    wc.getPage(post);
    q = rule.jenkins.getQueue().getItem(job);
    if (q != null) q.getFuture().get();
    while (job.getLastBuild().isBuilding()) Thread.sleep(100);
    assertEquals(xml, ceb.getEnvVars().get("SELECTOR"));
    job.getBuildersList().replace(ceb = new CaptureEnvironmentBuilder());

    // Run via CLI
    CLI cli = new CLI(rule.getURL());
    assertEquals(0, cli.execute(
            "build", job.getFullName(), "-p", "SELECTOR=<StatusRunSelector/>"));
    q = rule.jenkins.getQueue().getItem(job);
    if (q != null) q.getFuture().get();
    while (job.getLastBuild().isBuilding()) Thread.sleep(100);
    assertEquals("<StatusRunSelector/>", ceb.getEnvVars().get("SELECTOR"));
}
项目:jenkins-plugin    文件:IOpenShiftPluginDescriptor.java   
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;
}
项目:gitlab-build-plugin    文件:GitlabWebhookAction.java   
public void doIndex(StaplerRequest request, StaplerResponse response) throws IOException, ServletException {
    if ("GET".equals(request.getMethod())) {
        response.sendRedirect("readme");
        return;
    }

    Project project = getProject();

    if (project == null) {
        response.getWriter().print("Can't find any project, make sure your url is correct");
        return;
    }

    List<ParameterValue> values = new ArrayList<ParameterValue>();

    // add gitlab webhook parameters
    values.addAll(getParametersFromJsonPayload(request));

    // add all parameters with its default value
    ParametersDefinitionProperty paramDefProp = (ParametersDefinitionProperty)project.getProperty(
        ParametersDefinitionProperty.class);

    List<ParameterValue> fromDefault = new ArrayList<ParameterValue>();
    if (paramDefProp != null) {
        List<String> params = paramDefProp.getParameterDefinitionNames();
        for (String item : params) {
            boolean ignore = false;
            for (ParameterValue pv : values) {
                if (pv.getName().equals(item)) {
                    // just ignore the default value, if it has been in the webhook parameters
                    ignore = true;
                }
            }
            if (ignore) {
                continue;
            } else {
                ParameterDefinition pd = paramDefProp.getParameterDefinition(item);
                ParameterValue defaultValue = pd.getDefaultParameterValue();
                if (defaultValue != null) {
                    fromDefault.add(defaultValue);
                }
            }

        }
    }

    values.addAll(fromDefault);

    if (skippingBuildExpressionMatches(project, values)) {
        LOGGER.log(Level.INFO, String.format(
            "(Project:%s)Webhook received, but matches skipping build expression, will not trigger a build.",
            project.getName()));
        return;
    }

    List<Action> actions = new ArrayList<Action>();
    actions.add(new ParametersAction(values));

    Hudson.getInstance().getQueue().schedule((Queue.Task)project, 0, actions);
    response.getWriter().print("ok, scheduled.");

}
项目:uno-choice-plugin    文件:TestPersistingParameters.java   
/**
 * Test persisting jobs with parameters.
 *
 * @throws Exception in Jenkins rule
 */
@Test
public void testSaveParameters() throws Exception {
    FreeStyleProject project = j.createFreeStyleProject();
    GroovyScript scriptParam001 = new GroovyScript(new SecureGroovyScript(SCRIPT_PARAM001, false, null),
            new SecureGroovyScript(SCRIPT_FALLBACK_PARAM001, false, null));
    ChoiceParameter param001 = new ChoiceParameter("param001", "param001 description", "random-name",
            scriptParam001, AbstractUnoChoiceParameter.PARAMETER_TYPE_SINGLE_SELECT, true, 1);
    GroovyScript scriptParam002 = new GroovyScript(new SecureGroovyScript(SCRIPT_PARAM002, false, null),
            new SecureGroovyScript(SCRIPT_FALLBACK_PARAM002, false, null));
    CascadeChoiceParameter param002 = new CascadeChoiceParameter("param002", "param002 description", "random-name",
            scriptParam002, AbstractUnoChoiceParameter.PARAMETER_TYPE_SINGLE_SELECT, "param001", true, 1);
    ParametersDefinitionProperty param001Def = new ParametersDefinitionProperty(
            Arrays.<ParameterDefinition>asList(param001, param002));
    project.addProperty(param001Def);
    QueueTaskFuture<FreeStyleBuild> future = project.scheduleBuild2(0);
    FreeStyleBuild build = future.get();
    // even though the cascaded parameter will fail to evaluate, we should
    // still get a success here.
    assertEquals(Result.SUCCESS, build.getResult());
    XmlFile configXml = project.getConfigFile();
    FreeStyleProject reReadProject = (FreeStyleProject) configXml.read();
    int found = 0;
    for (Entry<JobPropertyDescriptor, JobProperty<? super FreeStyleProject>> entry : reReadProject.getProperties()
            .entrySet()) {
        JobProperty<? super FreeStyleProject> jobProperty = entry.getValue();
        if (jobProperty instanceof ParametersDefinitionProperty) {
            ParametersDefinitionProperty paramDef = (ParametersDefinitionProperty) jobProperty;
            List<ParameterDefinition> parameters = paramDef.getParameterDefinitions();
            for (ParameterDefinition parameter : parameters) {
                if (parameter instanceof AbstractScriptableParameter) {
                    found++;
                    AbstractScriptableParameter choiceParam = (AbstractScriptableParameter) parameter;
                    String scriptText = ((GroovyScript) choiceParam.getScript()).getScript().getScript();
                    String fallbackScriptText = ((GroovyScript) choiceParam.getScript()).getFallbackScript()
                            .getScript();
                    assertTrue("Found an empty script!", StringUtils.isNotBlank(scriptText));
                    assertTrue("Found an empty fallback script!", StringUtils.isNotBlank(fallbackScriptText));
                    if (parameter.getName().equals("param001")) {
                        assertEquals(SCRIPT_PARAM001, scriptText);
                        assertEquals(SCRIPT_FALLBACK_PARAM001, fallbackScriptText);
                    } else {
                        assertEquals(SCRIPT_PARAM002, scriptText);
                        assertEquals(SCRIPT_FALLBACK_PARAM002, fallbackScriptText);
                    }
                }
            }
        }
    }
    // We have two parameters before saving. We must have two now.
    assertEquals("Didn't find all parameters after persisting xml", 2, found);
}
项目:DotCi    文件:ParametersDefinitionPropertyCoverter.java   
public ParametersDefinitionPropertyCoverter() {
    super(ParametersDefinitionProperty.class);
}
项目:jenkins-inheritance-plugin    文件:InheritanceProject.java   
/**
 * This is called by {@link #doBuild(StaplerRequest, StaplerResponse, TimeDuration)}
 * and implements the actual build scheduling and parameter assignment magic.
 * <p>
 * Do note that it expects, that all relevant versioning information has
 * already been registered in the current request and / or thread via
 * {@link VersionHandler#initVersions(AbstractProject)}.
 * 
 * @param req the request the user submitted.
 * @param rsp the response to allow information to be passed to the user
 * @param delay the build delay
 * 
 * @throws IOException
 * @throws ServletException
 */
private void doBuildInternal(StaplerRequest req, StaplerResponse rsp, @QueryParameter TimeDuration delay)
        throws IOException, ServletException {
    //The delay parameter might be null in case somebody used a custom URL
    if (delay == null) {
        delay = new TimeDuration(0);
    }

    //Call the superclass to modify the job further
    this.onBuild(req, rsp);

    /* === START COPY OF SUPER FUNCTION ===
     * 
     * We can't call the super-function, as it does not allow us to
     * add a custom action to rescue the versioning over to the start of
     * the actual build.
     */

    //TODO: Check if this ACL check actually does the same as the commented
    //instruction below
    ACL acl = Jenkins.getInstance().getACL();
    acl.checkPermission(BUILD);
    //BuildAuthorizationToken.checkPermission(this, getAuthToken(), req, rsp);

    // if a build is parameterized, let that take over
    ParametersDefinitionProperty pp = getProperty(ParametersDefinitionProperty.class);
    if (pp != null) {
        pp._doBuild(req, rsp, delay);
        return;
    }

    // If this point is reached; the build is not parameterised

    if (!isBuildable()) {
        //Super implementation throws HTTP response; but we do not need the stacktrace
        rsp.sendError(
                SC_INTERNAL_SERVER_ERROR,
                String.format("%s is not buildable", this.getFullName())
        );
        return;
    }

    // Invoke the onBuild actions contributed by BuildViewExtension
    List<Action> actions = BuildViewExtension.callAll(this, req);
    //Add the versioning Action, with the CURRENTLY active versions
    actions.add(new VersioningAction(VersionHandler.getVersions()));
    //Add the cause action
    actions.add(this.getBuildCauseOverride(req));

    Jenkins.getInstance().getQueue().schedule2(
            this, delay.getTime(), actions
    );

    //Send the user back, except if "rebuildNoRedirect" is set
    if (req.getAttribute("rebuildNoRedirect") == null) {
        rsp.forwardToPreviousPage(req);
    }
    // === END COPY OF SUPER FUNCTION ===
}
项目:jenkins-inheritance-plugin    文件:InheritanceParametersDefinitionProperty.java   
public InheritanceParametersDefinitionProperty(
        AbstractProject<?,?> owner,
        ParametersDefinitionProperty other) {
    this(owner, other.getParameterDefinitions());
}