use of io.jenkins.plugins.casc.model.CNode in project configuration-as-code-plugin by jenkinsci.
the class DataBoundConfigurator method tryConstructor.
private T tryConstructor(Constructor<T> constructor, Mapping config, ConfigurationContext context) throws ConfiguratorException {
final Parameter[] parameters = constructor.getParameters();
final String[] names = ClassDescriptor.loadParameterNames(constructor);
Object[] args = new Object[names.length];
if (parameters.length > 0) {
for (int i = 0; i < names.length; i++) {
final CNode value = config.get(names[i]);
final Class t = parameters[i].getType();
Class<?> clazz = constructor.getDeclaringClass();
if (value == null && (parameters[i].isAnnotationPresent(Nonnull.class) || constructor.isAnnotationPresent(ParametersAreNonnullByDefault.class) || clazz.isAnnotationPresent(ParametersAreNonnullByDefault.class) || clazz.getPackage().isAnnotationPresent(ParametersAreNonnullByDefault.class) && !parameters[i].isAnnotationPresent(CheckForNull.class))) {
if (Set.class.isAssignableFrom(t)) {
LOGGER.log(Level.FINER, "The parameter to be set is @Nonnull but is not present; " + "setting equal to empty set.");
args[i] = Collections.emptySet();
} else if (List.class.isAssignableFrom(t)) {
LOGGER.log(Level.FINER, "The parameter to be set is @Nonnull but is not present; " + "setting equal to empty list.");
args[i] = Collections.emptyList();
} else {
throw new ConfiguratorException(names[i] + " is required to configure " + target);
}
continue;
}
if (value != null) {
if (Collection.class.isAssignableFrom(t)) {
final Type pt = parameters[i].getParameterizedType();
final Configurator lookup = context.lookupOrFail(pt);
final Collection<Object> collection;
if (Set.class.isAssignableFrom(t)) {
collection = new HashSet<>();
} else {
collection = new ArrayList<>();
}
for (CNode o : value.asSequence()) {
collection.add(lookup.configure(o, context));
}
args[i] = collection;
} else {
final Type pt = parameters[i].getParameterizedType();
final Type k = pt != null ? pt : t;
final Configurator configurator = context.lookupOrFail(k);
args[i] = configurator.configure(value, context);
}
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE, "Setting {0}.{1} = {2}", new Object[] { target, names[i], t == Secret.class || Attribute.calculateIfSecret(target, names[i]) ? "****" : value });
}
} else if (t.isPrimitive()) {
args[i] = defaultPrimitiveValue(t);
}
}
}
final T object;
try {
object = constructor.newInstance(args);
} catch (IllegalArgumentException | InstantiationException | InvocationTargetException | IllegalAccessException ex) {
List<String> argumentTypes = new ArrayList<>(args.length);
for (Object arg : args) {
argumentTypes.add(arg != null ? arg.getClass().getName() : "null");
}
List<String> parameterTypes = new ArrayList<>(parameters.length);
for (Parameter parameter : parameters) {
parameterTypes.add(parameter.getParameterizedType().getTypeName());
}
List<String> expectedParamList = new ArrayList<>(parameters.length);
for (int i = 0; i < parameters.length; i++) {
expectedParamList.add(names[i] + " " + parameterTypes.get(i));
}
throw new ConfiguratorException(this, "Failed to construct instance of " + target + ".\n Constructor: " + constructor + ".\n Arguments: " + argumentTypes + ".\n Expected Parameters: " + String.join(", ", expectedParamList), ex);
}
// constructor was successful, so let's removed configuration elements we have consumed doing so.
for (String name : names) {
config.remove(name);
}
return object;
}
use of io.jenkins.plugins.casc.model.CNode in project configuration-as-code-plugin by jenkinsci.
the class ExportTest method export.
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);
}
}
use of io.jenkins.plugins.casc.model.CNode in project configuration-as-code-plugin by jenkinsci.
the class Util method toYamlString.
/**
* 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();
}
use of io.jenkins.plugins.casc.model.CNode in project configuration-as-code-plugin by jenkinsci.
the class ConfigurationAsCodeTest method multiline_literal_stays_literal_in_export.
@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));
}
use of io.jenkins.plugins.casc.model.CNode in project configuration-as-code-plugin by jenkinsci.
the class AdminWhitelistRuleConfiguratorTest method checkA2MAccessControl_disable.
@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());
}
Aggregations