groovy.util.GroovyScriptEngine Java Examples

The following examples show how to use groovy.util.GroovyScriptEngine. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TestGroovyCapabilityBindings.java    From arcusplatform with Apache License 2.0 7 votes vote down vote up
@Test
public void testPlatformDeviceConnectionImport() {
   CapabilityRegistry registry = ServiceLocator.getInstance(CapabilityRegistry.class);

   CompilerConfiguration config = new CompilerConfiguration();
   config.setTargetDirectory(new File(TMP_DIR));
   config.addCompilationCustomizers(new DriverCompilationCustomizer(registry));

   GroovyScriptEngine engine = new GroovyScriptEngine(new ClasspathResourceConnector());
   engine.setConfig(config);
   DriverBinding binding = new DriverBinding(
           ServiceLocator.getInstance(CapabilityRegistry.class),
           new GroovyDriverFactory(engine, registry, ImmutableSet.of(new ControlProtocolPlugin()))
   );
   GroovyDriverBuilder builder = binding.getBuilder();
   assertNotNull(builder.importCapability(GroovyDrivers.PLATFORM_DEVICE_CONNECTION_CAPABILITY));
}
 
Example #2
Source File: TestGroovyCapabilityDefinition.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
@Before
public void setUp() throws Exception {
   super.setUp();
   AttributeMap attributes = AttributeMap.newMap();
   attributes.set(DeviceCapability.KEY_DEVTYPEHINT, "device");
   attributes.set(DeviceCapability.KEY_MODEL, "model");
   attributes.set(DeviceCapability.KEY_VENDOR, "vendor");

   Device device = Fixtures.createDevice();
   device.setAccount(UUID.fromString(accountId));
   device.setPlace(UUID.fromString(placeId));
   device.setDevtypehint("device");
   device.setModel("model");
   device.setName("name");
   device.setVendor("vendor");

   engine = new GroovyScriptEngine(new ClasspathResourceConnector(TestGroovyCapabilityDefinition.class));
   context = new PlatformDeviceDriverContext(device, DeviceDriverDefinition.builder().withName("TestDriver").create(), new DeviceDriverStateHolder(attributes), mockPopulationCacheMgr);
   binding = new DriverBinding(new StaticCapabilityRegistryImpl(Collections.singleton(deviceCapability())), null);
   script = engine.createScript("TestGroovyCapabilityDefinition.gscript", binding);
   script.setProperty(DeviceCapability.NAME, new GroovyCapabilityDefinition(deviceCapability(), binding));
   script.run();

   GroovyContextObject.setContext(context);
}
 
Example #3
Source File: GroovyMod.java    From Cardshifter with Apache License 2.0 6 votes vote down vote up
public GroovyMod(File directory, String name) {
    Throwable ex = null;

    try {
        URL groovyURL = GroovyMod.class.getResource("");

        GroovyScriptEngine scriptEngine = new GroovyScriptEngine(new URL[]{groovyURL, directory.toURI().toURL()});
        CompilerConfiguration config = new CompilerConfiguration();
        scriptEngine.setConfig(config);

        script = new GroovyRunner(directory, name, scriptEngine.getGroovyClassLoader());
    } catch (Exception | AssertionError e) {
        ex = e;
    }

    this.exception = ex;
}
 
Example #4
Source File: AbstractScripting.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
public void clearCache() {
    getGroovyClassLoader().clearCache();
    javaClassLoader.clearCache();
    getPool().clear();
    GroovyScriptEngine gse = getGroovyScriptEngine();
    try {
        Field scriptCacheField = gse.getClass().getDeclaredField("scriptCache");
        scriptCacheField.setAccessible(true);
        Map scriptCacheMap = (Map) scriptCacheField.get(gse);
        scriptCacheMap.clear();
    } catch (NoSuchFieldException | IllegalAccessException e) {
        //ignore the exception
    }
}
 
Example #5
Source File: GroovyScriptFactory.java    From engine with GNU General Public License v3.0 5 votes vote down vote up
public GroovyScriptFactory(SiteContext siteContext, ResourceConnector resourceConnector,
                           ClassLoader parentClassLoader, Map<String, Object> globalVariables,
                           boolean enableScriptSandbox) {
    this.siteContext = siteContext;
    this.scriptEngine = new GroovyScriptEngine(resourceConnector, parentClassLoader);
    this.scriptEngine.setConfig(getCompilerConfiguration(enableScriptSandbox));
    this.globalVariables = globalVariables;
}
 
