Jan 1, 2012

Following is a technical white paper that shows you how to reset field values in ADF using ADF JavaScript client library.

View/Download

Posted on Sunday, January 01, 2012 by Unknown

Nov 24, 2011

To override the default error handler one can extend the  DCErrorHandlerImpl. In this you can process the exceptions or can choose to suppress them. In this post i will explain a way to suppress the RowValException message and display only the detail entity attribute level exception ie AttrValException.

In ADF the exceptions are grouped and raised together as a single object. For example let's say that 2 of the attributes fail the mandatory validation then the exceptions raised for them will be 2 individual AttrValException these are then attached as detail objects into a RowValException and if there are many such RowValException they will be attached and raised together as a TxnValException.

So now to handle the aforementioned task we need to recursively  process the exceptions and suppress the RowValException message. The snippet below shows that :-

public class MyErrorHandler extends DCErrorHandlerImpl {
    private static final ADFLogger logger = ADFLogger.createADFLogger(VleAdminErrorHandler.class);
    private static ResourceBundle rb = ResourceBundle.getBundle("mypackage.myBundle");
    public MyErrorHandler() {
        super(true);
    }

    public MyErrorHandler(boolean setToThrow) {
        super(setToThrow);
    }

    public void reportException(DCBindingContainer bc, java.lang.Exception ex) {
        disableAppendCodes(ex);
        logger.info("entering reportException() method");
        BindingContext ctx = bc.getBindingContext();
        String err_code;
        err_code = null;
        if(ex instanceof NullPointerException){
              logger.severe(ex); 
              JboException e = new JboException(rb.getString("STANDARD_ERROR_MESSAGE"));
              super.reportException(bc, e);
            }
        else if(ex instanceof RowValException){
          
          Object[] exceptions= ((RowValException)ex).getDetails();
          if(exceptions!=null){
            for(int i=0;i<exceptions.length;i++){
                  if(exceptions[i] instanceof RowValException){
                       this.reportException(bc, (Exception)exceptions[i]);                                 
                  }
                  else if(exceptions[i] instanceof AttrValException){
                super.reportException(bc, (Exception)exceptions[i]);
                  }
              }
          }
            else{
            this.reportException(bc, ex);
            }
            
        }
       else if (ex instanceof TxnValException) {
          Object[] exceptions= ((TxnValException)ex).getDetails();
          if(exceptions!=null){
          for(int i=0;i<exceptions.length;i++){
              if(exceptions[i] instanceof RowValException){
                   this.reportException(bc, (Exception)exceptions[i]);                                 
              }
              else{
            super.reportException(bc, (Exception)exceptions[i]);
              }
          }
          }
          else {
                super.reportException(bc, ex);
              }
        }
      
       else if (ex instanceof oracle.jbo.DMLException) {
           JboException e = new JboException(rb.getString("STANDARD_ERROR_MESSAGE"));
            super.reportException(bc, e);
        }
       else if(ex instanceof javax.xml.ws.WebServiceException){
            JboException e=new JboException(rb.getString("WEB_SERVICE_EXCEPTION"));
            super.reportException(bc, e);
            }
       
        else if (ex instanceof JboException) {
            super.reportException(bc, ex);
        }

    }


    public static FacesMessage getMessageFromBundle(String key, FacesMessage.Severity severity) {
        ResourceBundle bundle = ResourceBundle.getBundle("sahaj.apps.vleadministration.view.resources.VLEAdministrationUIBundle");
        String summary = JSFUtil.getStringSafely(bundle, key, null);
        String detail = JSFUtil.getStringSafely(bundle, key + "_detail", summary);
        FacesMessage message = new FacesMessage(summary, detail);
        message.setSeverity(severity);
        return message;
    }
  private void disableAppendCodes(Exception ex) {
      if (ex instanceof JboException) {
        JboException jboEx = (JboException) ex;
        jboEx.setAppendCodes(false);
        Object[] detailExceptions = jboEx.getDetails();
        if ((detailExceptions != null) && (detailExceptions.length > 0)) {
          for (int z = 0, numEx = detailExceptions.length; z < numEx; z++) {
            disableAppendCodes((Exception) detailExceptions[z]);
          }
        }
      }
  }
  @Override  
    protected boolean skipException(Exception ex) {  
      if (ex instanceof JboException) {  
        return false;  
      } else if (ex instanceof SQLIntegrityConstraintViolationException) {  
        return true;  
      }  
      return super.skipException(ex);  
    }

