Search in sources :

Example 6 with MetaClass

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

the class Parse method parse.

@SuppressWarnings({ "rawtypes", "unchecked" })
public static Object parse(Object value, String format, final Object target) throws Exception {
    Reader reader = null;
    Object result = target;
    if (value instanceof Reader) {
        reader = ((Reader) value);
    } else if (value instanceof InputStream) {
        reader = new BufferedReader(new InputStreamReader((InputStream) value, "UTF-8"));
    } else if (value instanceof File) {
        reader = new FileReader((File) value);
    } else if (value instanceof byte[]) {
        String str = new String(((byte[]) value), "UTF-8").trim();
        reader = new StringReader(str);
        if (format == null) {
            if (str.startsWith("<")) {
                format = "xml";
            }
        }
    } else if (value instanceof HttpResponse) {
        HttpResponse response = (HttpResponse) value;
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            org.apache.http.Header ct = entity.getContentType();
            String charset = "UTF-8";
            if (ct != null) {
                String contentType = ct.getValue();
                Matcher charMatcher = charsetPattern.matcher(contentType);
                if (charMatcher.find()) {
                    charset = charMatcher.group(1);
                }
                if (format == null) {
                    if (contentType.contains("xml")) {
                        format = "xml";
                    }
                }
            }
            reader = new BufferedReader(new InputStreamReader(entity.getContent(), charset));
        }
    } else if (value instanceof Map) {
        if (target.equals(Object.class)) {
            result = Model.copy(value);
        } else {
            ((Map) value).forEach((k, v) -> {
                Model.put(target, k.toString(), v);
            });
        }
    } else if (value != null) {
        // check for http request
        MetaClass mc = GroovySystem.getMetaClassRegistry().getMetaClass(value.getClass());
        MetaProperty mp = mc.hasProperty(value, "reader");
        if (mp != null && Reader.class.isAssignableFrom(mp.getType())) {
            reader = (Reader) mp.getProperty(value);
            if (format == null) {
                MetaProperty ctp = mc.hasProperty(value, "contentType");
                if (ctp != null) {
                    String ct = (String) ctp.getProperty(value);
                    if (ct != null && ct.contains("xml")) {
                        format = "xml";
                    }
                }
            }
        } else {
            String toParse = value.toString().trim();
            reader = new StringReader(toParse);
            if (format == null) {
                if (toParse.startsWith("<")) {
                    format = "xml";
                }
            }
        }
    }
    if (reader != null) {
        if (format != null && "xml".equalsIgnoreCase(format.toString())) {
            boolean usejaxb = false;
            if (!target.equals(Object.class)) {
                if (target.getClass().isAnnotationPresent(XmlRootElement.class)) {
                    usejaxb = true;
                }
            }
            if (usejaxb) {
                JAXBContext context = getJAXBContext(target.getClass());
                Unmarshaller um = context.createUnmarshaller();
                XMLReader xreader = borrowXMLReader();
                try {
                    result = um.unmarshal(new SAXSource(xreader, new InputSource(reader)));
                } finally {
                    returnXMLReader(xreader);
                    reader.close();
                }
            } else {
                XMLReader xreader = borrowXMLReader();
                try {
                    XmlSlurper slurper = new XmlSlurper(xreader);
                    GPathResult gpr = slurper.parse(reader);
                    Object converted = convert(gpr);
                    if (!target.equals(Object.class)) {
                        if (target instanceof Model) {
                            Model.each(converted, ((Model) target)::put);
                        } else {
                            Model.each(converted, (k, v) -> {
                                Model.put(target, k, v);
                            });
                        }
                    } else {
                        result = converted;
                    }
                } finally {
                    returnXMLReader(xreader);
                    reader.close();
                }
            }
        } else {
            try {
                Object parsed = new JsonSlurper().parse(reader);
                if (!target.equals(Object.class)) {
                    if (target instanceof Model) {
                        Model.each(parsed, ((Model) target)::put);
                    } else {
                        Model.each(parsed, (k, v) -> {
                            Model.put(target, k, v);
                        });
                    }
                } else {
                    result = parsed;
                }
            } finally {
                reader.close();
            }
        }
    }
    return result;
}
Also used : XmlSlurper(groovy.util.XmlSlurper) Taggable(com.disney.groovity.Taggable) GroovySystem(groovy.lang.GroovySystem) Closure(groovy.lang.Closure) Writable(groovy.lang.Writable) GPathResult(groovy.util.slurpersupport.GPathResult) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) XMLReader(org.xml.sax.XMLReader) Node(groovy.util.slurpersupport.Node) Matcher(java.util.regex.Matcher) Map(java.util.Map) MetaProperty(groovy.lang.MetaProperty) JAXBContext(javax.xml.bind.JAXBContext) MetaClass(groovy.lang.MetaClass) Unmarshaller(javax.xml.bind.Unmarshaller) InputSource(org.xml.sax.InputSource) JsonSlurper(groovy.json.JsonSlurper) NodeChild(groovy.util.slurpersupport.NodeChild) Tag(com.disney.groovity.doc.Tag) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HttpEntity(org.apache.http.HttpEntity) CharArrayWriter(java.io.CharArrayWriter) Reader(java.io.Reader) XmlRootElement(javax.xml.bind.annotation.XmlRootElement) InputStreamReader(java.io.InputStreamReader) Collectors(java.util.stream.Collectors) JAXBException(javax.xml.bind.JAXBException) File(java.io.File) Attr(com.disney.groovity.doc.Attr) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) XMLReaderFactory(org.xml.sax.helpers.XMLReaderFactory) List(java.util.List) SAXSource(javax.xml.transform.sax.SAXSource) StringReader(java.io.StringReader) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAXException(org.xml.sax.SAXException) GroovityConstants(com.disney.groovity.GroovityConstants) HttpResponse(org.apache.http.HttpResponse) BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader) Queue(java.util.Queue) Pattern(java.util.regex.Pattern) Model(com.disney.groovity.model.Model) InputStream(java.io.InputStream) InputSource(org.xml.sax.InputSource) HttpEntity(org.apache.http.HttpEntity) Matcher(java.util.regex.Matcher) XmlSlurper(groovy.util.XmlSlurper) XMLReader(org.xml.sax.XMLReader) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) StringReader(java.io.StringReader) BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader) JAXBContext(javax.xml.bind.JAXBContext) StringReader(java.io.StringReader) FileReader(java.io.FileReader) GPathResult(groovy.util.slurpersupport.GPathResult) MetaProperty(groovy.lang.MetaProperty) Unmarshaller(javax.xml.bind.Unmarshaller) XMLReader(org.xml.sax.XMLReader) JsonSlurper(groovy.json.JsonSlurper) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) HttpResponse(org.apache.http.HttpResponse) SAXSource(javax.xml.transform.sax.SAXSource) MetaClass(groovy.lang.MetaClass) BufferedReader(java.io.BufferedReader) Model(com.disney.groovity.model.Model) File(java.io.File) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Example 7 with MetaClass

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

