org.codehaus.groovy.runtime.MethodClosure Java Examples

The following examples show how to use org.codehaus.groovy.runtime.MethodClosure. 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: ExceptionReportServiceBean.java    From cuba with Apache License 2.0 6 votes vote down vote up
@Override
public void sendExceptionReport(String supportEmail, Map<String, Object> binding) {
    try {
        Map<String, Object> map = new HashMap<>(binding);
        User user = userSessionSource.getUserSession().getUser();
        map.put("user", user);
        map.put("toHtml", new MethodClosure(HtmlUtils.class, "convertToHtml"));

        String body = getExceptionReportBody(map);
        String subject = getExceptionReportSubject(map);

        EmailInfo info = EmailInfoBuilder.create()
                .setAddresses(supportEmail)
                .setCaption(subject)
                .setBody(body)
                .build();

        emailer.sendEmail(info);
    } catch (Exception e) {
        log.error("Error sending exception report", e);
        throw new RuntimeException("Error sending exception report");
    }
}
 
Example #2
Source File: GroovyTemplateEngine.java    From jbake with MIT License 6 votes vote down vote up
private Map<String, Object> wrap(final Map<String, Object> model) {
    return new HashMap<String, Object>(model) {
        @Override
        public Object get(final Object property) {
            if (property instanceof String || property instanceof GString) {
                String key = property.toString();
                if ("include".equals(key)) {
                    return new MethodClosure(GroovyTemplateEngine.this, "doInclude").curry(this);
                }
                try {
                    return extractors.extractAndTransform(db, key, model, new TemplateEngineAdapter.NoopAdapter());
                } catch (NoModelExtractorException e) {
                    // fallback to parent model
                }
            }

            return super.get(property);
        }
    };
}
 
Example #3
Source File: GroovyEvaluator.java    From jasperreports with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected void addFunctionClosureMethods(MethodClosure methodClosure, String functionName)
{
	// calling registerInstanceMethod(String, Closure) would register all methods, but we only want public methods
	List<MetaMethod> closureMethods = ClosureMetaMethod.createMethodList(functionName, getClass(), methodClosure);
	for (MetaMethod metaMethod : closureMethods)
	{
		if (!(metaMethod instanceof ClosureMetaMethod))
		{
			// should not happen
			log.warn("Got unexpected closure method " + metaMethod + " of type " + metaMethod.getClass().getName());
			continue;
		}
		
		ClosureMetaMethod closureMethod = (ClosureMetaMethod) metaMethod;
		if (!closureMethod.getDoCall().isPublic())
		{
			if (log.isDebugEnabled())
			{
				log.debug("method " + closureMethod.getDoCall() + " is not public, not registering");
			}
			continue;
		}
		
		if (log.isDebugEnabled())
		{
			log.debug("creating closure method for " + closureMethod.getDoCall());
		}
		
		functionMethods.add(closureMethod);
	}
}
 
Example #4
Source File: PersistenceSecurityImpl.java    From cuba with Apache License 2.0 5 votes vote down vote up
protected Object runGroovyScript(Entity entity, String groovyScript) {
    Map<String, Object> context = new HashMap<>();
    context.put("__entity__", entity);
    context.put("parse", new MethodClosure(this, "parseValue"));
    context.put("userSession", userSessionSource.getUserSession());
    fillGroovyConstraintsContext(context);
    return scripting.evaluateGroovy(groovyScript.replace("{E}", "__entity__"), context);
}
 
Example #5
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 #6
Source File: ScriptTest.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * When a method is not found in the current script, checks that it's possible to call a method closure from the binding.
 *
 * @throws IOException
 * @throws CompilationFailedException
 * @throws IllegalAccessException
 * @throws InstantiationException
 */
