Java Code Examples for hudson.model.queue.QueueTaskFuture#get()

The following examples show how to use hudson.model.queue.QueueTaskFuture#get() . 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: AbstractPipelineTestProject.java    From aws-codecommit-trigger-plugin with Apache License 2.0 6 votes vote down vote up
protected void subscribeProject(ProjectFixture fixture) throws Exception {
    String name = UUID.randomUUID().toString();
    WorkflowJob job = jenkinsRule.getInstance().createProject(WorkflowJob.class, name);

    String script = fixture.getPipelineScript().replace("${EmitEvent}", AbstractPipelineTestProject.class.getName() + ".emitBuildEvent()");
    CpsFlowDefinition flowDefinition = new CpsFlowDefinition(script, true);
    job.setDefinition(flowDefinition);

    QueueTaskFuture<WorkflowRun> run = job.scheduleBuild2(0);
    WorkflowRun wfRun = run.get();
    Assertions.assertThat(wfRun.getResult())
        .describedAs("Pipeline unable to start succeed")
        .isEqualTo(Result.SUCCESS);
    jenkinsRule.assertBuildStatusSuccess(wfRun);

    resetPipelineBuildEvent(fixture);

    if (!fixture.isHasTrigger()) {
        return;
    }

    final String uuid = this.sqsQueue.getUuid();
    SQSTrigger trigger = new SQSTrigger(uuid, fixture.isSubscribeInternalScm(), fixture.getScmConfigs());
    job.addTrigger(trigger);
    trigger.start(job, false);
}
 
Example 2
Source File: DockerComputerConnectorTest.java    From docker-plugin with MIT License 6 votes vote down vote up
protected void should_connect_agent(DockerTemplate template) throws IOException, ExecutionException, InterruptedException, TimeoutException {

        // FIXME on CI windows nodes don't have Docker4Windows
        Assume.assumeFalse(SystemUtils.IS_OS_WINDOWS);

        String dockerHost = SystemUtils.IS_OS_WINDOWS ? "tcp://localhost:2375" : "unix:///var/run/docker.sock";

        DockerCloud cloud = new DockerCloud(cloudName, new DockerAPI(new DockerServerEndpoint(dockerHost, null)),
                Collections.singletonList(template));

        j.jenkins.clouds.replaceBy(Collections.singleton(cloud));

        final FreeStyleProject project = j.createFreeStyleProject("test-docker-ssh");
        project.setAssignedLabel(Label.get(LABEL));
        project.getBuildersList().add(new Shell("whoami"));
        final QueueTaskFuture<FreeStyleBuild> scheduledBuild = project.scheduleBuild2(0);
        try {
            final FreeStyleBuild build = scheduledBuild.get(60L, TimeUnit.SECONDS);
            Assert.assertTrue(build.getResult() == Result.SUCCESS);
            Assert.assertTrue(build.getLog().contains("jenkins"));
        } finally {
            scheduledBuild.cancel(true);
        }
    }
 
Example 3
Source File: NoDelayProvisionStrategyPerformanceTest.java    From ec2-spot-jenkins-plugin with Apache License 2.0 5 votes vote down vote up
private static void waitTasksFinish(List<QueueTaskFuture> tasks) {
    for (final QueueTaskFuture<FreeStyleBuild> task : tasks) {
        try {
            task.get();
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException(e);
        }
    }
}
 
Example 4
Source File: AWSDeviceFarmRecorderTest.java    From aws-device-farm-jenkins-plugin with Apache License 2.0 5 votes vote down vote up
@Test
@Issue("JENKINS-50483")
public void dataSerializationSmokeTest() throws Exception {
    FreeStyleProject p = j.createFreeStyleProject();
    AWSDeviceFarmRecorder rec = new AWSDeviceFarmRecorder(
            "TestProjectName", "TestDevicePool", null, null,
            null, null, "APPIUM_JAVA_JUNIT", false, false, null,
            null, null, null, null, null, null,
            null, null, null, null, null, null, null, null,
            null, null, null, null, null, null,
            null, null, null, null, false, false,
            null, null, null, null, null, null,
            false, false, false, 10, false, false,
            false, false, false, null
    );
    p.getPublishersList().add(rec);

    // Try to build it. It is not supposed to work, but we will filter out the JEP-200 exception
    final QueueTaskFuture<FreeStyleBuild> future = p.scheduleBuild2(0);
    final FreeStyleBuild build = future.get();
    j.assertBuildStatus(Result.FAILURE, build);
    // Currently it fails with Either IAM Role ARN or AKID/SKID must be set and does not report the serialization issue after that

    // No matter what, we should be able to save the project even after the failure
    p.save();
    build.save();
}
 
