Monday, January 19, 2015

Vaadin app


package net.mycom.vaadin;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

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

import net.mycom.myapp.domain.Account;
import net.mycom.myapp.misc.myappProperties;
import net.mycom.myapp.util.HibernateUtil;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.vaadin.Application;
import com.vaadin.terminal.gwt.server.HttpServletRequestListener;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.RichTextArea;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;
import com.vaadin.ui.Window.CloseEvent;

public class mycomVaadinApplication extends Application implememycom HttpServletRequestListener {
 private static final long serialVersionUID = 1L;
 private static final String ERR_NITEFLIRT = "err_niteflirt";
 private static final String ERR_SCRIPT = "err_script";
 private static final String ERR_NONE = "err_none";
 private static final String ERR_NOACCOUNTID = "err_noAccountId";
 private static final String ERR_MAXSIZE = "err_maxsize";
 private static final String ERR_UNKNOWN = "err_unknown";
 private static ThreadLocal threadLocal = new ThreadLocal();
 public static Logger logger = Logger.getRootLogger();
 private static Integer dbProfilePageHtmlSize;
 Long accountId=0L;
 private transient HttpServletResponse response;
 private transient HttpServletRequest request;
 @Override
 public void init() {
  if (accountId == null || accountId == 0L) {
   try {
    String req = request.getRequestURI();
    response.sendRedirect(req.substring(0, req.indexOf("/VAADIN")) + "/home");
   } catch (IOException io) {
    
   }
   return;
  }
  String req = request.getRequestURL().toString();
  req = req.substring(0, req.indexOf("/VAADIN"));
    
  Window mainWindow = new Window("My Profile " + accountId);
  final RichTextArea ta = new RichTextArea();
  ta.setHeight("500");
  ta.setWidth("800");
  ta.setValue(getTextAreaContent());
  VerticalLayout layout=new VerticalLayout();
  Button saveButton = new Button();
  saveButton.addListener(new ClickListener() { 
   @Override
   public void buttonClick(ClickEvent event) {
    switch(saveTextAreaContent((String)ta.getValue())) {
    case ERR_NONE:
     logger.info("saving rich text area content=" + ta.getValue());
     getMainWindow().showNotification("Content saved");
     break;
    case ERR_SCRIPT:
     getMainWindow().showNotification("Not Saved. Cannot use script or javascript tags");
     break;
    case ERR_NITEFLIRT:
     getMainWindow().showNotification("Not Saved. Cannot use NITEFLIRT");
     break;
    case ERR_MAXSIZE:
     getMainWindow().showNotification("Not Saved. Content size exceeded maximum size. Reduce and try again");
     break;
    case ERR_UNKNOWN:
     getMainWindow().showNotification("Not Saved. Unknown error; please contact system administrator");
     break;
    default:
     getMainWindow().showNotification("Not Saved. No account Id...could not save");
    }
   } 
          });
  saveButton.setStyleName("vaadinButton");
  layout.addComponent(ta);
  layout.addComponent(saveButton);
  mainWindow.addComponent(layout);
  // Close the application if the main window is closed.
  mainWindow.addListener(new Window.CloseListener(){
     @Override
      public void windowClose(CloseEvent e) {
         logger.info("Closing the application");
         close();
      } 
  });
  setMainWindow(mainWindow);
 }
  @Override     
   public void onRequestStart(HttpServletRequest request, HttpServletResponse response) {
   accountId = (Long) request.getSession().getAttribute("accountId");
   this.response = response;
   this.request = request;
      mycomVaadinApplication.setInstance(this);   
   }  
  @Override     
   public void onRequestEnd(HttpServletRequest request, HttpServletResponse response) {
     threadLocal.remove();     
   } 
  // Set the current application instance  
   public static void setInstance(mycomVaadinApplication application) {      
       threadLocal.set(application);   
   }
   // @return the current application instance    
   public static mycomVaadinApplication getInstance() {   
     return threadLocal.get();  
   } 
   
