Vivek

Wednesday 7 May 2014

Error creating bean with name 'centralAuthenticationService' While Configuring CAS for SSO functionality in Tomcat server.


 I got Error : creating bean with name 'centralAuthenticationService' , While Configuring CAS for SSO functionality.


SafeContextLoaderListener:
The Spring ContextLoaderListener we wrap threw on contextInitialized.
But for our having caught this error, the web application context would not have initialized.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'centralAuthenticationService' defined in ServletContext resource [/WEB-INF/spring-configuration/applicationContext.xml]: Cannot resolve reference to bean 'authenticationManager' while setting bean property 'authenticationManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'authenticationManager' defined in ServletContext resource [/WEB-INF/deployerConfigContext.xml]: Cannot create inner bean 'org.jasig.cas.adaptors.jdbc.SearchModeSearchDatabaseAuthenticationHandler#1453d72' of type [org.jasig.cas.adaptors.jdbc.SearchModeSearchDatabaseAuthenticationHandler] while setting bean property 'authenticationHandlers' with key [1]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.jasig.cas.adaptors.jdbc.SearchModeSearchDatabaseAuthenticationHandler#1453d72' defined in ServletContext resource [/WEB-INF/deployerConfigContext.xml]: Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.apache.commons.dbcp.BasicDataSource] for bean with name 'dataSource' defined in ServletContext resource [/WEB-INF/deployerConfigContext.xml]; nested exception is java.lang.ClassNotFoundException: org.apache.commons.dbcp.BasicDataSource
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328)
.
.
.
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.jasig.cas.adaptors.jdbc.SearchModeSearchDatabaseAuthenticationHandler#1453d72' defined in ServletContext resource [/WEB-INF/deployerConfigContext.xml]: Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.apache.commons.dbcp.BasicDataSource] for bean with name 'dataSource' defined in ServletContext resource [/WEB-INF/deployerConfigContext.xml]; nested exception is java.lang.ClassNotFoundException: org.apache.commons.dbcp.BasicDataSource


Basically, If you are getting this error, reason is, you are missing some jars in your CAS server application's WEB-INF/lib/  directory related to creation of DataSource and ConnectionPooling.

Step 1.
Please collect below jars:
1. commons-collections-3.2.1.jar
2. commons-dbcp-1.4.jar
3. commons-pool-1.5.4.jar

Or similar version of Jars as per the CAS server.
While writing this, I have used:
where my cas server environment is: cas-server-3.5.2, Tomcat 7.x, Java 1.7 and Maven 2.1

Step 2.
Now Copy above jars to your CAS server's deployed location (e.g.  apache-tomcat-7.0.27/webapps/cas/WEB-INF/lib).

Step 3.
Before starting the tomcat, delete the  work and log folder inside the tomcat.

Step 4.

Test your application and check the logs, you should not get mentioned errors above. It should have been solved.

Wednesday 13 November 2013

Create the Simple XMl based mapping Hibernate Application in Eclipse IDE

Simple basic step to  create a simple XML based example of hibernate application using eclipse IDE. For creating the hibernate application in Eclipse IDE, we need to follow following steps:
  1. Create the java project
  2. Add jar files for hibernate
  3. Create the Persistent class
  4. Create the mapping file for Persistent class
  5. Create the Configuration file
  6. Create the class that retrieves or stores the persistent object
  7. Run the application

Step-1 Create the java project.

Create the java project by File Menu - New - project - java project . Now specify the project name e.g. DemoHb then next finish .

Step-2 Add jar files in your class path for hibernate.

To add the jar files Right click on your project - Build path - Add external archives. and  select  all the jar files as shown in the image given below then click ok button .

     you can download library from given link..


Step-3 Create the Persistent class

To create the persistent class, Right click on src - New - Class - specify the class with package name (e.g. com.demo.vivekdemo) click finish button.

Employee.java


package com.demo.vivekdemo;
public class Employee{  
        private int id;  
       private String firstName, lastName; 
                 public int getId() {
                       return id;  
                  }
                 public void setId(int id) {
                       this.id = id;
                 }
                 public String getFirstName() {
                      return firstName;
                }
                public void setFirstName(String firstName) {
                     this.firstName = firstName;
                }
                public String getLastName() {
                     return lastName;
               }
               public void setLastName(String lastName) {
                    this.lastName = lastName;
               }
   }  

Step-4 Create the mapping (XML) file for Persistent class

Create the mapping file, Right click on src - new - file - specify the file name (e.g. employee.hbm.xml) click ok. It must be outside the package.

