-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathAbstractTask.java
More file actions
454 lines (385 loc) · 15.5 KB
/
AbstractTask.java
File metadata and controls
454 lines (385 loc) · 15.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
/**
* (C) Copyright IBM Corporation 2014.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.wasdev.wlp.ant;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.ResourceBundle;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
public abstract class AbstractTask extends Task {
protected File installDir;
protected File userDir;
protected File outputDir;
protected File serverConfigDir = null;
protected File serverOutputDir = null;
protected String serverName;
protected String ref;
protected static String osName;
protected static boolean isWindows;
protected ProcessBuilder processBuilder;
protected static final String DEFAULT_SERVER = "defaultServer";
protected static final String DEFAULT_LOG_FILE = "logs/messages.log";
protected static final String WLP_USER_DIR_VAR = "WLP_USER_DIR";
protected static final String WLP_OUTPUT_DIR_VAR = "WLP_OUTPUT_DIR";
protected static final ResourceBundle messages = ResourceBundle.getBundle("net.wasdev.wlp.ant.AntMessages");
protected void initTask() {
if (ref != null) {
Object serverRef = getProject().getReference(ref);
if (serverRef != null && (serverRef instanceof ServerTask)) {
setInstallDir(((ServerTask) serverRef).getInstallDir());
setServerName(((ServerTask) serverRef).getServerName());
setUserDir(((ServerTask) serverRef).getUserDir());
setOutputDir(((ServerTask) serverRef).getOutputDir());
}
}
try {
if (installDir != null) {
installDir = installDir.getCanonicalFile();
// Quick sanity check
File file = new File(installDir, "lib/ws-launch.jar");
if (!file.exists()) {
throw new BuildException(messages.getString("error.installDir.set"));
}
log(MessageFormat.format(messages.getString("info.variable"), "installDir", installDir.getCanonicalPath()), Project.MSG_VERBOSE);
} else {
throw new BuildException("Liberty installation directory must be set.");
}
if (serverName == null) {
setServerName(DEFAULT_SERVER);
}
processBuilder = new ProcessBuilder();
if (userDir != null) {
log(MessageFormat.format(messages.getString("info.variable"), "userDir", userDir.getCanonicalPath()), Project.MSG_VERBOSE);
processBuilder.environment().put(WLP_USER_DIR_VAR, userDir.getCanonicalPath());
serverConfigDir = new File(userDir, "servers/" + serverName);
} else {
String wlpUserDir = processBuilder.environment().get(WLP_USER_DIR_VAR);
if (wlpUserDir != null) {
log(MessageFormat.format(messages.getString("info.variable"), "WLP_USER_DIR", wlpUserDir), Project.MSG_VERBOSE);
serverConfigDir = new File(wlpUserDir, "servers/" + serverName);
} else {
serverConfigDir = new File(installDir, "usr/servers/" + serverName);
}
}
log(MessageFormat.format(messages.getString("info.variable"), "server.config.dir", serverConfigDir.getCanonicalPath()));
if (outputDir != null) {
log(MessageFormat.format(messages.getString("info.variable"), "outputDir", outputDir.getCanonicalPath()), Project.MSG_VERBOSE);
processBuilder.environment().put(WLP_OUTPUT_DIR_VAR, outputDir.getCanonicalPath());
serverOutputDir = new File(outputDir, serverName);
} else {
String wlpOutputDir = processBuilder.environment().get(WLP_OUTPUT_DIR_VAR);
if (wlpOutputDir != null) {
log(MessageFormat.format(messages.getString("info.variable"), "WLP_OUTPUT_DIR", wlpOutputDir), Project.MSG_VERBOSE);
serverOutputDir = new File(wlpOutputDir, serverName);
} else {
serverOutputDir = serverConfigDir;
}
}
log(MessageFormat.format(messages.getString("info.variable"), "server.output.dir", serverOutputDir.getCanonicalPath()));
} catch (IOException e) {
throw new BuildException(e);
}
// Check for windows..
osName = System.getProperty("os.name", "unknown").toLowerCase();
isWindows = osName.indexOf("windows") >= 0 && System.getenv("SHELL") == null;
}
public File getInstallDir() {
return installDir;
}
public void setInstallDir(File installDir) {
this.installDir = installDir;
}
public File getUserDir() {
return userDir;
}
public void setUserDir(File userDir) {
this.userDir = userDir;
}
public File getOutputDir() {
return outputDir;
}
public void setOutputDir(File outputDir) {
this.outputDir = outputDir;
}
/**
* @return the serverName
*/
public String getServerName() {
return serverName;
}
/**
* @param serverName
* the serverName to set
*/
public void setServerName(String serverName) {
this.serverName = serverName;
}
public File getLogFile() {
return new File(serverOutputDir, DEFAULT_LOG_FILE);
}
/**
* @return the ref
*/
public String getRef() {
return ref;
}
/**
* @param ref the ref to set
*/
public void setRef(String ref) {
this.ref = ref;
}
protected int getReturnCode(Process p, String commandLine) throws InterruptedException {
log(MessageFormat.format(messages.getString("info.variable"), "Invoke command", commandLine, Project.MSG_VERBOSE));
StreamCopier copier = new StreamCopier(p.getInputStream());
copier.start();
int exitVal = p.waitFor();
copier.doJoin();
return exitVal;
}
public void checkReturnCode(Process p, String commandLine, int... expectedExitCodes) throws InterruptedException {
int exitVal = getReturnCode(p, commandLine);
for (int expectedExitCode : expectedExitCodes) {
if (exitVal == expectedExitCode) {
return;
}
}
throw new BuildException(MessageFormat.format(messages.getString("error.invoke.command"), commandLine, exitVal, Arrays.toString(expectedExitCodes)));
}
private class StreamCopier extends Thread {
private final BufferedReader reader;
private boolean joined;
private boolean terminated;
StreamCopier(InputStream input) {
this.reader = new BufferedReader(new InputStreamReader(input));
setDaemon(true);
}
@Override
public void run() {
try {
for (String line; (line = reader.readLine()) != null;) {
synchronized (this) {
if (joined) {
// The main thread was notified that the process
// ended and has already given up waiting for
// output from the foreground process.
break;
}
log(line);
}
}
} catch (IOException ex) {
throw new BuildException(ex);
} finally {
if (isWindows) {
synchronized (this) {
terminated = true;
notifyAll();
}
}
}
}
public void doJoin() throws InterruptedException {
if (isWindows) {
// Windows doesn't disconnect background processes (start /b)
// from the console of foreground processes, so waiting until
// the end of output from server.bat means waiting until the
// server process itself ends. We can't wait that long, so we
// wait one second after .waitFor() ends. Hopefully this will
// be long enough to copy all the output from the script.
synchronized (this) {
long begin = System.nanoTime();
long end = begin
+ TimeUnit.NANOSECONDS.convert(1, TimeUnit.SECONDS);
long duration = end - begin;
while (!terminated && duration > 0) {
TimeUnit.NANOSECONDS.timedWait(this, duration);
duration = end - System.nanoTime();
}
// If the thread didn't end after waiting for a second,
// then assume it's stuck in a blocking read. Oh well,
// it's a daemon thread, so it'll go away eventually. Let
// it know that we gave up to avoid spurious output in case
// it eventually wakes up.
joined = true;
}
} else {
super.join();
}
}
}
/**
* Check for a number of strings in a potentially remote file
*
* @param regexp
* a regular expression to search for
* @param timeout
* a timeout, in milliseconds
* @param outputFile
* file to check
* @return line that matched the regexp
*/
public String waitForStringInLog(String regexp, long timeout,
File outputFile) {
int waited = 0;
final int waitIncrement = 500;
log(MessageFormat.format(messages.getString("info.search.string"), regexp, outputFile.getAbsolutePath(), timeout / 1000));
try {
while (waited <= timeout) {
String string = findStringInFile(regexp, outputFile);
if (string == null) {
try {
Thread.sleep(waitIncrement);
} catch (InterruptedException e) {
// Ignore and carry on
}
waited += waitIncrement;
} else {
return string;
}
}
log(MessageFormat.format(messages.getString("error.serch.string.timeout"), regexp, outputFile.getAbsolutePath()));
} catch (Exception e) {
// I think we can assume if we can't read the file it doesn't
// contain our string
throw new BuildException(e);
}
return null;
}
/**
* Searches the given file for the given regular expression.
*
* @param regexp
* a regular expression (or just a text snippet) to search for
* @param fileToSearch
* the file to search
* @return The first line which includes the pattern, or null if the pattern
* isn't found or if the file doesn't exist
* @throws Exception
*/
protected String findStringInFile(String regexp, File fileToSearch) throws Exception {
String foundString = null;
List<String> matches = findStringsInFileCommon(regexp, true, -1, fileToSearch);
if (matches != null && !matches.isEmpty()) {
foundString = matches.get(0);
}
return foundString;
}
/**
* Searches the given file for the given regular expression.
*
* @param regexp
* a regular expression (or just a text snippet) to search for
* @param fileToSearch
* the file to search
* @return List of Strings which match the pattern. No match results in an
* empty list.
* @throws Exception
*/
protected List<String> findStringsInFileCommon(String regexp,
boolean stopOnFirst, int searchLimit, File fileToSearch)
throws Exception {
if (fileToSearch == null) {
log(messages.getString("info.file.validated"));
return null;
}
if (!fileToSearch.exists()) {
log(MessageFormat.format(messages.getString("info.file.validate.noexist"), fileToSearch.getCanonicalPath()));
return null;
}
InputStream serverOutput = null;
InputStreamReader in = null;
Scanner s = null;
List<String> matches = null;
try {
// Read file and search
serverOutput = new FileInputStream(fileToSearch);
in = new InputStreamReader(serverOutput);
s = new Scanner(in);
log(MessageFormat.format(messages.getString("info.look.string.infile"), regexp, fileToSearch.getName()), Project.MSG_VERBOSE);
String foundString = null;
Pattern pattern = Pattern.compile(regexp);
matches = new ArrayList<String>();
while (s.hasNextLine()) {
if (foundString != null && stopOnFirst) {
break;
}
if (searchLimit <= 0 && searchLimit >= matches.size()) {
break;
}
String line = s.nextLine();
if (pattern.matcher(line).find()) {
foundString = line;
matches.add(line);
log(MessageFormat.format(messages.getString("info.match.string"), matches.size(), line));
}
}
} catch (Exception e) {
log(e.toString());
} finally {
try {
s.close();
} catch (Exception e) {
// Ignore
}
try {
serverOutput.close();
} catch (Exception e) {
// Ignore
}
try {
in.close();
} catch (Exception e) {
//Ignore
}
}
return matches;
}
/*
* Returns file name without the extension.
*/
protected String getFileName(String fileName) {
int index = fileName.lastIndexOf('.');
return (index == -1) ? fileName : fileName.substring(0, index);
}
protected void stopServer(String timeout) {
//Stop server if exception happens.
ServerTask st = new ServerTask();
st.setProject(getProject());
st.setInstallDir(getInstallDir());
st.setUserDir(getUserDir());
st.setOutputDir(getOutputDir());
st.setServerName(getServerName());
st.setTimeout(timeout);
st.setOperation("stop");
st.execute();
}
protected String getMessage(String key, Object... args) {
return MessageFormat.format(messages.getString(key), args);
}
}