Example 5
Source File: BuildPageRedirectActionTest.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void redirectToBuildUrl() throws IOException, ExecutionException, InterruptedException, TimeoutException {
    FreeStyleProject testProject = jenkins.createFreeStyleProject();
    testProject.setScm(new GitSCM(gitRepoUrl));
    testProject.setQuietPeriod(0);
    QueueTaskFuture<FreeStyleBuild> future = testProject.scheduleBuild2(0);
    FreeStyleBuild build = future.get(15, TimeUnit.SECONDS);

    getBuildPageRedirectAction(testProject).execute(response);

    verify(response).sendRedirect2(jenkins.getInstance().getRootUrl() + build.getUrl());
}
 
Example 6
Source File: BuildPageRedirectActionTest.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void redirectToBuildStatusUrl() throws IOException, ExecutionException, InterruptedException, TimeoutException {
    FreeStyleProject testProject = jenkins.createFreeStyleProject();
    testProject.setScm(new GitSCM(gitRepoUrl));
    testProject.setQuietPeriod(0);
    QueueTaskFuture<FreeStyleBuild> future = testProject.scheduleBuild2(0);
    FreeStyleBuild build = future.get(15, TimeUnit.SECONDS);

    doThrow(IOException.class).when(response).sendRedirect2(jenkins.getInstance().getRootUrl() + build.getUrl());
    getBuildPageRedirectAction(testProject).execute(response);

    verify(response).sendRedirect2(jenkins.getInstance().getRootUrl() + build.getBuildStatusUrl());
}
 
Example 7
Source File: NoteBuildActionTest.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void build_alreadyBuiltMR_alreadyBuiltMR() throws IOException, ExecutionException, InterruptedException {
    FreeStyleProject testProject = jenkins.createFreeStyleProject();
    testProject.addTrigger(trigger);
    testProject.setScm(new GitSCM(gitRepoUrl));
    QueueTaskFuture<?> future = testProject.scheduleBuild2(0, new ParametersAction(new StringParameterValue("gitlabTargetBranch", "master")));
    future.get();

    exception.expect(HttpResponses.HttpResponseException.class);
    new NoteBuildAction(testProject, getJson("NoteEvent_alreadyBuiltMR.json"), null).execute(response);

    verify(trigger).onPost(any(NoteHook.class));
}
 
Example 8
Source File: NoteBuildActionTest.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void build_alreadyBuiltMR_differentTargetBranch() throws IOException, ExecutionException, InterruptedException {
    FreeStyleProject testProject = jenkins.createFreeStyleProject();
    testProject.addTrigger(trigger);
    testProject.setScm(new GitSCM(gitRepoUrl));
    QueueTaskFuture<?> future = testProject.scheduleBuild2(0, new GitLabWebHookCause(causeData()
            .withActionType(CauseData.ActionType.NOTE)
            .withSourceProjectId(1)
            .withTargetProjectId(1)
            .withBranch("feature")
            .withSourceBranch("feature")
            .withUserName("")
            .withSourceRepoHomepage("https://gitlab.org/test")
            .withSourceRepoName("test")
            .withSourceNamespace("test-namespace")
            .withSourceRepoUrl("[email protected]:test.git")
            .withSourceRepoSshUrl("[email protected]:test.git")
            .withSourceRepoHttpUrl("https://gitlab.org/test.git")
            .withMergeRequestTitle("Test")
            .withMergeRequestId(1)
            .withMergeRequestIid(1)
            .withTargetBranch("master")
            .withTargetRepoName("test")
            .withTargetNamespace("test-namespace")
            .withTargetRepoSshUrl("[email protected]:test.git")
            .withTargetRepoHttpUrl("https://gitlab.org/test.git")
            .withTriggeredByUser("test")
            .withLastCommit("123")
            .withTargetProjectUrl("https://gitlab.org/test")
            .build()));
    future.get();

    exception.expect(HttpResponses.HttpResponseException.class);
    new NoteBuildAction(testProject, getJson("NoteEvent_alreadyBuiltMR.json"), null).execute(response);

    verify(trigger).onPost(any(NoteHook.class));
}
 
