/****************************************************************
 * Copyright (C) 2005 LAMS Foundation (http://lamsfoundation.org)
 * =============================================================
 * License Information: http://lamsfoundation.org/licensing/lams/2.0/
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2.0 
 * as published by the Free Software Foundation.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
 * USA
 * 
 * http://www.gnu.org/licenses/gpl.txt
 * ****************************************************************
 */

/* $$Id: TwitterAuthoringAction.java,v 1.36 2007/10/08 06:14:13 ernieg Exp $$ */
package org.lamsfoundation.lams.tool.twitter.web;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.upload.FormFile;
import org.apache.struts.util.MessageResources;
import org.lamsfoundation.lams.authoring.web.AuthoringConstants;
import org.lamsfoundation.lams.contentrepository.InvalidParameterException;
import org.lamsfoundation.lams.contentrepository.NodeKey;
import org.lamsfoundation.lams.contentrepository.RepositoryCheckedException;
import org.lamsfoundation.lams.contentrepository.client.IToolContentHandler;
import org.lamsfoundation.lams.tool.twitter.TwitterApplicationException;
import org.lamsfoundation.lams.tool.twitter.TwitterAttachment;
import org.lamsfoundation.lams.tool.twitter.TwitterConstants;
import org.lamsfoundation.lams.tool.twitter.TwitterContent;
import org.lamsfoundation.lams.tool.twitter.service.ITwitterService;
import org.lamsfoundation.lams.tool.twitter.service.TwitterServiceProxy;
import org.lamsfoundation.lams.tool.twitter.util.TwitterWebUtil;
import org.lamsfoundation.lams.usermanagement.dto.UserDTO;
import org.lamsfoundation.lams.util.FileValidatorUtil;
import org.lamsfoundation.lams.util.WebUtil;
import org.lamsfoundation.lams.web.action.LamsDispatchAction;
import org.lamsfoundation.lams.web.session.SessionManager;
import org.lamsfoundation.lams.web.util.AttributeNames;
import org.lamsfoundation.lams.web.util.SessionMap;

/**
 * @author mtruong
 * 
 * <p>This class is a simple combination of TwitterAuthoringStarterAction and TwitterAuthoringAction.
 * It has been created for the purpose of supporting the new authoring page which is done using 
 * DHTML.</p>
 * 
 * <p>The unspecified method, is the same as the execute method for TwitterAuthoringStarterAction.
 * It will get called when the method parameter is not specified (that is on first entry
 * into the authoring environment).</p>
 * 
 * <p> The save, upload and delete method is the same as that of TwitterAuthoringAction, to see its explanation,
 * please see org.lamsfoundation.lams.tool.twitter.web.TwitterAuthoringAction </p>
 *
 * ----------------XDoclet Tags--------------------
 * 
 * @struts:action path="/authoring" name="TwitterAuthoringForm" scope="request"
 * 				  type="org.lamsfoundation.lams.tool.twitter.web.TwitterAuthoringAction"
 *                parameter="method" validate="true" input="/author_page.jsp"
 *
 * @struts:action-forward name="authoringContent" path="/authoring/authoring.jsp"
 * @struts:action-forward name="displayMessage" path=".message"
 * 
 * ----------------XDoclet Tags--------------------
 */

public class TwitterAuthoringAction extends LamsDispatchAction {
	
	
    static Logger logger = Logger.getLogger(TwitterAuthoringAction.class.getName());
    public final static String FORM="TwitterAuthoringForm";
    
