Search in sources :

Example 36 with GradleException

use of org.gradle.api.GradleException in project meecrowave by apache.

the class MeecrowaveTask method doRun.

private void doRun() {
    final Thread thread = Thread.currentThread();
    final ClassLoader loader = thread.getContextClassLoader();
    final AtomicBoolean running = new AtomicBoolean(false);
    Thread hook = null;
    AutoCloseable container;
    try {
        final Class<?> containerClass = loader.loadClass("org.apache.meecrowave.Meecrowave");
        final Class<?> configClass = loader.loadClass("org.apache.meecrowave.Meecrowave$Builder");
        final Object config = getConfig(configClass);
        running.set(true);
        container = AutoCloseable.class.cast(containerClass.getConstructor(configClass).newInstance(config));
        final AutoCloseable finalContainer = container;
        hook = new Thread() {

            @Override
            public void run() {
                if (running.compareAndSet(true, false)) {
                    final Thread thread = Thread.currentThread();
                    final ClassLoader old = thread.getContextClassLoader();
                    thread.setContextClassLoader(loader);
                    try {
                        finalContainer.close();
                    } catch (final NoClassDefFoundError noClassDefFoundError) {
                        // debug cause it is too late to shutdown properly so don't pollute logs
                        getLogger().debug("can't stop Meecrowave", noClassDefFoundError);
                    } catch (final Exception e) {
                        getLogger().error("can't stop Meecrowave", e);
                    } finally {
                        thread.setContextClassLoader(old);
                    }
                }
            }
        };
        hook.setName("Meecrowave-Embedded-ShutdownHook");
        Runtime.getRuntime().addShutdownHook(hook);
        containerClass.getMethod("start").invoke(container);
        final String fixedContext = ofNullable(context).orElse("");
        if (webapp == null) {
            containerClass.getMethod("deployClasspath", String.class).invoke(container, fixedContext);
        } else {
            containerClass.getMethod("deployWebapp", String.class, File.class).invoke(container, fixedContext, webapp);
        }
        getLogger().info("Meecrowave started on " + configClass.getMethod("getHost").invoke(config) + ":" + configClass.getMethod("getHttpPort").invoke(config));
    } catch (final Exception e) {
        ofNullable(hook).ifPresent(h -> {
            try {
                h.run();
            } finally {
                Runtime.getRuntime().removeShutdownHook(h);
            }
        });
        throw new GradleException(e.getMessage(), e);
    }
    try {
        String line;
        final Scanner scanner = new Scanner(System.in);
        while ((line = scanner.nextLine()) != null) {
            final String cmd = line.trim().toLowerCase(Locale.ENGLISH);
            switch(cmd) {
                case "exit":
                case "quit":
                    running.set(false);
                    try {
                        hook.run();
                    } finally {
                        Runtime.getRuntime().removeShutdownHook(hook);
                    }
                    return;
                default:
                    getLogger().warn("Unknown: '" + cmd + "', use 'exit' or 'quit'");
            }
        }
    } catch (final Exception e) {
        Thread.interrupted();
    } finally {
        thread.setContextClassLoader(loader);
    }
}
Also used : URL(java.net.URL) Scanner(java.util.Scanner) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashSet(java.util.HashSet) Configuration(org.gradle.api.artifacts.Configuration) TaskAction(org.gradle.api.tasks.TaskAction) URLClassLoader(java.net.URLClassLoader) Locale(java.util.Locale) Arrays.asList(java.util.Arrays.asList) Map(java.util.Map) DefaultTask(org.gradle.api.DefaultTask) LinkedList(java.util.LinkedList) LinkedHashSet(java.util.LinkedHashSet) Project(org.gradle.api.Project) MalformedURLException(java.net.MalformedURLException) Optional.ofNullable(java.util.Optional.ofNullable) Collection(java.util.Collection) Optional(org.gradle.api.tasks.Optional) Field(java.lang.reflect.Field) FilterGradleClassLoader(org.apache.meecrowave.gradle.classloader.FilterGradleClassLoader) File(java.io.File) InvocationTargetException(java.lang.reflect.InvocationTargetException) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) Stream(java.util.stream.Stream) GradleException(org.gradle.api.GradleException) Input(org.gradle.api.tasks.Input) Scanner(java.util.Scanner) MalformedURLException(java.net.MalformedURLException) InvocationTargetException(java.lang.reflect.InvocationTargetException) GradleException(org.gradle.api.GradleException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) GradleException(org.gradle.api.GradleException) URLClassLoader(java.net.URLClassLoader) FilterGradleClassLoader(org.apache.meecrowave.gradle.classloader.FilterGradleClassLoader) File(java.io.File)