Example #6
Source File: GroovyScriptFactory.java    From engine with GNU General Public License v3.0 5 votes vote down vote up
public GroovyScriptFactory(SiteContext siteContext, ResourceConnector resourceConnector,
                           Map<String, Object> globalVariables, boolean enableScriptSandbox) {
    this.siteContext = siteContext;
    this.scriptEngine = new GroovyScriptEngine(resourceConnector);
    this.scriptEngine.setConfig(getCompilerConfiguration(enableScriptSandbox));
    this.globalVariables = globalVariables;
}
 
Example #7
Source File: MyJointCompilationApp.java    From tutorials with MIT License 5 votes vote down vote up
public MyJointCompilationApp() {
    loader = new GroovyClassLoader(this.getClass().getClassLoader());
    shell = new GroovyShell(loader, new Binding());

    URL url = null;
    try {
        url = new File("src/main/groovy/com/baeldung/").toURI().toURL();
    } catch (MalformedURLException e) {
        LOG.error("Exception while creating url", e);
    }
    engine = new GroovyScriptEngine(new URL[] {url}, this.getClass().getClassLoader());
    engineFromFactory = new GroovyScriptEngineFactory().getScriptEngine();
}
 
Example #8
Source File: LibvirtKvmAgentHook.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public LibvirtKvmAgentHook(String path, String script, String method) throws IOException {
    this.script = script;
    this.method = method;
    File full_path = new File(path, script);
    if (!full_path.canRead()) {
        s_logger.warn("Groovy script '" + full_path.toString() + "' is not available. Transformations will not be applied.");
        this.gse = null;
    } else {
        this.gse = new GroovyScriptEngine(path);
    }
}
 
Example #9
Source File: ITestUtils.java    From pom-manipulation-ext with Apache License 2.0 5 votes vote down vote up
/**
 * Run runScript.groovy script in workingDir directory.
 *
 * @param workingDir - Directory with groovy script.
 * @param file - groovy script to run
 * @throws Exception if an error occurs
 */
private static void runScript( String workingDir, String file )
    throws Exception
{
    File verify = new File( workingDir + File.separator + file + ".groovy" );
    if ( !verify.isFile() )
    {
        return;
    }
    Binding binding = new Binding();
    binding.setVariable( "basedir", workingDir );
    GroovyScriptEngine engine = new GroovyScriptEngine( workingDir );
    engine.run( file + ".groovy", binding );
}
 
Example #10
Source File: ScriptingService.java    From vethrfolnir-mu with GNU General Public License v3.0 5 votes vote down vote up
public ScriptingService() {
	engine = new GroovyScriptEngine(getPackageURLs());
	
	try { // so bad
		ScriptEngineRoots = engine.getClass().getDeclaredField("roots");
		ScriptEngineRoots.setAccessible(true);
	}
	catch (Exception e) {
		log.warn("Failed getting Script engine roots field, new paths wont be added at runtime.", e);
	}
	
	log.info("Ready.");
}
 
Example #11
Source File: GroovyFacadeImpl.java    From zstack with Apache License 2.0 5 votes vote down vote up
@Override
public void executeScriptByPath(String scriptPath, Map<Object, Object> context) {
    try {
        String scriptName = PathUtil.fileName(scriptPath);
        String scriptDir = PathUtil.parentFolder(scriptPath);

        GroovyScriptEngine gse = new GroovyScriptEngine(scriptDir);
        Binding binding = new Binding(context);
        gse.run(scriptName, binding);
    } catch (Exception e) {
        throw new CloudRuntimeException(e);
    }
}
 
