Search in sources :

Example 1 with Groovity

use of com.disney.groovity.Groovity in project groovity by disney.

the class GroovityPackageMojo method execute.

public void execute() throws MojoExecutionException, MojoFailureException {
    String oldAuth = System.getProperty(DISABLE_AUTH);
    System.setProperty(DISABLE_AUTH, "true");
    try {
        getLog().info("STARTING Groovity package");
        populateSystemProperties();
        Groovity groovity = new GroovityBuilder().setSourceLocations(Arrays.asList(groovitySourceDirectory.toURI())).setDefaultBinding(defaultBinding).setParentClassLoader(createClassLoader(ClassLoaderScope.COMPILE)).setJarDirectory(groovityJarDirectory).setJarPhases(EnumSet.of(GroovityPhase.RUNTIME)).build(false);
        try {
            if (failOnError) {
                validateFactory(groovity);
            }
        } finally {
            groovity.destroy();
        }
        if (groovityJarDirectory.exists()) {
            // now we will generate a manifest of the generated jar files
            File manifest = new File(groovityJarDirectory, "manifest");
            FileOutputStream stream = new FileOutputStream(manifest);
            PrintWriter writer = new PrintWriter(stream);
            try {
                walk(groovityJarDirectory.toPath(), groovityJarDirectory, writer);
            } finally {
                writer.close();
            }
        }
    } catch (MojoFailureException e) {
        throw e;
    } catch (Throwable e) {
        getLog().error("ERROR in Groovity package", e);
        throw new MojoFailureException(e.getMessage());
    } finally {
        if (oldAuth != null) {
            System.setProperty(DISABLE_AUTH, oldAuth);
        } else {
            System.getProperties().remove(DISABLE_AUTH);
        }
    }
}
Also used : GroovityBuilder(com.disney.groovity.GroovityBuilder) Groovity(com.disney.groovity.Groovity) FileOutputStream(java.io.FileOutputStream) MojoFailureException(org.apache.maven.plugin.MojoFailureException) File(java.io.File) PrintWriter(java.io.PrintWriter)

Example 2 with Groovity

use of com.disney.groovity.Groovity in project groovity by disney.

the class GroovityRunMojo method execute.

public void execute() throws MojoExecutionException, MojoFailureException {
    try {
        getLog().info("STARTING Groovity run ");
        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);
            }
        }
        GroovityServletContainer container = builder.build();
        container.start();
        try {
            GroovityStatistics.reset();
            Groovity groovity = container.getGroovity();
            if (path != null) {
                groovity.getArgsLookup().chainLast(new ArgsLookup.ConsoleArgsLookup());
                String[] pathParts = path.split("\\s*,\\s*");
                for (String pathPart : pathParts) {
                    container.run(pathPart);
                }
            } else {
                container.enterConsole();
            }
        } finally {
            container.stop();
        }
        getLog().info("DONE with Groovity run ");
    } catch (Throwable e) {
        getLog().error("ERROR in Groovity run ", e);
        throw new MojoFailureException(e.getMessage());
    }
}
Also used : GroovityServletContainer(com.disney.groovity.servlet.container.GroovityServletContainer) ArgsLookup(com.disney.groovity.ArgsLookup) Groovity(com.disney.groovity.Groovity) GroovityServletContainerBuilder(com.disney.groovity.servlet.container.GroovityServletContainerBuilder) MojoFailureException(org.apache.maven.plugin.MojoFailureException) File(java.io.File)

Example 3 with Groovity

use of com.disney.groovity.Groovity 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 4 with Groovity

use of com.disney.groovity.Groovity in project groovity by disney.

