Search in sources :

Example 81 with GroovyObject

use of groovy.lang.GroovyObject in project cas by apereo.

the class InternalGroovyScriptDao method getAttributesForUser.

@Override
public Map<String, Object> getAttributesForUser(final String uid) {
    final Map<String, Object> finalAttributes = new HashedMap();
    casProperties.getAuthn().getAttributeRepository().getGroovy().forEach(groovy -> {
        final ClassLoader parent = getClass().getClassLoader();
        try (GroovyClassLoader loader = new GroovyClassLoader(parent)) {
            if (groovy.getConfig().getLocation() != null) {
                final File groovyFile = groovy.getConfig().getLocation().getFile();
                if (groovyFile.exists()) {
                    final Class<?> groovyClass = loader.parseClass(groovyFile);
                    LOGGER.debug("Loaded groovy class [{}] from script [{}]", groovyClass.getSimpleName(), groovyFile.getCanonicalPath());
                    final GroovyObject groovyObject = (GroovyObject) groovyClass.newInstance();
                    LOGGER.debug("Created groovy object instance from class [{}]", groovyFile.getCanonicalPath());
                    final Object[] args = { uid, LOGGER, casProperties, applicationContext };
                    LOGGER.debug("Executing groovy script's run method, with parameters [{}]", args);
                    final Map<String, Object> personAttributesMap = (Map<String, Object>) groovyObject.invokeMethod("run", args);
                    LOGGER.debug("Creating person attributes with the username [{}] and attributes [{}]", uid, personAttributesMap);
                    finalAttributes.putAll(personAttributesMap);
                }
            }
        } catch (final Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
    });
    return finalAttributes;
}
Also used : GroovyClassLoader(groovy.lang.GroovyClassLoader) GroovyClassLoader(groovy.lang.GroovyClassLoader) GroovyObject(groovy.lang.GroovyObject) HashedMap(org.apache.commons.collections.map.HashedMap) File(java.io.File) HashMap(java.util.HashMap) HashedMap(org.apache.commons.collections.map.HashedMap) Map(java.util.Map) GroovyObject(groovy.lang.GroovyObject)

Example 82 with GroovyObject

use of groovy.lang.GroovyObject in project cas by apereo.

the class GroovyScriptAttributeReleasePolicy method getAttributesInternal.

@Override
protected Map<String, Object> getAttributesInternal(final Map<String, Object> attributes, final RegisteredService service) {
    final ClassLoader parent = getClass().getClassLoader();
    try (GroovyClassLoader loader = new GroovyClassLoader(parent)) {
        final File groovyFile = ResourceUtils.getResourceFrom(this.groovyScript).getFile();
        if (groovyFile.exists()) {
            final Class<?> groovyClass = loader.parseClass(groovyFile);
            final GroovyObject groovyObject = (GroovyObject) groovyClass.newInstance();
            LOGGER.debug("Created groovy object instance from class [{}]", groovyFile.getCanonicalPath());
            final Object[] args = { attributes, LOGGER };
            LOGGER.debug("Executing groovy script's run method, with parameters [{}]", args);
            final Map<String, Object> personAttributesMap = (Map<String, Object>) groovyObject.invokeMethod("run", args);
            LOGGER.debug("Final set of attributes determined by the script are [{}]", personAttributesMap);
            return personAttributesMap;
        }
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
    LOGGER.warn("Groovy script [{}] does not exist, or cannot be loaded", groovyScript);
    return new HashMap<>();
}
Also used : GroovyClassLoader(groovy.lang.GroovyClassLoader) HashMap(java.util.HashMap) GroovyClassLoader(groovy.lang.GroovyClassLoader) GroovyObject(groovy.lang.GroovyObject) File(java.io.File) Map(java.util.Map) HashMap(java.util.HashMap) GroovyObject(groovy.lang.GroovyObject)

Example 83 with GroovyObject

use of groovy.lang.GroovyObject in project grails-core by grails.

the class LazyTagLibraryLookup method lookupTagLibrary.

@Override
public GroovyObject lookupTagLibrary(String namespace, String tagName) {
    GroovyObject tagLibrary = super.lookupTagLibrary(namespace, tagName);
    if (tagLibrary == null) {
        String tagKey = tagNameKey(namespace, tagName);
        GrailsTagLibClass taglibClass = lazyLoadableTagLibs.get(tagKey);
        if (taglibClass != null) {
            if (!applicationContext.containsBean(taglibClass.getFullName())) {
                GenericBeanDefinition bd = new GenericBeanDefinition();
                bd.setBeanClass(taglibClass.getClazz());
                bd.setAutowireCandidate(true);
                bd.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_NAME);
                ((GenericApplicationContext) applicationContext).getDefaultListableBeanFactory().registerBeanDefinition(taglibClass.getFullName(), bd);
            }
            registerTagLib(taglibClass);
            tagLibrary = super.lookupTagLibrary(namespace, tagName);
        }
    }
    return tagLibrary;
}
Also used : GenericBeanDefinition(org.springframework.beans.factory.support.GenericBeanDefinition) GroovyObject(groovy.lang.GroovyObject) GrailsTagLibClass(grails.core.GrailsTagLibClass) DefaultGrailsTagLibClass(org.grails.core.DefaultGrailsTagLibClass)

Example 84 with GroovyObject

use of groovy.lang.GroovyObject in project grails-core by grails.

the class TagOutput method captureTagOutput.

@SuppressWarnings("rawtypes")
public static final Object captureTagOutput(TagLibraryLookup gspTagLibraryLookup, String namespace, String tagName, Map attrs, Object body, OutputContext outputContext) {
    GroovyObject tagLib = lookupCachedTagLib(gspTagLibraryLookup, namespace, tagName);
    if (tagLib == null) {
        throw new GrailsTagException("Tag [" + tagName + "] does not exist. No corresponding tag library found.");
    }
    if (!(attrs instanceof GroovyPageAttributes)) {
        attrs = new GroovyPageAttributes(attrs, false);
    }
    ((GroovyPageAttributes) attrs).setGspTagSyntaxCall(false);
    Closure actualBody = createOutputCapturingClosure(tagLib, body, outputContext);
    final GroovyPageTagWriter tagOutput = new GroovyPageTagWriter();
    OutputEncodingStack outputStack = null;
    try {
        outputStack = OutputEncodingStack.currentStack(outputContext, false);
        if (outputStack == null) {
            outputStack = OutputEncodingStack.currentStack(outputContext, true, tagOutput, true, true);
        }
        Map<String, Object> defaultEncodeAs = gspTagLibraryLookup.getEncodeAsForTag(namespace, tagName);
        Map<String, Object> codecSettings = createCodecSettings(namespace, tagName, attrs, defaultEncodeAs);
        OutputEncodingStackAttributes.Builder builder = WithCodecHelper.createOutputStackAttributesBuilder(codecSettings, outputContext.getGrailsApplication());
        builder.topWriter(tagOutput);
        outputStack.push(builder.build());
        // retrieve tag lib and create wrapper writer
        Object tagLibProp = tagLib.getProperty(tagName);
        if (tagLibProp instanceof Closure) {
            Closure tag = (Closure) ((Closure) tagLibProp).clone();
            Object bodyResult;
            switch(tag.getParameterTypes().length) {
                case 1:
                    bodyResult = tag.call(new Object[] { attrs });
                    if (actualBody != null && actualBody != EMPTY_BODY_CLOSURE) {
                        Object bodyResult2 = actualBody.call();
                        if (bodyResult2 != null) {
                            if (actualBody instanceof ConstantClosure) {
                                outputStack.getStaticWriter().print(bodyResult2);
                            } else {
                                outputStack.getTaglibWriter().print(bodyResult2);
                            }
                        }
                    }
                    break;
                case 2:
                    bodyResult = tag.call(new Object[] { attrs, actualBody });
                    break;
                default:
                    throw new GrailsTagException("Tag [" + tagName + "] does not specify expected number of params in tag library [" + tagLib.getClass().getName() + "]");
            }
            Encoder taglibEncoder = outputStack.getTaglibEncoder();
            boolean returnsObject = gspTagLibraryLookup.doesTagReturnObject(namespace, tagName);
            if (returnsObject && bodyResult != null && !(bodyResult instanceof Writer)) {
                if (taglibEncoder != null) {
                    bodyResult = taglibEncoder.encode(bodyResult);
                }
                return bodyResult;
            }
            // add some method to always return string, configurable?
            if (taglibEncoder != null) {
                return taglibEncoder.encode(tagOutput.getBuffer());
            } else {
                return tagOutput.getBuffer();
            }
        }
        throw new GrailsTagException("Tag [" + tagName + "] does not exist in tag library [" + tagLib.getClass().getName() + "]");
    } finally {
        if (outputStack != null)
            outputStack.pop();
    }
}
Also used : Closure(groovy.lang.Closure) GroovyObject(groovy.lang.GroovyObject) Encoder(org.grails.encoder.Encoder) OutputEncodingStackAttributes(org.grails.taglib.encoder.OutputEncodingStackAttributes) GroovyObject(groovy.lang.GroovyObject) OutputEncodingStack(org.grails.taglib.encoder.OutputEncodingStack) Writer(java.io.Writer)

Example 85 with GroovyObject

use of groovy.lang.GroovyObject in project groovy-core by groovy.

the class ProxyGeneratorAdapter method proxy.

@SuppressWarnings("unchecked")
public GroovyObject proxy(Map<Object, Object> map, Object... constructorArgs) {
    if (constructorArgs == null && cachedNoArgConstructor != null) {
        // if there isn't any argument, we can make invocation faster using the cached constructor
        try {
            return (GroovyObject) cachedNoArgConstructor.newInstance(map);
        } catch (InstantiationException e) {
            throw new GroovyRuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new GroovyRuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new GroovyRuntimeException(e);
        }
    }
    if (constructorArgs == null)
        constructorArgs = EMPTY_ARGS;
    Object[] values = new Object[constructorArgs.length + 1];
    System.arraycopy(constructorArgs, 0, values, 0, constructorArgs.length);
    values[values.length - 1] = map;
    return DefaultGroovyMethods.<GroovyObject>newInstance(cachedClass, values);
}
Also used : GroovyRuntimeException(groovy.lang.GroovyRuntimeException) GroovyObject(groovy.lang.GroovyObject) InvocationTargetException(java.lang.reflect.InvocationTargetException) GroovyObject(groovy.lang.GroovyObject)

Aggregations

GroovyObject (groovy.lang.GroovyObject)142 GroovyClassLoader (groovy.lang.GroovyClassLoader)15 Closure (groovy.lang.Closure)11 File (java.io.File)8 Map (java.util.Map)8 Decorator (com.opensymphony.module.sitemesh.Decorator)7 GroovyRuntimeException (groovy.lang.GroovyRuntimeException)7 MetaClass (groovy.lang.MetaClass)7 HashMap (java.util.HashMap)7 GrailsWebRequest (org.grails.web.servlet.mvc.GrailsWebRequest)7 Page (com.opensymphony.module.sitemesh.Page)5 HTMLPageParser (com.opensymphony.module.sitemesh.parser.HTMLPageParser)5 Config (grails.config.Config)5 InvocationTargetException (java.lang.reflect.InvocationTargetException)5 ServletContext (javax.servlet.ServletContext)5 PropertySourcesConfig (org.grails.config.PropertySourcesConfig)5 MockApplicationContext (org.grails.support.MockApplicationContext)5 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)5 MockServletConfig (org.springframework.mock.web.MockServletConfig)5 ArrayList (java.util.ArrayList)4