Java Code Examples for jenkins.model.Jenkins#getDescriptor()

The following examples show how to use jenkins.model.Jenkins#getDescriptor() . 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: ArtifactoryTest.java    From configuration-as-code-plugin with MIT License 7 votes vote down vote up
@Test
@ConfiguredWithReadme(value = "artifactory/README.md")
public void configure_artifactory() throws Exception {
    final Jenkins jenkins = Jenkins.get();
    final ArtifactoryBuilder.DescriptorImpl descriptor = (ArtifactoryBuilder.DescriptorImpl) jenkins.getDescriptor(ArtifactoryBuilder.class);
    assertTrue(descriptor.getUseCredentialsPlugin());

    final List<ArtifactoryServer> actifactoryServers = descriptor.getArtifactoryServers();
    assertThat(actifactoryServers, hasSize(1));
    assertThat(actifactoryServers.get(0).getName(), is(equalTo("artifactory")));
    assertThat(actifactoryServers.get(0).getUrl(), is(equalTo("http://acme.com/artifactory")));
    assertThat(actifactoryServers.get(0).getDeployerCredentialsConfig().getCredentialsId(), is(equalTo("artifactory")));
    assertThat(actifactoryServers.get(0).getResolverCredentialsConfig().getUsername(), is(equalTo("artifactory_user")));
    assertThat(actifactoryServers.get(0).getResolverCredentialsConfig().getPassword(), is(equalTo("password123")));

}
 
Example 2
Source File: TopReadmeTest.java    From configuration-as-code-plugin with MIT License 6 votes vote down vote up
@Test
@ConfiguredWithReadme("README.md#0")
public void configure_demo_first_code_block() throws Exception {
    final Jenkins jenkins = Jenkins.get();
    assertEquals("Jenkins configured automatically by Jenkins Configuration as Code plugin\n\n", jenkins.getSystemMessage());
    final LDAPSecurityRealm securityRealm = (LDAPSecurityRealm) jenkins.getSecurityRealm();
    assertEquals(1, securityRealm.getConfigurations().size());
    assertEquals(50000, jenkins.getSlaveAgentPort());

    assertEquals(1, jenkins.getNodes().size());
    assertEquals("static-agent", jenkins.getNode("static-agent").getNodeName());

    final GitTool.DescriptorImpl gitTool = (GitTool.DescriptorImpl) jenkins.getDescriptor(GitTool.class);
    assertEquals(1, gitTool.getInstallations().length);

    List<BasicSSHUserPrivateKey> sshPrivateKeys = CredentialsProvider.lookupCredentials(
        BasicSSHUserPrivateKey.class, jenkins, ACL.SYSTEM, Collections.emptyList()
    );
    assertThat(sshPrivateKeys, hasSize(1));

    final BasicSSHUserPrivateKey ssh_with_passphrase = sshPrivateKeys.get(0);
    assertThat(ssh_with_passphrase.getPassphrase().getPlainText(), equalTo("ABCD"));

    final DirectEntryPrivateKeySource source = (DirectEntryPrivateKeySource) ssh_with_passphrase.getPrivateKeySource();
    assertThat(source.getPrivateKey().getPlainText(), equalTo("s3cr3t"));
}
 
Example 3
Source File: GitTool.java    From git-client-plugin with MIT License 6 votes vote down vote up
@Initializer(after=EXTENSIONS_AUGMENTED)
public static void onLoaded() {
    //Creates default tool installation if needed. Uses "git" or migrates data from previous versions

    Jenkins jenkinsInstance = Jenkins.getInstance();
    DescriptorImpl descriptor = (DescriptorImpl) jenkinsInstance.getDescriptor(GitTool.class);
    GitTool[] installations = getInstallations(descriptor);

    if (installations != null && installations.length > 0) {
        //No need to initialize if there's already something
        return;
    }

    String defaultGitExe = isWindows() ? "git.exe" : "git";
    GitTool tool = new GitTool(DEFAULT, defaultGitExe, Collections.<ToolProperty<?>>emptyList());
    descriptor.setInstallations(new GitTool[] { tool });
    descriptor.save();
}
 
Example 4
Source File: RoundTripMailerTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Override
protected void assertConfiguredAsExpected(RestartableJenkinsRule j, String configContent) {
    final Jenkins jenkins = Jenkins.get();
    final Mailer.DescriptorImpl descriptor = (Mailer.DescriptorImpl) jenkins.getDescriptor(Mailer.class);
    assertEquals("4441", descriptor.getSmtpPort());
    assertEquals("[email protected]", descriptor.getReplyToAddress());
}
 
Example 5
Source File: MailerTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Test
@ConfiguredWithReadme("mailer/README.md")
public void configure_mailer() throws Exception {
    final Jenkins jenkins = Jenkins.get();
    final Mailer.DescriptorImpl descriptor = (Mailer.DescriptorImpl) jenkins.getDescriptor(Mailer.class);
    assertEquals("4441", descriptor.getSmtpPort());
    assertEquals("[email protected]", descriptor.getReplyToAddress());
    assertEquals("smtp.acme.org", descriptor.getSmtpHost() );
}
 
