io.jenkins.plugins.casc.Configurator Java Examples

The following examples show how to use io.jenkins.plugins.casc.Configurator. 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: GitToolConfigurator.java    From git-client-plugin with MIT License 6 votes vote down vote up
@CheckForNull
@Override
public CNode describe(GitTool instance, ConfigurationContext context) throws Exception {
    Mapping mapping = new Mapping();
    if (instance instanceof JGitTool) {
        mapping.put("name", JGitTool.MAGIC_EXENAME);
    } else if (instance instanceof JGitApacheTool) {
        mapping.put("name", JGitApacheTool.MAGIC_EXENAME);
    } else if (instance != null) {
        mapping.put("name", instance.getName());
        mapping.put("home", instance.getHome());
    }
    if (context != null && instance != null && instance.getProperties() != null && !instance.getProperties().isEmpty()) {
        final Configurator<ToolProperty> configurator = context.lookupOrFail(ToolProperty.class);
        Sequence s = new Sequence(instance.getProperties().size());
        for (ToolProperty<?> property : instance.getProperties()) {
            s.add(configurator.describe(property, context));
        }
        mapping.put("properties", s);
    }
    return mapping;
}
 
Example #2
Source File: GitToolConfigurator.java    From git-client-plugin with MIT License 6 votes vote down vote up
@NonNull
private List<ToolProperty<?>> instantiateProperties(@CheckForNull CNode props, @NonNull ConfigurationContext context) throws ConfiguratorException {
    List<ToolProperty<?>> toolProperties = new ArrayList<>();
    if (props == null) {
        return toolProperties;
    }
    final Configurator<ToolProperty> configurator = context.lookupOrFail(ToolProperty.class);
    if (props instanceof Sequence) {
        Sequence s = (Sequence) props;
        for (CNode cNode : s) {
            toolProperties.add(configurator.configure(cNode, context));
        }
    } else {
        toolProperties.add(configurator.configure(props, context));
    }
    return toolProperties;
}
 
Example #3
Source File: GitLabConnectionConfigAsCodeTest.java    From gitlab-plugin with GNU General Public License v2.0 6 votes vote down vote up
@Test
@ConfiguredWithCode("global-config.yml")
public void export_configuration() throws Exception {
    GitLabConnectionConfig globalConfiguration = GitLabConnectionConfig.get();

    ConfiguratorRegistry registry = ConfiguratorRegistry.get();
    ConfigurationContext context = new ConfigurationContext(registry);
    final Configurator c = context.lookupOrFail(GitLabConnectionConfig.class);

    @SuppressWarnings("unchecked")
    CNode node = c.describe(globalConfiguration, context);
    assertNotNull(node);
    String exported = toYamlString(node);
    String expected = toStringFromYamlFile(this, "global-config-expected.yml");
    assertEquals(expected, exported);
}
 
Example #4
Source File: ProxyConfiguratorTest.java    From configuration-as-code-plugin with MIT License 6 votes vote down vote up
@Test
@ConfiguredWithCode("ProxyMinimal.yml")
public void shouldSetProxyWithMinimumFields() throws Exception {
    ProxyConfiguration proxy = j.jenkins.proxy;
    assertEquals(proxy.name, "proxyhost");
    assertEquals(proxy.port, 80);

    assertNull(proxy.getUserName());
    assertNull(proxy.getTestUrl());

    ConfiguratorRegistry registry = ConfiguratorRegistry.get();
    ConfigurationContext context = new ConfigurationContext(registry);
    final Configurator c = context.lookupOrFail(ProxyConfiguration.class);
    final CNode node = c.describe(proxy, context);
    assertNotNull(node);
    Mapping mapping = node.asMapping();
    assertEquals(2, node.asMapping().size());
    assertEquals("proxyhost", mapping.getScalarValue("name"));
    assertEquals("80", mapping.getScalarValue("port"));
}
 
