Java Code Examples for org.codehaus.groovy.runtime.InvokerHelper

The following examples show how to use org.codehaus.groovy.runtime.InvokerHelper. These examples are extracted from open source projects. 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: BindPath.java    License: Apache License 2.0 6 votes vote down vote up
private Object extractNewValue(Object newObject) {
    Object newValue;
    try {
        newValue = InvokerHelper.getProperty(newObject, propertyName);

    } catch (MissingPropertyException mpe) {
        //todo we should flag this when the path is created that this is a field not a prop...
        // try direct method...
        try {
            newValue = InvokerHelper.getAttribute(newObject, propertyName);
            if (newValue instanceof Reference) {
                newValue = ((Reference) newValue).get();
            }
        } catch (Exception e) {
            //LOGME?
            newValue = null;
        }
    }
    return newValue;
}
 
Example #2
Source Project: groovy   Author: apache   File: MetaClassImpl.java    License: Apache License 2.0 6 votes vote down vote up
private CachedConstructor createCachedConstructor(Object[] arguments) {
    if (arguments == null) arguments = EMPTY_ARGUMENTS;
    Class[] argClasses = MetaClassHelper.convertToTypeArray(arguments);
    MetaClassHelper.unwrap(arguments);
    CachedConstructor constructor = (CachedConstructor) chooseMethod("<init>", constructors, argClasses);
    if (constructor == null) {
        constructor = (CachedConstructor) chooseMethod("<init>", constructors, argClasses);
    }
    if (constructor == null) {
        throw new GroovyRuntimeException(
                "Could not find matching constructor for: "
                        + theClass.getName()
                        + "(" + InvokerHelper.toTypeString(arguments) + ")");
    }
    return constructor;
}
 
Example #3
Source Project: groovy   Author: apache   File: CallSiteArray.java    License: Apache License 2.0 6 votes vote down vote up
private static CallSite createCallStaticSite(CallSite callSite, final Class receiver, Object[] args) {
    AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
        try {
            Class.forName(receiver.getName(), true, receiver.getClassLoader());
        } catch (Exception e) {
            // force <clinit>
        }
        return null;
    });
    MetaClass metaClass = InvokerHelper.getMetaClass(receiver);
    CallSite site =
            metaClass instanceof MetaClassImpl
                    ? ((MetaClassImpl) metaClass).createStaticSite(callSite, args)
                    : new StaticMetaClassSite(callSite, metaClass);

    replaceCallSite(callSite, site);
    return site;
}
 
Example #4
Source Project: groovy   Author: apache   File: GroovyTypeCheckingExtensionSupport.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Object invokeMethod(final String name, final Object args) {
    if (name.startsWith("is") && name.endsWith("Expression") && args instanceof Object[] && ((Object[]) args).length == 1) {
        String type = name.substring(2);
        Object target = ((Object[]) args)[0];
        if (target==null) return false;
        try {
            Class typeClass = Class.forName("org.codehaus.groovy.ast.expr."+type);
            return typeClass.isAssignableFrom(target.getClass());
        } catch (ClassNotFoundException e) {
            return false;
        }
    }
    if (args instanceof Object[] && ((Object[]) args).length == 1 && ((Object[]) args)[0] instanceof Closure) {
        Object[] argsArray = (Object[]) args;
        String methodName = METHOD_ALIASES.get(name);
        if (methodName == null) {
            return InvokerHelper.invokeMethod(extension, name, args);
        }
        List<Closure> closures = extension.eventHandlers.computeIfAbsent(methodName, k -> new LinkedList<Closure>());
        closures.add((Closure) argsArray[0]);
        return null;
    } else {
        return InvokerHelper.invokeMethod(extension, name, args);
    }
}
 
Example #5
Source Project: groovy   Author: apache   File: MetaClassTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testSetPropertyWithArray() {
    DymmyClass dymmyClass = new DymmyClass();
    MetaClass metaClass = InvokerHelper.getMetaClass(dymmyClass);

    // test int[]
    int[] ints = new int[]{
            0, 1, 2, 3
    };
    metaClass.setProperty(dymmyClass, "ints", ints);
    assertEquals(ints, metaClass.getProperty(dymmyClass, "ints"));

    // test Integer[]
    Integer[] integers = new Integer[]{
            Integer.valueOf(0), Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3)
    };
    metaClass.setProperty(dymmyClass, "integers", integers);
    assertEquals(integers, metaClass.getProperty(dymmyClass, "integers"));
}
 
