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

Sep 3, 2011

If you have a requirement for opening a printable page and also the print dialog and you are using page fragments then you should implement the RegionController interface rather than  PagePhaseListener. I had such a requirement and then implemented it using RegionController interface. On any page fragment that you are required to implement this functionality just add an EL expression or a fully classified name of the class that implements the region controller class in the page definition's ControllerClass attribute.  The code snippet for the region controller implementation is shown below.

public boolean refreshRegion(RegionContext regionContext) {
      int refreshFlag=  regionContext.getRefreshFlag();
      
      FacesContext fctx = FacesContext.getCurrentInstance();
      //check internal request parameter
      Map requestMap = fctx.getExternalContext().getRequestMap();
      PhaseId currentPhase=(PhaseId)requestMap.get("oracle.adfinternal.view.faces.lifecycle.CURRENT_PHASE_ID");
     //compare phase
      if(currentPhase.getOrdinal()==PhaseId.RENDER_RESPONSE.getOrdinal()){
      Object showPrintableBehavior =
          requestMap.get("oracle.adfinternal.view.faces.el.PrintablePage");
      if (showPrintableBehavior != null) {
          if (Boolean.TRUE == showPrintableBehavior) {
              ExtendedRenderKitService erks = null;
              erks =
              Service.getRenderKitService(fctx, ExtendedRenderKitService.class);
              //invoke JavaScript from the server
              erks.addScript(fctx, "window.print();");
          }
      }
      }
     regionContext.getRegionBinding().refresh(refreshFlag);
     return false;
    }

    public boolean validateRegion(RegionContext regionContext) {
       regionContext.getRegionBinding().validate();
        return false;
    }

    public boolean isRegionViewable(RegionContext regionContext) {
        
        return regionContext.getRegionBinding().isViewable();
    }

   


This code checks to see if the phase id of current view is Render Response and if so checks whether show printable page behavior was used and if that is indeed the case, It calls the javascript's print function to print the form.
Hope this will be useful to someone who is trying to implement the functionality in adf page fragment.

Posted on Saturday, September 03, 2011 by Unknown

Aug 20, 2011

In JDeveloper 11g, if you delete the database connection, you will notice that none of the oracle domain types will  appear in the drop down when you create new objects. This happens because  type map of bc4j components is changed to JAVA. Also this will cause problem in case you try to edit a already existing bc4j component as the type is changed from oracle domain to the corresponding java type.

To change the type map to oracle, just follow the steps mentioned below:-
  • Open your *model.jpx file and find the entry for type map ie _TypeMap.
  • Remove the aforementioned entry and restart jdeveloper 11g and now you will be able to see the oracle domain types.
Hope this will be helpful to anyone facing this issue.

Posted on Saturday, August 20, 2011 by Unknown

May 10, 2011

SLF4J(Simple logging facade for JAVA) is a abstraction layer or facade for different logging frameworks like log4j,Logback etc which allows you to plugin the desired logging framework at deployment time. Also logback is a framework that implements the SLF4j api so it allows easy switching between different logging frameworks and it also provides more optimized logging than log4j by providing features such as parametrized logging.
To learn more about these frameworks refer to the comprehensive documentation at the following sites:-
1. SLF4J
2. Logback

I will here explain how to do logging using SLF4J and Logback.
The below mentioned example has the following features provided by the logback implementation.
  1. It has a rolling file appender with capability to archive the log files. The rolling policy for the appender will be configured to archive the log file if its size increases 100MB or at the month's end which ever happens earlier. The archived files will then be zipped. 
  2. It uses a MDCInsertingServletFilter that inserts the following keys into the Mapped Diagnostic Context :-
    • req.remoteHost:- It is set to the value returned by the getRemoteHost() of the ServletRequest api
    • req.xForwardedFor:- It is set to the value of the HTTP header X-Forwarded-For. It is useful to identify the originating ip address of the request in case the request is forwarded to the web server by a proxy server or load balancer.
    • req.requestURI:- To the value returned by getRequestURI().
    • req.requestURL:- To the value returned by getRequestURL().
    • req.queryString:- To the value returned by getQueryString().
    • req.userAgent:- To the value returned by getUserAgent().
  3. The encoder pattern which inserts the value obtained from the Mapped Diagnostic Context.
  4. Parametrized Logging
You will have to place the following code into a file named as logback.xml in your classpath. The code represents the configuration required for accomplishing the aforementioned features.

<configuration  debug="true">
 <contextName>Your Context</contextName>
 <appender name="ROLLINGFILE"
  class="ch.qos.logback.core.rolling.RollingFileAppender">
  <file>/oracle/logs/application.log</file>
  <append>true</append>
  <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
   <fileNamePattern>/oracle/archivedapplicationlogs/applicationlog-%d{yyyy-MM}.%i.zip
   </fileNamePattern>
   <maxHistory>10</maxHistory>
   <timeBasedFileNamingAndTriggeringPolicy
    class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
    <maxFileSize>100MB</maxFileSize>

   </timeBasedFileNamingAndTriggeringPolicy>
  </rollingPolicy>


  <encoder>
   <pattern>Proxy forwarding for %X{req.xForwardedFor} %n %d{dd-mm-yyyy hh:mm:ss}- %-5level %logger{15} - %msg%n</pattern>
  </encoder>
 </appender>
 <root>
  <appender-ref ref="ROLLINGFILE" />
 </root>
 <logger name="com.blogspot.ramannanda"  level="info">
  <appender-ref ref="ROLLINGFILE" />
 </logger>
