Search in sources :

Example 6 with GroovitySourceLocator

use of com.disney.groovity.source.GroovitySourceLocator 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 7 with GroovitySourceLocator

use of com.disney.groovity.source.GroovitySourceLocator 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)

Example 8 with GroovitySourceLocator

use of com.disney.groovity.source.GroovitySourceLocator 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

GroovitySourceLocator (com.disney.groovity.source.GroovitySourceLocator)8 ArrayList (java.util.ArrayList)7 GroovitySource (com.disney.groovity.source.GroovitySource)5 IOException (java.io.IOException)5 CopyOnWriteArrayList (java.util.concurrent.CopyOnWriteArrayList)4 FileGroovitySourceLocator (com.disney.groovity.source.FileGroovitySourceLocator)3 Script (groovy.lang.Script)3 File (java.io.File)3 FileNotFoundException (java.io.FileNotFoundException)3 InvocationTargetException (java.lang.reflect.InvocationTargetException)3 ArgsLookup (com.disney.groovity.ArgsLookup)2 Groovity (com.disney.groovity.Groovity)2 URI (java.net.URI)2 BindingDecorator (com.disney.groovity.BindingDecorator)1 GroovityBuilder (com.disney.groovity.GroovityBuilder)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