employee.hbm.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC  "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

 <hibernate-mapping>
  <class name="com.javatpoint.mypackage.Employee" table="emp1000">
    <id name="id">
           <generator class="assigned"></generator>
    </id>
         
    <property name="firstName"></property>
    <property name="lastName"></property>
         
  </class>
         
 </hibernate-mapping> 


Step-5 Create the Configuration file(it is like mysql-ds.xml file for normal JDBC connection )

The configuration file contains all the information for the datbase such as connection_url,  driver_class, username, password etc. The hbm2ddl.auto property is used to create the table in the database automatically. To create the configuration file, right click on src - new - file. Now specify the configuration file name (e.g. hibernate.cfg.xml) click ok button.

hibernate.cfg.xml

 <?xml version='1.0' encoding='UTF-8'?>  <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  
 <hibernate-configuration>
  <session-factory>
  <property name="hbm2ddl.auto">update</property>  
  <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
  <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/your-database-name</property>          
            <property name="hibernate.connection.username">your-mysql-user-id</property
            <property name="hibernate.connection.password">your-mysql-password</property>
            <mapping resource="employee.hbm.xml"/> 
  </session-factory>  
 </hibernate-configuration>  



Step-6 Create the class that retrieves or stores the persistent object (From database)



In this class, we are simply storing the employee object to the database.

package com.demo.vivekdemo;

import org.hibernate.Session;import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import  org.hibernate.cfg.Configuration;

public class StoreData {
      public static void main(String[] args) {
   
      Configuration cfg=new Configuration(); // create configuration object
      cfg.configure("hibernate.cfg.xml");//populates the data of the configuration file
      SessionFactory factory=cfg.buildSessionFactory(); //creating seession factory object
      Session session=factory.openSession();  //creating session object
      Transaction t=session.beginTransaction(); //creating transaction object
      Employee e1=new Employee();
      e1.setId(001);
      e1.setFirstName("Vivek");
      e1.setLastName("Rai");

      session.persist(e1);//persisting the object        t.commit();//transaction is commited        session.close();        System.out.println("successfully saved");
   }
 
}

Step-7 Run the application

See the output
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
successfully saved




Tuesday 29 October 2013

A guide to Online backup and Point-in-time Recovery (PITR) method. Postgress Incremental Backup.

========================================================
PostgresSQL "Point-in-time Recovery" also called as incremental database backup, online backup or may be archive backup. At all times, PostgresSQL server records all users 'data modification transactions like insert, update or delete' and write them into a file called Write-Ahead-Log(WAL) file which is located in the 'pg_xlog/' sub directory of the cluster's data directory. This log exists primarily for crash-safety purposes. If the system crashes, the database can be restored to consistency by "replaying" the log entries made since the last checkpoint. However, the existence of the log makes it possible to use a third strategy for backing up databases: we can combine a file-system-level backup with backup of the WAL files. If recovery is needed, we restore the backup and then replay from the backed-up WAL files to bring the backup up to current time.


Summary of PostgreSQL Backup Steps
=============================================================================
1. Create database cluster with name 'data' & initialize it.
2. Modify postgresql.conf to support archive log.
3. Start database.
4. Create 'testdb' database with user 'postgres'.
5. Create table 'testPITR1' and populate it.
6. Create a full databse backup – base backup
7. Create table 'testPITR2' and populate it.
PostgreSQL Backup Steps
===================================================================

 Step 1: Create database cluster with name 'data' & initialize it.

             1.1 Create 'data' db cluster
        
             [root@localhost 8.3]#pwd
                 /opt/PostgreSQL/8.3/
             [root@localhost 8.3]#mkdir data
             [root@localhost 8.3]#chown postgres:postgres -R data
             [root@localhost 8.3]#chmod 0700 -R data
           
           1.2 Initialize database cluster
            
             [root@localhost 8.3]#su postgres
              bash-3.2$bin/initdb data
            
            1.3 Create 'pg_log' folder if it is not there
         
                [root@localhost 8.3]#mkdir pg_log
                [root@localhost 8.3]#chown postgres:postgres -R pg_log  
  
 Step 2: Modify postgresql.conf to support archive log.
  
            we need to make some changes in postgresql.conf file to tell PostgreSQL
            how to copy or archive WAL files that generated from PostgreSQL server.
  
            2.1 Open postgresql.conf
          
                [root@localhost data]# vi postgresql.conf
              
            2.2 Make following changes in postgresql.conf
     
                fsync = on
                synchronous_commit = on
                wal_sync_method = fsync
                full_page_writes = on
                checkpoint_segments = 4
                archive_mode = on
                archive_command = 'cp %p /opt/pgsqlbackup/wals/%f'
  
            2.3 Create a wals folder
          
                [root@localhost pgsqlbackup]pwd
                   /opt/pgsqlbackup
                [root@localhost pgsqlbackup]#mkdir /opt/pgsqlbackup/wals

