com.offbytwo.jenkins.model.JobWithDetails Java Examples

The following examples show how to use com.offbytwo.jenkins.model.JobWithDetails. 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: GogsWebHook_IT.java    From gogs-webhook-plugin with MIT License 7 votes vote down vote up
/**
 * Wait for the build to be queued and complete
 *
 * @param jenkins          Jenkins server instance
 * @param expectedBuildNbr the build number we're are expecting
 * @param timeOut          the maximum time in millisecond we are waiting
 * @throws InterruptedException the build was interrupted
 * @throws TimeoutException     we exeeded the timeout period.
 * @throws IOException          an unexpected error occurred while communicating with Jenkins
 */
private void waitForBuildToComplete(JenkinsServer jenkins, int expectedBuildNbr, long timeOut, String jobname) throws InterruptedException, TimeoutException, IOException {
    boolean buildCompleted = false;
    long timeoutCounter = 0L;
    while (!buildCompleted) {
        Thread.sleep(2000);
        timeoutCounter = timeoutCounter + 2000L;
        if (timeoutCounter > timeOut) {
            throw new TimeoutException("The job did not complete in the expected time");
        }
        //When the build is in the queue, the nextbuild number didn't change.
        //When it changed, It might still be running.
        JobWithDetails wrkJobData = jenkins.getJob(jobname);
        int newNextNbr = wrkJobData.getNextBuildNumber();
        log.info("New Next Nbr:" + newNextNbr);
        if (expectedBuildNbr != newNextNbr) {
            log.info("The expected build is there");
            boolean isBuilding = wrkJobData.getLastBuild().details().isBuilding();
            if (!isBuilding) {
                buildCompleted = true;
            }
        }
    }
}
 
Example #2
Source File: TestJenkinsVerifier.java    From verigreen with Apache License 2.0 6 votes vote down vote up
@Test
public void testStopBuildById() throws IOException, InterruptedException {
    
    String jobName = "testing-jenkins-api";
    String parameterNameForJob = "ParamForTesting";
    final ImmutableMap<String, String> params = ImmutableMap.of(parameterNameForJob, "master");
    
    BuildVerifier buildVerifier = CollectorApi.getJenkinsVerifier();
    JenkinsServer jenkninsServer = CollectorApi.getJenkinsServer();
    JobWithDetails job = jenkninsServer.getJob(jobName);
    int nextBuildNumber = job.getNextBuildNumber();
    job.build(params);
    Thread.sleep(5000);
    boolean stopBuildResult =
            ((JenkinsVerifier) buildVerifier).stop(jobName, Integer.toString(nextBuildNumber));
    Assert.assertEquals(true, stopBuildResult);
}
 
Example #3
Source File: JenkinsServerIntegration.java    From verigreen with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateJob() throws Exception {
    final String sourceJob = "pr";
    final String jobName = "test-job-" + UUID.randomUUID().toString();

    String sourceXml = server.getJobXml(sourceJob);

    server.createJob(jobName, sourceXml);

    Map<String, Job> jobs = server.getJobs();
    assertTrue(jobs.containsKey(jobName));
    JobWithDetails thisJob = jobs.get(jobName).details();
    assertNotNull(thisJob);
    assertTrue(thisJob.getBuilds().size() == 0);
    thisJob.build(ImmutableMap.of("foo_param", "MUST_PROVIDE_VALUES_DEFAULTS_DONT_WORK"));

    // wait to see if the job finishes, but with a timeout
    Future<Void> future = executor.submit(new PerformPollingTest(server, jobName));

    // If this times out, either jenkins is slow or our test failed!
    // IME, usually takes about 10-15 seconds
    future.get(30, TimeUnit.SECONDS);

    Build b = server.getJobs().get(jobName).details().getLastSuccessfulBuild();
    assertTrue(b != null);
}
 
