io.jenkins.plugins.casc.ConfigurationAsCode Java Examples

The following examples show how to use io.jenkins.plugins.casc.ConfigurationAsCode. 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: 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 #2
Source File: CascJmhBenchmarkState.java    From configuration-as-code-plugin with MIT License 6 votes vote down vote up
/**
 * Setups the Jenkins instance using configuration as code
 * available through the {@link CascJmhBenchmarkState#getResourcePath()}.
 *
 * @throws ConfiguratorException when unable to configure
 */
@Override
public void setup() throws Exception {
    Class<?> enclosingClass = getEnclosingClass();

    if (!enclosingClass.isAnnotationPresent(JmhBenchmark.class)) {
        throw new IllegalStateException("The enclosing class must be annotated with @JmhBenchmark");
    }

    String config = Objects.requireNonNull(getEnclosingClass().getResource(getResourcePath()),
            "Unable to find YAML config file").toExternalForm();
    try {
        ConfigurationAsCode.get().configure(config);
    } catch (ConfiguratorException e) {
        LOGGER.log(Level.SEVERE, "Unable to configure using configuration as code. Aborting.");
        terminateJenkins();
        throw e; // causes JMH to abort benchmark
    }
}
 
Example #3
Source File: JobDslITest.java    From warnings-ng-plugin with MIT License 5 votes vote down vote up
/**
 * Helper method to get jenkins configuration file.
 *
 * @param fileName
 *         file with configuration.
 */
private void configureJenkins(final String fileName) {
    try {
        ConfigurationAsCode.get().configure(getResourceAsFile(fileName).toUri().toString());
    }
    catch (ConfiguratorException e) {
        throw new AssertionError(e);
    }
}
 
Example #4
Source File: TestCrumbIssuerConfigurationAsCodeTest.java    From jenkins-test-harness with MIT License 5 votes vote down vote up
@Test
public void testCrumbIssuerShouldBeSupportedWhenExportingConfiguration() throws Exception {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    ConfigurationAsCode.get().export(outputStream);

    ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
    String configuration = new Yaml().load(inputStream).toString();

    assertThat(configuration, containsString("crumbIssuer"));
    assertThat(configuration, not(containsString("FAILED TO EXPORT")));
    assertThat(logRule, not(recorded(containsString("Configuration-as-Code can't handle type class org.jvnet.hudson.test.TestCrumbIssuer"))));
}
 
Example #5
Source File: JenkinsConfiguratorCloudSupportTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Test
public void should_keep_cloud_abstractCloudSlave_nodes_configured_after_reload() throws Exception {
    final Node slave = new Cloud3PretendSlave();
    j.jenkins.addNode(slave);

    ConfigurationAsCode.get().configure(this.getClass().getResource("JenkinsConfiguratorCloudSupportTest.yml").toString());
    assertEquals("Cloud nodes not found", 3, j.jenkins.getNodes().size());
    assertNotNull("Slave 1", j.jenkins.getNode("agent1"));
    assertNotNull("Slave 1", j.jenkins.getNode("agent2"));
    assertNotNull("Slave cloud", j.jenkins.getNode("testCloud"));
}
 
Example #6
Source File: JenkinsConfiguratorCloudSupportTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Test
public void should_keep_cloud_ephemeral_nodes_configured_after_reload() throws Exception {
    final Node slave = new Cloud2PretendSlave();
    j.jenkins.addNode(slave);

    ConfigurationAsCode.get().configure(this.getClass().getResource("JenkinsConfiguratorCloudSupportTest.yml").toString());
    assertEquals("Cloud nodes not found", 3, j.jenkins.getNodes().size());
    assertNotNull("Slave 1", j.jenkins.getNode("agent1"));
    assertNotNull("Slave 1", j.jenkins.getNode("agent2"));
    assertNotNull("Slave cloud", j.jenkins.getNode("testCloud"));
}
 
Example #7
Source File: JenkinsConfiguratorCloudSupportTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Test
public void should_keep_cloud_no_instantiable_nodes_configured_after_reload() throws Exception {
    final Node slave = new Cloud1PretendSlave();
    j.jenkins.addNode(slave);

    ConfigurationAsCode.get().configure(this.getClass().getResource("JenkinsConfiguratorCloudSupportTest.yml").toString());
    assertEquals("Cloud nodes not found", 3, j.jenkins.getNodes().size());
    assertNotNull("Slave 1", j.jenkins.getNode("agent1"));
    assertNotNull("Slave 1", j.jenkins.getNode("agent2"));
    assertNotNull("Slave cloud", j.jenkins.getNode("testCloud"));
}
 
