org.jenkinsci.lib.configprovider.model.Config Java Examples

The following examples show how to use org.jenkinsci.lib.configprovider.model.Config. 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: DefaultsBinder.java    From pipeline-multibranch-defaults-plugin with MIT License 6 votes vote down vote up
@Override
public FlowExecution create(FlowExecutionOwner handle, TaskListener listener, List<? extends Action> actions) throws Exception {
    Jenkins jenkins = Jenkins.getInstance();
    if (jenkins == null) {
        throw new IllegalStateException("inappropriate context");
    }
    Queue.Executable exec = handle.getExecutable();
    if (!(exec instanceof WorkflowRun)) {
        throw new IllegalStateException("inappropriate context");
    }

    ConfigFileStore store = GlobalConfigFiles.get();
    if (store != null) {
        Config config = store.getById(PipelineBranchDefaultsProjectFactory.SCRIPT);
        if (config != null) {
            return new CpsFlowDefinition(config.content, false).create(handle, listener, actions);
        }
    }
    throw new IllegalArgumentException("Default " + PipelineBranchDefaultsProjectFactory.SCRIPT + " not found. Check configuration.");
}
 
Example #2
Source File: DefaultsBinderTest.java    From pipeline-multibranch-defaults-plugin with MIT License 6 votes vote down vote up
@Test
public void testDefaultJenkinsFile() throws Exception {
    GlobalConfigFiles globalConfigFiles = r.jenkins.getExtensionList(GlobalConfigFiles.class).get(GlobalConfigFiles.class);
    ConfigFileStore store = globalConfigFiles.get();

    Config config = new GroovyScript("Jenkinsfile", "Jenkinsfile", "",
        "semaphore 'wait'; node {checkout scm; echo readFile('file')}");
    store.save(config);

    sampleGitRepo.init();
    sampleGitRepo.write("file", "initial content");
    sampleGitRepo.git("commit", "--all", "--message=flow");
    WorkflowMultiBranchProject mp = r.jenkins.createProject(PipelineMultiBranchDefaultsProject.class, "p");
    mp.getSourcesList().add(new BranchSource(new GitSCMSource(null, sampleGitRepo.toString(), "", "*", "", false),
        new DefaultBranchPropertyStrategy(new BranchProperty[0])));
    WorkflowJob p = PipelineMultiBranchDefaultsProjectTest.scheduleAndFindBranchProject(mp, "master");
    SemaphoreStep.waitForStart("wait/1", null);
    WorkflowRun b1 = p.getLastBuild();
    assertNotNull(b1);
    assertEquals(1, b1.getNumber());
    SemaphoreStep.success("wait/1", null);
    r.assertLogContains("initial content", r.waitForCompletion(b1));
}
 
Example #3
Source File: DefaultsBinderTest.java    From pipeline-multibranch-defaults-plugin with MIT License 6 votes vote down vote up
@Test
public void testDefaultJenkinsFileLoadFromWorkspace() throws Exception {
    GlobalConfigFiles globalConfigFiles = r.jenkins.getExtensionList(GlobalConfigFiles.class).get(GlobalConfigFiles.class);
    ConfigFileStore store = globalConfigFiles.get();
    Config config = new GroovyScript("Jenkinsfile", "Jenkinsfile", "",
        "semaphore 'wait'; node {checkout scm; load 'Jenkinsfile'}");
    store.save(config);


    sampleGitRepo.init();
    sampleGitRepo.write("Jenkinsfile", "echo readFile('file')");
    sampleGitRepo.git("add", "Jenkinsfile");
    sampleGitRepo.write("file", "initial content");
    sampleGitRepo.git("commit", "--all", "--message=flow");
    WorkflowMultiBranchProject mp = r.jenkins.createProject(PipelineMultiBranchDefaultsProject.class, "p");
    mp.getSourcesList().add(new BranchSource(new GitSCMSource(null, sampleGitRepo.toString(), "", "*", "", false),
        new DefaultBranchPropertyStrategy(new BranchProperty[0])));
    WorkflowJob p = PipelineMultiBranchDefaultsProjectTest.scheduleAndFindBranchProject(mp, "master");
    SemaphoreStep.waitForStart("wait/1", null);
    WorkflowRun b1 = p.getLastBuild();
    assertNotNull(b1);
    assertEquals(1, b1.getNumber());
    SemaphoreStep.success("wait/1", null);
    r.assertLogContains("initial content", r.waitForCompletion(b1));
}
 