the class PortalSessionAuthorizationFilter method doFilter.

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    if (request instanceof HttpServletRequest) {
        HttpServletRequest hr = (HttpServletRequest) request;
        HttpSession session = hr.getSession(false);
        if (session != null) {
            Object userId = session.getAttribute("userId");
            if (userId != null) {
                Groovity groovity = (Groovity) servletContext.getAttribute(GroovityServlet.SERVLET_CONTEXT_GROOVITY_INSTANCE);
                Script factory;
                try {
                    factory = groovity.load("/data/factory", new Binding());
                } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
                    throw new ServletException(e);
                }
                Object user = factory.invokeMethod("call", new String[] { "person", userId.toString() });
                if (user != null && user instanceof Principal) {
                    request = new AuthenticatedRequestWrapper(hr, (Principal) user);
                }
            }
        }
    }
    chain.doFilter(request, response);
}
Also used : Binding(groovy.lang.Binding) Script(groovy.lang.Script) HttpSession(javax.servlet.http.HttpSession) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) Groovity(com.disney.groovity.Groovity) AuthenticatedRequestWrapper(com.disney.http.auth.server.AuthenticatedRequestWrapper) GroovyObject(groovy.lang.GroovyObject) Principal(java.security.Principal)

Example 5 with Groovity

use of com.disney.groovity.Groovity in project groovity by disney.

the class GroovityServlet method init.

/**
 * see {@link GenericServlet#init}
 */
