Monday, January 19, 2015

FB Authentication


FB Authentication
•  User clicks on the FB button on home page
•  the user is redirected to https://graph.facebook.com/oauth/authorize with these parameters:

client_id FB App Id
type web_server
display Popup
redirect_uri /myServices/connectToFBCallback
response_type Token
auth_type Reauthenticate
state Test
scope Email

• Note that  is set up in the FB App at developers.facebook.com

• after the user logs successfully into FB, the callback URL (/myServices/connectToFBCallback) is invoked by FB we are interested in the 2 parameters that are passed into the callback URL.

1) code
2) state

•  if code is null or empty, we assume the user is not authorized by FB and send the user to registration

•  state should be same as the one we passed with the  URL https://graph.facebook.com/oauth/authorize 

•  if state is null or empty, we assume the user is not authorized by FB and send the user to  registration

• Note: if the callback URL is never invoked by FB, there is nothing that we can do
 to inform the user about the status of their login

• the next step is to get the access token

•  the URL is https://graph.facebook.com/oauth/access_token

• parameters:

client_id 
code 
type web_server
client_secret 

•  open the URL connection is https://graph.facebook.com/oauth/access_token using HTTPS protocol and read the input. We are interested in the access token that could be read in the input as access_token=xyz...

• Save the access token in the Database

• We then need to get the FB username of the user 

•  open HTTPS URL connection to https://graph.facebook.com/me

• with parameter

 access_token=

•  the response from FB is read into a Gson object 
•  the username and email are parsed and stored in the Gson object
•  we then look up the   Account table using the email of Gson object
1) if the account is found, we log the user in and we are done
2) if the account is not found, we send the user to registration

Logging in FB User

• We redirect the user to myWebsite/loginFB.action with the following parameters:

