use of com.disney.groovity.GroovityBuilder 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);
}
}
}
use of com.disney.groovity.GroovityBuilder 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);
}
}
use of com.disney.groovity.GroovityBuilder in project groovity by disney.
the class TestGroovityTags method setup.
@BeforeClass
public static void setup() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, IOException, URISyntaxException {
Handler testHandler = new Handler() {
@Override
public void publish(LogRecord record) {
logRecords.add(record);
}
@Override
public void flush() {
}
@Override
public void close() throws SecurityException {
}
};
testHandler.setLevel(Level.FINE);
testScriptLogger = Logger.getLogger("/logTestScript.grvt");
testScriptLogger.addHandler(testHandler);
testScriptLogger.setLevel(Level.FINE);
groovity = new GroovityBuilder().setSourceLocations(Arrays.asList(new File("src/test/resources/tags").toURI())).build();
}
use of com.disney.groovity.GroovityBuilder in project groovity by disney.
the class HttpLocatorTest method testHTTPCompile.
@Test
public void testHTTPCompile() throws Exception {
stubFor(get(urlEqualTo("/")).willReturn(aResponse().withStatus(200).withHeader("Last-Modified", "100").withBody("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2 Final//EN\">\r\n" + "<html>\r\n" + " <head>\r\n" + " <title>Index of /groovy/nwsDynGroovy</title>\r\n" + " </head>\r\n" + " <body>\r\n" + "<h1>Index of /groovy/nwsDynGroovy</h1>\r\n" + "<ul><li><a href=\"/groovy/\"> Parent Directory</a></li>\r\n" + "<li><a href=\"test.grvt\"> test.grvt</a></li>\r\n" + "</ul>\r\n" + "</body></html>")));
String lmod = DateUtils.formatDate(new Date());
stubFor(head(urlEqualTo("/test.grvt")).willReturn(aResponse().withStatus(200).withHeader("Last-Modified", lmod)));
stubFor(get(urlEqualTo("/test.grvt")).willReturn(aResponse().withStatus(200).withHeader("Last-Modified", lmod).withBody(" out << \"hello\" ")));
Groovity groovity = new GroovityBuilder().setSourcePhases(EnumSet.of(GroovityPhase.STARTUP)).setSourceLocations(Arrays.asList(new URI("http://localhost:28187"))).build();
CharArrayWriter writer = new CharArrayWriter();
Binding binding = new Binding();
Script script = groovity.load("/test", binding);
binding.setProperty("out", writer);
script.run();
Assert.assertEquals("hello", writer.toString());
}
use of com.disney.groovity.GroovityBuilder in project groovity by disney.
the class TestCoreGroovity method setupGroovity.
private static Groovity setupGroovity(boolean caseSensitive, final Writer out) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, IOException, URISyntaxException {
Map<String, Object> defaultBinding = new HashMap<>();
defaultBinding.put("hello", "world");
defaultBinding.put("extensions", "overrideMe");
Groovity groovity = new GroovityBuilder().setSourceLocations(Arrays.asList(new File("src/test/resources/core").toURI())).setSourcePhases(EnumSet.of(GroovityPhase.STARTUP)).setCaseSensitive(caseSensitive).setDefaultBinding(defaultBinding).setBindingDecorator(new BindingDecorator() {
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public void decorate(Map binding) {
binding.put("extensions", Arrays.asList("antivirus", "firewall"));
binding.put("whatToSay", "Orange you glad I didn't say banana?");
if (!binding.containsKey("out")) {
binding.put("out", out);
}
}
}).build();
return groovity;
}
Aggregations