Example #8
Source File: JenkinsConfiguratorCloudSupportTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Test
public void should_remove_normal_nodes_configured_after_reload() throws Exception {
    final Node slave = new StaticPretendSlave();
    j.jenkins.addNode(slave);

    ConfigurationAsCode.get().configure(this.getClass().getResource("JenkinsConfiguratorCloudSupportTest.yml").toString());
    assertEquals("Base nodes not found", 2, j.jenkins.getNodes().size());
}
 
Example #9
Source File: JenkinsConfiguratorTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Test
@ConfiguredWithCode("ConfigureLabels.yml")
public void shouldExportLabelAtoms() throws Exception {
    DescribableList properties = Jenkins.get().getLabelAtom("label1").getProperties();
    properties.add(new TestProperty(1));

    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    ConfigurationAsCode.get().export(out);
    final String exported = out.toString();

    String content = FileUtils.readFileToString(new File(getClass().getResource("ExpectedLabelsConfiguration.yml").toURI()), "UTF-8");
    assertThat(exported, containsString(content));
}
 
Example #10
Source File: JenkinsConfiguredRule.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
/**
 * Exports the Jenkins configuration to a string.
 * @return YAML as string
 * @param strict Fail if any export operation returns error
 * @throws Exception Export error
 * @throws AssertionError Failed to export the configuration
 * @since 1.25
 */
public String exportToString(boolean strict) throws Exception {
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    ConfigurationAsCode.get().export(out);
    final String s = out.toString(StandardCharsets.UTF_8.name());
    if (strict && s.contains("Failed to export")) {
        throw new AssertionError("Failed to export the configuration: " + s);
    }
    return s;
}
 
Example #11
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 #12
Source File: ReloadJCascConfigurationCommand.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Override
protected int run() throws Exception {

    if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
        return -1;
    }

    ConfigurationAsCode.get().configure();
    return 0;
}
 
Example #13
Source File: ExportConfigurationCommand.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Override
protected int run() throws Exception {

    if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
        return -1;
    }


    ConfigurationAsCode.get().export(stdout);
    return 0;
}
 
Example #14
Source File: CheckConfigurationCommand.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Override
protected int run() throws Exception {

    if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
        return -1;
    }

    final Map<Source, String> issues = ConfigurationAsCode.get().checkWith(YamlSource.of(stdin));
    for (Map.Entry<Source, String> entry : issues.entrySet()) {
        stderr.printf("warning: line %d %s", entry.getKey().line, entry.getValue());
    }
    return 0;
}
 
Example #15
Source File: ApplyConfigurationCommand.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Override
protected int run() throws Exception {

    if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
        return -1;
    }

    ConfigurationAsCode.get().configureWith(YamlSource.of(stdin));
    return 0;
}
 
Example #16
Source File: ConfigurationAsCodeITest.java    From warnings-ng-plugin with MIT License 5 votes vote down vote up
private void configureJenkins(final String fileName) {
    try {
        ConfigurationAsCode.get().configure(getResourceAsFile(fileName).toUri().toString());
    }
    catch (ConfiguratorException e) {
        throw new AssertionError(e);
    }
}
 
Example #17
Source File: JenkinsConfiguredWithCodeRule.java    From configuration-as-code-plugin with MIT License 4 votes vote down vote up
@Override
public void before() throws Throwable {
    super.before();
    ConfiguredWithCode configuredWithCode = getConfiguredWithCode();
    if (Objects.nonNull(configuredWithCode)) {

        final Class<?> clazz = env.description().getTestClass();
        final String[] resource = configuredWithCode.value();

        final List<String> configs = Arrays.stream(resource)
            .map(s -> {
                // Let's get the resources from the given class.
                URL config = clazz.getResource(s);
                // Otherwise let's try with the more generic classloader
                if (config == null) {
                    config = clazz.getClassLoader().getResource(s);
                }
                if (config != null) {
                    return config.toExternalForm();
                } else {
                    throw new AssertionError("Exception when accessing the resources: " + s);
                }
            })
            .collect(Collectors.toList());

        try {
            ConfigurationAsCode.get().configure(configs);
        } catch (Throwable t) {
            if (!configuredWithCode.expected().isInstance(t)) {
                throw new AssertionError("Unexpected exception ", t);
            } else {
                if (!StringUtils.isBlank(configuredWithCode.message())) {
                    boolean match = new StringContains(false, configuredWithCode.message())
                        .matches(t.getMessage());
                    if (!match) {
                        throw new AssertionError(
                            "Exception did not contain the expected string: "
                                + configuredWithCode.message() + "\nMessage was:\n" + t
                                .getMessage());
                    }
                }
            }
        }
    }
}
 