Example #4
Source File: ClassicJobApi.java    From blueocean-plugin with MIT License 6 votes vote down vote up
public void abortAllBuilds(Folder folder, String pipeline) throws IOException {
    JobWithDetails job = jenkins.getJob(getFolder(folder, false), pipeline);

    for(Build build: job.getBuilds()){
        if(build.details().getResult() == null) {
            build.details().Stop();
            logger.info("Stopped build " + folder.getPath(pipeline) + " - #" + build.getNumber());
        }
    }

    Optional<FolderJob> folderJobOptional = jenkins.getFolderJob(job);

    if(folderJobOptional.isPresent()) {
        for (String s : folderJobOptional.get().getJobs().keySet()) {
            abortAllBuilds(folder.append(pipeline), s);
        }
    }
}
 
Example #5
Source File: BentenJenkinsClientTest.java    From benten with MIT License 5 votes vote down vote up
@Test
public void testGetJobByJobName() throws JsonProcessingException {
    String jobName = "BenTen-Env-Stability";
    JobWithDetails jobWithDetails = bentenJenkinsClient.getJobByJobName(jobName);
    String jobNameFromJenkins = jobWithDetails.getDisplayName();
    Assert.assertEquals("Build Names dont match",jobName, jobNameFromJenkins);
}
 
Example #6
Source File: BentenJenkinsClient.java    From benten with MIT License 5 votes vote down vote up
public String build(String jobName){
    logger.info("Building Jenkins job with jobName: " + jobName);

    try {
        Job job = jenkins.getJob(jobName);
        logger.info(jobName + " is buildable: " + job.details().isBuildable());
        int lastBuildNumber = job.details().getLastBuild().getNumber();
        int nextBuildNumber = job.details().getNextBuildNumber();

        QueueReference queueReference = job.build();
        logger.debug(job.toString());
        int waitFor = 0;
        while(job.details().isInQueue()){
            waitFor++;
            logger.info("Job in queue");
            Thread.sleep(5000);
            if(waitFor>4) return "Job is built successfully, but is in Queue";

        }
        JobWithDetails jobWithDetails =job.details();
        if(job.details().getBuildByNumber(nextBuildNumber).details().isBuilding()) {
            logger.info("Jenkins job "+ jobName +" is building with Build Number: " + nextBuildNumber);
            return "Jenkins job "+ jobName +" is building with Build Number: " + nextBuildNumber;
        }
        else {
            logger.info("Jenkins job is stuck for :" + jobName);
            return "Jenkins job is stuck for :" + jobName;
        }

    } catch (Exception e) {
        logger.info("Failed to build Jenkins job with jobName: " + jobName);
        e.printStackTrace();
        throw new BentenJenkinsException(e.getMessage());
    }
}
 
