Search in sources :

Example 11 with Descriptor

use of hudson.model.Descriptor in project workflow-cps-plugin by jenkinsci.

the class Snippetizer method doGenerateSnippet.

// accessed via REST API
@Restricted(DoNotUse.class)
public HttpResponse doGenerateSnippet(StaplerRequest req, @QueryParameter String json) throws Exception {
    // TODO is there not an easier way to do this? Maybe Descriptor.newInstancesFromHeteroList on a one-element JSONArray?
    JSONObject jsonO = JSONObject.fromObject(json);
    Jenkins j = Jenkins.getActiveInstance();
    Class<?> c = j.getPluginManager().uberClassLoader.loadClass(jsonO.getString("stapler-class"));
    Descriptor descriptor = j.getDescriptor(c.asSubclass(Describable.class));
    if (descriptor == null) {
        return HttpResponses.plainText("<could not find " + c.getName() + ">");
    }
    Object o;
    try {
        o = descriptor.newInstance(req, jsonO);
    } catch (RuntimeException x) {
        // e.g. IllegalArgumentException
        return HttpResponses.plainText(Functions.printThrowable(x));
    }
    try {
        Step step = null;
        if (o instanceof Step) {
            step = (Step) o;
        } else {
            // Look for a metastep which could take this as its delegate.
            for (StepDescriptor d : StepDescriptor.allMeta()) {
                if (d.getMetaStepArgumentType().isInstance(o)) {
                    DescribableModel<?> m = DescribableModel.of(d.clazz);
                    DescribableParameter soleRequiredParameter = m.getSoleRequiredParameter();
                    if (soleRequiredParameter != null) {
                        step = d.newInstance(Collections.singletonMap(soleRequiredParameter.getName(), o));
                        break;
                    }
                }
            }
        }
        if (step == null) {
            return HttpResponses.plainText("Cannot find a step corresponding to " + o.getClass().getName());
        }
        String groovy = step2Groovy(step);
        if (descriptor instanceof StepDescriptor && ((StepDescriptor) descriptor).isAdvanced()) {
            String warning = Messages.Snippetizer_this_step_should_not_normally_be_used_in();
            groovy = "// " + warning + "\n" + groovy;
        }
        return HttpResponses.plainText(groovy);
    } catch (UnsupportedOperationException x) {
        Logger.getLogger(CpsFlowExecution.class.getName()).log(Level.WARNING, "failed to render " + json, x);
        return HttpResponses.plainText(x.getMessage());
    }
}
Also used : DescribableParameter(org.jenkinsci.plugins.structs.describable.DescribableParameter) UninstantiatedDescribable(org.jenkinsci.plugins.structs.describable.UninstantiatedDescribable) Describable(hudson.model.Describable) Step(org.jenkinsci.plugins.workflow.steps.Step) SimpleBuildStep(jenkins.tasks.SimpleBuildStep) Jenkins(jenkins.model.Jenkins) JSONObject(net.sf.json.JSONObject) BuildStepDescriptor(hudson.tasks.BuildStepDescriptor) Descriptor(hudson.model.Descriptor) StepDescriptor(org.jenkinsci.plugins.workflow.steps.StepDescriptor) BuildStepDescriptor(hudson.tasks.BuildStepDescriptor) StepDescriptor(org.jenkinsci.plugins.workflow.steps.StepDescriptor) JSONObject(net.sf.json.JSONObject) Restricted(org.kohsuke.accmod.Restricted)

Example 12 with Descriptor

use of hudson.model.Descriptor in project configuration-as-code-plugin by jenkinsci.

the class GlobalConfigurationCategoryConfigurator method describe.

@Override
public Set<Attribute> describe() {
    Set<Attribute> attributes = new HashSet<>();
    final ExtensionList<Descriptor> descriptors = Jenkins.getInstance().getExtensionList(Descriptor.class);
    for (Descriptor descriptor : descriptors) {
        if (descriptor.getCategory() == category && descriptor.getGlobalConfigPage() != null) {
            final DescriptorConfigurator configurator = new DescriptorConfigurator(descriptor);
            attributes.add(new Attribute(configurator.getName(), configurator.getTarget()) {

                @Override
                public void setValue(Object target, Object value) throws Exception {
                // No actual attribute to set, DescriptorRootElementConfigurator manages singleton Descriptor components
                }
            });
        }
    }
    return attributes;
}
Also used : Descriptor(hudson.model.Descriptor) HashSet(java.util.HashSet)

