Versions Compared

Key

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

...

Code Block
languagejava
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.joget.apps.app.service.AppUtil;
import org.joget.apps.form.model.Element;
import org.joget.apps.form.model.FormData;
import org.joget.apps.form.model.FormRow;
import org.joget.apps.form.model.FormRowSet;
import org.joget.commons.util.LogUtil;
  
public FormRowSet load(Element element, String username, FormData formData) { 
    FormRowSet rows = new FormRowSet();
    if (username != null && !username.isEmpty()) {
        Connection con = null;
        try {
            // retrieve connection from the default datasource
            DataSource ds = (DataSource)AppUtil.getApplicationContext().getBean("setupDataSource");
            con = ds.getConnection();
         
            // execute SQL query
            if(!con.isClosed()) {
                PreparedStatement stmt = con.prepareStatement("SELECT username, firstName, lastName, email from dir_user where username=?");
                stmt.setObject(1, username);
                ResultSet rs = stmt.executeQuery();
                while (rs.next()) {
                    FormRow row = new FormRow();
                    System.out.println(rs.getObject("username") );
                    row.setProperty("username", (rs.getObject("username") != null)?rs.getObject("username").toString():"");
                    row.setProperty("firstName", (rs.getObject("firstName") != null)?rs.getObject("firstName").toString():"");
                    row.setProperty("lastName", (rs.getObject("lastName") != null)?rs.getObject("lastName").toString():"");
                    row.setProperty("email", (rs.getObject("email") != null)?rs.getObject("email").toString():"");
                    
                    rows.add(row);
                    break;
                }
            }
        } catch(Exception e) {
            LogUtil.error("Sample app - Form 1", e, "Error loading user data in load binder");
        } finally {
            //always close the connection after used
            try {
                if(con != null) {
                    con.close();
                }
            } catch(SQLException e) {/* ignored */}
        }
    }
    return rows;
}
  
//call load method with injected variable
return load(element, primaryKey, formData);

...

Validate the sum of a column values are less than 1000.

Code Block
 importimport java.util.Arrays;
import org.joget.apps.app.service.AppUtil;
import org.joget.apps.form.model.Element;
import org.joget.apps.form.model.Form;
import org.joget.apps.form.model.FormData;
import org.joget.apps.form.model.FormRow;
import org.joget.apps.form.model.FormRowSet;
import org.joget.apps.form.service.FormUtil;
 
public boolean validate(Element element, FormRowSet rows, FormData formData) {
    boolean result = true;
    if (rows != null && !rows.isEmpty()) {
        int total = 0;
        
        //Sum the values from column "amount"
        for (FormRow row : rows) {
            try {
                int amount = Integer.parseInt(row.getProperty("amount"));
                total += amount;
            } catch (Exception e) {}
        }
        
        //if amount larger than 1000
        if (total > 1000) {
            String id = FormUtil.getElementParameterName(element);
            formData.addFormError(id, "Total amount should not larger than 1000!!!!");
            result = false;
        }
    }
 
    return result;
}
 
//call validate method with injected variable
return validate(element, rows, formData);

...

Reuse Email tool to send separate email to each users.

Code Block
 

 

Use as Process Participant

Injected Variables:

...

. The following script is for a form not mapped to workflow assignment, therefore workflowAssignment is not available.

Code Block
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.joget.

...

apps.

...

app.model.AppDefinition;
import org.joget.

...

apps.

...

Expected Return Object:

    • A java.util.Collection of username in java.lang.String to be assign to the Workflow Activity.

Samples:

        Randomly assign an user in a department to a workflow activity.

Code Block
languagejava
import java.util.ArrayList;
import java.util.Collectionapp.service.AppPluginUtil;
import org.joget.apps.app.service.AppUtil;
import org.joget.directoryplugin.modelbase.UserApplicationPlugin;
import org.joget.directoryplugin.modelbase.service.ExtDirectoryManagerPlugin;
import org.joget.workflowplugin.modelbase.WorkflowActivityPluginManager;
import org.joget.plugin.property.model.PropertyEditable;
 
public CollectionObject getAssignees(WorkflowActivity activityexecute(AppDefinition appDef, HttpServletRequest request) { 
    CollectionString[] assigneesemails = new ArrayList() String[]{"test1@joget.org", "test2@joget.org"};
    
    //Reuse Email Tool ExtDirectoryManagerto directoryManagersend =separated (ExtDirectoryManager) pluginManager.getBean("directoryManager");
    email to a list of users;
    StringPlugin deptIdplugin = "D-005"pluginManager.getPlugin("org.joget.apps.app.lib.EmailTool");
    
    //Get total user in department default properties (SMTP setting) for email tool
    LongMap totalpropertiesMap = directoryManagerAppPluginUtil.getTotalUsersgetDefaultProperties(nullplugin, null, deptIdappDef, null, null, null, null);
    propertiesMap.put("pluginManager", pluginManager);
    propertiesMap.put("appDef", appDef);
    //Get random number from 0 to the total number of users in department
    int randompropertiesMap.put("request", request);
    
    ApplicationPlugin emailTool = (intApplicationPlugin) (Math.random() * total)plugin;
     
    //Getsend usersemail
 using directory manager
 for (String email Collection: userListemails) = directoryManager.getUsers(null, null, deptId, null, null, null, null, "firstName", false, random, 1);
{
        propertiesMap.put("toSpecific", email);
     for(Object u : userList){
        User user = (User) u propertiesMap.put("subject", "This is a test email for " + email);
        assigneespropertiesMap.add(user.getUsername())put("message", "Email content for " + email);
    }
    
       return assignees;
}

//callset getAssigneesproperties methodand withexecute injectedthe variable
return getAssignees(workflowActivity);

Use as Process Tool 

Injected Variables:

...

tool
        ((PropertyEditable) emailTool).setProperties(propertiesMap);
        emailTool.execute(propertiesMap);
    }
    
    return null;
}
 
