Microstrategy SDK - Custom Task

mstr-sdk

https://lw.microstrategy.com/msdz/MSDL/901/docs/WCE_Creating_a_New_Bean-based_Task.htm#

From inside a Custom Task, how can we get access to the RequestKeys or ContainerServices?

RequestKeys keys = context.getRequestKeys();
ContainerServices cs = context.getContainerServices();

The 'context' variable is the parameter that is passed into our processRequest method.

How to establish a connection to the iServer / How to get a server session?

  1. Get the singleton object from WebObjectsFactory: WebObjectFactory woFact = WebObjectsFactory.getInstance()
  2. Create the empty session object: WebIServerSession sessionInfo = woFact.getIServerSession()
  3. Set the server name, the project name, the admin credential
  4. Invoke getSessionID() to actually create the session
import com.microstrategy.web.objects.WebObjectsFactory;
import com.microstrategy.web.objects.WebIServerSession;

public static WebIServerSession getServerSession(String serverName, String projectName, String loginName, String password) {
    WebIServerSession sessionInfo = null;
    try {
        WebObjectsFactory woFact = WebObjectsFactory.getInstance();
        sessionInfo = woFact.getIServerSession();
        sessionInfo.setServerName(serverName);
        sessionInfo.setProjectName(projectName);
        //sessionInfo.setServerPort(0);
        sessionInfo.setLogin(loginName);
        sessionInfo.setPassword(password);
        //sessionInfo.setAuthMode(EnumDSSXMLAuthModes.DssXmlAuthStandard);  
        sessionInfo.setApplicationType(EnumDSSXMLApplicationType.DssXmlApplicationCustomApp);

        //Create a new session
        sessionInfo.getSessionID();
    } catch (WebObjectsException ex) {
        System.out.println("Error creating a sesion");
    }
    return sessionInfo;
}

How to perform a lookup to see if an object exist?

Assume that we have establish a session with the IServer (see above), we can perform the search:

import com.microstrategy.web.objects.WebFolder;
import com.microstrategy.web.objects.WebIServerSession;
import com.microstrategy.web.objects.WebObjectSource;
import com.microstrategy.web.objects.WebObjectsException;
import com.microstrategy.web.objects.WebObjectsFactory;
import com.microstrategy.web.objects.WebSearch;
import com.microstrategy.web.objects.admin.users.WebUser;
import com.microstrategy.web.objects.admin.users.WebUserGroup;
import com.microstrategy.webapi.EnumDSSXMLApplicationType;
import com.microstrategy.webapi.EnumDSSXMLObjectSubTypes;
import com.microstrategy.webapi.EnumDSSXMLSearchDomain;

public static Object performSearch(WebIServerSession session, String pattern, int type, int searchDomain) {
    // type: EnumDSSXMLObjectSubTypes.DssXmlSubTypeUser
    // searchDomain: EnumDSSXMLSearchDomain.DssXmlSearchConfigurationAndAllProjects
    WebObjectSource  source = sessionInfo.getFactory().getObjectSource();
    WebSearch search = source.getNewSearchObject();
    search.setNamePattern(pattern);
    search.setAsync(false);
    search.types().add(type);
    search.setDomain(searchDomain);
    search.submit();
    WebFolder folder = search.getResults();
    if (folder.size() == 1) {
        return folder.get(0);
    } else {
        throw new Exception("Multiple objects found!");
    }
}

How to add a user to a group?

WebUserGroup group = (WebUserGroup) performSearch(....);
if (group != null) {
    WebUser user = (WebUser) performSearch(.....);
    if (user != null) {
        group.getMembers().add(user);
    } else {
        throw new Exception("User " + ... + " not found!");
    }
    source.save()
} else {
    throw new Exception("Group " + ... + " not found!");
}

How to create a security filter and assign it to a user?

WebUser webUser = null;
WebUserSecurityFilters sFilters = null;
WebObjectSource adminWebObjectSource = adminServerSession.getFactory().getObjectSource();
WebObjectSource uObjSource = serverSession.getFactory().getObjectSource();
String projectID = serverSession.getProjectID();

// Assuming that we've lookup the user (webUser is now not null)
sFilters = webUser.getSecurityFilters();
WebProject proj = (WebProject) adminWebObjectSource.getObject(projectID, EnumDSSXMLObjectTypes.DssXmlTypeProject);
Object secFilterObject = performSearch(uObjSource,secFilterName,EnumDSSXMLObjectSubTypes.DssXmlSubTypeMDSecurityFilter);
WebMDSecurityFilter newSecFilter;
if (secFilterObject != null) {
    uObjSource.deleteObject((WebObjectInfo) secFilterObject);                    
}

WebMDSecurityFilter sFilter = (WebMDSecurityFilter) uObjSource.getNewObject(EnumDSSXMLObjectTypes.DssXmlTypeMDSecurityFilter);
WebExpression exp = sFilter.getExpression();
exp.populate(secFilterExpression);

String folderID = uObjSource.getFolderID(EnumDSSXMLFolderNames.DssXmlFolderNameSystemMDSecurityFilters);
WebFolder folder = (WebFolder) uObjSource.getObject(folderID, EnumDSSXMLObjectTypes.DssXmlTypeFolder);
uObjSource.save(sFilter, filterName, folder);

newSecFilter = createSecurityFilterForJSP(serverSession,secFilterName,secFiltExp);
sFilters.put(proj, sFilter);

adminWebObjectSource.save(userGroup);
adminWebObjectSource.save(webUser);

Search the SDK documentation for "Creating a Security Filter", "Assigning a Security Filter to a User"

What can we do with AbstractBaseTask?

This is a research question

Custom task to create user and security filter:

package com.yourcompany.microstrategy.custom.task;

import java.util.*;
import com.microstrategy.utils.log.Level;
import com.microstrategy.web.app.tags.Log;
import com.microstrategy.web.beans.BeanFactory;
import com.microstrategy.web.beans.MarkupOutput;
import com.microstrategy.web.beans.RequestKeys;
import com.microstrategy.web.beans.UserBean;
import com.microstrategy.web.objects.WebExpression;
import com.microstrategy.web.objects.WebFolder;
import com.microstrategy.web.objects.WebIServerSession;
import com.microstrategy.web.objects.WebObjectInfo;
import com.microstrategy.web.objects.WebObjectSource;
import com.microstrategy.web.objects.WebObjectsException;
import com.microstrategy.web.objects.WebObjectsFactory;
import com.microstrategy.web.objects.WebProject;
import com.microstrategy.web.objects.WebSearch;
import com.microstrategy.web.objects.WebSubscriptionAddress;
import com.microstrategy.web.objects.admin.users.WebMDSecurityFilter;
import com.microstrategy.web.objects.admin.users.WebSimpleSecurityPluginLoginInfo;
import com.microstrategy.web.objects.admin.users.WebSubscriptionUserAddresses;
import com.microstrategy.web.objects.admin.users.WebUser;
import com.microstrategy.web.objects.admin.users.WebStandardLoginInfo;
import com.microstrategy.web.objects.admin.users.WebUserGroup;
import com.microstrategy.web.objects.admin.users.WebUserSecurityFilters;
import com.microstrategy.web.platform.ContainerServices;
import com.microstrategy.web.tasks.AbstractBaseTask;
import com.microstrategy.web.tasks.TaskException;
import com.microstrategy.web.tasks.TaskParameterMetadata;
import com.microstrategy.web.tasks.TaskRequestContext;
import com.microstrategy.webapi.EnumDSSXMLAuthModes;
import com.microstrategy.webapi.EnumDSSXMLFolderNames;
import com.microstrategy.webapi.EnumDSSXMLObjectSubTypes;
import com.microstrategy.webapi.EnumDSSXMLObjectTypes;
import com.microstrategy.webapi.EnumDSSXMLSearchDomain;
import com.microstrategy.webapi.EnumDSSXMLSubscriptionDeliveryType;
import com.yourcompany.properties.PropertiesSupport;
import java.util.Random;
import com.microstrategy.web.objects.WebProjectSource;
import com.microstrategy.web.objects.WebProjectInstances;
import com.microstrategy.web.objects.WebProjectInstance;
import com.microstrategy.webapi.EnumDSSXMLProjectStatus;
import com.microstrategy.web.objects.admin.users.WebPrivilegeCategories;
import com.microstrategy.web.objects.admin.users.WebPrivilegeCategory;
import com.microstrategy.web.objects.admin.users.WebPrivilegeEntry;
import com.microstrategy.web.beans.UserGroupBean;
/**   
*  This class is used to synchronize MSTR users with external application
*/
public class CreateCustomJavaSecurityFilter extends AbstractBaseTask {