Example 9
Source File: MergeRequestBuildActionTest.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void build_acceptedMr() throws IOException, ExecutionException, InterruptedException {
    FreeStyleProject testProject = jenkins.createFreeStyleProject();
    trigger.setTriggerOnAcceptedMergeRequest(true);
    trigger.setTriggerOnMergeRequest(false);
    testProject.addTrigger(trigger);
    testProject.setScm(new GitSCM(gitRepoUrl));
    QueueTaskFuture<?> future = testProject.scheduleBuild2(0, new ParametersAction(new StringParameterValue("gitlabTargetBranch", "master")));
    future.get();

    executeMergeRequestAction(testProject, getJson("MergeRequestEvent_merged.json"));
    assertTrue(wouldFire);
}
 
Example 10
Source File: MergeRequestBuildActionTest.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void build_alreadyBuiltMR_differentTargetBranch() throws IOException, ExecutionException, InterruptedException {
    FreeStyleProject testProject = jenkins.createFreeStyleProject();
    testProject.addTrigger(trigger);
    testProject.setScm(new GitSCM(gitRepoUrl));
    QueueTaskFuture<?> future = testProject.scheduleBuild2(0, new GitLabWebHookCause(causeData()
            .withActionType(CauseData.ActionType.MERGE)
            .withSourceProjectId(1)
            .withTargetProjectId(1)
            .withBranch("feature")
            .withSourceBranch("feature")
            .withUserName("")
            .withSourceRepoHomepage("https://gitlab.org/test")
            .withSourceRepoName("test")
            .withSourceNamespace("test-namespace")
            .withSourceRepoUrl("[email protected]:test.git")
            .withSourceRepoSshUrl("[email protected]:test.git")
            .withSourceRepoHttpUrl("https://gitlab.org/test.git")
            .withMergeRequestTitle("Test")
            .withMergeRequestId(1)
            .withMergeRequestIid(1)
            .withTargetBranch("master")
            .withTargetRepoName("test")
            .withTargetNamespace("test-namespace")
            .withTargetRepoSshUrl("[email protected]:test.git")
            .withTargetRepoHttpUrl("https://gitlab.org/test.git")
            .withTriggeredByUser("test")
            .withLastCommit("123")
            .withTargetProjectUrl("https://gitlab.org/test")
            .build()));
    future.get();

    executeMergeRequestAction(testProject, getJson("MergeRequestEvent_alreadyBuiltMR_differentTargetBranch.json"));

    assertTrue(wouldFire);
}
 
Example 11
Source File: DollarSecretPatternFactoryTest.java    From credentials-binding-plugin with MIT License 5 votes vote down vote up
@Issue("JENKINS-24805")
@Test
public void maskingFreeStyleSecrets() throws Exception {
    String firstCredentialsId = "creds_1";
    String firstPassword = "a$build";
    StringCredentialsImpl firstCreds = new StringCredentialsImpl(CredentialsScope.GLOBAL, firstCredentialsId, "sample1", Secret.fromString(firstPassword));

    CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), firstCreds);

    String secondCredentialsId = "creds_2";
    String secondPassword = "a$$b";
    StringCredentialsImpl secondCreds = new StringCredentialsImpl(CredentialsScope.GLOBAL, secondCredentialsId, "sample2", Secret.fromString(secondPassword));

    CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), secondCreds);

    SecretBuildWrapper wrapper = new SecretBuildWrapper(Arrays.asList(new StringBinding("PASS_1", firstCredentialsId),
            new StringBinding("PASS_2", secondCredentialsId)));

    FreeStyleProject project = r.createFreeStyleProject();

    project.setConcurrentBuild(true);
    project.getBuildersList().add(Functions.isWindows() ? new BatchFile("echo %PASS_1%") : new Shell("echo \"$PASS_1\""));
    project.getBuildersList().add(Functions.isWindows() ? new BatchFile("echo %PASS_2%") : new Shell("echo \"$PASS_2\""));
    project.getBuildersList().add(new Maven("$PASS_1 $PASS_2", "default"));
    project.getBuildWrappersList().add(wrapper);

    r.configRoundtrip((Item)project);

    QueueTaskFuture<FreeStyleBuild> future = project.scheduleBuild2(0);
    FreeStyleBuild build = future.get();
    r.assertLogNotContains(firstPassword, build);
    r.assertLogNotContains(firstPassword.replace("$", "$$"), build);
    r.assertLogNotContains(secondPassword, build);
    r.assertLogNotContains(secondPassword.replace("$", "$$"), build);
    r.assertLogContains("****", build);
}
 
