Saturday 29 June 2013

Primefaces JSF Spring Web Application

Create java web application using primefaces

      I have been working with some of the web ui templates that makes my life easier for quite some time. I have tried vaadin, GWT kit, groovy and grails, primefaces etc. I would recommend Primefaces as the best option to design your template and pages. It's light weight compared to all other libraries. It has almost all UI components you are looking for. In my opinion, its the best ui component framework that works well with JSF and spring applications. Now it can be integrated with ROO applications also. primeface comes with built-in themes. If you want to apply twitter-bootstrap which is the most widely used themes in coming websites. Just add the maven dependency and enable the appropriate theme in web.xml. Its that simple.

Have a look at the comparison http://www.primefaces.org/whyprimefaces.html

Now we will see how to create a simple jsf-spring-prmeface maven web application.

Frameworks used:
  Spring 3.1.2.RELEASE
  JSF
  Spring security  3.1.0.RELEASE
  Primefaces

1) Since its a maven application, first get the required dependencies.

You can see that I have added bootstrap theme to my web application.

2) Now get the jsf dependencies. Most javaee containers supports built-in support for jsf. I have been working with glassfish server for quite some time. It has built in support for jsf. If you are using glassfish, add the below dependency.


servlet containers like tomcat needs the below dependencies

3) Add spring dependencies

If you want spring security, add the below dependencies too

4) Copy and paste the below contents to web.xml


5) Sample template jsf file
Clean and build your project. That's it!!!.


Thursday 27 June 2013

Getting JDBC Connection from EntityManager ( EclipseLink )

when things gets too complex, your hibernate/eclipselink jpa implementations won't help. You may need to access the underlying JDBC connection. Logic to extract a JDBC connection from JTA environment and non-JTA environment is not the same.
If you are using JTA datasource managed by the container, then you can get the connection directly from the JavaEE container Datasource. Just inject or lookup the datasource from JNDI. As long as you are with in a JTA trasactional context, the JDBC connection will be the same connection used by JPA.
If you are using non-JTA datasource, then you can still access the datasource from the javaEE container if you want a new connection. If you want the same connection used by JPA, then you can get it from JPAEntityManager interface.


Getting JDBC connection from JTA Datasource:

  First take a look at persistence.xml
  

  Now inject the Datasource bean in your java file
  

Getting JDBC connection from NON-JTA Datasource:

  JPA 2.0

  JPA 1.0

Wednesday 26 June 2013

Log4j Configuration

Steps to configure log4j in maven web application


Step: 1


   Add the required dependencies in pom.xml
                 

Step: 2

   Add log4j.xml in your application root folder.
   If you are using any IDE put log4j.xml in "src/main/resources". After compilation, it will be copied to "WEB-INF/classes" folder. Copy and paste the following contents in log4j.xml


I am using glassfish as the underlying server that's why the log folder relative path is "com.sun.aas.instanceRoot". For other servers, get the log folder path and replace that line. We are using RollingFileAppender, that enables us to create log files based on rolling policy. In other words, based on the date stamp it rolls at that time, 
            default is yyyy-MM-dd, (rolls at midnight)
See:http://logging.apache.org/log4j/companions/extras/apidocs/org/apache/log4j/rolling/TimeBasedRollingPolicy.html
So, instead of single file, It generates log files on daily basis.


Step: 3


    Add Log4jConfigListener in web.xml
    

To debug your java files
   
That's it! Now build and run the project.

Saturday 22 June 2013

Spring RESOURCE_LOCAL and JTA configurations

Spring RESOURCE_LOCAL(Local Transactions) and JTA(Global Transactions) configurations

So often people tend to make many mistakes with RESOURCE_LOCAL and JTA configurations, Without knowing the actual usage of tags, developers often mix these two configuration related tags. By doing so, spring instantiate unwanted beans in memory. So, I thought this blow would helps to developers to fix or create a proper RESOURCE_LOCAL and JTA xml configurations. I will also explain how to create proper JTA production configuration. Yes, JTA can be configured in different ways. But for production, Its better to handle the connections by the application container itself. So before start creating these configurations one has to have a complete knowledge of the xml tags used in these configurations.I would suggest you to read and understand all the topics discussed in http://static.springsource.org/spring/docs/2.0.x/reference/transaction.html