    ////////////////////////////////////////////////
    //private  attributes
    private TaskParameterMetadata serverParam;
    private TaskParameterMetadata adminParam;
    private TaskParameterMetadata adminPasswordParam;
    private TaskParameterMetadata objectNameParam;
    private TaskParameterMetadata projectParam;
    private TaskParameterMetadata secFilterNameParam;
    private TaskParameterMetadata secFilterExpresionParam;
    private TaskParameterMetadata userFullNameParam;
    private TaskParameterMetadata emailNameParam;
    private TaskParameterMetadata emailAddrParam;
    private TaskParameterMetadata groupNameParam;
    private TaskParameterMetadata parentGroupParam;
    private TaskParameterMetadata printPrivilegeParam;
    private TaskParameterMetadata excelPrivilegeParam;
    private TaskParameterMetadata pdfPrivilegeParam;
    private TaskParameterMetadata adminPrivilegeParam;

    private String objectName;
    private String projectID;
    private String server;
    private String admin;
    private String adminPassword;
    private String project;
    private String secFilterName;
    private String secFiltExp;
    private String userFullName;
    private String emailName;
    private String emailAddr;
    private String groupName;
    private String parentGroup;
    private String printPrivilege;
    private String pdfPrivilege;
    private String excelPrivilege;
    private String adminPrivilege;

    public CreateCustomJavaSecurityFilter() {
        super("Assign new created security filter to the new created user. Dependign of app ver (JSP/ASP) different logic is applied");    
        secFilterNameParam = addParameterMetadata("securityFilterName"," MicroStrategy security filter name",true,null);
        secFilterExpresionParam = addParameterMetadata("securityFilterExpresison"," Security filter expression",true,null);
        objectNameParam = addParameterMetadata("objectName"," MicroStrategy object name (userName or userGroup)",true,null);
        projectParam = addParameterMetadata("project"," MicroStrategy project ID",true,null);
        serverParam = addParameterMetadata("server", "Server", true, null);
        adminParam = addParameterMetadata("adminUser", "Administrator user", true, null);
        adminPasswordParam = addParameterMetadata("password", "password", true, "");
        userFullNameParam = addParameterMetadata("userFullName", "Role Group name", true, "");
        emailNameParam = addParameterMetadata("emailName", "Email delivery name", false, "");
        emailAddrParam = addParameterMetadata("emailAddr", "Physical email address", false, "");
        groupNameParam = addParameterMetadata("groupName", "Group name", true, "");
        parentGroupParam = addParameterMetadata("parentGroupName", "Parent Group", true, "");
        printPrivilegeParam = addParameterMetadata("printPrivilege", "Print Privilege", true, "");
        excelPrivilegeParam = addParameterMetadata("excelPrivilege", "Export to Excel", true, "");
        pdfPrivilegeParam = addParameterMetadata("pdfPrivilege", "Export to PDF", true, "");
        adminPrivilegeParam = addParameterMetadata("adminPrivilege", "Admin Privilege", true, "");
    }