Example #12
Source File: GroovyTest.java    From phoenix.webui.framework with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception
	{
		Binding binding = new Binding();
		binding.setVariable("language", "Groovy");
		
		GroovyShell shell = new GroovyShell(binding);
		
		GroovyScriptEngine engine = new GroovyScriptEngine(new URL[]{GroovyTest.class.getClassLoader().getResource("/")});
		Script script = shell.parse(GroovyTest.class.getClassLoader().getResource("random.groovy").toURI());
		
//		System.out.println(script);
//		script.invokeMethod("new SuRenRandom()", null);
//		script.evaluate("new SuRenRandom()");
//		engine.run("random.groovy", binding);
		
		InputStream stream = GroovyTest.class.getClassLoader().getResource("random.groovy").openStream();
		StringBuffer buf = new StringBuffer();
		byte[] bf = new byte[1024];
		int len = -1;
		while((len = stream.read(bf)) != -1)
		{
			buf.append(new String(bf, 0, len));
		}
		buf.append("\n");
		
		for(int i = 0; i < 30; i++)
		{
			System.out.println(shell.evaluate(buf.toString() + "new SuRenRandom().randomPhoneNum()"));
			System.out.println(shell.evaluate(buf.toString() + "new SuRenRandom().randomEmail()"));
			System.out.println(shell.evaluate(buf.toString() + "new SuRenRandom().randomZipCode()"));
		}
	}
 
Example #13
Source File: GroovyDriverFactory.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Inject
public GroovyDriverFactory(
      GroovyScriptEngine engine,
      CapabilityRegistry registry,
      Set<GroovyDriverPlugin> plugins
) {
   this.engine = engine;
   this.registry = registry;
   this.plugins = IrisCollections.unmodifiableCopy(plugins);
}
 
Example #14
Source File: TestGroovyDriverRegistry.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Provides
@Singleton
public GroovyScriptEngine provideGroovyScriptEngine(TestDriverConfig driverConfig, CapabilityRegistry registry) throws MalformedURLException {
   File driverDir = new File(driverConfig.getDriverDirectory());
   GroovyScriptEngine engine = new GroovyScriptEngine(new URL[] {
         driverDir.toURI().toURL(),
         new File("src/main/resources").toURI().toURL()
   } );
   engine.getConfig().addCompilationCustomizers(new DriverCompilationCustomizer(registry));
   return engine;
}
 
Example #15
Source File: GroovyDriverTestCase.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Provides
@Singleton
public GroovyScriptEngine scriptEngine(Set<CompilationCustomizer> customizers) {
   GroovyScriptEngine engine = scriptEngine();
   for(CompilationCustomizer customizer: customizers) {
      engine.getConfig().addCompilationCustomizers(customizer);
   }
   engine.getConfig().setScriptExtensions(ImmutableSet.of("driver", "capability", "groovy"));
   return engine;
}
 
Example #16
Source File: TestZWaveSender.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
   Device device = Fixtures.createDevice();
   device.setAddress(driverAddress.getRepresentation());
   device.setProtocolAddress(protocolAddress.getRepresentation());
   DeviceDriver driver = EasyMock.createNiceMock(DeviceDriver.class);
   EasyMock.expect(driver.getDefinition()).andReturn(DeviceDriverDefinition.builder().withName("TestDriver").create()).anyTimes();
   EasyMock.expect(driver.getBaseAttributes()).andReturn(AttributeMap.emptyMap()).anyTimes();
   EasyMock.replay(driver);

   ServiceLocator.init(GuiceServiceLocator.create(
         Bootstrap
            .builder()
            .withModuleClasses(InMemoryMessageModule.class)
            .withModules(new AbstractIrisModule() {
               @Override
               protected void configure() {
                  bind(ZWaveContext.class);
               }
               @Provides
               public PersonDAO personDao() {
                  return EasyMock.createMock(PersonDAO.class);
               }
               @Provides
               public PersonPlaceAssocDAO personPlaceAssociationDao() {
                  return EasyMock.createNiceMock(PersonPlaceAssocDAO.class);
               }
            })
            .build()
            .bootstrap()
   ));
   bus = ServiceLocator.getInstance(InMemoryProtocolMessageBus.class);
   engine = new GroovyScriptEngine(new ClasspathResourceConnector(this.getClass()));
   context = new PlatformDeviceDriverContext(device, driver, mockPopulationCacheMgr);
   script = engine.createScript("TestZWaveSend.gscript", new Binding());
   script.run();
   script.setProperty("zwave", ServiceLocator.getInstance(ZWaveContext.class));

   GroovyContextObject.setContext(context);
}
 