    @Override
    public String getDisplayMessage(BindingContext bindingContext,
                                    Exception exception) {
        return super.getDisplayMessage(bindingContext, exception);
    }

    @Override
    public DCErrorMessage getDetailedDisplayMessage(BindingContext bindingContext,
                                                    RegionBinding regionBinding,
                                                    Exception exception) {
        
        
    return super.getDetailedDisplayMessage(bindingContext, regionBinding, exception);
    }
} 

In this snippet i am recursively processing TxnValException->RowValException -> AttrValException. The AttrValException is being passed in the super call to the DCErrorHandlerImpl to process and display the message.




Posted on Thursday, November 24, 2011 by Unknown

Nov 17, 2011

I had a recently asked a question on bulk uploads in OTN forum. Seems the performance that i would receive for bulk update/insert scenarios isn't at par.
So i created the procedure and a custom object type and table of that object type which provides far better performance.

Let's say your table structure is as follows :-

--     TXN_TBL
("TXN_ID" Number,
"USER_NAME" VARCHAR2(50 BYTE),
"TXN_DATE" DATE,
"TXN_AMOUNT" NUMBER)

So you can basically create a object type mirroring that structure as follows
create or replace type TXN_TBL_R is object
("TXN_ID" Number,
"USER_NAME" VARCHAR2(50 BYTE),
"TXN_DATE" DATE,
"TXN_AMOUNT" NUMBER)
and then create a table type that will store record of these types:
create or replace type TXN_TBL_TB as table of  TXN_TBL_R
The procedure that will perform the updates and or inserts is shown in the below snippet:-

create or replace procedure B_INSERT(p_in IN TXN_TBL_TB) as
cursor for_insert is select * from TABLE(p_in) rt where not exists(select tmp.TXN_ID from TXN_TBL tmp where rt.TXN_ID=tmp.TXN_ID);
cursor for_update is select * from TABLE(p_in) rt where exists(select tmp.TXN_ID from TXN_TBL tmp where rt.TXN_ID=tmp.TXN_ID);
temp_insert TXN_TBL_R;
temp_update TXN_TBL_R;
begin
for temp_update in for_update loop
update TXN_TBL tmp set tmp.USER_NAME= temp_update.USER_NAME,tmp.TXN_DATE=temp_update.TXN_DATE,tmp.TXN_AMOUNT=temp_update.TXN_AMOUNT where tmp.TXN_ID= temp_update.TXN_ID;
end loop;
for temp_insert in for_insert loop
insert into TXN_TBL values(temp_insert.TXN_ID, temp_insert.USER_NAME, temp_insert.TXN_DATE, temp_insert.TXN_AMOUNT);
end loop;
end;

Then you can basically call this program from the ADF application using struct type. The snippet is shown below:-
/**
*@param valueSet the set of bean values
*/
 public void someMethod(Set valueSet){
         Connection conn=null;
        try {
          conn = getDBTransaction().createStatement(1).getConnection();
          StructDescriptor tblRecordStructType =
                          StructDescriptor.createDescriptor("TXN_TBL_R", conn);
        Iterator it= valueSet.iterator();
        Object txnArray[]=new Object[set.size()];
          while(it.hasNext()){
       SomeCustomBean detail=it.next();
  STRUCT tempStruct=new STRUCT(tblRecordStructType,conn,new Object[]{detail.getTranxId(),detail.getUserName(),detail.getTxnDate(),detail.getTransAmount()});  
    txnArray[i]=tempStruct;
    i=i+1;
    }
    //create array structure descriptor
     ArrayDescriptor txnTableDesc=ArrayDescriptor.createDescriptor("TXN_TBL",conn);
  //create an Array type with given structure definition
  ARRAY txnTableArray=new ARRAY(txnTableDesc,conn,txnArray); 
           String callableProcedureStatement=" begin  TMP_INSERT(?); end;" ;
          OracleCallableStatement st=null;
          st=(OracleCallableStatement)getDBTransaction().createCallableStatement(callableProcedureStatement, 0);  
          st.setARRAY(1, txnTableArray);
          st.executeUpdate();  
    this.getDBtransaction().commit();
        } catch (JboException e) {
this.getDBtransaction().rollBack();
         throw new JboException(e.getMessage());
   
        }
  }