Example #6
Source Project: groovy   Author: apache   File: NioExtensions.java    License: Apache License 2.0 6 votes vote down vote up
private static void appendBuffered(Path file, Object text, String charset, boolean writeBom) throws IOException {
    BufferedWriter writer = null;
    try {
        boolean shouldWriteBom = writeBom && !file.toFile().exists();
        writer = newWriter(file, charset, true);
        if (shouldWriteBom) {
            writeUTF16BomIfRequired(writer, charset);
        }
        InvokerHelper.write(writer, text);
        writer.flush();

        Writer temp = writer;
        writer = null;
        temp.close();
    } finally {
        closeWithWarning(writer);
    }
}
 
Example #7
Source Project: groovy   Author: apache   File: CachingGroovyEngine.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Evaluate an expression.
 */
public Object eval(String source, int lineNo, int columnNo, Object script) throws BSFException {
    try {
        Class scriptClass = evalScripts.get(script);
        if (scriptClass == null) {
            scriptClass = loader.parseClass(script.toString(), source);
            evalScripts.put(script, scriptClass);
        } else {
            LOG.fine("eval() - Using cached script...");
        }
        //can't cache the script because the context may be different.
        //but don't bother loading parsing the class again
        Script s = InvokerHelper.createScript(scriptClass, context);
        return s.run();
    } catch (Exception e) {
        throw new BSFException(BSFException.REASON_EXECUTION_ERROR, "exception from Groovy: " + e, e);
    }
}
 
Example #8
Source Project: groovy   Author: apache   File: PluginDefaultGroovyMethods.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Overloads the {@code ++} operator for enums. It will invoke Groovy's
 * default next behaviour for enums that do not have their own next method.
 *
 * @param self an Enum
 * @return the next defined enum from the enum class
 *
 * @since 1.5.2
 */
public static Object next(final Enum self) {
    for (Method method : self.getClass().getMethods()) {
        if (method.getName().equals("next") && method.getParameterCount() == 0) {
            return InvokerHelper.invokeMethod(self, "next", InvokerHelper.EMPTY_ARGS);
        }
    }
    Object[] values = (Object[]) InvokerHelper.invokeStaticMethod(self.getClass(), "values", InvokerHelper.EMPTY_ARGS);
    int index = Arrays.asList(values).indexOf(self);
    return values[index < values.length - 1 ? index + 1 : 0];
}
 
Example #9
Source Project: groovy   Author: apache   File: TestSupport.java    License: Apache License 2.0 5 votes vote down vote up
protected void assertScript(final String text, final String scriptName) throws Exception {
    log.info("About to execute script");
    log.info(text);
    GroovyCodeSource gcs = AccessController.doPrivileged(
            (PrivilegedAction<GroovyCodeSource>) () -> new GroovyCodeSource(text, scriptName, "/groovy/testSupport")
    );
    Class groovyClass = loader.parseClass(gcs);
    Script script = InvokerHelper.createScript(groovyClass, new Binding());
    script.run();
}
 
Example #10
Source Project: arcusplatform   Author: arcus-smart-home   File: DriverBinding.java    License: Apache License 2.0 5 votes vote down vote up
private void init() {
   // by default our getMetaClass will be generate from this class, but we
   // don't want to expose member variable, so drop down to Binding
   setMetaClass(InvokerHelper.getMetaClass(Binding.class));
   // TODO move this to DriverBindingMetaClass
   setProperty("driver", new SetName());
   setProperty("description", new SetDescription());
   setProperty("version", new SetVersion());
   setProperty("commit", new SetCommit());
   setProperty("populations", new SetPopulations());

   setProperty("deviceTypeHint", new SetAttribute(DriverConstants.DEV_ATTR_DEF_DEVTYPEHINT));
   setProperty("productId", new SetAttribute(DriverConstants.DEV_ATTR_DEF_PRODUCTID));
   setProperty("vendor", new SetAttribute(DriverConstants.DEV_ATTR_DEF_VENDOR));
   setProperty("model", new SetAttribute(DriverConstants.DEV_ATTR_DEF_MODEL));
   setProperty("protocol", new SetAttribute(DriverConstants.DEVADV_ATTR_DEF_PROTOCOL));
   setProperty("subprotocol", new SetAttribute(DriverConstants.DEVADV_ATTR_DEF_SUBPROTOCOL));

   setProperty("matcher", new SetMatcher());
   setProperty("capabilities", new SetCapabilities());
   setProperty("configure", new ConfigureAttributes());
   setProperty("instance", new AddInstanceMethod());

   ImportCapability importer = new ImportCapability();
   setProperty("importCapability", importer);
   setProperty("uses", importer);

   // most event handlers are added as meta function on DriverScriptMetaClass
   // these are added here because they are closures with attributes, not just
   // methods, and full closures have to be assigned for each object
   for(CapabilityDefinition definition: capabilityRegistry.listCapabilityDefinitions()) {
      setProperty("on" + definition.getCapabilityName(), new OnCapabilityClosure(definition, this));
   }
}
 
