Search in sources :

Example 76 with MetaClass

use of groovy.lang.MetaClass in project groovity by disney.

the class Write method tag.

@SuppressWarnings({ "rawtypes", "resource" })
public Object tag(Map attributes, Closure body) throws Exception {
    boolean valueDeclared = attributes.containsKey(VALUE);
    Object value = null;
    if (valueDeclared) {
        value = resolve(attributes, VALUE);
        if (value == null) {
            value = resolve(attributes, "null");
        }
    }
    Object format = resolve(attributes, "format");
    Object escape = resolve(attributes, "escape");
    Object pretty = resolve(attributes, "pretty");
    if (pretty != null && !(pretty instanceof Boolean)) {
        pretty = Boolean.valueOf(pretty.toString());
    }
    Object to = resolve(attributes, "to");
    boolean returnTo = true;
    if (to == null) {
        returnTo = false;
        // fall back on body out
        to = get(body, OUT);
    }
    if (to == null) {
        throw new IllegalArgumentException("write tag requires valid Writer or String.class for 'to'");
    }
    Object filter = resolve(attributes, "filter");
    Writer writer;
    boolean returnString = false;
    if (to instanceof Writer) {
        writer = (Writer) to;
    } else if (to.equals(String.class) || to instanceof CharSequence) {
        writer = new CharArrayWriter();
        returnString = true;
    } else {
        throw new IllegalArgumentException("write tag requires valid Writer or String.class for 'to', unrecognized option " + to);
    }
    if (escape != null) {
        String esc = escape.toString();
        if (esc.equalsIgnoreCase("xml")) {
            writer = new XmlEscapingWriter(writer);
        } else if (esc.equalsIgnoreCase("json")) {
            writer = new JsonEscapingWriter(writer);
        } else if (esc.equalsIgnoreCase("html")) {
            writer = new HtmlEscapingWriter(writer);
        } else {
            throw new IllegalArgumentException("Unrecognized escape value " + esc + ", try xml or json");
        }
    }
    if (value == null) {
        Object oldOut = get(body, OUT);
        bind(body, OUT, writer);
        try {
            value = body.call();
        } finally {
            bind(body, OUT, oldOut);
        }
    }
    if (value != null) {
        if (format != null && !"json".equals(format) && !"xml".equals(format)) {
            // we don't want to close the formatter because it's not our job to close the writer
            Formatter formatter = new Formatter(writer);
            if (value instanceof Collection) {
                formatter.format(format.toString(), ((Collection) value).toArray());
            } else {
                formatter.format(format.toString(), value);
            }
        } else {
            if (value instanceof CharSequence) {
                writer.append((CharSequence) value);
            } else if ((filter == null) && (value instanceof Writable) && (value != body.getOwner())) {
                ((Writable) value).writeTo(writer);
            } else {
                ModelWalker mw;
                if (format == null) {
                    Object response = get(body, "response");
                    if (response != null) {
                        MetaClass mc = GroovySystem.getMetaClassRegistry().getMetaClass(response.getClass());
                        MetaProperty mp = mc.hasProperty(response, "contentType");
                        if (mp != null) {
                            String ct = (String) mp.getProperty(response);
                            if (ct != null && ct.contains("xml")) {
                                format = "xml";
                            }
                        }
                    }
                }
                if ("xml".equals(format)) {
                    if (pretty != null && ((Boolean) pretty).booleanValue()) {
                        mw = new ModelXmlWriter(writer, "\t");
                        // prevent secondary pretty, just write it pretty up front!
                        pretty = Boolean.FALSE;
                    } else {
                        mw = new ModelXmlWriter(writer);
                    }
                    String root = resolve(attributes, "root", String.class);
                    if (root != null) {
                        ((ModelXmlWriter) mw).setRootElementName(root);
                    }
                    @SuppressWarnings("unchecked") Map<String, String> prefixes = resolve(attributes, "namespaces", Map.class);
                    if (prefixes != null) {
                        ((ModelXmlWriter) mw).setNamespacePrefixes(prefixes);
                    }
                } else {
                    if (pretty != null && ((Boolean) pretty).booleanValue()) {
                        mw = new ModelJsonWriter(writer, "\t");
                        // prevent secondary pretty, just write it pretty up front!
                        pretty = Boolean.FALSE;
                    } else {
                        mw = new ModelJsonWriter(writer);
                    }
                }
                if (filter != null) {
                    ModelFilter[] mfa = null;
                    if (filter instanceof Collection) {
                        Collection src = (Collection) filter;
                        mfa = new ModelFilter[src.size()];
                        int pos = 0;
                        for (Object mf : src) {
                            mfa[pos++] = (ModelFilter) DefaultTypeTransformation.castToType(mf, ModelFilter.class);
                        }
                    } else if (filter.getClass().isArray() && filter.getClass().getComponentType().equals(ModelFilter.class)) {
                        mfa = (ModelFilter[]) filter;
                    } else if (filter instanceof ModelFilter) {
                        mfa = new ModelFilter[] { (ModelFilter) filter };
                    } else {
                        mfa = new ModelFilter[] { (ModelFilter) DefaultTypeTransformation.castToType(filter, ModelFilter.class) };
                    }
                    mw.setFilters(mfa);
                }
                mw.visit(value);
            }
        }
    }
    if (!returnTo) {
        return null;
    }
    Object rval = returnString ? writer.toString() : writer;
    if (attributes.get(VAR) != null) {
        bind(body, attributes.get(VAR).toString(), rval);
    }
    return rval;
}
Also used : ModelFilter(com.disney.groovity.model.ModelFilter) Formatter(java.util.Formatter) Writable(groovy.lang.Writable) ModelWalker(com.disney.groovity.model.ModelWalker) CharArrayWriter(java.io.CharArrayWriter) HtmlEscapingWriter(com.disney.groovity.util.HtmlEscapingWriter) MetaClass(groovy.lang.MetaClass) ModelXmlWriter(com.disney.groovity.model.ModelXmlWriter) Collection(java.util.Collection) XmlEscapingWriter(com.disney.groovity.util.XmlEscapingWriter) JsonEscapingWriter(com.disney.groovity.util.JsonEscapingWriter) ModelJsonWriter(com.disney.groovity.model.ModelJsonWriter) MetaProperty(groovy.lang.MetaProperty) Map(java.util.Map) CharArrayWriter(java.io.CharArrayWriter) JsonEscapingWriter(com.disney.groovity.util.JsonEscapingWriter) ModelJsonWriter(com.disney.groovity.model.ModelJsonWriter) Writer(java.io.Writer) ModelXmlWriter(com.disney.groovity.model.ModelXmlWriter) HtmlEscapingWriter(com.disney.groovity.util.HtmlEscapingWriter) XmlEscapingWriter(com.disney.groovity.util.XmlEscapingWriter)

