use of com.disney.groovity.model.ModelFilter in project groovity by disney.
the class TestModel method testTypes.
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void testTypes() throws Exception {
HashMap main = new HashMap<>();
main.put("longChange", 100l);
main.put("intChange", (short) 100);
HashMap second = new HashMap();
second.put("double", 3.0);
main.put("second", second);
Map third = new LinkedHashMap<>();
third.put("x", "y");
third.put("a", "b");
third.put("longChange", 20l);
second.put("third", third);
HashMap features = new HashMap();
features.put("clowns", 5);
Map menu = new ConcurrentHashMap();
menu.put("appetizer", "pretzels");
menu.put("mainCourse", "pizza");
features.put("menu", menu);
Map place = new HashMap();
place.put("name", "State Fairground");
place.put("latitude", 1234);
place.put("longitude", 5678);
RealEvent event = new RealEvent();
event.time = new Date(1000000000);
event.name = "State Fair";
event.put("place", place);
event.description = "State Fun";
event.features = features;
second.put("event", event);
ModelCollector mc = new ModelCollector();
mc.setFilters(new ModelFilter[] { ModelFilter.transform(Short.class, o -> {
return o * 13;
}), ModelFilter.transform(Long.class, o -> {
return o * 17;
}), ModelFilter.transform(Number.class, o -> {
return o.doubleValue() * 2;
}), ModelFilter.exclude(LinkedHashMap.class, "longChange"), ModelFilter.add(LinkedHashMap.class, "ordered", o -> {
return o.size();
}), ModelFilter.collapse(RealEvent.class, "features"), ModelFilter.copy(RealEvent.class, "name", "allcaps", name -> {
return name.toString().toUpperCase();
}), ModelFilter.include(RealPlace.class, "name", "shortName"), ModelFilter.promote(ConcurrentHashMap.class, "mainCourse"), ModelFilter.rename(RealEvent.class, "description", "info"), ModelFilter.invoke(Date.class, "getTime", ""), ModelFilter.invoke(RealPlace.class, "getName", "shortName", 1, 11), ModelFilter.transform(RealPlace.class, "name", o -> {
return o.toString().concat("...");
}) });
mc.visit(main);
Map expected = new HashMap<>();
expected.put("longChange", 3400.0);
expected.put("intChange", 2600.0);
HashMap expectedSecond = new HashMap();
expectedSecond.put("double", 6.0);
expected.put("second", expectedSecond);
Map expectedThird = new HashMap();
expectedThird.put("x", "y");
expectedThird.put("a", "b");
expectedThird.put("ordered", 6.0);
expectedSecond.put("third", expectedThird);
Map expectedEvent = new HashMap<>();
expectedEvent.put("allcaps", "STATE FAIR");
expectedEvent.put("name", "State Fair");
expectedEvent.put("info", "State Fun");
expectedEvent.put("time", 1000000000l);
expectedEvent.put("clowns", 10.0);
expectedEvent.put("menu", "pizza");
Map expectedPlace = new HashMap<>();
expectedPlace.put("name", "State Fairground...");
expectedPlace.put("shortName", "tate Fairg");
expectedEvent.put("place", expectedPlace);
expectedSecond.put("event", expectedEvent);
Assert.assertEquals(expected, mc.getCollected());
}
use of com.disney.groovity.model.ModelFilter in project groovity by disney.
the class TestModel method testModel.
@SuppressWarnings({ "rawtypes", "unchecked", "serial" })
@Test
public void testModel() throws Exception {
HashMap place = new HashMap<>();
place.put("name", "State Fairground");
place.put("latitude", 1234);
place.put("longitude", 5678);
HashMap features = new HashMap();
features.put("clowns", 5);
HashMap menu = new HashMap();
menu.put("appetizer", "pretzels");
menu.put("mainCourse", "pizza");
features.put("menu", menu);
RealEvent event = new RealEvent();
event.name = "State Fair";
event.put("place", place);
event.description = "State Fun";
event.features = features;
Exception e = null;
try {
event.put("time", "last week");
} catch (IllegalArgumentException iae) {
e = iae;
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(event);
oos.close();
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
Object o = ois.readObject();
Assert.assertEquals(((Model) o).map(), event.map());
Assert.assertNotNull("Expected IllegalArgumentException, none was thrown", e);
event.put("time", 1000000000000l);
ModelCollector collector = new ModelCollector();
collector.setFilters(new ModelFilter[] { ModelFilter.invoke("", "reverseName", "reversedName", 2, 8), ModelFilter.exclude("description"), ModelFilter.copy("name", "allcaps", name -> {
return name.toString().toUpperCase();
}), ModelFilter.promote("place.name"), ModelFilter.invoke("place", "reverse", ""), ModelFilter.collapse("features.menu"), ModelFilter.include("*", "features.mainCourse", "features.clowns", "features.bands"), ModelFilter.transform("time", date -> {
return ((Date) date).getTime();
}), ModelFilter.rename("time", "date"), ModelFilter.add("features.bands", ev -> {
return Arrays.asList("Foo", "Bar");
}), ModelFilter.custom(new Closure(null) {
@SuppressWarnings("unused")
public void doCall(String k, Object v, ModelConsumer c) {
if (k.equals("clowns")) {
c.call(k, v.toString());
} else {
c.call(k, v);
}
}
}) });
HashMap expected = new HashMap<>();
expected.put("name", "State Fair");
expected.put("reversedName", "aF eta");
expected.put("allcaps", "STATE FAIR");
expected.put("date", 1000000000000l);
expected.put("place", "dnuorgriaF etatS");
HashMap expectedFeatures = new HashMap();
expectedFeatures.put("mainCourse", "pizza");
expectedFeatures.put("clowns", "5");
expectedFeatures.put("bands", Arrays.asList("Foo", "Bar"));
expected.put("features", expectedFeatures);
collector.visit(event);
Assert.assertEquals(expected, collector.getCollected());
HashMap firstLevel = new HashMap();
HashMap secondLevelA = new HashMap();
HashMap secondLevelB = new HashMap();
secondLevelA.put("name", "foo");
secondLevelB.put("name", "bar");
firstLevel.put("a", secondLevelA);
firstLevel.put("b", secondLevelB);
ModelCollector acc = new ModelCollector();
acc.setFilters(new ModelFilter[] { ModelFilter.include("a.name") });
acc.visit(firstLevel);
HashMap exacc = new HashMap<>();
exacc.put("a", secondLevelA);
Assert.assertEquals(exacc, acc.getCollected());
ModelCollector acc2 = new ModelCollector();
acc2.setFilters(new ModelFilter[] { ModelFilter.exclude("a.name") });
acc2.visit(firstLevel);
HashMap exacc2 = new HashMap<>();
exacc2.put("b", secondLevelB);
exacc2.put("a", new HashMap<>());
Assert.assertEquals(exacc2, acc2.getCollected());
}
use of com.disney.groovity.model.ModelFilter 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;
}
Aggregations