1) email (ex:abc@abc.com)
2) profilePic (ex: https://graph.facebook.com//picture)

• The loginFB method will store the profile pic in  Account.profile_pic.

• For example: https://graph.facebook.com/gandikotam/picture will  be the value stored in the Account.profile_pic for the FB user with username gandikotam

• To retrieve the image, the ProfilePicController needs to be modified to download the image using HTTPS protocol.

Sample mobile JSP


<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html>
<html>
 <head>
  <title><%= myappProperties.sitePageTitle() %> Action Menu</title>
  <s:head />
  <jsp:include page="/mobile/mobileScriptsAndStyles.jsp"></jsp:include>
  <style type="text/css">
   p img {
    max-width: 100%;
   }
  </style>
  
  <script type="text/javascript" src="js/mobile/scaleImage.js"></script>
  <script type="text/javascript">
   $("div[data-role='page']").live("pageshow", function(event, ui) {
    <s:if test="account.profilePic != null && account.profilePic != ''">
     scaleImage("profile/${account.accountId}/${account.profilePic}", "profilePicture2", 60, 60);
    </s:if>
    <s:elseif test="genderOfPhoneBookEntry == \"F\"">
     scaleImage("img/noImageFemale.png", "profilePicture2", 60, 60);
    </s:elseif>
    <s:else>
     scaleImage("img/noImageMale.png", "profilePicture2", 60, 60);
    </s:else>
   });
  </script>
 </head>

 <body>
  <div data-role="page" data-theme="c">
   <div data-role="content" style="background-color:#FFFFFF;">
    <!-- Menu button -->
    <div id="toggleButton" onclick="toggleMenu();" style="width: 26px; height: 26px; background: url(img/mobile/list.png) 0 0 no-repeat; cursor: pointer; float: left;"></div>
    <!-- Menu overlay -->
    <div id="menuClickOverlay">
     <%@ include file="/mobile/logo.jsp" %><br />
     
     <div data-role="content">
      <%@ include file="/mobile/popupCommon.jsp" %>
      <div id="agentProfile" style="width: 100%; min-width: 0px; line-height:auto; margin-top:0px;">
       ${account.profilePageHtml}
      </div>
     </div>
    </div>
    <!-- /Menu overlay -->
    <!-- Menu -->
    <%@ include file="/mobile/mobileMenu.jsp" %>
    <!-- /Menu -->
   </div>
   
   <jsp:include page="/mobile/navbar.jsp"></jsp:include>
  </div>
 </body>
</html>

mobileScriptsAndStyles.jsp
<%@page import="net.mycom.myapp.misc.myappProperties" %>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="format-detection" content="telephone=yes">

<link rel="apple-touch-icon-precomposed" href="img/mobile/apple-touch-icon.png" />
<link rel="apple-touch-startup-image" href="img/mobile/apple-touch-startup-image.png" />

<link rel="stylesheet" href="css/mobile/jquery.mobile-1.2.0.min.css" />
<link rel="stylesheet" href="css/mobile/jquery.mobile-1.1.0.c_mycom.css" />

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
 $(document).bind("mobileinit", function() {
  $.mobile.ajaxEnabled = false;
  $.mobile.hashListeningEnabled = false;
 });
</script>
<script type="text/javascript" src="js/mobile/jquery.mobile-1.2.0.min.js"></script>

<link href="css/style.css" rel="stylesheet" type="text/css" />
<link href="css/<%= myappProperties.siteTheme() %>.css" rel="stylesheet" type="text/css" />


<style type="text/css">
 /* Menu
  */
 .ui-btn-text,
 .ui-btn input, .ui-btn button,
 .ui-checkbox, .ui-radio,
 .ui-checkbox input, .ui-radio input,
 .ui-checkbox .ui-btn, .ui-radio .ui-btn,
 .ui-select .ui-btn select {
  z-index: 0;
 }
 
 /* Counters on menu */
 .ui-li-count {
  display: none;
 }
 /* /Menu
  */
  /* prevent zooming */
  .ui-select .ui-btn select{font-size: 50px;}
</style>

<jsp:include page="/analytics.jsp" />

Sample Ajax call using Jquery


function getNewAccountsHtml() {
 $.ajax({
     type: 'GET',
     cache: false,
     async: false,
     url: 'getXXX?hours=' + <%= Integer.parseInt(Properties.Hours())%>,
     data: $("#id").serialize(),
     success: function(data) {
      $("#newAccountsHtml").html(data.xyz); //the java method sets html.put("xyz", "value") and struts.xml has the action configured
      $("#newAccountsHtml").css("display", "block");
      $("#newAccountsUpdateTime").html(getCurrentTimestamp());
     },
     error: function(XMLHttpRequest, textStatus, errorThrown) {
         alert("Server Unavailable");
     },
     dataType: "json"
 });
}

Prestruts filter


import java.io.IOException;

import net.mycom.myapp.misc.myappProperties;

import org.apache.log4j.Logger;
import org.apache.log4j.MDC;
import org.apache.struts2.dispatcher.ng.filter.*;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class PreStrutsFilter  implememycom Filter {
 private static Logger logger = Logger.getLogger(PreStrutsFilter.class);
 
 Filter strutsFilter = new StrutsPrepareAndExecuteFilter();
 private String bypassStrutsExp;
 private String bypassStrutsExpMobile;
 private String bypassVaadin;
 private ServletContext ctx;

 @Override
    public void destroy() {
  strutsFilter.destroy();    
    }

 @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
  if(req instanceof HttpServletRequest){
   HttpServletRequest httpReq = (HttpServletRequest)req;
   String uri = httpReq.getRequestURI();
   
   String ctxRoot = this.ctx.getContextPath();
   uri = uri.replace(ctxRoot, "");
   
   if(!uri.matches(bypassStrutsExp) &&
      !uri.matches(bypassStrutsExpMobile) &&
      !uri.matches(bypassVaadin)
      ){
    
    // Browser cache images
    int dot = uri.lastIndexOf(".");
    if ((dot > 0) &&
        (uri.substring(dot).equalsIgnoreCase(".jpg") ||
         uri.substring(dot).equalsIgnoreCase(".jpeg") ||
         uri.substring(dot).equalsIgnoreCase(".gif") ||
         uri.substring(dot).equalsIgnoreCase(".png"))) {
     try {
      ((HttpServletResponse)res).setHeader("Cache-Control", "max-age=" + myappProperties.getCacheControlMaxAge());
     }
     catch (Exception e) {
      ((HttpServletResponse)res).setHeader("Cache-Control", "max-age=120");
      logger.error("Error retrieving cacheControlMaxAge", e);
     }
    }
    
    putMDC(httpReq); // Log user
    strutsFilter.doFilter(req, res, chain);
    MDC.clear(); // Remove from Mapped Diagnostic Context
   }
   else{
    chain.doFilter(req, res);
   }
  }
  else{
   chain.doFilter(req, res);
  }
    }

 @Override
    public void init(FilterConfig cfg) throws ServletException {
  strutsFilter.init(cfg);
  this.bypassStrutsExp = cfg.getInitParameter("struts_bypass_expression");
  this.bypassStrutsExpMobile = cfg.getInitParameter("struts_bypass_expression_mobile");
  this.bypassVaadin = cfg.getInitParameter("struts_bypass_vaadin");
  this.ctx = cfg.getServletContext();
    }
 
 private void putMDC(HttpServletRequest request) {
  Long accountId = (Long)request.getSession().getAttribute("accountId");
  String sessionId = request.getSession().getId();
  
  // If parameter exist put into Mapped Diagnostic Context
  if (accountId != null) { MDC.put("accountId", accountId); }
  if (sessionId != null) { MDC.put("sessionId", sessionId); }
 }
}

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);
      */
   }
}

Hibernateutil


import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateUtil {
 private static Logger logger = Logger.getRootLogger();
 
    private static SessionFactory sessionFactory;
    private static ServiceRegistry serviceRegistry;
 public static final String serviceUpdateUserName = "MYDOMAIN-SRVC";
 public static final String webUpdateUserName = "MYDOMAIN-WEB";
 public static final String customerServiceUpdateUserName = "MYDOMAIN-CS";
 public static final String batchUpdateUserName = "MYDOMAIN-BATCH";
 public static final ThreadLocal threadBoundSession = new ThreadLocal();
 
    public static void setConnectionParameters(String connectionUrl, String username, String password, String showSql) {
        logger.info("Hibernate connection: url=" + connectionUrl + " username=" + username);
        
  Configuration config = new Configuration();
  config.configure("hibernate_MYDOMAIN.cfg.xml");
  config.setProperty("hibernate.connection.url","jdbc:mysql:"+connectionUrl);
  config.setProperty("hibernate.connection.username",username);
  config.setProperty("hibernate.connection.password",password);
  config.setProperty("hibernate.show_sql", showSql);
  
  serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();  
  sessionFactory = config.buildSessionFactory(serviceRegistry);
  
        logger.info("Hibernate connection completed");
 }

    public static SessionFactory getSessionFactory() {
     return sessionFactory;
    }
    
    public static Session getCurreMYCOMession(){
     Session session = threadBoundSession.get();
     if(session == null || session.isOpen() == false){
      session = sessionFactory.openSession();
      threadBoundSession.set(session);
     }
     return session;
    }

 public static Session getCurreMYCOMessionIfNotNull() {
  return threadBoundSession.get();
 }
 
 public static void removeCurreMYCOMession(){
  threadBoundSession.remove();
 }

 public static void closeCurreMYCOMession(){
     Session session = threadBoundSession.get();
  if ((session != null) && session.isOpen())
   session.close();
 }
}

hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
 "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
 "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
 <session-factory>
  <!-- Database connection settings -->
  <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="connection.url">x</property>
  <property name="connection.username">x</property>
  <property name="connection.password">x</property>

  <!-- SQL dialect -->
  <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
  
  <!-- Enable Hibernate's automatic session context management -->
  <property name="current_session_context_class">thread</property>
  
  <!-- Second-level cache http://ehcache.org/documentation/integrations/hibernate -->
  <property name="hibernate.cache.use_second_level_cache">true</property>
  <property name="hibernate.cache.use_query_cache">true</property>
  <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
  <property name="hibernate.cache.provider_configuration_file_resource_path">ehcache.xml</property>
  
  
  <!-- Setup C3P0 pooling -->
  <property name="connection.provider_class">org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider</property>
  <property name="hibernate.c3p0.acquire_increment">1</property> <!-- Batched connection creates -->
  <property name="hibernate.c3p0.initialPoolSize">0</property>
  <property name="hibernate.c3p0.min_size">0</property>
  <property name="hibernate.c3p0.max_size">50</property>
  <property name="hibernate.c3p0.timeout">300</property> <!-- seconds a Connection can remain pooled but unused before being discarded -->

  <!-- Echo all executed SQL to stdout -->
  <property name="show_sql">true</property>

  <mapping resource="net/mycom/myapp/domain/SmsType.hbm.xml" />
  
 </session-factory>
</hibernate-configuration>

ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="ehcache.xsd"
         updateCheck="false" monitoring="autodetect"
         dynamicConfig="true">
 <!-- timeToIdleSeconds & timeToLiveSeconds are not used if eternal is true --> 
 <defaultCache
  maxElementsInMemory="10000"
        eternal="true"
        overflowToDisk="false"
        diskPersistent="false"
        memoryStoreEvictionPolicy="LRU"/>
 <cache name="net.mycom.myapp.domain.Parameter"
  maxElementsInMemory="200" 
  eternal="true"
  overflowToDisk="false" />    
 <cache name="org.hibernate.cache.spi.UpdateTimestampsCache"
  maxElementsInMemory="3000000" eternal="true" timeToIdleSeconds="0"
  timeToLiveSeconds="0" overflowToDisk="false" />
 <cache name="org.hibernate.cache.internal.StandardQueryCache"
  maxElementsInMemory="3000000" eternal="true" timeToIdleSeconds="0"
  timeToLiveSeconds="0" overflowToDisk="false" />
</ehcache>

