public void testDecoratedByApplicationConvention() throws Exception { GrailsWebRequest webRequest = buildMockRequest(); MockApplicationContext appCtx = (MockApplicationContext) webRequest.getApplicationContext(); appCtx.registerMockResource( "WEB-INF/grails-app/views/layouts/application.gsp", "<html><body><h1>Default Layout</h1><g:layoutBody /></body></html>"); MockHttpServletRequest request = new MockHttpServletRequest("GET", "orders/list"); ServletContext context = webRequest.getServletContext(); GroovyClassLoader gcl = new GroovyClassLoader(); // create mock controller GroovyObject controller = (GroovyObject) gcl.parseClass( "class FooController {\n" + "def controllerName = 'foo'\n" + "def actionUri = '/foo/fooAction'\n" + "}") .newInstance(); request.setAttribute(GrailsApplicationAttributes.CONTROLLER, controller); GrailsLayoutDecoratorMapper m = new GrailsLayoutDecoratorMapper(); Config c = new Config(new MockServletConfig(context)); m.init(c, null, null); HTMLPageParser parser = new HTMLPageParser(); String html = "<html><head><title>Foo title</title></head><body>here is the body</body></html>"; Page page = parser.parse(html.toCharArray()); Decorator d = m.getDecorator(request, page); assertNotNull(d); assertEquals("/WEB-INF/grails-app/views/layouts/application.gsp", d.getPage()); assertEquals("application", d.getName()); }
public void testInsertableUpdateableHibernateMapping() throws Exception { GroovyClassLoader cl = new GroovyClassLoader(); GrailsDomainClass domainClass = new DefaultGrailsDomainClass( cl.parseClass( "class TestInsertableUpdateableDomain {\n" + " Long id \n" + " Long version \n" + " String testString1 \n" + " String testString2 \n" + "\n" + " static mapping = {\n" + " testString1 insertable:false, updateable:false \n" + " testString2 updateable:false, insertable:false \n" + " }\n" + "}")); DefaultGrailsDomainConfiguration config = getDomainConfig(cl, new Class[] {domainClass.getClazz()}); PersistentClass persistentClass = config.getClassMapping("TestInsertableUpdateableDomain"); Property property1 = persistentClass.getProperty("testString1"); assertEquals(false, property1.isInsertable()); assertEquals(false, property1.isUpdateable()); Property property2 = persistentClass.getProperty("testString2"); assertEquals(false, property2.isUpdateable()); assertEquals(false, property2.isInsertable()); }
public static <T> T newInstance(String fileName) throws ScriptExecutionFailedException { GroovyObject groovyObject = null; try { File f = new File(fileName); if (!f.exists()) { f = new File( SubDirectory.SCRIPTS + File.separator + fileName + (fileName.endsWith(".groovy") ? "" : ".groovy")); } GroovyClassLoader loader = getGroovyClassLoader(); Class groovyClass = loader.parseClass(f); groovyObject = (GroovyObject) groovyClass.newInstance(); } catch (Exception e) { LOG.error(e, e); throw new ScriptExecutionFailedException(e); } try { return (T) groovyObject; } catch (ClassCastException e) { LOG.debug(e, e); throw new ScriptExecutionFailedException(e.getMessage(), e); } }
public void parse(String filterAsString) { String groovyString = "public class GroovyMatcher {\n" + "public org.jbehave.core.model.Meta meta\n" + " public boolean match() {\n" + " return (" + filterAsString.substring("groovy: ".length()) + ")\n" + " }\n" + " def propertyMissing(String name) {\n" + " if (!meta.hasProperty(name)) {\n" + " return false\n" + " }\n" + " def v = meta.getProperty(name)\n" + " if (v.equals('')) {\n" + " return true\n" + " }\n" + " return v\n" + " }\n" + "}"; GroovyClassLoader loader = new GroovyClassLoader(getClass().getClassLoader()); groovyClass = loader.parseClass(groovyString); try { match = groovyClass.getDeclaredMethod("match"); metaField = groovyClass.getField("meta"); } catch (NoSuchFieldException e) { // can never occur as we control the groovy string } catch (NoSuchMethodException e) { // can never occur as we control the groovy string } }
/** * Parse the template's (Groovy) script. The script must implement {@link IEmailDataScript}. * * @param keyVals * @return */ public Map<String, String> parseScript(Map<String, String> keyVals) { Map<String, String> resultMap = new HashMap<String, String>(); if (null == _script || "".equals(_script)) { return resultMap; } ClassLoader parent = getClass().getClassLoader(); GroovyClassLoader loader = new GroovyClassLoader(parent); Class<?> clazz = loader.parseClass(_script, "EmailDataScript"); IEmailDataScript scriptDelegate; try { scriptDelegate = (IEmailDataScript) clazz.newInstance(); resultMap = scriptDelegate.getEmailData((HashMap<String, String>) keyVals); if (MapUtils.isEmpty(resultMap)) { // This may not necessarily be an error for some parameter values. LOGGER.warn( "sendTemplateEmail no data returned from Groovy script for templateID: " + _templateId); } } catch (InstantiationException e) { LOGGER.error(DetailedException.getMessageOrType(e)); } catch (IllegalAccessException e) { LOGGER.error(DetailedException.getMessageOrType(e)); } catch (CompilationFailedException e) { LOGGER.error(DetailedException.getMessageOrType(e)); } return resultMap; }
public void testForeignKeyColumnBinding() { GroovyClassLoader cl = new GroovyClassLoader(); GrailsDomainClass oneClass = new DefaultGrailsDomainClass( cl.parseClass( "class TestOneSide {\n" + " Long id \n" + " Long version \n" + " String name \n" + " String description \n" + "}")); GrailsDomainClass domainClass = new DefaultGrailsDomainClass( cl.parseClass( "class TestManySide {\n" + " Long id \n" + " Long version \n" + " String name \n" + " TestOneSide testOneSide \n" + "\n" + " static mapping = {\n" + " columns {\n" + " testOneSide column:'EXPECTED_COLUMN_NAME'" + " }\n" + " }\n" + "}")); DefaultGrailsDomainConfiguration config = getDomainConfig(cl, new Class[] {oneClass.getClazz(), domainClass.getClazz()}); PersistentClass persistentClass = config.getClassMapping("TestManySide"); Column column = (Column) persistentClass.getProperty("testOneSide").getColumnIterator().next(); assertEquals("EXPECTED_COLUMN_NAME", column.getName()); }
public void initialise() throws InitialisationException { try { GroovyClassLoader loader = new GroovyClassLoader(getClass().getClassLoader()); // defaults to the logical name of the Transformer can be changed by explicit setting of the // scriptName if (script == null) { script = getName() + ".groovy"; } if (scriptLocation == null) { scriptLocation = loader.getResource(script); } if (scriptLocation == null) { File file = new File(script); if (file.exists()) { scriptLocation = file.toURL(); } else { throw new InitialisationException( new Message(Messages.CANT_LOAD_X_FROM_CLASSPATH_FILE, "Groovy Script: " + script), this); } } logger.info("Loading Groovy transformer with script " + scriptLocation.toExternalForm()); Class groovyClass = loader.parseClass(new GroovyCodeSource(scriptLocation)); transformer = (GroovyObject) groovyClass.newInstance(); } catch (Exception e) { throw new InitialisationException( new Message(Messages.FAILED_TO_CREATE_X, "Groovy transformer"), e, this); } }
/** * Clear the cube (and other internal caches) for a given ApplicationID. This will remove all the * n-cubes from memory, compiled Groovy code, caches related to expressions, caches related to * method support, advice caches, and local classes loaders (used when no sys.classpath is * present). * * @param appId ApplicationID for which the cache is to be cleared. */ public static void clearCache(ApplicationID appId) { synchronized (ncubeCache) { validateAppId(appId); Map<String, Object> appCache = getCacheForApp(appId); clearGroovyClassLoaderCache(appCache); appCache.clear(); GroovyBase.clearCache(appId); NCubeGroovyController.clearCache(appId); // Clear Advice cache Map<String, Advice> adviceCache = advices.get(appId); if (adviceCache != null) { adviceCache.clear(); } // Clear ClassLoader cache GroovyClassLoader classLoader = localClassLoaders.get(appId); if (classLoader != null) { classLoader.clearCache(); localClassLoaders.remove(appId); } } }
public void loadResource(final InputStream inputStream) throws ResourceInitializationException { ClassLoader parent = getClass().getClassLoader(); GroovyClassLoader groovyClassLoader = new GroovyClassLoader(parent); try { String scriptString = getScriptHeader(); StringWriter writer = new StringWriter(); IOUtils.copy(inputStream, writer); scriptString += "\n" + writer.toString(); scriptString += "\n" + getScriptFooter(); Class<?> groovyClass = groovyClassLoader.parseClass(scriptString); LOGGER.info("Loading groovy variant rules"); this.script = (GroovyObject) groovyClass.newInstance(); this.script.invokeMethod("init", new Object[] {}); initProfilingWithZeroCount(); LOGGER.info("Groovy variant rules loaded."); } catch (Exception e) { LOGGER.error("Could not load the groovy variant rules resource"); throw new ResourceInitializationException(e); } finally { try { groovyClassLoader.close(); } catch (IOException e) { LOGGER.warn("Could not close groovy class loader"); } } }
/** * Attempts to compile the given InputStream into a Groovy script using the given name * * @param in The InputStream to read the Groovy code from * @param name The name of the class to use * @param pageName The page name * @param metaInfo * @return The compiled java.lang.Class, which is an instance of groovy.lang.Script */ private Class<?> compileGroovyPage( InputStream in, String name, String pageName, GroovyPageMetaInfo metaInfo) { GroovyClassLoader groovyClassLoader = findOrInitGroovyClassLoader(); // Compile the script into an object Class<?> scriptClass; try { scriptClass = groovyClassLoader.parseClass(DefaultGroovyMethods.getText(in), name); } catch (CompilationFailedException e) { LOG.error("Compilation error compiling GSP [" + name + "]:" + e.getMessage(), e); int lineNumber = GrailsExceptionResolver.extractLineNumber(e); final int[] lineMappings = metaInfo.getLineNumbers(); if (lineNumber > 0 && lineNumber < lineMappings.length) { lineNumber = lineMappings[lineNumber - 1]; } throw new GroovyPagesException( "Could not parse script [" + name + "]: " + e.getMessage(), e, lineNumber, pageName); } catch (IOException e) { throw new GroovyPagesException( "IO exception parsing script [" + name + "]: " + e.getMessage(), e); } return scriptClass; }
public void testGenerateViews() throws Exception { GrailsTemplateGenerator generator; GroovyClassLoader gcl = new GroovyClassLoader(Thread.currentThread().getContextClassLoader()); generator = new DefaultGrailsTemplateGenerator(); Class dc = gcl.parseClass( "class Test { " + "\n Long id;" + "\n Long version;" + "\n String name;" + "\n TimeZone tz;" + "\n Locale locale;" + "\n Currency currency;" + "\n Boolean active;" + "\n Date age }"); GrailsDomainClass domainClass = new DefaultGrailsDomainClass(dc); generator.generateViews(domainClass, "test"); assertTrue(new File("test/grails-app/views/test/show.gsp").exists()); assertTrue(new File("test/grails-app/views/test/list.gsp").exists()); assertTrue(new File("test/grails-app/views/test/edit.gsp").exists()); assertTrue(new File("test/grails-app/views/test/create.gsp").exists()); }
public void testIsDomainClass() { GroovyClassLoader gcl = new GroovyClassLoader(); Class<?> c = gcl.parseClass("class Test { Long id;Long version;}\n"); ArtefactHandler handler = new DomainClassArtefactHandler(); assertTrue(handler.isArtefact(c)); }
private Class<?> createGroovyClass(String filename) throws CompilationFailedException, IOException { GroovyClassLoader gcl = new GroovyClassLoader(); String file = System.getProperty("opennms.home") + "/etc/selenium/" + filename; System.err.println("File name: " + file); return gcl.parseClass(new File(file)); }
/** * Called when one of the monitored files are created, deleted or modified. * * @param file File which has been changed. */ public void fileChanged(File file) throws IOException { try { GroovyClassLoader loader = new GroovyClassLoader(getClass().getClassLoader()); Class groovyClass = loader.parseClass(new GroovyCodeSource(file)); component = (GroovyObject) groovyClass.newInstance(); } catch (Exception e) { throw new IOException("Failed to reload groovy script: " + e.getMessage()); } }
@Override public void close() { loader.clearCache(); try { loader.close(); } catch (IOException e) { logger.warn("Unable to close Groovy loader", e); } }
public void testDefaultNamingStrategy() { GroovyClassLoader cl = new GroovyClassLoader(); GrailsDomainClass oneClass = new DefaultGrailsDomainClass( cl.parseClass( "class TestOneSide {\n" + " Long id \n" + " Long version \n" + " String fooName \n" + " String barDescriPtion \n" + "}")); GrailsDomainClass domainClass = new DefaultGrailsDomainClass( cl.parseClass( "class TestManySide {\n" + " Long id \n" + " Long version \n" + " TestOneSide testOneSide \n" + "\n" + " static mapping = {\n" + " columns {\n" + " testOneSide column:'EXPECTED_COLUMN_NAME'" + " }\n" + " }\n" + "}")); DefaultGrailsDomainConfiguration config = getDomainConfig(cl, new Class[] {oneClass.getClazz(), domainClass.getClazz()}); PersistentClass persistentClass = config.getClassMapping("TestOneSide"); assertEquals("test_one_side", persistentClass.getTable().getName()); Column column = (Column) persistentClass.getProperty("id").getColumnIterator().next(); assertEquals("id", column.getName()); column = (Column) persistentClass.getProperty("version").getColumnIterator().next(); assertEquals("version", column.getName()); column = (Column) persistentClass.getProperty("fooName").getColumnIterator().next(); assertEquals("foo_name", column.getName()); column = (Column) persistentClass.getProperty("barDescriPtion").getColumnIterator().next(); assertEquals("bar_descri_ption", column.getName()); persistentClass = config.getClassMapping("TestManySide"); assertEquals("test_many_side", persistentClass.getTable().getName()); column = (Column) persistentClass.getProperty("id").getColumnIterator().next(); assertEquals("id", column.getName()); column = (Column) persistentClass.getProperty("version").getColumnIterator().next(); assertEquals("version", column.getName()); column = (Column) persistentClass.getProperty("testOneSide").getColumnIterator().next(); assertEquals("EXPECTED_COLUMN_NAME", column.getName()); }
protected GroovyClassLoader buildClassLoaderFor() { // GROOVY-5044 if (!fork && !getIncludeantruntime()) { throw new IllegalArgumentException( "The includeAntRuntime=false option is not compatible with fork=false"); } ClassLoader parent = getIncludeantruntime() ? getClass().getClassLoader() : new AntClassLoader( new RootLoader(EMPTY_URL_ARRAY, null), getProject(), getClasspath()); if (parent instanceof AntClassLoader) { AntClassLoader antLoader = (AntClassLoader) parent; String[] pathElm = antLoader.getClasspath().split(File.pathSeparator); List<String> classpath = configuration.getClasspath(); /* * Iterate over the classpath provided to groovyc, and add any missing path * entries to the AntClassLoader. This is a workaround, since for some reason * 'directory' classpath entries were not added to the AntClassLoader' classpath. */ for (String cpEntry : classpath) { boolean found = false; for (String path : pathElm) { if (cpEntry.equals(path)) { found = true; break; } } /* * fix for GROOVY-2284 * seems like AntClassLoader doesn't check if the file * may not exist in the classpath yet */ if (!found && new File(cpEntry).exists()) { try { antLoader.addPathElement(cpEntry); } catch (BuildException e) { log.warn("The classpath entry " + cpEntry + " is not a valid Java resource"); } } } } GroovyClassLoader loader = new GroovyClassLoader(parent, configuration); if (!forceLookupUnnamedFiles) { // in normal case we don't need to do script lookups loader.setResourceLoader( new GroovyResourceLoader() { public URL loadGroovySource(String filename) throws MalformedURLException { return null; } }); } return loader; }
private static GroovyClassLoader getGroovyClassLoader() { GroovySystem.getMetaClassRegistry() .setMetaClassCreationHandle(new ExpandoMetaClassCreationHandle()); CompilerConfiguration config = new CompilerConfiguration(); config.setDebug(true); config.setVerbose(true); ClassLoader parent = ClassLoader.getSystemClassLoader(); GroovyClassLoader loader = new GroovyClassLoader(parent); loader.setShouldRecompile(true); return loader; }
/** * Creates a new instance of PolicyEnforcementLayer. * * @param upperLayer The upper layer (normally Tuple Space layer) * @param policy The policy to be enforced * @throws DepSpaceException If policy enforcer can not be instantiated */ @SuppressWarnings("rawtypes") public PolicyEnforcementLayer(DepSpaceServer upperLayer, String policy) throws DepSpaceException { this.upperLayer = upperLayer; GroovyClassLoader classLoader; classLoader = new GroovyClassLoader(getClass().getClassLoader()); try { Class policyClass = classLoader.parseClass(policy); this.policyEnforcer = (PolicyEnforcer) policyClass.newInstance(); this.policyEnforcer.setLayer(this); } catch (Exception e) { throw new DepSpaceException("Cannot instantiate policy enforcer: " + e); } }
/** * Parses the groovy script into a class. We store the Class instead of the script proper so that * it doesn't invoke race conditions on multiple executions of the script. */ private void createGroovyClass() { try { GroovyClassLoader loader = new GroovyClassLoader(getClassLoader()); InputStream scriptIs = getScriptInputStream(); GroovyCodeSource groovyCodeSource = new GroovyCodeSource(scriptIs, "nanocontainer.groovy", "groovyGeneratedForNanoContainer"); scriptClass = loader.parseClass(groovyCodeSource); } catch (CompilationFailedException e) { throw new GroovyCompilationException("Compilation Failed '" + e.getMessage() + "'", e); } catch (IOException e) { throw new NanoContainerMarkupException(e); } }
@Override public void doExecute(TestContext context) { try { ClassLoader parent = getClass().getClassLoader(); GroovyClassLoader loader = new GroovyClassLoader(parent); assertScriptProvided(); String rawCode = StringUtils.hasText(script) ? script.trim() : FileUtils.readToString(FileUtils.getFileResource(scriptResourcePath, context)); String code = context.replaceDynamicContentInString(rawCode.trim()); // load groovy code Class<?> groovyClass = loader.parseClass(code); // Instantiate an object from groovy code GroovyObject groovyObject = (GroovyObject) groovyClass.newInstance(); // only apply default script template in case we have feature enabled and code is not a class, // too if (useScriptTemplate && groovyObject.getClass().getSimpleName().startsWith("script")) { // build new script with surrounding template code = TemplateBasedScriptBuilder.fromTemplateResource( FileUtils.getFileResource(scriptTemplatePath, context)) .withCode(code) .build(); groovyClass = loader.parseClass(code); groovyObject = (GroovyObject) groovyClass.newInstance(); } if (log.isDebugEnabled()) { log.debug("Executing Groovy script:\n" + code); } // execute the Groovy script if (groovyObject instanceof ScriptExecutor) { ((ScriptExecutor) groovyObject).execute(context); } else { groovyObject.invokeMethod("run", new Object[] {}); } log.info("Groovy script execution successfully"); } catch (CitrusRuntimeException e) { throw e; } catch (Exception e) { throw new CitrusRuntimeException(e); } }
/* (non-Javadoc) * @see org.codehaus.groovy.grails.plugins.AbstractGrailsPlugin#refresh() */ @Override public void refresh() { // do nothing Resource descriptor = getDescriptor(); if (application != null && descriptor != null) { ClassLoader parent = application.getClassLoader(); GroovyClassLoader gcl = new GroovyClassLoader(parent); try { initialisePlugin(gcl.parseClass(descriptor.getFile())); } catch (Exception e) { LOG.error("Error refreshing plugin: " + e.getMessage(), e); } } }
/** Test that static constraints work */ @SuppressWarnings("rawtypes") public void testNullableConstraint() throws Exception { String bookClassSource = "package org.codehaus.groovy.grails.validation\n" + "class Book {\n" + " Long id\n" + " Long version\n" + " String title\n" + " String description\n" + " Author author\n" + " Author assistent\n" + " Set chapters\n" + " Map remarks\n" + " static hasMany = [chapters:Chapter]\n" + " static constraints = {\n" + " description(nullable: true)\n" + " assistent(nullable: true)\n" + " }\n" + "}\n" + "class Author {\n" + " Long id\n" + " Long version\n" + " String name\n" + "}\n" + "class Chapter {\n" + " Long id\n" + " Long version\n" + " String text\n" + "}"; GroovyClassLoader gcl = new GroovyClassLoader(); DefaultGrailsDomainClass bookClass = new DefaultGrailsDomainClass(gcl.parseClass(bookClassSource, "Book")); Map constraints = bookClass.getConstrainedProperties(); Constrained p = (Constrained) constraints.get("title"); assertFalse("Title property should be required", p.isNullable()); p = (Constrained) constraints.get("description"); assertTrue("Description property should be optional", p.isNullable()); p = (Constrained) constraints.get("author"); assertFalse("Author property should be required", p.isNullable()); p = (Constrained) constraints.get("assistent"); assertTrue("Assistent property should be optional", p.isNullable()); // Test that Collections and Maps are nullable by default p = (Constrained) constraints.get("chapters"); assertTrue("Chapters property should be optional", p.isNullable()); p = (Constrained) constraints.get("remarks"); assertTrue("Remarks property should be optional", p.isNullable()); }
public void testDomainClassBinding() { GroovyClassLoader cl = new GroovyClassLoader(); GrailsDomainClass domainClass = new DefaultGrailsDomainClass( cl.parseClass( "public class BinderTestClass {\n" + " Long id; \n" + " Long version; \n" + "\n" + " String firstName; \n" + " String lastName; \n" + " String comment; \n" + " Integer age;\n" + " boolean active = true" + "\n" + " static constraints = {\n" + " firstName(nullable:true,size:4..15)\n" + " lastName(nullable:false)\n" + " age(nullable:true)\n" + " }\n" + "}")); DefaultGrailsDomainConfiguration config = getDomainConfig(cl, cl.getLoadedClasses()); // Test database mappings PersistentClass persistentClass = config.getClassMapping("BinderTestClass"); assertTrue( "Property [firstName] must be optional in db mapping", persistentClass.getProperty("firstName").isOptional()); assertFalse( "Property [lastName] must be required in db mapping", persistentClass.getProperty("lastName").isOptional()); // Property must be required by default assertFalse( "Property [comment] must be required in db mapping", persistentClass.getProperty("comment").isOptional()); // Test properties assertTrue( "Property [firstName] must be optional", domainClass.getPropertyByName("firstName").isOptional()); assertFalse( "Property [lastName] must be optional", domainClass.getPropertyByName("lastName").isOptional()); assertFalse( "Property [comment] must be required", domainClass.getPropertyByName("comment").isOptional()); assertTrue( "Property [age] must be optional", domainClass.getPropertyByName("age").isOptional()); }
public Class loadClass( String name, boolean lookupScriptFiles, boolean preferClassOverScript, boolean resolve) throws ClassNotFoundException, CompilationFailedException { Class c = findLoadedClass(name); if (c != null) return c; return delegate.loadClass(name, lookupScriptFiles, preferClassOverScript, resolve); }
private void loadRegisteredScriptExtensions() { if (scriptExtensions.isEmpty()) { scriptExtensions.add( getScriptExtension() .substring(2)); // first extension will be the one set explicitly on <groovyc> Path classpath = getClasspath() != null ? getClasspath() : new Path(getProject()); final String[] pe = classpath.list(); final GroovyClassLoader loader = new GroovyClassLoader(getClass().getClassLoader()); for (String file : pe) { loader.addClasspath(file); } scriptExtensions.addAll(SourceExtensionHandler.getRegisteredExtensions(loader)); } }
public void testGenerateController() throws Exception { GrailsTemplateGenerator generator; GroovyClassLoader gcl = new GroovyClassLoader(Thread.currentThread().getContextClassLoader()); generator = new DefaultGrailsTemplateGenerator(); Class dc = gcl.parseClass("class Test { \n Long id;\n Long version; }"); GrailsDomainClass domainClass = new DefaultGrailsDomainClass(dc); File generatedFile = new File("test/grails-app/controllers/TestController.groovy"); if (generatedFile.exists()) { generatedFile.delete(); } StringWriter sw = new StringWriter(); generator.generateController(domainClass, sw); String text = sw.toString(); Class controllerClass = gcl.parseClass(text); BeanWrapper bean = new BeanWrapperImpl(controllerClass.newInstance()); assertEquals("TestController", controllerClass.getName()); assertTrue(bean.isReadableProperty("list")); assertTrue(bean.isReadableProperty("update")); assertTrue(bean.isReadableProperty("create")); assertTrue(bean.isReadableProperty("list")); assertTrue(bean.isReadableProperty("show")); assertTrue(bean.isReadableProperty("edit")); assertTrue(bean.isReadableProperty("delete")); Object propertyValue = GrailsClassUtils.getStaticPropertyValue(controllerClass, "allowedMethods"); assertTrue("allowedMethods property was the wrong type", propertyValue instanceof Map); Map map = (Map) propertyValue; assertTrue("allowedMethods did not contain the delete action", map.containsKey("delete")); assertTrue("allowedMethods did not contain the save action", map.containsKey("save")); assertTrue("allowedMethods did not contain the update action", map.containsKey("update")); assertEquals("allowedMethods had incorrect value for delete action", "POST", map.get("delete")); assertEquals("allowedMethods had incorrect value for save action", "POST", map.get("save")); assertEquals("allowedMethods had incorrect value for update action", "POST", map.get("update")); }
protected void addGrailsBuildListener(String listenerClassName) { Class<?> listenerClass; try { listenerClass = classLoader.loadClass(listenerClassName); } catch (ClassNotFoundException e) { throw new RuntimeException("Could not load grails build listener class", e); } addGrailsBuildListener(listenerClass); }
@SuppressWarnings("rawtypes") private void ensureConstraintsPresent( String[] classSource, int classIndexToTest, int constraintCount) throws Exception { // We need to do a real test here to make sure GroovyClassLoader gcl = new GroovyClassLoader(); Class[] classes = new Class[classSource.length]; for (int i = 0; i < classSource.length; i++) { classes[i] = gcl.parseClass(classSource[i]); } DefaultGrailsDomainClass domainClass = new DefaultGrailsDomainClass(classes[classIndexToTest]); Map constraints = domainClass.getConstrainedProperties(); ConstrainedProperty p = (ConstrainedProperty) constraints.get("name"); Collection cons = p.getAppliedConstraints(); assertEquals( "Incorrect number of constraints extracted: " + constraints, constraintCount, cons.size()); }
@SuppressWarnings({"rawtypes"}) public Response createCatalogEntryFromGroovyCode(String groovyCode) { ClassLoader parent = getCatalog().getRootClassLoader(); GroovyClassLoader loader = new GroovyClassLoader(parent); Class clazz = loader.parseClass(groovyCode); if (AbstractEntity.class.isAssignableFrom(clazz)) { CatalogItem<?> item = getCatalog().addItem(clazz); log.info("REST created " + item); return Response.created(URI.create("entities/" + clazz.getName())).build(); } else if (AbstractPolicy.class.isAssignableFrom(clazz)) { CatalogItem<?> item = getCatalog().addItem(clazz); log.info("REST created " + item); return Response.created(URI.create("policies/" + clazz.getName())).build(); } throw WebResourceUtils.preconditionFailed( "Unsupported type superclass " + clazz.getSuperclass() + "; expects Entity or Policy"); }