Example 13 with Descriptor

use of hudson.model.Descriptor in project configuration-as-code-plugin by jenkinsci.

the class JenkinsConfigurator method describe.

@Override
public Set<Attribute> describe() {
    final Set<Attribute> attributes = super.describe();
    final Jenkins jenkins = Jenkins.getInstance();
    attributes.add(new PersistedListAttribute<Cloud>("clouds", jenkins.clouds, Cloud.class));
    attributes.add(new Attribute<String>("jobs", String.class).multiple(true).setter((target, attribute, value) -> {
        JenkinsJobManagement mng = new JenkinsJobManagement(System.out, new EnvVars(), null, null, LookupStrategy.JENKINS_ROOT);
        for (String script : (List<String>) value) {
            new JenkinsDslScriptLoader(mng).runScript(script);
        }
    }));
    // Check for unclassified Descriptors
    final ExtensionList<Descriptor> descriptors = jenkins.getExtensionList(Descriptor.class);
    for (Descriptor descriptor : descriptors) {
        if (descriptor.getGlobalConfigPage() != null && descriptor.getCategory() instanceof GlobalConfigurationCategory.Unclassified) {
            final DescriptorConfigurator configurator = new DescriptorConfigurator(descriptor);
            attributes.add(new Attribute(configurator.getName(), configurator.getTarget()).setter(NOOP));
        }
    }
    // Add remoting security, all legwork will be done by a configurator
    attributes.add(new Attribute("remotingSecurity", AdminWhitelistRule.class).setter(NOOP));
    return attributes;
}
Also used : JenkinsDslScriptLoader(javaposse.jobdsl.plugin.JenkinsDslScriptLoader) JenkinsJobManagement(javaposse.jobdsl.plugin.JenkinsJobManagement) Descriptor(hudson.model.Descriptor) Jenkins(jenkins.model.Jenkins) AdminWhitelistRule(jenkins.security.s2m.AdminWhitelistRule) Set(java.util.Set) Logger(java.util.logging.Logger) Level(java.util.logging.Level) List(java.util.List) Map(java.util.Map) Extension(hudson.Extension) LookupStrategy(javaposse.jobdsl.plugin.LookupStrategy) EnvVars(hudson.EnvVars) Cloud(hudson.slaves.Cloud) ExtensionList(hudson.ExtensionList) GlobalConfigurationCategory(jenkins.model.GlobalConfigurationCategory) JenkinsJobManagement(javaposse.jobdsl.plugin.JenkinsJobManagement) JenkinsDslScriptLoader(javaposse.jobdsl.plugin.JenkinsDslScriptLoader) Jenkins(jenkins.model.Jenkins) EnvVars(hudson.EnvVars) Cloud(hudson.slaves.Cloud) Descriptor(hudson.model.Descriptor) GlobalConfigurationCategory(jenkins.model.GlobalConfigurationCategory)

Example 14 with Descriptor

use of hudson.model.Descriptor in project promoted-builds-plugin by jenkinsci.

the class ManualConditionTest method testManualPromotionProcessWithInvalidParam.

@Issue("SECURITY-170")
@Test
public /**
 * Verify that the plugin is tolerant against SECURITY-170 in Manual conditions
 */