</configuration>


  • The above mentioned configuration has a rolling file appender configured with time and size based triggering policy. The file name pattern in itself signifies that the file should be zipped and archived at the end of the month, whereas the time and name based triggering policy signifies the maximum size of the log file after which it will be archived. The MaxHistory attribute signifies the number of archived files to be kept on the system. After which they will be automatically deleted.
  • The pattern will print the originating ip address in case your application is behind a load-balancer or proxy followed by the time, the level of the log message,the name given to the logger (The name by which it is instantiated by your class) and finally the log message.
  • The logger can be used by any class under the package com.blogspot.ramannanda and it's level is info so any log messages above or at info level will be logged. 
  • The %X{key} signifies that the value must be taken from the mapped diagnostic context. 
  • The debug=true attribute will print the information during instantiation (using the logback.xml file) and configuration errors will be reported.
To use the MDCInsertingServletFilter you will have to configure it in the web.xml configuration.
....
<filter>
  <filter-name>MDCInsertingServletFilter</filter-name>
  <filter-class>
   ch.qos.logback.classic.helpers.MDCInsertingServletFilter</filter-class>
 </filter>
 <filter-mapping>
  <filter-name>MDCInsertingServletFilter</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>
 <filter>
...

Now all you need to do enable logging is place the following jars in your classpath logback-classic, logback-core and slf4j-api.jar. The class that uses the logging is mentioned below. It only needs to use the LoggerFactory.getInstance(String loggername) method to get the logger instance.
The following code snippet for a DAO class shows the usage.

package com.blogspot.ramannanda.db;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FileStoreDAO {
public static Logger logger=(Logger) LoggerFactory.getLogger("com.blogspot.ramannanda.db.FileStoreDAO");
.....
public void removeData(String fileName){
 Connection conn = null;
 PreparedStatement pstmt = null;
 
  try{
      conn = new DBConnection();
  pstmt = conn.getPreparedStatement("delete from temp_table where file_name = ?");
  pstmt.setString(1, fileName);
  int count=pstmt.executeUpdate();
             logger.info(" The user has deleted  {} file {} ",count,fileName); 
  }
  catch (SQLException e) {
         logger.error("An exception has occured {} {} while deleting files", e, e.getMessage());
   
   
  }
  finally {
   try {
    if (pstmt != null) {
     pstmt.close();

    }
    conn.closeConnection();
   } catch (Exception e1) {
logger.error("An exception has occured while closing connection or prepared statement {}", e1);
   }
  }
  
 }
.....
}

The above code shows the usage of parametrized logging provided by logback implementation. The values in {} are replaced by the parameters at run-time if needed. Also the number of parameters that can be specified is not limited to 1 as can be seen from the code above.

Posted on Tuesday, May 10, 2011 by Unknown

Apr 25, 2011

Ideally the resources like images, flash files etc should be cached on the client browser or proxy server to reduce server load and reduce bandwidth consumption. In this post i will explain on how one can enable caching of these resources if they are exposed as restful resources using JERSEY Restful framework.

To enable caching of resources by proxy server or by client you need to keep a last modified date column in your database table which is updated if you upload or modify the content. The solution that i am discussing over here is as follows :-

1. If it is a initial request for the resource we will fetch the information from a data source and then build a response setting the last modified property on ResponseBuilder  along with the max age value for CacheControl header.

2. The cached content will be forced to expire after 5 minutes after which if a request for a resource is sent to the proxy server it will be forwarded to the container, when the request is received by the container we only need to compare the modified time of the resource with the value in the request header,Only if the resource has indeed been changed will we build a new response(setting the aforementioned header values) otherwise we will tell the client to reuse the cached content.

The above solution will ensure that a client will cache the response for 5 minutes and only if the content has been changed during these 5 minutes will it be re-fetched from the data source. This solution will drastically reduce the load on server and the client side.

The necessary code to accomplish this is mentioned below:-

@Path("/") 
public class FileResource {
 /** 
sets a 5 minutes expiry time

**/
 public ResponseBuilder setExpiry(ResponseBuilder rbuilder){
  int maxAge;
  GregorianCalendar now=new GregorianCalendar();
                //trims the milliseconds
  maxAge=(int) ((now.getTimeInMillis()/1000L)+(5*60));
  CacheControl cc=new CacheControl();
  cc.setMaxAge(maxAge);
  rbuilder.cacheControl(cc);
  return rbuilder;
  
 }
 

