Joget DX 8 Stable Released
The stable release for Joget DX 8 is now available, with a focus on UX and Governance.
...
In this tutorial, we will following the guideline of developing a plugin to develop our Multi Store Binder pluginmulti store binders plugin. Please also refer to the very first tutorial How to develop a Bean Shell Hash Variable and also the following JDBC store binder related plugin for more details detailed steps.
...
...
English |
---|
We would like to |
...
run multiple store binders plugins in a single store binder selection. This would open up more use cases with the ability to store form data into multiple destinations without the need for relying on other approaches such as JSON Tool or SOAP Tool. |
Joget has
Joget Workflow has provided a plugin type called Form Store Binder Plugin. We will develop one based on this plugin category to support JDBC connection and custom query multiple selections and execution of store binders to store form data.
To develop a JDBC Multi Store binderbinders, we will need the JDBC connection setting and also the custom query to store the form data based the collected form data.
Datasource: Using custom datasource or Joget default datasource
Custom JDBC Driver: The JDBC driver for custom datasource
Custom JDBC URL: The JDBC connection URL for custom datasource
Custom JDBC Username: The username for custom datasource
Custom JDBC Password: The password for custom datasource
SQL Check Exist Query: The query to check whether an insert or update query should be execute.
a multi-selector in a grid form and a text editor for additional notes for app designers.
Binders: Displays a list of store binders available.
Comments: Additional notes users might wish to add.
All submitted data will store accordingly based on the configuration of each of the store binders selected.
We can refer to the implementation of other available Form Store Binder plugins. We can also refer to how Multi Tools plugin for the design:
We need to always have our Joget Workflow Source Code ready and built by following this guideline.
The following of this tutorial is prepared with Joget Source Code version 7.0.0. Please refer to Guideline for Developing a Plugin for other platform commands.
Let's use the following folder structure.
Code Block |
---|
- Home
- joget
- plugins
- jw-community
-7.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 stored.
Run the following command to create a maven project in the "plugins" directory.
Code Block | ||
---|---|---|
| ||
cd joget/plugins/
~/joget/jw-community/7.0.0/wflow-plugin-archetype/create-plugin.sh org.joget.marketplace multi_store_binder 7.0.0 |
Then, the shell script will ask us to key in a version for your plugin and ask us for confirmation before generate the maven project.
Code Block | ||
---|---|---|
| ||
Define value for property 'version': 1.0-SNAPSHOT: : 7.0.0
[INFO] Using property: package = org.joget.marketplace
Confirm properties configuration:
groupId: org.joget.marketplace
artifactId: multi_store_binder
version: 7.0.0
package: org.joget.marketplace
Y: : y |
We should get the "BUILD SUCCESS" message shown in our terminal and a "multi_store_binder" folder created in the "plugins" folder.
Open the maven project with your favorite IDE. We will be using NetBeans.
Create a "MultiStoreBinders" class under "org.joget.marketplace" package. Then, extend the class with org.joget.apps.form.model.FormBinder abstract class.
To make it work as a Form Store Binder, we will need to implement org.joget.apps.form.model.FormStoreBinder
SQL Insert Query: The query to insert form data.
SQL Update Query: The query to insert form data.
SQL Delete Query: The query to delete deleted form data when used as multirow binder.
We will have to support a syntax to inject the form data to the query. "{foreignKey}" can be used for Multi Rows storing.
We will also need to support a syntax to inject UUID value. In this case, we will use "{uuid}".
Example: INSERT INTO app_fd_test VALUES ({id}, {name}, {email}, {phone}, {foreignKey});
All submitted data will store accordingly based on the check/insert/update query.
We can refer to the implementation of other available Form Store 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 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 Guideline for developing a plugin for other platform command.
Let said our folder directory as following.
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 stored.
Run the following command to create a maven project in "plugins" directory.
Code Block | ||
---|---|---|
| ||
cd joget/plugins/
~/joget/jw-community/5.0.0/wflow-plugin-archetype/create-plugin.sh org.joget.tutorial jdbc_store_binder 5.0.0 |
Then, the shell script will ask us to key in a version for your plugin and ask us for confirmation before generate 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_store_binder
version: 5.0.0
package: org.joget.tutorial
Y: : y |
We should get "BUILD SUCCESS" message shown in our terminal and a "jdbc_store_binder" folder created in "plugins" folder.
Open the maven project with your favour IDE. I will be using NetBeans.
Create a "JdbcStoreBinder" class under "org.joget.tutorial" package. Then, extend the class with org.joget.apps.form.model.FormBinder abstract class.
To make it work as a Form Store Binder, we will need to implement org.joget.apps.form.model.FormStoreBinder interface. Then, we need to implement org.joget.apps.form.model.FormStoreElementBinder interface to make this plugin show as a selection in store binder select box and implement org.joget.apps.form.model.FormStoreMultiRowElementBinder interface to list it under the store binder select box of grid element.
Please refer to Form Store Binder Plugin .
As usual, we have to implement all the abstract methods. We will be using the AppPluginUtil.getMessage method to support i18n and using constant using the constant variable MESSAGE_PATH for the message resource bundle directory.
Code Block | ||||||||
---|---|---|---|---|---|---|---|---|
| ||||||||
package org.joget.tutorialmarketplace; 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.FormBinder; import org.joget.apps.form.model.FormData; import org.joget.apps.form.model.FormRowSet; import org.joget.apps.form.model.FormStoreBinder; import org.joget.apps.form.model.FormStoreElementBinder; import org.joget.apps.form.model.FormStoreMultiRowElementBinder; public class JdbcStoreBinderMultiStoreBinders extends FormBinder implements FormStoreBinder, FormStoreElementBinder, FormStoreMultiRowElementBinder { private final static String MESSAGE_PATH = "messages/JdbcStoreBindermultiStoreBinders"; public String getName() { return "JDBCmulti Storestore Binderbinders"; } public String getVersion() { return "57.0.0"; } public String getClassName() { return getClass().getName(); } public String getLabel() { //support i18n return AppPluginUtil.getMessage("org.joget.tutorialmarketplace.JdbcStoreBinderMultiStoreBinders.pluginLabel", getClassName(), MESSAGE_PATH); } public String getDescription() { //support i18n return AppPluginUtil.getMessage("org.joget.tutorialmarketplace.JdbcStoreBinderMultiStoreBinders.pluginDesc", getClassName(), MESSAGE_PATH); } public String getPropertyOptions() { return AppUtil.readPluginResource(getClassName(), "/properties/jdbcStoreBindermultiStoreBinders.json", null, true, MESSAGE_PATH); } public FormRowSet store(Element element, FormRowSet rows, FormData formData) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } } |
Then, we have to do a UI for admin user to provide inputs for our plugin. In getPropertyOptions method, we already specify our Plugin Properties Options definition file is locate located at "/properties/jdbcStoreBindermultiStoreBinders.json". Let us create a directory "resources/properties" under "jdbcmulti_store_binder/src/main" directory. After create creating the directory, create a file named "jdbcStoreBindermultiStoreBinders.json" in the "properties" folder.
...
Code Block | ||||
---|---|---|---|---|
| ||||
[ { "title" : '@@form.jdbcStoreBinder"@@org.joget.marketplace.MultiStoreBinders.config@@'", "properties" : [{ name : 'jdbcDatasource',{ label : '@@form.jdbcStoreBinder.datasource@@', type"name" : 'selectbox'"binders", options : [{ "label" : "@@org.joget.marketplace.MultiStoreBinders.storeBinder@@", value : 'custom', label"type" : '@@form.jdbcStoreBinder.customDatasource@@'"elementmultiselect", },{ "options_ajax" : value : 'default', "[CONTEXT_PATH]/web/property/json/getElements?classname=org.joget.apps.form.model.FormStoreBinder&exclude=org.joget.sample.MultiStoreBinders", label"url" : '@@form.jdbcStoreBinder.defaultDatasource@@'"[CONTEXT_PATH]/web/property/json[APP_PATH]/getPropertyOptions", }], value : 'default'"default_property_values_url" : "[CONTEXT_PATH]/web/property/json[APP_PATH]/getDefaultProperties", },{ name"required" : 'jdbcDriver',"true" label : '@@form.jdbcStoreBinder.driver@@', },{ description : '@@form.jdbcStoreBinder.driver.desc@@' "name" : "comment", type : 'textfield', value"label" : 'com.mysql.jdbc.Driver'"@@org.joget.marketplace.MultiStoreBinders.comment@@", control_field: 'jdbcDatasource', "type" control_value: 'custom',"codeeditor" control_use_regex: 'false', } required : 'true'] } ] |
Similar to the Multi Tool plugin, we will need a multi selector to list the available store binders excluding the multi store binders. Refer to Plugin Properties Options#MultiselectinGridInterface(New)
Once we are done, we can work on the main method of the plugin which is store method.
Code Block | ||
---|---|---|
| ||
,{ public FormRowSet store(Element name : 'jdbcUrl', element, FormRowSet rows, FormData formData) { final Object[] binders label : '@@form.jdbcStoreBinder.url@@', = (Object[]) getProperty("binders"); if (binders != null type : 'textfield',&& binders.length > 0) { value : 'jdbc:mysql://localhost/jwdb?characterEncoding=UTF8', Thread newThread; control_field: 'jdbcDatasource', control_value: 'custom', final PluginManager pluginManager = control_use_regex: 'false', (PluginManager) AppUtil.getApplicationContext().getBean("pluginManager"); required : 'true' newThread = },new PluginThread(new Runnable() { name : 'jdbcUser', label : '@@form.jdbcStoreBinder.username@@', public void run() { type : 'textfield', control_field: 'jdbcDatasource', control_value: 'custom', control_use_regex: 'false', value : 'root', for (Object binder required: : 'true' binders) { },{ name : 'jdbcPassword', label : '@@form.jdbcStoreBinder.password@@', if (binder != null && type : 'password',binder instanceof Map) { control_field: 'jdbcDatasource', control_value: 'custom', control_use_regex: 'false', Map binderMap = (Map) binder; value : '' },{ name : 'check_sql', label : '@@form.jdbcStoreBinder.check_sql@@', if (binderMap != descriptionnull :&& '@@form.jdbcStoreBinder.check_sql.desc@@', binderMap.containsKey("className") && !binderMap.get("className").toString().isEmpty()) { type : 'codeeditor', mode : 'sql', required : 'true' },{ String className name : 'insert_sql',= binderMap.get("className").toString(); label : '@@form.jdbcStoreBinder.insert_sql@@', description : '@@form.jdbcStoreBinder.insert_sql.desc@@', type : 'codeeditor', FormStoreBinder p mode= : 'sql',(FormStoreBinder) pluginManager.getPlugin(className); required : 'true' },{ name : 'update_sql', label : '@@form.jdbcStoreBinder.update_sql@@', if (p != null) { description : '@@form.jdbcStoreBinder.update_sql.desc@@', type : 'codeeditor', mode : 'sql', required : 'true' Map properties = },{new HashMap(); name : 'delete_sql', label : '@@form.jdbcStoreBinder.delete_sql@@', description : '@@form.jdbcStoreBinder.delete_sql.desc@@', type : 'codeeditor', properties.putAll((Map) binderMap.get("properties")); mode : 'sql', required : 'true' }], buttons : [{ name : 'testConnection', label : '@@form.jdbcStoreBinder.testConnection@@', ajax_url : '[CONTEXT_PATH]/web/json/app[APP_PATH]/plugin/org.joget.tutorial.JdbcStoreBinder/service?action=testConnection', fields : ['jdbcDriver', 'jdbcUrl', 'jdbcUser', 'jdbcPassword'], if (p instanceof PropertyEditable) { control_field: 'jdbcDatasource', control_value: 'custom', control_use_regex: 'false' }] }] |
Same as JDBC Options Binder, we will need to add a test connection button for custom JDBC setting. Please refer to How to develop a JDBC Options Binder on the Web Service Plugin implementation.
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 store method.
Code Block | ||
---|---|---|
| ||
public FormRowSet store(Element element, FormRowSet rows, FormData formData) { ((PropertyEditable) p).setProperties(properties); Form parentForm = FormUtil.findRootForm(element); } String primaryKeyValue = parentForm.getPrimaryKeyValue(formData); Connection con = null; PreparedStatement pstmt = null; p.store(element, rows, formData); ResultSet rs = null; try {} DataSource ds = createDataSource(); con = ds.getConnection(); } //check for deletion} FormRowSet originalRowSet = formData.getLoadBinderData(element); } if (originalRowSet != null && !originalRowSet.isEmpty()) { } for (FormRow r : originalRowSet) { }); if (!rowsnewThread.containsstart(r)); { String query = getPropertyString("delete_sql"); } pstmt = con.prepareStatement(getQuery(query))return null; int i = 1;} |
Our plugin is using dbcp, javax.servlet.http.HttpServletRequest and javax.servlet.http.HttpServletResponse class, so we will need to add jsp-api and commons-dbcp library to our POM file.
Code Block | ||
---|---|---|
| ||
<!-- Change plugin specific dependencies here --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> </dependency> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20080701</version> for (String obj : getParams(query, r, primaryKeyValue)) { pstmt.setObject(i, obj); i++; } pstmt.executeUpdate(); } } } if (!(rows == null || rows.isEmpty())) { //run query for each row for (FormRow row : rows) { //check to use insert query or update query String checkSql = getPropertyString("check_sql"); pstmt = con.prepareStatement(getQuery(checkSql)); int i = 1; for (String obj : getParams(checkSql, row, primaryKeyValue)) { pstmt.setObject(i, obj); i++; } String query = getPropertyString("insert_sql"); rs = pstmt.executeQuery(); //record exist, use update query if (rs.next()) { query = getPropertyString("update_sql"); } pstmt = con.prepareStatement(getQuery(query)); i = 1; for (String obj : getParams(query, row, primaryKeyValue)) { pstmt.setObject(i, obj); i++; } pstmt.executeUpdate(); } } } 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; } /** * Used to replaces all syntax like {field_id} to question mark * @param query * @return */ protected String getQuery(String query) { return query.replaceAll("\\{[a-zA-Z0-9_]+\\}", "?"); } /** * Used to retrieves the value of variables in query * @param query * @param row * @return */ protected Collection<String> getParams(String query, FormRow row, String primaryKey) { Collection<String> params = new ArrayList<String>(); Pattern pattern = Pattern.compile("\\{([a-zA-Z0-9_]+)\\}"); Matcher matcher = pattern.matcher(query); while (matcher.find()) { String key = matcher.group(1); if (FormUtil.PROPERTY_ID.equals(key)) { String value = row.getId(); if (value == null || value.isEmpty()) { value = UuidGenerator.getInstance().getUuid(); row.setId(value); } params.add(value); } else if ("uuid".equals(key)) { params.add(UuidGenerator.getInstance().getUuid()); } else if ("foreignKey".equals(key)) { params.add(primaryKey); } else { String value = row.getProperty(key); params.add((value != null)?value:""); } } return params; } /** * 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; } |
Our plugin is using dbcp, javax.servlet.http.HttpServletRequest and javax.servlet.http.HttpServletResponse class, so we will need to add jsp-api and commons-dbcp library to our POM file.
Code Block | ||
---|---|---|
| ||
<!-- Change plugin specific dependencies here -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.3</version>
</dependency>
<!-- End change plugin specific dependencies here --> |
We are using i18n message key in getLabel and getDescription method. We also used i18n message key in our properties options definition as well. So, we will need to create a message resource bundle properties file for our plugin.
Create directory "resources/messages" under "jdbc_store_binder/src/main" directory. Then, create a "JdbcStoreBinder.properties" file in the folder. In the properties file, let add all the message keys and its label as below.
<scope>provided</scope>
</dependency>
<!-- End change plugin specific dependencies here --> |
We are using i18n message key in getLabel and getDescription method. We also used i18n message key in our properties options definition as well. So, we will need to create a message resource bundle properties file for our plugin.
Create directory "resources/messages" under "jdbc_store_binder/src/main" directory. Then, create a "multiStoreBinders.properties" file in the folder. In the properties file, let add all the message keys and its label as below.
Code Block | ||
---|---|---|
| ||
org.joget.marketplace.MultiStoreBinders.pluginLabel=multi store binders
org.joget.marketplace.MultiStoreBinders.pluginDesc=Enable the use of multiple store binders
org.joget.marketplace.MultiStoreBinders.config=Configure multi store binders
org.joget.marketplace.MultiStoreBinders.storeBinder=Store Binders
org.joget.marketplace.MultiStoreBinders.comment=Comment | ||
Code Block | ||
| ||
org.joget.tutorial.JdbcStoreBinder.pluginLabel=JDBC Binder
org.joget.tutorial.JdbcStoreBinder.pluginDesc=Used to store form data using JDBC
form.jdbcStoreBinder.config=Configure JDBC Binder
form.jdbcStoreBinder.datasource=Datasource
form.jdbcStoreBinder.customDatasource=Custom Datasource
form.jdbcStoreBinder.defaultDatasource=Default Datasource
form.jdbcStoreBinder.driver=Custom JDBC Driver
form.jdbcStoreBinder.driver.desc=Eg. com.mysql.jdbc.Driver (MySQL), oracle.jdbc.driver.OracleDriver (Oracle), com.microsoft.sqlserver.jdbc.SQLServerDriver (Microsoft SQL Server)
form.jdbcStoreBinder.url=Custom JDBC URL
form.jdbcStoreBinder.username=Custom JDBC Username
form.jdbcStoreBinder.password=Custom JDBC Password
form.jdbcStoreBinder.check_sql=SQL SELECT Query
form.jdbcStoreBinder.check_sql.desc=Used to decide an insert or update operation. Use syntax like {field_id} in query to inject submitted form data.
form.jdbcStoreBinder.insert_sql=SQL INSERT Query
form.jdbcStoreBinder.insert_sql.desc=Use syntax like {field_id} in query to inject submitted form data.
form.jdbcStoreBinder.update_sql=SQL UPDATE Query
form.jdbcStoreBinder.update_sql.desc=Use syntax like {field_id} in query to inject submitted form data.
form.jdbcStoreBinder.delete_sql=SQL DELETE Query
form.jdbcStoreBinder.delete_sql.desc=Used to delete deleted form data in Grid element. Use syntax like {id} in query to inject form data primary key.
form.jdbcStoreBinder.testConnection=Test Connection
form.jdbcStoreBinder.connectionOk=Database connected
form.jdbcStoreBinder.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 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(JdbcStoreBinderMultiStoreBinders.class.getName(), new JdbcStoreBinderMultiStoreBinders(), null)); } |
Let build our plugin. Once the building process is done, we will found a "jdbcmulti_store_binder-57.0.0.jar" file is created under the "jdbcmulti_store_binder/target" directory.
Then, let upload the plugin jar to Manage Plugins. After upload, the jar file, double-check the plugin is uploaded and activated correctly.
Let create a form to create and update user to dir_user table.
Then, configure the store binder of the form with the following query.section to Default Form Binder and JDBC Binder.
Code Block | ||||
---|---|---|---|---|
| ||||
select username from dir_user where username = {id} |
Code Block | ||||
---|---|---|---|---|
| ||||
insert into dir_user (id, username, firstName, lastName, email, active) values ({id}, {id}, {firstName}, {lastName}, {email}, 1) |
...
Info | ||
---|---|---|
| ||
{uuid} can be used to generate a unique id |
Code Block | ||||
---|---|---|---|---|
| ||||
update dir_user set firstName = {firstName}, lastName = {lastName}, email = {email} where username = {id} |
Code Block | ||||
---|---|---|---|---|
| ||||
delete from TABLE_NAME where id = {id} |
Now, let test to add a user.
Check the user is created in dir_user table.
Let update the same record by pass the id in URL parameters.
Check the user is updated.
It works! Please remember to test the other features of the plugin as well.
You can download the source code from jdbcmulti_store_binder_src.zip
To download the ready-to-use plugin jar, please find it in at http://marketplace.joget.org/.
...