public String determineName(Object thing) { Object name; try { if (thing instanceof Named) { name = ((Named) thing).getName(); } else if (thing instanceof Map) { name = ((Map) thing).get("name"); } else if (thing instanceof GroovyObject) { name = ((GroovyObject) thing).getProperty("name"); } else { name = DynamicObjectUtil.asDynamicObject(thing).getProperty("name"); } } catch (MissingPropertyException e) { throw new NoNamingPropertyException(thing); } if (name == null) { throw new NullNamingPropertyException(thing); } return name.toString(); }
public GroovyObject execPlugIn(String name, GroovyObject groovyObject, GroovyObject proxyObject) throws Exception { Field[] fields=groovyObject.getClass().getDeclaredFields(); int size=fields.length; for(int i=0;i<size;i++){ Field field=fields[i]; Resource anno=field.getAnnotation(Resource.class); if(anno!=null){ String beanId=anno.name(); if(beanId==null || "".equals(beanId)){ beanId=field.getName(); } Object beanObj=MicroContextHolder.getContext().getBean(beanId); field.set(groovyObject, beanObj); } } return proxyObject; }
public static boolean execGroovy(String groovyName, String methodName, Object... paramArray) { try { GroovyObject groovyObject = (GroovyObject) getGroovyObj(groovyName); //groovyObject.invokeMethod(methodName, paramArray); //GroovyAopInter groovyAop=(GroovyAopInter) MicroContextHolder.getContextMap().get("groovyAop"); GroovyAopInter firstAop=GroovyAopChain.getFirstAop(); Object retObj=null; if(firstAop==null){ retObj=groovyObject.invokeMethod(methodName, paramArray); }else{ retObj=firstAop.invokeMethod(groovyObject,groovyName, methodName, paramArray); } return true; } catch (Throwable t) { logger.error(t.toString(), t); if(throwFlag){ throw new RuntimeException(t); } return false; } }
public static Object execGroovyRetObj(String groovyName, String methodName, Object... paramArray) { try { GroovyObject groovyObject = (GroovyObject) getGroovyObj(groovyName); //GroovyAopInter groovyAop=(GroovyAopInter) MicroContextHolder.getContextMap().get("groovyAop"); GroovyAopInter firstAop=GroovyAopChain.getFirstAop(); Object retObj=null; if(firstAop==null){ retObj=groovyObject.invokeMethod(methodName, paramArray); }else{ retObj=firstAop.invokeMethod(groovyObject,groovyName, methodName, paramArray); } return retObj; } catch (Throwable t) { logger.error(t.toString(), t); if(throwFlag){ throw new RuntimeException(t); } return null; } }
public static Object execGroovyRetObj(GroovyObject groovyObject, String methodName, Object... paramArray) { try { //GroovyObject groovyObject = (GroovyObject) getGroovyObj(groovyName); //GroovyAopInter groovyAop=(GroovyAopInter) MicroContextHolder.getContextMap().get("groovyAop"); GroovyAopInter firstAop=GroovyAopChain.getFirstAop(); Object retObj=null; if(firstAop==null){ retObj=groovyObject.invokeMethod(methodName, paramArray); }else{ retObj=firstAop.invokeMethod(groovyObject,null, methodName, paramArray); } return retObj; } catch (Throwable t) { logger.error(t.toString(), t); if(throwFlag){ throw new RuntimeException(t); } return null; } }
public static void loadGroovy(String name, String content) throws Exception { logger.info("begin load groovy name=" + name); logger.debug("groovy content=" + content); if(name.toLowerCase().contains("abstract")){ logger.info("skip load groovy name=" + name); return; } ClassLoader parent = GroovyLoadUtil.class.getClassLoader(); GroovyClassLoader loader = new GroovyClassLoader(parent); Class<?> groovyClass = loader.parseClass(content,name+".groovy"); GroovyObject groovyObject = (GroovyObject) groovyClass.newInstance(); GroovyObject proxyObject=groovyObject; if(pluginList!=null){ int size=pluginList.size(); for(int i=0;i<size;i++){ IGroovyLoadPlugin plugin=(IGroovyLoadPlugin) pluginList.get(i); proxyObject=plugin.execPlugIn(name, groovyObject, proxyObject); } } GroovyExecUtil.getGroovyMap().put(name, proxyObject); //GroovyExecUtil.getGroovyMap().put(name, groovyObject); logger.info("finish load groovy name=" + name); }
@Test(groups = {"groovy"}) public void testScript() throws Exception { String f1 = new File("./src/test/resources/StoreProc.groovy").getCanonicalPath(); URL url = new URL("file://"+f1); ExtendedGroovyLoader classLoader = new ExtendedGroovyLoader(); Class cls = classLoader.parseClass(new File(f1)); GroovyObject groovyObj = (GroovyObject) cls.newInstance(); System.out.println((String) groovyObj.invokeMethod("sayHello", new Object[] { "test" }) ); groovyObj.getMetaClass().setProperty(groovyObj, "city", "cypress"); System.out.println( groovyObj.getMetaClass().getProperty(groovyObj,"city")); Method[] methods = cls.getDeclaredMethods(); System.out.println("methods "+ methods.length); dumpMethod( methods); if ( classLoader.isSourceChange(url, cls)) { System.out.println("source change for f1 "+f1); Class cls1 = classLoader.recompile(url, groovyObj.getClass().getName(), cls); GroovyObject groovyObj1 = (GroovyObject) cls1.newInstance(); System.out.println( groovyObj1.invokeMethod("sayHello", new Object[]{"test"}) ); //assert "hello test".equals( output); } }
@Override public void customize(GroovyObject goo) { DelegatingMetaClass dmc = new DelegatingMetaClass(goo.getMetaClass()) { @Override public Object invokeMethod(Object arg0, String mName, Object[] arg2) { if (mName.contains("Missing")) { throw new IllegalStateException("Gotcha"); } else { return super.invokeMethod(arg0, mName, arg2); } } }; dmc.initialize(); goo.setMetaClass(dmc); }
@SuppressWarnings("resource") private static final GroovyObject getGroovyObject(String rule) throws IllegalAccessException, InstantiationException { if (!RULE_CLASS_CACHE.containsKey(rule)) { synchronized (GroovyRuleEngine.class) { if (!RULE_CLASS_CACHE.containsKey(rule)) { Matcher matcher = DimensionRule.RULE_COLUMN_PATTERN.matcher(rule); StringBuilder engineClazzImpl = new StringBuilder(200) .append("class RuleEngineBaseImpl extends " + RuleEngineBase.class.getName() + "{") .append("Object execute(Map context) {").append(matcher.replaceAll("context.get(\"$1\")")) .append("}").append("}"); GroovyClassLoader loader = new GroovyClassLoader(AbstractDimensionRule.class.getClassLoader()); Class<?> engineClazz = loader.parseClass(engineClazzImpl.toString()); RULE_CLASS_CACHE.put(rule, engineClazz); } } } return (GroovyObject) RULE_CLASS_CACHE.get(rule).newInstance(); }
static Class<?> createProxyClass(Class<?> persistentClass, Class<?>[] interfaces) throws HibernateException { // note: interfaces is assumed to already contain HibernateProxy.class try { Set<Class<?>> allInterfaces = new HashSet<>(); if(interfaces != null) { allInterfaces.addAll(Arrays.asList(interfaces)); } allInterfaces.add(GroovyObject.class); allInterfaces.add(EntityProxy.class); ProxyFactory factory = createJavassistProxyFactory(persistentClass, allInterfaces.toArray(new Class<?>[allInterfaces.size()])); Class<?> proxyClass = factory.createClass(); HibernateUtils.enhanceProxyClass(proxyClass); return proxyClass; } catch (Throwable t) { LogFactory.getLog(BasicLazyInitializer.class).error( "Javassist Enhancement failed: " + persistentClass.getName(), t); throw new HibernateException("Javassist Enhancement failed: " + persistentClass.getName(), t); } }
private static Class<?> getProxyFactory(Class<?> persistentClass, Class<?>[] interfaces) throws HibernateException { // note: interfaces is assumed to already contain HibernateProxy.class try { Set<Class<?>> allInterfaces = new HashSet<Class<?>>(); if(interfaces != null) { allInterfaces.addAll(Arrays.asList(interfaces)); } allInterfaces.add(GroovyObject.class); allInterfaces.add(EntityProxy.class); ProxyFactory factory = createProxyFactory(persistentClass, allInterfaces.toArray(new Class<?>[allInterfaces.size()])); Class<?> proxyClass = factory.createClass(); HibernateUtils.enhanceProxyClass(proxyClass); return proxyClass; } catch (Throwable t) { LogFactory.getLog(BasicLazyInitializer.class).error( "Javassist Enhancement failed: " + persistentClass.getName(), t); throw new HibernateException("Javassist Enhancement failed: " + persistentClass.getName(), t); } }
@Override public Class<? extends ActionBean> getActionBeanType(String path) { if(path.startsWith(APIRoot.PATH_PREFIX)) { return null; //Not an ActionBean (as far as Stripes is concerned) } Dispatch dispatch = getDispatch(path); if(dispatch != null) { Class<? extends ActionBean> actionBeanClass = dispatch.getActionBeanClass(); if(GroovyObject.class.isAssignableFrom(actionBeanClass) && !eventMappings.containsKey(actionBeanClass)) { synchronized (this) { addActionBean(actionBeanClass); } } return actionBeanClass; } else { return super.getActionBeanType(path); } }
/** * Creates a Closure representing the body of this GPathResult. * * @return the body of this GPathResult, converted to a <code>Closure</code> */ public Closure getBody() { return new Closure(this.parent,this) { public void doCall(Object[] args) { final GroovyObject delegate = (GroovyObject)getDelegate(); final GPathResult thisObject = (GPathResult)getThisObject(); Node node = (Node)thisObject.getAt(0); List children = node.children(); for (Object child : children) { delegate.getProperty("mkp"); if (child instanceof Node) { delegate.invokeMethod("yield", new Object[]{new NodeChild((Node) child, thisObject, "*", null)}); } else { delegate.invokeMethod("yield", new Object[]{child}); } } } }; }
/** * Invokes the given method on the object. */ public static Object invokeMethod(Object object, String methodName, Object arguments) { if (object == null) { object = NullObject.getNullObject(); //throw new NullPointerException("Cannot invoke method " + methodName + "() on null object"); } // if the object is a Class, call a static method from that class if (object instanceof Class) { Class theClass = (Class) object; MetaClass metaClass = metaRegistry.getMetaClass(theClass); return metaClass.invokeStaticMethod(object, methodName, asArray(arguments)); } // it's an instance; check if it's a Java one if (!(object instanceof GroovyObject)) { return invokePojoMethod(object, methodName, arguments); } // a groovy instance (including builder, closure, ...) return invokePogoMethod(object, methodName, arguments); }
private CallSite createPogoMetaClassGetPropertySite(GroovyObject receiver) { MetaClass metaClass = receiver.getMetaClass(); CallSite site; if (metaClass.getClass() != MetaClassImpl.class || GroovyCategorySupport.hasCategoryInCurrentThread()) { site = new PogoMetaClassGetPropertySite(this, metaClass); } else { final MetaProperty effective = ((MetaClassImpl) metaClass).getEffectiveGetMetaProperty(this.array.owner, receiver, name, false); if (effective != null) { if (effective instanceof CachedField) site = new GetEffectivePogoFieldSite(this, metaClass, (CachedField) effective); else site = new GetEffectivePogoPropertySite(this, metaClass, effective); } else { site = new PogoMetaClassGetPropertySite(this, metaClass); } } array.array[index] = site; return site; }
public final Object callCurrent(GroovyObject receiver, Object[] args) throws Throwable { if (checkCall(receiver)) { try { try { return metaClass.invokeMethod(array.owner, receiver, name, args, false, true); } catch (MissingMethodException e) { if (e instanceof MissingMethodExecutionFailed) { throw (MissingMethodException)e.getCause(); } else if (receiver.getClass() == e.getType() && e.getMethod().equals(name)) { // in case there's nothing else, invoke the object's own invokeMethod() return ((GroovyObject)receiver).invokeMethod(name, args); } else { throw e; } } } catch (GroovyRuntimeException gre) { throw ScriptBytecodeAdapter.unwrap(gre); } } else { return CallSiteArray.defaultCallCurrent(this, receiver, args); } }
private static CallSite createCallSite(CallSite callSite, Object receiver, Object[] args) { CallSite site; if (receiver == null) return new NullCallSite(callSite); if (receiver instanceof Class) site = createCallStaticSite(callSite, (Class) receiver, args); else if (receiver instanceof GroovyObject) { site = createPogoSite(callSite, receiver, args); } else { site = createPojoSite(callSite, receiver, args); } replaceCallSite(callSite, site); return site; }
/** * Gives the meta class to an Object. */ public void getMetaClass() { Object receiver = args[0]; if (receiver == null) { mc = NullObject.getNullObject().getMetaClass(); } else if (receiver instanceof GroovyObject) { mc = ((GroovyObject) receiver).getMetaClass(); } else if (receiver instanceof Class) { Class c = (Class) receiver; ClassLoader cl = c.getClassLoader(); try { Class.forName(c.getName(), true, cl); } catch (ClassNotFoundException e) {} mc = GroovySystem.getMetaClassRegistry().getMetaClass(c); this.cache &= !ClassInfo.getClassInfo(c).hasPerInstanceMetaClasses(); } else { mc = ((MetaClassRegistryImpl) GroovySystem.getMetaClassRegistry()).getMetaClass(receiver); this.cache &= !ClassInfo.getClassInfo(receiver.getClass()).hasPerInstanceMetaClasses(); } mc.initialize(); }
/** * Creates a MethodHandle, which will use the meta class path. * This method is called only if no handle has been created before. This * is usually the case if the method selection failed. */ public void setMetaClassCallHandleIfNedded(boolean standardMetaClass) { if (handle!=null) return; useMetaClass = true; if (LOG_ENABLED) LOG.info("set meta class invocation path"); Object receiver = getCorrectedReceiver(); if (receiver instanceof Class) { handle = META_CLASS_INVOKE_STATIC_METHOD.bindTo(mc); if (LOG_ENABLED) LOG.info("use invokeStaticMethod with bound meta class"); } else { handle = MOP_INVOKE_METHOD.bindTo(mc); if (LOG_ENABLED) LOG.info("use invokeMethod with bound meta class"); if (receiver instanceof GroovyObject) { // if the meta class call fails we may still want to fall back to call // GroovyObject#invokeMethod if the receiver is a GroovyObject if (LOG_ENABLED) LOG.info("add MissingMethod handler for GrooObject#invokeMethod fallback path"); handle = MethodHandles.catchException(handle, MissingMethodException.class, GROOVY_OBJECT_INVOKER); } } handle = MethodHandles.insertArguments(handle, 1, name); if (!spread) handle = handle.asCollector(Object[].class, targetType.parameterCount()-1); if (LOG_ENABLED) LOG.info("bind method name and create collector for arguments"); }
/** * Collect all types that make up the type hierarchy of the given types. */ public static Set<ModelType<?>> collectHierarchy(Iterable<? extends ModelType<?>> types) { Queue<ModelType<?>> queue = new ArrayDeque<ModelType<?>>(Iterables.size(types) * 2); Iterables.addAll(queue, types); Set<ModelType<?>> seenTypes = Sets.newLinkedHashSet(); ModelType<?> type; while ((type = queue.poll()) != null) { // Do not process Object's or GroovyObject's methods Class<?> rawClass = type.getRawClass(); if (rawClass.equals(Object.class) || rawClass.equals(GroovyObject.class)) { continue; } // Do not reprocess if (!seenTypes.add(type)) { continue; } Class<?> superclass = rawClass.getSuperclass(); if (superclass != null) { ModelType<?> superType = ModelType.of(superclass); if (!seenTypes.contains(superType)) { queue.add(superType); } } for (Class<?> iface : rawClass.getInterfaces()) { ModelType<?> ifaceType = ModelType.of(iface); if (!seenTypes.contains(ifaceType)) { queue.add(ifaceType); } } } return seenTypes; }
private static Object logical(Object node, String op, final Action<Object> withNode) { GroovyObject groovyObject = (GroovyObject) node; groovyObject.invokeMethod(op, new Closure(null, null) { void doCall() { withNode.execute(getDelegate()); } }); return node; }
private static Object addFilenames(Object node, Iterable<String> filenames, boolean caseSensitive) { GroovyObject groovyObject = (GroovyObject) node; Map<String, Object> props = new HashMap<String, Object>(2); props.put("casesensitive", caseSensitive); for (String filename : filenames) { props.put("name", AntUtil.maskFilename(filename)); groovyObject.invokeMethod("filename", props); } return node; }
public MetaClassAdapter determineDelegate(Object bean) { if (bean instanceof Class) { return new ClassAdapter((Class<?>) bean); } else if (bean instanceof Map) { return new MapAdapter(); } else if (bean instanceof DynamicObject || bean instanceof DynamicObjectAware || !(bean instanceof GroovyObject)) { return new MetaClassAdapter(); } return new GroovyObjectAdapter(); }
private MetaClass getMetaClass() { if (bean instanceof GroovyObject) { return ((GroovyObject) bean).getMetaClass(); } else { return GroovySystem.getMetaClassRegistry().getMetaClass(bean.getClass()); } }
public void test_groovy() throws Exception { ClassLoader parent = Thread.currentThread().getContextClassLoader(); GroovyClassLoader loader = new GroovyClassLoader(parent); // A类 Class AClass = loader.parseClass("class A {\n" + // " int id\n" + // "}"); // A实例 GroovyObject a = (GroovyObject) AClass.newInstance(); a.setProperty("id", 33); String textA = JSON.toJSONString(a); GroovyObject aa = (GroovyObject) JSON.parseObject(textA, AClass); Assert.assertEquals(a.getProperty("id"), aa.getProperty("id")); System.out.println(a); // B类,继承于A Class BClass = loader.parseClass("class B extends A {\n" + // " String name\n" + // "}"); // B实例 GroovyObject b = (GroovyObject) BClass.newInstance(); b.setProperty("name", "jobs"); String textB = JSON.toJSONString(b); GroovyObject bb = (GroovyObject) JSON.parseObject(textB, BClass); Assert.assertEquals(b.getProperty("id"), bb.getProperty("id")); Assert.assertEquals(b.getProperty("name"), bb.getProperty("name")); // 序列化失败 System.out.println(JSON.toJSONString(b, true)); }
/** * Execute groovy script t. * * @param <T> the type parameter * @param groovyScript the groovy script * @param methodName the method name * @param args the args * @param clazz the clazz * @return the t */ public static <T> T executeGroovyScript(final Resource groovyScript, final String methodName, final Object[] args, final Class<T> clazz) { if (groovyScript == null || StringUtils.isBlank(methodName)) { return null; } final ClassLoader parent = ScriptingUtils.class.getClassLoader(); try (GroovyClassLoader loader = new GroovyClassLoader(parent)) { final File groovyFile = groovyScript.getFile(); if (groovyFile.exists()) { final Class<?> groovyClass = loader.parseClass(groovyFile); LOGGER.trace("Creating groovy object instance from class [{}]", groovyFile.getCanonicalPath()); final GroovyObject groovyObject = (GroovyObject) groovyClass.newInstance(); LOGGER.trace("Executing groovy script's [{}] method, with parameters [{}]", methodName, args); final T result = (T) groovyObject.invokeMethod(methodName, args); LOGGER.trace("Results returned by the groovy script are [{}]", result); if (!clazz.isAssignableFrom(result.getClass())) { throw new ClassCastException("Result [" + result + " is of type " + result.getClass() + " when we were expecting " + clazz); } return result; } else { LOGGER.trace("Groovy script at [{}] does not exist", groovyScript); } } catch (final Exception e) { LOGGER.error(e.getMessage(), e); } return null; }
public static Closure<?> buildClosure(String... strings) throws IOException { Closure<?> closure = null; // Create a method returning a closure StringBuilder sb = new StringBuilder("def closure() { { script -> "); sb.append(StringUtils.join(strings, "\n")); sb.append(" } }"); // Create an anonymous class for the method GroovyClassLoader loader = new GroovyClassLoader(); Class<?> groovyClass = loader.parseClass(sb.toString()); try { // Create an instance of the class GroovyObject groovyObject = (GroovyObject) groovyClass.newInstance(); // Invoke the object's method and thus obtain the closure closure = (Closure<?>) groovyObject.invokeMethod("closure", null); } catch (Throwable e) { throw new RuntimeException(e); } finally { loader.close(); } return closure; }
@Override public GroovyObject execPlugIn(String name, GroovyObject groovyObject, GroovyObject proxyObject) { Annotation[] annos=groovyObject.getClass().getAnnotations(); MicroUrlMapping anno=groovyObject.getClass().getAnnotation(MicroUrlMapping.class); String root=""; if(anno!=null){ root=anno.name(); //MicroControllerMap.setUrl(root, name); }else{ return proxyObject; } Method[] methods=groovyObject.getClass().getMethods(); int size=methods.length; for(int i=0;i<size;i++){ Method method=methods[i]; MicroUrlMapping subAnno=method.getAnnotation(MicroUrlMapping.class); if(subAnno==null){ continue; } String subPath=subAnno.name(); String version=subAnno.version(); String methodName=method.getName(); String fullPath=root+subPath; MicroControllerMap.setUrl(fullPath, name, methodName,version); } return proxyObject; }
@Override public GroovyObject execPlugIn(String name, GroovyObject groovyObject, GroovyObject proxyObject) throws Exception { Field[] fields=groovyObject.getClass().getDeclaredFields(); int size=fields.length; for(int i=0;i<size;i++){ Field field=fields[i]; InjectGroovy anno=field.getAnnotation(InjectGroovy.class); if(anno==null){ continue; } String groovyName=null; groovyName=anno.name(); if(groovyName==null || "".equals(groovyName)){ groovyName=field.getName(); } Class cls=field.getType(); InjectGroovyProxy injectGroovyProxy=new InjectGroovyProxy(); injectGroovyProxy.setGroovyName(groovyName); //injectGroovyProxy.setGroovyObject(proxyObject); Object proxy = Proxy.newProxyInstance(cls.getClassLoader(), new Class[]{cls}, (InvocationHandler) injectGroovyProxy); field.set(groovyObject, proxy); } return proxyObject; }
public Object execNextHandler(GroovyObject groovyObject, String GroovyName, String methodName, Object... param){ if(nextAop!=null){ return nextAop.invokeMethod(groovyObject, GroovyName, methodName, param); }else{ return groovyObject.invokeMethod(methodName, param); } }
@Override public Object invokeMethod(Object target, String name, Object... args) { try { return ((GroovyObject) target).invokeMethod(name, args); } catch (Throwable e) { throw SpongeUtils.wrapException(target + "." + name, e); } }
protected static void executeMain() { String scriptName = WRAPPER_MANAGER.getGroovyScript(); if (scriptName == null) { System.out.println("script not found in configuration -> aborting"); System.exit(999); } File scriptFile = new File(scriptName); if (!scriptFile.exists()) { System.out.println("script not found -> aborting: " + scriptFile.getAbsolutePath()); System.exit(999); } Object[] mainMethodArgs = WRAPPER_MANAGER.getMainMethodArgs(); try { ClassLoader parent = WrapperGroovyMain.class.getClassLoader(); GroovyClassLoader loader = new GroovyClassLoader(parent); Class groovyClass = loader.parseClass(scriptFile); GroovyObject script = (GroovyObject) groovyClass.newInstance(); script.invokeMethod("main", mainMethodArgs); } catch (Throwable e) { e.printStackTrace(); exception = e; } }
@Test public void testWithTwoClassesDefinedInTheOneGroovyFile_CorrectClassFirst() throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("twoClassesCorrectOneFirst.xml", getClass()); Messenger messenger = (Messenger) ctx.getBean("messenger"); assertNotNull(messenger); assertEquals("Hello World!", messenger.getMessage()); // Check can cast to GroovyObject GroovyObject goo = (GroovyObject) messenger; assertNotNull(goo); }