Search in sources :

Example 1 with Job

use of com.offbytwo.jenkins.model.Job in project fabric8 by fabric8io.

the class JenkinsAsserts method findJobPath.

/**
 * Tries to find a job via the given path
 */
public static JobWithDetails findJobPath(JenkinsServer jenkins, String... jobPath) throws IOException {
    FolderJob folder = null;
    for (int i = 0, size = jobPath.length; i < size; i++) {
        String path = jobPath[i];
        if (size == 1 && i == 0) {
            return jenkins.getJob(path);
        }
        if (folder == null) {
            JobWithDetails jobDetails = jenkins.getJob(path);
            if (jobDetails == null) {
                return null;
            }
            Job job = new Job(jobDetails.getName(), jobDetails.getUrl());
            Optional<FolderJob> optional = jenkins.getFolderJob(job);
            if (!optional.isPresent()) {
                return null;
            }
            folder = optional.get();
            continue;
        }
        Job job = folder.getJob(path);
        if (job == null) {
            return null;
        }
        if (i == size - 1) {
            return job.details();
        } else {
            Optional<FolderJob> optional = jenkins.getFolderJob(job);
            if (!optional.isPresent()) {
                return null;
            }
            folder = optional.get();
        }
    }
    return null;
}
Also used : JobWithDetails(com.offbytwo.jenkins.model.JobWithDetails) FolderJob(com.offbytwo.jenkins.model.FolderJob) Job(com.offbytwo.jenkins.model.Job) FolderJob(com.offbytwo.jenkins.model.FolderJob)

Example 2 with Job

use of com.offbytwo.jenkins.model.Job in project fabric8 by fabric8io.

the class JenkinsAsserts method deleteAllCurrentJobs.

public static void deleteAllCurrentJobs(JenkinsServer jenkins) throws IOException {
    int numberOfAttempts = 2;
    for (int i = 1; i < numberOfAttempts; i++) {
        if (i > 1) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
            // ignore
            }
        }
        Map<String, Job> jobs = jenkins.getJobs();
        Set<Map.Entry<String, Job>> entries = jobs.entrySet();
        for (Map.Entry<String, Job> entry : entries) {
            String jobName = entry.getKey();
            Job job = entry.getValue();
            LOG.info("Deleting job " + jobName);
            try {
                jenkins.deleteJob(jobName, true);
            } catch (IOException e) {
                LOG.warn("Failed to delete job: " + jobName + ". " + e, e);
            }
        }
        if (numberOfJobs(jenkins) == 0) {
            return;
        }
    }
}
Also used : IOException(java.io.IOException) FolderJob(com.offbytwo.jenkins.model.FolderJob) Job(com.offbytwo.jenkins.model.Job) Map(java.util.Map)

Example 3 with Job

use of com.offbytwo.jenkins.model.Job 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 4 with Job

use of com.offbytwo.jenkins.model.Job 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 5 with Job

use of com.offbytwo.jenkins.model.Job in project stashbot by palantir.

the class JenkinsManagerTest method testPreserveJenkinsJobConfigDisabled.

@Test
public void testPreserveJenkinsJobConfigDisabled() throws IOException {
    JobTemplate jt = jtm.getDefaultVerifyJob();
    HashMap<String, Job> jobs = Maps.newHashMap();
    // update job logic requires the job be there already
    jobs.put(jt.getBuildNameFor(repo), new Job());
    Mockito.when(rc.getPreserveJenkinsJobConfig()).thenReturn(false);
    Mockito.when(jenkinsServer.getJobs()).thenReturn(jobs);
    jenkinsManager.updateJob(repo, jt);
    Mockito.verify(jenkinsServer).updateJob(Mockito.anyString(), Mockito.anyString());
}
Also used : JobTemplate(com.palantir.stash.stashbot.persistence.JobTemplate) Job(com.offbytwo.jenkins.model.Job) Test(org.junit.Test)

Aggregations

Job (com.offbytwo.jenkins.model.Job)15 JenkinsServer (com.offbytwo.jenkins.JenkinsServer)7 JobTemplate (com.palantir.stash.stashbot.persistence.JobTemplate)6 IOException (java.io.IOException)5 Test (org.junit.Test)5 FolderJob (com.offbytwo.jenkins.model.FolderJob)4 JobWithDetails (com.offbytwo.jenkins.model.JobWithDetails)4 JenkinsServerConfiguration (com.palantir.stash.stashbot.persistence.JenkinsServerConfiguration)4 RepositoryConfiguration (com.palantir.stash.stashbot.persistence.RepositoryConfiguration)4 URISyntaxException (java.net.URISyntaxException)4 SQLException (java.sql.SQLException)4 Map (java.util.Map)4 URI (java.net.URI)2 HashMap (java.util.HashMap)2 HttpResponseException (org.apache.http.client.HttpResponseException)2 Build (com.offbytwo.jenkins.model.Build)1 BuildWithDetails (com.offbytwo.jenkins.model.BuildWithDetails)1 URL (java.net.URL)1 Properties (java.util.Properties)1 Git (org.eclipse.jgit.api.Git)1