    /** 
     * Overridden method that is to be used each time when the task is being  executed  
     * @param context - type of the task context (xml,html,json)
     * @param mo      - markupoutput 
     */
    public void processRequest(TaskRequestContext context, MarkupOutput mo) throws TaskException {
        String methodName="processRequest";
        RequestKeys keys = context.getRequestKeys();
        objectName = keys.getValue(objectNameParam.getName());
        project = keys.getValue(projectParam.getName());
        secFiltExp = keys.getValue(secFilterExpresionParam.getName());
        secFilterName = keys.getValue(secFilterNameParam.getName());
        server = keys.getValue(serverParam.getName());
        admin = keys.getValue(adminParam.getName());
        adminPassword = keys.getValue(adminPasswordParam.getName());
        userFullName= keys.getValue(userFullNameParam.getName());
        emailName = keys.getValue(emailNameParam.getName());
        emailAddr = keys.getValue(emailAddrParam.getName());
        groupName = keys.getValue(groupNameParam.getName());
        parentGroup = keys.getValue(parentGroupParam.getName());
        printPrivilege = keys.getValue(printPrivilegeParam.getName());
        excelPrivilege = keys.getValue(excelPrivilegeParam.getName());
        pdfPrivilege = keys.getValue(pdfPrivilegeParam.getName());
        adminPrivilege = keys.getValue(adminPrivilegeParam.getName());
        WebIServerSession adminWebIServerSession= null;
        WebIServerSession normalWebIServerSession = null;

        try {
            /*
             * In MicroStrategy 8, there is only one type of session.  In MicroStrategy 9, there are two types
             * of sessions (admin and regular).  When we follow the instruction in TN31205 and TN31464, and we 
             * remove the iSession.setProjectName(project) from getAdminIServerSession, we can no longer obtain
             * the projectID from the admin IServer session.  We can go back to establishing 2 IServer sessions
             * (one regular session, and one admin session) like we did before.  We can also modify the application
             * code to store the project ID and pass the project ID to this custom task.  We can also follow
             * instruction in TN35228.  Following the instruction in TN35228 results in another exception.  
             * Right now, we do not have enough time to explore other alternatives.  Therefore, I am reverting back
             * to using two IServer sessions.  Notice that both getAdminWebIServerSession and getNormalWebIServerSession
             * both use the administrator account and password, but except for the iSession.setProjectName(project).
             * See MicroStrategy support case ID 633095.
             */

            adminWebIServerSession = getAdminWebIServerSession(server,project,0,admin,adminPassword,context.getContainerServices());
            WebObjectSource adminWOS = adminWebIServerSession.getFactory().getObjectSource();

            normalWebIServerSession = getNormalWebIServerSession(server,project,0,admin,adminPassword,context.getContainerServices());
            WebObjectSource normalWOS = normalWebIServerSession.getFactory().getObjectSource();
            projectID = normalWebIServerSession.getProjectID();
            if (Log.logger.isLoggable(Level.FINE)) {
            }

            Log.logger.logp(Level.INFO,  CreateCustomJavaSecurityFilter.class.getName(), methodName,"========== JSP =============");
            Log.logger.logp(Level.INFO,  CreateCustomJavaSecurityFilter.class.getName(), methodName,"projectID:" + projectID);
            Log.logger.logp(Level.INFO,  CreateCustomJavaSecurityFilter.class.getName(), methodName,"objectName:" + objectName);
            Log.logger.logp(Level.INFO,  CreateCustomJavaSecurityFilter.class.getName(), methodName,"project:" + project);
            Log.logger.logp(Level.INFO,  CreateCustomJavaSecurityFilter.class.getName(), methodName,"secFiltExp:" + secFiltExp);
            Log.logger.logp(Level.INFO,  CreateCustomJavaSecurityFilter.class.getName(), methodName,"secFilterName:" + secFilterName);
            Log.logger.logp(Level.INFO,  CreateCustomJavaSecurityFilter.class.getName(), methodName,"server:" + server);
            Log.logger.logp(Level.INFO,  CreateCustomJavaSecurityFilter.class.getName(), methodName,"admin:" + admin);
            Log.logger.logp(Level.INFO,  CreateCustomJavaSecurityFilter.class.getName(), methodName,"adminPassword:" + adminPassword);
            Log.logger.logp(Level.INFO,  CreateCustomJavaSecurityFilter.class.getName(), methodName,"userFullName:" + userFullName);
            Log.logger.logp(Level.INFO,  CreateCustomJavaSecurityFilter.class.getName(), methodName,"emailName:" + emailName);
            Log.logger.logp(Level.INFO,  CreateCustomJavaSecurityFilter.class.getName(), methodName,"emailAddr:" + emailAddr);
            Log.logger.logp(Level.INFO,  CreateCustomJavaSecurityFilter.class.getName(), methodName,"groupName:" + groupName);
            Log.logger.logp(Level.INFO,  CreateCustomJavaSecurityFilter.class.getName(), methodName,"parentGroup:" + parentGroup);
            Log.logger.logp(Level.INFO,  CreateCustomJavaSecurityFilter.class.getName(), methodName,"printPrivilege:" + printPrivilege);
            Log.logger.logp(Level.INFO,  CreateCustomJavaSecurityFilter.class.getName(), methodName,"pdfPrivilege:" + pdfPrivilege);
            Log.logger.logp(Level.INFO,  CreateCustomJavaSecurityFilter.class.getName(), methodName,"excelPrivilege:" + excelPrivilege);
            Log.logger.logp(Level.INFO,  CreateCustomJavaSecurityFilter.class.getName(), methodName,"adminPrivilege:" + adminPrivilege);

            WebUser webUser = null;
            WebUserSecurityFilters sFilters = null;

            // Check if the user exist.  Notice that the last parameter is EnumDSSXMLObjectSubTypes.DssXmlSubTypeUser
            Object userObject = checkIfExists(adminWOS,objectName,EnumDSSXMLObjectSubTypes.DssXmlSubTypeUser);
            if (userObject == null) {
                // The user does not exist
                Log.logger.logp(Level.INFO,  CreateCustomJavaSecurityFilter.class.getName(), methodName,"User " + objectName + " does not exist!");
                webUser = createUser(adminWebIServerSession,objectName,normalWOS,userFullName,emailAddr, emailName);    
                Log.logger.logp(Level.INFO,  CreateCustomJavaSecurityFilter.class.getName(), methodName,"User :" + webUser.getID() + " has been created");
            } else {
                // The user does exist
                Log.logger.logp(Level.INFO,  CreateCustomJavaSecurityFilter.class.getName(), methodName,"Object " + objectName + " exists!");
                webUser = (WebUser) userObject;

                // Modify the user (change name, email address, email name, etc)
                webUser = modifyUser(webUser,userFullName,emailAddr,emailName);
                Log.logger.logp(Level.INFO,  CreateCustomJavaSecurityFilter.class.getName(), methodName,"User :" + webUser.getID() + " has been modified");
            }

            // Automatically create group such as 
            createGroup(adminWOS,groupName,webUser, adminWebIServerSession,parentGroup);

            // Assign the user to appropriate groups
            WebUserGroup userGroup = assignUserToGroupJSP(adminWOS,groupName,webUser, adminWebIServerSession,parentGroup);
            Log.logger.logp(Level.INFO,  CreateCustomJavaSecurityFilter.class.getName(), methodName,"User :"+webUser.getID()+" has been assign to : "+userGroup.getID()+" MSTR group " + userGroup.getFullName());

            // Assign security filter
            // We first delete the existing security filter, create a new security filter, and the assign the new 
            // security filter to the user.  I think secFilterObject and newSecFilter are the same
            sFilters = webUser.getSecurityFilters();
            WebProject proj = (WebProject) adminWOS.getObject(projectID, EnumDSSXMLObjectTypes.DssXmlTypeProject);
            Object secFilterObject = checkIfExists(normalWOS,secFilterName,EnumDSSXMLObjectSubTypes.DssXmlSubTypeMDSecurityFilter);
            WebMDSecurityFilter newSecFilter;
            if (secFilterObject != null) {
                normalWOS.deleteObject((WebObjectInfo) secFilterObject);                    
            }
            newSecFilter = createSecurityFilterForJSP(normalWebIServerSession,secFilterName,secFiltExp);
            sFilters.put(proj, newSecFilter);
            Log.logger.logp(Level.INFO,  CreateCustomJavaSecurityFilter.class.getName(), methodName,"Security filter :"+newSecFilter.getID()+" has been created");

            adminWOS.save(userGroup);
            adminWOS.save(webUser);    

            handleAppLevelPrivileges(adminWOS,normalWOS,webUser);
            addOrRemoveUserFromSystemAdminGroup(adminWOS,"System Administration Reports Group",webUser,adminWebIServerSession);

            mo.append("<userID>"+webUser.getID()+"</userID>");
            mo.append("<secFilterID>"+newSecFilter.getID()+"</secFilterID>");
            mo.append("<userGroupID>"+userGroup.getID()+"</userGroupID>");

        } catch (Exception e) {
            /*
             * In my opinion, if an exception occur, we should not try to handle the exception.
             * We should let the system handle it (die with a 500) and let the front-end
             * handle it, which is better than catching the exception, logging it to the
             * log file, and let it sit rotten in the log file.  Basically, we are tricking
             * the system to think that everything was successful, but it is not.  I think we
             * should use the concept of global exception handling, and I try to eliminate
             * try-catch blocks, but in this case, I am not able to remove this particular
             * try-catch block because when I tried to do so, the signature of this method becomes
             * incompatible with the base class AbstractBaseTask, so I log the message to the
             * log file (so that we do not loose it), and I re-throw the Exception
             */
            Log.logger.logp(Level.SEVERE,  CreateCustomJavaSecurityFilter.class.getName(), methodName, e.getMessage(), e);
            throw new TaskException("Exception was thrown and logged to log file");
        }    
    }

    private synchronized void handleAppLevelPrivileges(WebObjectSource adminWOS, WebObjectSource normalWOS, WebUser user) throws Exception {
        HashMap m = new HashMap();
        m.put("printPrivilege", new ArrayList());
        m.put("pdfPrivilege", new ArrayList());
        m.put("excelPrivilege", new ArrayList());
        WebPrivilegeCategories cats = normalWOS.getUserServicesSource().getPrivilegeCategories(user);
        //Loop though all categories and privileges, determine which privileges we may be interested in
        for (int i = 0; i < cats.size(); i++) {
            WebPrivilegeCategory cat = cats.get(i);
            String catName = cat.getName(); //Category Name
            System.out.println("Privilege Category: " + catName);
            int size = cat.size();
            if (catName.equalsIgnoreCase("Web Reporter")) {
                for (int j = 0; j < size; j++) {
                    WebPrivilegeEntry privilege = cat.get(j);
                    String privilegeName = privilege.getName();
                    if (privilegeName.equalsIgnoreCase("Web print mode")) {
                        System.out.println("Privilege Name: " + privilegeName);
                        ArrayList list = (ArrayList) m.get("printPrivilege");
                        list.add(privilege);
                        break;
                    }
                }
            }
            if (catName.equalsIgnoreCase("Common Privileges")) {
                for (int j = 0; j < size; j++) {
                    WebPrivilegeEntry privilege = cat.get(j);
                    String privilegeName = privilege.getName();
                    if (privilegeName.equalsIgnoreCase("Export to Excel")) {
                        System.out.println("Privilege Name: " + privilegeName);
                        ArrayList list = (ArrayList) m.get("excelPrivilege");
                        list.add(privilege);
                    } else if (privilegeName.equalsIgnoreCase("Export to PDF")) {
                        System.out.println("Privilege Name: " + privilegeName);
                        ArrayList list = (ArrayList) m.get("pdfPrivilege");
                        list.add(privilege);                        
                    }
                }
            }
        }

        ArrayList list = (ArrayList) m.get("printPrivilege");
        int size = list.size();
        for (int i = 0; i < size; i++) {
            WebPrivilegeEntry privilege = (WebPrivilegeEntry) list.get(i);
            if ((printPrivilege.equalsIgnoreCase("Y")) && (! privilege.isGranted())) {
                privilege.grant();
            } else if ((printPrivilege.equalsIgnoreCase("N")) && (privilege.isGranted())) {
                privilege.revoke();                
            }
        }

        list = (ArrayList) m.get("pdfPrivilege");
        size = list.size();
        for (int i = 0; i < size; i++) {
            WebPrivilegeEntry privilege = (WebPrivilegeEntry) list.get(i);
            if ((pdfPrivilege.equalsIgnoreCase("Y")) && (! privilege.isGranted())) {
                privilege.grant();
            } else if ((pdfPrivilege.equalsIgnoreCase("N")) && (privilege.isGranted())) {
                privilege.revoke();                
            }
        }

        list = (ArrayList) m.get("excelPrivilege");
        size = list.size();
        for (int i = 0; i < size; i++) {
            WebPrivilegeEntry privilege = (WebPrivilegeEntry) list.get(i);
            if ((excelPrivilege.equalsIgnoreCase("Y")) && (! privilege.isGranted())) {
                privilege.grant();
            } else if ((excelPrivilege.equalsIgnoreCase("N")) && (privilege.isGranted())) {
                privilege.revoke();                
            }
        }

        normalWOS.save(user);    
    }

