Search in sources :

Example 1 with JenkinsServer

use of com.offbytwo.jenkins.JenkinsServer in project fabric8 by fabric8io.

the class JenkinsTestMain method main.

public static void main(String[] args) {
    if (args.length == 0) {
        System.out.println("Usage: [jenkinsServerUrl] [jobName]");
        return;
    }
    String jenkinsUrl = "http://jenkins.vagrant.f8/";
    String job = null;
    if (args.length > 0) {
        jenkinsUrl = args[0];
    }
    if (args.length > 1) {
        job = args[1];
    }
    try {
        JenkinsServer jenkins = JenkinsAsserts.createJenkinsServer(jenkinsUrl);
        Map<String, Job> jobs = jenkins.getJobs();
        Set<Map.Entry<String, Job>> entries = jobs.entrySet();
        for (Map.Entry<String, Job> entry : entries) {
            System.out.println("Job " + entry.getKey() + " = " + entry.getValue());
        }
        if (job != null) {
            JenkinsAsserts.assertJobLastBuildIsSuccessful(jenkins, job);
        }
    } catch (Exception e) {
        logError(e.getMessage(), e);
    }
}
Also used : JenkinsServer(com.offbytwo.jenkins.JenkinsServer) Job(com.offbytwo.jenkins.model.Job) Map(java.util.Map)

Example 2 with JenkinsServer

use of com.offbytwo.jenkins.JenkinsServer in project gogs-webhook-plugin by jenkinsci.

the class GogsWebHook_IT method smokeTest_build_masterBranch.