Example #5
Source File: ProxyConfiguratorTest.java    From configuration-as-code-plugin with MIT License 6 votes vote down vote up
@Test
@ConfiguredWithCode("Proxy.yml")
public void shouldSetProxyWithAllFields() throws Exception {
    ProxyConfiguration proxy = j.jenkins.proxy;
    assertEquals(proxy.name, "proxyhost");
    assertEquals(proxy.port, 80);

    assertEquals(proxy.getUserName(), "login");
    assertThat(proxy.getSecretPassword(), hasPlainText("password"));
    assertEquals(proxy.noProxyHost, "externalhost");
    assertEquals(proxy.getTestUrl(), "http://google.com");

    ConfiguratorRegistry registry = ConfiguratorRegistry.get();
    ConfigurationContext context = new ConfigurationContext(registry);
    final Configurator c = context.lookupOrFail(ProxyConfiguration.class);
    final CNode node = c.describe(proxy, context);
    assertNotNull(node);
    Mapping mapping = node.asMapping();
    assertEquals(6, mapping.size());
    assertEquals("proxyhost", mapping.getScalarValue("name"));
}
 
Example #6
Source File: UpdateCenterConfiguratorTest.java    From configuration-as-code-plugin with MIT License 6 votes vote down vote up
@Test
@ConfiguredWithCode("UpdateCenter.yml")
public void shouldSetUpdateCenterSites() throws Exception {
    UpdateCenter updateCenter = j.jenkins.getUpdateCenter();
    List<UpdateSite> sites = updateCenter.getSites();
    assertEquals(2, sites.size());
    UpdateSite siteOne = sites.get(0);
    assertEquals("default", siteOne.getId());
    assertEquals("https://updates.jenkins.io/update-center.json", siteOne.getUrl());
    UpdateSite siteTwo = sites.get(1);
    assertEquals("experimental", siteTwo.getId());
    assertEquals("https://updates.jenkins.io/experimental/update-center.json", siteTwo.getUrl());

    ConfiguratorRegistry registry = ConfiguratorRegistry.get();
    ConfigurationContext context = new ConfigurationContext(registry);
    final Configurator c = context.lookupOrFail(UpdateCenter.class);
    final CNode node = c.describe(updateCenter, context);
    assertNotNull(node);
    Mapping site1 = node.asMapping().get("sites").asSequence().get(1).asMapping();
    assertEquals("experimental", site1.getScalarValue("id"));

}
 
Example #7
Source File: DataBoundConfiguratorTest.java    From configuration-as-code-plugin with MIT License 6 votes vote down vote up
@Test
public void exportYaml() throws Exception {
    Foo foo = new Foo("foo", true, 42);
    foo.setZot("zot");
    foo.setDbl(12.34);
    ConfiguratorRegistry registry = ConfiguratorRegistry.get();
    final Configurator c = registry.lookupOrFail(Foo.class);
    final ConfigurationContext context = new ConfigurationContext(registry);
    final CNode node = c.describe(foo, context);
    assertNotNull(node);
    assertTrue(node instanceof Mapping);
    Mapping map = (Mapping) node;
    assertEquals(map.get("foo").toString(), "foo");
    assertEquals(map.get("bar").toString(), "true");
    assertEquals(map.get("qix").toString(), "42");
    assertEquals(map.get("zot").toString(), "zot");
    assertEquals(map.get("dbl").toString(), "12.34");
    assertEquals(Util.toYamlString(map.get("foo")).trim(), "\"foo\"");
    assertEquals(Util.toYamlString(map.get("bar")).trim(), "true");
    assertEquals(Util.toYamlString(map.get("qix")).trim(), "42");
    assertEquals(Util.toYamlString(map.get("zot")).trim(), "\"zot\"");
    assertEquals(Util.toYamlString(map.get("dbl")).trim(), "12.34");
    assertFalse(map.containsKey("other"));
}
 
Example #8
Source File: PrimitiveConfiguratorTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Test
public void _enum() throws Exception {
    // Jenkins do register a StaplerConverter for it.
    Configurator<Node.Mode> c = registry.lookupOrFail(Node.Mode.class);
    final Node.Mode value = c.configure(new Scalar("NORMAL"), context);
    assertEquals(Node.Mode.NORMAL, value);

}
 