    /**
     * @param filename passed in the get request
     * @returns builds and returns a response
     * 
     *
     **/       
 @GET
 @Path("/files/{filename}")
 @Produces(MediaType.WILDCARD)
 public Response returnFileAsStream(@Context Request request,@PathParam("filename") String fileName){
  FileStoreDAO ftDAO=FileStoreDAO.getInstance();
  FileUtility futil=FileUtility.getInstance();
  Date lastModified=ftDAO.getLastModifiedTime(fileName);
  // re-validate whether file has changed since last modified time
  ResponseBuilder  respBuilder=request.evaluatePreconditions(lastModified);
  if(respBuilder!=null){
                        //sets 5 minute cache expiry time
   return setExpiry(respBuilder).build();
   
   }
  else{
            //reads the file  and sets its value into a DTO 
     FileDTO fdto=ftDAO.readFile(fileName);
  if(fdto!=null){
                String contentType=fdto.getMime();
  InputStream is=fdto.getFileData();
  respBuilder=Response.ok(is,contentType);
  //sets the last modified header value
                respBuilder.lastModified(lastModified);
  return setExpiry(respBuilder).build();
     
  }
}
}

The above code creates the response using the response builder, sets the max age value in cache control header and the value for the last modified header for the response.

The code from the DAO layer is shown below that shows a important point about HTTP proxy, the proxy does not handle milliseconds so we must set the value for milliseconds to 0 when comparing the last modified date value otherwise the comparison would never succeed.

/**
  * @param fileName the filename 
  * @return the time truncated to seconds
  */
 public java.util.Date getLastModifiedTime(String fileName){
       //get prepared statement and execute a query
         pstmt=conn.getPreparedStatement("select last_mod_date from editor_file_store where file_name= ?");
         pstmt.setString(1,fileName);
         //populate result set
         rs=pstmt.executeQuery();
    
      if(rs.next()){
       sqlDate= rs.getDate(1);  
      }
          //set this value on a calendar variable and set the millisecond to 0
           cal.setTime(sqlDate);
  cal.set(Calendar.MILLISECOND, 0);
          
          
          return cal.getTime();
          catch (SQLException e) {
   logger.log("Exception occured"+ e.getMessage());
  }
          finally{
         // close result set and connection
 try {
  if(rs!=null){
   rs.close();
  }
    if (pstmt != null) {
     pstmt.close();

    }
    conn.closeConnection();
           }
         }
       catch (SQLException e1) {
    logger.log( "An error occured due to "+e1.getMessage());
   }
}
      return cal.getTime();

}
After changing the above code you can try using firebug for firefox and observe the values for the request and response headers in the net tab. You will notice the values for cache control and last-modified headers and the fact that content needs to be resent only in case it has been modified.

Hope this tutorial was helpful, kindly report any error that you may find it is duly appreciated.

Posted on Monday, April 25, 2011 by Unknown

Apr 23, 2011

In this post i will explain on how one can easily create a Content Management System using Tiny MCE , Richfaces and Jersey. This application as a whole can then be used to serve the content dynamically and can be integrated with your site.

The usage of three components is mentioned below:-
  1. Tiny MCE :- A javascript based WYSIWYG editor  for editing HTML content. This will serve as a  HTML editor for CMS system.
  2. Jersey :- This framework will provide a way to expose the content as a Restful resource. The content will also be cached for performance.
  3. RichFaces:- This JSF framework will provide us with components for uploading the file and previewing the content of the file.
I have already covered the file uploading part in the RichFaces file upload tutorial  , Now that the file has been uploaded in to the database , We have to enable the previewing of the file. The file preview feature mentioned below will enable viewing of flash files, images and movies. This is actually a pretty simple preview page with the option of deleting the file contents and retrieving the stored file URL.
<f:view >
<h:form id="vup1"> 
.....  
   <h:panelGrid columns="1" columnClasses="top,top">
           
              <h:panelGroup id="info">
              <rich:panel bodyClass="info">
                   
                    <rich:dataGrid columns="2" ajaxKeys="#{viewUploadedFilesBacking.files}" value="#{viewUploadedFilesBacking.files}"
                        var="file"  rowKeyVar="row">
                      <h:selectBooleanCheckbox value="#{file.selected}"></h:selectBooleanCheckbox>
                       <rich:spacer width="2" />
                       <rich:panel bodyClass="rich-laguna-panel-no-header">
                            <h:panelGrid columns="3">
                                <a4j:mediaOutput  element="#{file.elementType}"  uriAttribute="#{file.uriAttr}" type="#{file.mime}" mimeType="#{file.mime}" 
                                    createContent="#{viewUploadedFilesBacking.paint}"  value="#{row}"
                                    style="width:150px; height:150px;" cacheable="false">
                                    
                                 </a4j:mediaOutput>
                                
                             <h:panelGrid columns="2">
                                    <h:outputText value="File type:" />
                                    <h:outputText value="#{file.mime}"/>
                                     <h:outputText value="File URL:" />
                                       <h:inputTextarea  value="#{file.fullName}" readonly="true" cols="20" rows="2" style="overflow:auto"></h:inputTextarea>
                                    <h:outputText value="File Length(Kb):" />
                                    <h:outputText  value="#{file.lengthInKb}" />
                                </h:panelGrid>
                            </h:panelGrid>
                        </rich:panel>
                    </rich:dataGrid>
                </rich:panel>
                <rich:spacer height="3"/>
                <br />
               
            </h:panelGroup>
        </h:panelGrid>
</h:form>
<f:view>
The code above just shows the usage of a4j:mediaoutput tag that is used to render images,flash files etc. The code mentioned below shows the backing bean that fetches the relevant information.
//imports here 
public class ViewUploadedFilesBacking implements Serializable{

 private static final long serialVersionUID = 1L;
 //List of DTO's each representing a file 
 private ArrayList<FileDTO> files = new ArrayList<FileDTO>();
 //Selection option for selecting all files
    private List<SelectItem> selectOptions=new ArrayList<SelectItem>();
    private int selectedOption;

    
    public List<SelectItem> getSelectOptions() {
  return selectOptions;
 }

 public void setSelectOptions(List<SelectItem> selectOptions) {
  this.selectOptions = selectOptions;
 }

 public static String trimFilePath(String fileName) {
        return fileName.substring(fileName.lastIndexOf("/") + 
                                  1).substring(fileName.lastIndexOf("\\") + 1);
    }

    public ViewUploadedFilesBacking() {
     displayALL();
     this.setSelectOptions(populateSelection());
       }
    public String performSelectionChange(){
     if(selectedOption==0){
            return ""; 
     }
     if(selectedOption==1){
      for (int i = 0; i < files.size(); i++) {
          files.get(i).setSelected(true);
      }
      return "";
          
            }
     else{
      for (int i = 0; i < files.size(); i++) {
          files.get(i).setSelected(false);
              }
      return "";
     }
    
    } 
    