void testManualPromotionProcessWithInvalidParam() throws Exception {
    FreeStyleProject p = j.createFreeStyleProject();
    ExtensionList<Descriptor> list = j.jenkins.getExtensionList(Descriptor.class);
    list.add(new JobPropertyImpl.DescriptorImpl(JobPropertyImpl.class));
    JobPropertyImpl base = new JobPropertyImpl(p);
    p.addProperty(base);
    PromotionProcess foo = base.addProcess("foo");
    ManualCondition condition = new ManualCondition();
    condition.getParameterDefinitions().add(new StringParameterDefinition("FOO", "BAR", "Test parameter"));
    foo.conditions.add(condition);
    FreeStyleBuild b1 = j.assertBuildStatusSuccess(p.scheduleBuild2(0));
    // Promote a build. Also add one invalid parameter
    List<ParameterValue> paramValues = condition.createDefaultValues();
    paramValues.add(new StringParameterValue("INVALID_PARAM", "hacked!"));
    j.assertBuildStatusSuccess(condition.approve(b1, foo, paramValues));
    ManualApproval manualApproval = b1.getAction(ManualApproval.class);
    assertNotNull(manualApproval);
    List<ParameterValue> parameterValues = manualApproval.badge.getParameterValues();
    // Verify that the build succeeds && has no INVALID_PARAM
    PromotedBuildAction statuses = b1.getAction(PromotedBuildAction.class);
    assertNotNull(statuses);
    assertNotNull(statuses.getPromotions());
    assertFalse(statuses.getPromotions().isEmpty());
    Promotion pb = base.getItem("foo").getBuildByNumber(1);
    assertNotNull("INVALID_PARAM should not be injected into the environment", pb.getEnvironment(TaskListener.NULL).get("INVALID_PARAM", null));
}
Also used : ManualApproval(hudson.plugins.promoted_builds.conditions.ManualCondition.ManualApproval) StringParameterDefinition(hudson.model.StringParameterDefinition) StringParameterValue(hudson.model.StringParameterValue) ParameterValue(hudson.model.ParameterValue) StringParameterValue(hudson.model.StringParameterValue) FreeStyleBuild(hudson.model.FreeStyleBuild) PromotedBuildAction(hudson.plugins.promoted_builds.PromotedBuildAction) FreeStyleProject(hudson.model.FreeStyleProject) JobPropertyImpl(hudson.plugins.promoted_builds.JobPropertyImpl) Promotion(hudson.plugins.promoted_builds.Promotion) PromotionProcess(hudson.plugins.promoted_builds.PromotionProcess) Descriptor(hudson.model.Descriptor) Issue(org.jvnet.hudson.test.Issue) Test(org.junit.Test)

Example 15 with Descriptor

use of hudson.model.Descriptor in project promoted-builds-plugin by jenkinsci.

the class ManualConditionTest method testManualPromotionProcessViaWebClient.