ehcache.xsd
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" version="1.7">

    <xs:element name="ehcache">
        <xs:complexType>
            <xs:sequence>
                <xs:element maxOccurs="1" minOccurs="0" ref="diskStore"/>
                <xs:element maxOccurs="1" minOccurs="0" ref="transactionManagerLookup"/>
                <xs:element maxOccurs="1" minOccurs="0" ref="cacheManagerEventListenerFactory"/>
                <xs:element maxOccurs="unbounded" minOccurs="0" ref="cacheManagerPeerProviderFactory"/>
                <xs:element maxOccurs="unbounded" minOccurs="0" ref="cacheManagerPeerListenerFactory"/>
                <xs:element maxOccurs="1" minOccurs="0" ref="terracottaConfig"/>
                <xs:element maxOccurs= "1" minOccurs="0" ref="defaultCache"/>
                <xs:element maxOccurs="unbounded" minOccurs="0" ref="cache"/>
            </xs:sequence>
            <xs:attribute name="name" use="optional"/>
            <xs:attribute default="true" name="updateCheck" type="xs:boolean" use="optional"/>
            <xs:attribute default="autodetect" name="monitoring" type="monitoringType" use="optional"/>
            <xs:attribute default="true" name="dynamicConfig" type="xs:boolean" use="optional"/>
            <xs:attribute default="15" name="defaultTransactionTimeoutInSeconds" type="xs:integer" use="optional"/>
            <xs:attribute default="0" name="maxBytesLocalHeap" type="memoryUnitOrPercentage" use="optional"/>
            <xs:attribute default="0" name="maxBytesLocalOffHeap" type="memoryUnit" use="optional"/>
            <xs:attribute default="0" name="maxBytesLocalDisk" type="memoryUnit" use="optional"/>
        </xs:complexType>
    </xs:element>
    <xs:element name="diskStore">
        <xs:complexType>
            <xs:attribute name="path" use="optional"/>
        </xs:complexType>
    </xs:element>
     <xs:element name="transactionManagerLookup">
        <xs:complexType>
            <xs:attribute name="class" use="required"/>
            <xs:attribute name="properties" use="optional"/>
            <xs:attribute name="propertySeparator" use="optional"/>
        </xs:complexType>
    </xs:element>
    <xs:element name="cacheManagerEventListenerFactory">
        <xs:complexType>
            <xs:attribute name="class" use="required"/>
            <xs:attribute name="properties" use="optional"/>
            <xs:attribute name="propertySeparator" use="optional"/>
        </xs:complexType>
    </xs:element>
    <xs:element name="cacheManagerPeerProviderFactory">
        <xs:complexType>
            <xs:attribute name="class" use="required"/>
            <xs:attribute name="properties" use="optional"/>
            <xs:attribute name="propertySeparator" use="optional"/>
        </xs:complexType>
    </xs:element>
    <xs:element name="cacheManagerPeerListenerFactory">
        <xs:complexType>
            <xs:attribute name="class" use="required"/>
            <xs:attribute name="properties" use="optional"/>
            <xs:attribute name="propertySeparator" use="optional"/>
        </xs:complexType>
    </xs:element>
    <xs:element name="terracottaConfig">
        <xs:complexType>
            <xs:sequence>
                <xs:element maxOccurs="1" minOccurs="0" name="tc-config">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:any maxOccurs="unbounded" minOccurs="0" processContents="skip"/>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
            <xs:attribute default="localhost:9510" name="url" use="optional"/>
            <xs:attribute name="rejoin" type="xs:boolean" use="optional" default="false"/>
        </xs:complexType>
    </xs:element>
    <!-- add clone support for addition of cacheExceptionHandler. Important! -->
    <xs:element name="defaultCache">
        <xs:complexType>
            <xs:sequence>
                <xs:element minOccurs="0" maxOccurs="unbounded" ref="cacheEventListenerFactory"/>
                <xs:element minOccurs="0" maxOccurs="unbounded" ref="cacheExtensionFactory"/>
                <xs:element minOccurs="0" maxOccurs="unbounded" ref="cacheLoaderFactory"/>
                <xs:element minOccurs="0" maxOccurs="unbounded" ref="cacheDecoratorFactory"/>
                <xs:element minOccurs="0" maxOccurs="1" ref="bootstrapCacheLoaderFactory"/>
                <xs:element minOccurs="0" maxOccurs="1" ref="cacheExceptionHandlerFactory"/>
                <xs:element minOccurs="0" maxOccurs="1" ref="pinning"/>
                <xs:element minOccurs="0" maxOccurs="1" ref="terracotta"/>
                <xs:element minOccurs="0" maxOccurs="1" ref="cacheWriter"/>
                <xs:element minOccurs="0" maxOccurs="1" ref="copyStrategy"/>
                <xs:element minOccurs="0" maxOccurs="1" ref="elementValueComparator"/>
            </xs:sequence>
            <xs:attribute name="diskExpiryThreadIntervalSeconds" type="xs:integer" use="optional"/>
            <xs:attribute name="diskSpoolBufferSizeMB" type="xs:integer" use="optional"/>
            <xs:attribute name="diskPersistent" type="xs:boolean" use="optional"/>
            <xs:attribute name="diskAccessStripes" type="xs:integer" use="optional" default="1"/>
            <xs:attribute name="eternal" type="xs:boolean" use="required"/>
            <xs:attribute name="maxElementsInMemory" type="xs:integer" use="optional"/>
            <xs:attribute name="maxEntriesLocalHeap" type="xs:integer" use="optional"/>
            <xs:attribute name="clearOnFlush" type="xs:boolean" use="optional"/>
            <xs:attribute name="memoryStoreEvictionPolicy" type="xs:string" use="optional"/>
            <xs:attribute name="overflowToDisk" type="xs:boolean" use="required"/>
            <xs:attribute name="timeToIdleSeconds" type="xs:integer" use="optional"/>
            <xs:attribute name="timeToLiveSeconds" type="xs:integer" use="optional"/>
            <xs:attribute name="maxElementsOnDisk" type="xs:integer" use="optional"/>
            <xs:attribute name="maxEntriesLocalDisk" type="xs:integer" use="optional"/>
            <xs:attribute name="transactionalMode" type="transactionalMode" use="optional" default="off"/>
            <xs:attribute name="statistics" type="xs:boolean" use="optional" default="false"/>
            <xs:attribute name="copyOnRead" type="xs:boolean" use="optional" default="false"/>
            <xs:attribute name="copyOnWrite" type="xs:boolean" use="optional" default="false"/>
            <xs:attribute name="cacheLoaderTimeoutMillis" type="xs:integer" use="optional" default="0"/>
            <xs:attribute name="overflowToOffHeap" type="xs:boolean" use="optional" default="false"/>
            <xs:attribute name="maxMemoryOffHeap" type="xs:string" use="optional"/>
        </xs:complexType>
    </xs:element>
    <xs:element name="cache">
        <xs:complexType>
            <xs:sequence>
                <xs:element minOccurs="0" maxOccurs="unbounded" ref="cacheEventListenerFactory"/>
                <xs:element minOccurs="0" maxOccurs="unbounded" ref="cacheExtensionFactory"/>
                <xs:element minOccurs="0" maxOccurs="unbounded" ref="cacheLoaderFactory"/>
                <xs:element minOccurs="0" maxOccurs="unbounded" ref="cacheDecoratorFactory"/>
                <xs:element minOccurs="0" maxOccurs="1" ref="bootstrapCacheLoaderFactory"/>
                <xs:element minOccurs="0" maxOccurs="1" ref="cacheExceptionHandlerFactory"/>
                <xs:element minOccurs="0" maxOccurs="1" ref="pinning"/>
                <xs:element minOccurs="0" maxOccurs="1" ref="terracotta"/>
                <xs:element minOccurs="0" maxOccurs="1" ref="cacheWriter"/>
                <xs:element minOccurs="0" maxOccurs="1" ref="copyStrategy"/>
                <xs:element minOccurs="0" maxOccurs="1" ref="searchable"/>
                <xs:element minOccurs="0" maxOccurs="1" ref="elementValueComparator"/>
            </xs:sequence>
            <xs:attribute name="diskExpiryThreadIntervalSeconds" type="xs:integer" use="optional"/>
            <xs:attribute name="diskSpoolBufferSizeMB" type="xs:integer" use="optional"/>
            <xs:attribute name="diskPersistent" type="xs:boolean" use="optional"/>
            <xs:attribute name="diskAccessStripes" type="xs:integer" use="optional" default="1"/>
            <xs:attribute name="eternal" type="xs:boolean" use="required"/>
            <xs:attribute name="maxElementsInMemory" type="xs:integer" use="optional"/>
            <xs:attribute name="maxEntriesLocalHeap" type="xs:integer" use="optional"/>
            <xs:attribute name="memoryStoreEvictionPolicy" type="xs:string" use="optional"/>
            <xs:attribute name="clearOnFlush" type="xs:boolean" use="optional"/>
            <xs:attribute name="name" type="xs:string" use="required"/>
            <xs:attribute name="overflowToDisk" type="xs:boolean" use="required"/>
            <xs:attribute name="timeToIdleSeconds" type="xs:integer" use="optional"/>
            <xs:attribute name="timeToLiveSeconds" type="xs:integer" use="optional"/>
            <xs:attribute name="maxElementsOnDisk" type="xs:integer" use="optional"/>
            <xs:attribute name="maxEntriesLocalDisk" type="xs:integer" use="optional"/>
            <xs:attribute name="transactionalMode" type="transactionalMode" use="optional" default="off" />
            <xs:attribute name="statistics" type="xs:boolean" use="optional" default="false"/>
            <xs:attribute name="copyOnRead" type="xs:boolean" use="optional" default="false"/>
            <xs:attribute name="copyOnWrite" type="xs:boolean" use="optional" default="false"/>
            <xs:attribute name="logging" type="xs:boolean" use="optional" default="false"/>
            <xs:attribute name="cacheLoaderTimeoutMillis" type="xs:integer" use="optional" default="0"/>
            <xs:attribute name="overflowToOffHeap" type="xs:boolean" use="optional" default="false"/>
            <xs:attribute name="maxMemoryOffHeap" type="xs:string" use="optional"/>
            <xs:attribute default="0" name="maxBytesLocalHeap" type="memoryUnitOrPercentage" use="optional"/>
            <xs:attribute default="0" name="maxBytesLocalOffHeap" type="memoryUnitOrPercentage" use="optional"/>
            <xs:attribute default="0" name="maxBytesLocalDisk" type="memoryUnitOrPercentage" use="optional"/>
        </xs:complexType>
    </xs:element>
    <xs:element name="cacheEventListenerFactory">
        <xs:complexType>
            <xs:attribute name="class" use="required"/>
            <xs:attribute name="properties" use="optional"/>
            <xs:attribute name="propertySeparator" use="optional"/>
            <xs:attribute name="listenFor" use="optional" type="notificationScope" default="all"/>
        </xs:complexType>
    </xs:element>
    <xs:element name="bootstrapCacheLoaderFactory">
        <xs:complexType>
            <xs:attribute name="class" use="required"/>
            <xs:attribute name="properties" use="optional"/>
            <xs:attribute name="propertySeparator" use="optional"/>
        </xs:complexType>
    </xs:element>
    <xs:element name="cacheExtensionFactory">
        <xs:complexType>
            <xs:attribute name="class" use="required"/>
            <xs:attribute name="properties" use="optional"/>
            <xs:attribute name="propertySeparator" use="optional"/>
        </xs:complexType>
    </xs:element>
    <xs:element name="cacheExceptionHandlerFactory">
        <xs:complexType>
            <xs:attribute name="class" use="required"/>
            <xs:attribute name="properties" use="optional"/>
            <xs:attribute name="propertySeparator" use="optional"/>
        </xs:complexType>
    </xs:element>
    <xs:element name="cacheLoaderFactory">
        <xs:complexType>
            <xs:attribute name="class" use="required"/>
            <xs:attribute name="properties" use="optional"/>
            <xs:attribute name="propertySeparator" use="optional"/>
        </xs:complexType>
    </xs:element>
    <xs:element name="cacheDecoratorFactory">
        <xs:complexType>
            <xs:attribute name="class" use="required"/>
            <xs:attribute name="properties" use="optional"/>
            <xs:attribute name="propertySeparator" use="optional"/>
        </xs:complexType>
    </xs:element>
    <xs:element name="searchAttribute">
        <xs:complexType>
            <xs:attribute name="name" use="required" type="xs:string"/>
            <xs:attribute name="expression" type="xs:string"/>
            <xs:attribute name="class" type="xs:string"/>
            <xs:attribute name="properties" use="optional"/>
            <xs:attribute name="propertySeparator" use="optional"/>
        </xs:complexType>
    </xs:element>

    <xs:element name="searchable">
      <xs:complexType>
        <xs:sequence>
          <xs:element minOccurs="0" maxOccurs="unbounded" ref="searchAttribute"/>
        </xs:sequence>
        <xs:attribute name="keys" use="optional" type="xs:boolean" default="true"/>
        <xs:attribute name="values" use="optional" type="xs:boolean" default="true"/>
      </xs:complexType>
    </xs:element>

    <xs:element name="pinning">
        <xs:complexType>
            <xs:attribute name="store" use="required" type="pinningStoreType"/>
        </xs:complexType>
    </xs:element>

    <xs:element name="terracotta">
        <xs:complexType>
            <xs:sequence>
                <xs:element minOccurs="0" maxOccurs="1" ref="nonstop"/>
            </xs:sequence>
            <xs:attribute name="clustered" use="optional" type="xs:boolean" default="true"/>
            <xs:attribute name="valueMode" use="optional" type="terracottaCacheValueType" default="serialization"/>
            <xs:attribute name="coherentReads" use="optional" type="xs:boolean" default="true"/>
            <xs:attribute name="localKeyCache" use="optional" type="xs:boolean" default="false"/>
            <xs:attribute name="localKeyCacheSize" use="optional" type="xs:positiveInteger" default="300000"/>
            <xs:attribute name="orphanEviction" use="optional" type="xs:boolean" default="true"/>
            <xs:attribute name="orphanEvictionPeriod" use="optional" type="xs:positiveInteger" default="4"/>
            <xs:attribute name="copyOnRead" use="optional" type="xs:boolean" default="false"/>
            <xs:attribute name="coherent" use="optional" type="xs:boolean" default="false"/>
            <xs:attribute name="consistency" use="optional" type="consistencyType" default="eventual"/>
            <xs:attribute name="synchronousWrites" use="optional" type="xs:boolean" default="false"/>
            <xs:attribute name="storageStrategy" use="optional" type="storageStrategyType" default="DCV2"/>
            <xs:attribute name="concurrency" use="optional" type="xs:nonNegativeInteger" default="0"/>
            <xs:attribute name="localCacheEnabled" use="optional" type="xs:boolean" default="true"/>
        </xs:complexType>
    </xs:element>
    <xs:simpleType name="consistencyType">
        <xs:restriction base="xs:string">
            <xs:enumeration value="strong" />
            <xs:enumeration value="eventual" />
        </xs:restriction>
    </xs:simpleType>
    <xs:element name="nonstop">
        <xs:complexType>
            <xs:sequence>
                <xs:element minOccurs="0" maxOccurs="1" ref="timeoutBehavior"/>
            </xs:sequence>
            <xs:attribute name="enabled" use="optional" type="xs:boolean" default="true"/>
            <xs:attribute name="immediateTimeout" use="optional" type="xs:boolean" default="false"/>
            <xs:attribute name="timeoutMillis" use="optional" type="xs:positiveInteger" default="30000"/>
        </xs:complexType>
    </xs:element>
    <xs:element name="timeoutBehavior">
        <xs:complexType>
            <xs:attribute name="type" use="optional" type="timeoutBehaviorType" default="exception"/>
            <xs:attribute name="properties" use="optional" default=""/>
            <xs:attribute name="propertySeparator" use="optional" default=","/>
        </xs:complexType>
    </xs:element>
    <xs:simpleType name="timeoutBehaviorType">
        <xs:restriction base="xs:string">
            <xs:enumeration value="noop" />
            <xs:enumeration value="exception" />
            <xs:enumeration value="localReads" />
        </xs:restriction>
    </xs:simpleType>
    <xs:simpleType name="monitoringType">
        <xs:restriction base="xs:string">
            <xs:enumeration value="autodetect"/>
            <xs:enumeration value="on"/>
            <xs:enumeration value="off"/>
        </xs:restriction>
    </xs:simpleType>
    <xs:simpleType name="pinningStoreType">
        <xs:restriction base="xs:string">
            <xs:enumeration value="localHeap" />
            <xs:enumeration value="localMemory" />
            <xs:enumeration value="inCache" />
        </xs:restriction>
    </xs:simpleType>
    <xs:simpleType name="terracottaCacheValueType">
        <xs:restriction base="xs:string">
            <xs:enumeration value="serialization" />
            <xs:enumeration value="identity" />
        </xs:restriction>
    </xs:simpleType>
    <xs:simpleType name="storageStrategyType">
        <xs:restriction base="xs:string">
            <xs:enumeration value="classic" />
            <xs:enumeration value="DCV2" />
        </xs:restriction>
    </xs:simpleType>

    <xs:simpleType name="transactionalMode">
        <xs:restriction base="xs:string">
            <xs:enumeration value="off"/>
            <xs:enumeration value="xa_strict"/>
            <xs:enumeration value="xa"/>
            <xs:enumeration value="local"/>
        </xs:restriction>
    </xs:simpleType>

    <xs:element name="cacheWriter">
        <xs:complexType>
            <xs:sequence >
                <xs:element minOccurs="0" maxOccurs="1" ref="cacheWriterFactory"/>
            </xs:sequence>
            <xs:attribute name="writeMode" use="optional" type="writeModeType" default="write-through"/>
            <xs:attribute name="notifyListenersOnException" use="optional" type="xs:boolean" default="false"/>
            <xs:attribute name="minWriteDelay" use="optional" type="xs:nonNegativeInteger" default="1"/>
            <xs:attribute name="maxWriteDelay" use="optional" type="xs:nonNegativeInteger" default="1"/>
            <xs:attribute name="rateLimitPerSecond" use="optional" type="xs:nonNegativeInteger" default="0"/>
            <xs:attribute name="writeCoalescing" use="optional" type="xs:boolean" default="false"/>
            <xs:attribute name="writeBatching" use="optional" type="xs:boolean" default="false"/>
            <xs:attribute name="writeBatchSize" use="optional" type="xs:positiveInteger" default="1"/>
            <xs:attribute name="retryAttempts" use="optional" type="xs:nonNegativeInteger" default="0"/>
            <xs:attribute name="retryAttemptDelaySeconds" use="optional" type="xs:nonNegativeInteger" default="1"/>
            <xs:attribute name="writeBehindConcurrency" use="optional" type="xs:nonNegativeInteger" default="1"/>
            <xs:attribute name="writeBehindMaxQueueSize" use="optional" type="xs:nonNegativeInteger" default="0"/>
        </xs:complexType>
    </xs:element>
    <xs:simpleType name="writeModeType">
        <xs:restriction base="xs:string">
            <xs:enumeration value="write-through" />
            <xs:enumeration value="write-behind" />
        </xs:restriction>
    </xs:simpleType>
    <xs:element name="cacheWriterFactory">
        <xs:complexType>
            <xs:attribute name="class" use="required"/>
            <xs:attribute name="properties" use="optional"/>
            <xs:attribute name="propertySeparator" use="optional"/>
        </xs:complexType>
    </xs:element>

    <xs:element name="copyStrategy">
        <xs:complexType>
            <xs:attribute name="class" use="required" type="xs:string" />
        </xs:complexType>
    </xs:element>

    <xs:element name="elementValueComparator">
        <xs:complexType>
            <xs:attribute name="class" use="required" type="xs:string" />
        </xs:complexType>
    </xs:element>

    <xs:simpleType name="notificationScope">
        <xs:restriction base="xs:string">
            <xs:enumeration value="local"/>
            <xs:enumeration value="remote"/>
            <xs:enumeration value="all"/>
        </xs:restriction>
    </xs:simpleType>
    <xs:simpleType name="memoryUnit">
        <xs:restriction base="xs:token">
            <xs:pattern value="[0-9]+[bBkKmMgG]?"/>
        </xs:restriction>
    </xs:simpleType>
    <xs:simpleType name="memoryUnitOrPercentage">
        <xs:restriction base="xs:token">
            <xs:pattern value="([0-9]+[bBkKmMgG]?|100%|[0-9]{1,2}%)"/>
        </xs:restriction>
    </xs:simpleType>