Notes:- Relation between 'pg_xlog/' folder and 'wals/' folder.
===================================================================
            The 'pg_xlog/' folder contains WAL segment files.Each segment file size is 16MB.
            The segment files are given numeric names that reflect their position in the abstract
            WAL sequence.At any time,number of WAL segment files in this folder limited by
            this formula (2*checkpoint_segments+1).  Suppose,if any new log file being created
            is exceeds this limit,then oldest WAL segment from this folder copied to            
            '/opt/pgsqlbackup/wals' folder and it recyles the that oldest WAL segment file.
Step 3: Start database
  
            [root@localhost ~] /etc/init.d/postgresql-8.3 start
           
                                         OR

            [root@localhost ~] /opt/PostgreSQL/8.3/bin/pg_ctl start -D /opt/PostgreSQL/8.3/data -l tmp/pg.log
                 
Step 4: Create 'testdb' database  with user 'postgres'
          
            [root@localhost ~]su postgres
            bash-3.2$psql
            postgres=#CREATE DATABASE testdb;
            postgres=#GRANT ALL PRIVILEGES ON DATABASE testdb to test;
    
Step 5: Create table 'testPITR1' and populate this 455,252 records like this 
          
            [root@localhost ~]su postgres
            bash-3.2$ psql -d testdb -U postgres
            testdb=#create table testPITR1 as select * from pg_class, pg_description;
          
 Step 6: Create a full databse backup – base backup
                          
            6.1.Connect to the database as a superuser, and issue the command
          
                [root@localhost ~]# su postgres          
                bash-3.2$ psql -d testdb -U postgres
          
            6.2 Issue the base back up command
          
                testdb=#SELECT pg_start_backup('backup1');
          
                pg_start_backup()
                ——————–
                0/6BA9328
                (1 row)  
              
            6.3 Use a tar command to compress all 'data'(database cluster) to make a
                 database base backup.
              
                [root@localhost pgsqlbackup]pwd
                   /opt/pgsqlbackup
                [root@localhost pgsqlbackup]# tar -cvzf /opt/pgsqlbackup/pgdatabk2012Dec12.tar
                    /opt/PostgreSQL/8.3/data/
              
                Note:-
                      1. This command has be executed in other terminal.
                      2. pgdatabk2012Dec12.tar this is the full database backup (base backup) including
                          Postgresql configuration , system and all others files and folder.
              
            6.4 Again connect to the database as a superuser, and issue the command   
          
                select pg_stop_backup();
                ————————
                0/6BA9384
                (1 row)
              
 Step 7:    Create table 'testPITR2' and populate this records like this
  
            [root@localhost ~]su postgres
            bash-3.2$ psql -d testdb -U postgres
            testdb=#create table testPITR2 as select * from pg_class, pg_description;
  
  
    Note:-We created 2 tables for PITR recovery.First, testPIRT1 table is created
          & populated.After creation of this table, base backup of 'data'
          data cluster has been taken.Next,testPIRT2 is created.Assume that
          system was crashed after creation of testPIRT2 table.Now,the base back up
          contains only the testPITR1 table backup,but not testPITR2 table.
        
        
          Now,the Using PITR method whole data base can be recovered till the last
          checkpoint by using 'full base backup'+ archived WAL segment files
          in '/opt/pgsqlbackup/wals/' + remained Unarchived WAL segment files
          which are in 'pg_xlog/' folder of 'data' datacluster which is crashed.


PostgreSQL Point-in-time Recovery Steps
==============================================================================

Stop the database server assuming that it has been crashed.
   
Step 8. Rename 'data' db cluster to 'data.bad.data'
   
            [root@localhost 8.3]#pwd
               /opt/PostgreSQL/8.3/
            [root@localhost 8.3]#mv data data.bad.data
       
Step 9.  Create database cluster with name 'data' & don't initialize
       
            [root@localhost 8.3]#pwd
               /opt/PostgreSQL/8.3/
       
            [root@localhost 8.3]#mkdir data
            [root@localhost 8.3]#chown postgres:postgres -R data
            [root@localhost 8.3]#chmod 0700 -R data
            
