本文整理汇总了Java中org.codehaus.groovy.runtime.MethodClosure类的典型用法代码示例。如果您正苦于以下问题:Java MethodClosure类的具体用法?Java MethodClosure怎么用?Java MethodClosure使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
MethodClosure类属于org.codehaus.groovy.runtime包,在下文中一共展示了MethodClosure类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: wrap
import org.codehaus.groovy.runtime.MethodClosure; //导入依赖的package包/类
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);
}
};
}
示例2: sendExceptionReport
import org.codehaus.groovy.runtime.MethodClosure; //导入依赖的package包/类
@Override
public void sendExceptionReport(String supportEmail, Map<String, Object> binding) {
try {
Map<String, Object> map = new HashMap<>();
map.putAll(binding);
map.put("toHtml", new MethodClosure(HtmlUtils.class, "convertToHtml"));
String body = getExceptionReportBody(map);
String subject = getExceptionReportSubject(map);
EmailInfo info = new EmailInfo(supportEmail, subject, body);
User user = userSessionSource.getUserSession().getUser();
if (user.getEmail() != null) {
info.setFrom(user.getEmail());
}
emailer.sendEmail(info);
} catch (Exception e) {
log.error("Error sending exception report", e);
throw new RuntimeException("Error sending exception report");
}
}
示例3: testClosuresSleep
import org.codehaus.groovy.runtime.MethodClosure; //导入依赖的package包/类
@Test
public void testClosuresSleep() throws Exception {
final SleepMethodSupport sleepMethodSupport = new SleepMethodSupport();
HashMap<String, Object> args = new HashMap<String, Object>() {
{
put("sleepMethodSupport", sleepMethodSupport);
put("_sleep", new MethodClosure(sleepMethodSupport, "_sleep"));
}
};
final Script script = createScript("sleep(1000);_sleep(1000);sleepMethodSupport._sleep(1000)", args);
final AtomicInteger counter = new AtomicInteger(0);
Fiber fiber = new Fiber(scheduler, new SuspendableRunnable() {
@Override
public void run() throws SuspendExecution, InterruptedException {
counter.incrementAndGet();
script.run();
counter.incrementAndGet();
}
});
fiber.start();
fiber.join();
Assert.assertEquals(counter.intValue(), 2);
}
示例4: interact
import org.codehaus.groovy.runtime.MethodClosure; //导入依赖的package包/类
@SuppressWarnings("unchecked")
public static synchronized void interact(MethodClosure function, Object... parameters) {
final MessageCreator mc = new MessageCreator(KernelManager.get());
final List<ValueWidget<?>> witgets = widgetsFromAbbreviations(parameters);
for (ValueWidget<?> widget : witgets) {
widget.getComm().addMsgCallbackList(widget.new ValueChangeMsgCallbackHandler() {
@Override
public void updateValue(Object value, Message message) {
SimpleEvaluationObject seo = new SimpleEvaluationObject("",(seoResult) -> {
//nothing to do
});
seo.setJupyterMessage(message);
seo.setOutputHandler();
seo.addObserver(KernelManager.get().getExecutionResultSender());
InternalVariable.setValue(seo);
KernelManager.get().publish(mc.buildClearOutput(message, true));
Object result = function.call(getWidgetValues());
seo.clrOutputHandler();
MIMEContainer resultString = SerializeToString.doit(result);
logger.info("interact result is = " + resultString.getMime());
KernelManager.get().publish(mc.buildDisplayData(message, resultString));
}
private Object[] getWidgetValues(){
List<Object> ret = new ArrayList<>(witgets.size());
for (ValueWidget<?> wid : witgets) {
ret.add(wid.getValue());
}
return ret.toArray(new Object[ret.size()]);
}
});
logger.info("interact Widget: " + widget.getClass().getName());
widget.display();
}
}
示例5: addFunctionClosureMethods
import org.codehaus.groovy.runtime.MethodClosure; //导入依赖的package包/类
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);
}
}
示例6: evaluateConstraintScript
import org.codehaus.groovy.runtime.MethodClosure; //导入依赖的package包/类
@Override
public Object evaluateConstraintScript(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);
}
示例7: asCollection
import org.codehaus.groovy.runtime.MethodClosure; //导入依赖的package包/类
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);
}
}
示例8: testInvokeMethodFallsThroughToMethodClosureInBinding
import org.codehaus.groovy.runtime.MethodClosure; //导入依赖的package包/类
/**
* 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();
}
示例9: copyMethodsToMetaClass
import org.codehaus.groovy.runtime.MethodClosure; //导入依赖的package包/类
private void copyMethodsToMetaClass(final Expression from, final String methodName) {
Expression thisMetaClass = new PropertyExpression(THIS_EXPRESSION, "metaClass");
Expression methodPointer = constructorOf(MethodClosure.class, from, new ConstantExpression(methodName));
addToInitializerBlock(new BinaryExpression(
new PropertyExpression(thisMetaClass, methodName),
EQUAL_TOKEN,
methodPointer));
}
示例10: main
import org.codehaus.groovy.runtime.MethodClosure; //导入依赖的package包/类
/**
* Main entry point to the client execution.
*
* @param args Command line arguments
* @throws Exception
*/
public static void main (String[] args) throws Exception {
System.setProperty("groovysh.prompt", Constants.SQOOP_PROMPT);
Groovysh shell = new Groovysh();
// Install our error hook (exception handling)
shell.setErrorHook(new MethodClosure(ThrowableDisplayer.class, "errorHook"));
CommandRegistry registry = shell.getRegistry();
@SuppressWarnings("unchecked")
Iterator<Command> iterator = registry.iterator();
while (iterator.hasNext()) {
Command command = iterator.next();
if (!commandsToKeep.contains(command.getName())) {
iterator.remove();
// remove from "names" set to avoid duplicate error.
registry.remove(command);
}
}
shell.register(new HelpCommand(shell));
shell.register(new SetCommand(shell));
shell.register(new ShowCommand(shell));
shell.register(new CreateCommand(shell));
shell.register(new DeleteCommand(shell));
shell.register(new UpdateCommand(shell));
shell.register(new CloneCommand(shell));
shell.register(new StartCommand(shell));
shell.register(new StopCommand(shell));
shell.register(new StatusCommand(shell));
shell.register(new EnableCommand(shell));
shell.register(new DisableCommand(shell));
shell.register(new GrantCommand(shell));
shell.register(new RevokeCommand(shell));
// Configure shared shell io object
setIo(shell.getIo());
// We're running in batch mode by default
setInteractive(false);
// Let's see if user do have resource file with initial commands that he
// would like to apply.
String homeDir = System.getProperty(Constants.PROP_HOMEDIR);
File rcFile = new File(homeDir, RC_FILE);
if(rcFile.exists()) {
printlnResource(Constants.RES_SQOOP_PROMPT_SHELL_LOADRC, RC_FILE);
interpretFileContent(rcFile, shell);
printlnResource(Constants.RES_SQOOP_PROMPT_SHELL_LOADEDRC);
}
if (args.length == 0) {
// Interactive mode:
getIo().setVerbosity(Verbosity.QUIET);
printlnResource(Constants.RES_SQOOP_SHELL_BANNER);
println();
// Switch to interactive mode
setInteractive(true);
shell.run(args);
} else {
// Batch mode (with a script file):
File script = new File(args[0]);
if (!script.isAbsolute()) {
String userDir = System.getProperty(Constants.PROP_CURDIR);
script = new File(userDir, args[0]);
}
interpretFileContent(script, shell);
}
}
示例11: invokeMethodClosure
import org.codehaus.groovy.runtime.MethodClosure; //导入依赖的package包/类
private Object invokeMethodClosure(Object object, String methodName, Object[] arguments) {
final MethodClosure mc = (MethodClosure) object;
final Object owner = mc.getOwner();
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 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.reduceDimension(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)).booleanValue())) {
throw e;
}
if (arguments.length <= 0) {
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);
}
}
示例12: createMethodClosure
import org.codehaus.groovy.runtime.MethodClosure; //导入依赖的package包/类
public MethodClosure createMethodClosure() {
return new MethodClosure(this, "someMethod");
}
示例13: installInterceptors
import org.codehaus.groovy.runtime.MethodClosure; //导入依赖的package包/类
public void installInterceptors() {
systemOutInterceptor = new SystemOutputInterceptor(new MethodClosure(this, "notifySystemOut"), true);
systemOutInterceptor.start();
systemErrorInterceptor = new SystemOutputInterceptor(new MethodClosure(this, "notifySystemErr"), false);
systemErrorInterceptor.start();
}
示例14: main
import org.codehaus.groovy.runtime.MethodClosure; //导入依赖的package包/类
public static void main(String[] args) throws Exception {
System.setProperty("groovysh.prompt", "aquila");
Groovysh shell = new Groovysh();
shell.setErrorHook(new MethodClosure(ThrowableDisplayer.class, "errorHook"));
CommandRegistry registry = shell.getRegistry();
@SuppressWarnings("unchecked")
Iterator<Command> iterator = registry.iterator();
while (iterator.hasNext()) {
Command command = iterator.next();
if (!commandsToKeep.contains(command.getName())) {
iterator.remove();
registry.remove(command);
}
}
shell.register(new HelpCommand(shell));
shell.register(new CreateCommand(shell));
shell.register(new ShowCommand(shell));
shell.register(new LsCommand(shell));
shell.register(new StartCommand(shell));
shell.register(new DeleteCommand(shell));
try{
DerbyUtil.createTable2();
}catch(SQLException e){
}
// Configure shared shell io object
ShellEnvironment.setIo(shell.getIo());
// We're running in batch mode by default
ShellEnvironment.setInteractive(false);
if (args.length == 0) {
ShellEnvironment.getIo().setVerbosity(Verbosity.QUIET);
ShellEnvironment.println("@|green Aquila Shell:|@ Type '@|bold help|@' or '@|bold \\h|@' for help.");
ShellEnvironment.println();
ShellEnvironment.setInteractive(true);
shell.run(args);
} else {
File script = new File(args[0]);
if (!script.isAbsolute()) {
String userDir = System.getProperty(Constants.PROP_CURDIR);
script = new File(userDir, args[0]);
}
interpretFileContent(script, shell);
}
}
示例15: getKeywordProcessors
import org.codehaus.groovy.runtime.MethodClosure; //导入依赖的package包/类
@Override
public Map<String, Closure<?>> getKeywordProcessors() {
final Map<String, Closure<?>> outer = new HashMap<>();
outer.put("outerKeyword", new MethodClosure(this, "outer"));
return outer;
}