the class MetaPropertyLookup method getOrderedGettableProperties.

public static final MetaProperty[] getOrderedGettableProperties(Object o) {
    final Class<?> c = o.getClass();
    MetaProperty[] properties = orderedPropertiesCache.get(c);
    if (properties == null) {
        MetaClass mc = GroovySystem.getMetaClassRegistry().getMetaClass(c);
        List<MetaProperty> mps = mc.getProperties();
        TreeMap<String, MetaProperty> sortedProps;
        String[] declaredOrder = null;
        ModelOrder order = c.getAnnotation(ModelOrder.class);
        if (order != null) {
            declaredOrder = order.value();
        } else {
            XmlType xmlType = c.getAnnotation(XmlType.class);
            if (xmlType != null) {
                declaredOrder = xmlType.propOrder();
            }
        }
        if (declaredOrder != null && declaredOrder.length > 0) {
            final String[] declared = declaredOrder;
            final int dl = declared.length;
            Comparator<String> comp = new Comparator<String>() {

                @Override
                public int compare(String o1, String o2) {
                    int p1 = dl;
                    int p2 = dl;
                    for (int i = 0; i < dl; i++) {
                        String d = declared[i];
                        if (o1.equals(d)) {
                            p1 = i;
                        }
                        if (o2.equals(d)) {
                            p2 = i;
                        }
                        if (p1 < dl && p2 < dl) {
                            break;
                        }
                    }
                    if (p1 == p2) {
                        return o1.compareTo(o2);
                    }
                    return p1 - p2;
                }
            };
            sortedProps = new TreeMap<>(comp);
        } else {
            sortedProps = new TreeMap<>();
        }
        List<String> skipProperties = new ArrayList<>();
        skipProperties.add("class");
        skipProperties.add("binding");
        if (Map.class.isAssignableFrom(c) || Collection.class.isAssignableFrom(c)) {
            skipProperties.add("empty");
            if (NavigableMap.class.isAssignableFrom(c)) {
                skipProperties.add("firstEntry");
                skipProperties.add("lastEntry");
            }
        }
        for (MetaProperty mp : mps) {
            if (!skipProperties.contains(mp.getName()) && !Closeable.class.isAssignableFrom(mp.getType())) {
                // now check for skip annotations
                if (mp instanceof MetaBeanProperty) {
                    MetaBeanProperty mbp = ((MetaBeanProperty) mp);
                    if (mbp.getField() != null) {
                        ModelSkip skipAnn = mbp.getField().field.getAnnotation(ModelSkip.class);
                        if (skipAnn != null) {
                            continue;
                        }
                        if (mbp.getField().isStatic()) {
                            continue;
                        }
                    }
                    MetaMethod getter = mbp.getGetter();
                    if (getter instanceof CachedMethod) {
                        CachedMethod cm = (CachedMethod) getter;
                        ModelSkip skipAnn = cm.getCachedMethod().getAnnotation(ModelSkip.class);
                        if (skipAnn != null) {
                            continue;
                        }
                        if (cm.isStatic()) {
                            continue;
                        }
                        if (!cm.getCachedMethod().getDeclaringClass().equals(c)) {
                            // we may have an overridden method here
                            try {
                                Method override = c.getDeclaredMethod(cm.getCachedMethod().getName(), cm.getCachedMethod().getParameterTypes());
                                if (override.getAnnotation(ModelSkip.class) != null) {
                                    continue;
                                }
                            } catch (NoSuchMethodException | SecurityException e) {
                            }
                        }
                    }
                    if (mbp.getGetter() == null && mbp.getField() == null) {
                        continue;
                    }
                }
                sortedProps.put(mp.getName(), mp);
            }
        }
        properties = sortedProps.values().toArray(new MetaProperty[0]);
        orderedPropertiesCache.putIfAbsent(c, properties);
    }
    return properties;
}
Also used : ArrayList(java.util.ArrayList) CachedMethod(org.codehaus.groovy.reflection.CachedMethod) Comparator(java.util.Comparator) MethodMetaProperty(org.codehaus.groovy.runtime.metaclass.MethodMetaProperty) MetaProperty(groovy.lang.MetaProperty) MetaMethod(groovy.lang.MetaMethod) MetaBeanProperty(groovy.lang.MetaBeanProperty) CachedMethod(org.codehaus.groovy.reflection.CachedMethod) MetaMethod(groovy.lang.MetaMethod) Method(java.lang.reflect.Method) ModelOrder(com.disney.groovity.model.ModelOrder) XmlType(javax.xml.bind.annotation.XmlType) ModelSkip(com.disney.groovity.model.ModelSkip) MetaClass(groovy.lang.MetaClass) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) NavigableMap(java.util.NavigableMap) TreeMap(java.util.TreeMap) Map(java.util.Map)

