groovy.lang.GroovyObject Java Examples

The following examples show how to use groovy.lang.GroovyObject. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: groovy   Author: apache   File: PogoMetaClassSite.java    License: Apache License 2.0 6 votes vote down vote up
public final Object call(final Object receiver, final Object[] args) throws Throwable {
    if (checkCall(receiver)) {
        try {
            try {
                return metaClass.invokeMethod(receiver, name, args);
            } 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.defaultCall(this, receiver, args);
    }
}
 
Example #2
Source Project: zuul-netty   Author: neilbeveridge   File: GroovyCompiler.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testLoadGroovyFromString() {

    GroovyCompiler compiler = spy(new GroovyCompiler());

    try {

        String code = "class test { public String hello(){return \"hello\" } } ";
        Class clazz = compiler.compile(code, "test");
        assertNotNull(clazz);
        assertEquals(clazz.getName(), "test");
        GroovyObject groovyObject = (GroovyObject) clazz.newInstance();
        Object[] args = {};
        String s = (String) groovyObject.invokeMethod("hello", args);
        assertEquals(s, "hello");


    } catch (Exception e) {
        assertFalse(true);
    }

}
 
Example #3
Source Project: nh-micro   Author: jeffreyning   File: GroovyExecUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static Object execGroovyRetObj(GroovyObject groovyObject, String methodName,
		Object... paramArray) {
	try {
		//add 201806 ninghao
		if(groovyObject==null){
			throw new RuntimeException("groovyObject is null methodName="+methodName);
		}			
		
		//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;
	}
}
 
Example #4
Source Project: nh-micro   Author: jeffreyning   File: GroovyExecUtil.java    License: Apache License 2.0 6 votes vote down vote up
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;
	}
}
 
Example #5
Source Project: nh-micro   Author: jeffreyning   File: GroovyLoadUtil.java    License: Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #6
Source Project: groovy   Author: apache   File: Selector.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Gives the meta class to an Object.
 */
public MetaClass 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;
        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();

    return mc;
}
 
Example #7
Source Project: Zebra   Author: Meituan-Dianping   File: GroovyRuleEngine.java    License: Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #8
Source Project: groovy   Author: apache   File: ProxyGeneratorAdapter.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public GroovyObject proxy(Map<Object, Object> map, Object... constructorArgs) {
    if (constructorArgs == null && cachedNoArgConstructor != null) {
        // if there isn't any argument, we can make invocation faster using the cached constructor
        try {
            return (GroovyObject) cachedNoArgConstructor.newInstance(map);
        } catch (InstantiationException | InvocationTargetException | IllegalAccessException e) {
            throw new GroovyRuntimeException(e);
        }
    }
    if (constructorArgs == null) constructorArgs = EMPTY_ARGS;
    Object[] values = new Object[constructorArgs.length + 1];
    System.arraycopy(constructorArgs, 0, values, 0, constructorArgs.length);
    values[values.length - 1] = map;
    return DefaultGroovyMethods.<GroovyObject>newInstance(cachedClass, values);
}
 
Example #9
Source Project: groovy   Author: apache   File: GPathResult.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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});
                }
            }                
        }
    };
}
 
Example #10
Source Project: groovy   Author: apache   File: ProxyGeneratorAdapter.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public GroovyObject delegatingProxy(Object delegate, Map<Object, Object> map, Object... constructorArgs) {
    if (constructorArgs == null && cachedNoArgConstructor != null) {
        // if there isn't any argument, we can make invocation faster using the cached constructor
        try {
            return (GroovyObject) cachedNoArgConstructor.newInstance(map, delegate);
        } catch (InstantiationException | InvocationTargetException | IllegalAccessException e) {
            throw new GroovyRuntimeException(e);
        }
    }
    if (constructorArgs == null) constructorArgs = EMPTY_ARGS;
    Object[] values = new Object[constructorArgs.length + 2];
    System.arraycopy(constructorArgs, 0, values, 0, constructorArgs.length);
    values[values.length - 2] = map;
    values[values.length - 1] = delegate;
    return DefaultGroovyMethods.<GroovyObject>newInstance(cachedClass, values);
}
 