Example #17
Source File: AbstractZWaveDriverTest.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
@Provides
public GroovyScriptEngine scriptEngine(CapabilityRegistry capabilityRegistry) {
    GroovyScriptEngine engine = new GroovyScriptEngine(new ClasspathResourceConnector());
    engine.getConfig().addCompilationCustomizers(new DriverCompilationCustomizer(capabilityRegistry));
    return engine;
}
 
Example #18
Source File: ScriptEngine.java    From MirServer-Netty with GNU General Public License v3.0 4 votes vote down vote up
public static synchronized void reload() throws Exception {
	engine = new GroovyScriptEngine(DEFUALT_SCRIPT_DIR);
	scriptInstance.clear();
}
 
Example #19
Source File: GroovyClassLoaderDeadlockTest.java    From groovy with Apache License 2.0 4 votes vote down vote up
public Runner(GroovyScriptEngine gse, String script, int count) {
    this.gse = gse;
    this.script = script;
    this.count = count;
}
 
Example #20
Source File: ScriptingService.java    From vethrfolnir-mu with GNU General Public License v3.0 4 votes vote down vote up
/**
 * @return the engine
 */
public GroovyScriptEngine getEngine() {
	return engine;
}
 
Example #21
Source File: GroovyDriverTestCase.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
protected GroovyScriptEngine scriptEngine() {
   return new GroovyScriptEngine(new ClasspathResourceConnector());
}
 
Example #22
Source File: TestIpcdSender.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Before
public void setUp() throws Exception {
   protocol = IpcdProtocol.INSTANCE;
   Device device = Fixtures.createDevice();
   device.setAddress(driverAddress.getRepresentation());
   device.setProtocolAddress(protocolAddress.getRepresentation());
   device.setProtocolAttributes(IpcdFixtures.createProtocolAttributes());
   DeviceDriver driver = EasyMock.createNiceMock(DeviceDriver.class);
   EasyMock.expect(driver.getDefinition()).andReturn(DeviceDriverDefinition.builder().withName("TestDriver").create()).anyTimes();
   EasyMock.expect(driver.getBaseAttributes()).andReturn(AttributeMap.emptyMap()).anyTimes();
   EasyMock.replay(driver);

   ServiceLocator.init(GuiceServiceLocator.create(
         Bootstrap.builder()
            .withModuleClasses(InMemoryMessageModule.class)
            .withModules(new AbstractIrisModule() {

               @Override
               protected void configure() {
                  bind(IpcdContext.class);
               }
               @Provides
               public PersonDAO personDao() {
                  return EasyMock.createNiceMock(PersonDAO.class);
               }
               @Provides
               public PersonPlaceAssocDAO personPlaceAssocDao() {
                  return EasyMock.createNiceMock(PersonPlaceAssocDAO.class);
               }

            }).build().bootstrap()
         ));
   bus = ServiceLocator.getInstance(InMemoryProtocolMessageBus.class);
   engine = new GroovyScriptEngine(new ClasspathResourceConnector(this.getClass()));
   context = new PlatformDeviceDriverContext(device, driver, mockPopulationCacheMgr);
   script = engine.createScript("TestIpcdSend.gscript", new Binding());
   script.run();
   script.setProperty("Ipcd", ServiceLocator.getInstance(IpcdContext.class));

   GroovyContextObject.setContext(context);
}
 