Example #9
Source File: AdminWhitelistRuleConfiguratorTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Test
@Issue("Issue #172")
@ConfiguredWithCode("AdminWhitelistRuleConfigurator/Agent2MasterSecurityKillSwitch_disabled.yml")
public void checkA2MAccessControl_disable() throws Exception {
    final Jenkins jenkins = Jenkins.get();
    MasterKillSwitchConfiguration config = jenkins.getDescriptorByType(MasterKillSwitchConfiguration.class);
    Assert.assertFalse("Agent → Master Access Control should be disabled", config.getMasterToSlaveAccessControl());
    AdminWhitelistRule rule = jenkins.getInjector().getInstance(AdminWhitelistRule.class);
    ConfiguratorRegistry registry = ConfiguratorRegistry.get();
    ConfigurationContext context = new ConfigurationContext(registry);
    final Configurator c = context.lookupOrFail(AdminWhitelistRule.class);
    final CNode node = c.describe(rule, context);
    final Mapping agent = node.asMapping();
    assertEquals("false", agent.get("enabled").toString());
}
 
Example #10
Source File: AdminWhitelistRuleConfiguratorTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Test
@Issue("Issue #172")
@ConfiguredWithCode("AdminWhitelistRuleConfigurator/Agent2MasterSecurityKillSwitch_enabled.yml")
public void checkA2MAccessControl_enabled() throws Exception {
    final Jenkins jenkins = Jenkins.get();
    MasterKillSwitchConfiguration config = jenkins.getDescriptorByType(MasterKillSwitchConfiguration.class);
    Assert.assertTrue("Agent → Master Access Control should be enabled", config.getMasterToSlaveAccessControl());
    AdminWhitelistRule rule = jenkins.getInjector().getInstance(AdminWhitelistRule.class);
    ConfiguratorRegistry registry = ConfiguratorRegistry.get();
    ConfigurationContext context = new ConfigurationContext(registry);
    final Configurator c = context.lookupOrFail(AdminWhitelistRule.class);
    final CNode node = c.describe(rule, context);
    final Mapping agent = node.asMapping();
    assertEquals("true", agent.get("enabled").toString());
}
 
Example #11
Source File: DataBoundConfiguratorTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Test
public void shouldExportArray() throws Exception {
    ArrayConstructor obj = new ArrayConstructor(new Foo[]{new Foo("", false, 0)});

    ConfiguratorRegistry registry = ConfiguratorRegistry.get();

    final Configurator c = registry.lookupOrFail(ArrayConstructor.class);
    final ConfigurationContext context = new ConfigurationContext(registry);
    CNode node = c.describe(obj, context);

    assertNotNull(node);
    assertTrue(node instanceof Mapping);
    Mapping map = (Mapping) node;
    assertEquals(map.get("anArray").toString(), "[{qix=0, bar=false, foo=}]");
}
 
Example #12
Source File: PrimitiveConfiguratorTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Test
public void _string_env_default() throws Exception {
    environment.set("NOT_THERE", "abc");
    Configurator c = registry.lookupOrFail(String.class);
    final Object value = c.configure(new Scalar("${ENV_FOR_TEST:-unsecured-token}"), context);
    assertEquals("unsecured-token", value);
}
 
Example #13
Source File: PrimitiveConfiguratorTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Test
public void _string_env() throws Exception {
    environment.set("ENV_FOR_TEST", "abc");
    Configurator c = registry.lookupOrFail(String.class);
    final Object value = c.configure(new Scalar("${ENV_FOR_TEST}"), context);
    assertEquals("abc", value);
}
 
Example #14
Source File: PrimitiveConfiguratorTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Test
public void _Integer_env() throws Exception {
    environment.set("ENV_FOR_TEST", "123");
    Configurator c = registry.lookupOrFail(Integer.class);
    final Object value = c.configure(new Scalar("${ENV_FOR_TEST}"), context);
    assertEquals(123, (int) value);
}
 
