Search in sources :

Example 1 with FileGroovitySourceLocator

use of com.disney.groovity.source.FileGroovitySourceLocator in project groovity by disney.

the class GroovityTestMojo method execute.

public void execute() throws MojoExecutionException, MojoFailureException {
    try {
        if (skip) {
            return;
        }
        getLog().info("STARTING Groovity test");
        populateSystemProperties();
        ClassLoader testLoader = createClassLoader(ClassLoaderScope.TEST);
        GroovityServletContainerBuilder builder = new GroovityServletContainerBuilder().setPort(Integer.valueOf(port)).setWebappDirectory(new File(project.getBasedir(), "src/main/webapp")).setClassLoader(testLoader);
        if (groovitySourceDirectory != null && groovitySourceDirectory.exists()) {
            builder.addSourceLocation(groovitySourceDirectory.toURI(), true);
        }
        if (groovityTestDirectory != null && groovityTestDirectory.exists()) {
            builder.addSourceLocation(groovityTestDirectory.toURI(), true);
        }
        if (sources != null) {
            for (File source : sources) {
                builder.addSourceLocation(source.toURI(), true);
            }
        }
        GroovityStatistics.reset();
        GroovityServletContainer container = builder.build();
        container.start();
        Groovity groovity = container.getGroovity();
        ArrayList<String> appSources = new ArrayList<String>();
        try {
            if (failOnError) {
                validateFactory(groovity);
            }
            if (skipTests) {
                return;
            }
            GroovitySourceLocator[] sourceLocators = groovity.getSourceLocators();
            for (GroovitySourceLocator locator : sourceLocators) {
                if (!interactive && ((FileGroovitySourceLocator) locator).getDirectory().equals(groovityTestDirectory)) {
                    if (path != null) {
                        String[] pathParts = path.split("\\s*,\\s*");
                        for (String pathPart : pathParts) {
                            container.run(pathPart);
                        }
                    } else {
                        for (GroovitySource source : locator) {
                            String scriptPath = source.getPath();
                            scriptPath = scriptPath.substring(0, scriptPath.lastIndexOf("."));
                            String scriptName = scriptPath.substring(scriptPath.lastIndexOf('/') + 1);
                            if (scriptName.startsWith("test")) {
                                container.run(scriptPath);
                            }
                        }
                    }
                }
                if (((FileGroovitySourceLocator) locator).getDirectory().equals(groovitySourceDirectory)) {
                    for (GroovitySource source : locator) {
                        appSources.add(source.getPath());
                    }
                }
            }
            if (interactive) {
                // in interactive mode we wait for instructions and compile each time to allow
                // real-time development
                container.enterConsole();
            }
        } finally {
            container.stop();
        }
        Map<String, CodeCoverage> coverageMap = new TreeMap<String, GroovityTestMojo.CodeCoverage>();
        Collection<Class<Script>> scriptClasses = groovity.getGroovityScriptClasses();
        for (Class<Script> sc : scriptClasses) {
            String sourcePath = groovity.getSourcePath(sc);
            if (appSources.contains(sourcePath)) {
                String scriptLabel = sourcePath.substring(0, sourcePath.length() - 5);
                CodeCoverage cc = new CodeCoverage(sc, scriptLabel);
                if (cc.isCoverable()) {
                    coverageMap.put(scriptLabel, cc);
                }
                for (Class<?> c : ((GroovityClassLoader) sc.getClassLoader()).getLoadedClasses()) {
                    if (!c.equals(sc) && !(Closure.class.isAssignableFrom(c)) && !c.isInterface()) {
                        String cname = getClassLabel(c);
                        int p = 0;
                        if ((p = cname.indexOf("$Trait")) > 0) {
                            cname = cname.substring(0, p);
                        }
                        String classLabel = scriptLabel + "->" + cname;
                        CodeCoverage icc = new CodeCoverage(c, classLabel);
                        if (icc.isCoverable()) {
                            coverageMap.put(classLabel, icc);
                        }
                    }
                }
            }
        }
        List<Statistics> stats = GroovityStatistics.getStatistics();
        for (Statistics stat : stats) {
            String sks = stat.key.toString();
            int dot = sks.indexOf(".");
            if (dot > 0) {
                String className = sks.substring(0, dot);
                String method = sks.substring(dot + 1);
                CodeCoverage cc = coverageMap.get(className);
                if (cc != null) {
                    if (method.equals("run()") && cc.runnable) {
                        cc.ran = true;
                    } else {
                        if (cc.methods.containsKey(method)) {
                            cc.methods.put(method, true);
                        }
                    }
                }
            }
        }
        Collection<CodeCoverage> ccs = coverageMap.values();
        double total = 0;
        for (CodeCoverage cc : ccs) {
            total += cc.getCoverage();
        }
        total /= ccs.size();
        getLog().info("TEST COVERAGE " + ((int) (100 * total)) + "% TOTAL");
        for (Entry<String, CodeCoverage> entry : coverageMap.entrySet()) {
            CodeCoverage cc = entry.getValue();
            double covered = cc.getCoverage();
            getLog().info(" " + ((int) (100 * covered)) + "% coverage for " + cc.label);
            if (covered < 1.0) {
                if (cc.runnable && !cc.ran) {
                    getLog().warn("   Script body did not run during tests");
                }
                List<String> uncovered = cc.getUncoveredMethods();
                if (!uncovered.isEmpty()) {
                    for (String m : cc.getUncoveredMethods()) {
                        getLog().warn("   " + m + " did not execute during tests");
                    }
                }
            }
        /*
				for(String m: cc.getCoveredMethods()) {
					getLog().info("   " + m + " executed during tests");
				}
				*/
        }
    } catch (MojoFailureException e) {
        throw e;
    } catch (Throwable e) {
        getLog().error("ERROR in Groovity test", e);
        throw new MojoFailureException(e.getMessage());
    }
}
Also used : ArrayList(java.util.ArrayList) FileGroovitySourceLocator(com.disney.groovity.source.FileGroovitySourceLocator) Groovity(com.disney.groovity.Groovity) GroovityClassLoader(com.disney.groovity.compile.GroovityClassLoader) GroovitySource(com.disney.groovity.source.GroovitySource) GroovityServletContainer(com.disney.groovity.servlet.container.GroovityServletContainer) Script(groovy.lang.Script) GroovityServletContainerBuilder(com.disney.groovity.servlet.container.GroovityServletContainerBuilder) MojoFailureException(org.apache.maven.plugin.MojoFailureException) GroovityClassLoader(com.disney.groovity.compile.GroovityClassLoader) TreeMap(java.util.TreeMap) GroovityStatistics(com.disney.groovity.stats.GroovityStatistics) Statistics(com.disney.groovity.stats.GroovityStatistics.Statistics) GatherStatistics(com.disney.groovity.compile.GatherStatistics) GroovitySourceLocator(com.disney.groovity.source.GroovitySourceLocator) FileGroovitySourceLocator(com.disney.groovity.source.FileGroovitySourceLocator) File(java.io.File)