Example #11
Source Project: groovy   Author: apache   File: MetaClassTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testSetPropertyWithDoubleArray() {
    DymmyClass dymmyClass = new DymmyClass();
    MetaClass metaClass = InvokerHelper.getMetaClass(dymmyClass);
    Double[][] matrix2 =
            {
                    {
                            new Double(35), new Double(50), new Double(120)
                    },
                    {
                            new Double(75), new Double(80), new Double(150)
                    }
            };
    metaClass.setProperty(dymmyClass, "matrix", matrix2);
    metaClass.setProperty(dymmyClass, "matrix2", matrix2);
}
 
Example #12
Source Project: groovy   Author: apache   File: GroovyTypeCheckingExtensionSupport.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void setProperty(final String property, final Object newValue) {
    try {
        InvokerHelper.setProperty(extension, property, newValue);
    } catch (Exception e) {
        super.setProperty(property, newValue);
    }
}
 
Example #13
Source Project: groovy   Author: apache   File: DefaultTypeTransformation.java    License: Apache License 2.0 5 votes vote down vote up
public static Collection asCollection(Object value) {
    if (value == null) {
        return Collections.EMPTY_LIST;
    } else if (value instanceof Collection) {
        return (Collection) value;
    } else if (value instanceof Map) {
        Map map = (Map) value;
        return map.entrySet();
    } else if (value.getClass().isArray()) {
        return arrayAsCollection(value);
    } else if (value instanceof MethodClosure) {
        MethodClosure method = (MethodClosure) value;
        IteratorClosureAdapter adapter = new IteratorClosureAdapter(method.getDelegate());
        method.call(adapter);
        return adapter.asList();
    } else if (value instanceof String || value instanceof GString) {
        return StringGroovyMethods.toList((CharSequence) value);
    } else if (value instanceof File) {
        try {
            return ResourceGroovyMethods.readLines((File) value);
        } catch (IOException e) {
            throw new GroovyRuntimeException("Error reading file: " + value, e);
        }
    } else if (value instanceof Class && ((Class) value).isEnum()) {
        Object[] values = (Object[]) InvokerHelper.invokeMethod(value, "values", EMPTY_OBJECT_ARRAY);
        return Arrays.asList(values);
    } else {
        // let's assume it's a collection of 1
        return Collections.singletonList(value);
    }
}
 
Example #14
Source Project: groovy   Author: apache   File: ForTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testLoop() throws Exception {
    ClassNode classNode = new ClassNode("Foo", ACC_PUBLIC, ClassHelper.OBJECT_TYPE);
    classNode.addConstructor(new ConstructorNode(ACC_PUBLIC, null));

    Parameter[] parameters = {new Parameter(ClassHelper.OBJECT_TYPE.makeArray(), "coll")};

    Statement loopStatement = createPrintlnStatement(new VariableExpression("i"));

    ForStatement statement = new ForStatement(new Parameter(ClassHelper.OBJECT_TYPE, "i"), new VariableExpression("coll"), loopStatement);
    classNode.addMethod(new MethodNode("iterateDemo", ACC_PUBLIC, ClassHelper.VOID_TYPE, parameters, ClassNode.EMPTY_ARRAY, statement));

    Class fooClass = loadClass(classNode);
    assertTrue("Loaded a new class", fooClass != null);

    Object bean = fooClass.getDeclaredConstructor().newInstance();
    assertTrue("Managed to create bean", bean != null);

    System.out.println("################ Now about to invoke a method with looping");
    Object[] array = {Integer.valueOf(1234), "abc", "def"};

    try {
        InvokerHelper.invokeMethod(bean, "iterateDemo", new Object[]{array});
    } catch (InvokerInvocationException e) {
        System.out.println("Caught: " + e.getCause());
        e.getCause().printStackTrace();
        fail("Should not have thrown an exception");
    }
    System.out.println("################ Done");
}
 
Example #15
Source Project: groovy   Author: apache   File: GroovyTestCase.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Asserts that the arrays are equivalent and contain the same values
 *
 * @param expected
 * @param value
 */
protected void assertArrayEquals(Object[] expected, Object[] value) {
    String message =
            "expected array: " + InvokerHelper.toString(expected) + " value array: " + InvokerHelper.toString(value);
    assertNotNull(message + ": expected should not be null", expected);
    assertNotNull(message + ": value should not be null", value);
    assertEquals(message, expected.length, value.length);
    for (int i = 0, size = expected.length; i < size; i++) {
        assertEquals("value[" + i + "] when " + message, expected[i], value[i]);
    }
}
 