Example #15
Source File: PrimitiveConfiguratorTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Test
public void _enum2() throws Exception {
    // No explicit converter set by jenkins
    Configurator<TimeUnit> c = registry.lookupOrFail(TimeUnit.class);
    final TimeUnit value = c.configure(new Scalar("DAYS"), context);
    assertEquals(TimeUnit.DAYS, value);

}
 
Example #16
Source File: HeteroDescribableConfigurator.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@NonNull
@Override
public List<Configurator<T>> getConfigurators(ConfigurationContext context) {
    return getDescriptors()
        .flatMap(d -> lookupConfigurator(context, descriptorClass(d)))
        .append(this)
        .toJavaList();
}
 
Example #17
Source File: MavenConfigurator.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@NonNull
@Override
public Set<Attribute<GlobalMavenConfig,?>> describe() {
    final Set<Attribute<GlobalMavenConfig,?>> attributes = super.describe();
    final Descriptor descriptor = Jenkins.get().getDescriptorOrDie(Maven.class);
    final Configurator<Descriptor> task = new DescriptorConfigurator(descriptor);

    for (Attribute attribute : task.describe()) {
        attributes.add(new Attribute<GlobalMavenConfig,Object>(attribute.getName(), attribute.getType())
            .multiple(attribute.isMultiple())
            .getter(g -> attribute.getValue(descriptor))
            .setter((g,v) -> attribute.setValue(descriptor,v)));
    }
    return attributes;
}
 
Example #18
Source File: DefaultConfiguratorRegistry.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
/**
 * Looks for a configurator for exact type.
 * @param type Type
 * @return Configurator or {@code null} if it is not found
 */
@Override
@CheckForNull
public Configurator lookup(Type type) {
    try {
        return cache.get(type);
    } catch (ExecutionException e) {
        return null;
    }
}
 
Example #19
Source File: DefaultConfiguratorRegistry.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
/**
 * Looks for a configurator for exact type.
 * @param type Type
 * @return Configurator
 * @throws ConfiguratorException Configurator is not found
 */
@Override
@NonNull
public Configurator lookupOrFail(Type type) throws ConfiguratorException {
    try {
        return cache.get(type);
    } catch (ExecutionException e) {
        throw (ConfiguratorException) e.getCause();
    }
}
 
Example #20
Source File: GlobalConfigurationCategoryConfigurator.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
public static boolean reportDescriptorWithoutSetters(Configurator c) {
    if (c.describe().isEmpty()) {
        LOGGER.fine(c.getTarget().getName() +
                " has a global view but CasC didn't detect any configurable attribute; see: https://jenkins.io/redirect/casc-requirements/");
    }
    return true;
}
 
Example #21
Source File: HeteroDescribableConfigurator.java    From configuration-as-code-plugin with MIT License 4 votes vote down vote up
private Option<Configurator<T>> lookupConfigurator(ConfigurationContext context, Class<?> descriptor) {
    return Option.of(context.lookup(descriptor));
}
 
Example #22
Source File: PrimitiveConfiguratorTest.java    From configuration-as-code-plugin with MIT License 4 votes vote down vote up
@Test
public void _string() throws Exception {
    Configurator c = registry.lookupOrFail(String.class);
    final Object value = c.configure(new Scalar("abc"), context);
    assertEquals("abc", value);
}
 
Example #23
Source File: HeteroDescribableConfigurator.java    From configuration-as-code-plugin with MIT License 4 votes vote down vote up
private Configurator<T> forceLookupConfigurator(ConfigurationContext context, Descriptor<T> descriptor) {
    Class<T> klazz = descriptorClass(descriptor);
    return lookupConfigurator(context, klazz)
            .getOrElseThrow(() -> new IllegalStateException("No configurator implementation to manage " + klazz));
}
 
Example #24
Source File: GitToolConfigurator.java    From git-client-plugin with MIT License 4 votes vote down vote up
@NonNull
@Override
public List<Configurator<GitTool>> getConfigurators(ConfigurationContext context) {
    return Collections.singletonList(this);
}
 