public void testInvokeMethodFallsThroughToMethodClosureInBinding() throws IOException, CompilationFailedException, IllegalAccessException, InstantiationException {
    String text = "if (method() == 3) { println 'succeeded' }";

    GroovyCodeSource codeSource = new GroovyCodeSource(text, "groovy.script", "groovy.script");
    GroovyClassLoader loader = new GroovyClassLoader(Thread.currentThread().getContextClassLoader());
    Class clazz = loader.parseClass(codeSource);
    Script script = ((Script) clazz.newInstance());

    Binding binding = new Binding();
    binding.setVariable("method", new MethodClosure(new Dummy(), "method"));
    script.setBinding(binding);

    script.run();
}
 
Example #7
Source File: Word2VecDemo.java    From COMP6237 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Component getComponent(int width, int height) throws IOException {
	final Component comp = super.getComponent(width, height);
	binding.setVariable("w2v", new MethodClosure(this, "w2v"));
	binding.setVariable("v2w", new MethodClosure(this, "v2w"));
	binding.setVariable("nn", new MethodClosure(this, "nn"));
	binding.setVariable("help", new MethodClosure(this, "help"));

	return comp;
}
 
Example #8
Source File: MetaClassImpl.java    From groovy with Apache License 2.0 4 votes vote down vote up
private Object invokeMethodClosure(Object object, Object[] arguments) {
    final MethodClosure mc = (MethodClosure) object;
    final Object owner = mc.getOwner();

    String methodName = mc.getMethod();
    final Class ownerClass = owner instanceof Class ? (Class) owner : owner.getClass();
    final MetaClass ownerMetaClass = registry.getMetaClass(ownerClass);

    // To conform to "Least Surprise" principle, try to invoke method with original arguments first, which can match most of use cases
    try {
        return ownerMetaClass.invokeMethod(ownerClass, owner, methodName, arguments, false, false);
    } catch (MissingMethodExceptionNoStack | InvokerInvocationException e) {
        // CONSTRUCTOR REFERENCE
        if (owner instanceof Class && MethodClosure.NEW.equals(methodName)) {
            if (ownerClass.isArray()) {
                if (0 == arguments.length) {
                    throw new GroovyRuntimeException("The arguments(specifying size) are required to create array[" + ownerClass.getCanonicalName() + "]");
                }

                int arrayDimension = ArrayTypeUtils.dimension(ownerClass);

                if (arguments.length > arrayDimension) {
                    throw new GroovyRuntimeException("The length[" + arguments.length + "] of arguments should not be greater than the dimensions[" + arrayDimension + "] of array[" + ownerClass.getCanonicalName() + "]");
                }

                int[] sizeArray = new int[arguments.length];

                for (int i = 0, n = sizeArray.length; i < n; i++) {
                    Object argument = arguments[i];

                    if (argument instanceof Integer) {
                        sizeArray[i] = (Integer) argument;
                    } else {
                        sizeArray[i] = Integer.parseInt(String.valueOf(argument));
                    }
                }

                Class arrayType =
                        arguments.length == arrayDimension
                                ? ArrayTypeUtils.elementType(ownerClass) // Just for better performance, though we can use reduceDimension only
                                : ArrayTypeUtils.elementType(ownerClass, (arrayDimension - arguments.length));
                return Array.newInstance(arrayType, sizeArray);
            }

            return ownerMetaClass.invokeConstructor(arguments);
        }

        // METHOD REFERENCE
        // if and only if the owner is a class and the method closure can be related to some instance methods,
        // try to invoke method with adjusted arguments(first argument is the actual owner) again.
        // otherwise throw the MissingMethodExceptionNoStack.
        if (!(owner instanceof Class
                && (Boolean) mc.getProperty(MethodClosure.ANY_INSTANCE_METHOD_EXISTS))) {

            throw e;
        }

        if (arguments.length <= 0 || !(arguments[0].getClass().equals(ownerClass))) {
            return invokeMissingMethod(object, methodName, arguments);
        }

        Object newOwner = arguments[0];
        Object[] newArguments = Arrays.copyOfRange(arguments, 1, arguments.length);
        return ownerMetaClass.invokeMethod(ownerClass, newOwner, methodName, newArguments, false, false);
    }
}
 
