Skip to content

Commit 641cd1b

Browse files
authored
Merge pull request aerogear-attic#3 from aliok/AGDIGGER-59-trigger-jenkins-job-2
AGDIGGER-59 trigger jenkins job - 2
2 parents 795eb04 + 2271ff0 commit 641cd1b

File tree

5 files changed

+107
-57
lines changed

5 files changed

+107
-57
lines changed

README.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,20 @@ A java integration library for AeroGear Digger
44

55
## Usage
66

7+
Build a default client:
8+
```
9+
DiggerClient client = DiggerClient.createDefaultWithAuth("https://digger.com", "admin", "password");
10+
```
11+
12+
Build a customized client:
13+
```
14+
DiggerClient client = DiggerClient.builder()
15+
.createJobService(new CreateJobService())
16+
.triggerBuildService(new TriggerBuildService(10000, 100))
17+
.withAuth("https://digger.com", "admin", "password")
18+
.build();
19+
```
20+
721
Create job:
822

923
```

src/main/java/com/redhat/digkins/DiggerClient.java

Lines changed: 55 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -22,30 +22,71 @@ public class DiggerClient {
2222

2323
public static final long DEFAULT_BUILD_TIMEOUT = 60 * 1000;
2424

25-
private final JenkinsServer jenkins;
25+
private JenkinsServer jenkinsServer;
2626

27-
public DiggerClient(JenkinsAuth auth) throws URISyntaxException {
28-
this.jenkins = new JenkinsServer(new URI(auth.getUrl()), auth.getUser(), auth.getPassword());
27+
private CreateJobService createJobService;
28+
private TriggerBuildService triggerBuildService;
29+
30+
private DiggerClient() {
2931
}
3032

3133
/**
32-
* Create client using provided url and credentials
34+
* Create a client with defaults using provided url and credentials.
35+
* <p>
36+
* This client will use the defaults for the services. This is perfectly fine for majorith of the cases.
3337
*
3438
* @param url Jenkins url
3539
* @param user Jenkins user
3640
* @param password Jenkins password
3741
* @return client instance
3842
* @throws DiggerClientException if something goes wrong
3943
*/
40-
public static DiggerClient from(String url, String user, String password) throws DiggerClientException {
41-
try {
42-
JenkinsAuth jenkinsAuth = new JenkinsAuth(url, user, password);
43-
return new DiggerClient(jenkinsAuth);
44-
} catch (URISyntaxException e) {
45-
throw new DiggerClientException("Invalid jenkins url format.");
44+
public static DiggerClient createDefaultWithAuth(String url, String user, String password) throws DiggerClientException {
45+
return DiggerClient.builder()
46+
.createJobService(new CreateJobService())
47+
.triggerBuildService(new TriggerBuildService(TriggerBuildService.DEFAULT_FIRST_CHECK_DELAY, TriggerBuildService.DEFAULT_POLL_PERIOD))
48+
.withAuth(url, user, password)
49+
.build();
50+
}
51+
52+
public static DiggerClientBuilder builder() {
53+
return new DiggerClientBuilder();
54+
}
55+
56+
public static class DiggerClientBuilder {
57+
private JenkinsAuth auth;
58+
private CreateJobService createJobService;
59+
private TriggerBuildService triggerBuildService;
60+
61+
public DiggerClientBuilder withAuth(String url, String user, String password) {
62+
this.auth = new JenkinsAuth(url, user, password);
63+
return this;
64+
}
65+
66+
public DiggerClientBuilder createJobService(CreateJobService createJobService) {
67+
this.createJobService = createJobService;
68+
return this;
69+
}
70+
71+
public DiggerClientBuilder triggerBuildService(TriggerBuildService triggerBuildService) {
72+
this.triggerBuildService = triggerBuildService;
73+
return this;
74+
}
75+
76+
public DiggerClient build() throws DiggerClientException {
77+
final DiggerClient client = new DiggerClient();
78+
try {
79+
client.jenkinsServer = new JenkinsServer(new URI(auth.getUrl()), auth.getUser(), auth.getPassword());
80+
client.createJobService = this.createJobService;
81+
client.triggerBuildService = this.triggerBuildService;
82+
return client;
83+
} catch (URISyntaxException e) {
84+
throw new DiggerClientException("Invalid jenkins url format.");
85+
}
4686
}
4787
}
4888

89+
4990
/**
5091
* Create new Digger job on Jenkins platform
5192
*
@@ -55,9 +96,8 @@ public static DiggerClient from(String url, String user, String password) throws
5596
* @throws DiggerClientException if something goes wrong
5697
*/
5798
public void createJob(String name, String gitRepo, String gitBranch) throws DiggerClientException {
58-
CreateJobService service = new CreateJobService(this.jenkins);
5999
try {
60-
service.create(name, gitRepo, gitBranch);
100+
createJobService.create(this.jenkinsServer, name, gitRepo, gitBranch);
61101
} catch (Throwable e) {
62102
throw new DiggerClientException(e);
63103
}
@@ -72,22 +112,21 @@ public void createJob(String name, String gitRepo, String gitBranch) throws Digg
72112
* This method will block until there is a build number, or the given timeout period is passed. If the build is still in the queue
73113
* after the given timeout period, a {@code BuildStatus} is returned with state {@link BuildStatus.State#TIMED_OUT}.
74114
* <p>
75-
* Please note that timeout period is never meant to be very precise. It has the resolution of {@link TriggerBuildService#POLL_PERIOD} because
115+
* Please note that timeout period is never meant to be very precise. It has the resolution of {@link TriggerBuildService#DEFAULT_POLL_PERIOD} because
76116
* timeout is checked before every pull.
77117
* <p>
78118
* Similarly, {@link BuildStatus.State#CANCELLED_IN_QUEUE} is returned if the build is cancelled on Jenkins side and
79119
* {@link BuildStatus.State#STUCK_IN_QUEUE} is returned if the build is stuck.
80120
*
81121
* @param jobName name of the job to trigger the build
82122
* @param timeout how many milliseconds should this call block before returning {@link BuildStatus.State#TIMED_OUT}.
83-
* Should be larger than {@link TriggerBuildService#FIRST_CHECK_DELAY}
123+
* Should be larger than {@link TriggerBuildService#DEFAULT_FIRST_CHECK_DELAY}
84124
* @return the build status
85125
* @throws DiggerClientException if connection problems occur during connecting to Jenkins
86126
*/
87127
public BuildStatus build(String jobName, long timeout) throws DiggerClientException {
88-
final TriggerBuildService triggerBuildService = new TriggerBuildService(jenkins);
89128
try {
90-
return triggerBuildService.build(jobName, timeout);
129+
return triggerBuildService.build(this.jenkinsServer, jobName, timeout);
91130
} catch (IOException e) {
92131
LOG.debug("Exception while connecting to Jenkins", e);
93132
throw new DiggerClientException(e);

src/main/java/com/redhat/digkins/services/CreateJobService.java

Lines changed: 8 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -14,26 +14,20 @@ public class CreateJobService {
1414
private final static String GIT_REPO_URL = "GIT_REPO_URL";
1515
private final static String GIT_REPO_BRANCH = "GIT_REPO_BRANCH";
1616

17-
private JenkinsServer jenkins;
18-
19-
/**
20-
* @param jenkins jenkins api instance
21-
*/
22-
public CreateJobService(JenkinsServer jenkins) {
23-
this.jenkins = jenkins;
24-
}
17+
private static final String JOB_TEMPLATE_PATH = "templates/job.xml";
2518

2619
/**
2720
* Create new digger job on jenkins platform
2821
*
29-
* @param name job name that can be used later to reference job
30-
* @param gitRepo git repository url (full git repository url. e.g [email protected]:digger/helloworld.git
31-
* @param gitBranch git repository branch (default branch used to checkout source code)
22+
* @param jenkinsServer Jenkins server client
23+
* @param name job name that can be used later to reference job
24+
* @param gitRepo git repository url (full git repository url. e.g [email protected]:digger/helloworld.git
25+
* @param gitBranch git repository branch (default branch used to checkout source code)
3226
*/
33-
public void create(String name, String gitRepo, String gitBranch) throws IOException {
34-
JtwigTemplate template = JtwigTemplate.classpathTemplate("templates/job.xml");
27+
public void create(JenkinsServer jenkinsServer, String name, String gitRepo, String gitBranch) throws IOException {
28+
JtwigTemplate template = JtwigTemplate.classpathTemplate(JOB_TEMPLATE_PATH);
3529
JtwigModel model = JtwigModel.newModel().with(GIT_REPO_URL, gitRepo).with(GIT_REPO_BRANCH, gitBranch);
36-
jenkins.createJob(name, template.render(model));
30+
jenkinsServer.createJob(name, template.render(model));
3731
}
3832

3933
}

src/main/java/com/redhat/digkins/services/TriggerBuildService.java

Lines changed: 19 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -19,36 +19,40 @@ public class TriggerBuildService {
1919
private static final Logger LOG = LoggerFactory.getLogger(TriggerBuildService.class);
2020

2121
/**
22-
* How long should we wait before we start checking the queue item status.
22+
* Default value of {@link #firstCheckDelay}
2323
*/
24-
public static final long FIRST_CHECK_DELAY = 5 * 1000L;
24+
public static final long DEFAULT_FIRST_CHECK_DELAY = 5 * 1000L;
2525

2626
/**
27-
* How long should we wait before checking the queue item status for next time.
27+
* Default value of {@link #pollPeriod}
2828
*/
29-
public static final long POLL_PERIOD = 2 * 1000L;
29+
public static final long DEFAULT_POLL_PERIOD = 2 * 1000L;
3030

3131

32-
private JenkinsServer jenkinsServer;
32+
private long firstCheckDelay;
33+
private long pollPeriod;
3334

3435
/**
35-
* @param jenkinsServer jenkins api instance
36+
* @param firstCheckDelay how long should we wait (in milliseconds) before we start checking the queue item status
37+
* @param pollPeriod how long should we wait (in milliseconds) before checking the queue item status for next time
3638
*/
37-
public TriggerBuildService(JenkinsServer jenkinsServer) {
38-
this.jenkinsServer = jenkinsServer;
39+
public TriggerBuildService(long firstCheckDelay, long pollPeriod) {
40+
this.firstCheckDelay = firstCheckDelay;
41+
this.pollPeriod = pollPeriod;
3942
}
4043

4144
/**
4245
* See the documentation in {@link com.redhat.digkins.DiggerClient#build(String, long)}
4346
*
44-
* @param jobName name of the job
45-
* @param timeout timeout
47+
* @param jenkinsServer Jenkins server client
48+
* @param jobName name of the job
49+
* @param timeout timeout
4650
* @return the build status
4751
* @throws IOException if connection problems occur during connecting to Jenkins
4852
* @throws InterruptedException if a problem occurs during sleeping between checks
4953
* @see com.redhat.digkins.DiggerClient#build(String, long)
5054
*/
51-
public BuildStatus build(String jobName, long timeout) throws IOException, InterruptedException {
55+
public BuildStatus build(JenkinsServer jenkinsServer, String jobName, long timeout) throws IOException, InterruptedException {
5256
final long whenToTimeout = System.currentTimeMillis() + timeout;
5357

5458
LOG.debug("Going to build job with name: {}", jobName);
@@ -72,8 +76,8 @@ public BuildStatus build(String jobName, long timeout) throws IOException, Inter
7276
// do it until we have an executable.
7377
// we would have an executable when the build leaves queue and starts building.
7478

75-
LOG.debug("Going to sleep {} msecs", FIRST_CHECK_DELAY);
76-
Thread.sleep(FIRST_CHECK_DELAY);
79+
LOG.debug("Going to sleep {} msecs", firstCheckDelay);
80+
Thread.sleep(firstCheckDelay);
7781

7882
QueueItem queueItem;
7983
while (true) {
@@ -107,8 +111,8 @@ public BuildStatus build(String jobName, long timeout) throws IOException, Inter
107111
} else {
108112
LOG.debug("Build did not start executing yet.");
109113
if (whenToTimeout > System.currentTimeMillis()) {
110-
LOG.debug("Timeout period has not exceeded yet. Sleeping for {} msecs", POLL_PERIOD);
111-
Thread.sleep(POLL_PERIOD);
114+
LOG.debug("Timeout period has not exceeded yet. Sleeping for {} msecs", pollPeriod);
115+
Thread.sleep(pollPeriod);
112116
} else {
113117
LOG.debug("Timeout period has exceeded. Returning TIMED_OUT.");
114118
return new BuildStatus(BuildStatus.State.TIMED_OUT, -1);

src/test/java/com/redhat/digkins/services/TriggerBuildServiceTest.java

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,10 @@
1111
import org.junit.runner.RunWith;
1212
import org.mockito.Mock;
1313
import org.mockito.Mockito;
14-
15-
import static org.assertj.core.api.Assertions.*;
16-
1714
import org.mockito.runners.MockitoJUnitRunner;
1815

16+
import static org.assertj.core.api.Assertions.assertThat;
17+
1918

2019
@RunWith(MockitoJUnitRunner.class)
2120
public class TriggerBuildServiceTest {
@@ -32,27 +31,27 @@ public class TriggerBuildServiceTest {
3231

3332
@Before
3433
public void setUp() throws Exception {
35-
service = new TriggerBuildService(jenkinsServer);
34+
service = new TriggerBuildService(300, 50); // wait for 300 msecs for initial build, check every 50 msecs
3635

3736
Mockito.when(jenkinsServer.getJob("TEST")).thenReturn(mockJob);
3837
}
3938

4039
@Test(expected = IllegalArgumentException.class)
4140
public void shouldThrowExceptionIfJobCannotBeFound() throws Exception {
42-
service.build("UNKNOWN", 10000);
41+
service.build(jenkinsServer, "UNKNOWN", 10000);
4342
}
4443

4544
@Test(expected = IllegalStateException.class)
4645
public void shouldThrowExceptionIfJenkinsDoesNotReturnQueueReference() throws Exception {
4746
Mockito.when(mockJob.build()).thenReturn(null);
48-
service.build("TEST", 10000);
47+
service.build(jenkinsServer, "TEST", 10000);
4948
}
5049

5150
@Test(expected = IllegalStateException.class)
5251
public void shouldThrowExceptionIfQueueItemIsNullForReference() throws Exception {
5352
Mockito.when(mockJob.build()).thenReturn(queueReference);
5453
Mockito.when(jenkinsServer.getQueueItem(queueReference)).thenReturn(null);
55-
service.build("TEST", 10000);
54+
service.build(jenkinsServer, "TEST", 10000);
5655
}
5756

5857
@Test
@@ -63,7 +62,7 @@ public void shouldReturnCancelledStatus() throws Exception {
6362
Mockito.when(mockJob.build()).thenReturn(queueReference);
6463
Mockito.when(jenkinsServer.getQueueItem(queueReference)).thenReturn(queueItem);
6564

66-
final BuildStatus buildStatus = service.build("TEST", 10000);
65+
final BuildStatus buildStatus = service.build(jenkinsServer, "TEST", 10000);
6766
assertThat(buildStatus).isNotNull();
6867
assertThat(buildStatus.getState()).isEqualTo(BuildStatus.State.CANCELLED_IN_QUEUE);
6968
}
@@ -76,7 +75,7 @@ public void shouldReturnStuckStatus() throws Exception {
7675
Mockito.when(mockJob.build()).thenReturn(queueReference);
7776
Mockito.when(jenkinsServer.getQueueItem(queueReference)).thenReturn(queueItem);
7877

79-
final BuildStatus buildStatus = service.build("TEST", 10000);
78+
final BuildStatus buildStatus = service.build(jenkinsServer, "TEST", 10000);
8079
assertThat(buildStatus).isNotNull();
8180
assertThat(buildStatus.getState()).isEqualTo(BuildStatus.State.STUCK_IN_QUEUE);
8281
}
@@ -90,7 +89,7 @@ public void shouldReturnBuildNumber() throws Exception {
9089

9190
Mockito.when(mockJob.build()).thenReturn(queueReference);
9291
Mockito.when(jenkinsServer.getQueueItem(queueReference)).thenReturn(queueItem);
93-
final BuildStatus buildStatus = service.build("TEST", 10000);
92+
final BuildStatus buildStatus = service.build(jenkinsServer, "TEST", 10000);
9493

9594
assertThat(buildStatus).isNotNull();
9695
assertThat(buildStatus.getState()).isEqualTo(BuildStatus.State.BUILDING);
@@ -108,7 +107,7 @@ public void shouldReturnBuildNumber_whenDidNotStartExecutingImmediately() throws
108107
Mockito.when(mockJob.build()).thenReturn(queueReference);
109108
// return `not-building` for the first 2 checks, then return `building`
110109
Mockito.when(jenkinsServer.getQueueItem(queueReference)).thenReturn(queueItemNotBuildingYet, queueItemNotBuildingYet, queueItemBuilding);
111-
final BuildStatus buildStatus = service.build("TEST", 20000L);
110+
final BuildStatus buildStatus = service.build(jenkinsServer, "TEST", 10000L);
112111

113112
assertThat(buildStatus).isNotNull();
114113
assertThat(buildStatus.getState()).isEqualTo(BuildStatus.State.BUILDING);
@@ -123,7 +122,7 @@ public void shouldReturnTimeout() throws Exception {
123122

124123
Mockito.when(mockJob.build()).thenReturn(queueReference);
125124
Mockito.when(jenkinsServer.getQueueItem(queueReference)).thenReturn(queueItemNotBuildingYet);
126-
final BuildStatus buildStatus = service.build("TEST", 10000L);
125+
final BuildStatus buildStatus = service.build(jenkinsServer, "TEST", 500L);
127126

128127
assertThat(buildStatus).isNotNull();
129128
assertThat(buildStatus.getState()).isEqualTo(BuildStatus.State.TIMED_OUT);

0 commit comments

Comments
 (0)