    /**
     * This method creates MSTR user
     * @param session         Administrator session
     * @param name            MSTR login name  
     * @param userFullName    MSTR user full name
     * @param emailAdrr        MSTR physical email address
     * @param emailName        MSTR email name 
     * @return WebUser
     */
    private WebUser createUser(WebIServerSession session, String name, WebObjectSource source,String userFullName,String emailAddr,String emailName) throws Exception {
        String methodName = "createUser";
        UserBean newUser = null;
        WebUser webUser = null;
        newUser = (UserBean) BeanFactory.getInstance().newBean("UserBean");
        newUser.setSessionInfo(session);
        newUser.InitAsNew();
        newUser.getUserEntityObject().setName(name);
        webUser = (WebUser) newUser.getUserEntityObject();

        /*
         * If email address is provided, create an object representing the email.
         * This object encapsulates the name, the email address, and the device.
         * The ID of the device is a configuration setting coming from the 
         * task.properties file.
         * After creating this email object, save it to the user account, and
         * set it as the default email address
         */
        if (emailAddr != null) {
            WebSubscriptionUserAddresses addresses = webUser.getAddresses();
            WebSubscriptionAddress subAddr = addresses.addNewAddress(EnumDSSXMLSubscriptionDeliveryType.DssXmlDeliveryTypeEmail);
            subAddr.setName(emailName);
            subAddr.setValue(emailAddr);
            subAddr.setDevice(PropertiesSupport.getInstance().getProp("device"));
            subAddr.save();
            addresses.setDefaultAddress(subAddr.getID());
            addresses.saveAddress(subAddr);
        }

        // Set login name, full name, and display name
        webUser.setLoginName(name);
        webUser.setFullName(userFullName);
        webUser.setDisplayName(userFullName);

        String password = generateRandomPassword();
        //WebStandardLoginInfo loginInfo = webUser.getStandardLoginInfo();
        //loginInfo.setPassword(password);
        //loginInfo.setPasswordExpiresAutomatically(false); // Password never expires
        //loginInfo.setStandardAuthAllowed(false); // Prevent the user from accessing MicroStrategy Web directly

        // Not sure what this does beside enabling the user
        WebSimpleSecurityPluginLoginInfo info = webUser.getSimpleSecurityPluginLoginInfo();
        webUser.setEnabled(true);
        info.setUid(webUser.getLoginName());

        newUser.save();
        source.save(webUser);
        return webUser;
    }

    /**
     * This method modifies MSTR user
     * @param user             MSTR user object
     * @param fullName        MSTR fullName 
     * @param emailAdrr        MSTR physical email address  
     * @return WebUser
     */
    private WebUser modifyUser(WebUser user, String fullName, String emailAddr, String emailName) throws Exception {
        String methodName = "modifyUser";
        if (emailAddr!=null || user!=null) {
            WebSubscriptionUserAddresses addresses = user.getAddresses();
            if (addresses != null) {
                boolean isExists = false;
                for (int i=0;i<addresses.size();i++) {
                    WebSubscriptionAddress bsa = addresses.get(i);
                    if(bsa.getValue().equals(emailAddr)) {
                        isExists = true;
                        break;
                    }
                }
                if (! isExists) {
                    WebSubscriptionAddress subAddr;
                    subAddr = addresses.addNewAddress(EnumDSSXMLSubscriptionDeliveryType.DssXmlDeliveryTypeEmail);
                    subAddr.setName(emailName);
                    subAddr.setValue(emailAddr);
                    subAddr.setDevice(PropertiesSupport.getInstance().getProp("device"));
                    subAddr.save();
                    addresses.setDefaultAddress(subAddr.getID());
                    addresses.saveAddress(subAddr);
                }
            }
            user.setFullName(fullName);
            user.setDisplayName(fullName);
            WebSimpleSecurityPluginLoginInfo info = user.getSimpleSecurityPluginLoginInfo();
            info.setUid(user.getLoginName());
        }
        return user;
    }

    private void addOrRemoveUserFromSystemAdminGroup(WebObjectSource source, String gName, WebUser user, WebIServerSession adminSession) throws Exception {
        String methodName = "addOrRemoveUserFromSystemAdminGroup";
        Log.logger.logp(Level.INFO,  CreateCustomJavaSecurityFilter.class.getName(), methodName, methodName + " invoked!");
        Object groupObject = checkIfExists(source,gName,EnumDSSXMLObjectSubTypes.DssXmlSubTypeUserGroup);
        if (groupObject != null) {
            // Group exist
            Log.logger.logp(Level.INFO,  CreateCustomJavaSecurityFilter.class.getName(), methodName,"Group with name " + gName + " does exist!");
            WebUserGroup wug = (WebUserGroup) groupObject; 
            if (user != null) {
                if (adminPrivilege.equalsIgnoreCase("Y")) {
                    wug.getMembers().add((WebUser)user);
                } else {
                    wug.getMembers().remove((WebUser)user);
                }

            }
            source.save(wug);
        } else {
            // Group does not exist
            throw new Exception("Group does not exist!  Group " + gName + " must be pre-created at the time of activation.  If this group was deleted (accidentally), you may need to deactivate on the application side, or manually re-create this group on the MicroStrategy side.");
        }
    }

    private void createGroup(WebObjectSource source, String gName, WebUser user, WebIServerSession adminSession,String parentGroup) throws Exception {
        String methodName = "createGroup";
        Log.logger.logp(Level.INFO,  CreateCustomJavaSecurityFilter.class.getName(), methodName, methodName + " invoked!");
        Object parentGroupObject = checkIfExists(source,parentGroup,EnumDSSXMLObjectSubTypes.DssXmlSubTypeUserGroup);
        if (parentGroupObject != null) {
            WebUserGroup pwug = null;
            WebUserGroup wug = null;
            pwug = (WebUserGroup) parentGroupObject; 
            Object groupObject = checkIfExists(source,gName,EnumDSSXMLObjectSubTypes.DssXmlSubTypeUserGroup);
            if (groupObject == null) {
                // The group gName does not exist.  Need to create it, and search for it again.
                UserGroupBean group = null;
                group =(UserGroupBean) BeanFactory.getInstance().newBean("UserGroupBean");
                group.setSessionInfo(adminSession);
                group.InitAsNew();
                group.getUserEntityObject().setFullName(gName);
                //Save the group
                group.save();
                groupObject = checkIfExists(source,gName,EnumDSSXMLObjectSubTypes.DssXmlSubTypeUserGroup);
            }
            if (groupObject != null) {
                // Group gName exists.  We were able to search for it or create it
                wug = (WebUserGroup) groupObject; 
                source.save(wug);
                pwug.getMembers().add(wug);
                source.save(pwug);
            } else {
                // Something is really wrong.  We are unable to create or search for group gName
                throw new Exception("Something is really wrong.  We are unable to create or search for group '" + gName + "'");
            }
        } else {
            throw new Exception("Parent group '" + parentGroup + "' does not exist!  Did we accidentally delete this parent group?  If so, we may have to manually recreate it.");
        }
    }