   private String getTextAreaContent() {
     if ((Long)request.getSession().getAttribute("accountId") == null) {
    logger.info("no account id");
    return null;
   }
   logger.info("Retrieving html for accountId=" + (Long)request.getSession().getAttribute("accountId"));
   Session session = HibernateUtil.getCurremycomession();
   Account myAcc = (Account)session.get(Account.class, (Long)request.getSession().getAttribute("accountId"));
   session.close();
   
   return myAcc.getProfilePageHtml() == null ? "" : myAcc.getProfilePageHtml();
   }
   private String saveTextAreaContent(String html) {
     if ((Long)request.getSession().getAttribute("accountId") == null) {
    logger.info("no account id");
    return ERR_NOACCOUNTID;
   }
     try {
      if (!StringUtils.isEmpty(html) && html.length() > getDbProfilePageHtmlSize()) {
       logger.info("profile page too large");
       return ERR_MAXSIZE;
      }
     } catch (Exception e) {
      logger.error("max size property", e);
      return ERR_UNKNOWN;
     }
     String htmlNoWhiteSpaces = StringUtils.deleteWhitespace(html);
     if (htmlNoWhiteSpaces.toLowerCase().indexOf("javascript") > -1 || 
       htmlNoWhiteSpaces.toLowerCase().indexOf(" -1 || 
       htmlNoWhiteSpaces.toLowerCase().indexOf("/script") > -1) {
      logger.info("validation failed; found script tag");
      return ERR_SCRIPT;
     }
     if (htmlNoWhiteSpaces.toLowerCase().indexOf("niteflirt") > -1) {
      logger.info("validation failed; found niteflirt");
      return ERR_NITEFLIRT;
     }
     logger.info("saving -->" + html);
   Session session = HibernateUtil.getCurremycomession();
   Account myAcc = (Account)session.get(Account.class, (Long)request.getSession().getAttribute("accountId"));
   myAcc.setProfilePageHtml(html);
   Transaction tran = session.beginTransaction();
   session.saveOrUpdate(myAcc);
   tran.commit();
   session.close();
   return ERR_NONE;
   }
   public Integer getDbProfilePageHtmlSize () throws Exception {
     if (dbProfilePageHtmlSize == null) {
      dbProfilePageHtmlSize = retrieveDbProfilePageHtmlSize();
     }
      return dbProfilePageHtmlSize;
     
  }
   private synchronized Integer retrieveDbProfilePageHtmlSize()  {
    return 10000;
    /*
     Connection connection = null;
         int size =0;
         ResultSet rs=null;
         Statement st=null;
      try {
          Class.forName( "com.mysql.jdbc.Driver");
          connection = DriverManager.getConnection("jdbc:mysql:" + myappProperties.myappConnectionUrl(), myappProperties.myappUsername(), myappProperties.myappPassword());
          st = connection.createStatement();
          String sql = "select * from ACCOUNT LIMIT 1";
          rs = st.executeQuery(sql);
          ResultSetMetaData metadata = rs.getMetaData();
          int colCount = metadata.getColumnCount();
          for(int i=0; i < colCount; i++) {
           String name = metadata.getColumnName(i + 1);
           size = metadata.getColumnDisplaySize(i+1);
           String type =metadata.getColumnTypeName(i+1); 
           logger.debug("Column name: [" + name + "]; type: [" + type
               + "]; size: [" + size + "]");
           if (!StringUtils.isEmpty(name) && name.trim().equalsIgnoreCase("profile_page_html"))
            return new Integer(size);
          }
      } catch (SQLException e) {
          logger.error("sqlexception ", e);
      } catch (ClassNotFoundException e) {
       logger.error("classnotfoundexception ", e);
      } catch (Exception e) {
       logger.error("exception", e);
      } finally {
       try{
        st.close();
        rs.close();
        connection.close();
       } catch (Exception e) {}
      }
      return new Integer(size);
      */
   }
}

No comments:

Post a Comment