@Override
public void init() throws ServletException {
    try {
        LOG.info("Initializing GroovityServlet");
        ServletConfig config = getServletConfig();
        if (groovityScriptViewFactory == null) {
            GroovityBuilder builder = new GroovityBuilder();
            configProperties = new Properties();
            String propsFile = getParam(PROPS_FILE);
            if (isNotBlank(propsFile)) {
                URL url = config.getServletContext().getClassLoader().getResource(propsFile);
                if (url == null && propsFile.startsWith("/")) {
                    url = config.getServletContext().getResource(propsFile);
                }
                if (url != null) {
                    LOG.info("Found groovity properties resource " + url);
                    builder.setPropsUrl(url);
                    try (InputStream configStream = url.openStream()) {
                        configProperties.load(configStream);
                    }
                } else {
                    File file = new File(propsFile);
                    if (file.exists()) {
                        LOG.info("Found groovity properties file " + file.getAbsolutePath());
                        builder.setPropsFile(file);
                        if (!file.isDirectory()) {
                            try (InputStream configStream = new FileInputStream(file)) {
                                configProperties.load(configStream);
                            }
                        }
                    } else {
                        LOG.warning("Groovity properties file " + propsFile + " not found");
                    }
                }
            } else {
                URL url = config.getServletContext().getClassLoader().getResource("groovity.properties");
                if (url != null) {
                    LOG.info("Found groovity.properties on classpath");
                    builder.setPropsUrl(url);
                    try (InputStream configStream = url.openStream()) {
                        configProperties.load(configStream);
                    }
                }
            }
            if (configProperties.containsKey(IGNORE_STATUS_CODES) && !System.getProperties().containsKey(IGNORE_STATUS_CODES)) {
                System.setProperty(IGNORE_STATUS_CODES, configProperties.getProperty(IGNORE_STATUS_CODES));
            }
            if (configProperties.containsKey(ERROR_PAGE) && !System.getProperties().containsKey(ERROR_PAGE)) {
                System.setProperty(ERROR_PAGE, configProperties.getProperty(ERROR_PAGE));
            }
            String async = getParam(ASYNC_THREADS_PARAM);
            if (isNotBlank(async)) {
                builder.setAsyncThreads(Integer.parseInt(async));
            }
            String caseSens = getParam(CASE_SENSITIVE_PARAM);
            if (isNotBlank(caseSens)) {
                builder.setCaseSensitive(Boolean.parseBoolean(caseSens));
            }
            String maxPerRoute = getParam(MAX_CONN_PER_ROUTE_PARAM);
            if (isNotBlank(maxPerRoute)) {
                builder.setMaxHttpConnPerRoute(Integer.parseInt(maxPerRoute));
            }
            String maxTotal = getParam(MAX_CONN_TOTAL_PARAM);
            if (isNotBlank(maxTotal)) {
                builder.setMaxHttpConnTotal(Integer.parseInt(maxTotal));
            }
            File jarDirectory;
            String jarDir = getParam(JAR_DIRECTORY_PARAM);
            if (isNotBlank(jarDir)) {
                jarDirectory = new File(jarDir);
            } else {
                // default jar directory;
                jarDirectory = new File(getServletContext().getRealPath("/"), JAR_DIRECTORY_PARAM_DEFAULT_VALUE);
            }
            builder.setJarDirectory(jarDirectory);
            String jarPhase = getParam(JAR_PHASES_PARAM);
            if (isNotBlank(jarPhase)) {
                builder.setJarPhase(jarPhase);
            }
            String scriptBase = getParam(SCRIPT_BASE_CLASS_PARAM);
            if (isNotBlank(scriptBase)) {
                builder.setScriptBaseClass(scriptBase);
            }
            String defaultBinding = getParam(DEFAULT_BINDING);
            if (isNotBlank(defaultBinding)) {
                @SuppressWarnings("unchecked") Map<String, Object> db = (Map<String, Object>) new JsonSlurper().parse(new StringReader(defaultBinding));
                builder.setDefaultBinding(db);
            }
            String sourcePhase = getParam(SOURCE_PHASES_PARAM);
            if (isNotBlank(sourcePhase)) {
                builder.setSourcePhase(sourcePhase);
            }
            String sourcePoll = getParam(SOURCE_POLL_SECONDS);
            if (isNotBlank(sourcePoll)) {
                builder.setSourcePollSeconds(Integer.parseInt(sourcePoll));
            }
            String configurator = getParam(CONFIGURATOR);
            if (isNotBlank(configurator)) {
                builder.setConfigurator((Configurator) loadInstance(configurator));
            }
            String shutdown = getParam(SHUTDOWN_HANDLER);
            if (isNotBlank(shutdown)) {
                shutdownHandler = (Runnable) loadInstance(shutdown);
            }
            String hostnameVerifier = getParam(HOSTNAME_VERIFIER);
            if (isNotBlank(hostnameVerifier)) {
                builder.getHttpClientBuilder().setSSLHostnameVerifier((HostnameVerifier) loadInstance(hostnameVerifier));
            }
            String trustStrategy = getParam(TRUST_STRATEGY);
            if (isNotBlank(trustStrategy)) {
                SSLContextBuilder sslb = new SSLContextBuilder();
                sslb.loadTrustMaterial((TrustStrategy) loadInstance(trustStrategy));
                builder.getHttpClientBuilder().setSSLContext(sslb.build());
            }
            String sourceLocation = getParam(SOURCE_LOCATION_PARAM);
            String sourceLocator = getParam(SOURCE_LOCATOR_PARAM);
            if (isNotBlank(sourceLocation)) {
                // newlines separate multiple
                String[] sources = sourceLocation.split(SOURCE_LOCATOR_SPLIT_REGEX);
                ArrayList<URI> sourceURIs = new ArrayList<URI>(sources.length);
                for (String source : sources) {
                    if (isNotBlank(source)) {
                        sourceURIs.add(new URI(source));
                    }
                }
                builder.setSourceLocations(sourceURIs);
            } else if (isNotBlank(sourceLocator)) {
                String[] sources = sourceLocator.split(SOURCE_LOCATOR_SPLIT_REGEX);
                ArrayList<GroovitySourceLocator> sourceLocators = new ArrayList<GroovitySourceLocator>(sources.length);
                for (String source : sources) {
                    if (isNotBlank(source)) {
                        sourceLocators.add((GroovitySourceLocator) loadInstance(source));
                    }
                }
                builder.setSourceLocators(sourceLocators);
            }
            // we want to allow unconfigured groovities to run, presuming there are embedded
            // groovity classes
            BindingDecorator userDecorator = null;
            String userDecoratorClass = getParam(BINDING_DECORATOR);
            if (isNotBlank(userDecoratorClass)) {
                userDecorator = (BindingDecorator) loadInstance(userDecoratorClass);
            }
            builder.setBindingDecorator(new BindingDecorator(userDecorator) {

                @Override
                public void decorate(Map<String, Object> binding) {
                    binding.put("servletContext", GroovityServlet.this.getServletContext());
                }
            });
            builder.setArgsLookup(new ArgsLookup(new RequestArgsLookup()));
            GroovityErrorHandlerChain errorHandlers = GroovityErrorHandlerChain.createDefault();
            String chainDecorator = getParam(ERROR_CHAIN_DECORATOR);
            if (isNotBlank(chainDecorator)) {
                ((GroovityErrorHandlerChainDecorator) loadInstance(chainDecorator)).decorate(errorHandlers);
            }
            ServiceLoader.load(GroovityErrorHandlerChainDecorator.class).forEach(decorator -> {
                decorator.decorate(errorHandlers);
            });
            Groovity groovity = builder.build();
            groovityScriptViewFactory = new GroovityScriptViewFactory();
            groovityScriptViewFactory.setGroovity(groovity);
            groovityScriptViewFactory.setServletContext(getServletContext());
            groovityScriptViewFactory.setErrorHandlers(errorHandlers);
            groovityScriptViewFactory.init();
            config.getServletContext().setAttribute(SERVLET_CONTEXT_GROOVITY_VIEW_FACTORY, groovityScriptViewFactory);
            config.getServletContext().setAttribute(SERVLET_CONTEXT_GROOVITY_INSTANCE, groovity);
        }
        javax.websocket.server.ServerContainer webSocketServer = (javax.websocket.server.ServerContainer) config.getServletContext().getAttribute("javax.websocket.server.ServerContainer");
        if (webSocketServer != null) {
            // register websocket endpoint
            webSocketServer.addEndpoint(ServerEndpointConfig.Builder.create(GroovityServerEndpoint.class, "/ws/{socketName}").configurator(new GroovityServerEndpoint.Configurator(groovityScriptViewFactory)).build());
            LOG.info("Created groovity web socket endpoint");
        }
        LOG.info("Completed initialization of GroovityServlet");
    } catch (Exception e) {
        throw new ServletException(e);
    }
}
Also used : ArrayList(java.util.ArrayList) Properties(java.util.Properties) URI(java.net.URI) URL(java.net.URL) ServletException(javax.servlet.ServletException) GroovityBuilder(com.disney.groovity.GroovityBuilder) Groovity(com.disney.groovity.Groovity) StringReader(java.io.StringReader) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder) JsonSlurper(groovy.json.JsonSlurper) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) GroovityErrorHandlerChain(com.disney.groovity.servlet.error.GroovityErrorHandlerChain) ServletConfig(javax.servlet.ServletConfig) FileInputStream(java.io.FileInputStream) ServletException(javax.servlet.ServletException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) ArgsLookup(com.disney.groovity.ArgsLookup) GroovitySourceLocator(com.disney.groovity.source.GroovitySourceLocator) GroovityErrorHandlerChainDecorator(com.disney.groovity.servlet.error.GroovityErrorHandlerChainDecorator) BindingDecorator(com.disney.groovity.BindingDecorator) File(java.io.File) Map(java.util.Map)