Example #11
Source Project: everrest   Author: codenvy   File: ObjectBuilderTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private ObjectValue createJsonBook(GroovyObject book) {
    ObjectValue objectValue = new ObjectValue();
    objectValue.addElement("author", new StringValue((String)book.getProperty("author")));
    objectValue.addElement("title", new StringValue((String)book.getProperty("title")));
    objectValue.addElement("pages", new LongValue((Integer)book.getProperty("pages")));
    objectValue.addElement("isdn", new LongValue((Long)book.getProperty("isdn")));
    objectValue.addElement("price", new DoubleValue((Double)book.getProperty("price")));
    objectValue.addElement("availability", new BooleanValue((Boolean)book.getProperty("availability")));
    objectValue.addElement("delivery", new BooleanValue((Boolean)book.getProperty("delivery")));
    return objectValue;
}
 
Example #12
Source Project: spring-analysis-note   Author: Vip-Augus   File: AnnotationTransactionAttributeSourceTests.java    License: MIT License 5 votes vote down vote up
@Test
public void transactionAttributeDeclaredOnGroovyClass() throws Exception {
	Method getAgeMethod = ITestBean1.class.getMethod("getAge");
	Method getNameMethod = ITestBean1.class.getMethod("getName");
	Method getMetaClassMethod = GroovyObject.class.getMethod("getMetaClass");

	AnnotationTransactionAttributeSource atas = new AnnotationTransactionAttributeSource();
	TransactionAttribute getAgeAttr = atas.getTransactionAttribute(getAgeMethod, GroovyTestBean.class);
	assertEquals(TransactionAttribute.PROPAGATION_REQUIRED, getAgeAttr.getPropagationBehavior());
	TransactionAttribute getNameAttr = atas.getTransactionAttribute(getNameMethod, GroovyTestBean.class);
	assertEquals(TransactionAttribute.PROPAGATION_REQUIRED, getNameAttr.getPropagationBehavior());
	assertNull(atas.getTransactionAttribute(getMetaClassMethod, GroovyTestBean.class));
}
 
Example #13
Source Project: arcusplatform   Author: arcus-smart-home   File: ZigbeeActionContext.java    License: Apache License 2.0 5 votes vote down vote up
public void send(Map<String,Object> args, GroovyObject obj) {
   final CapabilityHandlerContext ctx = GroovyCapabilityDefinition.CapabilityHandlerContext.getContext(this);
   ZigbeeReflex.ZigbeeSendProcessor proc = new ZigbeeReflex.ZigbeeSendProcessor() {
      @Override
      public void processSendCommand(ProtocStruct msg) {
         ctx.addAction(new ZigbeeSendAction(msg));
      }
   };

   if (obj instanceof Closure<?>) {
      ((Closure<?>)obj).call(proc,args);
   } else {
      obj.invokeMethod("send", new Object[] {proc,args});
   }
}
 
Example #14
Source Project: arcusplatform   Author: arcus-smart-home   File: GroovyCapabilityDefinitionFactory.java    License: Apache License 2.0 5 votes vote down vote up
public static GroovyObject create(String capabilityName, Script script) {
   Binding binding = script.getBinding();
   if(!(binding instanceof EnvironmentBinding)) {
      throw new IllegalArgumentException("Invalid bindings of class " + binding.getClass());
   }
   EnvironmentBinding environment = (EnvironmentBinding) binding;
   CapabilityDefinition definition = environment.getBuilder().getCapabilityDefinitionByName(capabilityName);
   if(definition == null) {
      throw new IllegalStateException("Unable to load capability defintion [" + capabilityName + "]");
   }

   return new GroovyCapabilityDefinition(definition, environment);
}
 
Example #15
Source Project: groovy   Author: apache   File: InvokerHelper.java    License: Apache License 2.0 5 votes vote down vote up
public static void setAttribute(Object object, String attribute, Object newValue) {
    if (object == null) {
        object = NullObject.getNullObject();
    }

    if (object instanceof Class) {
        metaRegistry.getMetaClass((Class) object).setAttribute(object, attribute, newValue);
    } else if (object instanceof GroovyObject) {
        ((GroovyObject) object).getMetaClass().setAttribute(object, attribute, newValue);
    } else {
        metaRegistry.getMetaClass(object.getClass()).setAttribute(object, attribute, newValue);
    }
}
 