Example 8 with MetaClass

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

the class MetaClassRegistryCleaner method cleanMetaClassOfClass.

private void cleanMetaClassOfClass(MetaClassRegistryImpl registry) {
    Set<Class> classes = new HashSet<Class>(alteredClasses.keySet());
    for (Class aClass : classes) {
        Object alteredMetaClass = alteredClasses.get(aClass);
        if (alteredMetaClass == NO_CUSTOM_METACLASS) {
            registry.removeMetaClass(aClass);
        } else {
            registry.setMetaClass(aClass, (MetaClass) alteredMetaClass);
        }
    }
    alteredClasses.clear();
}
Also used : MetaClass(groovy.lang.MetaClass) ExpandoMetaClass(groovy.lang.ExpandoMetaClass) HashSet(java.util.HashSet)

Example 9 with MetaClass

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

the class GrailsMetaClassUtils method getExpandoMetaClass.

public static ExpandoMetaClass getExpandoMetaClass(Class<?> aClass) {
    MetaClassRegistry registry = getRegistry();
    MetaClass mc = registry.getMetaClass(aClass);
    if (mc instanceof ExpandoMetaClass) {
        ExpandoMetaClass emc = (ExpandoMetaClass) mc;
        // make permanent
        registry.setMetaClass(aClass, emc);
        return emc;
    }
    registry.removeMetaClass(aClass);
    mc = registry.getMetaClass(aClass);
    if (mc instanceof ExpandoMetaClass) {
        return (ExpandoMetaClass) mc;
    }
    ExpandoMetaClass emc = new ExpandoMetaClass(aClass, true, true);
    emc.initialize();
    registry.setMetaClass(aClass, emc);
    return emc;
}
Also used : MetaClassRegistry(groovy.lang.MetaClassRegistry) MetaClass(groovy.lang.MetaClass) ExpandoMetaClass(groovy.lang.ExpandoMetaClass) AdaptingMetaClass(groovy.lang.AdaptingMetaClass) DelegatingMetaClass(groovy.lang.DelegatingMetaClass) ExpandoMetaClass(groovy.lang.ExpandoMetaClass)

Example 10 with MetaClass

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

the class GrailsMetaClassUtils method getMetaClass.

public static MetaClass getMetaClass(Object instance) {
    if (instance instanceof GroovyObject) {
        GroovyObject groovyObject = (GroovyObject) instance;
        MetaClass metaClass = groovyObject.getMetaClass();
        metaClass = unwrapDelegatingMetaClass(metaClass);
        if (!(metaClass instanceof ExpandoMetaClass)) {
            metaClass = getExpandoMetaClass(instance.getClass());
            groovyObject.setMetaClass(metaClass);
        }
        return metaClass;
    }
    return getExpandoMetaClass(instance.getClass());
}
Also used : MetaClass(groovy.lang.MetaClass) ExpandoMetaClass(groovy.lang.ExpandoMetaClass) AdaptingMetaClass(groovy.lang.AdaptingMetaClass) DelegatingMetaClass(groovy.lang.DelegatingMetaClass) ExpandoMetaClass(groovy.lang.ExpandoMetaClass) GroovyObject(groovy.lang.GroovyObject)

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