This is basically it. This will perform faster than normal ADF update/insert.


Posted on Thursday, November 17, 2011 by Unknown

If you are using ADF11g version 11.1.1.3 and want to reset the values in the popup, you are not provided with the resetEditableValues option. But you can accomplish this using a custom javascript that i have made.

All you have to do is set clientComponent="true" for all the components that you want to reset and pass the client id of the root component to use this.

resetAction=function(clientId){
    var component= AdfPage.PAGE.findComponentByAbsoluteId(clientId);
    console.log(component);
    var components=component.getDescendantComponents();
    this.resetFunction(components);
    }
   resetFunction=function(components){
     for (var i=0;i<components.length;i++){
     if(components[i] instanceof AdfRichInputText){
     if(components[i].getVisible()&&!components[i].getDisabled()&&!components[i].getReadOnly()){
     components[i].setValue("");
     }
     }
     if(components[i] instanceof AdfRichSelectOneChoice){
    if(components[i].getVisible()&&!components[i].getDisabled()&&!components[i].getReadOnly()){
    components[i].resetValue();
    }
     }
     }
  }
   
    
Save the contents of this file to a JS file and then import it in your fragment or a jsf page.

Now you have to bind the parent container like panelFormLayout and then on action of the command button use ExtendedRenderKitService to pass the client id of the root component dynamically to resetAction Method so that this script always works. The snippet is shown below.

/**
     * Resets the popup
     * @return null
     */
    public String resetPopupAction() {
      FacesContext context = FacesContext.getCurrentInstance();
      ExtendedRenderKitService erks =
      Service.getRenderKitService(context, ExtendedRenderKitService.class);
      erks.addScript(context,"resetAction('"+formBinding.getClientId(context) +"')"); 
    
      return null;
    }


Hope this will be helpful :D

Posted on Thursday, November 17, 2011 by Unknown

Sep 21, 2011

If you are using ADF 11g and you encounter this issue kindly check your ps_txn table. You can delete the records from this table and then you will see that this error will go away.
This table is used by ADFm internally to serialize user session state to database, so this table has to be monitored and appropriate grants have to be given to the database user so that it can create the database objects.
For more information kindly refer to this article by chris muir.
PS_TXN


Posted on Wednesday, September 21, 2011 by Unknown

This is a short tip on where to add the <af:resource type="javascript"> tag when you want to include javascript in your adf page fragment. The place to include the tag is inside of a root component layout like panelFormLayout or panelGroupLayout because otherwise if you place it outside of the root component the resource might not be loaded and hence your script method will not be found which can sometimes lead to issues with the user interface also because a javascript error will prevent panelStretchLayout from stretching. But if you place it inside the root component layout the script will be loaded always.



Posted on Wednesday, September 21, 2011 by Unknown

You might face a scenario where you have to reuse the same view object in different task flows. But the issue you will encounter if you are not using separate View Object instances is that changes made to view objects in one task flow will reflect in the view object in the other task flow.
If you are not using separate view object instances you can either call clearCache on the view object when the region renders or call ApplicationModuleImpl clearVOCaches method.  The former method will clear cache for both transient and entity based view object instances and the latter can be used to clear the cache on all the entity based view objects.