Aggregations

Groovity (com.disney.groovity.Groovity)8 File (java.io.File)5 GroovityBuilder (com.disney.groovity.GroovityBuilder)4 Binding (groovy.lang.Binding)3 Script (groovy.lang.Script)3 MojoFailureException (org.apache.maven.plugin.MojoFailureException)3 ArgsLookup (com.disney.groovity.ArgsLookup)2 BindingDecorator (com.disney.groovity.BindingDecorator)2 GroovityServletContainer (com.disney.groovity.servlet.container.GroovityServletContainer)2 GroovityServletContainerBuilder (com.disney.groovity.servlet.container.GroovityServletContainerBuilder)2 GroovitySourceLocator (com.disney.groovity.source.GroovitySourceLocator)2 URI (java.net.URI)2 ArrayList (java.util.ArrayList)2 Map (java.util.Map)2 ServletException (javax.servlet.ServletException)2 Test (org.junit.Test)2 GatherStatistics (com.disney.groovity.compile.GatherStatistics)1 GroovityClassLoader (com.disney.groovity.compile.GroovityClassLoader)1 GroovityErrorHandlerChain (com.disney.groovity.servlet.error.GroovityErrorHandlerChain)1 GroovityErrorHandlerChainDecorator (com.disney.groovity.servlet.error.GroovityErrorHandlerChainDecorator)1