Example #16
Source Project: arcusplatform   Author: arcus-smart-home   File: ReflexMatchContext.java    License: Apache License 2.0 5 votes vote down vote up
public void send(GroovyObject action) {
   if (action instanceof Closure) {
      send((Closure<?>)action);
   } else {
      action.invokeMethod("send", new Object[] { getProtocolSendProcessor() } );
   }
}
 
Example #17
Source Project: groovy   Author: apache   File: ScriptBytecodeAdapter.java    License: Apache License 2.0 5 votes vote down vote up
public static Object getGroovyObjectFieldSpreadSafe(Class senderClass, GroovyObject receiver, String messageName) throws Throwable {
    if (receiver == null) return null;
    List answer = new ArrayList();
    for (Iterator it = InvokerHelper.asIterator(receiver); it.hasNext();) {
        answer.add(getFieldSafe(senderClass, it.next(), messageName));
    }
    return answer;
}
 
Example #18
Source Project: groovy   Author: apache   File: PogoInterceptableSite.java    License: Apache License 2.0 5 votes vote down vote up
public final Object invoke(Object receiver, Object[] args) throws Throwable {
  try {
    return ((GroovyObject)receiver).invokeMethod(name, InvokerHelper.asUnwrappedArray(args));
  } catch (GroovyRuntimeException gre) {
      throw ScriptBytecodeAdapter.unwrap(gre);
  }
}
 
Example #19
Source Project: groovy   Author: apache   File: ScriptBytecodeAdapter.java    License: Apache License 2.0 5 votes vote down vote up
public static void setGroovyObjectField(Object messageArgument, Class senderClass, GroovyObject receiver, String messageName) throws Throwable {
    try {
        receiver.getMetaClass().setAttribute(receiver, messageName, messageArgument);
    } catch (GroovyRuntimeException gre) {
        throw unwrap(gre);
    }
}
 
Example #20
Source Project: groovy   Author: apache   File: ScriptBytecodeAdapter.java    License: Apache License 2.0 5 votes vote down vote up
public static Object invokeMethodOnSuperN(Class senderClass, GroovyObject receiver, String messageName, Object[] messageArguments) throws Throwable {
    MetaClass metaClass = receiver.getMetaClass();
    // ignore interception and missing method fallback
    Object result = null;
    try {
        result = metaClass.invokeMethod(senderClass, receiver, messageName, messageArguments, true, true);
    } catch (GroovyRuntimeException gre) {
        throw unwrap(gre);
    }
    return result;
}
 
Example #21
Source Project: groovy   Author: apache   File: GetEffectivePogoPropertySite.java    License: Apache License 2.0 5 votes vote down vote up
public final Object callGetProperty (Object receiver) throws Throwable {
    if (GroovyCategorySupport.hasCategoryInCurrentThread() || !(receiver instanceof GroovyObject) || ((GroovyObject) receiver).getMetaClass() != metaClass) {
        return createGetPropertySite(receiver).getProperty(receiver);
    } else {
        try {
            return effective.getProperty(receiver);
        } catch (GroovyRuntimeException gre) {
            throw ScriptBytecodeAdapter.unwrap(gre);
        }
    }
}
 
Example #22
Source Project: groovy   Author: apache   File: GetEffectivePogoFieldSite.java    License: Apache License 2.0 5 votes vote down vote up
public final Object callGroovyObjectGetProperty (Object receiver) throws Throwable {
    if (GroovyCategorySupport.hasCategoryInCurrentThread() || ((GroovyObject) receiver).getMetaClass() != metaClass) {
        return createGroovyObjectGetPropertySite(receiver).getProperty(receiver);
    } else {
        return getProperty(receiver);
    }
}
 
Example #23
Source Project: groovy   Author: apache   File: AbstractCallSite.java    License: Apache License 2.0 5 votes vote down vote up
protected final CallSite createGetPropertySite(final Object receiver) {
    if (receiver == null) {
        return new NullCallSite(this);
    } else if (receiver instanceof GroovyObject) {
        return createGroovyObjectGetPropertySite(receiver);
    } else if (receiver instanceof Class) {
        return createClassMetaClassGetPropertySite((Class<?>) receiver);
    }
    return createPojoMetaClassGetPropertySite(receiver);
}
 