Example #4
Source File: ConfigFileProviderTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Test
@ConfiguredWithReadme(value = "config-file-provider/README.md")
public void configure_config_file_provider() throws Exception {
    assertThat(GlobalConfigFiles.get().getConfigs(), hasSize(4));

    Config config = GlobalConfigFiles.get().getById("custom-test");
    assertThat(config.name, is("DummyCustom1"));
    assertThat(config.comment, is("dummy custom 1"));
    assertThat(config.content, is("dummy content 1"));

    config = GlobalConfigFiles.get().getById("json-test");
    assertThat(config.name, is("DummyJsonConfig"));
    assertThat(config.comment, is("dummy json config"));
    assertThat(config.content, containsString("{ \"dummydata\": {\"dummyKey\": \"dummyValue\"} }"));

    config = GlobalConfigFiles.get().getById("xml-test");
    assertThat(config.name, is("DummyXmlConfig"));
    assertThat(config.comment, is("dummy xml config"));
    assertThat(config.content, containsString("<root><dummy test=\"abc\"></dummy></root>"));

    MavenSettingsConfig mavenSettings = (MavenSettingsConfig) GlobalConfigFiles.get().getById("maven-test");
    assertThat(mavenSettings.name, is("DummySettings"));
    assertThat(mavenSettings.comment, is("dummy settings"));
    assertThat(mavenSettings.isReplaceAll, is(false));
    assertThat(mavenSettings.getServerCredentialMappings(), hasSize(2));
    assertThat(mavenSettings.getServerCredentialMappings().get(0).getServerId(), is("server1"));
    assertThat(mavenSettings.getServerCredentialMappings().get(0).getCredentialsId(), is("someCredentials1"));
    assertThat(mavenSettings.getServerCredentialMappings().get(1).getServerId(), is("server2"));
    assertThat(mavenSettings.getServerCredentialMappings().get(1).getCredentialsId(), is("someCredentials2"));
    assertThat(mavenSettings.content, containsString("<activeProfiles>"));
}
 
Example #5
Source File: WithMavenStep.java    From pipeline-maven-plugin with MIT License 5 votes vote down vote up
@Restricted(NoExternalUse.class) // Only for UI calls
public ListBoxModel doFillMavenSettingsConfigItems(@AncestorInPath ItemGroup context) {
    ListBoxModel r = new ListBoxModel();
    r.add("--- Use system default settings or file path ---",null);
    for (Config config : ConfigFiles.getConfigsInContext(context, MavenSettingsConfigProvider.class)) {
        r.add(config.name, config.id);
    }
    return r;
}
 
Example #6
Source File: WithMavenStep.java    From pipeline-maven-plugin with MIT License 5 votes vote down vote up
@Restricted(NoExternalUse.class) // Only for UI calls
public ListBoxModel doFillGlobalMavenSettingsConfigItems(@AncestorInPath ItemGroup context) {
    ListBoxModel r = new ListBoxModel();
    r.add("--- Use system default settings or file path ---",null);
    for (Config config : ConfigFiles.getConfigsInContext(context, GlobalMavenSettingsConfigProvider.class)) {
        r.add(config.name, config.id);
    }
    return r;
}
 