Step 10. Extract files from base backup   
          
           10.1 Extract files from tar file
          
                  [root@localhost pgsqlbackup]pwd
                     /opt/pgsqlbackup
                  [root@localhost pgsqlbackup]tar -xvzf pgdatabk2012Dec12.tar
             
             10.2  After extract,move to data folder   
            
                  [root@localhost pgsqlbackup]cd opt/PostgreSQL/8.3/data/
                  [root@localhost data]# pwd
                      /opt/pgsqlbackup/opt/PostgreSQL/8.3/data
             
             10.3 Move all files from 'data' folder to 'data' folder created in
                 
                  Step 9    (**user 'mv' command only)    
                          
                  [root@localhost data] mv * /opt/PostgreSQL/8.3/data
                 
Step 11. Copy files from 'pg_xlog' folder of crashed 'data' folder renamed as
              'data.bad.data' to 'data' cluster files copied in step 10.3
             
              11.1.Before copying,issue commands to clear content of
                     'pg_xlog' of 'data' cluster files copied in step 10.3.
                    
                   [root@localhost 8.3 data]#pwd
                        /opt/PostgreSQL/8.3/data
                   [root@localhost 8.3 data]#cd pg_xlog
                   [root@localhost 8.3 pg_xlog]#pwd
                      /opt/PostgreSQL/8.3/data/pg_xlog
                   [root@localhost 8.3 pg_xlog]#rm -f 0* (remove all wal files)
                   [root@localhost 8.3 pg_xlog]#cd  archive_status
                   [root@localhost archive_status]#pwd
                      /opt/PostgreSQL/8.3/data/pg_xlog/archive_status
                   [root@localhost archive_status]rm -f 0* (remove all wal files)
                  
                  
                   ** Now, no contents in pg_xlog folder except 'archive_status' folder.
                  
             
              11.1 Go to pg_xlog folder of 'data.bad.data'
             
                    [root@localhost 8.3 data.bad.data]#pwd
                       /opt/PostgreSQL/8.3/data.bad.data
                    [root@localhost 8.3 data.bad.data]cd pg_xlog
                    [root@localhost 8.3 pg_xlog]pwd
                      /opt/PostgreSQL/8.3/data.bad.data/pg_xlog
                 
              11.2 Move unarchived files from 'pg_xlog' folder of 'data.bad.data'
                   to 'pg_xlog' folder of 'data' cluster copied in step 10.3.
                  
                   a) To find which are unarchived files, goto
                     'cd /opt/pgsqlbackup/wals/' archived folder of WAL files.
                   b) Find out which file is the last file in above folder.
                      Assume that  '000000010000000000000011' is the last file in
                      the 'wals/' folder.From  that we can understood that
                      from file number  '000000010000000000000012' to last file
                      in 'pg_xlog' folder of crashed 'data.bad.data' cluster has
                      to be copied to 'pg_xlog' folder of 'data' cluster copied
                      in step 10.3
                     
                      ** only user copy command for copying fiels,
                      so that data won't be corrupted
                     
12.Create recovery.conf file
   
           [root@localhost 8.3 data]#pwd
           /opt/PostgreSQL/8.3/data
           [root@localhost 8.3 data]#vi recovery.conf
                #add this content to above file
                restore_command = 'cp /opt/pgsqlbackup/wals/%f %p'

13.Start Recover
   
        [root@localhost ~] /etc/init.d/postgresql-8.3 start
        or
        [root@localhost ~] /opt/PostgreSQL/8.3/bin/pg_ctl  start -D /opt/PostgreSQL/8.3/data -l /tmp/pg.log
       
       a)if recovery is successful,then
            - 'recovery.conf' file name is changed to 'recovery.done'
            - history file is created.
            - WAL segment file number sequence is changed(e.g from x to x+1)
       b)check the log whether data base is recovered or not.
       c)connect to database & check db restoration is done properly or not.

*** Before proceeding recovery,maintain another copy of 'wals' folder contents & 'pg_xlog' folder contents of crashed 'data.bad.data' cluster.

Monday 11 February 2013

Java.lang.UnsupportedClassVersionError Unsupported major.minor version 51.0

If you are getting error Java.lang.UnsupportedClassVersionError Unsupported major.minor version 51.0 during compilation time
ErrorLog:-

BUILD FAILED
java.lang.UnsupportedClassVersionError: in/cdac/mobile/computing/mtrans/MtransService : Unsupported major.minor version 51.0
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClassCond(ClassLoader.java:631)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:615)
    at org.apache.tools.ant.AntClassLoader.defineClassFromData(AntClassLoader.java:1146)
    at org.apache.tools.ant.AntClassLoader.getClassFromStream(AntClassLoader.java:1324)
    at org.apache.tools.ant.AntClassLoader.findClassInComponents(AntClassLoader.java:1388)