Example #25
Source File: HeteroDescribableConfigurator.java    From configuration-as-code-plugin with MIT License 4 votes vote down vote up
private T doConfigure(ConfigurationContext context, Configurator<T> configurator, CNode subConfig) {
    return unchecked(() -> configurator.configure(subConfig, context)).apply();
}
 
Example #26
Source File: HeteroDescribableConfigurator.java    From configuration-as-code-plugin with MIT License 4 votes vote down vote up
@SuppressWarnings("unchecked")
private CNode convertToNode(ConfigurationContext context, Configurator configurator, Describable instance) {
    return unchecked(() -> configurator.describe(instance, context)).apply();
}
 
Example #27
Source File: PrimitiveConfigurator.java    From configuration-as-code-plugin with MIT License 4 votes vote down vote up
@NonNull
@Override
public List<Configurator> getConfigurators(ConfigurationContext context) {
    return Collections.emptyList();
}
 
Example #28
Source File: DefaultConfiguratorRegistry.java    From configuration-as-code-plugin with MIT License 4 votes vote down vote up
@Override
public Configurator load(@NonNull Type type) throws Exception {
    final Configurator configurator = internalLookup(type);
    if (configurator == null) throw new ConfiguratorException("Cannot find configurator for type " + type);
    return configurator;
}
 
Example #29
Source File: DefaultConfiguratorRegistry.java    From configuration-as-code-plugin with MIT License 4 votes vote down vote up
private Configurator internalLookup(Type type) {
    Class clazz = Types.erasure(type);

    final Jenkins jenkins = Jenkins.get();
    final ExtensionList<Configurator> l = jenkins.getExtensionList(Configurator.class);
    for (Configurator c : l) {
        if (c.canConfigure(clazz)) {
            // this type has a dedicated Configurator implementation
            return c;
        }
    }

    //TODO: Only try to cast if we can actually get the parameterized type
    if (Collection.class.isAssignableFrom(clazz) && type instanceof ParameterizedType) {
        ParameterizedType pt = (ParameterizedType) type;
        Type actualType = pt.getActualTypeArguments()[0];
        if (actualType instanceof WildcardType) {
            actualType = ((WildcardType) actualType).getUpperBounds()[0];
        }
        if (actualType instanceof ParameterizedType) {
            actualType = ((ParameterizedType) actualType).getRawType();
        }
        if (!(actualType instanceof Class)) {
            throw new IllegalStateException("Can't handle " + type);
        }
        return lookup(actualType);
    }

    if (Configurable.class.isAssignableFrom(clazz)) {
        return new ConfigurableConfigurator(clazz);
    }

    if (Descriptor.class.isAssignableFrom(clazz)) {
        ExtensionList extensions = jenkins.getExtensionList(clazz);
        if (!extensions.isEmpty()) {
            return new DescriptorConfigurator((Descriptor) extensions.get(0));
        }
    }

    if (DataBoundConfigurator.getDataBoundConstructor(clazz) != null) {
        return new DataBoundConfigurator(clazz);
    }

    if (Modifier.isAbstract(clazz.getModifiers()) && Describable.class.isAssignableFrom(clazz)) {
        // this is a jenkins Describable component, with various implementations
        return new HeteroDescribableConfigurator(clazz);
    }

    if (Extension.class.isAssignableFrom(clazz)) {
        return new ExtensionConfigurator(clazz);
    }

    if (Stapler.lookupConverter(clazz) != null) {
        return new PrimitiveConfigurator(clazz);
    }

    if (clazz.isEnum()) {
        return new EnumConfigurator(clazz);
    }

    LOGGER.warning("Configuration-as-Code can't handle type "+ type);
    return null;
}
 
Example #30
Source File: PrimitiveConfiguratorTest.java    From configuration-as-code-plugin with MIT License 4 votes vote down vote up
@Test
public void _int_env_default() throws Exception {
    Configurator c = registry.lookupOrFail(Integer.class);
    final Object value = c.configure(new Scalar("${ENV_FOR_TEST:-123}"), context);
    assertEquals(123, value);
}