    /**
     * This method assigns the user to the MSTR group (JSP ver)
     * @param source         MSTR source object
     * @param gName            MSTR group name
     * @param user            MSTR user object
     * @param adminSession    MSTR IServer session
     * @return WebUserGroup 
     */
    private WebUserGroup assignUserToGroupJSP(WebObjectSource source, String gName, WebUser user, WebIServerSession adminSession,String parentGroup) throws Exception {
        String methodName = "assignUserToGroupJSP";
        Object groupObject = checkIfExists(source,gName,EnumDSSXMLObjectSubTypes.DssXmlSubTypeUserGroup);
        WebUserGroup wug = null;
        Log.logger.logp(Level.INFO,  CreateCustomJavaSecurityFilter.class.getName(), methodName, methodName + " invoked!");
        if (groupObject != null) {
            // Group exist
            Log.logger.logp(Level.INFO,  CreateCustomJavaSecurityFilter.class.getName(), methodName,"Group with name " + gName + " does exist!");
            wug = (WebUserGroup) groupObject; 
            if (wug != null) {
                if (user != null) {
                    wug.getMembers().add((WebUser)user);
                }
            }
            source.save(wug);
        } else {
            // Group does not exist
            throw new Exception("Group does not exist!  Group " + gName + " must be pre-created at the time of activation.  If this group was created and deleted (accidentally), you may need to deactivate on the application side, or manually re-create this group on the MicroStrategy side.");
        }
        return wug;
    }

    /**
     * This method creates MSTR security filter (JSP ver)
     * @param sessionInfo    MSTR IServer session
     * @param filterName    MSTR Security filter name
     * @param expression    MSTR security filter expression
     * @return WebMDSecurityFilter
     */
    private WebMDSecurityFilter createSecurityFilterForJSP(WebIServerSession sessionInfo, String filterName, String expression) throws Exception{
        String methodName="createSecurityFilterForJSP";
        WebObjectSource source = sessionInfo.getFactory().getObjectSource();
        Log.logger.logp(Level.INFO,  CreateCustomJavaSecurityFilter.class.getName(), methodName, methodName + " invoked!");

        WebMDSecurityFilter sFilter = (WebMDSecurityFilter) source.getNewObject(EnumDSSXMLObjectTypes.DssXmlTypeMDSecurityFilter);
        WebExpression exp = sFilter.getExpression();
        exp.populate(expression);

        String folderID = source.getFolderID(EnumDSSXMLFolderNames.DssXmlFolderNameSystemMDSecurityFilters);
        WebFolder folder = (WebFolder) source.getObject(folderID, EnumDSSXMLObjectTypes.DssXmlTypeFolder);
        source.save(sFilter, filterName, folder);

        Log.logger.logp(Level.INFO,  CreateCustomJavaSecurityFilter.class.getName(), methodName,"Security filter created "+sFilter.getID());
        return sFilter;
    }

    /**
     * This method creates MSTR IServer session to the using following project name
     * @param server        MSTR server name
     * @param project        MSTR project name
     * @param port            MSTR IServer port number
     * @param uid            MSTR user login
     * @param pwd            MSTR user password
     * @param cntSvcs        Container services
     * @return WebIserverSession
     */
    private static WebIServerSession getAdminWebIServerSession(String server, String project, int port, String uid,String pwd, ContainerServices cntSvcs) throws WebObjectsException {
        WebIServerSession iSession = WebObjectsFactory.getInstance().getIServerSession(); 
        iSession.setServerName(server); 
        //iSession.setProjectName(project);
        iSession.setServerPort(port); 
        iSession.setLogin(uid); 
        iSession.setPassword(pwd);
        iSession.setAuthMode(EnumDSSXMLAuthModes.DssXmlAuthStandard);  
        iSession.getSessionID();
        return iSession;
    }

    /*
     * In MicroStrategy 8, there is only one type of session.  In MicroStrategy 9, there are two types
     * of sessions (admin and regular).  When we follow the instruction in TN31205 and TN31464, and we 
     * remove the iSession.setProjectName(project) from getAdminIServerSession, we can no longer obtain
     * the projectID from the admin IServer session.  We can go back to establishing 2 IServer sessions
     * (one regular session, and one admin session) like we did before.  We can also modify the application
     * code to store the project ID and pass the project ID to this custom task.  We can also follow
     * instruction in TN35228 (which is the approach being used here).  See MicroStrategy support case
     * ID 633095.
     */
    private WebIServerSession getNormalWebIServerSession(String server, String project, int port, String uid,String pwd, ContainerServices cntSvcs) throws WebObjectsException {
        WebIServerSession iSession = WebObjectsFactory.getInstance().getIServerSession(); 
        iSession.setServerName(server); 
        iSession.setProjectName(project);
        iSession.setServerPort(port); 
        iSession.setLogin(uid); 
        iSession.setPassword(pwd);
        iSession.setAuthMode(EnumDSSXMLAuthModes.DssXmlAuthStandard);  
        iSession.getSessionID();
        return iSession;
    }

    /**
     * This method checks if an object exists
     * @param source    MSTR source object
     * @param name        MSTR object name
     * @param type        MSTR object type
     * @return Object
     */
    private Object checkIfExists(WebObjectSource source, String name, int type) throws Exception{
        String methodName="checkIfExists";
        WebSearch search = null;
        if (type == EnumDSSXMLObjectSubTypes.DssXmlSubTypeUser) {
            Log.logger.logp(Level.INFO,  CreateCustomJavaSecurityFilter.class.getName(), methodName,"Searching for user with login name :" + name);
            search = source.getNewSearchObject();
            search.setAbbreviationPattern(name);
            search.setAsync(false);
            search.types().add(EnumDSSXMLObjectSubTypes.DssXmlSubTypeUser);
            search.setDomain(EnumDSSXMLSearchDomain.DssXmlSearchConfigurationAndAllProjects);
            return performSearch(search);
        } else if (type==EnumDSSXMLObjectSubTypes.DssXmlSubTypeUserGroup) {
            Log.logger.logp(Level.INFO,  CreateCustomJavaSecurityFilter.class.getName(), methodName,"Searching for group with name :" + name);
            search = source.getNewSearchObject();
            search.setAbbreviationPattern(name);
            search.setAsync(false);
            search.types().add(EnumDSSXMLObjectSubTypes.DssXmlSubTypeUserGroup);
            search.setDomain(EnumDSSXMLSearchDomain.DssXmlSearchConfigurationAndAllProjects);
            return performSearch(search);
        } else {
            Log.logger.logp(Level.INFO,  CreateCustomJavaSecurityFilter.class.getName(), methodName,"Searching for object with name :" + name);
            search = source.getNewSearchObject();
            search.setNamePattern(name);
            search.setAsync(false);
            search.types().add(type);
            //search.setDomain(EnumDSSXMLSearchDomain.DssXmlSearchConfigurationAndAllProjects);
            return performSearch(search);
        }
    }

    /**
     * This method searches given object
     * @param search        MSTR search object
     * @return Object
     */
    public static Object performSearch(WebSearch search) throws Exception{
        String methodName = "performSearch";
        search.submit();
        WebFolder folder = search.getResults();
        if (folder.size() > 0) {
            if (folder.size() == 1) {
                return folder.get(0);
            } else {
                throw new Exception("Search returns more than 1 object!");
            }
        }
        return null;
    }

    /**
     * This method generate a random password
     */
    private String generateRandomPassword() {
        String characterSet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()";
        Random rnd = new Random();
        int desiredLength = 8;
        StringBuilder sb = new StringBuilder( desiredLength );
        for (int i = 0; i < desiredLength; i++ ) {
            sb.append( characterSet.charAt( rnd.nextInt(characterSet.length()) ) );
        }
        return sb.toString();
    }
}

Custom task to create user and security filter (different from above):

package com.yourcompany.microstrategy.custom.task;

import java.util.Enumeration;
import java.util.Random;

