io.jenkins.plugins.casc.ConfiguratorException Java Examples

The following examples show how to use io.jenkins.plugins.casc.ConfiguratorException. 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: 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 #2
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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
Source File: DataBoundConfigurator.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
/**
 * Gets DataBoundConstructor or fails.
 * @return constructor with {@link org.kohsuke.stapler.DataBoundConstructor} annotation
 * @throws ConfiguratorException Constructor not found
 */
private Constructor getDataBoundConstructor() throws ConfiguratorException {
    final Constructor constructor = getDataBoundConstructor(target);
    if (constructor == null) {
        throw new ConfiguratorException(target.getName() + " is missing a @DataBoundConstructor");
    }
    return constructor;
}
 
Example #9
Source File: GitToolConfiguratorTest.java    From git-client-plugin with MIT License 5 votes vote down vote up
@Test(expected = ConfiguratorException.class)
public void testInstanceGitToolWithoutHome() throws Exception {
    Mapping mapping = new Mapping();
    mapping.put("name", "testGitName"); // No home mapping defined
    ConfigurationContext context = new ConfigurationContext(null);
    gitToolConfigurator.instance(mapping, context);
}
 
Example #10
Source File: VaultSecretSourceTest.java    From hashicorp-vault-plugin with MIT License 5 votes vote down vote up
@Test
@ConfiguredWithCode("vault.yml")
@EnvsFromFile(VAULT_APPROLE_FILE)
@Envs({
    @Env(name = "CASC_VAULT_PATHS", value = VAULT_PATH_KV2_1 + "," + VAULT_PATH_KV2_2),
    @Env(name = "CASC_VAULT_ENGINE_VERSION", value = "2")
})
public void kv2WithApprole() throws ConfiguratorException {
    assertThat(SecretSourceResolver.resolve(context, "${key1}"), equalTo("123"));
    assertThat(SecretSourceResolver.resolve(context, "${" + VAULT_PATH_KV2_1 + "/key1}"), equalTo("123"));
}
 
Example #11
Source File: DataBoundConfiguratorTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Test
public void packageParametersAreNonnullByDefault() {
    Mapping config = new Mapping();
    ConfiguratorRegistry registry = ConfiguratorRegistry.get();

    String expectedMessage = "string is required to configure class io.jenkins.plugins.casc.impl.configurators.nonnull.nonnullparampackage.PackageParametersAreNonnullByDefault";

    ConfiguratorException exception = assertThrows(ConfiguratorException.class, () -> registry
        .lookupOrFail(PackageParametersAreNonnullByDefault.class)
        .configure(config, new ConfigurationContext(registry)));

   assertThat(exception.getMessage(), is(expectedMessage));
}
 
Example #12
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 #13
Source File: DefaultConfiguratorRegistry.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
/**
 * Looks for a configurator for exact type.
 * @param type Type
 * @return Configurator
 * @throws ConfiguratorException Configurator is not found
 */
@Override
@NonNull
public Configurator lookupOrFail(Type type) throws ConfiguratorException {
    try {
        return cache.get(type);
    } catch (ExecutionException e) {
        throw (ConfiguratorException) e.getCause();
    }
}
 
Example #14
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 #15
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 #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: 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 #18
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 #19
Source File: ExtensionConfigurator.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Override
protected T instance(Mapping mapping, ConfigurationContext context) throws ConfiguratorException {
    final ExtensionList<T> list = Jenkins.get().getExtensionList(target);
    if (list.size() != 1) {
        throw new ConfiguratorException("Expected a unique instance of extension "+target);
    }
    return list.get(0);
}
 
Example #20
Source File: UpdateSiteConfigurator.java    From configuration-as-code-plugin with MIT License 4 votes vote down vote up
@Override
protected UpdateSite instance(Mapping mapping, ConfigurationContext context) throws ConfiguratorException {
    return new UpdateSite(mapping.getScalarValue("id"), mapping.getScalarValue("url"));
}
 