Example #23
Source File: TestGroovyDriverBindings.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
@Test
//   @Ignore
   public void testCompile() throws Exception {
      CapabilityRegistry registry = ServiceLocator.getInstance(CapabilityRegistry.class);

      CompilerConfiguration config = new CompilerConfiguration();
      config.setTargetDirectory(new File(TMP_DIR));
      config.addCompilationCustomizers(new DriverCompilationCustomizer(registry));
      org.codehaus.groovy.tools.Compiler compiler = new org.codehaus.groovy.tools.Compiler(config);
      compiler.compile(new File("src/test/resources/Metadata.driver"));
      ClassLoader loader = new ClassLoader() {

         @Override
         protected Class<?> findClass(String name) throws ClassNotFoundException {
            File f = new File(TMP_DIR + "/" + name.replaceAll("\\.", "/") + ".class");
            if(!f.exists()) {
               throw new ClassNotFoundException();
            }
            try (FileInputStream is = new FileInputStream(f)) {
               byte [] bytes = IOUtils.toByteArray(is);
               return defineClass(name, bytes, 0, bytes.length);
            }
            catch(Exception e) {
               throw new ClassNotFoundException("Unable to load " + name, e);
            }
         }

      };
      Class<?> metadataClass = loader.loadClass("Metadata");
      System.out.println(metadataClass);
      System.out.println("Superclass: " + metadataClass.getSuperclass());
      System.out.println("Interfaces: " + Arrays.asList(metadataClass.getInterfaces()));
      System.out.println("Methods: ");
      for(Method m: Arrays.asList(metadataClass.getMethods())) {
         System.out.println("\t" + m);
      }

      GroovyScriptEngine engine = new GroovyScriptEngine(new ClasspathResourceConnector());
      engine.setConfig(config);
      DriverBinding binding = new DriverBinding(
            ServiceLocator.getInstance(CapabilityRegistry.class),
            new GroovyDriverFactory(engine, registry, ImmutableSet.of(new ControlProtocolPlugin()))
      );
      Script s = (Script) metadataClass.getConstructor(Binding.class).newInstance(binding);
      s.setMetaClass(new DriverScriptMetaClass(s.getClass()));
      s.setBinding(binding);
      s.run();
      System.out.println("Definition: " + binding.getBuilder().createDefinition());
   }
 
Example #24
Source File: TestZigbeeSender.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Before
public void setUp() throws Exception {
   protocol = ZigbeeProtocol.INSTANCE;
   Device device = Fixtures.createDevice();
   device.setAddress(driverAddress.getRepresentation());
   device.setProtocolAddress(protocolAddress.getRepresentation());
   device.setProtocolAttributes(ZigbeeFixtures.createProtocolAttributes());
   DeviceDriver driver = EasyMock.createNiceMock(DeviceDriver.class);
   EasyMock.expect(driver.getDefinition()).andReturn(DeviceDriverDefinition.builder().withName("TestDriver").create()).anyTimes();
   EasyMock.expect(driver.getBaseAttributes()).andReturn(AttributeMap.emptyMap()).anyTimes();
   EasyMock.replay(driver);

   ServiceLocator.init(GuiceServiceLocator.create(
         Bootstrap
            .builder()
            .withModuleClasses(InMemoryMessageModule.class)
            .withModules(new AbstractIrisModule() {
               @Override
               protected void configure() {
                  bind(ZigbeeContext.class);
               }
               @Provides
               public PersonDAO personDao() {
                  return EasyMock.createMock(PersonDAO.class);
               }
               @Provides
               public PersonPlaceAssocDAO personPlaceAssocDao() {
                  return EasyMock.createMock(PersonPlaceAssocDAO.class);
               }
            })
            .build()
            .bootstrap()
   ));
   bus = ServiceLocator.getInstance(InMemoryProtocolMessageBus.class);
   engine = new GroovyScriptEngine(new ClasspathResourceConnector(this.getClass()));
   context = new PlatformDeviceDriverContext(device, driver, mockPopulationCacheMgr);
   script = engine.createScript("TestZigbeeSend.gscript", new Binding());
   script.run();
   script.setProperty("Zigbee", ServiceLocator.getInstance(ZigbeeContext.class));

   GroovyContextObject.setContext(context);
}
 
Example #25
Source File: AbstractDriverTestCase.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
@Inject
public void cacheScripts(GroovyScriptEngine engine) throws MalformedURLException {
    engine.getConfig().setRecompileGroovySource(false);
    engine.getConfig().setTargetDirectory("build/drivers");
}
 
Example #26
Source File: GroovyServlet.java    From groovy with Apache License 2.0 2 votes vote down vote up
/**
 * Hook method to setup the GroovyScriptEngine to use.<br>
 * Subclasses may override this method to provide a custom engine.
 */
protected GroovyScriptEngine createGroovyScriptEngine(){
    return new GroovyScriptEngine(this);
}