Java源码示例:io.jenkins.plugins.casc.ConfigurationAsCode
示例1
/**
* 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
}
}
示例2
@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"));
}
示例3
private void configureJenkins(final String fileName) {
try {
ConfigurationAsCode.get().configure(getResourceAsFile(fileName).toUri().toString());
}
catch (ConfiguratorException e) {
throw new AssertionError(e);
}
}
示例4
/**
* 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);
}
}
示例5
@Override
protected int run() throws Exception {
if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
return -1;
}
ConfigurationAsCode.get().configureWith(YamlSource.of(stdin));
return 0;
}
示例6
@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;
}
示例7
@Override
protected int run() throws Exception {
if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
return -1;
}
ConfigurationAsCode.get().export(stdout);
return 0;
}
示例8
@Override
protected int run() throws Exception {
if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
return -1;
}
ConfigurationAsCode.get().configure();
return 0;
}
示例9
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);
}
}
示例10
/**
* 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;
}
示例11
@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));
}
示例12
@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());
}
示例13
@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"));
}
示例14
@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"));
}
示例15
@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"));
}
示例16
@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"))));
}
示例17
private void configureWithResource(String config) throws ConfiguratorException {
ConfigurationAsCode.get().configure(this.getClass().getResource(config).toExternalForm());
}
示例18
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());
}
示例19
@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());
}
}
}
}
}
}
示例20
@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());
}
}
}
}
}
}
示例21
/**
* 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();
}