Example 2 with FileGroovitySourceLocator

use of com.disney.groovity.source.FileGroovitySourceLocator in project groovity by disney.

the class GroovityBuilder method build.

/**
 * After setting all initialization parameters, call build(true) to construct, initialize and return the fully started Groovity,
 * or build(false) to initialize the Groovity without starting (e.g. to just build jar files without initing and starting classes)
 *
 * @return an initialized Groovity
 * @throws IllegalAccessException
 * @throws IllegalArgumentException
 * @throws InvocationTargetException
 * @throws IOException
 * @throws URISyntaxException
 */
public Groovity build(boolean start) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, IOException, URISyntaxException {
    CopyOnWriteArrayList<Configurator> configurators = new CopyOnWriteArrayList<Configurator>();
    configurators.add(new SystemConfigurator());
    if (propsResource != null) {
        configurators.add(new PropertiesResourceConfigurator(propsResource));
    }
    if (propsFile != null) {
        configurators.add(new PropertiesFileConfigurator(propsFile));
    }
    if (propsURL != null) {
        configurators.add(new PropertiesURLConfigurator(propsURL));
    }
    if (configurator != null) {
        configurators.add(configurator);
    }
    Groovity groovity = new Groovity();
    groovity.setJarDirectory(jarDirectory);
    groovity.setJarPhases(jarPhases);
    groovity.setSourcePhases(sourcePhases);
    groovity.setCaseSensitive(caseSensitive);
    groovity.setArgsLookup(argsLookup);
    groovity.setAsyncThreads(asyncThreads);
    groovity.setScriptBaseClass(scriptBaseClass);
    groovity.setParentLoader(parentClassLoader);
    groovity.setConfigurator(new MultiConfigurator(configurators));
    final AtomicReference<BindingDecorator> bindingDecoratorRef = new AtomicReference<BindingDecorator>(bindingDecorator);
    if (defaultBinding != null) {
        bindingDecoratorRef.set(new BindingMapDecorator(new ConcurrentHashMap<String, Object>(defaultBinding), bindingDecoratorRef.get()));
    }
    ServiceLoader.load(BindingDecorator.class).forEach(decorator -> {
        decorator.setChainedDecorator(bindingDecoratorRef.get());
        bindingDecoratorRef.set(decorator);
    });
    groovity.setBindingDecorator(bindingDecoratorRef.get());
    if (httpClientBuilder == null) {
        httpClientBuilder = HttpClientBuilder.create().useSystemProperties();
    }
    if (maxHttpConnPerRoute > 0) {
        httpClientBuilder.setMaxConnPerRoute(maxHttpConnPerRoute);
    }
    if (maxHttpConnTotal > 0) {
        httpClientBuilder.setMaxConnTotal(maxHttpConnTotal);
    }
    groovity.setHttpClient(httpClientBuilder.build());
    List<GroovitySourceLocator> locators = new ArrayList<GroovitySourceLocator>();
    if ((sourceLocations == null || sourceLocations.isEmpty()) && (sourceLocators == null || sourceLocators.isEmpty()) && jarDirectory == null) {
        throw new IllegalArgumentException("No groovity source locators or jar directories configured");
    }
    if (sourceLocators != null) {
        for (GroovitySourceLocator locator : sourceLocators) {
            locators.add(locator);
        }
    }
    if (sourceLocations != null) {
        for (URI location : sourceLocations) {
            AbstractGroovitySourceLocator sourceLocator = null;
            String scheme = location.getScheme();
            if (scheme != null) {
                scheme = scheme.toLowerCase();
                if (scheme.startsWith("http")) {
                    sourceLocator = new HttpGroovitySourceLocator(location);
                } else if (scheme.equals("classpath")) {
                    sourceLocator = new ClasspathGroovitySourceLocator(location.getPath());
                }
            }
            if (sourceLocator == null) {
                // file locator
                if (location.isAbsolute()) {
                    sourceLocator = new FileGroovitySourceLocator(new File(location));
                } else {
                    sourceLocator = new FileGroovitySourceLocator(new File(location.getPath()));
                }
            }
            sourceLocator.setInterval(sourcePollSeconds);
            locators.add(sourceLocator);
        }
    }
    groovity.setSourceLocators(locators.toArray(new GroovitySourceLocator[0]));
    if (start) {
        groovity.start();
    } else {
        groovity.init(false);
    }
    return groovity;
}
Also used : SystemConfigurator(com.disney.groovity.conf.SystemConfigurator) HttpGroovitySourceLocator(com.disney.groovity.source.HttpGroovitySourceLocator) PropertiesURLConfigurator(com.disney.groovity.conf.PropertiesURLConfigurator) PropertiesResourceConfigurator(com.disney.groovity.conf.PropertiesResourceConfigurator) PropertiesFileConfigurator(com.disney.groovity.conf.PropertiesFileConfigurator) MultiConfigurator(com.disney.groovity.conf.MultiConfigurator) Configurator(com.disney.groovity.conf.Configurator) SystemConfigurator(com.disney.groovity.conf.SystemConfigurator) PropertiesResourceConfigurator(com.disney.groovity.conf.PropertiesResourceConfigurator) ArrayList(java.util.ArrayList) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) FileGroovitySourceLocator(com.disney.groovity.source.FileGroovitySourceLocator) MultiConfigurator(com.disney.groovity.conf.MultiConfigurator) URI(java.net.URI) AbstractGroovitySourceLocator(com.disney.groovity.source.AbstractGroovitySourceLocator) PropertiesURLConfigurator(com.disney.groovity.conf.PropertiesURLConfigurator) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) ClasspathGroovitySourceLocator(com.disney.groovity.source.ClasspathGroovitySourceLocator) PropertiesFileConfigurator(com.disney.groovity.conf.PropertiesFileConfigurator) ClasspathGroovitySourceLocator(com.disney.groovity.source.ClasspathGroovitySourceLocator) GroovitySourceLocator(com.disney.groovity.source.GroovitySourceLocator) FileGroovitySourceLocator(com.disney.groovity.source.FileGroovitySourceLocator) AbstractGroovitySourceLocator(com.disney.groovity.source.AbstractGroovitySourceLocator) HttpGroovitySourceLocator(com.disney.groovity.source.HttpGroovitySourceLocator) File(java.io.File) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList)