Example #7
Source File: ClassicJobApi.java    From blueocean-plugin with MIT License 5 votes vote down vote up
public com.google.common.base.Function<WebDriver, Boolean> untilJobResultFunction(AbstractPipeline pipeline, BuildResult desiredResult) {
    return driver -> {
        try {
            JobWithDetails job = ClassicJobApi.this.jenkins.getJob(ClassicJobApi.this.getFolder(pipeline.getFolder(), false), pipeline.getName());
            BuildResult result = job.getLastBuild().details().getResult();
            return result == desiredResult;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    };
}
 
Example #8
Source File: GogsWebHook_IT.java    From gogs-webhook-plugin with MIT License 5 votes vote down vote up
/**
 * Loads the marker file of the last build (archived during the build)
 *
 * @param jenkins the jenkins instance we want to load from
 * @return the marker file loaded as a property file (so that it can be easily queried)
 * @throws IOException        Something unexpected went wrong when querying the Jenkins server
 * @throws URISyntaxException Something unexpected went wrong loading the marker as a property
 */
private Properties loadMarkerArtifactAsProperty(JenkinsServer jenkins, String jobName) throws IOException, URISyntaxException {
    JobWithDetails detailedJob = jenkins.getJob(jobName);
    BuildWithDetails lastBuild = detailedJob.getLastBuild().details();
    int buildNbr = lastBuild.getNumber();
    boolean isBuilding = lastBuild.isBuilding();
    log.info("BuildNbr we are examining: " + buildNbr);

    List<Artifact> artifactList = lastBuild.getArtifacts();
    assertEquals("Not the expected number of artifacts", 1, artifactList.size());

    Artifact markerArtifact = artifactList.get(0);
    String markerArtifactFileName = markerArtifact.getFileName();
    assertEquals("The artifact is not the expected one", "marker.txt", markerArtifactFileName);
    InputStream markerArtifactInputStream = lastBuild.details().downloadArtifact(markerArtifact);
    String markerAsText = IOUtils.toString(markerArtifactInputStream, Charset.defaultCharset());
    log.info("\n" + markerAsText);
    StringReader reader = new StringReader(markerAsText);
    Properties markerAsProperty = new Properties();
    markerAsProperty.load(reader);

    //check if the marker matches the build number we expect.
    String buildNbrFromMarker = markerAsProperty.getProperty("BUILD_NUMBER");
    String buildNbrFromQery = String.valueOf(buildNbr);
    assertEquals("The build number from the marker does not match the last build number", buildNbrFromMarker, buildNbrFromQery);
    return markerAsProperty;
}
 
Example #9
Source File: BentenJenkinsClient.java    From benten with MIT License 5 votes vote down vote up
public JobWithDetails getJobByJobName(String jobName){
    try{
        logger.info("Get Jenkins job by JobName: " + jobName);
        return jenkins.getJob(jobName);
    }catch (Exception e){
        logger.error("Failed to get Jenkins job by JobName: " + jobName);
        e.printStackTrace();
        throw new BentenJenkinsException(e.getMessage());
    }
}
 
Example #10
Source File: JenkinsServerIntegration.java    From verigreen with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnBuildStatusForBuild() throws Exception {
    JobWithDetails job = server.getJobs().get("pr").details();
    BuildWithDetails build = job.getBuilds().get(0).details();
    assertEquals(BuildResult.SUCCESS, build.getResult());
    assertEquals("foobar", build.getParameters().get("REVISION"));
}
 
Example #11
Source File: JenkinsServerIntegration.java    From verigreen with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetJobByName() throws Exception {
    final String jobName = "trunk";

    JobWithDetails job = server.getJob(jobName);

    assertEquals("trunk",job.getName());
    assertEquals("trunk",job.getDisplayName());
}
 
Example #12
Source File: JenkinsServerIntegration.java    From verigreen with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetJobByNameDoesntExist() throws Exception {
    final String jobName = "imprettysurethereisnojobwiththisname";

    JobWithDetails job = server.getJob(jobName);

    assertEquals(null, job);
}
 
Example #13
Source File: JenkinsServerIntegration.java    From verigreen with Apache License 2.0 5 votes vote down vote up
public Void call() throws InterruptedException, IOException {
    while(true) {
        Thread.sleep(500);
        JobWithDetails jwd = server.getJobs().get(jobName).details();

        try {
            // Throws NPE until the first build succeeds
            jwd.getLastSuccessfulBuild();
        } catch (NullPointerException e) {
            continue;
        }
        // build succeeded
        return null;
    }
}
 
Example #14
Source File: JenkinsVerifier.java    From verigreen with Apache License 2.0 5 votes vote down vote up
@Override
public boolean stop(String jobName, String buildIdToStop) {
    //TODO: Remove unnecessary calls to Jenkins for stopping a Build. Try to minimize the number of calls.   
    boolean ans = false;
    try {
        VerigreenLogger.get().log(
                getClass().getName(),
                RuntimeUtils.getCurrentMethodName(),
                String.format("Stopping build (%s)", buildIdToStop));
        JobWithDetails job = CollectorApi.getJenkinsServer().getJob(jobName);
        Build buildToStop = job.getBuildByNumber(Integer.parseInt(buildIdToStop));
        if (buildIdToStop != null) {
            buildToStop.Stop();
            ans = buildToStop.details().getResult().equals(BuildResult.ABORTED);
        } else {
            VerigreenLogger.get().error(
                    getClass().getName(),
                    RuntimeUtils.getCurrentMethodName(),
                    String.format(
                            "There is no build number [%s] for job [%s]",
                            buildIdToStop,
                            jobName));
        }
    } catch (Throwable e) {
        VerigreenLogger.get().error(
                getClass().getName(),
                RuntimeUtils.getCurrentMethodName(),
                String.format("Failed to stop build [%s] for job [%s]", buildIdToStop, jobName),
                e);
    }
    
    return ans;
}
 
Example #15
Source File: TestJenkinsVerifier.java    From verigreen with Apache License 2.0 5 votes vote down vote up
@Test
public void testBuild() throws IOException {
    
	String jobName = "testing-jenkins-api";
    String parameterNameForJob = "ParamForTesting";
    final ImmutableMap<String, String> params = ImmutableMap.of(parameterNameForJob, "master");
    JenkinsServer jenkninsServer = CollectorApi.getJenkinsServer();
    JobWithDetails job = jenkninsServer.getJob(jobName);
    job.build(params);
}
 
Example #16
Source File: ForgeTestSupport.java    From fabric8-forge with Apache License 2.0 4 votes vote down vote up
protected Build assertCodeChangeTriggersWorkingBuild(final String projectName, Build firstBuild) throws Exception {
    File cloneDir = new File(getBasedir(), "target/projects/" + projectName);

    String gitUrl = asserGetAppGitCloneURL(forgeClient, projectName);
    Git git = ForgeClientAsserts.assertGitCloneRepo(gitUrl, cloneDir);

    // lets make a dummy commit...
    File readme = new File(cloneDir, "ReadMe.md");
    boolean mustAdd = false;
    String text = "";
    if (readme.exists()) {
        text = IOHelpers.readFully(readme);
    } else {
        mustAdd = true;
    }
    text += "\nupdated at: " + new Date();
    Files.writeToFile(readme, text, Charset.defaultCharset());

    if (mustAdd) {
        AddCommand add = git.add().addFilepattern("*").addFilepattern(".");
        add.call();
    }


    LOG.info("Committing change to " + readme);

    CommitCommand commit = git.commit().setAll(true).setAuthor(forgeClient.getPersonIdent()).setMessage("dummy commit to trigger a rebuild");
    commit.call();
    PushCommand command = git.push();
    command.setCredentialsProvider(forgeClient.createCredentialsProvider());
    command.setRemote("origin").call();

    LOG.info("Git pushed change to " + readme);

    // now lets wait for the next build to start
    int nextBuildNumber = firstBuild.getNumber() + 1;


    Asserts.assertWaitFor(10 * 60 * 1000, new Block() {
        @Override
        public void invoke() throws Exception {
            JobWithDetails job = assertJob(projectName);
            Build lastBuild = job.getLastBuild();
            assertThat(lastBuild.getNumber()).describedAs("Waiting for latest build for job " + projectName + " to start").isGreaterThanOrEqualTo(nextBuildNumber);
        }
    });

    return ForgeClientAsserts.assertBuildCompletes(forgeClient, projectName);
}
 
Example #17
Source File: ForgeClientAsserts.java    From fabric8-forge with Apache License 2.0 4 votes vote down vote up
public static JobWithDetails assertJob(String projectName) throws URISyntaxException, IOException {
    JenkinsServer jenkins = createJenkinsServer();
    JobWithDetails job = jenkins.getJob(projectName);
    assertThat(job).describedAs("No Jenkins Job found for name: " + projectName).isNotNull();
    return job;
}
 
Example #18
Source File: JenkinsServerIntegration.java    From verigreen with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldReturnBuildsForJob() throws Exception {
    JobWithDetails job = server.getJobs().get("trunk").details();
    assertEquals(5, job.getBuilds().get(0).getNumber());
}
 
Example #19
Source File: SlackJenkinsMessageRenderer.java    From benten with MIT License 4 votes vote down vote up
public static BentenSlackResponse renderJobDetailByJobName(JobWithDetails jobWithDetails) {

        BentenSlackResponse bentenSlackResponse= new BentenSlackResponse();
        try{
            if(jobWithDetails!=null){
                List<BentenSlackField> bentenSlackFields = new ArrayList<BentenSlackField>();
                List<BentenSlackAttachment> bentenSlackAttachments = new ArrayList<BentenSlackAttachment>();
                BentenSlackAttachment bentenSlackAttachment = new BentenSlackAttachment();

                bentenSlackResponse.setSlackText("Below is the Job details");
                SlackFormatter slackFormatter = SlackFormatter.create();
                slackFormatter.link(jobWithDetails.getUrl(),jobWithDetails.getDisplayName()).text(jobWithDetails.getDescription()).newline().newline();

                BuildResult buildResult = jobWithDetails.getLastBuild().details().getResult();
                if(buildResult!=null) {
                    bentenSlackFields.add(new BentenSlackField("Last Build Status", buildResult.toString(), true));
                    if(buildResult.equals(BuildResult.SUCCESS))
                        bentenSlackAttachment.setColor("GOOD");
                    else if(buildResult.equals(BuildResult.FAILURE))
                        bentenSlackAttachment.setColor("DANGER");
                    else if(buildResult.equals(BuildResult.UNSTABLE))
                        bentenSlackAttachment.setColor("WARNING");
                    else
                        bentenSlackAttachment.setColor("WARNING");
                }
                else {
                    bentenSlackFields.add(new BentenSlackField("Last Build Status", "INPROGRESS", true));
                }
                bentenSlackFields.add(new BentenSlackField("Last Build",Integer.toString(jobWithDetails.getLastBuild().getNumber()),true));
                bentenSlackFields.add(new BentenSlackField("Last Successful Build",Integer.toString(jobWithDetails.getLastSuccessfulBuild().getNumber()),true));
                bentenSlackFields.add(new BentenSlackField("Last Failed Build",Integer.toString(jobWithDetails.getLastFailedBuild().getNumber()),true));
                bentenSlackFields.add(new BentenSlackField("Is in Queue",Boolean.toString(jobWithDetails.isInQueue()),true));
                bentenSlackFields.add(new BentenSlackField("Is Buildable",Boolean.toString(jobWithDetails.isBuildable()),true));

                bentenSlackAttachment.setText(slackFormatter.build());
                bentenSlackAttachment.setBentenSlackFields(bentenSlackFields);
                bentenSlackAttachments.add(bentenSlackAttachment);

                bentenSlackResponse.setBentenSlackAttachments(bentenSlackAttachments);
            }
            else {
                bentenSlackResponse.setSlackText("Errr!! The Jenkins Job was not found.");
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new BentenJenkinsException(e.getMessage());
        }
        return bentenSlackResponse;
    }
 
Example #20
Source File: JenkinsJobDetailsByJobNameActionHandler.java    From benten with MIT License 3 votes vote down vote up
public BentenHandlerResponse handle(BentenMessage bentenMessage) {
    String jobName = BentenMessageHelper.getParameterAsString(bentenMessage,JenkinsActionParameters.PARAMETER_JOB_JOBNAME);

    JobWithDetails jobWithDetails = bentenJenkinsClient.getJobByJobName(jobName);

    BentenHandlerResponse bentenHandlerResponse = new BentenHandlerResponse();
    bentenHandlerResponse.setBentenSlackResponse(SlackJenkinsMessageRenderer.renderJobDetailByJobName(jobWithDetails));

    return bentenHandlerResponse;
}