Global Transactions. Global transactions have a significant downside, in that code needs to use JTA, and JTA is a cumbersome API to use (partly due to its exception model). Furthermore, a JTAUserTransaction normally needs to be sourced from JNDI: meaning that we need to use both JNDIand JTA to use JTA. Obviously all use of global transactions limits the reusability of application code, as JTA is normally only available in an application server environment. Previously, the preferred way to use global transactions was via EJB CMT (Container Managed Transaction): CMT is a form of declarative transaction management (as distinguished from programmatic transaction management). EJB CMT removes the need for transaction-related JNDI lookups - although of course the use of EJB itself necessitates the use of JNDI. It removes most of the need (although not entirely) to write Java code to control transactions. The significant downside is that CMT is tied to JTA and an application server environment. Also, it is only available if one chooses to implement business logic in EJBs, or at least behind a transactional EJB facade. The negatives around EJB in general are so great that this is not an attractive proposition, especially in the face of compelling alternatives for declarative transaction management.
Local Transactions. Local transactions may be easier to use, but have significant disadvantages: they cannot work across multiple transactional resources. For example, code that manages transactions using a JDBC connection cannot run within a global JTA transaction. Another downside is that local transactions tend to be invasive to the programming model.
Spring resolves these problems. It enables application developers to use a consistent programming model in any environment. You write your code once, and it can benefit from different transaction management strategies in different environments. The Spring Framework provides both declarative and programmatic transaction management. Declarative transaction management is preferred by most users, and is recommended in most cases.
With programmatic transaction management, developers work with the Spring Framework transaction abstraction, which can run over any underlying transaction infrastructure. With the preferred declarative model, developers typically write little or no code related to transaction management, and hence don't depend on the Spring Framework's transaction API (or indeed on any other transaction API).

We can use Hibernate/Eclipselink/Toplink,etc as the unerlying ORM technology, since I am familier with JPA 2 and its also the default implementation of glassfish I would always prefer to go with eclipselink for my web applications. Configured with Spring 3.1.2 release and mysql database and tested in glassfish 3.1.2.2 server.


Is an application server needed for transaction management?
The Spring Framework's transaction management support significantly changes traditional thinking as to when a J2EE application requires an application server.
In particular, you don't need an application server just to have declarative transactions via EJB. In fact, even if you have an application server with powerful JTA capabilities, you may well decide that the Spring Framework's declarative transactions offer more power and a much more productive programming model than EJB CMT.
Typically you need an application server's JTA capability only if you need to enlist multiple transactional resources, and for many applications being able to handle transactions across multiple resources isn't a requirement. For example, many high-end applications use a single, highly scalable database (such as Oracle 9i RAC). Standalone transaction managers such as Atomikos Transactions and JOTM are other options. (Of course you may need other application server capabilities such as JMS and JCA.)
The most important point is that with the Spring Framework you can choose when to scale your application up to a full-blown application server. Gone are the days when the only alternative to using EJB CMT or JTA was to write code using local transactions such as those on JDBC connections, and face a hefty rework if you ever needed that code to run within global, container-managed transactions. With the Spring Framework, only configuration needs to change so that your code doesn't have to.


Below you can see the JTA configuration with entityManagerFactory bean created from LocalContainerEntityManagerFactoryBean class


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
        xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
                http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd" default-autowire="byName">


<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="persistenceUnitName" value="xxxx"/>
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter" >
                <property name="showSql" value="false" />
                <property name="generateDdl" value="false" />
                <property name="databasePlatform" value="org.eclipse.persistence.platform.database.MySQLPlatform" />
            </bean>
        </property>
        <property name="loadTimeWeaver">
            <bean class="org.springframework.instrument.classloading.ReflectiveLoadTimeWeaver"/>
        </property>
    </bean>               
        
        <tx:annotation-driven /> 
        <tx:jta-transaction-manager/> 
        
<bean
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />


</beans>


JTA configuration with entityManagerFactory bean created from JNDI


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:jee="http://www.springframework.org/schema/jee"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
                http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd" default-autowire="byName">    
    
    <jee:jndi-lookup id="entityManagerFactory" jndi-name="jdbc/xxxx"/>
    <tx:annotation-driven /> 
    <tx:jta-transaction-manager/> 
        
    <bean
        class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
</beans>

If we are using jndi lookup in spring configuration file. Its necessary to place persistence-unit-ref in web.xml

web.xml
<persistence-unit-ref>
        <persistence-unit-ref-name>jdbc/xxxx</persistence-unit-ref-name>
        <persistence-unit-name>xxxx</persistence-unit-name>
    </persistence-unit-ref>