    /** Get the user from the shared session */
	public UserDTO getUser(HttpServletRequest request) {
		// set up the user details
		HttpSession ss = SessionManager.getSession();
		UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER);
		if ( user == null )
		{
		    MessageResources resources = getResources(request);
		    String error = resources.getMessage(TwitterConstants.ERR_MISSING_PARAM, "User");
		    logger.error(error);
			throw new TwitterApplicationException(error);
		}
		return user;
	}

    
    public ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws TwitterApplicationException {
        
	    //to ensure that we are working with a new form, not one from previous session
		TwitterAuthoringForm twitterForm = new TwitterAuthoringForm();		
		
		Long contentId = WebUtil.readLongParam(request, TwitterConstants.TOOL_CONTENT_ID);
		String contentFolderId = WebUtil.readStrParam(request, TwitterConstants.CONTENT_FOLDER_ID);
		
		twitterForm.setToolContentID(contentId.toString());
		
		/* DefineLater is used in the basic screen. If defineLater is set, then in the authoring page,
		 * the two tabs {Advanced, Instructions} are not visible.
		 */
		twitterForm.setDefineLater(request.getParameter(TwitterConstants.DEFINE_LATER));
							
		/*
		 * Retrieve the Service
		 */
		ITwitterService twitterService = TwitterServiceProxy.getTwitterService(getServlet().getServletContext());
		
		List attachmentList = null;
		if (!contentExists(twitterService, contentId))
		{
			//	Pre-fill the form with the default content
			//TwitterContent twitter =	twitterService.retrieveTwitter(TwitterConstants.DEFAULT_CONTENT_ID);
		    Long defaultToolContentId = twitterService.getToolDefaultContentIdBySignature(TwitterConstants.TOOL_SIGNATURE);
		  //  logger.debug("Default tool content id is " + defaultToolContentId);
		    TwitterContent twitter = twitterService.retrieveTwitter(defaultToolContentId);
			
		    if (twitter==null)
		    {
		        String error= "There is data missing in the database";
		        logger.error(error);
		        throw new TwitterApplicationException(error);
		    }
			
			//initialise the values in the form, so the values will be shown in the jsp
			twitterForm.setToolContentID(contentId.toString());
			twitterForm.setContentFolderID(contentFolderId);
			twitterForm.setTitle(twitter.getTitle());
			twitterForm.setContent(twitter.getContent());
			twitterForm.setOnlineInstructions(twitter.getOnlineInstructions());
			twitterForm.setOfflineInstructions(twitter.getOfflineInstructions());
			twitterForm.setTeacherTwitterUsername(twitter.getTeacherTwitterUsername());
			twitterForm.setLearnersTwitterUsernames(twitter.getLearnersTwitterUsernames());
			twitterForm.setHashtags(twitter.getHashtags());
			
			attachmentList = TwitterWebUtil.setupAttachmentList(twitterService,null);
		
		}
		else //content already exists on the database
		{
			//get the values from the database
			TwitterContent twitter = twitterService.retrieveTwitter(contentId);
			
			/* If retrieving existing content, check whether the contentInUse flag is set, if set, the
			 * author is not allowed to edit content 
			 */
			
		    /* Define later set to true when the edit activity tab is brought up 
		     * So that users cannot start using the content while the staff member is editing the content */
		    twitterForm.populateFormWithTwitterContentValues(twitter);
		    twitterForm.setContentFolderID(contentFolderId);
		    twitter.setDefineLater(Boolean.parseBoolean(twitterForm.getDefineLater()));
		    twitterService.saveTwitter(twitter);
			    
		    /** TODO: setup values in the instructions map */
			
			//Setup the map containing the files that have been uploaded for this particular tool content id
			attachmentList = TwitterWebUtil.setupAttachmentList(twitterService,twitter);
		
		}
		
		SessionMap map = TwitterWebUtil.addUploadsToSession(null, request, attachmentList, TwitterWebUtil.setupDeletedAttachmentList());
		twitterForm.setSessionMapID(map.getSessionID());
		
		request.setAttribute(FORM, twitterForm);
		return mapping.findForward(TwitterConstants.AUTHOR_PAGE);
    }

	/**
	 * Checks the session to see if the title and content session variables exist or not.
	 * 
	 * @param session The HttpSession to check.
	 * @return true if the parameters title and content exists in the session, false otherwise
	 */
	private boolean contentExists(ITwitterService service, Long id)
	{
		TwitterContent twitter = service.retrieveTwitter(id);
		if (twitter == null)
			return false;
		else
			return true;
		
	}
	
	public ActionForward save(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws TwitterApplicationException {
			
		TwitterAuthoringForm twitterForm = (TwitterAuthoringForm)form;

		//copyAuthoringFormValuesIntoFormBean(request, twitterForm);
		
		ITwitterService twitterService = TwitterServiceProxy.getTwitterService(getServlet().getServletContext());
		String idAsString = twitterForm.getToolContentID();
		if (idAsString == null)
		{
		    MessageResources resources = getResources(request);
		    String error = resources.getMessage(TwitterConstants.ERR_MISSING_PARAM, "Tool Content Id");
		    logger.error(error);
			throw new TwitterApplicationException(error);
		}
		Long content_id = TwitterWebUtil.convertToLong(twitterForm.getToolContentID());
		
		//throws exception if the content id does not exist
		checkContentId(content_id);
		
		TwitterContent twitterContent = twitterService.retrieveTwitter(content_id);
		if ( twitterContent == null ) {
			//create a new twitter object 
			twitterContent = new TwitterContent();
			twitterContent.setTwitterContentId(content_id);
		}
		
		twitterForm.copyValuesIntoTwitterContent(twitterContent);
		
		//Obtiene los hashtags del texto ingresado por el usuario
		twitterContent.setTeacherTwitterUsername(twitterContent.getTeacherTwitterUsername().trim());
		twitterContent.setLearnersTwitterUsernames(parseTags(twitterContent.getLearnersTwitterUsernames()));
		twitterContent.setHashtags(parseTags(twitterContent.getHashtags()));
		
		//Generaci—n de hashtag de la actividad
		twitterContent.setActivityHashtag("lams_"+getRandomString(6));
		System.out.println("lams_"+getRandomString(6)+"******");
		
		if ( twitterContent.getDateCreated() == null )
			twitterContent.setDateCreated(twitterContent.getDateUpdated()); 
		
		UserDTO user = getUser(request);
		twitterContent.setCreatorUserId(new Long(user.getUserID().longValue()));
		
		// Author has finished editing the content and mark the defineLater flag to false
		twitterContent.setDefineLater(false);
		twitterService.saveTwitter(twitterContent);
		
		// Save the attachments then update the attachment collections in the session.
		SessionMap sessionMap = getSessionMap(request, twitterForm);
		List attachmentList = (List) sessionMap.get(TwitterConstants.ATTACHMENT_LIST);
		List deletedAttachmentList = (List) sessionMap.get(TwitterConstants.DELETED_ATTACHMENT_LIST);
		deletedAttachmentList = saveAttachments(twitterService, twitterContent, attachmentList, deletedAttachmentList, mapping, request);
		sessionMap = TwitterWebUtil.addUploadsToSession(sessionMap, request, attachmentList, deletedAttachmentList);
	
		request.setAttribute(AuthoringConstants.LAMS_AUTHORING_SUCCESS_FLAG,Boolean.TRUE);		    	
		return mapping.findForward(TwitterConstants.AUTHOR_PAGE);
		
	}
	  
	/** 
	* Go through the attachments collections. Remove any content repository or tool objects
	* matching entries in the the deletedAttachments collection, add any new attachments in the
	* attachments collection. Clear the deletedAttachments collection, ready for new editing.
	*/ 
  	private List saveAttachments (ITwitterService twitterService, TwitterContent twitterContent, 
  			List attachmentList, List deletedAttachmentList,
  			ActionMapping mapping, HttpServletRequest request) {

  		if ( deletedAttachmentList != null ) {
  			Iterator iter = deletedAttachmentList.iterator();
  			while (iter.hasNext()) {
				TwitterAttachment attachment = (TwitterAttachment) iter.next();
				
		    	try
		    	{
		    	// remove tool entry from db, does not removing entry from the content repository
		    	// deleting a non-existent entry shouldn't cause any errors.
					if ( attachment.getAttachmentId() != null ) {
						twitterService.removeAttachment(twitterContent, attachment);
					}
		    	} catch (RepositoryCheckedException e) {
		            logger.error("Unable to delete file",e);
		    		ActionMessages am = new ActionMessages(); 
		    		am.add( ActionMessages.GLOBAL_MESSAGE,  
		    	           new ActionMessage( TwitterConstants.ERROR_FILE_UPLOAD_CONTENT_REPOSITORY , 
		    	        		   			  attachment.getFilename())); 
		    		saveErrors( request, am );
		    	}
  			}
  			deletedAttachmentList.clear();
  		}
  		
  		if ( attachmentList != null ) {
  			Iterator iter = attachmentList.iterator();
  			while (iter.hasNext()) {
				TwitterAttachment attachment = (TwitterAttachment) iter.next();

				if ( attachment.getAttachmentId() == null ) {
					// add entry to tool table - file already in content repository
					twitterService.saveAttachment(twitterContent, attachment);
				}
  			}
  		}
  			
  		return deletedAttachmentList;
  	}
	  	
    /**
	 * This method will either upload an online instructions file or an offline instructions file. 
	 * It will upload an online file if the bean property onlineFile is not null and similarly,
	 * will upload an offline file if the bean property offlineFile is not null.
	 * By using the term "upload", we are saving the file information on the local database (?)
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws TwitterApplicationException
	 */
	public ActionForward upload(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
		throws InvalidParameterException, FileNotFoundException, RepositoryCheckedException, IOException, TwitterApplicationException {
	    		
	    
	    	//set up the values in the map
	    	//call the uploadFile method from toolContentHandler
	    	TwitterAuthoringForm twitterForm = (TwitterAuthoringForm)form;
	    	//copyAuthoringFormValuesIntoFormBean(request, twitterForm);
	    	FormFile theFile;
	    	ITwitterService twitterService = TwitterServiceProxy.getTwitterService(getServlet().getServletContext());
			
	    	Long content_id = TwitterWebUtil.convertToLong(twitterForm.getToolContentID());
			//throws exception if the content id does not exist
			checkContentId(content_id);
			TwitterContent twitterContent = twitterService.retrieveTwitter(content_id);
			
			//validate file max size
			ActionMessages errors = new ActionMessages();
			FileValidatorUtil.validateFileSize(twitterForm.getOnlineFile(), true, errors );
			FileValidatorUtil.validateFileSize(twitterForm.getOfflineFile(), true, errors );
			if(!errors.isEmpty()){
				this.saveErrors(request, errors);
				return mapping.findForward(TwitterConstants.AUTHOR_PAGE);
			}
			
	    	//check if the file uploaded is an online instructions file or offline instructions file.
	    	//if one of the types is null, then the other one must have been uploaded. 
	    	//here we check if the file is an online one
			
			if ((twitterForm.getOnlineFile() != null && (twitterForm.getOnlineFile().getFileName().trim().length() != 0)) ||
			        (twitterForm.getOfflineFile() != null && (twitterForm.getOfflineFile().getFileName().trim().length() != 0)))
			{
		    	boolean isOnlineFile = ((twitterForm.getOnlineFile() != null && (twitterForm.getOnlineFile().getFileName().trim().length() != 0)) ? true: false );
		    	theFile = (isOnlineFile ? twitterForm.getOnlineFile() : twitterForm.getOfflineFile());
		    	String fileType = isOnlineFile ? IToolContentHandler.TYPE_ONLINE : IToolContentHandler.TYPE_OFFLINE;

		    	SessionMap map = getSessionMap(request, twitterForm);
				List attachmentList = (List) map.get(TwitterConstants.ATTACHMENT_LIST);
		    	List deletedAttachmentList = (List) map.get(TwitterConstants.DELETED_ATTACHMENT_LIST);
		    	
		    	// if a file with the same name already exists then move the old one to deleted
		    	deletedAttachmentList = moveToDelete(theFile.getFileName(), isOnlineFile, attachmentList, deletedAttachmentList );
		    	
		    	try
		    	{
	    	        // This is a new file and so is saved to the content repository. Add it to the 
		    		// attachments collection, but don't add it to the tool's tables yet.
		    		NodeKey node = twitterService.uploadFile(theFile.getInputStream(), theFile.getFileName(), theFile.getContentType(), fileType);
	    	        TwitterAttachment file = new TwitterAttachment();
		    	    file.setFilename(theFile.getFileName());
		    	   	file.setOnlineFile(isOnlineFile);
			    	file.setTwitterContent(twitterContent);
			    	file.setUuid(node.getUuid());
			    	file.setVersionId(node.getVersion()); 
			    	
			    	// add the files to the attachment collection - if one existed, it should have already been removed.
		    	    attachmentList.add(file);
			    	map = TwitterWebUtil.addUploadsToSession(map, request, attachmentList, deletedAttachmentList);
			    	
			    	//reset the fields so that more files can be uploaded
			    	twitterForm.setOfflineFile(null);
			    	twitterForm.setOnlineFile(null);
		    	}
		    	catch (FileNotFoundException e) {
		            logger.error("Unable to uploadfile",e);
		            throw new TwitterApplicationException("Unable to upload file, exception was "+e.getMessage());
		    	} catch (IOException e) {
		            logger.error("Unable to uploadfile",e);
		            throw new TwitterApplicationException("Unable to upload file, exception was "+e.getMessage());
		    	} catch (RepositoryCheckedException e) {
		            logger.error("Unable to uploadfile",e);
		            throw new TwitterApplicationException("Unable to upload file, exception was "+e.getMessage());
		    	}			    	
			}
	  
			twitterForm.setMethod(TwitterConstants.INSTRUCTIONS);
			
			return mapping.findForward(TwitterConstants.AUTHOR_PAGE);
	}
		
		/** If this file exists in attachments list, move it to the deleted attachments list.
		 * Returns the updated deletedAttachments list, creating a new one if needed. Uses the filename 
		 * and isOnline flag to match up the attachment entry */
		private List moveToDelete(String filename, boolean isOnline, List attachmentsList, List deletedAttachmentsList ) {
			return moveToDelete(filename, isOnline, null, attachmentsList, deletedAttachmentsList);
		}
		/** If this file exists in attachments list, move it to the deleted attachments list.
		 * Returns the updated deletedAttachments list, creating a new one if needed. Uses the uuid of the
		 * file to match up the attachment entry */
		private List moveToDelete(Long uuid, List attachmentsList, List deletedAttachmentsList ) {
			return moveToDelete(null, false, uuid, attachmentsList, deletedAttachmentsList);
		}
		
		/** If this file exists in attachments map, move it to the deleted attachments map.
		 * Returns the updated deletedAttachments map, creating a new one if needed. If uuid supplied
		 * then tries to match on that, otherwise uses filename and isOnline. */
		private List moveToDelete(String filename, boolean isOnline, Long uuid, List attachmentsList, List deletedAttachmentsList ) {

			List deletedList = deletedAttachmentsList != null ? deletedAttachmentsList : TwitterWebUtil.setupDeletedAttachmentList();
			
			if ( attachmentsList != null ) {
				Iterator iter = attachmentsList.iterator();
				TwitterAttachment attachment = null;
				while ( iter.hasNext() && attachment == null ) {
					TwitterAttachment value = (TwitterAttachment) iter.next();
					
					if ( uuid != null ) {
						// compare using uuid
						if ( uuid.equals(value.getUuid()) ) {
							attachment = value;
						}
					} else {
						// compare using filename and online/offline flag
						if ( value.isOnlineFile() == isOnline && value.getFilename().equals(filename) ) {
							attachment = value;
						}
					}
				}
				if ( attachment != null ) {
					deletedList.add(attachment);
					attachmentsList.remove(attachment);
				}
			}
			
			return deletedList;
		}
		
		public ActionForward deleteAttachment(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
			throws InvalidParameterException, RepositoryCheckedException, TwitterApplicationException {
		
	    	//set up the values in the map
	    	TwitterAuthoringForm twitterForm = (TwitterAuthoringForm)form;

	    	Long uuid = twitterForm.getDeleteFileUuid();
	    	if (uuid == null)
	    	{
	    	    String error = "Unable to continue. The file uuid is missing.";
				logger.error(error);
				throw new TwitterApplicationException(error);
	    	}
	    	
	    	// move the file's details from the attachment collection to the deleted attachments collection
	    	// the attachment will be delete on saving.
		    SessionMap map = getSessionMap(request, twitterForm);
			List attachmentList = (List) map.get(TwitterConstants.ATTACHMENT_LIST);
	    	List deletedAttachmentList = (List) map.get(TwitterConstants.DELETED_ATTACHMENT_LIST);
	    	deletedAttachmentList = moveToDelete(uuid, attachmentList, deletedAttachmentList );
	    	
	    	twitterForm.setMethod(TwitterConstants.INSTRUCTIONS);
		
		   	return mapping.findForward(TwitterConstants.AUTHOR_PAGE);
		}
		

		/**
		 * It is assumed that the contentId is passed as a http parameter
		 * if the contentId is null, an exception is thrown, otherwise proceed as normal
		 * 
		 * @param contentId the <code>toolContentId</code> to check
		 */
		private void checkContentId(Long contentId)
		{
		    if (contentId == null)
			{
				String error = "Unable to continue. Tool content id missing.";
				
				throw new TwitterApplicationException(error);
			}
		}
		
		/**
		 * Retrieve the SessionMap from the HttpSession.
		 * 
		 * @param request
		 * @param authForm
		 * @return
		 */
		private SessionMap getSessionMap(HttpServletRequest request, TwitterAuthoringForm twitterForm) {
			return (SessionMap) request.getSession().getAttribute(twitterForm.getSessionMapID());
		}
		
		private String parseTags(String s){
		    
		    Boolean b = false;
			ArrayList arrayList = new ArrayList();
			String t = s.trim();
			
			String[] hashtags = t.split(",");
			
			for(int i = 0; i < hashtags.length; i++){
			    b = false;
			    hashtags[i] = hashtags[i].trim();
			    
			    for(int j = 0; j < arrayList.size(); j++){
				if(hashtags[i].equals(arrayList.get(j).toString())){
				    b = true;
				    break;
				}
			    }
			    if(!b){
				arrayList.add(hashtags[i]);
			    }
			}
			
			t = "";
			
			for(int k = 0; k < arrayList.size(); k++){
			    if(k == 0){
				t += arrayList.get(k).toString();
			    }
			    else{
				t += "," + arrayList.get(k).toString();
			    }
			}
			
			return t;
		    
		}
		
		/**
		 * This method copies the values of the request parameters <code>richTextOnlineInstructions</code>
		 * <code>richTextOfflineInstructions</code> <code>richTextContent</code> into the form properties
		 * onlineInstructions, offlineInstructions and content respectively.
		 * 
		 * @param request HttpServlet request
		 * @param form The ActionForm class containing data submitted by the forms.
		 */
	/*	private void copyAuthoringFormValuesIntoFormBean(HttpServletRequest request, TwitterAuthoringForm form)
		{
		    String onlineInstruction = WebUtil.readStrParam(request, TwitterConstants.RICH_TEXT_ONLINE_INSTRN, true);
		    String offlineInstruction = WebUtil.readStrParam(request, TwitterConstants.RICH_TEXT_OFFLINE_INSTRN, true);
		  	String content = WebUtil.readStrParam(request, TwitterConstants.RICH_TEXT_CONTENT, true);
		  	String title = WebUtil.readStrParam(request, TwitterConstants.RICH_TEXT_TITLE, true);

		  	
		  	    form.setTitle(title);
		  	
		  	    form.setContent(content);
		  	
		        form.setOnlineInstructions(onlineInstruction);
		  	
		  	    form.setOfflineInstructions(offlineInstruction);
		   
		}  */
		
	/*	private void copyFormValuesIntoTwitterContent(HttpServletRequest request, TwitterContent twitterContent)
		{
		    twitterContent.setTitle((String)request.getParameter(TwitterConstants.RICH_TEXT_TITLE));
		    twitterContent.setContent((String)request.getParameter(TwitterConstants.RICH_TEXT_CONTENT));
		    twitterContent.setOnlineInstructions((String)request.getParameter(TwitterConstants.RICH_TEXT_ONLINE_INSTRN));
		    twitterContent.setOfflineInstructions((String)request.getParameter(TwitterConstants.RICH_TEXT_OFFLINE_INSTRN));
		    
		} */
		
		public static String getRandomString(int length){
		    
		    String charset = "!0123456789abcdefghijklmnopqrstuvwxyz";
		    
		    Random rand = new Random(System.currentTimeMillis());
		    StringBuffer sb = new StringBuffer();
		    for (int i = 0; i < length; i++) {
			int pos = rand.nextInt(charset.length());
			sb.append(charset.charAt(pos));
		    }
		    return sb.toString();
		}
		
}	
	
