io.jenkins.plugins.casc.model.CNode Java Examples

The following examples show how to use io.jenkins.plugins.casc.model.CNode. 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: DataBoundConfigurator.java    From configuration-as-code-plugin with MIT License 6 votes vote down vote up
@NonNull
@Override
public T configure(CNode c, ConfigurationContext context) throws ConfiguratorException {
    T object = super.configure(c, context);

    for (Method method : target.getMethods()) {
        if (method.getParameterCount() == 0 && method.getAnnotation(PostConstruct.class) != null) {
            try {
                method.invoke(object, null);
            } catch (IllegalAccessException | InvocationTargetException e) {
                throw new ConfiguratorException(this, "Failed to invoke configurator method " + method, e);
            }
        }
    }
    return object;
}
 
Example #2
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 #3
Source File: GitToolConfigurator.java    From git-client-plugin with MIT License 6 votes vote down vote up
@Override
protected GitTool instance(Mapping mapping, @NonNull ConfigurationContext context) throws ConfiguratorException {
    if (mapping == null) {
        return new GitTool("Default", "", instantiateProperties(null, context));
    }
    final CNode mproperties = mapping.remove("properties");
    final String name = mapping.getScalarValue("name");
    if (JGitTool.MAGIC_EXENAME.equals(name)) {
        if (mapping.remove("home") != null) { //Ignored but could be added, so removing to not fail handleUnknown
            logger.warning("property `home` is ignored for `" + JGitTool.MAGIC_EXENAME + "`");
        }
        return new JGitTool(instantiateProperties(mproperties, context));
    } else if (JGitApacheTool.MAGIC_EXENAME.equals(name)) {
        if (mapping.remove("home") != null) { //Ignored but could be added, so removing to not fail handleUnknown
            logger.warning("property `home` is ignored for `" + JGitApacheTool.MAGIC_EXENAME + "`");
        }
        return new JGitApacheTool(instantiateProperties(mproperties, context));
    } else {
        if (mapping.get("home") == null) {
            throw new ConfiguratorException(this, "Home required for cli git configuration.");
        }
        String home = mapping.getScalarValue("home");
        return new GitTool(name, home, instantiateProperties(mproperties, context));
    }
}
 
Example #4
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 #5
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 #6
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 #7
Source File: ConfigurationAsCodeTest.java    From configuration-as-code-plugin with MIT License 6 votes vote down vote up
@Test
@ConfiguredWithCode("multi-line1.yml")
public void multiline_literal_stays_literal_in_export() throws Exception {
    assertEquals("Welcome to our build server.\n\n"
            + "This Jenkins is 100% configured and managed 'as code'.\n",
        j.jenkins.getSystemMessage());

    ConfiguratorRegistry registry = ConfiguratorRegistry.get();
    ConfigurationContext context = new ConfigurationContext(registry);
    CNode systemMessage = getJenkinsRoot(context).get("systemMessage");
    String exported = toYamlString(systemMessage);
    String expected = "|\n"
        + "  Welcome to our build server.\n\n"
        + "  This Jenkins is 100% configured and managed 'as code'.\n";
    assertThat(exported, is(expected));
}
 
Example #8
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 #9
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 #10
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 #11
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 #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: Configurator.java    From configuration-as-code-plugin with MIT License 6 votes vote down vote up
/**
 * Describe Structure of the attributes, as required by the schema.
 * @param instance
 * @param context
 * @since 1.35
 * @return CNode describing the attributes.
 */
@CheckForNull
default CNode describeStructure(T instance, ConfigurationContext context)
    throws Exception {
    Mapping mapping = new Mapping();
    for (Attribute attribute : getAttributes()) {
        if (context.getMode().equals("JSONSchema")) {
            attribute.setJsonSchema(true);
        }
        CNode value = attribute.describeForSchema(instance, context);
        if (value != null) {
            mapping.put(attribute.getName(), attribute.getType().getSimpleName());
        }
    }
    return mapping;
}
 
Example #14
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 #15
Source File: Configurator.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
/**
 * Describe a component as a Configuration Nodes {@link CNode} to be exported as yaml.
 * Only export attributes which are <b>not</b> set to default value.
 */