Example #7
Source File: WithContainerStepTest.java    From docker-workflow-plugin with MIT License 5 votes vote down vote up
@Issue("JENKINS-27152")
@Test public void configFile() throws Exception {
    story.addStep(new Statement() {
        @Override public void evaluate() throws Throwable {
            DockerTestUtil.assumeDocker();
            ConfigProvider configProvider = story.j.jenkins.getExtensionList(ConfigProvider.class).get(CustomConfig.CustomConfigProvider.class);
            String id = configProvider.getProviderId() + "myfile";
            Config config = new CustomConfig(id, "My File", "", "some-content");
            configProvider.save(config);
            WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "prj");
            p.setDefinition(new CpsFlowDefinition(
                "node {\n" +
                "  withDockerContainer('ubuntu') {\n" +
                    "  wrap([$class: 'ConfigFileBuildWrapper', managedFiles: [[fileId: '" + config.id + "', variable: 'FILE']]]) {\n" +
                    "    sh 'cat \"$FILE\"'\n" +
                    "  }\n" +
                "  }\n" +
                "  wrap([$class: 'ConfigFileBuildWrapper', managedFiles: [[fileId: '" + config.id + "', variable: 'FILE']]]) {\n" +
                "    withDockerContainer('ubuntu') {\n" +
                "      sh 'tr \"a-z\" \"A-Z\" < \"$FILE\"'\n" +
                "    }\n" +
                "  }\n" +
                "}", true));
            WorkflowRun b = story.j.assertBuildStatusSuccess(p.scheduleBuild2(0));
            story.j.assertLogContains("some-content", b);
            story.j.assertLogContains("SOME-CONTENT", b);
        }
    });
}
 
Example #8
Source File: WithMavenStepExecution2.java    From pipeline-maven-plugin with MIT License 4 votes vote down vote up
/**
 * Reads the config file from Config File Provider, expands the credentials and stores it in a file on the temp
 * folder to use it with the maven wrapper script
 *
 * @param mavenSettingsConfigId config file id from Config File Provider
 * @param mavenSettingsFile     path to write te content to
 * @param credentials
 * @return the {@link FilePath} to the settings file
 * @throws AbortException in case of error
 */
private void settingsFromConfig(String mavenSettingsConfigId, FilePath mavenSettingsFile, @Nonnull Collection<Credentials> credentials) throws AbortException {

    Config c = ConfigFiles.getByIdOrNull(build, mavenSettingsConfigId);
    if (c == null) {
        throw new AbortException("Could not find the Maven settings.xml config file id:" + mavenSettingsConfigId + ". Make sure it exists on Managed Files");
    }
    if (StringUtils.isBlank(c.content)) {
        throw new AbortException("Could not create Maven settings.xml config file id:" + mavenSettingsConfigId + ". Content of the file is empty");
    }

    MavenSettingsConfig mavenSettingsConfig;
    if (c instanceof MavenSettingsConfig) {
        mavenSettingsConfig = (MavenSettingsConfig) c;
    } else {
        mavenSettingsConfig = new MavenSettingsConfig(c.id, c.name, c.comment, c.content, MavenSettingsConfig.isReplaceAllDefault, null);
    }

    try {
        final Map<String, StandardUsernameCredentials> resolvedCredentialsByMavenServerId = resolveCredentials(mavenSettingsConfig.getServerCredentialMappings(), "Maven settings");

        String mavenSettingsFileContent;
        if (resolvedCredentialsByMavenServerId.isEmpty()) {
            mavenSettingsFileContent = mavenSettingsConfig.content;
            if (LOGGER.isLoggable(Level.FINE)) {
                console.println("[withMaven] using Maven settings.xml '" + mavenSettingsConfig.id + "' with NO Maven servers credentials provided by Jenkins");
            }
        } else {
            credentials.addAll(resolvedCredentialsByMavenServerId.values());
            List<String> tempFiles = new ArrayList<>();
            mavenSettingsFileContent = CredentialsHelper.fillAuthentication(mavenSettingsConfig.content, mavenSettingsConfig.isReplaceAll, resolvedCredentialsByMavenServerId, tempBinDir, tempFiles);
            if (LOGGER.isLoggable(Level.FINE)) {
                console.println("[withMaven] using Maven settings.xml '" + mavenSettingsConfig.id + "' with Maven servers credentials provided by Jenkins " +
                        "(replaceAll: " + mavenSettingsConfig.isReplaceAll + "): " +
                        resolvedCredentialsByMavenServerId.entrySet().stream().map(new MavenServerToCredentialsMappingToStringFunction()).sorted().collect(Collectors.joining(", ")));
            }
        }

        mavenSettingsFile.write(mavenSettingsFileContent, getComputer().getDefaultCharset().name());
    } catch (Exception e) {
        throw new IllegalStateException("Exception injecting Maven settings.xml " + mavenSettingsConfig.id +
                " during the build: " + build + ": " + e.getMessage(), e);
    }
}
 