Example 3 with FileGroovitySourceLocator

use of com.disney.groovity.source.FileGroovitySourceLocator in project groovity by disney.

the class GroovityServletContainer method enterConsole.

public void enterConsole() {
    groovity.getArgsLookup().chainLast(new ArgsLookup.ConsoleArgsLookup());
    try {
        Console console = System.console();
        if (console == null) {
            log.warning("Unable to retrieve System.console(), GroovityServletContainer will not be interactive");
            try {
                Thread.currentThread().join();
            } catch (InterruptedException e) {
            }
            return;
        }
        String cmdFmt = "(l)ist, (a)ll, (q)uit, or script path [%1$s] : ";
        String scriptPath = "";
        String command = console.readLine(cmdFmt, scriptPath);
        while (!"q".equals(command)) {
            if (!command.trim().isEmpty()) {
                scriptPath = command.trim();
            }
            if (scriptPath.isEmpty()) {
                console.printf("Error: enter a script path or q to quit\n");
            } else {
                // pick up any code changes
                groovity.compileAll(false, true);
                final AtomicBoolean error = new AtomicBoolean(false);
                groovity.getCompilerEvents().forEach((k, v) -> {
                    if (v.getError() != null) {
                        error.set(true);
                    }
                });
                if (!error.get()) {
                    String[] pathParts;
                    if ("a".equals(scriptPath) || "l".equals(scriptPath)) {
                        ArrayList<String> paths = new ArrayList<>();
                        for (GroovitySourceLocator locator : groovity.getSourceLocators()) {
                            if (locator instanceof FileGroovitySourceLocator) {
                                String directory = ((FileGroovitySourceLocator) locator).getDirectory().toURI().toString();
                                if (consoleSourceLocations.contains(directory)) {
                                    for (GroovitySource source : locator) {
                                        paths.add(source.getPath().substring(0, source.getPath().lastIndexOf(".")));
                                    }
                                }
                            }
                        }
                        if (paths.isEmpty()) {
                            paths.addAll(groovity.getGroovityScriptNames());
                        }
                        pathParts = paths.toArray(new String[0]);
                    } else {
                        pathParts = scriptPath.split("\\s*,\\s*");
                    }
                    if ("l".equals(scriptPath)) {
                        console.printf("All available paths:\n");
                        for (String pathPart : pathParts) {
                            console.printf("\t%1$s\n", pathPart);
                        }
                    } else {
                        for (String pathPart : pathParts) {
                            try {
                                run(pathPart);
                            } catch (Throwable e) {
                                console.printf("%1$s running script %2$s :\n", e.getClass().getName(), pathPart);
                                e.printStackTrace(console.writer());
                            }
                        }
                    }
                }
            }
            command = console.readLine(cmdFmt, scriptPath);
        }
    } finally {
        groovity.getArgsLookup().removeLast();
    }
}
Also used : ArrayList(java.util.ArrayList) FileGroovitySourceLocator(com.disney.groovity.source.FileGroovitySourceLocator) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ArgsLookup(com.disney.groovity.ArgsLookup) GroovitySourceLocator(com.disney.groovity.source.GroovitySourceLocator) FileGroovitySourceLocator(com.disney.groovity.source.FileGroovitySourceLocator) Console(java.io.Console) GroovitySource(com.disney.groovity.source.GroovitySource)