@CheckForNull
default CNode describe(T instance, ConfigurationContext context) throws Exception {
    Mapping mapping = new Mapping();
    for (Attribute attribute : getAttributes()) {
        CNode value = attribute.describe(instance, context);
        if (value != null) {
            mapping.put(attribute.getName(), value);
        }
    }
    return mapping;
}
 
Example #16
Source File: GitToolConfiguratorTest.java    From git-client-plugin with MIT License 5 votes vote down vote up
@Test
public void testDescribeGitToolWithoutProperties() throws Exception {
    String gitName = "git-name";
    String gitHome = "/opt/git-2.23.0/bin/git";
    GitTool gitTool = new GitTool(gitName, gitHome, null);
    CNode cNode = gitToolConfigurator.describe(gitTool, NULL_CONFIGURATION_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 #17
Source File: ConfigurationAsCodeTest.java    From lockable-resources-plugin with MIT License 5 votes vote down vote up
@Test
public void should_support_configuration_export() throws Exception {
  ConfiguratorRegistry registry = ConfiguratorRegistry.get();
  ConfigurationContext context = new ConfigurationContext(registry);
  CNode yourAttribute = getUnclassifiedRoot(context).get("lockableResourcesManager");
  String exported = toYamlString(yourAttribute);
  String expected = toStringFromYamlFile(this, "casc_expected_output.yml");

  assertThat(exported, is(expected));
}
 
Example #18
Source File: GlobalNodePropertiesTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Test
public void export() throws Exception {
    ConfiguratorRegistry registry = ConfiguratorRegistry.get();
    ConfigurationContext context = new ConfigurationContext(registry);
    CNode yourAttribute = getJenkinsRoot(context).get("globalNodeProperties");

    String exported = toYamlString(yourAttribute);

    String expected = toStringFromYamlFile(this, "GlobalNodePropertiesTestExpected.yml");

    assertThat(exported, is(expected));
}
 
Example #19
Source File: JdkConfiguratorTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Test
public void export_jdk_tool() throws Exception {
    ConfiguratorRegistry registry = ConfiguratorRegistry.get();
    ConfigurationContext context = new ConfigurationContext(registry);
    CNode yourAttribute = getToolRoot(context).get("jdk");

    String exported = toYamlString(yourAttribute);

    String expected = toStringFromYamlFile(this, "JdkConfiguratorTestExpected.yml");

    assertThat(exported, is(expected));
}
 
Example #20
Source File: CredentialsTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@ConfiguredWithCode("GlobalCredentials.yml")
@Test
public void testExportSSHCredentials() throws Exception {
    ConfiguratorRegistry registry = ConfiguratorRegistry.get();
    ConfigurationContext context = new ConfigurationContext(registry);
    CredentialsRootConfigurator root = ExtensionList.lookupSingleton(CredentialsRootConfigurator.class);

    CNode node = root.describe(root.getTargetComponent(context), context);
    assertNotNull(node);
    final Mapping mapping = node.asMapping();

    Mapping sshCredential = mapping.get("system")
            .asMapping()
            .get("domainCredentials")
            .asSequence().get(0)
            .asMapping().get("credentials")
            .asSequence().get(1)
            .asMapping().get("basicSSHUserPrivateKey").asMapping();

    assertThat(sshCredential.getScalarValue("scope"), is("SYSTEM"));
    assertThat(sshCredential.getScalarValue("id"), is("agent-private-key"));
    assertThat(sshCredential.getScalarValue("username"), is("agentuser"));

    String passphrase = sshCredential.getScalarValue("passphrase");
    assertThat(passphrase, not("password"));
    assertThat(requireNonNull(Secret.decrypt(passphrase), "Failed to decrypt the password from " + passphrase)
            .getPlainText(), is("password"));

    String sshKeyExported = sshCredential.get("privateKeySource")
            .asMapping()
            .get("directEntry")
            .asMapping()
            .get("privateKey")
            .asScalar()
            .getValue();

    assertThat(sshKeyExported, not("sp0ds9d+skkfjf"));
    assertThat(requireNonNull(Secret.decrypt(sshKeyExported)).getPlainText(), is("sp0ds9d+skkfjf"));
}
 
Example #21
Source File: ToolDefaultPropertiesExportBlacklistTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Test
@Issue("JENKINS-57122")
public void export_tool_configuration() throws Exception {
    ConfiguratorRegistry registry = ConfiguratorRegistry.get();
    ConfigurationContext context = new ConfigurationContext(registry);
    CNode yourAttribute = getToolRoot(context);

    String exported = toYamlString(yourAttribute).replaceAll("git\\.exe", "git");

    String expected = toStringFromYamlFile(this, "ToolDefaultPropertiesExportBlacklistExpected.yml");

    assertThat(exported, is(expected));
}
 
Example #22
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 #23
Source File: ConfigurationAsCodeTest.java    From folder-auth-plugin with MIT License 5 votes vote down vote up
@Test
@ConfiguredWithCode("config.yml")
public void configurationExportTest() throws Exception {
    ConfiguratorRegistry registry = ConfiguratorRegistry.get();
    ConfigurationContext context = new ConfigurationContext(registry);
    CNode yourAttribute = getJenkinsRoot(context).get("authorizationStrategy").asMapping()
        .get("folderBased");

    String exported = toYamlString(yourAttribute);
    String expected = toStringFromYamlFile(this, "expected.yml");

    assertThat(exported, is(expected));
}
 
Example #24
Source File: JNLPLauncherConfigurator.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Override
protected JNLPLauncher instance(Mapping config, ConfigurationContext context) throws ConfiguratorException {
    try {
        return super.instance(config, context);
    } catch (ConfiguratorException e) {
        // see https://issues.jenkins.io/browse/JENKINS-51603
        final CNode tunnel = config.get("tunnel");
        final CNode vmargs = config.get("vmargs");
        return new JNLPLauncher(tunnel != null ? tunnel.asScalar().getValue() : null,
                                vmargs != null ? vmargs.asScalar().getValue() : null);
    }
}
 
Example #25
Source File: ConfigurationAsCodeTest.java    From github-autostatus-plugin with MIT License 5 votes vote down vote up
@Test
public void should_support_configuration_export() throws Exception {
    ConfiguratorRegistry registry = ConfiguratorRegistry.get();
    ConfigurationContext context = new ConfigurationContext(registry);
    CNode buildStatusConfigAttribute = getUnclassifiedRoot(context).get("buildStatusConfig");

    String exported = toYamlString(buildStatusConfigAttribute);

    String expected = toStringFromYamlFile(this, "configuration-as-code-expected.yml");

    assertThat(exported, is(expected));
}
 
Example #26
Source File: TerraformTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Test
public void export_terraform_tool() throws Exception {
    ConfiguratorRegistry registry = ConfiguratorRegistry.get();
    ConfigurationContext context = new ConfigurationContext(registry);
    CNode yourAttribute = getToolRoot(context).get("terraform");

    String exported = toYamlString(yourAttribute);

    String expected = toStringFromYamlFile(this, "TerraformConfiguratorTestExpected.yml");

    assertThat(exported, is(expected));
}
 
Example #27
Source File: GlobalConfigurationCategoryConfigurator.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@CheckForNull
@Override
public CNode describe(GlobalConfigurationCategory instance, ConfigurationContext context) {

    final Mapping mapping = new Mapping();
    Jenkins.get().getExtensionList(Descriptor.class).stream()
        .filter(this::filterDescriptors)
        .forEach(d -> describe(d, mapping, context));
    return mapping;
}
 
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: GitToolConfiguratorTest.java    From git-client-plugin with MIT License 5 votes vote down vote up
@Test
public void testDescribeJGitApacheTool() throws Exception {
    GitTool gitTool = new JGitApacheTool();
    CNode cNode = gitToolConfigurator.describe(gitTool, NULL_CONFIGURATION_CONTEXT);
    assertThat(cNode, is(notNullValue()));
    assertThat(cNode.getType(), is(CNode.Type.MAPPING));
    Mapping cNodeMapping = cNode.asMapping();
    assertThat(cNodeMapping.getScalarValue("name"), is(JGitApacheTool.MAGIC_EXENAME));
}
 
Example #30
Source File: GlobalConfigurationCategoryConfigurator.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
private void describe(Descriptor d, Mapping mapping, ConfigurationContext context) {
    final DescriptorConfigurator c = new DescriptorConfigurator(d);
    try {
        final CNode node = c.describe(d, context);
        if (node != null) mapping.put(c.getName(), node);
    } catch (Exception e) {
        final Scalar scalar = new Scalar(
            "FAILED TO EXPORT\n" + d.getClass().getName() + " : " + printThrowable(e));
        mapping.put(c.getName(), scalar);
    }
}