Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
languagejava
titleImplementation of all basic abstract methods
collapsetrue
package org.joget.tutorial;
 
import org.joget.apps.app.model.DefaultHashVariablePlugin;
import org.joget.apps.app.service.AppPluginUtil;
 
public class BeanShellHashVariable extends DefaultHashVariablePlugin {
    
    private final static String MESSAGE_PATH = "messagemessages/BeanShellHashVariable";
 
    public String getName() {
        return "BeanShellHashVariable";
    }
 
    public String getVersion() {
        return "5.0.0";
    }
 
    public String getClassName() {
        return getClass().getName();
    }
    
    public String getLabel() {
        //support i18n
        return AppPluginUtil.getMessage("org.joget.tutorial.BeanShellHashVariable.pluginLabel", getClassName(), MESSAGE_PATH);
    }
    
    public String getDescription() {
        //support i18n
        return AppPluginUtil.getMessage("org.joget.tutorial.BeanShellHashVariable.pluginDesc", getClassName(), MESSAGE_PATH);
    }
 
    public String getPropertyOptions() {
        //Hash variable plugin do not support property options
        return "";
    }
    
    public String getPrefix() {
        return "beanshell";
    }
    
    public String processHashVariable(String variableKey) {
        throw new UnsupportedOperationException("Not supported yet."); 
    }
}

Now, let focus on the main method of our Hash Variable plugin which is processHashVariable.

 

We will refer to the source code of Environment Variable Hash Variable plugin on how to retrieve the Environment variable. Then, refer to the source code of Bean Shell Form Binder on how to execute a bean shell script.

Code Block
languagejava
    public String processHashVariable(String variableKey) {
        try {
            String environmentVariableKey = variableKey;
            
            //first check and retrieve parameters passed in with URL query parameters syntax wrapped in square bracket []
            String queryParams = null;
            if (variableKey.contains("[") && variableKey.contains("]")) {
                queryParams = variableKey.substring(variableKey.indexOf("[") + 1, variableKey.indexOf("]"));
                environmentVariableKey = variableKey.substring(0, variableKey.indexOf("["));
            }
 
            //Parse the query parameters to a map
            Map<String, String[]> parameters = null;
            if (queryParams != null && !queryParams.isEmpty()) {
                parameters = StringUtil.getUrlParams(queryParams);
                
                //put all parameters to plugin properties
                getProperties().putAll(parameters);
            }
 
            //Retrieve the environment variable based on environmentVariableKey
            AppDefinition appDef = (AppDefinition) getProperty("appDefinition");
            if (appDef != null) {
                ApplicationContext appContext = AppUtil.getApplicationContext();
                EnvironmentVariableDao environmentVariableDao = (EnvironmentVariableDao) appContext.getBean("environmentVariableDao");
                EnvironmentVariable env = environmentVariableDao.loadById(environmentVariableKey, appDef);
                if (env != null) {
                    String script = env.getValue();
                    //execute the script with all plugin properties
                    return executeScript(script, getProperties());
                } else {
                    //environment variable not found, return empty value
                    return "";
                }
            }
        } catch (Exception e) {
            //log the exception using LogUtil
            LogUtil.error(getClassName(), e, "#beanshell."+variableKey+"# fail to parse.");
        }
        
        //return null to by pass the replacing
        return null;
    }
    
    protected String executeScript(String script, Map properties) throws Exception {
        Interpreter interpreter = new Interpreter();
        interpreter.setClassLoader(getClass().getClassLoader());
        for (Object key : properties.keySet()) {
            interpreter.set(key.toString(), properties.get(key));
        }
        LogUtil.debug(getClass().getName(), "Executing script " + script);
        return (String) interpreter.eval(script);
    }

c. Manage the dependency libraries of your plugin

Our plugin class cannot resolve "bsh.Interpreter". So, we will have to add bean shell library to our POM file.

Image Added

Code Block
languagexml
<!-- Change plugin specific dependencies here -->
<dependency>
    <groupId>org.beanshell</groupId>
    <artifactId>bsh</artifactId>
    <version>2.0b4</version>
</dependency>
<!-- End change plugin specific dependencies here -->

d. Make your plugin internationalization (i18n) ready

We are using AppPluginUtil.getMessage method to display i18n value for our getLabel and getDescription method. We will have to create a message resource bundle properties file for it. Create directory "resources/messages" under "beanshell_hash_variable/src/main" directory. Then, create a "BeanShellHashVariable.properties" file in it.

Image Added

In our properties file, we will need to add the key we had used.

Code Block
languagetext
org.joget.tutorial.BeanShellHashVariable.pluginLabel=Bean Shell Hash Variable
org.joget.tutorial.BeanShellHashVariable.pluginDesc=Using environment variable to execute bean shell script.

e. Register your plugin to Felix Framework

We will have to register our plugin class in Activator class to tell Felix Framework that this is a plugin.

Image Added

Code Block
languagejava
public void start(BundleContext context) {
    registrationList = new ArrayList<ServiceRegistration>();

    //Register plugin here
    registrationList.add(context.registerService(BeanShellHashVariable.class.getName(), new BeanShellHashVariable(), null));
}

f. Build it and testing

Let build our plugin. Once the building process is done, we will found a "beanshell_hash_variable-5.0.0.jar" file is created under "beanshell_hash_variable/target" directory.

Image Added

 Then, let upload the plugin jar to Manage Plugins. After upload the jar file, double check the plugin is uploaded and activated correctly.

Image Added

Now, let test our plugin.

Let assume we have a HTML menu page in userview want to display the following line to logged in user. Normally, we will use "Welcome #currentUser,username#," to display a welcome message.

Image Added

But, this way has a problem, which is shown "Welcome ," without an username when the user is an anonymous.

Image Added

Now, change the whole message to our Bean Shell Hash Variable and create an environment variable to put our script.

Change the following

Code Block
Welcome #currentUser.username#,

to the following. We we need to pass the current user's username as one of our parameters and do not forget to escape it as url.

Code Block
#beanshell.welcome[username={currentUser.username?url}]?html#

Then, we can create an environment variable with ID "welcome" and use the following script. Due to we are using getUrlParams method from StringUtil to parse the parameters, all value from parameters are String array.

Code Block
languagejava
//all parameters passed in from Beanshell Hash Variable will converted to String array 
if (username != null && username.length == 1 && !username[0].isEmpty()) {
    return "Welcome " + username[0] + ",";
} else {
    return ""; 
}

Let go back to our HTML menu page to see the result.

When user is logged in, it shown the message.

Image Added

When no user is logged in, it did not show the welcome message.

Image Added

8. Take a step further, share it or sell it

You can download the source code from beanshell_hash_variable.zip.

To download the ready-to-use plugin jar, please find it in http://marketplace.joget.org/.