Example #24
Source Project: groovy   Author: apache   File: AbstractCallSite.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object callCurrent(final GroovyObject receiver, final Object arg1, final Object arg2) throws Throwable {
    CallSite stored = array.array[index];
    if (stored!=this) {
        return stored.callCurrent(receiver, arg1, arg2);
    }
    return callCurrent(receiver, ArrayUtil.createArray(arg1, arg2));
}
 
Example #25
Source Project: groovy   Author: apache   File: IndyGuardsFiltersAndSignatures.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@link GroovyObject#invokeMethod(String, Object)} path as fallback.
 * This method is called by the handle as exception handler in case the
 * selected method causes a MissingMethodExecutionFailed, where
 * we will just give through the exception, and a normal
 * MissingMethodException where we call {@link GroovyObject#invokeMethod(String, Object)}
 * if receiver class, the type transported by the exception and the name
 * for the method stored in the exception and our current method name
 * are equal.
 * Should those conditions not apply we just rethrow the exception.
 */
public static Object invokeGroovyObjectInvoker(MissingMethodException e, Object receiver, String name, Object[] args) {
    if (e instanceof MissingMethodExecutionFailed) {
        throw (MissingMethodException) e.getCause();
    } else if (receiver.getClass() == e.getType() && e.getMethod().equals(name)) {
        //TODO: we should consider calling this one directly for MetaClassImpl,
        //      then we save the new method selection

        // in case there's nothing else, invoke the object's own invokeMethod()
        return ((GroovyObject) receiver).invokeMethod(name, args);
    } else {
        throw e;
    }
}
 
Example #26
Source Project: Pushjet-Android   Author: Pushjet   File: PatternSetAntBuilderDelegate.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
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", filename);
        groovyObject.invokeMethod("filename", props);
    }
    return node;
}
 
Example #27
Source Project: groovy   Author: apache   File: ScriptBytecodeAdapter.java    License: Apache License 2.0 5 votes vote down vote up
public static Object invokeMethodOnCurrentNSpreadSafe(Class senderClass, GroovyObject receiver, String messageName, Object[] messageArguments) throws Throwable {
    List answer = new ArrayList();
    for (Iterator it = InvokerHelper.asIterator(receiver); it.hasNext();) {
        answer.add(invokeMethodNSafe(senderClass, it.next(), messageName, messageArguments));
    }
    return answer;
}
 
Example #28
Source Project: groovy   Author: apache   File: AbstractCallSite.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object callCurrent(final GroovyObject receiver, final Object arg1) throws Throwable {
    CallSite stored = array.array[index];
    if (stored!=this) {
        return stored.callCurrent(receiver, arg1);
    }
    return callCurrent(receiver, ArrayUtil.createArray(arg1));
}
 
Example #29
Source Project: groovy   Author: apache   File: ScriptBytecodeAdapter.java    License: Apache License 2.0 5 votes vote down vote up
public static Object invokeMethodOnCurrentN(Class senderClass, GroovyObject receiver, String messageName, Object[] messageArguments) throws Throwable {
    Object result = null;
    boolean intercepting = receiver instanceof GroovyInterceptable;
    try {
        try {
            // if it's a pure interceptable object (even intercepting toString(), clone(), ...)
            if (intercepting) {
                result = receiver.invokeMethod(messageName, messageArguments);
            }
            //else if there's a statically typed method or a GDK method
            else {
                result = receiver.getMetaClass().invokeMethod(senderClass, receiver, messageName, messageArguments, false, true);
            }
        } catch (MissingMethodException e) {
            if (e instanceof MissingMethodExecutionFailed) {
                throw (MissingMethodException)e.getCause();
            } else if (!intercepting && receiver.getClass() == e.getType() && e.getMethod().equals(messageName)) {
                // in case there's nothing else, invoke the object's own invokeMethod()
                result = receiver.invokeMethod(messageName, messageArguments);
            } else {
                throw e;
            }
        }
    } catch (GroovyRuntimeException gre) {
        throw unwrap(gre);
    }
    return result;
}
 
Example #30
Source Project: groovy   Author: apache   File: ScriptBytecodeAdapter.java    License: Apache License 2.0 5 votes vote down vote up
public static void setPropertyOnSuper(Object messageArgument, Class senderClass, GroovyObject receiver, String messageName) throws Throwable {
    try {
        InvokerHelper.setAttribute(receiver, messageName, messageArgument);
    } catch (GroovyRuntimeException gre) {
        throw unwrap(gre);
    }
}