//call execute method with injected variable
return execute(appDef, request);

Use as Process Participant

Injected Variables:

    • pluginManager - Plugin Manager service bean for convenient usage. (org.joget.plugin.base.PluginManager)
    • appDef - App definition of the processworkflowActivity - Workflow Activity that trying to retrieves assignee. (org.joget.apps.appworkflow.model.AppDefinition)request - Http Request object of current HTTP Request. Not available if the tool is trigger by Deadline. (javax.servlet.http.HttpServletRequestWorkflowActivity)

Expected Return Object:

    • None

Samples:

Start a new process in the same app with current record id.

Code Block
languagejava
 

 

Use as Userview Permission

Injected Variables:

...

    • A java.util.Collection of username in java.lang.String to be assign to the Workflow Activity.

Samples:

        Randomly assign an user in a department to a workflow activity.

Code Block
languagejava
import java.util.ArrayList;
import java.util.Collection;
import org.joget.apps.app.service.AppUtil;
import org.joget.directory.model.User

...

;
import org.joget.directory.model.service.ExtDirectoryManager;
import org.joget.workflow.model.WorkflowActivity;

public Collection getAssignees(WorkflowActivity activity) { 
    Collection assignees = new ArrayList();
    
    ExtDirectoryManager directoryManager = (ExtDirectoryManager) pluginManager.getBean("directoryManager");
    
    String deptId = "D-005";
    
    //Get total user in department
    Long total = directoryManager.getTotalUsers(null, null, deptId, null, null, null, null);
    
    //Get random number from 0 to the total number of users in department
    int random = (int) (Math.random() * total);
    
    //Get users using directory manager
    Collection userList = directoryManager.getUsers(null, null, deptId, null, null, null, null, "firstName", false, random, 1);
    for(Object u : userList){
        User user = (User) u;
        assignees.add(user.getUsername());
    }
    
    return assignees;
}

//call getAssignees method with injected variable
return getAssignees(workflowActivity);

Use as Process Tool 

Injected Variables:

    • workflowAssignment - The workflow tool activity assignment object. (org.joget.workflow.model.WorkflowAssignment)
    • pluginManager - Plugin Manager service bean for convenient usage. (org.joget.plugin.base.PluginManager)
    • appDef - App definition of the process. (org.joget.apps.app.model.AppDefinition)
    • request - Http Request object of current HTTP Request. Not available if the tool is trigger by Deadline. (javax.servlet.http.HttpServletRequest)

Expected Return Object:

    • None

Samples:

Start a new process in the same app with current record id.

Code Block
languagejava
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.joget.apps.app.model.AppDefinition;
import org.joget.apps.app.service.AppService;
import org.joget.apps.app.service.AppUtil;
import org.joget.workflow.model.service.WorkflowManager;
import org.joget.workflow.model.WorkflowAssignment;
import org.joget.workflow.model.WorkflowProcess;
 
public Object execute(WorkflowAssignment assignment, AppDefinition appDef, HttpServletRequest request) {
    AppService appService = (AppService) AppUtil.getApplicationContext().getBean("appService");
    WorkflowManager workflowManager = (WorkflowManager) AppUtil.getApplicationContext().getBean("workflowManager");
    
    //get current record id
    String recordId = appService.getOriginProcessId(assignment.getProcessId());
    
    //get process
    WorkflowProcess process = appService.getWorkflowProcessForApp(appDef.getAppId(), appDef.getVersion().toString(), "process2");
    
    //start process
    workflowManager.processStart(process.getId(), null, null, null, recordId, false);
    
    return null;
}
 
//call execute method with injected variable
return execute(workflowAssignment, appDef, request);

Use as Userview Permission

Injected Variables:

    • user - User object of current logged in user (org.joget.directory.model.User)
    • requestParams - Request parameters map of current HTTP Request (java.util.Map)

Expected Return Object:

    • A boolean value to indicate the user is authorized.

Samples:

Check the user is in a group and is an admin user.

Code Block
languagejava
import java.util.Collection;
import java.util.Map;
import org.joget.apps.app.service.AppUtil;
import org.joget.directory.model.Group;
import org.joget.directory.model.User;
import org.joget.directory.model.service.ExtDirectoryManager;
import org.joget.workflow.model.service.WorkflowUserManager;
import org.joget.workflow.util.WorkflowUtil;
public boolean isAuthorized(User user, Map params) { 
    //if no logged in user
    if (user == null) {
        return false;
    }
    //check current user is admin
    boolean isAdmin = WorkflowUtil.isCurrentUserInRole(WorkflowUserManager.ROLE_ADMIN);
    
    //check current user is in group "G-001"
    boolean inGroup = false;
    
    ExtDirectoryManager directoryManager = (ExtDirectoryManager) AppUtil.getApplicationContext().getBean("directoryManager");
    Collection groups = directoryManager.getGroupByUsername(user.getUsername());
    if (groups != null) {
        String groupId = "G-001";
        for (Group g : groups) {
            if (groupId.equals(g.getId())) {
                inGroup = true;
            }
        }
    }
    
    return isAdmin && inGroup;
}
  
//call isAuthorized method with injected variable
return isAuthorized(user, requestParams);

Expected Return Object:

    • A boolean value to indicate the user is authorized.

Samples:

Check the user is in a group and is an admin user.

Code Block
languagejava
 

...

Best Practices

1. Only import classes that are needed

...