Joget DX 8 Stable Released
The stable release for Joget DX 8 is now available, with a focus on UX and Governance.
...
Sometime, we may need to write some custom query to populate the options for our multi options field.
...
Joget Workflow has provided a plugin type called Form Options Binder Plugin. We will develop one to support JDBC connection and custom query.
...
The first column of returned JDBC result will be the value of the option and second column is the label of the option. There will be another optional third column for grouping when no not using AJAX for cascading drop-down list.
...
...
We can refer to the implementation of other available Form Options Binder plugins. Joget default datasource can be retrieve with AppUtil.getApplicationContext().getBean("setupDataSource").
...
We need to always have our Joget Workflow Source Code ready and builded built by following this guideline.
The following of this tutorial is prepared with a Macbook Pro and Joget Source Code version 5.0.0. Please refer to to the Guideline for developing a plugin for article for other platform commandcommands.
Let said 's say our folder directory is as followingfollows.
Code Block |
---|
- Home - joget - plugins - jw-community -5.0.0 |
The "plugins" directory is the folder we will create and store all our plugins and the "jw-community" directory is where the Joget Workflow Source code is stored.
Run the following command to create a maven project in "plugins" directory.
...
Then, the shell script will ask us to key in a version number for your the plugin and ask us request for a confirmation before generate generating the maven project.
Code Block | ||
---|---|---|
| ||
Define value for property 'version': 1.0-SNAPSHOT: : 5.0.0 [INFO] Using property: package = org.joget.tutorial Confirm properties configuration: groupId: org.joget.tutorial artifactId: jdbc_options_binder version: 5.0.0 package: org.joget.tutorial Y: : y |
...
As usual, we have to implement all the abstract methods. We will be using AppPluginUtil.getMessage method to support i18n and using constant variable MESSAGE_PATH for message resource bundle directory.
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
package org.joget.tutorial; import org.joget.apps.app.service.AppPluginUtil; import org.joget.apps.app.service.AppUtil; import org.joget.apps.form.model.Element; import org.joget.apps.form.model.FormAjaxOptionsBinder; import org.joget.apps.form.model.FormBinder; import org.joget.apps.form.model.FormData; import org.joget.apps.form.model.FormLoadOptionsBinder; import org.joget.apps.form.model.FormRowSet; public class JdbcOptionsBinder extends FormBinder implements FormLoadOptionsBinder, FormAjaxOptionsBinder { private final static String MESSAGE_PATH = "messages/JdbcOptionsBinder"; public String getName() { return "JDBC Option Binder"; } public String getVersion() { return "5.0.0"; } public String getClassName() { return getClass().getName(); } public String getLabel() { //support i18n return AppPluginUtil.getMessage("org.joget.tutorial.JdbcOptionsBinder.pluginLabel", getClassName(), MESSAGE_PATH); } public String getDescription() { //support i18n return AppPluginUtil.getMessage("org.joget.tutorial.JdbcOptionsBinder.pluginDesc", getClassName(), MESSAGE_PATH); } public String getPropertyOptions() { return AppUtil.readPluginResource(getClassName(), "/properties/jdbcOptionsBinder.json", null, true, MESSAGE_PATH); } public FormRowSet load(Element element, String primaryKey, FormData formData) { return loadAjaxOptions(null); // reuse loadAjaxOptions method } public boolean useAjax() { return "true".equalsIgnoreCase(getPropertyString("useAjax")); // let user to decide whether or not to use ajax for dependency field } public FormRowSet loadAjaxOptions(String[] dependencyValues) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } } |
Then, we have to do create a UI for admin user to provide inputs for our plugin. In getPropertyOptions method, we have already specify that our Plugin Properties Options definition file is locate located at "/properties/jdbcOptionsBinder.json". Let us create a directory "resources/properties" under "jdbc_options_binder/src/main" directory. After create creating the directory, create a file named "jdbcOptionsBinder.json" in the "properties" folder.
In the properties definition options file, we will need to provide options as below. Please note that we can will use "@@message.key@@" syntax to support i18n in our properties options.
...
In the Properties Options, we added a button for testing connection when using a custom datasource. This button is calling will call a JSON API to do the test. So, our plugin will need to implement org.joget.plugin.base.PluginWebSupport interface to make it as a Web Service Plugin as well. Let's implement the webService method as following for follows, to test the JDBC connection.
Code Block | ||
---|---|---|
| ||
/** * JSON API for test connection button * @param request * @param response * @throws ServletException * @throws IOException */ public void webService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Limit the API for admin usage only boolean isAdmin = WorkflowUtil.isCurrentUserInRole(WorkflowUserManager.ROLE_ADMIN); if (!isAdmin) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return; } String action = request.getParameter("action"); if ("testConnection".equals(action)) { String message = ""; Connection conn = null; try { AppDefinition appDef = AppUtil.getCurrentAppDefinition(); String jdbcDriver = AppUtil.processHashVariable(request.getParameter("jdbcDriver"), null, null, null, appDef); String jdbcUrl = AppUtil.processHashVariable(request.getParameter("jdbcUrl"), null, null, null, appDef); String jdbcUser = AppUtil.processHashVariable(request.getParameter("jdbcUser"), null, null, null, appDef); String jdbcPassword = AppUtil.processHashVariable(SecurityUtil.decrypt(request.getParameter("jdbcPassword")), null, null, null, appDef); Class.forName(jdbcDriver); conn = DriverManager.getConnection(jdbcUrl, jdbcUser, jdbcPassword); message = AppPluginUtil.getMessage("form.jdbcOptionsBinder.connectionOk", getClassName(), MESSAGE_PATH); } catch (Exception e) { LogUtil.error(getClassName(), e, "Test Connection error"); message = AppPluginUtil.getMessage("form.jdbcOptionsBinder.connectionFail", getClassName(), MESSAGE_PATH) + "\n" + e.getMessage(); } finally { try { if (conn != null && !conn.isClosed()) { conn.close(); } } catch (Exception e) { LogUtil.error(DynamicDataSourceManager.class.getName(), e, ""); } } try { JSONObject jsonObject = new JSONObject(); jsonObject.accumulate("message", message); jsonObject.write(response.getWriter()); } catch (Exception e) { //ignore } } else { response.setStatus(HttpServletResponse.SC_NO_CONTENT); } } |
Once we are done with the properties option to collect input and the web service to test the connection, we can work on the main method of the plugin which is the loadAjaxOptions method.
Code Block | ||
---|---|---|
| ||
public FormRowSet loadAjaxOptions(String[] dependencyValues) { FormRowSet rows = new FormRowSet(); rows.setMultiRow(true); //add empty option based on setting if ("true".equals(getPropertyString("addEmpty"))) { FormRow empty = new FormRow(); empty.setProperty(FormUtil.PROPERTY_LABEL, getPropertyString("emptyLabel")); empty.setProperty(FormUtil.PROPERTY_VALUE, ""); rows.add(empty); } //Check the sql. If require dependency value and dependency value is not exist, return empty result. String sql = getPropertyString("sql"); if ((dependencyValues == null || dependencyValues.length == 0) && sql.contains("?")) { return rows; } Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { DataSource ds = createDataSource(); con = ds.getConnection(); //support for multiple dependency values if (sql.contains("?") && dependencyValues != null && dependencyValues.length > 1) { String mark = "?"; for (int i = 1; i < dependencyValues.length; i++) { mark += ", ?"; } sql = sql.replace("?", mark); } pstmt = con.prepareStatement(sql); //set query parameters if (sql.contains("?") && dependencyValues != null && dependencyValues.length > 0) { for (int i = 0; i < dependencyValues.length; i++) { pstmt.setObject(i + 1, dependencyValues[i]); } } rs = pstmt.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData(); int columnsNumber = rsmd.getColumnCount(); // Set retrieved result to Form Row Set while (rs.next()) { FormRow row = new FormRow(); String value = rs.getString(1); String label = rs.getString(2); row.setProperty(FormUtil.PROPERTY_VALUE, (value != null)?value:""); row.setProperty(FormUtil.PROPERTY_LABEL, (label != null)?label:""); if (columnsNumber > 2) { String grouping = rs.getString(3); row.setProperty(FormUtil.PROPERTY_GROUPING, grouping); } rows.add(row); } } catch (Exception e) { LogUtil.error(getClassName(), e, ""); } finally { try { if (rs != null) { rs.close(); } if (pstmt != null) { pstmt.close(); } if (con != null) { con.close(); } } catch (Exception e) { LogUtil.error(getClassName(), e, ""); } } return rows; } /** * To creates data source based on setting * @return * @throws Exception */ protected DataSource createDataSource() throws Exception { DataSource ds = null; String datasource = getPropertyString("jdbcDatasource"); if ("default".equals(datasource)) { // use current datasource ds = (DataSource)AppUtil.getApplicationContext().getBean("setupDataSource"); } else { // use custom datasource Properties dsProps = new Properties(); dsProps.put("driverClassName", getPropertyString("jdbcDriver")); dsProps.put("url", getPropertyString("jdbcUrl")); dsProps.put("username", getPropertyString("jdbcUser")); dsProps.put("password", getPropertyString("jdbcPassword")); ds = BasicDataSourceFactory.createDataSource(dsProps); } return ds; } |
...
Create directory "resources/messages" under "jdbc_options_binder/src/main" directory. Then, create a "JdbcOptionsBinder.properties" file in the folder. In the properties file, let us add all the message keys and its label labels as below.
Code Block |
---|
org.joget.tutorial.JdbcOptionsBinder.pluginLabel=JDBC Binder org.joget.tutorial.JdbcOptionsBinder.pluginDesc=Used to load field's options using JDBC form.jdbcOptionsBinder.config=Configure JDBC Binder form.jdbcOptionsBinder.datasource=Datasource form.jdbcOptionsBinder.customDatasource=Custom Datasource form.jdbcOptionsBinder.defaultDatasource=Default Datasource form.jdbcOptionsBinder.driver=Custom JDBC Driver form.jdbcOptionsBinder.driver.desc=Eg. com.mysql.jdbc.Driver (MySQL), oracle.jdbc.driver.OracleDriver (Oracle), com.microsoft.sqlserver.jdbc.SQLServerDriver (Microsoft SQL Server) form.jdbcOptionsBinder.url=Custom JDBC URL form.jdbcOptionsBinder.username=Custom JDBC Username form.jdbcOptionsBinder.password=Custom JDBC Password form.jdbcOptionsBinder.useAjax=Use AJAX for cascade options? form.jdbcOptionsBinder.addEmpty=Add Empty Option? form.jdbcOptionsBinder.emptyLabel=Empty Option Label form.jdbcOptionsBinder.sql=SQL SELECT Query form.jdbcOptionsBinder.sql.desc=Use question mark (?) in your query to represent dependency values when using AJAX form.jdbcOptionsBinder.testConnection=Test Connection form.jdbcOptionsBinder.connectionOk=Database connected form.jdbcOptionsBinder.connectionFail=Not able to establish connection. |
We will have to register our plugin class in Activator class (Auto generated in the same class package) to tell the Felix Framework that this is a plugin.
Code Block | ||
---|---|---|
| ||
public void start(BundleContext context) { registrationList = new ArrayList<ServiceRegistration>(); //Register plugin here registrationList.add(context.registerService(JdbcOptionsBinder.class.getName(), new JdbcOptionsBinder(), null)); } |
...
Let build our plugin. Once the building process is done, we will found find that a "jdbc_options_binder-5.0.0.jar" file is created under "jdbc_options_binder/target" directory.
Then, let us upload the plugin jar to Manage Plugins. After upload uploading the jar file, double check that the plugin is uploaded and activated correctly.
...
Then, let us create an AJAX Cascading Drop-Down List in a form to test it. Let's create our test form as followingfollows.
Then, configure our select box and JDBC binder.
...
In the query, we will use the following query to get the user list based on group id.
...
The user select box options changed based on the selected values of group select box.
Now, let's change the query to the following to test Cascading test the Cascading Drop-Down List without using AJAX.
...
Remember to un-tick the "Use AJAX for cascade options?" option to make it not using use AJAX.
Yes, it work works as well. Then, we can test the custom configuration and the test connection button.
...