Example #18
Source File: RoundTripAbstractTest.java    From configuration-as-code-plugin with MIT License 4 votes vote down vote up
private void putConfigInHome(String config) throws IOException {
    File configFile = new File(r.home, ConfigurationAsCode.DEFAULT_JENKINS_YAML_PATH);

    writeToFile(config, configFile.getAbsolutePath());
    assertTrue(ConfigurationAsCode.DEFAULT_JENKINS_YAML_PATH + " should be created", configFile.exists());
}
 
Example #19
Source File: JenkinsConfiguredWithReadmeRule.java    From configuration-as-code-plugin with MIT License 4 votes vote down vote up
@Override
public void before() throws Throwable {
    super.before();
    ConfiguredWithReadme configuredWithReadme = getConfiguredWithReadme();
    if (Objects.nonNull(configuredWithReadme)) {

        final Class<?> clazz = env.description().getTestClass();
        final String[] resource = configuredWithReadme.value();

        final List<String> configs = Arrays.stream(resource)
            .map(s -> {
                try {
                    String currentResource = s.replaceAll("#.*", "");
                    int position = getFencedCodeBlockIndex(s);
                    File codeBlockFile = File.createTempFile("integrations", "markdown");
                    InputStream inputStream = clazz.getClassLoader().getResourceAsStream(currentResource);
                    List<String> lines = Collections.singletonList(
                        transformFencedCodeBlockFromMarkdownToString(inputStream).get(position));
                    Path file = Paths.get(codeBlockFile.getCanonicalPath());
                    Files.write(file, lines, StandardCharsets.UTF_8);
                    return  codeBlockFile.toURI().toString();
                } catch (IOException e) {
                    throw new AssertionError("Exception when accessing the resources: " + s , e);
                }
            })
            .collect(Collectors.toList());

        try {
            ConfigurationAsCode.get().configure(configs);
        } catch (Throwable t) {
            if (!configuredWithReadme.expected().isInstance(t)) {
                throw new AssertionError("Unexpected exception ", t);
            } else {
                if (!StringUtils.isBlank(configuredWithReadme.message())) {
                    boolean match = new StringContains(false, configuredWithReadme.message())
                        .matches(t.getMessage());
                    if (!match) {
                        throw new AssertionError(
                            "Exception did not contain the expected string: "
                                + configuredWithReadme.message() + "\nMessage was:\n" + t
                                .getMessage());
                    }
                }
            }
        }
    }
}
 
Example #20
Source File: RoundTripAbstractTest.java    From configuration-as-code-plugin with MIT License 4 votes vote down vote up
private void configureWithResource(String config) throws ConfiguratorException {
    ConfigurationAsCode.get().configure(this.getClass().getResource(config).toExternalForm());
}
 
Example #21
Source File: Util.java    From configuration-as-code-plugin with MIT License 3 votes vote down vote up
/**
 * Converts a given {@code CNode} into a string.
 * <p>
 * Example usage:
 * <pre>{@code
 * ConfiguratorRegistry registry = ConfiguratorRegistry.get();
 * ConfigurationContext context = new ConfigurationContext(registry);
 * CNode yourAttribute = getUnclassifiedRoot(context).get("<your-attribute>");
 *
 * String exported = toYamlString(yourAttribute);}</pre>
 *
 * @param rootNode the {@code CNode} to convert to a string
 * @return a YAML string
 * @throws IOException if exporting to YAML fails
 */
public static String toYamlString(CNode rootNode) throws IOException {
    Node yamlRoot = ConfigurationAsCode.get().toYaml(rootNode);
    StringWriter buffer = new StringWriter();
    serializeYamlNode(yamlRoot, buffer);
    return buffer.toString();
}