org.gradle.api.tasks.TaskExecutionException Java Examples

The following examples show how to use org.gradle.api.tasks.TaskExecutionException. 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: ChecksumTask.java    From jenetics with Apache License 2.0 6 votes vote down vote up
@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);
	}
}
 
Example #2
Source File: AuthenticationTest.java    From gradle-download-task with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
}
 
Example #3
Source File: RedirectTest.java    From gradle-download-task with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
}
 
Example #4
Source File: VerifyTest.java    From gradle-download-task with Apache License 2.0 6 votes vote down vote up
/**
 * 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
}
 
Example #5
Source File: ContentLengthTest.java    From gradle-download-task with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
}
 
Example #6
Source File: TimeoutTest.java    From gradle-download-task with Apache License 2.0 6 votes vote down vote up
/**
 * 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");
        }
    }
}
 
Example #7
Source File: TimeoutTest.java    From gradle-download-task with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example #8
Source File: DefaultExceptionAnalyser.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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;
    }
}
 
Example #9
Source File: Lyx2PDFTask.java    From jenetics with Apache License 2.0 6 votes vote down vote up
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);
	}
}
 
Example #10
Source File: DefaultExceptionAnalyser.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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;
    }
}
 
Example #11
Source File: DefaultExceptionAnalyser.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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;
    }
}
 
Example #12
Source File: DefaultExceptionAnalyser.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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;
    }
}
 
Example #13
Source File: AddTask.java    From azure-gradle-plugins with MIT License 6 votes vote down vote up
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);
    }
}
 
Example #14
Source File: AddTask.java    From azure-gradle-plugins with MIT License 6 votes vote down vote up
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);
    }
}
 
Example #15
Source File: AddTask.java    From azure-gradle-plugins with MIT License 6 votes vote down vote up
@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);
    }
}
 
Example #16
Source File: AddTask.java    From azure-gradle-plugins with MIT License 6 votes vote down vote up
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("");
    }
}
 
Example #17
Source File: RunTask.java    From azure-gradle-plugins with MIT License 5 votes vote down vote up
@TaskAction
void runFunction() {
    try {
        checkStageDirectoryExistence();

        checkRuntimeExistence();

        runFunctions();
    } catch (Exception ex) {
        throw new TaskExecutionException(this, ex);
    }
}
 
Example #18
Source File: AuthenticationTest.java    From gradle-download-task with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example #19
Source File: RedirectTest.java    From gradle-download-task with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example #20
Source File: RetryTest.java    From gradle-download-task with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example #21
Source File: VerifyTest.java    From gradle-download-task with Apache License 2.0 5 votes vote down vote up
/**
 * 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
}
 
Example #22
Source File: SslTest.java    From gradle-download-task with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example #23
Source File: DeployTask.java    From azure-gradle-plugins with MIT License 5 votes vote down vote up
@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);
    }
}
 
Example #24
Source File: DownloadTest.java    From gradle-download-task with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example #25
Source File: DownloadTest.java    From gradle-download-task with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example #26
Source File: DownloadTest.java    From gradle-download-task with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example #27
Source File: DownloadTest.java    From gradle-download-task with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example #28
Source File: ColorizerTask.java    From jenetics with Apache License 2.0 5 votes vote down vote up
@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);
	}
}
 
Example #29
Source File: DeployTask.java    From azure-gradle-plugins with MIT License 5 votes vote down vote up
@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);
    }
}
 
Example #30
Source File: PackageTask.java    From azure-gradle-plugins with MIT License 4 votes vote down vote up
@TaskAction
void packageFunction() {
    try {
        final AnnotationHandler handler = getAnnotationHandler();

        final Set<Method> methods = findAnnotatedMethods(handler);

        final Map<String, FunctionConfiguration> configMap = getFunctionConfigurations(handler, methods);

        validateFunctionConfigurations(configMap);

        final ObjectWriter objectWriter = getObjectWriter();

        writeHostJsonFile(objectWriter);

        copyLocalSettingsJson();

        writeFunctionJsonFiles(objectWriter, configMap);

        copyJarsToStageDirectory();

        getLogger().quiet(BUILD_SUCCESS);
    } catch (Exception ex) {
        throw new TaskExecutionException(this, ex);
    }
}