Class BSHResourceCloser<T,​U>

  • Type Parameters:
    T - The resource type
    U - The return type

    public abstract class BSHResourceCloser<T,​U>
    extends Object
    An interface to implement the “try with resources” type of structure in Beanshell, which does not support it.

    You should create an anonymous inner class extending BSHResourceCloser, then pass it to execute(BSHResourceCloser).

    The open() method will be called and should produce an AutoCloseable resource. After that, the run() method will be invoked with the opened resource. If you need more than one thing to be opened, you may want to return a Closer.

    If your resource is AutoCloseable, its close() method will be invoked. If not, you must implement close() in your class.

    You may

    Example:

    BSHResourceCloser.execute(new BSHResourceCloser() {
        public Object open() {
            // Open a connection or something
        }
    });
    • Method Detail

      • execute

        public static <T> Object execute​(T resource,
                                         bsh.This bshThis,
                                         String methodName)
                                  throws Exception
        Executes the given Beanshell method with the resource, closing it once the method has completed.
        Type Parameters:
        T - The type of the resource
        Parameters:
        resource - The resource to use
        bshThis - The ‘this’ reference in your Beanshell script
        methodName - The method name to invoke with the resource
        Returns:
        The result of the Beanshell method
        Throws:
        Exception - if anything fails
      • execute

        public static <T,​U> U execute​(BSHResourceCloser<T,​U> closer)
                                     throws Exception
        Executes your action after getting the resource required
        Type Parameters:
        T - The resource type
        U - The return type
        Parameters:
        closer - The resource closer
        Returns:
        The return from your run() method
        Throws:
        Exception - if the resource open or the call fails
      • close

        public void close​(T resource)
        Closes the given resource.

        This will be invoked if the resource does not implement AutoCloseable.

        Parameters:
        resource - the resource to close
      • open

        public abstract T open()
                        throws Exception
        Opens the resource for this action
        Returns:
        The resource
        Throws:
        Exception - if anything fails
      • run

        public abstract U run​(T resource)
                       throws Exception
        Executes the action, passing the resource returned from open()
        Parameters:
        resource - The resource to use
        Returns:
        An arbitrary return value
        Throws:
        Exception - If the action fails for some reason