</xs:schema>

Application Listener
package net.mycom.myapp.application.listener;

import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import net.mycom.myapp.misc.MycomCsProperties;
import net.mycom.myapp.util.HibernateUtil;

@WebListener
public class MycomApplicationListener implements ServletContextListener {
 public static Logger logger;
 private ServletContext ctx;

 public void contextInitialized(ServletContextEvent ctxEv) {
  PropertyConfigurator.configure("/Mycom/customerservice/log4j.properties");
  logger = Logger.getRootLogger();
        this.ctx = ctxEv.getServletContext();
  
        // Setup Mycom database
        try {
         net.mycom.myapp.util.HibernateUtil.setConnectionParameters(MycomCsProperties.MycomConnectionUrl(),
           MycomCsProperties.MycomUsername(),
           MycomCsProperties.MycomPassword(),
           MycomCsProperties.MycomShowSql());
         net.nts.cos.util.HibernateUtil.setConnectionParameters(MycomCsProperties.cosConnectionUrl(),
           MycomCsProperties.cosUsername(),
           MycomCsProperties.cosPassword(), 
           MycomCsProperties.MycomShowSql());
        } catch (Exception e) { logger.error("Failed to setup parameters",e); }
    }

 public void contextDestroyed(ServletContextEvent ctxEv) {
     net.mycom.myapp.util.HibernateUtil.getSessionFactory().close();
     net.mycom.cos.util.HibernateUtil.getSessionFactory().close();
     deregisterJdbcConnections();        
    }
 
