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 Ramandeep Singh Nanda

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 Ramandeep Singh Nanda