io.jenkins.plugins.casc.ConfigurationContext Java Examples

The following examples show how to use io.jenkins.plugins.casc.ConfigurationContext. 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: ProxyConfiguratorTest.java    From configuration-as-code-plugin with MIT License 6 votes vote down vote up
@Test
@ConfiguredWithCode("Proxy.yml")
public void describeProxyConfig() throws Exception {
    ConfiguratorRegistry registry = ConfiguratorRegistry.get();
    ConfigurationContext context = new ConfigurationContext(registry);
    final CNode configNode = getProxyNode(context);

    Secret password = requireNonNull(Secret.decrypt(getProxyNode(context).getScalarValue("secretPassword")));

    final String yamlConfig = Util.toYamlString(configNode);
    assertEquals(String.join("\n",
            "name: \"proxyhost\"",
            "noProxyHost: \"externalhost\"",
            "port: 80",
            "secretPassword: \"" + password.getEncryptedValue() + "\"",
            "testUrl: \"http://google.com\"",
            "userName: \"login\"",
            ""
    ), yamlConfig);
}
 
Example #2
Source File: HeteroDescribableConfigurator.java    From configuration-as-code-plugin with MIT License 6 votes vote down vote up
@CheckForNull
@Override
public CNode describe(T instance, ConfigurationContext context) {
    Predicate<CNode> isScalar = node -> node.getType().equals(MAPPING)
        && unchecked(node::asMapping).apply().size() == 0;
    return lookupConfigurator(context, instance.getClass())
            .map(configurator -> convertToNode(context, configurator, instance))
            .filter(Objects::nonNull)
            .map(node -> {
                if (isScalar.test(node)) {
                    return new Scalar(preferredSymbol(instance.getDescriptor()));
                } else {
                    final Mapping mapping = new Mapping();
                    mapping.put(preferredSymbol(instance.getDescriptor()), node);
                    return mapping;
                }
            }).getOrNull();
}
 
Example #3
Source File: YamlUtils.java    From configuration-as-code-plugin with MIT License 6 votes vote down vote up
public static Node read(YamlSource source, Reader reader, ConfigurationContext context) throws IOException {
    LoaderOptions loaderOptions = new LoaderOptions();
    loaderOptions.setMaxAliasesForCollections(context.getYamlMaxAliasesForCollections());
    Composer composer = new Composer(
        new ParserImpl(new StreamReaderWithSource(source, reader)),
        new Resolver(),
        loaderOptions);
    try {
        return composer.getSingleNode();
    } catch (YAMLException e) {
        if (e.getMessage().startsWith("Number of aliases for non-scalar nodes exceeds the specified max")) {
            throw new ConfiguratorException(String.format(
                "%s%nYou can increase the maximum by setting an environment variable or property%n  ENV: %s=\"100\"%n  PROPERTY: -D%s=\"100\"",
                e.getMessage(), ConfigurationContext.CASC_YAML_MAX_ALIASES_ENV,
                ConfigurationContext.CASC_YAML_MAX_ALIASES_PROPERTY));
        }
        throw e;
    }
}
 
Example #4
Source File: YamlUtils.java    From configuration-as-code-plugin with MIT License 6 votes vote down vote up
public static Node merge(List<YamlSource> sources,
    ConfigurationContext context) throws ConfiguratorException {
    Node root = null;
    for (YamlSource<?> source : sources) {
        try (Reader reader = reader(source)) {
            final Node node = read(source, reader, context);

            if (root == null) {
                root = node;
            } else {
                if (node != null) {
                    merge(root, node, source.toString());
                }
            }
        } catch (IOException io) {
            throw new ConfiguratorException("Failed to read " + source, io);
        }
    }

    return root;
}
 
Example #5
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 #6
Source File: PrimitiveConfigurator.java    From configuration-as-code-plugin with MIT License 6 votes vote down vote up
@CheckForNull
@Override
public CNode describe(Object instance, ConfigurationContext context) {

    if (instance == null) return null;

    if (instance instanceof Number) {
        return new Scalar((Number) instance);
    }
    if (instance instanceof Boolean) {
        return new Scalar((Boolean) instance);
    }
    if (instance instanceof Secret) {
        // Secrets are sensitive, but they do not need masking since they are exported in the encrypted form
        return new Scalar(((Secret) instance).getEncryptedValue()).encrypted(true);
    }
    if (target.isEnum()) {
        return new Scalar((Enum) instance);
    }

    return new Scalar(SecretSourceResolver.encode(String.valueOf(instance)));
}
 