Total time: 1 second
Solution:-
Check your java version
In Unix type command : java -verion
java version "1.6.0_30"
Java(TM) SE Runtime Environment (build 1.6.0_30-b12)
Java HotSpot(TM) Client VM (build 20.5-b03, mixed mode, sharing)
java.lang.UnsupportedClassVersionError occurs because of a higher JDK during compile time and lower JDK during runtime.
The version number shown describe which version if Java was used to compile the code.

The reported major numbers are

J2SE 7 = 51,
J2SE 6.0 = 50,
J2SE 5.0 = 49,
JDK 1.4 = 48,
JDK 1.3 = 47,
JDK 1.2 = 46,
JDK 1.1 = 45
Follow these step
Project -> Properties -> Java Compiler
Enable project specific settings.
Then select Compiler Compliance Level to 1.7,1.6 or 1.5, build and test your app.

Thursday 13 September 2012

How to connect jboss-as-7.1.1 to postgresql with JDBC driver


Download PgJDBC. postgresql-9.1-902.jdbc4.jar, the current version at time of writing. Adjust any filenames to match if you need a different version.
Now deploy the JDBC driver to JBoss AS 7 by putting it in the deployments folder or using the deploy command in jboss-cli. This will work for most, but not all, purposes.
Alternately, you an define a PostgreSQL JDBC driver module:
  1. Create the path $JBOSS_HOME/modules/org/postgresql/main. The modules/org part should already exist, make directories for the rest.
  2. In $JBOSS_HOME/modules/org/postgresql/main/modules.xml with the following content, changing the resource-root entry for the PgJDBC driver to refer to the driver you wish to use. 
       <?xml version="1.0" encoding="UTF-8"?>
      <module xmlns="urn:jboss:module:1.1" name="org.postgresql">
           <resources>
              <resource-root path="postgresql-9.1-902.jdbc4.jar"/>
          </resources>
          <dependencies>
              <module name="javax.api"/>
              <module name="javax.transaction.api"/>
              <module name="javax.servlet.api" optional="true"/>
         </dependencies>
      </module> 
   3. Into the same directory as modules.xml place postgresql-9.1-902.jdbc4.jar
   4. Open jboss-cli by running $JBOSS_HOME/bin/jboss-cli --connect
   5. Run the command:
       /subsystem=datasources/jdbc-driver=postgresql-driver:add(driver-name=postgresql-driver, driver-class-name=org.postgresql.Driver, driver-module-name=org.postgresql)
   6. Now create any required data sources, etc, using postgresql-driver as the driver name.
 
      You can create a datasource via the web ui, with jboss-cli with the data-source create command 
      (see data-source --help, data-source add --help), or by deploying a -ds.xml file like this 

      <?xml version="1.0" encoding="UTF-8"?>
      <datasources>
            <datasource jndi-name="java:/datasources/some-ds" enabled="true" use-java-context="true"  
                pool-name="some-ds-pool">
               <connection-url>jdbc:postgresql:dbname</connection-url>
               <driver>postgresql-driver</driver>
               <security>
                  <user-name>username</user-name>
                  <password>password</password>
              </security>
          </datasource>
     </datasources>
 

Thursday 16 August 2012

How to Create secure TCP/IP Connection with SSL

Follow these step to  Create secure TCP/IP Connection with SSL 


1. openssl req -new -text -out server.req

Generating a 1024 bit RSA private key
........................++++++
.............................++++++
writing new private key to 'privkey.pem'
Enter PEM pass phrase:1234567890
Verifying - Enter PEM pass phrase:1234567890
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [GB]:IN
State or Province Name (full name) [Berkshire]:Karnataka
Locality Name (eg, city) [Newbury]:Bangalore
Organization Name (eg, company) [My Company Ltd]:Center for development of advanced computing
Organizational Unit Name (eg, section) []:SENG
Common Name (eg, your name or your server's hostname) []:NKN
Email Address []:vivek.k.ray@gmail.com

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:welcome123#
An optional company name []:National Center for Software Technology

2.openssl rsa -in privkey.pem -out server.key
Enter pass phrase for privkey.pem:1234567890
writing RSA key

3.rm privkey.pem

4.openssl req -x509 -in server.req -text -key server.key -out server.crt

5.chmod og-rwx server.key