Example 12
Source File: DockerShellStepIT.java    From yet-another-docker-plugin with MIT License 4 votes vote down vote up
@Test
    public void testDockerShellStep() throws Throwable {
        jRule.getInstance().setNumExecutors(0);
//        jRule.createSlave();
//        jRule.createSlave("my-slave", "remote-slave", new EnvVars());
        final UsernamePasswordCredentialsImpl credentials = new UsernamePasswordCredentialsImpl(CredentialsScope.SYSTEM,
                null, "description", "vagrant", "vagrant");

        CredentialsStore store = CredentialsProvider.lookupStores(jRule.getInstance()).iterator().next();
        store.addCredentials(Domain.global(), credentials);

        final SSHLauncher sshLauncher = new SSHLauncher("192.168.33.10", 22, credentials.getId(),
                "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005", //jvmopts
                "", //      String javaPath,
                "",  //      String prefixStartSlaveCmd,
                "", //      String suffixStartSlaveCmd,
                20, //      Integer launchTimeoutSeconds,
                1, //      Integer maxNumRetries,
                3,//      Integer retryWaitTime
                new NonVerifyingKeyVerificationStrategy()
        );
        final DumbSlave dumbSlave = new DumbSlave("docker-daemon", "/home/vagrant/jenkins2", sshLauncher);
        jRule.getInstance().addNode(dumbSlave);
        await().timeout(60, SECONDS).until(() -> assertThat(dumbSlave.getChannel(), notNullValue()));
//        String dockerfilePath = dumbSlave.getChannel().call(new DockerBuildImageStepTest.StringThrowableCallable());


        final CredentialsYADockerConnector dockerConnector = new CredentialsYADockerConnector()
                .withConnectorType(JERSEY)
                .withServerUrl("tcp://127.0.0.1:2376")
                .withSslConfig(new LocalDirectorySSLConfig("/home/vagrant/keys"));
//                .withCredentials(new DockerDaemonFileCredentials(null, "docker-cert", "",
//                        "/home/vagrant/keys"));

        DockerShellStep dockerShellStep = new DockerShellStep();
        dockerShellStep.setShellScript("env && pwd");
        dockerShellStep.setConnector(dockerConnector);

        FreeStyleProject project = jRule.createFreeStyleProject("test");
        project.getBuildersList().add(dockerShellStep);

        project.save();

        QueueTaskFuture<FreeStyleBuild> taskFuture = project.scheduleBuild2(0);
        FreeStyleBuild freeStyleBuild = taskFuture.get();

        jRule.waitForCompletion(freeStyleBuild);

        jRule.assertBuildStatusSuccess(freeStyleBuild);
    }
 
Example 13
Source File: DockerImageComboStepTest.java    From yet-another-docker-plugin with MIT License 4 votes vote down vote up
@Ignore
    @Test
    public void testComboBuild() throws Throwable {
        jRule.getInstance().setNumExecutors(0);
//        jRule.createSlave();
//        jRule.createSlave("my-slave", "remote-slave", new EnvVars());
        final UsernamePasswordCredentialsImpl credentials = new UsernamePasswordCredentialsImpl(CredentialsScope.SYSTEM,
                null, "description", "vagrant", "vagrant");

        CredentialsStore store = CredentialsProvider.lookupStores(jRule.getInstance()).iterator().next();
        store.addCredentials(Domain.global(), credentials);

        final SSHLauncher sshLauncher = new SSHLauncher("192.168.33.10", 22, credentials.getId(),
                "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005", //jvmopts
                "", //      String javaPath,
                "",  //      String prefixStartSlaveCmd,
                "", //      String suffixStartSlaveCmd,
                20, //      Integer launchTimeoutSeconds,
                1, //      Integer maxNumRetries,
                3,//      Integer retryWaitTime
                new NonVerifyingKeyVerificationStrategy()
        );
        final DumbSlave dumbSlave = new DumbSlave("docker-daemon", "/home/vagrant/jenkins2", sshLauncher);
        jRule.getInstance().addNode(dumbSlave);
        await().timeout(60, SECONDS).until(() -> assertThat(dumbSlave.getChannel(), notNullValue()));
        String dockerfilePath = dumbSlave.getChannel().call(new StringThrowableCallable());


        final CredentialsYADockerConnector dockerConnector = new CredentialsYADockerConnector()
                .withConnectorType(JERSEY)
                .withServerUrl("tcp://127.0.0.1:2376")
                .withSslConfig(new LocalDirectorySSLConfig("/home/vagrant/keys"));
//                .withCredentials(new DockerDaemonFileCredentials(null, "docker-cert", "",
//                        "/home/vagrant/keys"));

        DockerBuildImage buildImage = new DockerBuildImage();
        buildImage.setBaseDirectory(dockerfilePath);
        buildImage.setPull(true);
        buildImage.setTags(Collections.singletonList("localhost:5000/myfirstimage"));

        DockerImageComboStep comboStep = new DockerImageComboStep(dockerConnector, buildImage);
        comboStep.setClean(true);
        comboStep.setCleanupDangling(true);
        comboStep.setPush(true);

        FreeStyleProject project = jRule.createFreeStyleProject("test");
        project.getBuildersList().add(comboStep);

        project.save();

        QueueTaskFuture<FreeStyleBuild> taskFuture = project.scheduleBuild2(0);
        FreeStyleBuild freeStyleBuild = taskFuture.get();
        jRule.waitForCompletion(freeStyleBuild);
        jRule.assertBuildStatusSuccess(freeStyleBuild);
    }
 