Example #7
Source File: ConfigurationAsCodeTest.java    From oic-auth-plugin with MIT License 6 votes vote down vote up
@Test
public void testExport() throws Exception {
    ConfigurationContext context = new ConfigurationContext(ConfiguratorRegistry.get());
    CNode yourAttribute = getJenkinsRoot(context).get("securityRealm").asMapping().get("oic");

    String exported = toYamlString(yourAttribute);

    // secrets are always changing. so, just remove them before there's a better solution
    String[] lines = exported.split("\n");
    List<String> lineList = new ArrayList<>();
    for(String line : lines) {
        if(!line.contains("Secret")) {
            lineList.add(line);
        }
    }
    String cleanedExported = String.join("\n", lineList);
    String expected = toStringFromYamlFile(this, "ConfigurationAsCodeExport.yml");

    assertThat(cleanedExported, is(expected));
}
 
Example #8
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 #9
Source File: DataBoundConfiguratorTest.java    From configuration-as-code-plugin with MIT License 6 votes vote down vote up
@Test
@Issue("PR #838, Issue #222")
public void export_mapping_should_not_be_null() throws Exception {
    j.createFreeStyleProject("testJob1");
    ConfigurationAsCode casc = ConfigurationAsCode.get();
    casc.configure(this.getClass().getResource("DataBoundDescriptorNonNull.yml")
            .toString());

    ConfiguratorRegistry registry = ConfiguratorRegistry.get();
    ConfigurationContext context = new ConfigurationContext(registry);
    final Mapping configNode = getJenkinsRoot(context);
    final CNode viewsNode = configNode.get("views");
    Mapping listView = viewsNode.asSequence().get(1).asMapping().get("list").asMapping();
    Mapping otherListView = viewsNode.asSequence().get(2).asMapping().get("list").asMapping();
    Sequence listViewColumns = listView.get("columns").asSequence();
    Sequence otherListViewColumns = otherListView.get("columns").asSequence();
    assertNotNull(listViewColumns);
    assertEquals(6, listViewColumns.size());
    assertNotNull(otherListViewColumns);
    assertEquals(7, otherListViewColumns.size());
    assertEquals("loggedInUsersCanDoAnything", configNode.getScalarValue("authorizationStrategy"));
    assertEquals("plainText", configNode.getScalarValue("markupFormatter"));
}
 
Example #10
Source File: DataBoundConfiguratorTest.java    From configuration-as-code-plugin with MIT License 6 votes vote down vote up
@Test
public void shouldThrowConfiguratorException() {
    Mapping config = new Mapping();
    config.put("foo", "foo");
    config.put("bar", "abcd");
    config.put("qix", "99");
    ConfiguratorRegistry registry = ConfiguratorRegistry.get();
    try {
        registry.lookupOrFail(Foo.class).configure(config, new ConfigurationContext(registry));
        fail("above action is excepted to throw ConfiguratorException!");
    } catch (ConfiguratorException e) {
        assertThat(e.getMessage(), is("foo: Failed to construct instance of class io.jenkins.plugins.casc.impl.configurators.DataBoundConfiguratorTest$Foo.\n" +
                " Constructor: public io.jenkins.plugins.casc.impl.configurators.DataBoundConfiguratorTest$Foo(java.lang.String,boolean,int).\n" +
                " Arguments: [java.lang.String, java.lang.Boolean, java.lang.Integer].\n" +
                " Expected Parameters: foo java.lang.String, bar boolean, qix int"));
    }
}
 