@Test
public void testManualPromotionProcessViaWebClient() throws Exception {
    FreeStyleProject p = j.createFreeStyleProject();
    ExtensionList<Descriptor> list = j.jenkins.getExtensionList(Descriptor.class);
    list.add(new JobPropertyImpl.DescriptorImpl(JobPropertyImpl.class));
    JobPropertyImpl base = new JobPropertyImpl(p);
    p.addProperty(base);
    PromotionProcess foo = base.addProcess("foo");
    ManualCondition condition = new ManualCondition();
    condition.getParameterDefinitions().add(new StringParameterDefinition("bogus_string_param_1", "bogus_value_1", "Bog parameter"));
    condition.getParameterDefinitions().add(new StringParameterDefinition("bogus_string_param_2", "bogus_value_2", "Bog parameter"));
    foo.conditions.add(condition);
    FreeStyleBuild b1 = j.assertBuildStatusSuccess(p.scheduleBuild2(0));
    assertNull(b1.getAction(ManualApproval.class));
    HtmlPage page = j.createWebClient().getPage(b1, "promotion");
    // Approve Promotion
    List<HtmlForm> forms = getFormsByName(page, "approve");
    assertFalse(forms.isEmpty());
    assertEquals(1, forms.size());
    HtmlForm form = forms.get(0);
    List<HtmlElement> parameters = getFormParameters(form);
    assertEquals(parameters.size(), condition.getParameterDefinitions().size());
    for (HtmlElement param : parameters) {
        HtmlElement v = param.getElementsByAttribute("input", "name", "value").get(0);
        v.setAttribute("value", v.getAttribute("value") + "1");
    }
    submit(forms.get(0));
    ManualApproval approval = b1.getAction(ManualApproval.class);
    assertNotNull(approval);
    SortedMap<Integer, Promotion> builds = foo.getBuildsAsMap();
    assertNotNull(builds);
    assertEquals(1, builds.size());
    // Re-Execute approved promotion
    page = j.createWebClient().getPage(b1, "promotion");
    forms = getFormsByName(page, "build");
    assertFalse(forms.isEmpty());
    assertEquals(1, forms.size());
    form = forms.get(0);
    parameters = getFormParameters(form);
    assertEquals(parameters.size(), condition.getParameterDefinitions().size());
    for (HtmlElement param : parameters) {
        HtmlElement v = param.getElementsByAttribute("input", "name", "value").get(0);
        v.setAttribute("value", v.getAttribute("value") + "2");
    }
    submit(form);
    builds = foo.getBuildsAsMap();
    assertEquals(2, builds.size());
    List<ManualApproval> actions = b1.getActions(ManualApproval.class);
    assertEquals(1, actions.size());
    PromotedBuildAction buildActions = b1.getAction(PromotedBuildAction.class);
    int buildIndex = 1;
    String valueSufix = "1";
    List<Promotion> promotions = new ArrayList<Promotion>();
    promotions.addAll(builds.values());
    Collections.reverse(promotions);
    for (Promotion build : promotions) {
        List<ParameterDefinition> values = build.getParameterDefinitionsWithValue();
        assertEquals(values.size(), condition.getParameterDefinitions().size());
        for (ParameterDefinition v : values) {
            assertTrue(v instanceof StringParameterDefinition);
            String pvalue = ((StringParameterDefinition) v).getDefaultValue();
            assertTrue(pvalue.endsWith(valueSufix));
        }
        buildIndex++;
        valueSufix += buildIndex;
    }
    for (Status status : buildActions.getPromotions()) {
        assertNotNull(status.getLast() != null);
        List<ParameterDefinition> values = status.getLast().getParameterDefinitionsWithValue();
        assertEquals(values.size(), condition.getParameterDefinitions().size());
    }
}
Also used : StringParameterDefinition(hudson.model.StringParameterDefinition) HtmlPage(com.gargoylesoftware.htmlunit.html.HtmlPage) ArrayList(java.util.ArrayList) FreeStyleBuild(hudson.model.FreeStyleBuild) Promotion(hudson.plugins.promoted_builds.Promotion) HtmlForm(com.gargoylesoftware.htmlunit.html.HtmlForm) PromotionProcess(hudson.plugins.promoted_builds.PromotionProcess) Status(hudson.plugins.promoted_builds.Status) ManualApproval(hudson.plugins.promoted_builds.conditions.ManualCondition.ManualApproval) HtmlElement(com.gargoylesoftware.htmlunit.html.HtmlElement) PromotedBuildAction(hudson.plugins.promoted_builds.PromotedBuildAction) FreeStyleProject(hudson.model.FreeStyleProject) JobPropertyImpl(hudson.plugins.promoted_builds.JobPropertyImpl) Descriptor(hudson.model.Descriptor) ParameterDefinition(hudson.model.ParameterDefinition) StringParameterDefinition(hudson.model.StringParameterDefinition) Test(org.junit.Test)

Aggregations

Descriptor (hudson.model.Descriptor)22 Test (org.junit.Test)9 JobPropertyImpl (hudson.plugins.promoted_builds.JobPropertyImpl)8 ArrayList (java.util.ArrayList)8 ManualApproval (hudson.plugins.promoted_builds.conditions.ManualCondition.ManualApproval)7 StringParameterDefinition (hudson.model.StringParameterDefinition)6 PromotedBuildAction (hudson.plugins.promoted_builds.PromotedBuildAction)6 PromotionProcess (hudson.plugins.promoted_builds.PromotionProcess)6 FreeStyleBuild (hudson.model.FreeStyleBuild)5 FreeStyleProject (hudson.model.FreeStyleProject)5 Promotion (hudson.plugins.promoted_builds.Promotion)4 StepDescriptor (org.jenkinsci.plugins.workflow.steps.StepDescriptor)4 HtmlElement (com.gargoylesoftware.htmlunit.html.HtmlElement)3 HtmlForm (com.gargoylesoftware.htmlunit.html.HtmlForm)3 HtmlPage (com.gargoylesoftware.htmlunit.html.HtmlPage)3 AbstractProjectDescriptor (hudson.model.AbstractProject.AbstractProjectDescriptor)3 ParameterDefinition (hudson.model.ParameterDefinition)3 ParameterValue (hudson.model.ParameterValue)3 Jenkins (jenkins.model.Jenkins)3 Describable (hudson.model.Describable)2