Example 14
Source File: DockerBuildImageStepTest.java    From yet-another-docker-plugin with MIT License 4 votes vote down vote up
@Test
    public void testBuild() throws Throwable {
        jRule.getInstance().setNumExecutors(0);
//        jRule.createSlave();
//        jRule.createSlave("my-slave", "remote-slave", new EnvVars());
        final UsernamePasswordCredentialsImpl credentials = new UsernamePasswordCredentialsImpl(CredentialsScope.SYSTEM,
                null, "description", "vagrant", "vagrant");

        CredentialsStore store = CredentialsProvider.lookupStores(jRule.getInstance()).iterator().next();
        store.addCredentials(Domain.global(), credentials);

        final SSHLauncher sshLauncher = new SSHLauncher("192.168.33.10", 22, credentials.getId(),
                "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005", //jvmopts
                "", //      String javaPath,
                "",  //      String prefixStartSlaveCmd,
                "", //      String suffixStartSlaveCmd,
                20, //      Integer launchTimeoutSeconds,
                1, //      Integer maxNumRetries,
                3,//      Integer retryWaitTime
                new NonVerifyingKeyVerificationStrategy()
        );
        final DumbSlave dumbSlave = new DumbSlave("docker-daemon", "/home/vagrant/jenkins2", sshLauncher);
        jRule.getInstance().addNode(dumbSlave);
        await().timeout(60, SECONDS).until(() -> assertThat(dumbSlave.getChannel(), notNullValue()));
        String dockerfilePath = dumbSlave.getChannel().call(new StringThrowableCallable());


        final CredentialsYADockerConnector dockerConnector = new CredentialsYADockerConnector()
                .withConnectorType(JERSEY)
                .withServerUrl("tcp://127.0.0.1:2376")
                .withSslConfig(new LocalDirectorySSLConfig("/home/vagrant/keys"))
                ;
//                .withCredentials(new DockerDaemonFileCredentials(null, "docker-cert", "",
//                        "/home/vagrant/keys"));

        DockerBuildImage buildImage = new DockerBuildImage();
        buildImage.setBaseDirectory(dockerfilePath);
        buildImage.setPull(true);
        buildImage.setNoCache(true);

        DockerBuildImageStep dockerBuildImageStep = new DockerBuildImageStep(dockerConnector, buildImage);

        FreeStyleProject project = jRule.createFreeStyleProject("test");
        project.getBuildersList().add(dockerBuildImageStep);

        project.save();

        QueueTaskFuture<FreeStyleBuild> taskFuture = project.scheduleBuild2(0);
        FreeStyleBuild freeStyleBuild = taskFuture.get();
        jRule.waitForCompletion(freeStyleBuild);
        jRule.assertBuildStatusSuccess(freeStyleBuild);
    }
 