 private void deregisterJdbcConnections() {
  // This manually de-registers JDBC driver, which prevents Tomcat 7 from
  // complaining about memory leaks wrto this class
  logger.info("Shutting down JDBC drivers");
  Enumeration drivers = DriverManager.getDrivers();
  while (drivers.hasMoreElements()) {
   Driver driver = drivers.nextElement();
   try {
    DriverManager.deregisterDriver(driver);
    logger.info(String.format("deregistering jdbc driver: %s",
      driver));
   } catch (SQLException e) {
    logger.warn(
      String.format("Error deregistering driver %s", driver),
      e);
   }
  }
 }

}

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>MyWebsite</display-name>
  <listener>
   <listener-class>net.mycom.myapp.application.listener.MycomApplicationListener</listener-class>
  </listener>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <filter>
    <filter-name>connectionFilter</filter-name>
    <filter-class>net.mycom.myapp.filter.HibernateSessionRequestFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>connectionFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <filter>
    <filter-name>preStruts2</filter-name>
    <filter-class>net.mycom.myapp.filter.PreStrutsFilter</filter-class>
    <init-param>
     <param-name>struts_bypass_expression</param-name>
     <param-value>^(/img/.*)$</param-value>
    </init-param>
    <init-param>
     <param-name>struts_bypass_expression_mobile</param-name>
     <param-value>^(/css/mobile/images/.*)$</param-value>
    </init-param>
   <init-param>
     <param-name>struts_bypass_vaadin</param-name>
     <param-value>^(/VAADIN/.*)$</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>preStruts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <context-param>
   <description>Vaadin production mode</description>
   <param-name>productionMode</param-name>
   <param-value>true</param-value>
  </context-param>
   <servlet>
  <servlet-name>Vaadin Application</servlet-name>
   <servlet-class>
     com.vaadin.terminal.gwt.server.ApplicationServlet
   </servlet-class>
   <init-param>
      <description>Vaadin application class to start</description>
      <param-name>application</param-name>
      <param-value>
        net.nts.vaadin.NtsVaadinApplication
      </param-value>
  </init-param>
 </servlet>
 
 <servlet-mapping>
 <servlet-name>Vaadin Application</servlet-name>
 <url-pattern>/VAADIN/*</url-pattern>
 </servlet-mapping>

  <distributable/>
    <error-page>
    <error-code>404</error-code>
    <location>/error.html</location>
  </error-page>
    <error-page>
    <exception-type>java.lang.Exception</exception-type>
    <location>/error.html</location>
  </error-page>
</web-app>

struts.xml sample for Struts2


<struts>

 <constant name="struts.multipart.saveDir" value="/mydomain/myapp/website/temp/"/> 
 
 <constant name="struts.devMode" value="false" />
 
 <constant name="struts.enable.SlashesInActionNames" value="true"/>
 <constant name="struts.mapper.alwaysSelectFullNamespace" value="false"/>
 <constant name="struts.action.extension" value="action,,mpg,mp3,gif,png,jpeg,jpg,bmp" />
 <constant name="struts.multipart.maxSize" value="10000000" />
 <!-- struts2 ssl plugin -->
 <constant name="struts2.sslplugin.httpPort" value="80"/>
 <constant name="struts2.sslplugin.httpsPort" value="443"/>
 <constant name="struts2.sslplugin.annotations" value="true"/>
 
 <package name="default" extends="struts-default">
  
  <interceptors>
   <interceptor name="clientTypeInterceptor" class="net.mydomain.myapp.interceptor.ClientTypeInterceptor"></interceptor>
   <interceptor name="ajaxInterceptor" class="net.mydomain.myapp.interceptor.AjaxInterceptor"></interceptor>
   <interceptor name="accessInterceptor" class="net.mydomain.myapp.misc.AccessInterceptor"></interceptor>
   <interceptor name="sslInterceptor"  class="net.mydomain.myapp.ssl.SSLInterceptor"/>
   
   
   <interceptor-stack name="myAjaxStack">
    <interceptor-ref name="ajaxInterceptor"/>
   </interceptor-stack>
   
   <interceptor-stack name="myDefaultStack">
    <!-- remove the following line to work with localhost -->
    <interceptor-ref name="sslInterceptor"/>
    <interceptor-ref name="clientTypeInterceptor">
     <param name="interceptorName">mobileClientInteceptor</param>              
    </interceptor-ref> 
    <interceptor-ref name="defaultStack"/> 
   </interceptor-stack>
   
   <!--  accessStack is same as myDefaultStack with  the accessInterceptor to be used by login methods -->
   <interceptor-stack name="accessStack">
    <!-- remove the following line to work with localhost -->
    <interceptor-ref name="accessInterceptor"/>
    <interceptor-ref name="sslInterceptor"/>
    <interceptor-ref name="clientTypeInterceptor">
     <param name="interceptorName">mobileClientInteceptor</param>              
    </interceptor-ref> 
    <interceptor-ref name="defaultStack"/> 
   </interceptor-stack>
     </interceptors>

  <default-interceptor-ref name="myDefaultStack"/> 
   
  <action name="clientEvent" class="net.mydomain.myapp.controller.EventController" method="clientEvent" >
   <interceptor-ref name="defaultStack"/>
   <result type="stream" name="success">
              <param name="contentType">text/plain</param>
              <param name="inputName">inputStream</param>
              <param name="contentDisposition">filename="response.txt"</param>              
            </result>
  </action>
</package>
<package name="json" namespace="/" extends="json-default">
          <action name="updateVoiceRate" 
        class="net.mydomain.myapp.controller.SettingsController" method="saveVoiceRate">
           <result type="json" name="success">
            <param name="root">jsonObject</param>
           </result>
          </action>


</package>