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;
}
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();
}
}
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);
}
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);
}
}
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);
}
}
Aggregations