import com.microstrategy.utils.log.Level;
import com.microstrategy.web.app.tags.Log;
import com.microstrategy.web.beans.BeanFactory;
import com.microstrategy.web.beans.MarkupOutput;
import com.microstrategy.web.beans.RequestKeys;
import com.microstrategy.web.beans.UserBean;
import com.microstrategy.web.objects.WebExpression;
import com.microstrategy.web.objects.WebFolder;
import com.microstrategy.web.objects.WebIServerSession;
import com.microstrategy.web.objects.WebObjectInfo;
import com.microstrategy.web.objects.WebObjectSource;
import com.microstrategy.web.objects.WebObjectsException;
import com.microstrategy.web.objects.WebObjectsFactory;
import com.microstrategy.web.objects.WebProject;
import com.microstrategy.web.objects.WebSearch;
import com.microstrategy.web.objects.WebSubscriptionAddress;
import com.microstrategy.web.objects.admin.users.WebMDSecurityFilter;
import com.microstrategy.web.objects.admin.users.WebSimpleSecurityPluginLoginInfo;
import com.microstrategy.web.objects.admin.users.WebSubscriptionUserAddresses;
import com.microstrategy.web.objects.admin.users.WebUser;
import com.microstrategy.web.objects.admin.users.WebStandardLoginInfo;
import com.microstrategy.web.objects.admin.users.WebUserEntity;
import com.microstrategy.web.objects.admin.users.WebUserGroup;
import com.microstrategy.web.objects.admin.users.WebUserList;
import com.microstrategy.web.objects.admin.users.WebUserSecurityFilters;
import com.microstrategy.web.platform.ContainerServices;
import com.microstrategy.web.tasks.AbstractBaseTask;
import com.microstrategy.web.tasks.TaskException;
import com.microstrategy.web.tasks.TaskParameterMetadata;
import com.microstrategy.web.tasks.TaskRequestContext;
import com.microstrategy.webapi.EnumDSSXMLAuthModes;
import com.microstrategy.webapi.EnumDSSXMLFolderNames;
import com.microstrategy.webapi.EnumDSSXMLObjectSubTypes;
import com.microstrategy.webapi.EnumDSSXMLObjectTypes;
import com.microstrategy.webapi.EnumDSSXMLSearchDomain;
import com.microstrategy.webapi.EnumDSSXMLSubscriptionDeliveryType;
import com.yourcompany.properties.PropertiesSupport;

/**
 * This class is used to synchronize MSTR users with external application
 */
public class CreateCustomDotNetSecurityFilter extends AbstractBaseTask {

    ////////////////////////////////////////////////
    //private  attributes
    private TaskParameterMetadata serverParam;
    private TaskParameterMetadata adminParam;
    private TaskParameterMetadata adminPasswordParam;
    private TaskParameterMetadata objectNameParam;
    private TaskParameterMetadata flagParam;
    private TaskParameterMetadata projectParam;
    private TaskParameterMetadata secFilterNameParam;
    private TaskParameterMetadata secFilterExpresionParam;
    private TaskParameterMetadata organizationIDParam;
    private TaskParameterMetadata roleIDParam;
    private TaskParameterMetadata userFullNameParam;
    private TaskParameterMetadata emailNameParam;
    private TaskParameterMetadata emailAddrParam;
    private TaskParameterMetadata groupNameParam;
    private TaskParameterMetadata activeGroupParam;
    private String roleID;
    private String organizationID;
    private String objectName;
    private String flag;
    private String projectID;
    private String server;
    private String admin;
    private String adminPassword;
    private String project;
    private String secFilterName;
    private String secFiltExp;
    private String userFullName;
    private String emailName;
    private String emailAddr;
    private String groupName;
    private String activeGroupID;

    public CreateCustomDotNetSecurityFilter() {
        super("Assign new created security filter to the new created user. Dependign of app ver (JSP/ASP) different logic is applied");    
        secFilterNameParam = addParameterMetadata("securityFilterName"," MicroStrategy security filter name",true,null);
        secFilterExpresionParam = addParameterMetadata("securityFilterExpresison"," Security filter expression",false,null);
        objectNameParam = addParameterMetadata("objectName"," MicroStrategy object name (userName or userGroup)",true,null);
        flagParam = addParameterMetadata("flag"," flag that informs whether object is an user or user group",true,null);
        projectParam = addParameterMetadata("project"," MicroStrategy project ID",true,null);
        serverParam = addParameterMetadata("server", "Server", true, null);
        adminParam = addParameterMetadata("adminUser", "Administrator user", true, null);
        adminPasswordParam = addParameterMetadata("password", "password", true, "");
        organizationIDParam = addParameterMetadata("organizationID", "Organization ID", false, "");
        roleIDParam = addParameterMetadata("roleID", "Role Group name", false, "");
        userFullNameParam = addParameterMetadata("userFullName", "Role Group name", false, "");
        emailNameParam = addParameterMetadata("emailName", "Email delivery name", false, "");
        emailAddrParam = addParameterMetadata("emailAddr", "Physical email address", false, "");
        groupNameParam = addParameterMetadata("groupName", "Group name", false, "");
        activeGroupParam = addParameterMetadata("activeGroupID", "Active MSTR group that user belongs to", false, "");
    }

