下面列出了怎么用org.gradle.api.tasks.TaskExecutionException的API类实例代码及写法,或者点击链接到github查看源代码。
private Throwable findDeepestRootException(Throwable exception) {
// TODO: fix the way we work out which exception is important: TaskExecutionException is not always the most helpful
Throwable locationAware = null;
Throwable result = null;
Throwable contextMatch = null;
for (Throwable current = exception; current != null; current = current.getCause()) {
if (current instanceof LocationAwareException) {
locationAware = current;
} else if (current instanceof GradleScriptException || current instanceof TaskExecutionException) {
result = current;
} else if (contextMatch == null && current.getClass().getAnnotation(Contextual.class) != null) {
contextMatch = current;
}
}
if (locationAware != null) {
return locationAware;
} else if (result != null) {
return result;
} else if (contextMatch != null) {
return contextMatch;
} else {
return exception;
}
}
private Throwable findDeepestRootException(Throwable exception) {
// TODO: fix the way we work out which exception is important: TaskExecutionException is not always the most helpful
Throwable locationAware = null;
Throwable result = null;
Throwable contextMatch = null;
for (Throwable current = exception; current != null; current = current.getCause()) {
if (current instanceof LocationAwareException) {
locationAware = current;
} else if (current instanceof GradleScriptException || current instanceof TaskExecutionException) {
result = current;
} else if (contextMatch == null && current.getClass().getAnnotation(Contextual.class) != null) {
contextMatch = current;
}
}
if (locationAware != null) {
return locationAware;
} else if (result != null) {
return result;
} else if (contextMatch != null) {
return contextMatch;
} else {
return exception;
}
}
@TaskAction
void add() {
try {
final List<FunctionTemplate> templates = loadAllFunctionTemplates();
final FunctionTemplate template = getFunctionTemplate(templates);
final Map params = prepareRequiredParameters(template);
final String newFunctionClass = substituteParametersInTemplate(template, params);
saveNewFunctionToFile(newFunctionClass);
} catch (Exception ex) {
throw new TaskExecutionException(this, ex);
}
}
private void prepareFunctionName() throws TaskExecutionException {
getLogger().quiet("Common parameter [Function Name]: name for both the new function and Java class");
if (settings != null/* && !settings.isInteractiveMode()*/) {
assureInputInBatchMode(getFunctionName(),
str -> isNotEmpty(str) && str.matches(FUNCTION_NAME_REGEXP),
this::setFunctionName,
true);
} else {
assureInputFromUser("Enter value for Function Name: ",
getFunctionName(),
str -> isNotEmpty(str) && str.matches(FUNCTION_NAME_REGEXP),
"Function name must start with a letter and can contain letters, digits, '_' and '-'",
this::setFunctionName);
}
}
private void preparePackageName() throws TaskExecutionException {
getLogger().quiet("Common parameter [Package Name]: package name of the new Java class");
if (settings != null/* && !settings.isInteractiveMode()*/) {
assureInputInBatchMode(getFunctionPackageName(),
str -> isNotEmpty(str) && isName(str),
this::setFunctionPackageName,
true);
} else {
assureInputFromUser("Enter value for Package Name: ",
getFunctionPackageName(),
str -> isNotEmpty(str) && isName(str),
"Input should be a valid Java package name.",
this::setFunctionPackageName);
}
}
private void assureInputInBatchMode(final String input, final Function<String, Boolean> validator,
final Consumer<String> setter, final boolean required)
throws TaskExecutionException {
if (validator.apply(input)) {
getLogger().quiet(FOUND_VALID_VALUE);
setter.accept(input);
return;
}
if (required) {
throw new IllegalArgumentException(String.format("invalid input: %s", input));
} else {
out.printf("The input is invalid. Use empty string.%n");
setter.accept("");
}
}
private Throwable findDeepestRootException(Throwable exception) {
// TODO: fix the way we work out which exception is important: TaskExecutionException is not always the most helpful
Throwable locationAware = null;
Throwable result = null;
Throwable contextMatch = null;
for (Throwable current = exception; current != null; current = current.getCause()) {
if (current instanceof LocationAwareException) {
locationAware = current;
} else if (current instanceof GradleScriptException || current instanceof TaskExecutionException) {
result = current;
} else if (contextMatch == null && current.getClass().getAnnotation(Contextual.class) != null) {
contextMatch = current;
}
}
if (locationAware != null) {
return locationAware;
} else if (result != null) {
return result;
} else if (contextMatch != null) {
return contextMatch;
} else {
return exception;
}
}
private Throwable findDeepestRootException(Throwable exception) {
// TODO: fix the way we work out which exception is important: TaskExecutionException is not always the most helpful
Throwable locationAware = null;
Throwable result = null;
Throwable contextMatch = null;
for (Throwable current = exception; current != null; current = current.getCause()) {
if (current instanceof LocationAwareException) {
locationAware = current;
} else if (current instanceof GradleScriptException || current instanceof TaskExecutionException) {
result = current;
} else if (contextMatch == null && current.getClass().getAnnotation(Contextual.class) != null) {
contextMatch = current;
}
}
if (locationAware != null) {
return locationAware;
} else if (result != null) {
return result;
} else if (contextMatch != null) {
return contextMatch;
} else {
return exception;
}
}
private void convert() {
final File workingDir = _document.getParentFile();
final String documentName = _document.getName();
final ProcessBuilder builder = new ProcessBuilder(
BINARY, "-e", "pdf2", documentName
);
builder.directory(workingDir);
builder.redirectErrorStream(true);
getLogger().debug(workingDir + "/" + documentName);
try {
final Process process = builder.start();
output(process.getInputStream());
_exitValue = process.waitFor();
if (_exitValue != 0) {
getLogger().lifecycle("Error while generating PDF.");
getLogger().lifecycle("Manual PDF has not been created.");
}
} catch (IOException | InterruptedException e) {
throw new TaskExecutionException(this, e);
}
}
@TaskAction
public void checksum() {
try {
final MessageDigest digest = MessageDigest.getInstance(_algorithm);
// Read the file.
try (FileInputStream in = new FileInputStream(_inputFile)) {
final byte[] data = new byte[4096];
for (int l = in.read(data); l != -1; l = in.read(data)) {
digest.update(data, 0, l);
}
}
// Write the checksum file.
try (FileOutputStream out = new FileOutputStream(getChecksumFile())) {
out.write(toString(digest.digest()).getBytes());
}
} catch (NoSuchAlgorithmException | IOException e) {
throw new TaskExecutionException(this, e);
}
}
/**
* Tests that the task times out if the response takes too long
* @throws Exception if anything else goes wrong
*/
@Test
public void readTimeout() throws Exception {
wireMockRule.stubFor(get(urlEqualTo("/" + TIMEOUT))
.willReturn(aResponse()
.withFixedDelay(TIMEOUT_MS * 10)
.withBody("Whatever")));
Download t = makeProjectAndTask();
t.readTimeout(TIMEOUT_MS);
assertEquals(TIMEOUT_MS, t.getReadTimeout());
t.src(wireMockRule.url(TIMEOUT));
File dst = folder.newFile();
t.dest(dst);
try {
t.execute();
fail("Connection should have timed out by now");
} catch (TaskExecutionException e) {
assertTrue(e.getCause() instanceof UncheckedIOException);
assertTrue(e.getCause().getCause() instanceof SocketTimeoutException);
}
}
/**
* Tests that the task times out if takes too long to connect to the server
* @throws Exception if anything else goes wrong
*/
@Test
public void connectTimeout() throws Exception {
Download t = makeProjectAndTask();
t.connectTimeout(TIMEOUT_MS);
assertEquals(TIMEOUT_MS, t.getConnectTimeout());
t.src("http://10.255.255.1"); // try to connect to an invalid host
File dst = folder.newFile();
t.dest(dst);
long start = System.currentTimeMillis();
try {
t.execute();
fail("Connection should have timed out by now");
} catch (TaskExecutionException e) {
assertTrue(e.getCause() instanceof UncheckedIOException);
assertTrue(e.getCause().getCause() instanceof ConnectTimeoutException);
long end = System.currentTimeMillis();
if (end - start > TIMEOUT_MS * 2) {
fail("Timeout took way too long");
}
}
}
/**
* Tests if the plugin can handle an incorrect Content-Length header
* @throws Exception if anything goes wrong
*/
@Test(expected = TaskExecutionException.class)
public void tooLargeContentLength() throws Exception {
String testFileName = "/test.txt";
String contents = "Hello";
wireMockRule.stubFor(get(urlEqualTo(testFileName))
.willReturn(aResponse()
.withHeader("content-length", "10000")
.withBody(contents)));
Download t = makeProjectAndTask();
t.compress(false); // do not use GZIP or the response will be chunked
t.src(wireMockRule.url(testFileName));
File dst = folder.newFile();
t.dest(dst);
t.execute();
}
/**
* Tests if the Verify task fails if the checksum is wrong
* @throws Exception if anything goes wrong
*/
@Test(expected = TaskExecutionException.class)
public void verifyWrongMD5() throws Exception {
configureDefaultStub();
Download t = makeProjectAndTask();
t.src(wireMockRule.url(TEST_FILE_NAME));
File dst = folder.newFile();
t.dest(dst);
Verify v = makeVerifyTask(t);
v.algorithm("MD5");
v.checksum("WRONG");
v.src(t.getDest());
t.execute();
v.execute(); // should throw
}
/**
* Make sure the plugin fails with too many redirects
* @throws Exception if anything goes wrong
*/
@Test(expected = TaskExecutionException.class)
public void tooManyRedirects() throws Exception {
UrlPattern up1 = urlPathEqualTo("/" + REDIRECT);
redirectWireMockRule.stubFor(get(up1)
.withQueryParam("r", matching("[0-9]+"))
.willReturn(aResponse()
.withStatus(HttpServletResponse.SC_FOUND)
.withTransformer("redirect", "redirects", 51)));
Download t = makeProjectAndTask();
t.src(redirectWireMockRule.url(REDIRECT) + "?r=52");
File dst = folder.newFile();
t.dest(dst);
t.execute();
}
/**
* Tests if the plugin can handle failed authentication
* @throws Exception if anything goes wrong
*/
@Test(expected = TaskExecutionException.class)
public void invalidCredentials() throws Exception {
String wrongUser = USERNAME + "!";
String wrongPass = PASSWORD + "!";
String ahdr = "Basic " + Base64.encodeBase64String(
(wrongUser + ":" + wrongPass).getBytes(StandardCharsets.UTF_8));
wireMockRule.stubFor(get(urlEqualTo("/" + AUTHENTICATE))
.withHeader("Authorization", equalTo(ahdr))
.willReturn(aResponse()
.withStatus(HttpServletResponse.SC_UNAUTHORIZED)));
Download t = makeProjectAndTask();
t.src(wireMockRule.url(AUTHENTICATE));
File dst = folder.newFile();
t.dest(dst);
t.username(wrongUser);
t.password(wrongPass);
t.execute();
}
@TaskAction
void deploy() {
try {
getLogger().quiet(String.format(WEBAPP_DEPLOY_START, azureWebAppExtension.getAppName()));
createOrUpdateWebApp();
deployArtifacts();
getLogger().quiet(String.format(WEBAPP_DEPLOY_SUCCESS, azureWebAppExtension.getAppName()));
} catch (Exception ex) {
throw new TaskExecutionException(this, ex);
}
}
@TaskAction
void runFunction() {
try {
checkStageDirectoryExistence();
checkRuntimeExistence();
runFunctions();
} catch (Exception ex) {
throw new TaskExecutionException(this, ex);
}
}
@TaskAction
void deployFunction() {
try {
getLogger().quiet(FUNCTION_DEPLOY_START + getAppName() + "...");
createOrUpdateFunctionApp();
getArtifactHandler().publish();
getLogger().quiet(String.format(FUNCTION_DEPLOY_SUCCESS, getAppName()));
} catch (Exception ex) {
throw new TaskExecutionException(this, ex);
}
}
@TaskAction
public void colorize() {
try {
final Colorizer colorizer = new Colorizer(_directory);
colorizer.colorize();
getLogger().lifecycle(
"Colorizer processed {} files and modified {}.",
colorizer.getProcessed(), colorizer.getModified()
);
} catch (final IOException e) {
throw new TaskExecutionException(this, e);
}
}
/**
* Tests if the task throws an exception if you try to download
* multiple files to a single destination file
* @throws Exception if anything goes wrong
*/
@Test(expected = TaskExecutionException.class)
public void downloadMultipleFilesToFile() throws Exception {
Download t = makeProjectAndTask();
t.src(Arrays.asList(wireMockRule.url(TEST_FILE_NAME),
wireMockRule.url(TEST_FILE_NAME2)));
File dst = folder.newFile();
t.dest(dst);
t.execute();
}
/**
* Test if the plugin throws an exception if the 'src' property is invalid
* @throws Exception if the test succeeds
*/
@Test(expected = TaskExecutionException.class)
public void testInvalidSrc() throws Exception {
Download t = makeProjectAndTask();
t.src(new Object());
t.dest(folder.newFile());
t.execute();
}
/**
* Test if the plugin throws an exception if the 'dest' property is invalid
*/
@Test(expected = TaskExecutionException.class)
public void testInvalidDest() {
Download t = makeProjectAndTask();
String src = wireMockRule.url(TEST_FILE_NAME);
t.src(src);
t.dest(new Object());
t.execute();
}
/**
* Test if the plugin throws an exception if the 'dest' property is empty
*/
@Test(expected = TaskExecutionException.class)
public void testExecuteEmptyDest() {
Download t = makeProjectAndTask();
String src = wireMockRule.url(TEST_FILE_NAME);
t.src(src);
t.execute();
}
/**
* Tests if connecting to a HTTPS URL fails if the certificate is unknown
* @throws Exception if anything goes wrong
*/
@Test(expected = TaskExecutionException.class)
public void unknownCertificate() throws Exception {
Download t = makeProjectAndTask();
t.src(sslWireMockRule.url(TEST_FILE_NAME));
File dst = folder.newFile();
t.dest(dst);
assertFalse(t.isAcceptAnyCertificate());
t.execute();
}
/**
* Test if the plugin throws an exception if the 'algorithm' property is empty
* @throws Exception if the test succeeds
*/
@Test(expected = TaskExecutionException.class)
public void testExecuteEmptyAlgorithm() throws Exception {
Download t = makeProjectAndTask();
File dst = folder.newFile();
t.dest(dst);
Verify v = makeVerifyTask(t);
String calculatedChecksum = calculateChecksum();
v.checksum(calculatedChecksum);
v.algorithm(null);
v.src(t.getDest());
v.execute(); // should throw
}
/**
* Test if the download task does not retry requests by default
* @throws Exception if anything else goes wrong
*/
@Test
public void retryDefault() throws Exception {
wireMockRule.stubFor(get(urlEqualTo("/" + TEST_FILE_NAME))
.inScenario(SCENARIO)
.whenScenarioStateIs(STARTED)
.willReturn(aResponse().withFault(Fault.EMPTY_RESPONSE))
.willSetStateTo(TWO));
wireMockRule.stubFor(get(urlEqualTo("/" + TEST_FILE_NAME))
.inScenario(SCENARIO)
.whenScenarioStateIs(TWO)
.willReturn(aResponse().withBody(CONTENTS)));
Download t = makeProjectAndTask();
assertEquals(0, t.getRetries());
t.src(wireMockRule.url(TEST_FILE_NAME));
File dst = folder.newFile();
t.dest(dst);
try {
t.execute();
fail("Request should have failed");
} catch (TaskExecutionException e) {
wireMockRule.verify(1, getRequestedFor(urlEqualTo("/" + TEST_FILE_NAME)));
assertTrue(e.getCause() instanceof UncheckedIOException);
assertTrue(e.getCause().getCause() instanceof NoHttpResponseException);
}
}
/**
* Tests if the plugin can handle circular redirects
* @throws Exception if anything goes wrong
*/
@Test(expected = TaskExecutionException.class)
public void circularRedirect() throws Exception {
UrlPattern up1 = urlPathEqualTo("/" + REDIRECT);
wireMockRule.stubFor(get(up1)
.willReturn(aResponse()
.withStatus(HttpServletResponse.SC_FOUND)
.withHeader("Location", "/" + REDIRECT)));
Download t = makeProjectAndTask();
t.src(wireMockRule.url(REDIRECT));
File dst = folder.newFile();
t.dest(dst);
t.execute();
}
/**
* Tests if the plugin can handle failed authentication
* @throws Exception if anything goes wrong
*/
@Test(expected = TaskExecutionException.class)
public void noAuthorization() throws Exception {
wireMockRule.stubFor(get(urlEqualTo("/" + AUTHENTICATE))
.withHeader("Authorization", absent())
.willReturn(aResponse()
.withStatus(HttpServletResponse.SC_UNAUTHORIZED)));
Download t = makeProjectAndTask();
t.src(wireMockRule.url(AUTHENTICATE));
File dst = folder.newFile();
t.dest(dst);
t.execute();
}
@Override
protected void executeGoal() throws Exception {
final Set<Application> modules = new HashSet<>();
final Set<Project> subProjects = project.getSubprojects();
// if the plugin applied to an 'aggregator' project, then the project itself
// is not producing any report
if (this.projectOutputType != null) {
modules.add(this.app);
}
// if the project has subprojects examine them
if (!subProjects.isEmpty()) {
getLogger().debug("Adding subprojects if eligible for reporting");
for (Project sp : subProjects) {
if (!sp.getPlugins().hasPlugin(VulasPlugin.class)) {
getLogger().debug("Vulas plugin not applied on subproject {} , skipping it." , sp.getName());
continue;
}
if (!hasKnownProjectOutputType (sp, getLogger())){
getLogger().debug("Output type of subproject {} is unknown, skipping it." , sp.getName());
continue;
}
String groupId = getMandatoryProjectProperty(sp, GradleGavProperty.group, getLogger());
String artifactId = getMandatoryProjectProperty(sp, GradleGavProperty.name, getLogger());
String version = getMandatoryProjectProperty(sp, GradleGavProperty.version, getLogger());
Application subProjectMvnId = new Application(groupId, artifactId, version);
modules.add(subProjectMvnId);
}
}
if (!modules.isEmpty()) {
((ReportGoal)this.goal).setApplicationModules(modules);
try {
this.goal.executeSync();
}
// ReportException will be passed on as MojoFailure, i.e., the goal execution terminates normally
catch (ReportException re) {
getLogger().error(re.getLongMessage());
throw new TaskExecutionException(this, re);
}
} else {
getLogger().quiet("Skipping report generation as neither the project or none of its subprojects are eligible.");
}
}