Example #11
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 #12
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 #13
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 #14
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 #15
Source File: GitToolConfiguratorJenkinsRuleTest.java    From git-client-plugin with MIT License 6 votes vote down vote up
@Test
public void testDescribeGitToolEmptyProperties() throws Exception {
    String gitName = "git-2.19.1-name";
    String gitHome = "/opt/git-2.19.1/bin/git";

    ConfiguratorRegistry registry = ConfiguratorRegistry.get();
    ConfigurationContext context = new ConfigurationContext(registry);

    // Intentionally empty properties passed to GitTool constructor
    List<ToolProperty<ToolInstallation>> gitToolProperties = new ArrayList<>();

    GitTool gitTool = new GitTool(gitName, gitHome, gitToolProperties);

    CNode cNode = gitToolConfigurator.describe(gitTool, context);

    assertThat(cNode, is(notNullValue()));
    assertThat(cNode.getType(), is(CNode.Type.MAPPING));
    Mapping cNodeMapping = cNode.asMapping();
    assertThat(cNodeMapping.getScalarValue("name"), is(gitName));
    assertThat(cNodeMapping.getScalarValue("home"), is(gitHome));
}
 
Example #16
Source File: YamlUtils.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
/**
 * Load configuration-as-code model from a set of Yaml sources, merging documents
 */
public static Mapping loadFrom(List<YamlSource> sources,
    ConfigurationContext context) throws ConfiguratorException {
    if (sources.isEmpty()) return Mapping.EMPTY;
    final Node merged = merge(sources, context);
    if (merged == null) {
        LOGGER.warning("configuration-as-code yaml source returned an empty document.");
        return Mapping.EMPTY;
    }
    return loadFrom(merged);
}
 
Example #17
Source File: DataBoundConfiguratorTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Test
@Issue("SECURITY-1497")
public void shouldNotLogSecretsForUndefinedConstructors() throws Exception {
    Mapping config = new Mapping();
    config.put("secret", "mySecretValue");
    ConfiguratorRegistry registry = ConfiguratorRegistry.get();
    registry.lookupOrFail(SecretHolderWithString.class).configure(config, new ConfigurationContext(registry));
    assertLogContains(logging, "secret");
    assertNotInLog(logging, "mySecretValue");
}
 
Example #18
Source File: DataBoundConfiguratorTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Test
public void shouldNotLogSecrets() throws Exception {
    Mapping config = new Mapping();
    config.put("secret", "mySecretValue");
    ConfiguratorRegistry registry = ConfiguratorRegistry.get();
    registry.lookupOrFail(SecretHolder.class).configure(config, new ConfigurationContext(registry));
    assertLogContains(logging, "secret");
    assertNotInLog(logging, "mySecretValue");
}
 
Example #19
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 #20
Source File: DataBoundConfiguratorTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Test
public void configureWithEmptySet() throws Exception {
    Mapping config = new Mapping();
    ConfiguratorRegistry registry = ConfiguratorRegistry.get();
    final Bar configured = (Bar) registry.lookupOrFail(Bar.class).configure(config, new ConfigurationContext(registry));
    Set<String> strings = configured.getStrings();
    assertEquals(0, strings.size());
}
 
Example #21
Source File: DataBoundConfiguratorTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Test
public void configureWithSets() throws Exception {
    Mapping config = new Mapping();
    Sequence sequence = new Sequence();
    sequence.add(new Scalar("bar"));
    sequence.add(new Scalar("foo"));
    config.put("strings", sequence);
    ConfiguratorRegistry registry = ConfiguratorRegistry.get();
    final Bar configured = (Bar) registry.lookupOrFail(Bar.class).configure(config, new ConfigurationContext(registry));
    Set<String> strings = configured.getStrings();
    assertTrue(strings.contains("foo"));
    assertTrue(strings.contains("bar"));
    assertFalse(strings.contains("baz"));
}
 
Example #22
Source File: GitToolConfiguratorTest.java    From git-client-plugin with MIT License 5 votes vote down vote up
@Test
public void testInstance() throws Exception {
    Mapping mapping = null;
    ConfigurationContext context = new ConfigurationContext(null);
    GitTool gitTool = gitToolConfigurator.instance(mapping, context);
    assertThat(gitTool, is(instanceOf(GitTool.class)));
    assertThat(gitTool.getName(), is("Default"));
    assertThat(gitTool.getHome(), is(""));
}
 