 public int getSelectedOption() {
  return selectedOption;
 }


 public void setSelectedOption(int selectedOption) {
  this.selectedOption = selectedOption;
 }

    private List<SelectItem> populateSelection() {
     List<SelectItem> tempList=new ArrayList<SelectItem>();
  SelectItem item=new SelectItem(0,"-----Select------");
  tempList.add(item);
  item=new SelectItem(1,"Select ALL");
  tempList.add(item);
  item=new SelectItem(2,"Deselect ALL");
  tempList.add(item);
  return tempList;
 }
    //

    public void paint(OutputStream stream, Object object) throws IOException {
        stream.write(getFiles().get((Integer)object).getData());
    }

    
   
    
   public void displayALL(){
    FileStoreDAO fdao = FileStoreDAO.getInstance();
       files=fdao.getFiles();
           
    }

    public String deleteData() {
      FileStoreDAO fdao = FileStoreDAO.getInstance();
      FileUtility util=FileUtility.getInstance();
      Iterator it=files.listIterator();
      int i=0;
     while(it.hasNext()) {
      
      FileDTO fdto=(FileDTO)it.next();
      if(fdto.getSelected()){
            fdao.removeData(ViewUploadedFilesBacking.trimFilePath(fdto.getName()));
            util.deleteFile(ViewUploadedFilesBacking.trimFilePath(fdto.getName()));
     it.remove();
      
      }
      
        }
     FacesContext context = FacesContext.getCurrentInstance();
     String viewId = context.getViewRoot().getViewId();
     ViewHandler handler = context.getApplication().getViewHandler();
     UIViewRoot root = handler.createView(context, viewId);
     root.setViewId(viewId);
     context.setViewRoot(root);
     
        return null;
    }

    public long getTimeStamp() {
        return System.currentTimeMillis();
    }

    public ArrayList<FileDTO> getFiles() {
        return files;
    }