Example #21
Source File: YamlUtils.java    From configuration-as-code-plugin with MIT License 4 votes vote down vote up
private static void merge(Node root, Node node, String source) throws ConfiguratorException {
    if (root.getNodeId() != node.getNodeId()) {
        // means one of those yaml file doesn't conform to JCasC schema
        throw new ConfiguratorException(
                String.format("Found incompatible configuration elements %s %s", source, node.getStartMark()));
    }

    switch (root.getNodeId()) {
        case sequence:
            SequenceNode seq = (SequenceNode) root;
            SequenceNode seq2 = (SequenceNode) node;
            seq.getValue().addAll(seq2.getValue());
            return;
        case mapping:
            MappingNode map = (MappingNode) root;
            MappingNode map2 = (MappingNode) node;
            // merge common entries
            final Iterator<NodeTuple> it = map2.getValue().iterator();
            while (it.hasNext()) {
                NodeTuple t2 = it.next();
                for (NodeTuple tuple : map.getValue()) {

                    final Node key = tuple.getKeyNode();
                    final Node key2 = t2.getKeyNode();
                    if (key.getNodeId() == NodeId.scalar) {
                        // We dont support merge for more complex cases (yet)
                        if (((ScalarNode) key).getValue().equals(((ScalarNode) key2).getValue())) {
                            merge(tuple.getValueNode(), t2.getValueNode(), source);
                            it.remove();
                        }
                    } else {
                        throw new ConfiguratorException(
                                String.format("Found unmergeable configuration keys %s %s)", source, node.getEndMark()));
                    }
                }
            }
            // .. and add others
            map.getValue().addAll(map2.getValue());
            return;
        default:
            throw new ConfiguratorException(
                    String.format("Found conflicting configuration at %s %s", source, node.getStartMark()));
    }

}
 
Example #22
Source File: CNode.java    From configuration-as-code-plugin with MIT License 4 votes vote down vote up
default Mapping asMapping() throws ConfiguratorException {
    throw new ConfiguratorException("Item isn't a Mapping");
}
 
Example #23
Source File: SelfConfiguratorTest.java    From configuration-as-code-plugin with MIT License 4 votes vote down vote up
@Test
@ConfiguredWithCode(value = "SelfConfiguratorRestrictedTest.yml", expected = ConfiguratorException.class)
public void self_configure_restricted() {
    // expected to throw Configurator Exception
    assertThat(j.jenkins.getRawBuildsDir(), is(not("/tmp")));
}
 
Example #24
Source File: CNode.java    From configuration-as-code-plugin with MIT License 4 votes vote down vote up
default Sequence asSequence() throws ConfiguratorException {
    throw new ConfiguratorException("Item isn't a Sequence");
}
 
Example #25
Source File: CNode.java    From configuration-as-code-plugin with MIT License 4 votes vote down vote up
default Scalar asScalar() throws ConfiguratorException {
    throw new ConfiguratorException("Item isn't a Scalar");
}
 
Example #26
Source File: Mapping.java    From configuration-as-code-plugin with MIT License 4 votes vote down vote up
public String getScalarValue(String key) throws ConfiguratorException {
    return remove(key).asScalar().getValue();
}
 
Example #27
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 #28
Source File: LabelAtomConfigurator.java    From configuration-as-code-plugin with MIT License 4 votes vote down vote up
@Override
protected LabelAtom instance(Mapping mapping, ConfigurationContext context) throws ConfiguratorException {
    return new LabelAtom(mapping.getScalarValue("name"));
}
 
Example #29
Source File: NoneSecurityRealmConfigurator.java    From configuration-as-code-plugin with MIT License 4 votes vote down vote up
@NonNull
@Override
public SecurityRealm configure(CNode config, ConfigurationContext context) throws ConfiguratorException {
    return SecurityRealm.NO_AUTHENTICATION;
}
 
Example #30
Source File: DataBoundConfigurator.java    From configuration-as-code-plugin with MIT License 4 votes vote down vote up
/**
 * Build a fresh new component based on provided configuration and {@link org.kohsuke.stapler.DataBoundConstructor}
 */
@Override
protected T instance(Mapping config, ConfigurationContext context) throws ConfiguratorException {
    final Constructor dataBoundConstructor = getDataBoundConstructor();
    return tryConstructor((Constructor<T>) dataBoundConstructor, config, context);
}