org.codehaus.groovy.runtime.InvokerHelper Java Examples

The following examples show how to use org.codehaus.groovy.runtime.InvokerHelper. 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 File: CallSiteArray.java    From groovy with 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 #2
Source File: NioExtensions.java    From groovy with 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 #3
Source File: MetaClassImpl.java    From groovy with 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 #4
Source File: MetaClassTest.java    From groovy with 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 #5
Source File: BindPath.java    From groovy with 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 #6
Source File: GroovyTypeCheckingExtensionSupport.java    From groovy with 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 #7
Source File: CachingGroovyEngine.java    From groovy with 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 File: XmlUtil.java    From groovy with 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 #9
Source File: ForTest.java    From groovy with 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 #10
Source File: GroovyTypeCheckingExtensionSupport.java    From groovy with 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 #11
Source File: MetaClassTest.java    From groovy with 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 File: DriverBinding.java    From arcusplatform with 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 #13
Source File: TestSupport.java    From groovy with 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 #14
Source File: GroovyTestCase.java    From groovy with 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 #15
Source File: DefaultTypeTransformation.java    From groovy with 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 #16
Source File: PluginDefaultGroovyMethods.java    From groovy with 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 #17
Source File: XmlTemplateEngine.java    From groovy with Apache License 2.0 4 votes vote down vote up
protected void printSimpleItem(Object value) {
    this.printLineBegin();
    out.print(escapeSpecialChars(InvokerHelper.toString(value)));
    printLineEnd();
}
 
Example #18
Source File: NumberMathModificationInfo.java    From groovy with Apache License 2.0 4 votes vote down vote up
private static int plusSlow(short op1, short op2) {
    return ((Number) InvokerHelper.invokeMethod(op1, "plus", op2)).intValue();
}
 
Example #19
Source File: NumberMathModificationInfo.java    From groovy with Apache License 2.0 4 votes vote down vote up
private static long minusSlow(long op1, long op2) {
    return ((Number) InvokerHelper.invokeMethod(op1, "minus", op2)).longValue();
}
 
Example #20
Source File: NumberMathModificationInfo.java    From groovy with Apache License 2.0 4 votes vote down vote up
private static double multiplySlow(float op1, float op2) {
    return ((Number) InvokerHelper.invokeMethod(op1, "multiply", op2)).doubleValue();
}
 
Example #21
Source File: NumberMathModificationInfo.java    From groovy with Apache License 2.0 4 votes vote down vote up
private static long rightShiftUnsignedSlow(long op1, short op2) {
    return ((Number) InvokerHelper.invokeMethod(op1, "rightShiftUnsigned", op2)).longValue();
}
 
Example #22
Source File: NumberMathModificationInfo.java    From groovy with Apache License 2.0 4 votes vote down vote up
private static double divSlow(double op1, double op2) {
    return ((Number) InvokerHelper.invokeMethod(op1, "div", op2)).doubleValue();
}
 
Example #23
Source File: MultipleSetterProperty.java    From groovy with Apache License 2.0 4 votes vote down vote up
@Override
public void setProperty(Object object, Object newValue) {
    InvokerHelper.getMetaClass(object).invokeMethod(object, setterName, new Object[]{newValue});
}
 
Example #24
Source File: NumberMathModificationInfo.java    From groovy with Apache License 2.0 4 votes vote down vote up
private static double minusSlow(float op1, float op2) {
    return ((Number) InvokerHelper.invokeMethod(op1, "minus", op2)).doubleValue();
}
 
Example #25
Source File: NumberMathModificationInfo.java    From groovy with Apache License 2.0 4 votes vote down vote up
private static long orSlow(long op1, short op2) {
    return ((Number) InvokerHelper.invokeMethod(op1, "or", op2)).longValue();
}
 
Example #26
Source File: NumberMathModificationInfo.java    From groovy with Apache License 2.0 4 votes vote down vote up
private static long leftShiftSlow(int op1, long op2) {
    return ((Number) InvokerHelper.invokeMethod(op1, "leftShift", op2)).longValue();
}
 
Example #27
Source File: EventTriggerBinding.java    From groovy with Apache License 2.0 4 votes vote down vote up
public void bind() {
    InvokerHelper.setProperty(triggerBean, eventName, handler);
}
 
Example #28
Source File: GroovyBeanDefinitionReader.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
public Object invokeMethod(String name, Object args) {
	return InvokerHelper.invokeMethod(this.propertyValue, name, args);
}
 
Example #29
Source File: NumberMathModificationInfo.java    From groovy with Apache License 2.0 4 votes vote down vote up
private static int divSlow(byte op1, short op2) {
    return ((Number) InvokerHelper.invokeMethod(op1, "div", op2)).intValue();
}
 
Example #30
Source File: GroovyBeanDefinitionReader.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
public boolean add(Object value) {
	boolean retVal = (Boolean) InvokerHelper.invokeMethod(this.propertyValue, "add", value);
	updateDeferredProperties(value);
	return retVal;
}