Example #9
Source File: Groovy4104A.java    From groovy with Apache License 2.0 4 votes vote down vote up
public MethodClosure createMethodClosure() {
    return new MethodClosure(this, "someMethod");
}
 
Example #10
Source File: GroovyConsoleSlide.java    From COMP6237 with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public void installInterceptors() {
	systemOutInterceptor = new SystemOutputInterceptor(new MethodClosure(this, "notifySystemOut"), true);
	systemOutInterceptor.start();
	systemErrorInterceptor = new SystemOutputInterceptor(new MethodClosure(this, "notifySystemErr"), false);
	systemErrorInterceptor.start();
}
 
Example #11
Source File: MethodEffector.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
/**
 * @deprecated since 0.11.0; explicit groovy utilities/support will be deleted.
 */
@Deprecated
public MethodEffector(MethodClosure mc) {
    this(new AnnotationsOnMethod((Class<?>)mc.getDelegate(), mc.getMethod()), null);
}
 
Example #12
Source File: DefaultInvoker.java    From groovy-cps with Apache License 2.0 4 votes vote down vote up
public Object methodPointer(Object lhs, String name) {
    return new MethodClosure(lhs, name);
}
 
Example #13
Source File: Interactive.java    From beakerx with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public static void interact(MethodClosure function, Object... parameters) {

  final List<ValueWidget<?>> widgets = widgetsFromAbbreviations(parameters);

  for (ValueWidget<?> widget : widgets) {
    widget.getComm().addMsgCallbackList(widget.new ValueChangeMsgCallbackHandler() {

      private void processCode(Object... params) throws Exception {
        Object call = function.call(getWidgetValues());
        if (call instanceof String || call instanceof Number) {
          label.setValue(call);
        }
      }

      @Override
      public void updateValue(Object value, Message message) {
        try {
          processCode();
        } catch (Exception e) {
          throw new IllegalStateException("Error occurred during updating interactive widget.", e);
        }
      }

      private Object[] getWidgetValues() {
        List<Object> ret = new ArrayList<>(widgets.size());
        for (ValueWidget<?> wid : widgets) {
          ret.add(wid.getValue());
        }
        return ret.toArray(new Object[ret.size()]);
      }

    });
    logger.info("interact Widget: " + widget.getClass().getName());
  }

  widgets.forEach(Widget::display);
  Object response = function.call(widgets.stream().map(ValueWidget::getValue).toArray());
  if (response instanceof Widget) {
    ((Widget) response).display();
  } else {
    label = new Label();
    label.setValue(response);
    label.display();
  }
}
 
Example #14
Source File: Groovy1.java    From ysoserial-modified with MIT License 3 votes vote down vote up
public InvocationHandler getObject(CmdExecuteHelper cmdHelper) throws Exception {
	final ConvertedClosure closure = new ConvertedClosure(new MethodClosure(cmdHelper.getCommand(), "execute"), "entrySet");
	
	final Map map = Gadgets.createProxy(closure, Map.class);		

	final InvocationHandler handler = Gadgets.createMemoizedInvocationHandler(map);
	
	return handler;
}
 
Example #15
Source File: Groovy1.java    From JavaSerialKiller with MIT License 3 votes vote down vote up
public InvocationHandler getObject(final String command) throws Exception {
	final ConvertedClosure closure = new ConvertedClosure(new MethodClosure(command, "execute"), "entrySet");
	
	final Map map = Gadgets.createProxy(closure, Map.class);		

	final InvocationHandler handler = Gadgets.createMemoizedInvocationHandler(map);
	
	return handler;
}
 
Example #16
Source File: Groovy1.java    From ysoserial with MIT License 3 votes vote down vote up
public InvocationHandler getObject(final String command) throws Exception {
	final ConvertedClosure closure = new ConvertedClosure(new MethodClosure(command, "execute"), "entrySet");

	final Map map = Gadgets.createProxy(closure, Map.class);

	final InvocationHandler handler = Gadgets.createMemoizedInvocationHandler(map);

	return handler;
}