persistence.xml ( JTA )

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence       http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
  <persistence-unit name="xxxx" transaction-type="JTA">
    <jta-data-source>jdbc/xxxx</jta-data-source>
    <properties>
      <property name="eclipselink.jpa.uppercase-column-names" value="true"/>      
      <property name="eclipselink.cache.shared.default" value="false"/> 
      <property name="javax.persistence.lock.timeout" value="1000"/>     
      <property name="eclipselink.logging.level" value="SEVERE" />      
      <property name="eclipselink.target-server" value="SunAS9"/>
    </properties>
  </persistence-unit>
</persistence>


Below you can see the RESOURCE_LOCAL configuration with entityManagerFactory bean created from LocalContainerEntityManagerFactoryBean class

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd" default-autowire="byName">

    
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">        
        <property name="persistenceUnitName" value="xxxx"/>
        <property name="persistenceXmlLocation" value="classpath:META-INF/test-persistence.xml"/>
        <property name="jpaVendorAdapter" ref="jpaVendorAdapter"/>
        <property name="jpaDialect">
            <bean class="org.springframework.orm.jpa.vendor.EclipseLinkJpaDialect"/>
        </property>
        <property name="jpaPropertyMap">
            <props>
                <prop key="eclipselink.weaving">false</prop>
            </props>
        </property>

        <property name="loadTimeWeaver">
            <bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver">
            </bean>
        </property>        
    </bean>

    <bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter">
        <property name="databasePlatform" value="org.eclipse.persistence.platform.database.MySQLPlatform" />
        <property name="generateDdl" value="false"/>
        <property name="showSql" value="true"/>
    </bean>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${db.driver}" />
        <property name="url" value="${db.url}" />
        <property name="username" value="${db.username}" />
        <property name="password" value="${db.password}" />
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <tx:annotation-driven />

    <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

</beans>


persistence.xml ( RESOURCE_LOCAL )


<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
  <persistence-unit name="xxxx" transaction-type="RESOURCE_LOCAL">
    <class>xxxx</class>    
    <exclude-unlisted-classes>true</exclude-unlisted-classes>
    <properties/>
  </persistence-unit>
</persistence>