    /** 
     * Overridden method that is to be used each time when the task is being  executed  
     * @param context - type of the task context (xml,html,json)
     * @param mo      - markupoutput 
     */
    public void processRequest(TaskRequestContext context, MarkupOutput mo) throws TaskException {
        String methodName="processRequest";
        RequestKeys keys = context.getRequestKeys();
        objectName = keys.getValue(objectNameParam.getName());
        flag = keys.getValue(flagParam.getName());
        project = keys.getValue(projectParam.getName());
        secFiltExp = keys.getValue(secFilterExpresionParam.getName());
        secFilterName = keys.getValue(secFilterNameParam.getName());
        server = keys.getValue(serverParam.getName());
        admin = keys.getValue(adminParam.getName());
        adminPassword = keys.getValue(adminPasswordParam.getName());
        roleID = keys.getValue(roleIDParam.getName());
        organizationID = keys.getValue(organizationIDParam.getName());
        userFullName = keys.getValue(userFullNameParam.getName());
        emailName = keys.getValue(emailNameParam.getName());
        emailAddr = keys.getValue(emailAddrParam.getName());
        groupName = keys.getValue(groupNameParam.getName());
        activeGroupID= keys.getValue(activeGroupParam.getName());
        WebIServerSession adminServerSession;
        try {
            adminServerSession = getAdminIServerSession(server,project,0,admin,adminPassword,context.getContainerServices());
            WebObjectSource wos = adminServerSession.getFactory().getObjectSource();

            projectID = adminServerSession.getProjectID();
            if (Log.logger.isLoggable(Level.FINE)) {
            }

            Log.logger.logp(Level.INFO,  CreateCustomDotNetSecurityFilter.class.getName(), methodName,"========== ASP =============");
            Log.logger.logp(Level.INFO,  CreateCustomDotNetSecurityFilter.class.getName(), methodName,"projectID:" + projectID);
            Log.logger.logp(Level.INFO,  CreateCustomDotNetSecurityFilter.class.getName(), methodName,"objectName:" + objectName);
            Log.logger.logp(Level.INFO,  CreateCustomDotNetSecurityFilter.class.getName(), methodName,"flag:" + flag);
            Log.logger.logp(Level.INFO,  CreateCustomDotNetSecurityFilter.class.getName(), methodName,"project:" + project);
            Log.logger.logp(Level.INFO,  CreateCustomDotNetSecurityFilter.class.getName(), methodName,"secFiltExp:" + secFiltExp);
            Log.logger.logp(Level.INFO,  CreateCustomDotNetSecurityFilter.class.getName(), methodName,"secFilterName:" + secFilterName);
            Log.logger.logp(Level.INFO,  CreateCustomDotNetSecurityFilter.class.getName(), methodName,"server:" + server);
            Log.logger.logp(Level.INFO,  CreateCustomDotNetSecurityFilter.class.getName(), methodName,"admin:" + admin);
            Log.logger.logp(Level.INFO,  CreateCustomDotNetSecurityFilter.class.getName(), methodName,"adminPassword:" + adminPassword);
            Log.logger.logp(Level.INFO,  CreateCustomDotNetSecurityFilter.class.getName(), methodName,"roleID:" + roleID);
            Log.logger.logp(Level.INFO,  CreateCustomDotNetSecurityFilter.class.getName(), methodName,"organizationID:" + organizationID);
            Log.logger.logp(Level.INFO,  CreateCustomDotNetSecurityFilter.class.getName(), methodName,"userFullName:" + userFullName);
            Log.logger.logp(Level.INFO,  CreateCustomDotNetSecurityFilter.class.getName(), methodName,"emailName:" + emailName);
            Log.logger.logp(Level.INFO,  CreateCustomDotNetSecurityFilter.class.getName(), methodName,"emailAddr:" + emailAddr);
            Log.logger.logp(Level.INFO,  CreateCustomDotNetSecurityFilter.class.getName(), methodName,"groupName:" + groupName);
            Log.logger.logp(Level.INFO,  CreateCustomDotNetSecurityFilter.class.getName(), methodName,"activeGroupID:" + activeGroupID);

            if (flag.equalsIgnoreCase("u")) {
                WebUser webUser = null;
                WebUserSecurityFilters sFilters = null;

                // Check if the user exist.  Notice that the last parameter is EnumDSSXMLObjectSubTypes.DssXmlSubTypeUser
                Object userObject = checkIfExists(wos,objectName,EnumDSSXMLObjectSubTypes.DssXmlSubTypeUser);
                if (userObject == null) {
                    // The user does not exist
                    Log.logger.logp(Level.INFO,  CreateCustomDotNetSecurityFilter.class.getName(), methodName,"User " + objectName + " does not exist!");
                    webUser = createUser(adminServerSession,objectName,wos,userFullName,emailAddr, emailName);
                    Log.logger.logp(Level.INFO,  CreateCustomDotNetSecurityFilter.class.getName(), methodName,"User :" + webUser.getID() + " has been created");
                } else {
                    // The user does exist
                    Log.logger.logp(Level.INFO,  CreateCustomDotNetSecurityFilter.class.getName(), methodName,"Object " + objectName + " exists!");
                    webUser = (WebUser) userObject;

                    // Modify the user (change name, email address, email name, etc)
                    webUser = modifyUser(webUser,userFullName,emailAddr,emailName);
                    Log.logger.logp(Level.INFO,  CreateCustomDotNetSecurityFilter.class.getName(), methodName,"User :" + webUser.getID() + " has been modified");
                }

                // Assign the user to appropriate groups
                WebUserGroup userGroup = assignUserToGroupASP(wos,roleID,webUser);
                Log.logger.logp(Level.INFO,  CreateCustomDotNetSecurityFilter.class.getName(), methodName,"User :"+webUser.getID()+" has been assign to : " + roleID + " MSTR group");

                // Assign security filter
                // We first delete the existing security filter, create a new security filter, and the assign the new 
                // security filter to the user.  I think secFilterObject and newSecFilter are the same
                sFilters = webUser.getSecurityFilters();
                WebProject proj = (WebProject) wos.getObject(projectID, EnumDSSXMLObjectTypes.DssXmlTypeProject);
                Object secFilterObject = checkIfExists(wos,secFilterName,EnumDSSXMLObjectSubTypes.DssXmlSubTypeMDSecurityFilter);
                WebMDSecurityFilter newSecFilter;
                if (secFilterObject != null) {
                    wos.deleteObject((WebObjectInfo) secFilterObject);
                }
                newSecFilter = createRolesSecurityFilter(adminServerSession, roleID, organizationID, secFilterName);
                sFilters.put(proj, newSecFilter);
                Log.logger.logp(Level.INFO,  CreateCustomDotNetSecurityFilter.class.getName(), methodName,"Security filter :"+newSecFilter.getID()+" has been created");

                wos.save(userGroup);
                wos.save(webUser);    
            }    
        } catch (Exception e) {
            /*
             * In my opinion, if an exception occur, we should not try to handle the exception.
             * We should let the system handle it (die with a 500) and let the front-end
             * handle it, which is better than catching the exception, logging it to the
             * log file, and let it sit rotten in the log file.  Basically, we are tricking
             * the system to think that everything was successful, but it is not.  I think we
             * should use the concept of global exception handling, and I try to eliminate
             * try-catch blocks, but in this case, I am not able to remove this particular
             * try-catch block because when I tried to do so, the signature of this method becomes
             * incompatible with the base class AbstractBaseTask, so I log the message to the
             * log file (so that we do not loose it), and I re-throw the Exception
             */
            Log.logger.logp(Level.SEVERE,  CreateCustomDotNetSecurityFilter.class.getName(), methodName, e.getMessage(), e);
            throw new TaskException("Exception was thrown and logged to log file");
        }
    }

    /**
     * This method creates MSTR user
     * @param session         Administrator session
     * @param name            MSTR login name
     * @param userFullName    MSTR user full name
     * @param emailAdrr        MSTR physical email address  
     * @param emailName        MSTR email name 
     * @return WebUser
     */
    private WebUser createUser(WebIServerSession session, String name, WebObjectSource source,String userFullName,String emailAddr,String emailName) throws Exception {
        String methodName = "createUser";
        UserBean newUser = null;
        WebUser webUser = null;
        newUser = (UserBean) BeanFactory.getInstance().newBean("UserBean");
        newUser.setSessionInfo(session);
        newUser.InitAsNew();
        newUser.getUserEntityObject().setName(name);
        webUser = (WebUser) newUser.getUserEntityObject();

        /*
         * If email address is provided, create an object representing the email.
         * This object encapsulates the name, the email address, and the device.
         * The ID of the device is a configuration setting coming from the 
         * task.properties file.
         * After creating this email object, save it to the user account, and
         * set it as the default email address
         */
        if (emailAddr != null) {
            WebSubscriptionUserAddresses addresses = webUser.getAddresses();
            WebSubscriptionAddress subAddr = addresses.addNewAddress(EnumDSSXMLSubscriptionDeliveryType.DssXmlDeliveryTypeEmail);
            subAddr.setName(emailName);
            subAddr.setValue(emailAddr);
            subAddr.setDevice(PropertiesSupport.getInstance().getProp("device"));
            subAddr.save();
            addresses.setDefaultAddress(subAddr.getID());
            addresses.saveAddress(subAddr);
        }

        // Set login name, full name, and display name
        webUser.setLoginName(name);
        webUser.setFullName(userFullName);
        webUser.setDisplayName(userFullName);

        String password = generateRandomPassword();
        //WebStandardLoginInfo loginInfo = webUser.getStandardLoginInfo();
        //loginInfo.setPassword(password);
        //loginInfo.setPasswordExpiresAutomatically(false); // Password never expires
        //loginInfo.setStandardAuthAllowed(false);  // Prevent the user from accessing MicroStrategy Web directly

        // Not sure what this does beside enabling the user
        WebSimpleSecurityPluginLoginInfo info = webUser.getSimpleSecurityPluginLoginInfo();
        webUser.setEnabled(true);
        info.setUid(webUser.getLoginName());

        newUser.save();
        source.save(webUser);
        return webUser;
    }