If you are using dynamic regions you can use use the either of the following fragments for clearing the cache which solves your re-usability scenario as clicking on the command link will clear the view object cache's and hence you will get consistent results.
       DCBindingContainer container=(DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();
       TestAMImpl amImpl=(TestAMImpl) container.findDataControl("TestAMDataControl").getDataProvider();
       //clear the all entity caches and do it recursively. 
       amImpl.clearVOCaches(null, true);
      
or
       
    DCBindingContainer container=(DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();
       TestAMImpl amImpl=(TestAMImpl) container.findDataControl("TestAMDataControl").getDataProvider();
       String [] viewObjectName=amImpl.getViewObjectNames();
       for (int i=0;i<viewobjectname.length;i++){ amimpl.findviewobject(viewobjectname[i]).clearcache();}
Note: This is only a workaround and not a best practice, though if you want to reuse the view object in many places this will suffice.

Posted on Wednesday, September 21, 2011 by Unknown

Sep 9, 2011

In this post i am sharing a utility for performing the following operations on OID using the OPSS API :-
  1. User creation 
  2. Dropping a user
  3. Getting all roles for a user
  4. Role/Roles assignment to user/users
  5. Revocation of role/roles from user/ users
  6. Changing password for a user 
  7. Resetting password for a user 
  8. Searching a User 
  9. Getting members belonging to a particular role. 
The relevant code fragment is attached below. Hope this utility will be helpful for someone who wants to integrate application with OID using OPSS.


import java.security.Principal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import oracle.adf.share.ADFContext;
import oracle.adf.share.logging.ADFLogger;
import oracle.adf.share.security.SecurityContext;
import oracle.adf.share.security.identitymanagement.UserProfile;

import oracle.security.idm.ComplexSearchFilter;
import oracle.security.idm.IMException;
import oracle.security.idm.Identity;
import oracle.security.idm.IdentityStore;


import oracle.security.idm.IdentityStoreFactory;
import oracle.security.idm.IdentityStoreFactoryBuilder;
import oracle.security.idm.ObjectNotFoundException;
import oracle.security.idm.OperationNotSupportedException;
import oracle.security.idm.Role;
import oracle.security.idm.RoleManager;
import oracle.security.idm.RoleProfile;
import oracle.security.idm.SearchFilter;
import oracle.security.idm.SearchParameters;
import oracle.security.idm.SearchResponse;
import oracle.security.idm.SimpleSearchFilter;
import oracle.security.idm.User;
import oracle.security.idm.UserManager;
import oracle.security.idm.providers.oid.OIDIdentityStoreFactory;
/**
 *This class can be used to perform operation on OID using OPSS API
 * @author Ramandeep Nanda
 */

public class OIDOperations {
  public static final ADFLogger OIDLogger=ADFLogger.createADFLogger(OIDOperations.class);
  private static final ResourceBundle rb =
    ResourceBundle.getBundle("yourresourcebundlelocation");
    /**
     *
     * @return The store instance for OID store
     */
    public static IdentityStore getStoreInstance(){
        return  IdentityStoreConfigurator.initializeDefaultStore();
        }
    public static IdentityStoreFactory getIdentityStoreFactory(){
        return IdentityStoreConfigurator.idStoreFactory;
        }
    /**
     * Returns the logged in User if using ADF security
     * @return The logged in User
     */
    public static String getLoggedInUser(){
          ADFContext ctxt=ADFContext.getCurrent();
          SecurityContext sctxt=ctxt.getSecurityContext();
        return   sctxt.getUserName();
        }
    /**
     * This method returns the user profile of currently logged in user if using ADF security
     * @return oracle.adf.share.security.identitymanagement.UserProfile;
     */
    public static UserProfile getLoggedInUserProfile(){
          ADFContext ctxt=ADFContext.getCurrent();
          SecurityContext sctxt=ctxt.getSecurityContext();
         return sctxt.getUserProfile();
        }
    /**
     * Assigns the specified role to the user
     * @param roleName the role to assign
     * @param userName the user to assign role to
     */
    public static void assignRoleToUser(String roleName,String userName){
       String methodName=Thread.currentThread().getStackTrace()[1].getMethodName();
      IdentityStore store=OIDOperations.getStoreInstance();
        try {
           Role role= store.searchRole(IdentityStore.SEARCH_BY_NAME,roleName);
           User user= store.searchUser(userName); 
           RoleManager rm=store.getRoleManager();
          if(!rm.isGranted(role, user.getPrincipal())){   
           rm.grantRole(role, user.getPrincipal()); 
          }
            
        } catch (IMException e) {
          OIDLogger.severe("Exception in "+methodName + "Could not assign role ["+roleName+"] to the user ["+userName +"] because of " +e.getMessage() +" ", e);
          throw new JboException("Could not assign role ["+roleName+"] to the user ["+userName +"] due to "+e.getMessage());
         
        }
        finally  {
            try{
            store.close();
                }
              catch (IMException e) {
              OIDLogger.severe("Exception occured in closing store");
              }
            }
    }
  /**
     * Assigns the specified role to the user
     * @param roleNames the roles to assign
     * @param userName the user to assign role to
     * @return the set of users who are assigned roles
     */
  public static Set assignRolesToUser(Set roleNames,String userName){
     Set rolesAssigned=new HashSet();
     
     String methodName=Thread.currentThread().getStackTrace()[1].getMethodName();
     IdentityStore store=OIDOperations.getStoreInstance();
     String roleName=null;
      try {
        User user= store.searchUser(userName); 
        Principal userPrincipal=user.getPrincipal(); 
        RoleManager rm=store.getRoleManager();
        Iterator it=roleNames.iterator();
        while(it.hasNext()){
         roleName=(String)it.next();
         Role role= store.searchRole(IdentityStore.SEARCH_BY_NAME,roleName);
          if(!rm.isGranted(role, user.getPrincipal())){   
         rm.grantRole(role,userPrincipal); 
         rolesAssigned.add(roleName);
          }
        }
      } catch (IMException e) {
          
        OIDLogger.severe("Exception in "+methodName + "Could not assign role ["+roleName+"] to the user ["+userName +"] because of " +e.getMessage() +" ", e);
        throw new JboException("Could not assign role ["+roleName+"] to the user ["+userName +"] due to "+e.getMessage());
        
        
      }
    finally  {
        try{
        store.close();
            }
          catch (IMException e) {
          OIDLogger.severe("Exception occured in closing store");
          }
        }
    
      return rolesAssigned;
  }
  /**
     * Assigns the specified role to the user
     * @param roleName the role to assign
     * @param users the users to assign role to
     * @return The users who are assigned the role
     */
  public static Set assignRoleToUsers(String roleName,Map users){
     Set usersAssigned=new HashSet();
     String methodName=Thread.currentThread().getStackTrace()[1].getMethodName();
     IdentityStore store=OIDOperations.getStoreInstance();
        Set entrySet = users.entrySet();
        Iterator it=entrySet.iterator();
        String userName=null;
  
      try {
         Role role= store.searchRole(IdentityStore.SEARCH_BY_NAME,roleName);
         RoleManager rm=store.getRoleManager();
        while(it.hasNext()){
          Map.Entry entry=(Map.Entry)it.next();     
          userName=(String)entry.getKey();
          User user= store.searchUser(userName); 
            if(!rm.isGranted(role, user.getPrincipal())){   
              rm.grantRole(role, user.getPrincipal()); 
              usersAssigned.add(user);
            }
        }  
      } catch (IMException e) {
        OIDLogger.severe("Exception in "+methodName + "Could not assign role ["+roleName+"] to the user ["+userName +"] because of " +e.getMessage() +" ", e);
       }
    finally  {
        try{
        store.close();
            }
          catch (IMException e) {
          OIDLogger.severe("Exception occured in closing store");
          }
        }
      return usersAssigned;
  }

//revoke sample below It is similar to the above mentioned assign case so mentioning a sample operation 

    /**
     * To remove the role from user
     * @param roleName the role to remove/ revoke
     * @param userName the user from which to revoke role
     */
    public static void removeRoleFromUser(String roleName,String userName){
          String methodName=Thread.currentThread().getStackTrace()[1].getMethodName();
          IdentityStore store=OIDOperations.getStoreInstance();
           try {
              Role role= store.searchRole(IdentityStore.SEARCH_BY_NAME,roleName);
               
              User user= store.searchUser(userName); 
              RoleManager rm=store.getRoleManager();
             if(rm.isGranted(role, user.getPrincipal())){   
              rm.revokeRole(role, user.getPrincipal()); 
             }
           } catch (IMException e) {
             OIDLogger.severe("Exception in "+methodName + "Could not revoke role ["+roleName+"] from the user ["+userName +"] because of " +e.getMessage() +" ", e);
             throw new JboException("Could not remove role ["+roleName+"] from the user ["+userName +"] due to "+e.getMessage());
             
           }
          finally  {
              try{
              store.close();
                  }
                catch (IMException e) {
                OIDLogger.severe("Exception occured in closing store");
                }
              }
        }
    public static void dropUserWithRoles(String userId){
          UserManager um = null;
          IdentityStore store=null;
          User newUser = null;
           try {
              store=OIDOperations.getStoreInstance();
              User user = store.searchUser(IdentityStore.SEARCH_BY_NAME, userId);
              um=store.getUserManager();
              if (user != null) {
                  //drop user if already present
                  um.dropUser(user);
                  RoleManager rm = store.getRoleManager();
                  Principal userPrincipal= user.getPrincipal();
                  SearchResponse resp=rm.getGrantedRoles(userPrincipal, true);
                  while(resp.hasNext()){
                  rm.revokeRole((Role)resp.next(), user.getPrincipal());
                  }
                }
          }
          catch (IMException e) {
              OIDLogger.info("[dropUser]" +
                            
                            e);

          }
          finally  {
              try{
              store.close();
                  }
                catch (IMException e) {
                OIDLogger.severe("Exception occured in closing store");
                }
              }
        }
  public static void dropUser(String userId){
        UserManager um = null;
        User newUser = null;
        IdentityStore store=null;

        try {
           store =OIDOperations.getStoreInstance();
            User user = store.searchUser(IdentityStore.SEARCH_BY_NAME, userId);
            um=store.getUserManager();
            if (user != null) {
                //drop user if already present
                um.dropUser(user);
              }
        }
        catch (IMException e) {
            OIDLogger.info("[dropUser]" +
                          e);

        }
        finally  {
            try{
            store.close();
                }
              catch (IMException e) {
              OIDLogger.severe("Exception occured in closing store");
              }
            }
      }

    /**
     * Gets the userProfile of the logged in user if using ADF security
     * @param approverUser
     * @return
     */
    public static oracle.security.idm.UserProfile getUserProfile(String approverUser) {
      IdentityStore store=OIDOperations.getStoreInstance();
       oracle.security.idm.UserProfile profile=null;
        try {
           User user= store.searchUser(approverUser);
           profile=user.getUserProfile();
            
        } catch (IMException e) {
            OIDLogger.info("Could not find user in OID with supplied Id"+approverUser);
          throw new JboException(e.getMessage());
        }
      finally  {
          try{
          store.close();
              }
            catch (IMException e) {
            OIDLogger.severe("Exception occured in closing store");
            }
          }
        return profile;
    }
    /**
     * Gets all the roles 
     * @return
     */
    public static List getAllRoles(){
          String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
          List returnList=new ArrayList();
          IdentityStore store=OIDOperations.getStoreInstance();

          try{
             SimpleSearchFilter filter=store.getSimpleSearchFilter(RoleProfile.NAME,SimpleSearchFilter.TYPE_EQUAL,null);
             String wildCardChar=filter.getWildCardChar();
            // Here the default_role is a property this is just a placeholder can be  any pattern you want to search
            filter.setValue(wildCardChar+rb.getString("DEFAULT_ROLE")+wildCardChar);
                       SearchParameters parameters=new SearchParameters(filter,SearchParameters.SEARCH_ROLES_ONLY) ;
             SearchResponse resp=store.searchRoles(Role.SCOPE_ANY,parameters);
             while(resp.hasNext()){
                 Role role=(Role)resp.next();
                           String tempRole=role.getPrincipal().getName();
                           returnList.add(tempRole);
                          }
             store.close();  
           }catch(IMException e){
                 OIDLogger.severe("Exception in "+methodName + " " +e.getMessage() +" ", e);
                 throw new JboException(e.getMessage());
                 }
          finally  {
              try{
              store.close();
                  }
                catch (IMException e) {
                OIDLogger.severe("Exception occured in closing store");
                }
              }
            
           return returnList;
        }
    /**
     * Fetches all the roles assigned to the user
     * @param userName
     * @return
     */
    public static List getAllUserRoles(String userName, String searchPath) {
      String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
      List returnList=new ArrayList();
      IdentityStoreFactory storeFactory = OIDOperations.getIdentityStoreFactory();
      IdentityStore store=null;
      String[] userSearchBases=   {rb.getString(searchPath)};    
      String[] groupSearchBases=     {rb.getString("group.search.bases")};  
      Hashtable storeEnv=new Hashtable();
      storeEnv.put(OIDIdentityStoreFactory.ADF_IM_SUBSCRIBER_NAME,rb.getString("oidsubscribername"));
      storeEnv.put(OIDIdentityStoreFactory.RT_USER_SEARCH_BASES,userSearchBases);
      storeEnv.put(OIDIdentityStoreFactory.RT_GROUP_SEARCH_BASES,groupSearchBases);
     
       try{
          store = storeFactory.getIdentityStoreInstance(storeEnv);
          User user= store.searchUser(IdentityStore.SEARCH_BY_NAME,userName);
          RoleManager mgr=store.getRoleManager();
          SearchResponse resp= mgr.getGrantedRoles(user.getPrincipal(), false);
           while(resp.hasNext()){
              String name= resp.next().getName();
              returnList.add(name);
               }
    
        }catch(IMException e){
              OIDLogger.severe("Exception in "+methodName + " " +e.getMessage() +" ", e);
              throw new JboException(e.getMessage());
              }
      finally  {
          try{
          store.close();
              }
            catch (IMException e) {
            OIDLogger.severe("Exception occured in closing store");
            }
          }
         
        return returnList;
    }

 /**
*Use to change the passoword for logged in user It uses ADF Security Context to get logged in user
*
**/
  public static void changePasswordForUser(String oldPassword,String newPassword, String userName){
        String methodName =
            java.lang.Thread.currentThread().getStackTrace()[1].getMethodName();
        SecurityContext securityContext =
            ADFContext.getCurrent().getSecurityContext();
        String user = securityContext.getUserName();
      IdentityStore oidStore=null;
         oidStore= OIDOperations.getStoreInstance();
        try {
            UserManager uMgr = oidStore.getUserManager();
            User authUser =
                uMgr.authenticateUser(user, oldPassword.toCharArray());

            if (authUser != null) {
                UserProfile profile = authUser.getUserProfile();

                profile.setPassword( oldPassword.toCharArray(),
                                    newPasswordtoCharArray());
              }
        } catch (IMException e) {
            if (OIDLogger.isLoggable(Level.SEVERE)) {
                OIDLogger.severe("[" + methodName +
                                "]  Exception occured due to " + e.getCause(),
                                e);
            }
            throw new JboException(e.getMessage());
        }
      finally  {
          try{
          oidStore.close();
              }
            catch (IMException e) {
            OIDLogger.severe("Exception occured in closing store");
            }
          }


}

/**
* Resets the password for user 
*
**/
public static void resetPasswordForUser(String userId)
{
        String methodName =
            java.lang.Thread.currentThread().getStackTrace()[1].getMethodName();
        IdentityStore oidStore = OIDOperations.getStoreInstance();
        User user = null;
        try {
            user = oidStore.searchUser(userId);
            if (user != null) {
                UserProfile userProfile = user.getUserProfile();
                List passwordValues =
                    userProfile.getProperty("userpassword").getValues();
             ModProperty prop =
                    new ModProperty("PASSWORD", passwordValues.get(0),
                                    ModProperty.REMOVE);
                userProfile.setProperty(prop);
                String randomPassword = generateRandomPassword();
                userProfile.setPassword(null, randomPassword.toCharArray());
            }
        } catch (IMException e) {
            OIDLogger.severe("[" + methodName + "]" +
                            "Exception occured due to ", e);
         
        }
      finally  {
          try{
          oidStore.close();
              }
            catch (IMException e) {
            OIDLogger.severe("Exception occured in closing store");
            }
          }

}


    /**
     * This nested private class is used for configuring and initializing a store instance
     * @author Ramandeep Nanda
     */
  private static final class IdentityStoreConfigurator {
                              private static final IdentityStoreFactory idStoreFactory=initializeFactory();
                           
  
                             private static IdentityStoreFactory initializeFactory(){
                                       String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
                                       IdentityStoreFactoryBuilder builder = new 
                                       IdentityStoreFactoryBuilder();
                                       IdentityStoreFactory oidFactory = null;
                                             try {
                                       Hashtable factEnv = new Hashtable();
                                       factEnv.put(OIDIdentityStoreFactory.ST_SECURITY_PRINCIPAL,rb.getString("oidusername"));
                                       factEnv.put(OIDIdentityStoreFactory.ST_SECURITY_CREDENTIALS, rb.getString("oiduserpassword"));
                                       factEnv.put(OIDIdentityStoreFactory.ST_SUBSCRIBER_NAME,rb.getString("oidsubscribername"));
                                       factEnv.put(OIDIdentityStoreFactory.ST_LDAP_URL,rb.getString("ldap.url"));
                                       factEnv.put(OIDIdentityStoreFactory.ST_USER_NAME_ATTR,rb.getString("username.attr"));       
                                       oidFactory = builder.getIdentityStoreFactory("oracle.security.idm.providers.oid.OIDIdentityStoreFactory", factEnv);
                                          }
                                       catch (IMException e) { 
                                               OIDLogger.severe("Exception in "+methodName + " " +e.getMessage() +" ", e);
                                     //re throw exception here
                                       }
                                      return oidFactory;       
                                     }    
                             private static  IdentityStore initializeDefaultStore(){
                                       IdentityStore store=null;
                                       String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
                                       String[] userSearchBases=   {rb.getString("user.search.bases")};    
                                       String[] groupCreateBases=     {rb.getString("group.search.bases")};  
                                       String []usercreate={rb.getString("user.create.bases")};
                                       String [] groupClass={rb.getString("GROUP_CLASSES")};
                                       Hashtable storeEnv=new Hashtable();
                                       storeEnv.put(OIDIdentityStoreFactory.ADF_IM_SUBSCRIBER_NAME,rb.getString("oidsubscribername"));
                                       storeEnv.put(OIDIdentityStoreFactory.RT_USER_SEARCH_BASES,userSearchBases);
                                       storeEnv.put(OIDIdentityStoreFactory.RT_GROUP_SEARCH_BASES,groupCreateBases);
                                       storeEnv.put(OIDIdentityStoreFactory.RT_USER_CREATE_BASES,usercreate);
                                       storeEnv.put(OIDIdentityStoreFactory.RT_USER_SELECTED_CREATEBASE,rb.getString("user.create.bases"));
                                       storeEnv.put(OIDIdentityStoreFactory.RT_GROUP_OBJECT_CLASSES,groupClass); 
                                       try{
                                       store = IdentityStoreConfigurator.idStoreFactory.getIdentityStoreInstance(storeEnv);
                                       }  
                               catch (IMException e) { 
                                       OIDLogger.severe("Exception in "+methodName + " " +e.getMessage() +" ", e);
                                     // re throw exception here
                
            }
          return  store;

        }
                             

}
The rb instance being used in the code is a static final instance of a resource bundle.
The relevant properties are mentioned below that you can put into your resource bundle.
ldap.url=ldap://your_ldap_server_ip:port
user.create.bases=cn=Users,dc=oracle,dc=com
username.attr=uid
oidusername=userName
#not safe
oiduserpassword=userpass
user.search.bases=cn=Users,dc=oracle,dc=com
group.search.bases=cn=Groups,dc=oracle,dc=com
oidsubscribername=dc=oracle,dc=com

Posted on Friday, September 09, 2011 by Unknown