Example 37 with GradleException

use of org.gradle.api.GradleException in project cayenne by apache.

the class DbGenerateTask method generateDb.

@TaskAction
public void generateDb() throws GradleException {
    dataSource.validate();
    getLogger().info("connection settings - [driver: {}, url: {}, username: {}]", dataSource.getDriver(), dataSource.getUrl(), dataSource.getUsername());
    getLogger().info("generator options - " + "[dropTables: {}, dropPK: {}, createTables: {}, createPK: {}, createFK: {}]", dropTables, dropPK, createTables, createPK, createFK);
    Injector injector = DIBootstrap.createInjector(new DbSyncModule(), new ToolsModule(getLogger()));
    try {
        DbGenerator generator = createGenerator(loadDataMap(injector));
        generator.runGenerator(createDataSource());
    } catch (Exception ex) {
        Throwable th = Util.unwindException(ex);
        String message = "Error generating database";
        if (th.getLocalizedMessage() != null) {
            message += ": " + th.getLocalizedMessage();
        }
        getLogger().error(message);
        throw new GradleException(message, th);
    }
}
Also used : Injector(org.apache.cayenne.di.Injector) GradleException(org.gradle.api.GradleException) DbSyncModule(org.apache.cayenne.dbsync.DbSyncModule) DbGenerator(org.apache.cayenne.access.DbGenerator) ToolsModule(org.apache.cayenne.dbsync.reverse.configuration.ToolsModule) GradleException(org.gradle.api.GradleException) TaskAction(org.gradle.api.tasks.TaskAction)

Example 38 with GradleException

use of org.gradle.api.GradleException in project gradle by gradle.

the class DefaultTestReport method generateFiles.

private void generateFiles(AllTestResults model, final TestResultsProvider resultsProvider, final File reportDir) {
    try {
        HtmlReportRenderer htmlRenderer = new HtmlReportRenderer();
        buildOperationExecutor.run(new RunnableBuildOperation() {

            @Override
            public void run(BuildOperationContext context) {
                // Clean-up old HTML report directories
                GFileUtils.deleteQuietly(new File(reportDir, "packages"));
                GFileUtils.deleteQuietly(new File(reportDir, "classes"));
            }

            @Override
            public BuildOperationDescriptor.Builder description() {
                return BuildOperationDescriptor.displayName("Delete old HTML results");
            }
        });
        htmlRenderer.render(model, new ReportRenderer<AllTestResults, HtmlReportBuilder>() {

            @Override
            public void render(final AllTestResults model, final HtmlReportBuilder output) throws IOException {
                buildOperationExecutor.runAll(new Action<BuildOperationQueue<HtmlReportFileGenerator<? extends CompositeTestResults>>>() {

                    @Override
                    public void execute(BuildOperationQueue<HtmlReportFileGenerator<? extends CompositeTestResults>> queue) {
                        queue.add(generator("index.html", model, new OverviewPageRenderer(), output));
                        for (PackageTestResults packageResults : model.getPackages()) {
                            queue.add(generator(packageResults.getBaseUrl(), packageResults, new PackagePageRenderer(), output));
                            for (ClassTestResults classResults : packageResults.getClasses()) {
                                queue.add(generator(classResults.getBaseUrl(), classResults, new ClassPageRenderer(resultsProvider), output));
                            }
                        }
                    }
                });
            }
        }, reportDir);
    } catch (Exception e) {
        throw new GradleException(String.format("Could not generate test report to '%s'.", reportDir), e);
    }
}
Also used : BuildOperationContext(org.gradle.internal.operations.BuildOperationContext) Action(org.gradle.api.Action) BuildOperationQueue(org.gradle.internal.operations.BuildOperationQueue) HtmlReportBuilder(org.gradle.reporting.HtmlReportBuilder) IOException(java.io.IOException) IOException(java.io.IOException) GradleException(org.gradle.api.GradleException) HtmlReportBuilder(org.gradle.reporting.HtmlReportBuilder) GradleException(org.gradle.api.GradleException) RunnableBuildOperation(org.gradle.internal.operations.RunnableBuildOperation) File(java.io.File) HtmlReportRenderer(org.gradle.reporting.HtmlReportRenderer)

Example 39 with GradleException

use of org.gradle.api.GradleException in project gradle by gradle.

the class AbstractTestFrameworkDetector method classVisitor.