    /**
     * This method modifies MSTR user
     * @param user             MSTR user object
     * @param fullName        MSTR fullName 
     * @param emailAdrr        MSTR physical email address 
     * @param emailName        MSTR email name
     * @return WebUser
     */
    private WebUser modifyUser(WebUser user, String fullName, String emailAddr, String emailName) throws Exception {
        String methodName = "modifyUser";
        if (emailAddr!=null || user!=null) {
            WebSubscriptionUserAddresses addresses = user.getAddresses();
            if (addresses != null) {
                boolean isExists = false;
                for (int i=0;i<addresses.size();i++) {
                    WebSubscriptionAddress bsa = addresses.get(i);
                    if(bsa.getValue().equals(emailAddr)) {
                        isExists = true;
                        break;
                    }
                }

                if (! isExists) {
                    WebSubscriptionAddress subAddr;
                    subAddr = addresses.addNewAddress(EnumDSSXMLSubscriptionDeliveryType.DssXmlDeliveryTypeEmail);
                    subAddr.setName(emailName);
                    subAddr.setValue(emailAddr);
                    subAddr.setDevice(PropertiesSupport.getInstance().getProp("device"));
                    subAddr.save();
                    addresses.setDefaultAddress(subAddr.getID());
                    addresses.saveAddress(subAddr);
                }
            }
            user.setFullName(fullName);
            user.setDisplayName(fullName);
            WebSimpleSecurityPluginLoginInfo info = user.getSimpleSecurityPluginLoginInfo();
            info.setUid(user.getLoginName());
        }
        return user;
    }

    /**
     * This method assigns the user to the MSTR group
     * @param source         MSTR object source
     * @param groupID        MSTR group ID 
     * @param user            MSTR user object
     * @return WebUserGroup
     */
    private WebUserGroup assignUserToGroupASP(WebObjectSource source, String groupID, WebUser user) throws Exception {
        String methodName = "assignUserToGroupASP";
        /*********************************************************************
         * Remove user from all of the groups that he belongs to              *
         *********************************************************************/
        user.populate();
        WebUserList lParents=user.getParents();
        for(Enumeration<WebUserEntity> lEnum = lParents.elements() ; lEnum.hasMoreElements() ;){
            WebUserEntity lUserEntity = lEnum.nextElement();
              lUserEntity.getParents().remove(user);
              source.save(lUserEntity);
        }
        WebUserGroup userGroup = (WebUserGroup) source.getObject(groupID,EnumDSSXMLObjectTypes.DssXmlTypeUser); 
        if( userGroup != null) {
            userGroup.getMembers().add((WebUser)user);
        } else {
            // Group does not exist
            throw new Exception("Group ID " + groupID + " does not exist!");
        }
        return userGroup;
    }

    /**
     * This method creates MSTR security filter (ASP ver)
     * @param sessionInfo        MSTR IServer session
     * @param roleID            role ID
     * @param organizationID     organization ID
     * @param filterName        MSTR Security filter name 
     * @return WebMDSecurityFilter 
     */
    private WebMDSecurityFilter createRolesSecurityFilter(WebIServerSession sessionInfo, String roleID, String organizationID, String filterName) throws Exception {
        String methodName = "createRolesSecurityFilter";
        WebObjectSource source = sessionInfo.getFactory().getObjectSource();
        WebMDSecurityFilter sFilter = (WebMDSecurityFilter) source.getNewObject(EnumDSSXMLObjectTypes.DssXmlTypeMDSecurityFilter);
        String expression = createExp(roleID,organizationID);
        WebExpression exp = sFilter.getExpression();
        exp.populate(expression);
        String folderID = source.getFolderID(EnumDSSXMLFolderNames.DssXmlFolderNameSystemMDSecurityFilters);
        WebFolder folder = (WebFolder) source.getObject(folderID, EnumDSSXMLObjectTypes.DssXmlTypeFolder);
        source.save(sFilter, filterName, folder);
        return sFilter;
    }

    /**
     * This method creates MSTR security filter expression (ASP ver)
     * @paramr roleID                roleID
     * @param organizationID        organizationID 
     * @return string with security filter`s expression
     */
    private String createExp(String roleID, String organizationID) throws Exception {
        String role = PropertiesSupport.getInstance().getProp(roleID);
        String hierarchy = role.split(",")[1];
        StringBuilder sb = new StringBuilder(hierarchy).append("@ID in (\"").append(organizationID).append("\")");
        return sb.toString();
    }

    /**
     * This method creates MSTR IServer session to the using following project name
     * @param server        MSTR server name
     * @param project        MSTR project name  
     * @param port            MSTR IServer port number
     * @param uid            MSTR user login
     * @param pwd            MSTR user password 
     * @param cntSvcs        Container services
     * @return WebIserverSession
     */
    private static WebIServerSession getAdminIServerSession(String server, String project, int port, String uid,String pwd, ContainerServices cntSvcs) throws WebObjectsException {
        WebIServerSession iSession = WebObjectsFactory.getInstance().getIServerSession(); 
        iSession.setServerName(server); 
        iSession.setProjectName(project);
        iSession.setServerPort(port); 
        iSession.setLogin(uid); 
        iSession.setPassword(pwd);
        iSession.setAuthMode(EnumDSSXMLAuthModes.DssXmlAuthStandard);  
        iSession.getSessionID();
        return iSession;
    }

    /**
     * This method checks if an object exists
     * @param source        MSTR source object
     * @param name        MSTR object name
     * @param type        MSTR object type
     * @return Object
     */
    private Object checkIfExists(WebObjectSource source, String name, int type) throws Exception{
        String methodName = "checkIfExists";
        WebSearch search = null;
        if (type == EnumDSSXMLObjectSubTypes.DssXmlSubTypeUser) {
            Log.logger.logp(Level.INFO,  CreateCustomDotNetSecurityFilter.class.getName(), methodName,"Searching for user with login name :" + name);
            search = source.getNewSearchObject();
            search.setAbbreviationPattern(name);
            search.setAsync(false);
            search.types().add(EnumDSSXMLObjectSubTypes.DssXmlSubTypeUser);
            search.setDomain(EnumDSSXMLSearchDomain.DssXmlSearchConfigurationAndAllProjects);
            return performSearch(search);
        } else if (type==EnumDSSXMLObjectSubTypes.DssXmlSubTypeUserGroup) {
            Log.logger.logp(Level.INFO,  CreateCustomDotNetSecurityFilter.class.getName(), methodName,"Searching for group with name :" + name);
            search = source.getNewSearchObject();
            search.setAbbreviationPattern(name);
            search.setAsync(false);
            search.types().add(EnumDSSXMLObjectSubTypes.DssXmlSubTypeUserGroup);
            search.setDomain(EnumDSSXMLSearchDomain.DssXmlSearchConfigurationAndAllProjects);
            return performSearch(search);
        } else {
            Log.logger.logp(Level.INFO,  CreateCustomDotNetSecurityFilter.class.getName(), methodName,"Searching for object with name :" + name);
            search = source.getNewSearchObject();
            search.setNamePattern(name);
            search.setAsync(false);
            search.types().add(type);
            //search.setDomain(EnumDSSXMLSearchDomain.DssXmlSearchConfigurationAndAllProjects);
            return performSearch(search);
        }
    }

    /**
     * This method searches given object
     * @param search        MSTR search object
     * @return Object
     */
    public static Object performSearch(WebSearch search)  throws Exception{
        String methodName = "performSearch";
        search.submit();
        WebFolder folder = search.getResults();
        if (folder.size() > 0) {
            if (folder.size() == 1) {
                return folder.get(0);
            } else {
                throw new Exception("Search returns more than 1 object!");
            }
        }
        return null;
    }

    /**
     * This method generate a random password
     */
    private String generateRandomPassword() {
        String characterSet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()";
        Random rnd = new Random();
        int desiredLength = 8;
        StringBuilder sb = new StringBuilder( desiredLength );
        for (int i = 0; i < desiredLength; i++ ) {
            sb.append( characterSet.charAt( rnd.nextInt(characterSet.length()) ) );
        }
        return sb.toString();
    }

}

How to prevent the user from being able to directly access MicroStrategy Web?

From the Custom Task side, we need to:

if (user != null) {
    WebStandardLoginInfo loginInfo = user.getStandardLoginInfo();
    loginInfo.setStandardAuthAllowed(false); // Prevent the user from accessing MicroStrategy Web directly
}

and from the CustomESM / CustomSSO side, inside our getWebIServerSession method, we need to:

iSession.setAuthMode(EnumDSSXMLAuthModes.DssXmlAuthTrusted);
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License