Example 15
Source File: DashboardView.java    From jenkins-deployment-dashboard-plugin with MIT License 4 votes vote down vote up
@JavaScriptMethod
public String deploy(String version, String environment) {
    LOGGER.info("Deploy version " + version + " to environment " + environment);

    // Get the environment with corresponding build-job
    Environment buildEnvironment = null;
    for (Environment env : environments) {
        if (env.getAwsInstance().equals(environment)) {
            buildEnvironment = env;
            break;
        }
    }

    final AbstractProject buildJob = Jenkins.getInstance().getItemByFullName(buildEnvironment.getBuildJob(), AbstractProject.class);
    LOGGER.info("Executing job: " + buildJob);

    if (buildJob == null) {
        return String.format(Messages.DashboardView_buildJobNotFound(), buildEnvironment.getName());
    }

    if ((!buildJob.isBuildable()) || (!buildJob.isParameterized())) {
        return Messages.DashboardView_deploymentCannotBeExecuted();
    }

    final ParametersAction versionParam = new ParametersAction(new StringParameterValue(PARAM_VERSION, version));
    final ParametersAction environmentParam = new ParametersAction(new StringParameterValue(PARAM_ENVIRONMENT, environment));
    final ParametersAction ec2RegionParam = new ParametersAction(new StringParameterValue(PARAM_EC2_REGION, environment));
    final ParametersAction awsKeyParam = new ParametersAction(new StringParameterValue(PARAM_AWS_KEY, environment));

    List<ParametersAction> actions = Arrays.asList(versionParam, environmentParam, ec2RegionParam, awsKeyParam);
    QueueTaskFuture<AbstractBuild> scheduledBuild = buildJob.scheduleBuild2(2, new Cause.UserIdCause(), actions);

    Result result = Result.FAILURE;
    try {
        AbstractBuild finishedBuild = scheduledBuild.get();
        result = finishedBuild.getResult();
        LOGGER.info("Build finished with result: " + result + " completed in: " + finishedBuild.getDurationString() + ". ");
    } catch (Exception e) {
        LOGGER.severe("Error while waiting for build " + scheduledBuild.toString() + ".");
        LOGGER.severe(e.getMessage());
        LOGGER.severe(ExceptionUtils.getFullStackTrace(e));
        return String.format(Messages.DashboardView_buildJobFailed(), buildJob.getName());
    }
    if (result == Result.SUCCESS) {
        return String.format(Messages.DashboardView_buildJobScheduledSuccessfully(), buildJob.getName());
    }
    return String.format(Messages.DashboardView_buildJobSchedulingFailed(), buildJob.getName());
}
 
Example 16
Source File: FreeStyleProjectTest.java    From lockable-resources-plugin with MIT License 4 votes vote down vote up
@Test
public void migrateToScript() throws Exception {
  LockableResourcesManager.get().createResource("resource1");

  FreeStyleProject p = j.createFreeStyleProject("p");
  p.addProperty(
      new RequiredResourcesProperty(
          null, null, null, "groovy:resourceName == 'resource1'", null));

  p.save();

  j.jenkins.reload();

  FreeStyleProject p2 = j.jenkins.getItemByFullName("p", FreeStyleProject.class);
  RequiredResourcesProperty newProp = p2.getProperty(RequiredResourcesProperty.class);
  assertNull(newProp.getLabelName());
  assertNotNull(newProp.getResourceMatchScript());
  assertEquals("resourceName == 'resource1'", newProp.getResourceMatchScript().getScript());

  SemaphoreBuilder p2Builder = new SemaphoreBuilder();
  p2.getBuildersList().add(p2Builder);

  FreeStyleProject p3 = j.createFreeStyleProject("p3");
  p3.addProperty(new RequiredResourcesProperty("resource1", null, "1", null, null));
  SemaphoreBuilder p3Builder = new SemaphoreBuilder();
  p3.getBuildersList().add(p3Builder);

  final QueueTaskFuture<FreeStyleBuild> taskA =
      p3.scheduleBuild2(0, new TimerTrigger.TimerTriggerCause());
  TestHelpers.waitForQueue(j.jenkins, p3);
  final QueueTaskFuture<FreeStyleBuild> taskB =
      p2.scheduleBuild2(0, new TimerTrigger.TimerTriggerCause());

  p3Builder.release();
  final FreeStyleBuild buildA = taskA.get(60, TimeUnit.SECONDS);
  p2Builder.release();
  final FreeStyleBuild buildB = taskB.get(60, TimeUnit.SECONDS);

  long buildAEndTime = buildA.getStartTimeInMillis() + buildA.getDuration();
  assertTrue(
      "Project A build should be finished before the build of project B starts. "
          + "A finished at "
          + buildAEndTime
          + ", B started at "
          + buildB.getStartTimeInMillis(),
      buildB.getStartTimeInMillis() >= buildAEndTime);
}