@Test
public void smokeTest_build_masterBranch() throws Exception {
    // Instantiate the Gogs Handler object and wait for the server to be available
    GogsConfigHandler gogsServer = new GogsConfigHandler(GOGS_URL, GOGS_USER, GOGS_PASSWORD);
    gogsServer.waitForServer(12, 5);
    // Create the test repository on the server
    try {
        gogsServer.createEmptyRepo("testRep1");
    } catch (IOException e) {
        // check for the exist message;
        if (e.getMessage().contains("422")) {
            log.warn("GOGS Repo already exists. Trying to continue.");
        } else {
            fail("Unexpected error creating GOGS repo: " + e.getMessage());
        }
    }
    // initialize local Git repository used for tests
    File testRepoDir = new File("target/test-repos/demo-app");
    Git git = Git.init().setDirectory(testRepoDir).call();
    // Configure user, email, remote and tracking branch
    StoredConfig config = git.getRepository().getConfig();
    config.setString(CONFIG_USER_SECTION, null, "name", "Automated Test");
    config.setString(CONFIG_USER_SECTION, null, "email", "test@test.org");
    config.setString(CONFIG_REMOTE_SECTION, "origin", "url", "http://localhost:3000/butler/testRep1.git");
    config.setString(CONFIG_REMOTE_SECTION, "origin", "fetch", "+refs/heads/*:refs/remotes/origin/*");
    config.setString(CONFIG_BRANCH_SECTION, "master", "remote", "origin");
    config.setString(CONFIG_BRANCH_SECTION, "master", "merge", "refs/heads/master");
    config.save();
    // add the files located there and commit them
    Status status = git.status().call();
    DirCache index = git.add().addFilepattern(".").call();
    RevCommit commit = git.commit().setMessage("Repos initialization").call();
    log.info("Commit" + commit.getName());
    // push
    UsernamePasswordCredentialsProvider user2 = new UsernamePasswordCredentialsProvider("butler", "butler");
    RefSpec spec = new RefSpec("refs/heads/master:refs/heads/master");
    Iterable<PushResult> resultIterable = git.push().setRemote("origin").setCredentialsProvider(user2).setRefSpecs(spec).call();
    // Setup the Jenkins job
    JenkinsServer jenkins = new JenkinsServer(new URI(JENKINS_URL), JENKINS_USER, JENKINS_PASSWORD);
    waitUntilJenkinsHasBeenStartedUp(jenkins);
    // Check if the job exist. If not create it.
    Job job = jenkins.getJob(JENKINS_JOB_NAME);
    if (job == null) {
        // Read the job configuration into a string
        File jenkinsConfigFile = new File(JENKINS_CONFIGS_PATH + "test-project.xml");
        byte[] encoded = Files.readAllBytes(jenkinsConfigFile.toPath());
        String configXml = new String(encoded, Charset.defaultCharset());
        jenkins.createJob(JENKINS_JOB_NAME, configXml);
    }
    // Get the expected build number
    JobWithDetails jobAtIntitalState = jenkins.getJob(JENKINS_JOB_NAME);
    int expectedBuildNbr = jobAtIntitalState.getNextBuildNumber();
    log.info("Next build number: " + expectedBuildNbr);
    // Build the job
    jobAtIntitalState.build();
    // Wait for the job to complete
    long timeOut = 60000L;
    waitForBuildToComplete(jenkins, expectedBuildNbr, timeOut);
    // Get the data we stored in the marker file and check it
    Properties markerAsProperty = loadMarkerArtifactAsProperty(jenkins);
    String buildedCommit = markerAsProperty.getProperty("GIT_COMMIT");
    assertEquals("Not the expected GIT commit", commit.getName(), buildedCommit);
    // add the trigger to Gogs
    File jsonCommandFile = new File(JSON_COMMANDFILE_PATH + "webHookDefinition.json");
    int hookId = gogsServer.createWebHook(jsonCommandFile, "testRep1");
    log.info("Created hook with ID " + hookId);
    // Get what is the next build number of the test jenkins job
    jobAtIntitalState = jenkins.getJob(JENKINS_JOB_NAME);
    expectedBuildNbr = jobAtIntitalState.getNextBuildNumber();
    // change the source file
    changeTheSourceFile("target/test-repos/demo-app/README.md");
    // commit and push the changed file
    git.add().addFilepattern(".").call();
    RevCommit commitForHook = git.commit().setMessage("Small test modification").call();
    log.info("Commit" + commitForHook.getName());
    git.push().setRemote("origin").setCredentialsProvider(user2).setRefSpecs(spec).call();
    // wait for the build
    waitForBuildToComplete(jenkins, expectedBuildNbr, timeOut);
    // Get the data we stored in the marker file and check it
    Properties hookMarkerAsProperty = loadMarkerArtifactAsProperty(jenkins);
    String hookBuildedCommit = hookMarkerAsProperty.getProperty("GIT_COMMIT");
    assertEquals("Not the expected GIT commit", commitForHook.getName(), hookBuildedCommit);
    // Cleanup - remove the hook we created
    gogsServer.removeHook("demoApp", hookId);
}
Also used : Status(org.eclipse.jgit.api.Status) UsernamePasswordCredentialsProvider(org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider) JenkinsServer(com.offbytwo.jenkins.JenkinsServer) PushResult(org.eclipse.jgit.transport.PushResult) JobWithDetails(com.offbytwo.jenkins.model.JobWithDetails) Properties(java.util.Properties) URI(java.net.URI) StoredConfig(org.eclipse.jgit.lib.StoredConfig) DirCache(org.eclipse.jgit.dircache.DirCache) Git(org.eclipse.jgit.api.Git) RefSpec(org.eclipse.jgit.transport.RefSpec) Job(com.offbytwo.jenkins.model.Job) RevCommit(org.eclipse.jgit.revwalk.RevCommit) Test(org.junit.Test)

Example 3 with JenkinsServer

use of com.offbytwo.jenkins.JenkinsServer in project stashbot by palantir.

the class JenkinsClientManagerTest method testJCM.

@Test
public void testJCM() throws URISyntaxException {
    JenkinsServer js = jcm.getJenkinsServer(jsc, rc);
    Assert.notNull(js);
}
Also used : JenkinsServer(com.offbytwo.jenkins.JenkinsServer) Test(org.junit.Test)

Example 4 with JenkinsServer

use of com.offbytwo.jenkins.JenkinsServer in project stashbot by palantir.

the class JenkinsManager method createJob.