protected TestClassVisitor classVisitor(final File testClassFile) {
    final TestClassVisitor classVisitor = createClassVisitor();
    InputStream classStream = null;
    try {
        classStream = new BufferedInputStream(new FileInputStream(testClassFile));
        final ClassReader classReader = new PatchedClassReader(IOUtils.toByteArray(classStream));
        classReader.accept(classVisitor, ClassReader.SKIP_DEBUG | ClassReader.SKIP_CODE | ClassReader.SKIP_FRAMES);
    } catch (Throwable e) {
        throw new GradleException("failed to read class file " + testClassFile.getAbsolutePath(), e);
    } finally {
        IOUtils.closeQuietly(classStream);
    }
    return classVisitor;
}
Also used : BufferedInputStream(java.io.BufferedInputStream) BufferedInputStream(java.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) GradleException(org.gradle.api.GradleException) PatchedClassReader(org.gradle.util.internal.PatchedClassReader) ClassReader(org.objectweb.asm.ClassReader) PatchedClassReader(org.gradle.util.internal.PatchedClassReader) FileInputStream(java.io.FileInputStream)

Example 40 with GradleException

use of org.gradle.api.GradleException in project gradle by gradle.

the class TestNGTestClassProcessor method runTests.

private void runTests() {
    TestNG testNg = new TestNG();
    testNg.setOutputDirectory(testReportDir.getAbsolutePath());
    testNg.setDefaultSuiteName(options.getDefaultSuiteName());
    testNg.setDefaultTestName(options.getDefaultTestName());
    if (options.getParallel() != null) {
        testNg.setParallel(options.getParallel());
    }
    if (options.getThreadCount() > 0) {
        testNg.setThreadCount(options.getThreadCount());
    }
    invokeVerifiedMethod(testNg, "setConfigFailurePolicy", String.class, options.getConfigFailurePolicy(), DEFAULT_CONFIG_FAILURE_POLICY);
    invokeVerifiedMethod(testNg, "setPreserveOrder", boolean.class, options.getPreserveOrder(), false);
    invokeVerifiedMethod(testNg, "setGroupByInstances", boolean.class, options.getGroupByInstances(), false);
    testNg.setUseDefaultListeners(options.getUseDefaultListeners());
    testNg.setVerbose(0);
    testNg.setGroups(CollectionUtils.join(",", options.getIncludeGroups()));
    testNg.setExcludedGroups(CollectionUtils.join(",", options.getExcludeGroups()));
    // this way, custom listeners are more powerful and, for example, they can change test status.
    for (String listenerClass : options.getListeners()) {
        try {
            testNg.addListener(applicationClassLoader.loadClass(listenerClass).newInstance());
        } catch (Throwable e) {
            throw new GradleException(String.format("Could not add a test listener with class '%s'.", listenerClass), e);
        }
    }
    if (!options.getIncludedTests().isEmpty() || !options.getIncludedTestsCommandLine().isEmpty()) {
        testNg.addListener(new SelectedTestsFilter(options.getIncludedTests(), options.getIncludedTestsCommandLine()));
    }
    if (!suiteFiles.isEmpty()) {
        testNg.setTestSuites(GFileUtils.toPaths(suiteFiles));
    } else {
        testNg.setTestClasses(testClasses.toArray(new Class[0]));
    }
    testNg.addListener((Object) adaptListener(new TestNGTestResultProcessorAdapter(resultProcessor, idGenerator, clock)));
    testNg.run();
}
Also used : TestNG(org.testng.TestNG) GradleException(org.gradle.api.GradleException)

Aggregations

GradleException (org.gradle.api.GradleException)114 File (java.io.File)40 IOException (java.io.IOException)32 TaskAction (org.gradle.api.tasks.TaskAction)16 ArrayList (java.util.ArrayList)10 UncheckedIOException (org.gradle.api.UncheckedIOException)10 MtlBaseTaskAction (com.taobao.android.builder.tasks.manager.MtlBaseTaskAction)9 AndroidDependencyTree (com.taobao.android.builder.dependency.AndroidDependencyTree)8 HashSet (java.util.HashSet)8 FileOutputStream (java.io.FileOutputStream)6 Method (java.lang.reflect.Method)6 UncheckedException (org.gradle.internal.UncheckedException)6 AwbBundle (com.taobao.android.builder.dependency.model.AwbBundle)5 URL (java.net.URL)5 List (java.util.List)5 ConsoleRenderer (org.gradle.internal.logging.ConsoleRenderer)5 ProcessOutputHandler (com.android.ide.common.process.ProcessOutputHandler)4 FileInputStream (java.io.FileInputStream)4 InvocationTargetException (java.lang.reflect.InvocationTargetException)4 MalformedURLException (java.net.MalformedURLException)4