Example 6
Source File: GitToolInstallationTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Test
public void configure_git_installations() throws Exception {
    final Jenkins jenkins = Jenkins.get();
    final GitTool.DescriptorImpl descriptor = (GitTool.DescriptorImpl) jenkins.getDescriptor(GitTool.class);
    assertEquals(2, descriptor.getInstallations().length);
    assertEquals("/usr/local/bin/git", descriptor.getInstallation("another_git").getGitExe());
    assertEquals("/bin/git", descriptor.getInstallation("git").getGitExe());
}
 
Example 7
Source File: KubernetesCloud.java    From kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"rawtypes", "unused"}) // used by jelly
public Descriptor getDefaultPodRetention() {
    Jenkins jenkins = Jenkins.getInstanceOrNull();
    if (jenkins == null) {
        return null;
    }
    return jenkins.getDescriptor(PodRetention.getKubernetesCloudDefault().getClass());
}
 
Example 8
Source File: JenkinsDemoTest.java    From configuration-as-code-plugin with MIT License 4 votes vote down vote up
@Test
@ConfiguredWithCode("jenkins/jenkins.yaml")
public void configure_demo_yaml() throws Exception {
    final Jenkins jenkins = Jenkins.get();
    assertEquals("Jenkins configured automatically by Jenkins Configuration as Code plugin\n\n", jenkins.getSystemMessage());
    assertEquals(5, jenkins.getNumExecutors());
    assertEquals(2, jenkins.getScmCheckoutRetryCount());
    assertEquals(Mode.NORMAL, jenkins.getMode());
    assertEquals("https://ci.example.com/", jenkins.getRootUrl());

    final FullControlOnceLoggedInAuthorizationStrategy strategy = (FullControlOnceLoggedInAuthorizationStrategy) jenkins.getAuthorizationStrategy();
    assertFalse(strategy.isAllowAnonymousRead());

    final DockerCloud docker = DockerCloud.getCloudByName("docker");
    assertNotNull(docker);
    assertNotNull(docker.getDockerApi());
    assertNotNull(docker.getDockerApi().getDockerHost());
    assertEquals("unix:///var/run/docker.sock", docker.getDockerApi().getDockerHost().getUri());

    final GitTool.DescriptorImpl gitTool = (GitTool.DescriptorImpl) jenkins.getDescriptor(GitTool.class);
    assertEquals(1, gitTool.getInstallations().length);

    assertEquals(1, GlobalLibraries.get().getLibraries().size());
    final LibraryConfiguration library = GlobalLibraries.get().getLibraries().get(0);
    assertEquals("awesome-lib", library.getName());

    final Mailer.DescriptorImpl descriptor = (Mailer.DescriptorImpl) jenkins.getDescriptor(Mailer.class);
    assertEquals("4441", descriptor.getSmtpPort());
    assertEquals("[email protected]", descriptor.getReplyToAddress());
    assertEquals("smtp.acme.org", descriptor.getSmtpHost() );

    final ArtifactoryBuilder.DescriptorImpl artifactory = (ArtifactoryBuilder.DescriptorImpl) jenkins.getDescriptor(ArtifactoryBuilder.class);
    assertTrue(artifactory.getUseCredentialsPlugin());

    final List<ArtifactoryServer> actifactoryServers = artifactory.getArtifactoryServers();
    assertThat(actifactoryServers, hasSize(1));
    assertThat(actifactoryServers.get(0).getName(), is(equalTo("artifactory")));
    assertThat(actifactoryServers.get(0).getUrl(), is(equalTo("http://acme.com/artifactory")));
    assertThat(actifactoryServers.get(0).getResolverCredentialsConfig().getUsername(), is(equalTo("artifactory_user")));
    assertThat(actifactoryServers.get(0).getResolverCredentialsConfig().getPassword(), is(equalTo("password123")));
}
 
Example 9
Source File: MattermostSendStep.java    From jenkins-mattermost-plugin with MIT License 4 votes vote down vote up
@Override
protected Void run() throws Exception
{

 // default to global config values if not set in step, but allow step to
 // override all global settings
 Jenkins jenkins;
 // Jenkins.getInstance() may return null, no message sent in that case
 try
 {
  jenkins = Jenkins.get();
 } catch (NullPointerException ne)
 {
  listener.error(String.format("Mattermost notification failed with exception: %s", ne), ne);
  return null;
 }//TODO REFACTOR jenkins.getdescriptor by class
 MattermostNotifier.DescriptorImpl mattermostDesc =
	  jenkins.getDescriptorByType(MattermostNotifier.DescriptorImpl.class);
 if (mattermostDesc == null)
  mattermostDesc = (MattermostNotifier.DescriptorImpl) jenkins.getDescriptor("mattermostNotifier");//junit test fallback
 String team =
       step.getEndpoint() != null
	  ? step.getEndpoint()
	  : mattermostDesc.getEndpoint().getPlainText();
 String channel = step.channel != null ? step.channel : mattermostDesc.getRoom();
 String icon = step.icon != null ? step.icon : (mattermostDesc.getIcon() != null ? mattermostDesc.getIcon() : "");
 String color = step.color != null ? step.color : "";
 String text = step.text != null ? step.text : "";

 // placing in console log to simplify testing of retrieving values from global
 // config or from step field; also used for tests
 listener
       .getLogger()
       .printf(
           "Mattermost Send Pipeline step configured values from global config - connector: %s, icon: %s, channel: %s, color: %s",
           step.endpoint == null, step.icon == null, step.channel == null, step.color == null);

 MattermostService mattermostService = getMattermostService(team, channel, icon);
 boolean publishSuccess = mattermostService.publish(step.message, text, color);
 if (!publishSuccess && step.failOnError)
 {
  throw new AbortException("Mattermost notification failed. See Jenkins logs for details.");
 } else if (!publishSuccess)
 {
  listener.error("Mattermost notification failed. See Jenkins logs for details.");
 }
 return null;
}
 