Example #9
Source File: WithMavenStepExecution2.java    From pipeline-maven-plugin with MIT License 4 votes vote down vote up
/**
 * Reads the global config file from Config File Provider, expands the credentials and stores it in a file on the temp
 * folder to use it with the maven wrapper script
 *
 * @param mavenGlobalSettingsConfigId global config file id from Config File Provider
 * @param mavenGlobalSettingsFile     path to write te content to
 * @param credentials
 * @return the {@link FilePath} to the settings file
 * @throws AbortException in case of error
 */
private void globalSettingsFromConfig(String mavenGlobalSettingsConfigId, FilePath mavenGlobalSettingsFile, Collection<Credentials> credentials) throws AbortException {

    Config c = ConfigFiles.getByIdOrNull(build, mavenGlobalSettingsConfigId);
    if (c == null) {
        throw new AbortException("Could not find the Maven global settings.xml config file id:" + mavenGlobalSettingsFile + ". Make sure it exists on Managed Files");
    }
    if (StringUtils.isBlank(c.content)) {
        throw new AbortException("Could not create Maven global settings.xml config file id:" + mavenGlobalSettingsFile + ". Content of the file is empty");
    }

    GlobalMavenSettingsConfig mavenGlobalSettingsConfig;
    if (c instanceof GlobalMavenSettingsConfig) {
        mavenGlobalSettingsConfig = (GlobalMavenSettingsConfig) c;
    } else {
        mavenGlobalSettingsConfig = new GlobalMavenSettingsConfig(c.id, c.name, c.comment, c.content, MavenSettingsConfig.isReplaceAllDefault, null);
    }

    try {
        final Map<String, StandardUsernameCredentials> resolvedCredentialsByMavenServerId = resolveCredentials(mavenGlobalSettingsConfig.getServerCredentialMappings(), " Global Maven settings");

        String mavenGlobalSettingsFileContent;
        if (resolvedCredentialsByMavenServerId.isEmpty()) {
            mavenGlobalSettingsFileContent = mavenGlobalSettingsConfig.content;
            console.println("[withMaven] using Maven global settings.xml '" + mavenGlobalSettingsConfig.id + "' with NO Maven servers credentials provided by Jenkins");

        } else {
            credentials.addAll(resolvedCredentialsByMavenServerId.values());

            List<String> tempFiles = new ArrayList<>();
            mavenGlobalSettingsFileContent = CredentialsHelper.fillAuthentication(mavenGlobalSettingsConfig.content, mavenGlobalSettingsConfig.isReplaceAll, resolvedCredentialsByMavenServerId, tempBinDir, tempFiles);
            console.println("[withMaven] using Maven global settings.xml '" + mavenGlobalSettingsConfig.id + "' with Maven servers credentials provided by Jenkins " +
                    "(replaceAll: " + mavenGlobalSettingsConfig.isReplaceAll + "): " +
                    resolvedCredentialsByMavenServerId.entrySet().stream().map(new MavenServerToCredentialsMappingToStringFunction()).sorted().collect(Collectors.joining(", ")));

        }


        mavenGlobalSettingsFile.write(mavenGlobalSettingsFileContent, getComputer().getDefaultCharset().name());
        LOGGER.log(Level.FINE, "Created global config file {0}", new Object[]{mavenGlobalSettingsFile});
    } catch (Exception e) {
        throw new IllegalStateException("Exception injecting Maven settings.xml " + mavenGlobalSettingsConfig.id +
                " during the build: " + build + ": " + e.getMessage(), e);
    }
}