001package org.nuxeo.segment.io; 002 003import groovy.lang.Binding; 004import groovy.lang.GroovyClassLoader; 005import groovy.lang.Script; 006 007import java.io.Serializable; 008import java.util.ArrayList; 009import java.util.HashMap; 010import java.util.List; 011import java.util.Map; 012 013import org.codehaus.groovy.runtime.InvokerHelper; 014import org.nuxeo.common.xmap.annotation.XNode; 015import org.nuxeo.common.xmap.annotation.XNodeList; 016import org.nuxeo.common.xmap.annotation.XNodeMap; 017import org.nuxeo.common.xmap.annotation.XObject; 018 019@XObject("mapper") 020public class SegmentIOMapper { 021 022 @XNode("@name") 023 String name; 024 025 @XNode("@targetAPI") 026 String target = "track"; 027 028 @XNodeList(value = "events/event", type = ArrayList.class, componentType = String.class) 029 List<String> events; 030 031 @XNode("groovy") 032 String groovyMapping; 033 034 @XNodeMap(value = "parameters/parameter", key = "@name", type = HashMap.class, componentType = String.class) 035 Map<String, String> parameters = new HashMap<String, String>(); 036 037 @Override 038 public boolean equals(Object obj) { 039 if (obj instanceof SegmentIOMapper) { 040 return name.equals(((SegmentIOMapper)obj).name); 041 } 042 return super.equals(obj); 043 } 044 045 public boolean isIdentify() { 046 return "identify".equalsIgnoreCase(target); 047 } 048 049 public Map<String, Serializable> getMappedData(Map<String, Object> context) { 050 051 Map<String, Serializable> mapping = new HashMap<String, Serializable>(); 052 context.put("mapping", mapping); 053 054 StringBuffer sb = new StringBuffer(); 055 for (String key : parameters.keySet()) { 056 sb.append("mapping.put(\""); 057 sb.append(key); 058 sb.append("\", "); 059 sb.append(parameters.get(key)); 060 sb.append(");\n"); 061 } 062 063 if (groovyMapping!=null && !groovyMapping.isEmpty()) { 064 sb.append(groovyMapping); 065 } 066 067 Binding binding = new Binding(context); 068 GroovyClassLoader loader = new GroovyClassLoader(this.getClass().getClassLoader()); 069 Class<?> klass = loader.parseClass(sb.toString()); 070 Script script = InvokerHelper.createScript(klass, binding); 071 script.run(); 072 return mapping; 073 } 074 075 public String getName() { 076 return name; 077 } 078 079 public String getTarget() { 080 return target; 081 } 082 083}