Example 10
Source File: FreestyleTest.java    From yet-another-docker-plugin with MIT License 4 votes vote down vote up
@Override
        public Boolean call() throws Throwable {
            final Jenkins jenkins = Jenkins.getInstance();

            String logName = "com.github.kostyasha.yad";
            final LogRecorder logRecorder = new LogRecorder(logName);
            logRecorder.targets.add(new LogRecorder.Target("com.github.kostyasha.yad", Level.ALL));
            jenkins.getLog().logRecorders.put("logName", logRecorder);
            logRecorder.save();

            // prepare jenkins global (url, cred)
            JenkinsLocationConfiguration.get().setUrl(String.format("http://%s:%d", dockerUri.getHost(), jenkinsPort));

            SystemCredentialsProvider.getInstance().getCredentials().add(dockerServerCredentials);

            //verify doTestConnection
            final DescriptorImpl descriptor = (DescriptorImpl) jenkins.getDescriptor(DockerConnector.class);
            checkFormValidation(descriptor.doTestConnection(dockerUri.toString(), "",
                    dockerServerCredentials.getId(), connectorType, 10 * 1000, 11 * 1000));
//           checkFormValidation(descriptor.doTestConnection(dockerUri.toString(), "",
//                    dockerServerCredentials.getId(), JERSEY, 10 * 1000, 11 * 1000));
//           checkFormValidation(descriptor.doTestConnection(dockerUri.toString(), "",
//                    dockerServerCredentials.getId(), OKHTTP, 10 * 1000, 11 * 1000));

            // prepare Docker Cloud
            final DockerConnector dockerConnector = new DockerConnector(dockerUri.toString());
            dockerConnector.setCredentialsId(dockerServerCredentials.getId());
            dockerConnector.setConnectTimeout(10 * 1000);
            dockerConnector.setReadTimeout(0);
            dockerConnector.setConnectorType(connectorType);
            dockerConnector.testConnection();

            //launcher
            final DockerComputerJNLPLauncher launcher = new DockerComputerJNLPLauncher();
            launcher.setNoCertificateCheck(true);
            launcher.setJvmOpts("-XX:-PrintClassHistogram");
            final DockerPullImage pullImage = new DockerPullImage();
            pullImage.setPullStrategy(PULL_LATEST);

            //remove
            final DockerRemoveContainer removeContainer = new DockerRemoveContainer();
            removeContainer.setRemoveVolumes(true);
            removeContainer.setForce(true);

            //lifecycle
            final DockerContainerLifecycle containerLifecycle = new DockerContainerLifecycle();
            containerLifecycle.setImage(slaveImage);
            containerLifecycle.setPullImage(pullImage);
            containerLifecycle.setRemoveContainer(removeContainer);

            //template
            final Entry entry = new Entry("super-key", TEST_VALUE);
            final EnvironmentVariablesNodeProperty nodeProperty = new EnvironmentVariablesNodeProperty(entry);

            final ArrayList<NodeProperty<?>> nodeProperties = new ArrayList<>();
            nodeProperties.add(nodeProperty);
            nodeProperties.add(new DockerNodeProperty(CONTAINER_ID, CLOUD_ID, DOCKER_HOST));


            final DockerSlaveTemplate slaveTemplate = new DockerSlaveTemplate();
            slaveTemplate.setMaxCapacity(4);
            slaveTemplate.setLabelString(DOCKER_CLOUD_LABEL);
            slaveTemplate.setLauncher(launcher);
            slaveTemplate.setMode(Node.Mode.EXCLUSIVE);
            slaveTemplate.setRetentionStrategy(new DockerOnceRetentionStrategy(10));
            slaveTemplate.setDockerContainerLifecycle(containerLifecycle);
            slaveTemplate.setNodeProperties(nodeProperties);

            final List<DockerSlaveTemplate> templates = new ArrayList<>();
            templates.add(slaveTemplate);

            final DockerCloud dockerCloud = new DockerCloud(
                    DOCKER_CLOUD_NAME,
                    templates,
                    3,
                    dockerConnector
            );
            jenkins.clouds.add(dockerCloud);
            jenkins.save(); // either xmls a half broken

            return true;
        }