Aggregations

FileGroovitySourceLocator (com.disney.groovity.source.FileGroovitySourceLocator)3 GroovitySourceLocator (com.disney.groovity.source.GroovitySourceLocator)3 ArrayList (java.util.ArrayList)3 GroovitySource (com.disney.groovity.source.GroovitySource)2 File (java.io.File)2 ArgsLookup (com.disney.groovity.ArgsLookup)1 Groovity (com.disney.groovity.Groovity)1 GatherStatistics (com.disney.groovity.compile.GatherStatistics)1 GroovityClassLoader (com.disney.groovity.compile.GroovityClassLoader)1 Configurator (com.disney.groovity.conf.Configurator)1 MultiConfigurator (com.disney.groovity.conf.MultiConfigurator)1 PropertiesFileConfigurator (com.disney.groovity.conf.PropertiesFileConfigurator)1 PropertiesResourceConfigurator (com.disney.groovity.conf.PropertiesResourceConfigurator)1 PropertiesURLConfigurator (com.disney.groovity.conf.PropertiesURLConfigurator)1 SystemConfigurator (com.disney.groovity.conf.SystemConfigurator)1 GroovityServletContainer (com.disney.groovity.servlet.container.GroovityServletContainer)1 GroovityServletContainerBuilder (com.disney.groovity.servlet.container.GroovityServletContainerBuilder)1 AbstractGroovitySourceLocator (com.disney.groovity.source.AbstractGroovitySourceLocator)1 ClasspathGroovitySourceLocator (com.disney.groovity.source.ClasspathGroovitySourceLocator)1 HttpGroovitySourceLocator (com.disney.groovity.source.HttpGroovitySourceLocator)1