    public void setFiles(ArrayList<FileDTO> files) {
        this.files = files;
    }

   
}
The relevant part of DAO for retrieving the file is mentioned below.
//fetch records by executing prepared statement
rs=pstmt.executeQuery();
   FileDTO fdto=null;
   byte b[]=null;
   while(rs.next())
   {
    fdto=new FileDTO();
    int size=Integer.parseInt(rs.getString("file_size"));
    fdto.setLength(size);
    fdto.setLengthInKb((int)(size/1024));
    b=new byte[size];
    rs.getBinaryStream("file_data").read(b);
    fdto.setData(b);
    String contentType=rs.getString("file_type");
    fdto.setMime(contentType);
      if(contentType.contains("image")){
            fdto.setElementType("img");
            fdto.setUriAttr("src");
           }
           else if(contentType.contains("flash")){
            fdto.setElementType("object");
            fdto.setUriAttr("data");
           }
           else if(contentType.contains("javascript")){
            fdto.setElementType("script");
            fdto.setUriAttr("src");
           }
           else{
            fdto.setElementType("img");
            fdto.setUriAttr("src");
           }
ResourceBundle rb = 
                ResourceBundle.getBundle("bundle location here");

 fdto.setFullName(rb.getString("context root")+"rest servlet path"+rs.getString("file_name"));
 fdto.setName(rs.getString("file_name"));
 files.add(fdto);
return files;
.....
The thing to note in the above code is the element type and URI attribute properties these will be used by the a4j media output tag to render the file such as flash, images etc.

The FileDTO class is mentioned below
public class FileDTO {
    private String fullName;
    private String uriAttr;
    private int lengthInKb;
    private String Name;
    private String mime;
    private Boolean selected;
    private String fileName;
    private long length;
    private byte[]data;

    public  FileDTO(){
        
    }
   
    public int getLengthInKb() {
  return lengthInKb;
 }

 public void setLengthInKb(int lengthInKb) {
  this.lengthInKb = lengthInKb;
 }

 public String getUriAttr() {
  return uriAttr;
 }

 public void setUriAttr(String uriAttr) {
  this.uriAttr = uriAttr;
 }

 public String getFullName() {
  return fullName;
 }

 public void setFullName(String fullName) {
  this.fullName = fullName;
 }


   
    public Boolean getSelected() {
  return selected;
 }

 public void setSelected(Boolean selected) {
  this.selected = selected;
 }

 private String elementType;
 public String getElementType() {
  return elementType;
 }

 public void setElementType(String elementType) {
  this.elementType = elementType;
 }

    public String getFileName() {
  return fileName;
 }

 public void setFileName(String fileName) {
  this.fileName = fileName;
 }
    
    
    public void setData(byte []b){
     this.data=b;
    
    }
    public byte[] getData(){
     
     return data;
    }


 public void setMime(String mime) {
  this.mime = mime;
 }


    public String getName() {
        return Name;
    }
    public void setName(String name) {
        Name = name;
    
    }
    public long getLength() {
        return length;
    }
    public void setLength(long length) {
        this.length = length;
    }
    
    public String getMime(){
        return mime;
    }
}

Now that previewing and uploading is done, we can now use the uploaded files and create our own html pages on the fly and expose these pages as rest resources.
The jsf code for using tiny mce is mentioned below. Note that here there is no option of creating a file, this can easily be added. The code below shows how to edit a file that is already stored in the database.
// taglib imports go here 
<f:view>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="tiny_mce/tiny_mce.js"></script>
<script type="text/javascript">

//valid elements tag is there to ensure that tiny mce does not strip these tags 
//off as invalid html this is crucial.

 tinyMCE.init({
 // General options
 mode : "exact",
 elements:"form1:data",
 theme : "advanced",
 skin : "o2k7",
 cleanup : true,
 
 valid_elements:"blink,"
  +"a[accesskey|charset|class|coords|dir<ltr?rtl|href|hreflang|id|lang|name"
    +"|onblur|onclick|ondblclick|onfocus|onkeydown|onkeypress|onkeyup"
    +"|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|rel|rev"
    +"|shape<circle?default?poly?rect|style|tabindex|title|target|type],"
  +"abbr[class|dir<ltr?rtl|id|lang|onclick|ondblclick|onkeydown|onkeypress"
    +"|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style"
    +"|title],"
  +"acronym[class|dir<ltr?rtl|id|id|lang|onclick|ondblclick|onkeydown|onkeypress"
    +"|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style"
    +"|title],"
  +"address[class|align|dir<ltr?rtl|id|lang|onclick|ondblclick|onkeydown"
    +"|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover"
    +"|onmouseup|style|title],"
  +"applet[align<bottom?left?middle?right?top|alt|archive|class|code|codebase"
    +"|height|hspace|id|name|object|style|title|vspace|width],"
  +"area[accesskey|alt|class|coords|dir<ltr?rtl|href|id|lang|nohref<nohref"
    +"|onblur|onclick|ondblclick|onfocus|onkeydown|onkeypress|onkeyup"
    +"|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup"
    +"|shape<circle?default?poly?rect|style|tabindex|title|target],"
  +"base[href|target],"
  +"basefont[color|face|id|size],"
  +"bdo[class|dir<ltr?rtl|id|lang|style|title],"
  +"big[class|dir<ltr?rtl|id|lang|onclick|ondblclick|onkeydown|onkeypress"
    +"|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style"
    +"|title],"
  +"blockquote[cite|class|dir<ltr?rtl|id|lang|onclick|ondblclick"
    +"|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout"
    +"|onmouseover|onmouseup|style|title],"
  +"body[alink|background|bgcolor|class|dir<ltr?rtl|id|lang|link|onclick"
    +"|ondblclick|onkeydown|onkeypress|onkeyup|onload|onmousedown|onmousemove"
    +"|onmouseout|onmouseover|onmouseup|onunload|style|title|text|vlink],"
  +"br[class|clear<all?left?none?right|id|style|title],"
  +"button[accesskey|class|dir<ltr?rtl|disabled<disabled|id|lang|name|onblur"
    +"|onclick|ondblclick|onfocus|onkeydown|onkeypress|onkeyup|onmousedown"
    +"|onmousemove|onmouseout|onmouseover|onmouseup|style|tabindex|title|type"
    +"|value],"
  +"caption[align<bottom?left?right?top|class|dir<ltr?rtl|id|lang|onclick"
    +"|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove"
    +"|onmouseout|onmouseover|onmouseup|style|title],"
  +"center[class|dir<ltr?rtl|id|lang|onclick|ondblclick|onkeydown|onkeypress"
    +"|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style"
    +"|title],"
  +"cite[class|dir<ltr?rtl|id|lang|onclick|ondblclick|onkeydown|onkeypress"
    +"|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style"
    +"|title],"
  +"code[class|dir<ltr?rtl|id|lang|onclick|ondblclick|onkeydown|onkeypress"
    +"|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style"
    +"|title],"
  +"col[align<center?char?justify?left?right|char|charoff|class|dir<ltr?rtl|id"
    +"|lang|onclick|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown"
    +"|onmousemove|onmouseout|onmouseover|onmouseup|span|style|title"
    +"|valign<baseline?bottom?middle?top|width],"
  +"colgroup[align<center?char?justify?left?right|char|charoff|class|dir<ltr?rtl"
    +"|id|lang|onclick|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown"
    +"|onmousemove|onmouseout|onmouseover|onmouseup|span|style|title"
    +"|valign<baseline?bottom?middle?top|width],"
  +"dd[class|dir<ltr?rtl|id|lang|onclick|ondblclick|onkeydown|onkeypress|onkeyup"
    +"|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style|title],"
  +"del[cite|class|datetime|dir<ltr?rtl|id|lang|onclick|ondblclick|onkeydown"
    +"|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover"
    +"|onmouseup|style|title],"
  +"dfn[class|dir<ltr?rtl|id|lang|onclick|ondblclick|onkeydown|onkeypress"
    +"|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style"
    +"|title],"
  +"dir[class|compact<compact|dir<ltr?rtl|id|lang|onclick|ondblclick|onkeydown"
    +"|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover"
    +"|onmouseup|style|title],"
  +"div[align<center?justify?left?right|class|dir<ltr?rtl|id|lang|onclick"
    +"|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove"
    +"|onmouseout|onmouseover|onmouseup|style|title],"
  +"dl[class|compact<compact|dir<ltr?rtl|id|lang|onclick|ondblclick|onkeydown"
    +"|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover"
    +"|onmouseup|style|title],"
  +"dt[class|dir<ltr?rtl|id|lang|onclick|ondblclick|onkeydown|onkeypress|onkeyup"
    +"|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style|title],"
  +"em/i[class|dir<ltr?rtl|id|lang|onclick|ondblclick|onkeydown|onkeypress"
    +"|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style"
    +"|title],"
  +"fieldset[class|dir<ltr?rtl|id|lang|onclick|ondblclick|onkeydown|onkeypress"
    +"|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style"
    +"|title],"
  +"font[class|color|dir<ltr?rtl|face|id|lang|size|style|title],"
  +"form[accept|accept-charset|action|class|dir<ltr?rtl|enctype|id|lang"
    +"|method<get?post|name|onclick|ondblclick|onkeydown|onkeypress|onkeyup"
    +"|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|onreset|onsubmit"
    +"|style|title|target],"
  +"frame[class|frameborder|id|longdesc|marginheight|marginwidth|name"
    +"|noresize<noresize|scrolling<auto?no?yes|src|style|title],"
  +"frameset[class|cols|id|onload|onunload|rows|style|title],"
  +"h1[align<center?justify?left?right|class|dir<ltr?rtl|id|lang|onclick"
    +"|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove"
    +"|onmouseout|onmouseover|onmouseup|style|title],"
  +"h2[align<center?justify?left?right|class|dir<ltr?rtl|id|lang|onclick"
    +"|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove"
    +"|onmouseout|onmouseover|onmouseup|style|title],"
  +"h3[align<center?justify?left?right|class|dir<ltr?rtl|id|lang|onclick"
    +"|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove"
    +"|onmouseout|onmouseover|onmouseup|style|title],"
  +"h4[align<center?justify?left?right|class|dir<ltr?rtl|id|lang|onclick"
    +"|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove"
    +"|onmouseout|onmouseover|onmouseup|style|title],"
  +"h5[align<center?justify?left?right|class|dir<ltr?rtl|id|lang|onclick"
    +"|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove"
    +"|onmouseout|onmouseover|onmouseup|style|title],"
  +"h6[align<center?justify?left?right|class|dir<ltr?rtl|id|lang|onclick"
    +"|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove"
    +"|onmouseout|onmouseover|onmouseup|style|title],"
  +"head[dir<ltr?rtl|lang|profile],"
  +"hr[align<center?left?right|class|dir<ltr?rtl|id|lang|noshade<noshade|onclick"
    +"|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove"
    +"|onmouseout|onmouseover|onmouseup|size|style|title|width],"
  +"html[dir<ltr?rtl|lang|version],"
  +"iframe[align<bottom?left?middle?right?top|class|frameborder|height|id"
    +"|longdesc|marginheight|marginwidth|name|scrolling<auto?no?yes|src|style"
    +"|title|width],"
  +"img[align<bottom?left?middle?right?top|alt|border|class|dir<ltr?rtl|height"
    +"|hspace|id|ismap<ismap|lang|longdesc|name|onclick|ondblclick|onkeydown"
    +"|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover"
    +"|onmouseup|src|style|title|usemap|vspace|width],"
  +"input[accept|accesskey|align<bottom?left?middle?right?top|alt"
    +"|checked<checked|class|dir<ltr?rtl|disabled<disabled|id|ismap<ismap|lang"
    +"|maxlength|name|onblur|onclick|ondblclick|onfocus|onkeydown|onkeypress"
    +"|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|onselect"
    +"|readonly<readonly|size|src|style|tabindex|title"
    +"|type<button?checkbox?file?hidden?image?password?radio?reset?submit?text"
    +"|usemap|value],"
  +"ins[cite|class|datetime|dir<ltr?rtl|id|lang|onclick|ondblclick|onkeydown"
    +"|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover"
    +"|onmouseup|style|title],"
  +"isindex[class|dir<ltr?rtl|id|lang|prompt|style|title],"
  +"kbd[class|dir<ltr?rtl|id|lang|onclick|ondblclick|onkeydown|onkeypress"
    +"|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style"
    +"|title],"
  +"label[accesskey|class|dir<ltr?rtl|for|id|lang|onblur|onclick|ondblclick"
    +"|onfocus|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout"
    +"|onmouseover|onmouseup|style|title],"
  +"legend[align<bottom?left?right?top|accesskey|class|dir<ltr?rtl|id|lang"
    +"|onclick|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove"
    +"|onmouseout|onmouseover|onmouseup|style|title],"
  +"li[class|dir<ltr?rtl|id|lang|onclick|ondblclick|onkeydown|onkeypress|onkeyup"
    +"|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style|title|type"
    +"|value],"
  +"link[charset|class|dir<ltr?rtl|href|hreflang|id|lang|media|onclick"
    +"|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove"
    +"|onmouseout|onmouseover|onmouseup|rel|rev|style|title|target|type],"
  +"map[class|dir<ltr?rtl|id|lang|name|onclick|ondblclick|onkeydown|onkeypress"
    +"|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style"
    +"|title],"
  +"menu[class|compact<compact|dir<ltr?rtl|id|lang|onclick|ondblclick|onkeydown"
    +"|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover"
    +"|onmouseup|style|title],"
  +"meta[content|dir<ltr?rtl|http-equiv|lang|name|scheme],"
  +"noframes[class|dir<ltr?rtl|id|lang|onclick|ondblclick|onkeydown|onkeypress"
    +"|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style"
    +"|title],"
  +"noscript[class|dir<ltr?rtl|id|lang|style|title],"
  +"object[align<bottom?left?middle?right?top|archive|border|class|classid"
    +"|codebase|codetype|data|declare|dir<ltr?rtl|height|hspace|id|lang|name"
    +"|onclick|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove"
    +"|onmouseout|onmouseover|onmouseup|standby|style|tabindex|title|type|usemap"
    +"|vspace|width],"
  +"ol[class|compact<compact|dir<ltr?rtl|id|lang|onclick|ondblclick|onkeydown"
    +"|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover"
    +"|onmouseup|start|style|title|type],"
  +"optgroup[class|dir<ltr?rtl|disabled<disabled|id|label|lang|onclick"
    +"|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove"
    +"|onmouseout|onmouseover|onmouseup|style|title],"
  +"option[class|dir<ltr?rtl|disabled<disabled|id|label|lang|onclick|ondblclick"
    +"|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout"
    +"|onmouseover|onmouseup|selected<selected|style|title|value],"
  +"p[align<center?justify?left?right|class|dir<ltr?rtl|id|lang|onclick"
    +"|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove"
    +"|onmouseout|onmouseover|onmouseup|style|title],"
  +"param[id|name|type|value|valuetype<DATA?OBJECT?REF],"
  +"pre/listing/plaintext/xmp[align|class|dir<ltr?rtl|id|lang|onclick|ondblclick"
    +"|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout"
    +"|onmouseover|onmouseup|style|title|width],"
  +"q[cite|class|dir<ltr?rtl|id|lang|onclick|ondblclick|onkeydown|onkeypress"
    +"|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style"
    +"|title],"
  +"s[class|dir<ltr?rtl|id|lang|onclick|ondblclick|onkeydown|onkeypress|onkeyup"
    +"|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style|title],"
  +"samp[class|dir<ltr?rtl|id|lang|onclick|ondblclick|onkeydown|onkeypress"
    +"|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style"
    +"|title],"
  +"script[charset|defer|language|src|type],"
  +"select[class|dir<ltr?rtl|disabled<disabled|id|lang|multiple<multiple|name"
    +"|onblur|onchange|onclick|ondblclick|onfocus|onkeydown|onkeypress|onkeyup"
    +"|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|size|style"
    +"|tabindex|title],"
  +"small[class|dir<ltr?rtl|id|lang|onclick|ondblclick|onkeydown|onkeypress"
    +"|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style"
    +"|title],"
  +"span[align<center?justify?left?right|class|dir<ltr?rtl|id|lang|onclick|ondblclick|onkeydown"
    +"|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover"
    +"|onmouseup|style|title],"
  +"strike[class|class|dir<ltr?rtl|id|lang|onclick|ondblclick|onkeydown"
    +"|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover"
    +"|onmouseup|style|title],"
  +"strong/b[class|dir<ltr?rtl|id|lang|onclick|ondblclick|onkeydown|onkeypress"
    +"|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style"
    +"|title],"
  +"style[dir<ltr?rtl|lang|media|title|type],"
  +"sub[class|dir<ltr?rtl|id|lang|onclick|ondblclick|onkeydown|onkeypress"
    +"|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style"
    +"|title],"
  +"sup[class|dir<ltr?rtl|id|lang|onclick|ondblclick|onkeydown|onkeypress"
    +"|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style"
    +"|title],"
  +"table[align<center?left?right|bgcolor|border|cellpadding|cellspacing|class"
    +"|dir<ltr?rtl|frame|height|id|lang|onclick|ondblclick|onkeydown|onkeypress"
    +"|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|rules"
    +"|style|summary|title|width|bordercolor],"
  +"tbody[align<center?char?justify?left?right|char|class|charoff|dir<ltr?rtl|id"
    +"|lang|onclick|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown"
    +"|onmousemove|onmouseout|onmouseover|onmouseup|style|title"
    +"|valign<baseline?bottom?middle?top],"
  +"td[abbr|align<center?char?justify?left?right|axis|bgcolor|char|charoff|class"
    +"|colspan|dir<ltr?rtl|headers|height|id|lang|nowrap<nowrap|onclick"
    +"|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove"
    +"|onmouseout|onmouseover|onmouseup|rowspan|scope<col?colgroup?row?rowgroup"
    +"|style|title|valign<baseline?bottom?middle?top|width],"
  +"textarea[accesskey|class|cols|dir<ltr?rtl|disabled<disabled|id|lang|name"
    +"|onblur|onclick|ondblclick|onfocus|onkeydown|onkeypress|onkeyup"
    +"|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|onselect"
    +"|readonly<readonly|rows|style|tabindex|title],"
  +"tfoot[align<center?char?justify?left?right|char|charoff|class|dir<ltr?rtl|id"
    +"|lang|onclick|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown"
    +"|onmousemove|onmouseout|onmouseover|onmouseup|style|title"
    +"|valign<baseline?bottom?middle?top],"
  +"th[abbr|align<center?char?justify?left?right|axis|bgcolor|char|charoff|class"
    +"|colspan|dir<ltr?rtl|headers|height|id|lang|nowrap<nowrap|onclick"
    +"|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove"
    +"|onmouseout|onmouseover|onmouseup|rowspan|scope<col?colgroup?row?rowgroup"
    +"|style|title|valign<baseline?bottom?middle?top|width],"
  +"thead[align<center?char?justify?left?right|char|charoff|class|dir<ltr?rtl|id"
    +"|lang|onclick|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown"
    +"|onmousemove|onmouseout|onmouseover|onmouseup|style|title"
    +"|valign<baseline?bottom?middle?top],"
  +"title[dir<ltr?rtl|lang],"
  +"tr[abbr|align<center?char?justify?left?right|bgcolor|char|charoff|class"
    +"|rowspan|dir<ltr?rtl|id|lang|onclick|ondblclick|onkeydown|onkeypress"
    +"|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style"
    +"|title|valign<baseline?bottom?middle?top],"
  +"tt[class|dir<ltr?rtl|id|lang|onclick|ondblclick|onkeydown|onkeypress|onkeyup"
    +"|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style|title],"
  +"u[class|dir<ltr?rtl|id|lang|onclick|ondblclick|onkeydown|onkeypress|onkeyup"
    +"|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style|title],"
  +"ul[class|compact<compact|dir<ltr?rtl|id|lang|onclick|ondblclick|onkeydown"
    +"|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover"
    +"|onmouseup|style|title|type],"
  +"var[class|dir<ltr?rtl|id|lang|onclick|ondblclick|onkeydown|onkeypress"
    +"|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style"
    +"|title],font[size|*]",
   
 convert_fonts_to_spans : false,   
 convert_urls : false,
 skin_variant : "black",
 plugins : "safari,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras",
    width:1000,
    height:700,
    trim_span_elements : false,
    
    
 // Theme options
 theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
 theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
 theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
 theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,spellchecker,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,blockquote,pagebreak,|,insertfile,insertimage",
 theme_advanced_toolbar_location : "top",
 theme_advanced_toolbar_align : "left",
 theme_advanced_statusbar_location : "bottom",
 theme_advanced_resizing : true,

 // Example content CSS (should be your site CSS)
 content_css : "css/example.css",

 // Drop lists for link/image/media/template dialogs
 template_external_list_url : "js/template_list.js",
 external_link_list_url : "js/link_list.js",
 external_image_list_url : "js/image_list.js",
 media_external_list_url : "js/media_list.js",

 
});



</head>
<body>
<h:form id="form1">
...
<div id="heading">
                                                <h1><label>CMS Editor</label></h1>
                                                <div class="clear">                                  
                 <fieldset style="width:96%; ">
                  <legend style="background-color:#cc6666;color:#FFFFFF;font-size:small; font-weight:bold;">Content File Editor</legend> 
                    <h:messages id="message" errorClass="error"/>
                   <table border="0">
                 <tr >
                 

<h:selectOneMenu id="file"   value="#{EditFile.fileID}" >
                        <f:selectItems value="#{EditFile.fileList}"/>
                       <a4j:support event="onchange" action="#{EditFile.getDataFromDB}" reRender="data"/>
                        
</h:selectOneMenu>

<h:inputTextarea id="data" value="#{EditFile.data}"/> 
<br/> 
<h:commandButton value="Save Changes" action="#{EditFile.storeData}" />

<rich:effect event="onmouseover" for="message" type="Fade"/> 
</h:form>

</body>
</html>
</f:view>

The thing to note above is on selection change you will need to force refresh in JSF code so that tiny mce element is populated with the stored file from the database.

Below is the code for refreshing the JSF page after fetching data from the database.
...
this.setData(dao.getFileData(fileID));
FacesContext context = FacesContext.getCurrentInstance();
String viewId = context.getViewRoot().getViewId();
ViewHandler handler = context.getApplication().getViewHandler();
UIViewRoot root = handler.createView(context, viewId);
root.setViewId(viewId);
context.setViewRoot(root);
...
Now this editor can be used to edit the files, when you need to insert an image or flash file just use the preview files window to get the restful path of the uploaded files and then place that path in the tiny mce when you insert an image or flash object. After you are done with making changes just save the file and changes will be written to the database, After the changes are written you can use the path appended with the rest resource path and the file name to expose this saved file as a rest resource to retrieve the updated html page.

The jersey code is mentioned below
@Path("/") 
public class FileResource {
 

    /**
     * @param filename passed in the get request
     * @returns the requested resource as stream 
     * 
     *
     **/       
 @GET
 @Path("/files/{filename}")
 @Produces(MediaType.WILDCARD)
 public Response returnFileAsStream(@PathParam("filename") String fileName){
  FileStoreDAO ftDAO=FileStoreDAO.getInstance();
  FileUtility futil=FileUtility.getInstance();
  
  
        FileDTO fdto=ftDAO.readFile(fileName);
  if(fdto!=null){
        String contentType=fdto.getMime();
  InputStream is=fdto.getFileData();
  return Response.ok(is,contentType).build();
  }
  InputStream is=null;
 
  if((is=futil.getDataAsStream(fileName))!=null){
      
                      MediaType mt=DefaultMediaTypePredictor.CommonMediaTypes.getMediaTypeFromFileName(fileName);
                      return Response.ok(is,mt).build();
                     
                     
  }
  return Response.noContent().build();
 }
 @GET
 @Path("/content/{filename}")
 @Produces(MediaType.TEXT_HTML)
 public Response returnContentAsStream(@PathParam("filename") String fileName)
 {
  FileDataDAO fdDAO= new FileDataDAO();
  FileUtility futil=FileUtility.getInstance();
  String data=fdDAO.getFileData(fileName);
  if(data!=null&&!data.trim().equals("")){
  return Response.ok(fdDAO.getFileData(fileName),MediaType.TEXT_HTML).build();
  }
  InputStream is=null;
  
  if((is=futil.getDataAsStream(fileName))!=null){
    MediaType mt=DefaultMediaTypePredictor.CommonMediaTypes.getMediaTypeFromFileName(fileName);
    return Response.ok(is,mt).build();
  }
  else
  {
   return Response.noContent().build();
  }
 }

}
The above code exposes two resources one that returns the HTML page, the other returns the stored files like images, flash, movies.Note: You should employ the cache control header to reduce the fetching from database, increase performance and reduce load both on client and server side.

Hope this tutorial will be indicative enough on how one can easily make their own Content Management System through which content can be edited in real time.


Posted on Saturday, April 23, 2011 by Unknown