Example 77 with MetaClass

use of groovy.lang.MetaClass in project groovity by disney.

the class ModelXmlWriter method visitObjectField.

public void visitObjectField(String name, Object value) throws Exception {
    if (inAttribute) {
        writer.write(" ");
        writer.write(name);
        writer.write("=\"");
        super.visitObjectField(name, value);
        writer.write("\"");
        return;
    }
    boolean writeTag = true;
    Object currentObject = getCurrentObject();
    MetaClass mc = GroovySystem.getMetaClassRegistry().getMetaClass(currentObject.getClass());
    MetaProperty mp = mc.hasProperty(currentObject, name);
    XmlAttribute xa = getAnnotation(mp, XmlAttribute.class);
    if (xa != null) {
        // attributes are written with open tag
        return;
    }
    String listElementName = null;
    if (value instanceof List || (value != null && value.getClass().isArray()) || (mp != null && (mp.getType().isArray() || List.class.isAssignableFrom(mp.getType())))) {
        writeTag = false;
        listElementName = name;
        Map<Class<?>, String> listTypedNames = NO_NAMES;
        XmlElementWrapper xew = getAnnotation(mp, XmlElementWrapper.class);
        if (xew != null) {
            writeTag = true;
            if (!"##default".equals(xew.name())) {
                name = xew.name();
            }
            name = getTagName(xew.namespace(), name);
        }
        XmlElement xe = getAnnotation(mp, XmlElement.class);
        if (xe != null) {
            if (!"##default".equals(xe.name())) {
                listElementName = xe.name();
            }
            listElementName = getTagName(xe.namespace(), listElementName);
        }
        if (xe == null) {
            XmlElements xes = getAnnotation(mp, XmlElements.class);
            if (xes != null) {
                listTypedNames = new HashMap<>();
                for (int i = 0; i < xes.value().length; i++) {
                    XmlElement e = xes.value()[i];
                    listTypedNames.put(e.type(), e.name());
                }
            }
        }
        XmlList xel = getAnnotation(mp, XmlList.class);
        if (xel != null) {
            writeTag = true;
            name = listElementName;
            value = transformField(mp, value);
        }
        XmlMixed xm = getAnnotation(mp, XmlMixed.class);
        if (xm != null) {
            listTypedNames = SKIP_TAG;
        }
        listElementNames.push(listElementName);
        listTypedElementNames.push(listTypedNames);
    } else {
        XmlElement xe = getAnnotation(mp, XmlElement.class);
        if (xe != null) {
            if (!"##default".equals(xe.name())) {
                name = xe.name();
            }
            name = getTagName(xe.namespace(), name);
        }
    }
    doDelimit = true;
    if (writeTag) {
        final String n = name;
        writeTag(name, value, o -> {
            try {
                super.visitObjectField(n, o);
            } catch (RuntimeException e) {
                throw e;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
    } else {
        super.visitObjectField(name, value);
    }
    if (listElementName != null) {
        listElementNames.pop();
        listTypedElementNames.pop();
    }
}
Also used : XmlAttribute(javax.xml.bind.annotation.XmlAttribute) XmlMixed(javax.xml.bind.annotation.XmlMixed) IOException(java.io.IOException) XmlList(javax.xml.bind.annotation.XmlList) XmlElements(javax.xml.bind.annotation.XmlElements) MetaClass(groovy.lang.MetaClass) XmlElement(javax.xml.bind.annotation.XmlElement) ArrayList(java.util.ArrayList) List(java.util.List) XmlList(javax.xml.bind.annotation.XmlList) MetaClass(groovy.lang.MetaClass) MetaProperty(groovy.lang.MetaProperty) XmlElementWrapper(javax.xml.bind.annotation.XmlElementWrapper)

Example 78 with MetaClass

use of groovy.lang.MetaClass in project groovity by disney.

the class MetaPropertyLookup method getSettableMetaProperty.

public static final MetaProperty getSettableMetaProperty(Object o, String name) {
    final Class<?> c = o.getClass();
    ConcurrentHashMap<String, MetaProperty> properties = singlePropertyCache.get(c);
    if (properties == null) {
        MetaClass mc = GroovySystem.getMetaClassRegistry().getMetaClass(c);
        List<MetaProperty> mps = mc.getProperties();
        properties = new ConcurrentHashMap<>();
        for (MetaProperty mp : mps) {
            if (mp instanceof MetaBeanProperty) {
                MetaBeanProperty mbp = ((MetaBeanProperty) mp);
                if (mbp.getSetter() == null) {
                    CachedField cf = mbp.getField();
                    if (cf == null || cf.isFinal() || cf.isStatic()) {
                        continue;
                    }
                }
            } else if (mp instanceof MethodMetaProperty) {
                continue;
            }
            properties.put(mp.getName(), mp);
        }
        singlePropertyCache.putIfAbsent(c, properties);
    }
    return properties.get(name);
}
Also used : MetaClass(groovy.lang.MetaClass) MetaBeanProperty(groovy.lang.MetaBeanProperty) MethodMetaProperty(org.codehaus.groovy.runtime.metaclass.MethodMetaProperty) MethodMetaProperty(org.codehaus.groovy.runtime.metaclass.MethodMetaProperty) MetaProperty(groovy.lang.MetaProperty) CachedField(org.codehaus.groovy.reflection.CachedField)

Example 79 with MetaClass

use of groovy.lang.MetaClass in project gremlin by tinkerpop.

the class GremlinGroovyScriptEngine method eval.

Object eval(final Class scriptClass, final ScriptContext context) throws ScriptException {
    this.checkClearCache();
    context.setAttribute("context", context, ScriptContext.ENGINE_SCOPE);
    java.io.Writer writer = context.getWriter();
    context.setAttribute("out", writer instanceof PrintWriter ? writer : new PrintWriter(writer), ScriptContext.ENGINE_SCOPE);
    Binding binding = new Binding() {

        public Object getVariable(String name) {
            synchronized (context) {
                int scope = context.getAttributesScope(name);
                if (scope != -1) {
                    return context.getAttribute(name, scope);
                }
                throw new MissingPropertyException(name, getClass());
            }
        }

        public void setVariable(String name, Object value) {
            synchronized (context) {
                int scope = context.getAttributesScope(name);
                if (scope == -1) {
                    scope = ScriptContext.ENGINE_SCOPE;
                }
                context.setAttribute(name, value, scope);
            }
        }
    };
    try {
        Script scriptObject = InvokerHelper.createScript(scriptClass, binding);
        Method[] methods = scriptClass.getMethods();
        Map<String, MethodClosure> closures = new HashMap<String, MethodClosure>();
        for (Method m : methods) {
            String name = m.getName();
            closures.put(name, new MethodClosure(scriptObject, name));
        }
        globalClosures.putAll(closures);
        final MetaClass oldMetaClass = scriptObject.getMetaClass();
        scriptObject.setMetaClass(new DelegatingMetaClass(oldMetaClass) {

            public Object invokeMethod(Object object, String name, Object args) {
                if (args == null) {
                    return invokeMethod(object, name, MetaClassHelper.EMPTY_ARRAY);
                } else if (args instanceof Tuple) {
                    return invokeMethod(object, name, ((Tuple) args).toArray());
                } else if (args instanceof Object[]) {
                    return invokeMethod(object, name, (Object[]) args);
                } else {
                    return invokeMethod(object, name, new Object[] { args });
                }
            }

            public Object invokeMethod(Object object, String name, Object[] args) {
                try {
                    return super.invokeMethod(object, name, args);
                } catch (MissingMethodException mme) {
                    return callGlobal(name, args, context);
                }
            }

            public Object invokeStaticMethod(Object object, String name, Object[] args) {
                try {
                    return super.invokeStaticMethod(object, name, args);
                } catch (MissingMethodException mme) {
                    return callGlobal(name, args, context);
                }
            }
        });
        return scriptObject.run();
    } catch (Exception e) {
        throw new ScriptException(e);
    }
}
Also used : Binding(groovy.lang.Binding) Script(groovy.lang.Script) CompiledScript(javax.script.CompiledScript) GroovyCompiledScript(org.codehaus.groovy.jsr223.GroovyCompiledScript) HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) MissingPropertyException(groovy.lang.MissingPropertyException) Method(java.lang.reflect.Method) MethodClosure(org.codehaus.groovy.runtime.MethodClosure) MissingPropertyException(groovy.lang.MissingPropertyException) ScriptException(javax.script.ScriptException) MissingMethodException(groovy.lang.MissingMethodException) IOException(java.io.IOException) CompilationFailedException(org.codehaus.groovy.control.CompilationFailedException) SyntaxException(org.codehaus.groovy.syntax.SyntaxException) ScriptException(javax.script.ScriptException) MissingMethodException(groovy.lang.MissingMethodException) MetaClass(groovy.lang.MetaClass) DelegatingMetaClass(groovy.lang.DelegatingMetaClass) DelegatingMetaClass(groovy.lang.DelegatingMetaClass) Tuple(groovy.lang.Tuple) PrintWriter(java.io.PrintWriter)

Example 80 with MetaClass

use of groovy.lang.MetaClass in project groovy by apache.

the class MetaClassRegistryImpl method setMetaClass.

/**
 * if oldMc is null, newMc will replace whatever meta class was used before.
 * if oldMc is not null, then newMc will be used only if the stored mc is
 * the same as oldMc
 */
private void setMetaClass(Class theClass, MetaClass oldMc, MetaClass newMc) {
    final ClassInfo info = ClassInfo.getClassInfo(theClass);
    MetaClass mc = null;
    info.lock();
    try {
        mc = info.getStrongMetaClass();
        info.setStrongMetaClass(newMc);
    } finally {
        info.unlock();
    }
    if ((oldMc == null && mc != newMc) || (oldMc != null && mc != newMc && mc != oldMc)) {
        fireConstantMetaClassUpdate(null, theClass, mc, newMc);
    }
}
Also used : ExpandoMetaClass(groovy.lang.ExpandoMetaClass) MetaClass(groovy.lang.MetaClass) ClassInfo(org.codehaus.groovy.reflection.ClassInfo)

Aggregations

MetaClass (groovy.lang.MetaClass)141 DelegatingMetaClass (groovy.lang.DelegatingMetaClass)62 GroovyObject (groovy.lang.GroovyObject)62 ExpandoMetaClass (groovy.lang.ExpandoMetaClass)40 MetaClassImpl (groovy.lang.MetaClassImpl)18 MetaProperty (groovy.lang.MetaProperty)12 GroovyRuntimeException (groovy.lang.GroovyRuntimeException)11 MetaMethod (groovy.lang.MetaMethod)11 ArrayList (java.util.ArrayList)11 MixinInMetaClass (org.codehaus.groovy.reflection.MixinInMetaClass)11 AdaptingMetaClass (groovy.lang.AdaptingMetaClass)9 MetaClassRegistry (groovy.lang.MetaClassRegistry)9 Map (java.util.Map)9 GString (groovy.lang.GString)7 CachedClass (org.codehaus.groovy.reflection.CachedClass)7 ClassInfo (org.codehaus.groovy.reflection.ClassInfo)7 MissingMethodException (groovy.lang.MissingMethodException)6 MissingPropertyException (groovy.lang.MissingPropertyException)6 IOException (java.io.IOException)6 Method (java.lang.reflect.Method)6