To create web applications I always use maven archetype that helps to automate the build process, dependency management, SCM, etc. If you find any difficulty in getting the required dependencies please use the below pom.xml file.
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <jetty.version>6.1.4</jetty.version>
        <spring.version>3.1.2.RELEASE</spring.version>
        <spring.security.version>3.1.0.RELEASE</spring.security.version>
        <slf4j.version>1.5.10</slf4j.version>
        <java.version>1.6</java.version>
        <junit.version>4.10</junit.version>
        <mysql.connector.version>5.1.16</mysql.connector.version>
        <netbeans.hint.deploy.server>gfv3ee6</netbeans.hint.deploy.server>
    </properties>

    <dependencies>
     
         <dependency>
            <groupId>org.glassfish.extras</groupId>
            <artifactId>glassfish-embedded-all</artifactId>
            <version>3.2-b06</version>
            <scope>provided</scope>
        </dependency>  
               
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-core-asl</artifactId>
            <version>0.9.8</version>
        </dependency>  
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.primefaces</groupId>
            <artifactId>primefaces</artifactId>
            <version>3.5</version>
        </dependency>
        <dependency>
            <groupId>org.primefaces.themes</groupId>
            <artifactId>all-themes</artifactId>
            <version>1.0.9</version>
        </dependency>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.2.2</version>
        </dependency>


        <!-- Spring Dependencies -->

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
            <exclusions>
                <!-- Exclude Commons Logging in favor of SLF4j -->
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
            <type>jar</type>
            <scope>test</scope>
        </dependency>

        <!-- spring security -->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>${spring.security.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>${spring.security.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>${spring.security.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- DB Dependencies -->
        <!-- MySQL Connector -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.connector.version}</version>
            <type>jar</type>
            <scope>provided</scope>
        </dependency>
        <!-- Test Dependencies -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jettison</groupId>
            <artifactId>jettison</artifactId>
            <version>1.3.3</version>
        </dependency>
       
        <!-- logging -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>${slf4j.version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${slf4j.version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
            <exclusions>
                <exclusion>
                    <groupId>com.sun.jdmk</groupId>
                    <artifactId>jmxtools</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.sun.jmx</groupId>
                    <artifactId>jmxri</artifactId>
                </exclusion>
            </exclusions>
            <scope>compile</scope>
        </dependency>
<dependency>
            <groupId>log4j</groupId>
            <artifactId>apache-log4j-extras</artifactId>
            <version>1.1</version>
        </dependency>

    </dependencies>


I would recommend JTA configuration for production environment and RESOURCE_LOCAL for unit testing. With RESOURCE_LOCAL we have to take care of connection pooling and any change in connection pooling needs an application redepolyment. But with JTA, your application server provides connection pooling, transaction management and at run time we can change the connection pool settings without the need for application redeployment.

Friday 14 June 2013

Push Notification

Push notifications to IOS devices

JavaPNS, so far the best library available in java. I have been using this in one of my projects and we have been so successful with that. I have a service that runs for every 20 min and reads around 400k records from mysql and iterates over and over and send pushes in batches.
Before you integrate this library, I suggest you to take a look at apple push notification docs. Its very important to understand the underlying behavior of notifications.


In particular, You should know what happen if you send a push notification to an erroneous push token(ie, push token that doesn't exist ) and how push token errors are handled in these libraries 



Example to send pushes using multithreads

numberOfThreads = Enable multithreading and allows us to send large number of push notifications concurrently


Apple doc says that its possible to send 9000 pushes/sec. JavaPNS  library has the ability to send large number of pushes at a time using thread mechanism. But to achieve somewhere closer to that count, It takes more than the brilliance of this library. Its up to the developer, If you would have read the above links, you can clearly get a picture of what I am taking about. Its about push token error handling logic.

There are two types of error handling in push notifications.
a) Handling erroneous push tokens(tokens that doesn't exist, ie, If user uninstall an app, token mapped to that app deosn't exist anymore, its invalid )
b) Retry and send rest of the notifications after a failure because of invalid push tokens.

Type(b) is already handled in javapns library, it has an exceptional way of handling errors. Now, the developer job is to handle type(a) properly.

To handle type(b), As a developer, when you are sending a bulk of push notifications, ignore all invalid push tokens and push everything in to a List
Next, Implement Feedback service. Its must, run feedback service on daily basis and remove invalid push tokens from your database to prevent sending pushes to invalid tokens.

Download JavaPNS library https://code.google.com/p/javapns/



Push notifications to Android devices

Server side implementation to send push notification to android devices

Add the below dependency in pom.xml



Spring annotation problem and fixes

Spring annotation problems and fixes

Multiple bean instances ( duplicate instances )

I have been dealing with spring and glassfish for almost 3 years. I have encountered many problems with bean xml declarations. Latest spring release supports annotations in java level and eliminated the need of xml declarations. But for some declarations like jpa repository, you still need the xml declarations. I feel that this blog will really help for people those who are struggling with duplicate bean instantiation problem because of improper tag definitions.

Spring offers <context:component-scan> tag to scan your source files and instantiate beans. 
We usually place this tag in your applicationContext.xml file.

    <context:component-scan base-package="com.xxxxxx" />

If you are using spring controller, placing this tag in applicationContext.xml is not just enough.
You have to put the same tag in your dispatcher-servlet.xml file to instantiate your spring controllers and map RequestMap annotations.

    <context:component-scan base-package="com.xxxxxx" /> 

Now, you have same tag definitions in applicationContext.xml and dispatcher-servlet.xml.
When spring scans these two files, it will instantiate the beans twice.

To avoid this problem. Use the below tag in applicationContext.xml

    <context:component-scan base-package="com.xxxxxx" >
        <context:exclude-filter expression="org.springframework.stereotype.Controller"
                                type="annotation"/>
    </context:component-scan>


In dispatcher-servlet.xml

   <context:component-scan base-package="com.xxxx" use-default-filters="false">
        <context:include-filter expression="org.springframework.stereotype.Controller" 
                                type="annotation"/>
    </context:component-scan>

  

Thursday 13 June 2013

Glassfish Open Source Edition

Glassfish Open Source installation step by step procedure

Create User Account

  #Create new user     
sudo adduser --home /home/glassfish --system --shell /bin/bash glassfish

#Create new user group      
sudo groupadd glassfishadmin

#Assign glassfish user to glassfishadmin group    
sudo usermod -a -G glassfishadmin glassfish


Configure Java


#Remove openjdk if installed
sudo apt-get remove openjdk-6-jre openjdk-6-jdk

#Remove sun's jdk if installed

sudo apt-get remove sun-java6-jdk  sun-java6-jre

#Remove unwanted automatically installed packages
sudo apt-get autoremove

sudo apt-get autoclean

#Extract jdk 7 tar file
tar -xvf jdk-7u7-linux-x64.tar.gz

#Remove previous jdk 7 installations
rm -rf /usr/lib/jvm/jdk1.7

#If jvm folder doesn't exist, create a new one
sudo mkdir /usr/lib/jvm

#Move extracted files
sudo mv ./jdk1.7 /usr/lib/jvm/jdk1.7
sudo chgrp -R root /usr/lib/jvm/jdk1.7

sudo chown -R root /usr/lib/jvm/jdk1.7

#Update alternatives
sudo update-alternatives --install "/usr/bin/java" "java" "/usr/lib/jvm/jdk1.7/bin/java" 1
sudo update-alternatives --install "/usr/bin/javac" "javac" "/usr/lib/jvm/jdk1.7/bin/javac" 1
sudo update-alternatives --install "/usr/bin/javaws" "javaws" "/usr/lib/jvm/jdk1.7/bin/javaws" 1

sudo update-alternatives --config java

#Check jdk installation
cd /etc/alternatives

ls -lrt java*

#Setting environment variables JAVA_HOMEfor all users(only for bash)
sudo nano /etc/bash.bashrc
#append the following lines:
export GLASSFISH_HOME=/home/glassfish
export JAVA_HOME=/usr/lib/jvm/jdk1.7

export PATH=$PATH:$JAVA_HOME/bin:$GLASSFISH_HOME/bin

#Setting JAVA_HOME and AS_JAVA for everyone
sudo nano /etc/environment
#append the following lines:
JAVA_HOME=/usr/lib/jvm/jdk1.7

AS_JAVA=/usr/lib/jvm/jdk1.7

#Finally check the installation in /etc/alternatives directoy

cd /etc/alternatives

ls -lrt java*

Glassfish installation


#switch over to glassfish user account
sudo su glassfish

#Change to home directory of glassfish
cd /home/glassfish/

#Create downloads directory 
mkdir downloads

#Go to downloads directory
cd /home/glassfish/downloads/

#Download and install glassfish 3.1.2
unzip glassfish-3.1.2.zip

#Move extracted contents to glassfish home directory
mv /home/glassfish/downloads/glassfish3.1.2/* /home/glassfish/

#Exit from glassfish user
exit


#change group of glassfish home directory to glassfishadmin

sudo chgrp -R glassfishadmin /home/glassfish


#change owner of glassfish home directory to glassfish

sudo chown -R glassfish /home/glassfish
#make sure the files are executable/modifyable/readable for owner and group

sudo chmod -R ug+rwx /home/glassfish/bin/
sudo chmod -R ug+rwx /home/glassfish/glassfish/bin/
#others are not allowed to execute/modify/read them
sudo chmod -R o-rwx /home/glassfish/bin/
sudo chmod -R o-rwx /home/glassfish/glassfish/bin/

#Now you can start and stop glassfish
#Switch over to glassfish user
sudo su glassfish

#Start glassfish
/home/glassfish/bin/asadmin start-domain domain1

#Stop glassfish
/home/glassfish/bin/asadmin stop-domain domain1

#Exit
exit

Configure glassfish init script


#Now you need an init script to automatically start glassfish on system reboot.

#Create init script
sudo nano /etc/init.d/glassfish


#(paste the lines below into the file and save it)


#! /bin/sh


export AS_JAVA=/usr/lib/jvm/jdk1.7
GLASSFISHPATH=/home/glassfish/bin
case "$1" in
start)
echo "starting glassfish from $GLASSFISHPATH"
sudo -u glassfish $GLASSFISHPATH/asadmin start-domain domain1
;;
restart)
$0 stop
$0 start
;;
stop)
echo "stopping glassfish from $GLASSFISHPATH"
sudo -u glassfish $GLASSFISHPATH/asadmin stop-domain domain1
;;
*)
echo $"usage: $0 {start|stop|restart}"
exit 3
;;
esac
:

#To start this init script automatically issue the following commands
#Make the init script executable
sudo chmod a+x /etc/init.d/glassfish

#configure Glassfish for autostart on linux boot
sudo update-rc.d glassfish defaults

#if apache2 is installed, remove that from startup
#stopping apache2
sudo /etc/init.d/apache2 stop
#removing apache2 from autostart
update-rc.d -f apache2 remove

#Now we can start glassfish easily be the following commands
#start
/etc/init.d/glassfish start
#stop
/etc/init.d/glassfish stop
#restart
/etc/init.d/glassfish restart