public void createJob(Repository repo, JobTemplate jobTemplate) {
    try {
        final RepositoryConfiguration rc = cpm.getRepositoryConfigurationForRepository(repo);
        final JenkinsServerConfiguration jsc = cpm.getJenkinsServerConfiguration(rc.getJenkinsServerName());
        final JenkinsServer jenkinsServer = jenkinsClientManager.getJenkinsServer(jsc, rc);
        final String jobName = jobTemplate.getBuildNameFor(repo);
        // If we try to create a job which already exists, we still get a
        // 200... so we should check first to make
        // sure it doesn't already exist
        Map<String, Job> jobMap = jenkinsServer.getJobs();
        if (jobMap.containsKey(jobName)) {
            throw new IllegalArgumentException("Job " + jobName + " already exists");
        }
        String xml = xmlFormatter.generateJobXml(jobTemplate, repo);
        log.trace("Sending XML to jenkins to create job: " + xml);
        jenkinsServer.createJob(jobName, xml);
    } catch (IOException e) {
        // TODO: something other than just rethrow?
        throw new RuntimeException(e);
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}
Also used : SQLException(java.sql.SQLException) JenkinsServer(com.offbytwo.jenkins.JenkinsServer) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) RepositoryConfiguration(com.palantir.stash.stashbot.persistence.RepositoryConfiguration) JenkinsServerConfiguration(com.palantir.stash.stashbot.persistence.JenkinsServerConfiguration) Job(com.offbytwo.jenkins.model.Job)

Example 5 with JenkinsServer

use of com.offbytwo.jenkins.JenkinsServer in project stashbot by palantir.

the class JenkinsManager method updateJob.

/**
 * This method IGNORES the current job XML, and regenerates it from scratch, and posts it. If any changes were made
 * to the job directly via jenkins UI, this will overwrite those changes.
 *
 * @param repo
 * @param buildType
 */
public void updateJob(Repository repo, JobTemplate jobTemplate) {
    try {
        final RepositoryConfiguration rc = cpm.getRepositoryConfigurationForRepository(repo);
        final JenkinsServerConfiguration jsc = cpm.getJenkinsServerConfiguration(rc.getJenkinsServerName());
        final JenkinsServer jenkinsServer = jenkinsClientManager.getJenkinsServer(jsc, rc);
        final String jobName = jobTemplate.getBuildNameFor(repo);
        // If we try to create a job which already exists, we still get a
        // 200... so we should check first to make
        // sure it doesn't already exist
        Map<String, Job> jobMap = jenkinsServer.getJobs();
        String xml = xmlFormatter.generateJobXml(jobTemplate, repo);
        if (jobMap.containsKey(jobName)) {
            if (!rc.getPreserveJenkinsJobConfig()) {
                log.trace("Sending XML to jenkins to update job: " + xml);
                jenkinsServer.updateJob(jobName, xml);
            } else {
                log.trace("Skipping sending XML to jenkins. Repo Config is set to preserve jenkins job config.");
            }
            return;
        }
        log.trace("Sending XML to jenkins to create job: " + xml);
        jenkinsServer.createJob(jobName, xml);
    } catch (IOException e) {
        // TODO: something other than just rethrow?
        throw new RuntimeException(e);
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}
Also used : SQLException(java.sql.SQLException) JenkinsServer(com.offbytwo.jenkins.JenkinsServer) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) RepositoryConfiguration(com.palantir.stash.stashbot.persistence.RepositoryConfiguration) JenkinsServerConfiguration(com.palantir.stash.stashbot.persistence.JenkinsServerConfiguration) Job(com.offbytwo.jenkins.model.Job)

Aggregations

JenkinsServer (com.offbytwo.jenkins.JenkinsServer)8 Job (com.offbytwo.jenkins.model.Job)7 JenkinsServerConfiguration (com.palantir.stash.stashbot.persistence.JenkinsServerConfiguration)4 RepositoryConfiguration (com.palantir.stash.stashbot.persistence.RepositoryConfiguration)4 IOException (java.io.IOException)4 URISyntaxException (java.net.URISyntaxException)4 SQLException (java.sql.SQLException)4 JobWithDetails (com.offbytwo.jenkins.model.JobWithDetails)2 JobTemplate (com.palantir.stash.stashbot.persistence.JobTemplate)2 URI (java.net.URI)2 HttpResponseException (org.apache.http.client.HttpResponseException)2 Test (org.junit.Test)2 URL (java.net.URL)1 Map (java.util.Map)1 Properties (java.util.Properties)1 Git (org.eclipse.jgit.api.Git)1 Status (org.eclipse.jgit.api.Status)1 DirCache (org.eclipse.jgit.dircache.DirCache)1 StoredConfig (org.eclipse.jgit.lib.StoredConfig)1 RevCommit (org.eclipse.jgit.revwalk.RevCommit)1