Example #23
Source File: DataBoundConfiguratorTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Test
public void configure_databound() throws Exception {
    Mapping config = new Mapping();
    config.put("foo", "foo");
    config.put("bar", "true");
    config.put("qix", "123");
    config.put("zot", "DataBoundSetter");
    ConfiguratorRegistry registry = ConfiguratorRegistry.get();
    final Foo configured = (Foo) registry.lookupOrFail(Foo.class).configure(config, new ConfigurationContext(registry));
    assertEquals("foo", configured.foo);
    assertTrue(configured.bar);
    assertEquals(123, configured.qix);
    assertEquals("DataBoundSetter", configured.zot);
    assertThat(configured.initialized, is(true));
}
 
Example #24
Source File: ExportTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
public <T> String export(DataBoundConfigurator<T> configurator, T object) throws Exception {
    ConfigurationAsCode casc = ConfigurationAsCode.get();
    ConfiguratorRegistry registry = ConfiguratorRegistry.get();
    ConfigurationContext context = new ConfigurationContext(registry);

    final CNode config = configurator.describe(object, context);
    final Node valueNode = casc.toYaml(config);

    try (StringWriter writer = new StringWriter()) {
        ConfigurationAsCode.serializeYamlNode(valueNode, writer);
        return writer.toString();
    } catch (IOException e) {
        throw new YAMLException(e);
    }
}
 
Example #25
Source File: GitToolConfiguratorTest.java    From git-client-plugin with MIT License 5 votes vote down vote up
@Test
public void testInstanceJGitToolWithHome() throws Exception {
    Mapping mapping = new Mapping();
    mapping.put("name", JGitTool.MAGIC_EXENAME);
    mapping.put("home", "unused-value-for-home"); // Will log a message
    ConfigurationContext context = new ConfigurationContext(null);
    GitTool gitTool = gitToolConfigurator.instance(mapping, context);
    assertThat(gitTool, is(instanceOf(JGitTool.class)));
    assertThat(gitTool, is(not(instanceOf(JGitApacheTool.class))));
}
 
Example #26
Source File: GitHubAppCredentialsJCasCCompatibilityTest.java    From github-branch-source-plugin with MIT License 5 votes vote down vote up
private Sequence getCredentials() throws Exception {
    CredentialsRootConfigurator root = Jenkins.get()
            .getExtensionList(CredentialsRootConfigurator.class).get(0);

    ConfiguratorRegistry registry = ConfiguratorRegistry.get();
    ConfigurationContext context = new ConfigurationContext(registry);
    Mapping configNode = Objects
            .requireNonNull(root.describe(root.getTargetComponent(context), context)).asMapping();
    Mapping domainCredentials = configNode
            .get("system").asMapping().get("domainCredentials")
            .asSequence()
            .get(0).asMapping();
    return domainCredentials.get("credentials").asSequence();
}
 
Example #27
Source File: AdminWhitelistRuleConfigurator.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Override
protected AdminWhitelistRule instance(Mapping mapping, ConfigurationContext context) {
    Injector injector = Jenkins.get().getInjector();
    if (injector == null) {
        throw new IllegalStateException("Required dependency injection container is not present");
    }
    return injector.getInstance(AdminWhitelistRule.class);
}
 
Example #28
Source File: ConfigurableConfigurator.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Override
public T check(CNode config, ConfigurationContext context) throws ConfiguratorException {
    try {
        final T instance = target.newInstance();
        instance.check(config);
        return instance;
    } catch (InstantiationException | IllegalAccessException e) {
        throw new ConfiguratorException("Cannot instantiate Configurable "+target+" with default constructor", e);
    }
}
 
Example #29
Source File: ConfigurableConfigurator.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@NonNull
@Override
public T configure(CNode config, ConfigurationContext context) throws ConfiguratorException {
    try {
        final T instance = target.newInstance();
        instance.configure(config);
        return instance;
    } catch (InstantiationException | IllegalAccessException e) {
        throw new ConfiguratorException("Cannot instantiate Configurable "+target+" with default constructor", e);
    }
}
 
Example #30
Source File: DataBoundConfiguratorTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Test
public void classParametersAreNonnullByDefault() throws Exception {
    Mapping config = new Mapping();
    ConfiguratorRegistry registry = ConfiguratorRegistry.get();
    final ClassParametersAreNonnullByDefault configured = (ClassParametersAreNonnullByDefault) registry
                                                    .lookupOrFail(ClassParametersAreNonnullByDefault.class)
                                                    .configure(config, new ConfigurationContext(registry));
    assertTrue(configured.getStrings().isEmpty());
}