Example #16
Source Project: groovy   Author: apache   File: XmlUtil.java    License: Apache License 2.0 5 votes vote down vote up
private static String asString(GPathResult node) {
    // little bit of hackery to avoid Groovy dependency in this file
    try {
        Object builder = Class.forName("groovy.xml.StreamingMarkupBuilder").getDeclaredConstructor().newInstance();
        InvokerHelper.setProperty(builder, "encoding", "UTF-8");
        Writable w = (Writable) InvokerHelper.invokeMethod(builder, "bindNode", node);
        return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + w.toString();
    } catch (Exception e) {
        return "Couldn't convert node to string because: " + e.getMessage();
    }
}
 
Example #17
Source Project: groovy   Author: apache   File: NumberMathModificationInfo.java    License: Apache License 2.0 4 votes vote down vote up
private static int multiplySlow(byte op1, byte op2) {
    return ((Number) InvokerHelper.invokeMethod(op1, "multiply", op2)).intValue();
}
 
Example #18
Source Project: groovy   Author: apache   File: NumberMathModificationInfo.java    License: Apache License 2.0 4 votes vote down vote up
private static double plusSlow(short op1, float op2) {
    return ((Number) InvokerHelper.invokeMethod(op1, "plus", op2)).doubleValue();
}
 
Example #19
Source Project: groovy   Author: apache   File: NumberMathModificationInfo.java    License: Apache License 2.0 4 votes vote down vote up
private static long orSlow(short op1, long op2) {
    return ((Number) InvokerHelper.invokeMethod(op1, "or", op2)).longValue();
}
 
Example #20
Source Project: groovy   Author: apache   File: NumberMathModificationInfo.java    License: Apache License 2.0 4 votes vote down vote up
private static long intdivSlow(int op1, long op2) {
    return ((Number) InvokerHelper.invokeMethod(op1, "intdiv", op2)).longValue();
}
 
Example #21
Source Project: groovy   Author: apache   File: PropertyModel.java    License: Apache License 2.0 4 votes vote down vote up
public void setValue(Object value) {
    Object source = sourceModel.getValue();
    if (source != null) {
        InvokerHelper.setProperty(source, property, value);
    }
}
 
Example #22
Source Project: java-technology-stack   Author: codeEngraver   File: GroovyBeanDefinitionReader.java    License: MIT License 4 votes vote down vote up
public GroovyRuntimeBeanReference(String beanName, GroovyBeanDefinitionWrapper beanDefinition, boolean toParent) {
	super(beanName, toParent);
	this.beanDefinition = beanDefinition;
	this.metaClass = InvokerHelper.getMetaClass(this);
}
 
Example #23
Source Project: groovy   Author: apache   File: NumberMathModificationInfo.java    License: Apache License 2.0 4 votes vote down vote up
private static int minusSlow(int op1, short op2) {
    return ((Number) InvokerHelper.invokeMethod(op1, "minus", op2)).intValue();
}
 
Example #24
Source Project: groovy   Author: apache   File: NumberMathModificationInfo.java    License: Apache License 2.0 4 votes vote down vote up
private static long rightShiftSlow(long op1, long op2) {
    return ((Number) InvokerHelper.invokeMethod(op1, "rightShift", op2)).longValue();
}
 
Example #25
Source Project: groovy   Author: apache   File: NumberMathModificationInfo.java    License: Apache License 2.0 4 votes vote down vote up
private static int orSlow(short op1, int op2) {
    return ((Number) InvokerHelper.invokeMethod(op1, "or", op2)).intValue();
}
 
Example #26
Source Project: groovy   Author: apache   File: NumberMathModificationInfo.java    License: Apache License 2.0 4 votes vote down vote up
private static int modSlow(byte op1, short op2) {
    return ((Number) InvokerHelper.invokeMethod(op1, "mod", op2)).intValue();
}
 
Example #27
Source Project: groovy   Author: apache   File: NumberMathModificationInfo.java    License: Apache License 2.0 4 votes vote down vote up
private static double multiplySlow(double op1, short op2) {
    return ((Number) InvokerHelper.invokeMethod(op1, "multiply", op2)).doubleValue();
}
 
Example #28
Source Project: groovy   Author: apache   File: NumberMathModificationInfo.java    License: Apache License 2.0 4 votes vote down vote up
private static int xorSlow(short op1, int op2) {
    return ((Number) InvokerHelper.invokeMethod(op1, "xor", op2)).intValue();
}
 
Example #29
Source Project: groovy   Author: apache   File: NumberMathModificationInfo.java    License: Apache License 2.0 4 votes vote down vote up
private static int multiplySlow(byte op1, short op2) {
    return ((Number) InvokerHelper.invokeMethod(op1, "multiply", op2)).intValue();
}
 
Example #30
Source Project: pushfish-android   Author: PushFish   File: HtmlRenderContext.java    License: BSD 2-Clause "Simplified" License 4 votes vote down vote up
private boolean groovyTrue(Object equal) {
    return (Boolean) InvokerHelper.invokeMethod(equal, "asBoolean", null);
}