Sunday, January 23, 2011

Struts Internationalization Example

web.xml :


<?xml version="1.0" encoding="Shift_JIS"?>

<!DOCTYPE web-app
  PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
  "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
  <servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
    <init-param>
      <param-name>config</param-name>
      <param-value>/WEB-INF/struts-config.xml</param-value>
    </init-param>
    <init-param>
      <param-name>debug</param-name>
      <param-value>2</param-value>
    </init-param>
    <init-param>
      <param-name>detail</param-name>
      <param-value>2</param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
  <welcome-file>login.jsp</welcome-file>
  </welcome-file-list>

  <taglib>
    <taglib-uri>/tags/struts-bean</taglib-uri>
    <taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
  </taglib>

  <taglib>
    <taglib-uri>/tags/struts-html</taglib-uri>
    <taglib-location>/WEB-INF/struts-html.tld</taglib-location>
  </taglib>

  <taglib>
    <taglib-uri>/tags/struts-logic</taglib-uri>
    <taglib-location>/WEB-INF/struts-logic.tld</taglib-location>
  </taglib>

  <taglib>
    <taglib-uri>/tags/struts-nested</taglib-uri>
    <taglib-location>/WEB-INF/struts-nested.tld</taglib-location>
  </taglib>

  <taglib>
    <taglib-uri>/tags/struts-tiles</taglib-uri>
    <taglib-location>/WEB-INF/struts-tiles.tld</taglib-location>
  </taglib>

  <!--
  <taglib>
    <taglib-uri>http://java.sun.com/jstl/core</taglib-uri>
    <taglib-location>/WEB-INF/c.tld</taglib-location>
  </taglib>

  <taglib>
    <taglib-uri>http://java.sun.com/jstl/fmt</taglib-uri>
    <taglib-location>/WEB-INF/fmt.tld</taglib-location>
  </taglib>

  <taglib>
    <taglib-uri>http://java.sun.com/jstl/sql</taglib-uri>
    <taglib-location>/WEB-INF/sql.tld</taglib-location>
  </taglib>

  <taglib>
    <taglib-uri>http://java.sun.com/jstl/x</taglib-uri>
    <taglib-location>/WEB-INF/x.tld</taglib-location>
  </taglib>
  -->
</web-app>

  struts-config.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">
<struts-config>
  <data-sources>
  </data-sources>
  <form-beans>
      <form-bean name="loginform" type="org.apache.struts.validator.DynaValidatorForm">
          <form-property name="username" type="java.lang.String"></form-property>
          <form-property name="password" type="java.lang.String"></form-property>
      </form-bean>
  </form-beans>
  <global-exceptions>
  </global-exceptions>
  <global-forwards>
  </global-forwards>
  <action-mappings>
      <action path="/login" type="com.test.struts.LoginAction" name="loginform" validate="true" input="/login.jsp">
          <forward name="success" path="/welcome.jsp"></forward>
          <forward name="failure" path="/login.jsp"></forward>
      </action>
  </action-mappings>
  <controller locale="true" processorClass="org.apache.struts.tiles.TilesRequestProcessor"/>
  <message-resources parameter="ApplicationResources"/>
  <plug-in className="org.apache.struts.tiles.TilesPlugin">
    <set-property property="definitions-config" value="/WEB-INF/tiles-defs.xml"/>
    <set-property property="moduleAware" value="true"/>
  </plug-in>
  <plug-in className="org.apache.struts.validator.ValidatorPlugIn">
    <set-property property="pathnames" value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
  </plug-in>
</struts-config>
    
login.jsp :   

<%@ taglib uri="/tags/struts-bean" prefix="bean" %>
<%@ taglib uri="/tags/struts-logic" prefix="logic" %>
<%@ taglib uri="/tags/struts-html" prefix="html" %>
<%@ taglib uri="/tags/struts-nested" prefix="nested" %>

<html:html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=Cp1252"/>
        <title></title>
    </head>
    <body bgcolor="yellow">
         <center>
              <html:errors/>
              <bean:message key="welcome.message"/>
              <html:form method="POST" action="login">
                  <bean:message key="username"/><html:text property="username"></html:text><br><br>
                  <bean:message key="password"/><html:text property="password"></html:text><br><br>
                  <html:submit><bean:message key="register.submit"/></html:submit>
            </html:form>
        </center>
    </body>
</html:html>



 LoginAction.java


 package com.test.struts;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import org.apache.struts.action.Action;
 import org.apache.struts.action.ActionForm;
 import org.apache.struts.action.ActionForward;
 import org.apache.struts.action.ActionMapping;
 import org.apache.struts.validator.DynaValidatorForm;


    /**
     *
     * @author Mallik
     *
     */

    /**
     * LoginAction Class
     */

 public class LoginAction extends Action {
        /**
         * Action class execute method
         */

 public ActionForward execute(ActionMapping actionMapping,ActionForm actionForm,HttpServletRequest request,HttpServletResponse response)throws Exception{

 String responseKey="failure";
 DynaValidatorForm dynaValidatorForm=(DynaValidatorForm) actionForm;
 String user=(String)dynaValidatorForm.get("username");
 String pwd=(String)dynaValidatorForm.get("password");

 if(user.equals(pwd))
               responseKey="success";
 return actionMapping.findForward(responseKey);

        }
    }


welcome.jsp :

<%@ page contentType="text/html; charset=Cp1252" %>
<%@ taglib uri="/tags/struts-bean" prefix="bean" %>
<%@ taglib uri="/tags/struts-logic" prefix="logic" %>
<%@ taglib uri="/tags/struts-html" prefix="html" %>
<%@ taglib uri="/tags/struts-nested" prefix="nested" %>


<html:html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=Cp1252"/>
        <title></title>
    </head>
    <body bgcolor="green">
        <h1><bean:message key="welcome"/></h1>
    </body>
</html:html>
      

 ApplicationResources_it.properties :

welcome.message=Dare if benevenuato all aperatoreitaliano(in english:welcome to italian user)
welcome=<b>Dare if benevenuato all aperatoreitaliano</b>
username=<b>nome de operatore</b>
password=<b>parola de ordine</b>
register.submit=registero
errors.required=<li><i>if compo di{0}non puo essere vuoto</i></li>
errors.minlength=<li><i>la {0}non puo essere vuoto {2} carreteri.</i></li>


 ApplicationResources_en.properties :

welcome.message = welcome to english user
welcome=<b>Hello english user welcome to our website</b>
username=<b>username</b>
password=<b>password</b>
register.submit=register
errors.required=<li><i>{0}field cannot be empty.</i></li>
errors.minlength=<li><i>{0}cannot be lessthan {2} charecters.</i></li>

Saturday, January 8, 2011

Log4j - The best logging implementation in Java

While developing the applications, some times we need to log the some data or some information message or errors into a separate file. For Java based web applications, we use Log4j api to implement this functionality.


Log4j has three main components: loggers, appenders and layouts. These three types of components work together to enable developers to log messages according to message type and level, and to control at run time how these messages are formatted and where they are reported.

Loggers may be assigned levels. The set of possible levels, that is:
TRACE,
DEBUG,
INFO,
WARN,
ERROR and
FATAL

Log4j is providing different appenders. Using these appenders user can append the messages to different messages medias. The basic appenders of Log4j are:

1. Console Appender
2. File Appender
3. Daily rolling file appender
4. Email Appender
5. SMS appender.

User can control these appenders from the log4j configurations files called log4j.properties or log4j.xml.

User can define different layouts for the logging message called Simple layout, Flow layout ... etc.


Log4j Examples:


The basic example to implement the Log4j:
import org.apache.log4j.Logger;

public class LogExample {

    public LogExample() {
    }
    static Logger log = Logger.getLogger(LogExample.class);

    public static void main(String argsp[]) {
       
        log.debug("projectname-modulename-Class-method-Here is some DEBUG");
        log.info("projectname-modulename-Class-method-Here is some INFO");
        log.warn("projectname-modulename-Class-method-Here is some WARN");
        log.error("projectname-modulename-Class-method-Here is some ERROR");
        log.fatal("projectname-modulename-Class-method-Here is some FATAL");
        log.warn("projectname-modulename-Class-method-Here is some WARN");
     
   }
}



 The sample example to read the log4j configurations from properties file:
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;


public class Example2  {
   
    public static void main(String a[])
    {
        Logger l=Logger.getLogger(Example2.class);
   
        PropertyConfigurator.configure("src/prop.properties");
         
          l.setLevel(Level.DEBUG);
          l.debug("Myprojectname-modulename-Class-method-ok executedddddddddddddd");
          l.info("projectname-modulename-Class-method-some infoooooooooo");
          l.warn("projectname-modulename-Class-method-warn msg");
          l.error("projectname-modulename-Class-method-error msg......");
          l.fatal("projectname-modulename-Class-method-this is some fatal errrrrrrr");
    }
}


Log4j configurations in properties file:  prop.properties
log4j.rootLogger=debug, stdout
log4j.appender.stdout=org.apache.log4j.DailyRollingFileAppender
log4j.appender.stdout.File=logs/dailyrollfile3333.txt
log4j.appender.stdout.DatePattern='.'yyyy-MM-dd-HH-mm
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%r  [%t]  %p  %c  %m  %d  %n                    



 Implementing log4j with Console appender :

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Layout;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;

//ConsoleAppender
public class Example1 {
   
public static void main(String a[])
{
    Logger l=Logger.getLogger(Example1.class);
    Layout lay=new SimpleLayout();
ConsoleAppender ap=new ConsoleAppender(lay);

l.addAppender(ap);
l.setLevel(Level.DEBUG);

  try{
Class.forName("oracle.jdbc.driver.OracleDriver");
l.debug("driver loaded");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@192.168.1.214:1521:XE","kiran","kiran");
l.info("connection established successfully");

  }catch(ClassNotFoundException e)
  {
      l.fatal(" OOPS.........DriverClass Problem(plz check Driverclass)");
      e.printStackTrace();
  }catch(SQLException se)
  {
      l.fatal("OOPS............Db Connection Problem");
      se.printStackTrace();
  }
  catch(Exception se)
  {
      l.error("OOPS............Db Problem");
      se.printStackTrace();
  }
   
}
}



File Appender example in Log4j :

import java.sql.Connection;
import java.sql.DriverManager;

import org.apache.log4j.*;

//FileAppender

public class Example2  {
   
    public static void main(String a[])
    {
        Logger l=Logger.getLogger(Example2.class);
          try{
    Layout lay=new SimpleLayout();
    FileAppender ap=new FileAppender(lay,"sample.log",true);
    l.addAppender(ap);
    l.setLevel(Level.DEBUG);
          }catch(Exception d)
          {
              l.debug("log4j stmts problem");
          }
    try{
    Class.forName("oracle.jdbc.driver.OracleDriver");
    l.debug("driver loaded......");
    Connection con=DriverManager.getConnection("jdbc:oracle:thin:@192.168.1.214:1521:XE","kiran","kiran");
    l.info("connection established successfully..........");
   
      }catch(Exception e)
      {
          l.fatal("Db Problem");
          e.printStackTrace();
      }
       
    }
}

Sunday, January 2, 2011

My Top 5 Best posts in 2010

We have successfully completed the year 2010. I just rewind myself on blog posts in 2010. I have posted total 47 posts in the year 2010. While looking into my posts I decided to list out the top 5 posts in 2010. I am trying to list the posts depending on time taken to write it and the importance of the posts.

The Top 5 posts are:

My wonderful journey to "Shirdi"  

I went shirdi tour for three days with colleagues. The journey has taken three days and we have enjoyed a lot. I have shared my experience with this post, It has taken nearly 3 days to complete but it was good post. Because, if a person wants to visit Shirdi he can know that the near by tourist places.

My Hero : Stephen Hawking 

I have read about Stephen Hawking for three days continuously. He is a great person and great scientist. While I am reading about him, I found that he is a great role model for most of the young people and scientists. So, I have shared my opinion with you.

Introduction to Apache Cassandra 

In my project I got  chance to work on Apache Cassandra. I have done R & D on it for a month. I have learned so many things about Cassandra, So I have shared my knowledge with you all.

A Small Request to 2011 - from 2010

While I am leaving the year 2010, I found that it is ending as more corrupted year of the last decade. So  I have planned to share my opinion to realize in the next year.

Java Performance Tuning Tips

 As a software engineer, I am working on Java. So, I shared few performance tips which useful to build a good application.

 

These top 5 posts are chosen by me depending on my back ground work. This purely my opinion.


Friday, December 31, 2010

What is a Web Service?

A Web service is a software system identified by a URI whose public interfaces and bindings are defined and described using xml. Its definition can be discovered by other software systems. These systems may then interact with internet protocols.

(OR)

A Web service is a software application, accessible on the web through URL, that is accessed by clients using XML based protocols, such as SOAP(Simple Object access protocol) sent over accepted Internet protocols such as HTTP. Client access a web service application through ts interfaces and bindings, which are defined using XML artifacts sch as a WSDL (Web Service Definition Language) file.

Thursday, December 30, 2010

A Small Request to 2011 - from 2010

Dear 2011,

As you know that , today I am completing my life time, I am going to die on this day. So, I want to take the opportunity to share my experience with you while leaving.

I am very happy in welcoming you, but at the same time I am very sad because I am leaving today.

I have spent my 365 days with all the people with some happiness and  with some sorrows.Even I tried allot to be more successful, but it was not as such as expected. I have taken formers stomach with Jal and Lila cyclones and at the end i am leaving with more corrupted year in the last decade with 2G Spectrum. I have made more successful inventions in the science and technology but those became very small under the corruption. 

I request you to don't repeat my mistakes in your 365 days of life and I am intimating you to that don't leave the corrupted politicians.

I request you to the more inventions in technology and don't eat the farmers stomach. Don't allow the terrorists into the country and try to eradicate the terrorist politicians. I can say that be cool and calm for all the days and be helpful to the poor people all ways in your life.

I hope that you will become a best year in this century ... :)


Yours loving friend

Your's 2010




Saturday, November 27, 2010

Caching in hibernate

Caching is a Temporary memory or buffer which resides at client side and stores the results sent by server. When client generates same request for multiple number of times, the first request generated results will be stored in cache and this result will be used across the multiple requests. This reduces the round trips between the client and server. Since the result will be collected from cache that is available at client side.

Hibernate supports for 2 levels of cache:
  1. Level one cache
  2. Level two cache.
Level One Cache:   
Level 1 cache is inbuilt cache and it will be associated with hibernate session objects. Every session object of hibernate application contains one inbuilt level one cache.

Responsibilities of Level one cache:
a)      If select query executed for multiple no of times with in a session. Only one time query goes to database software gets the result, remaining all the times result will be gathered from cache.
b)      If one of POJO class object is modified for multiple no of times with in a transaction of session object, instead of sending update query for multiple number of times, all the changes done on the object will be kept tracked and only one update query will be generated reflecting all the changes at the end of the transaction.

The different ways to remove the level 1 cache from session
i)                    Session.flush()  --> Flushes level one cache content to db software
ii)                   Session.evict()  --> Remove the content of level 1 cache
iii)                 Session.close() --> closes level 1 cache, before that it calls session.flush()
A hibernate client application can have multiple level1 caches because a hibernate application can have multiple hibernate session objects.
The data stored in level1 cache, level2 cache will be in full synchronization with table rows.

Level-2 Cache:

It is a configurable cache (Not a built in cache). Third party vendors are supplying supporting jar files for level 2 cache. Level2 cache is global cache and it is visible for all the session objects of the hibernate application.
When level-2 cache is enabled the results gathered for database software will be stored in both level 1 and level 2 caches.
sessionFactory.close()  --> Destroys the session factory object and releases level 2 cache.
sessionFactory.evict(arga …)  --> Removes pojo class object from session factory.
sessionFactory.evictQueries(args…)  --> Cleans queries related data from cache. 

If hibernate use same request as second request or different session objects then software tries to collects the results either from leve1/level2 caches.
There are different third party providers for level 2 cache:
  1. Swarm Cache
  2. OS Cache,
  3. EH Cache
  4. JBoss Tree Cache … etc.

Friday, November 19, 2010

My Hero : Stephen Hawking

Heroes are the people who can overcome fear, or help others overcome fear. 
Here I am happy to tell about is, someone who just lives his life as he is. He has faced terrible problems and has become a great person of new scientific era.
So he is my Role Model, He is my Hero, He is my Inspiration….
He is Stephen Hawking… He is a unique person with extraordinary mind.
My Hero is a person whose greatness sneaked up on the world. He was born on 8th January 1942 in England. Although there were thousands of people born on that day, but he was special. As child he is little clumsy and bit too smart.
With his smartness he became great intellect but with his clumsiness he got the disease called “Motor Neuron Disease”. With this disease he has been confined to a wheel chair from the last 4 decades and most of his external body organs stopped working. From the last 25 years he is not able to speak.


Hacking’s external organs eyes, ears and little left hand small fingers only active. In spite of all these physical disabilities he is totally dedicated to his work. 
Actually Hawking has been working on basic laws of the Universe. Hawking has done many great things, I found fallowing are the major things according to me.
He has done the extreme work in new scientific era. He has been proved that the Black Holes emit the Radiation and now it’s named as Hacking’s radiation.
In 1988 he wrote a book called “A Brief History of Time” which became the international best seller of the year.
American news paper Chicago Times wrote “Hawking is a legend right up there with Galilee and Newton and Einstein”.
Here I will share one important thing about Hawking which happened in his life. Once he was in middle of writing a book. With his disease he lost his voice. There is no other way to write or communicate except by blinking of eyes. Fortunately, he loved his work so much that he continued on with it despite the ever clinking fear dying.
After several years he has received a present from his college friend. The present was a revolutionary new Computer that attached to his Wheel chair and would talk to him. He now had a way to write his papers and lectures to students. It seemed that his life was now seems better.
I hope that, generally our problems are not bigger than Hawking’s problems.
He has not saved someone’s life, but he inspired mine. So in my opinion, He is my Hero and if you don’t mind he will always be my hero.
Are our problems are bigger than Hawking’s problems? Never right…..
So, He is My Role model, He is my inspiration finally he is my HERO…

Thanks….

Wednesday, November 3, 2010

Connection Sql Server using Java

package com.javatutorials;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class SqlServerConnection {
    public static Connection connection = null;
    public static Connection getDbConnection() {
        try {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            connection = DriverManager
                    .getConnection("jdbc:odbc:mydsn;user=sa;password=sa12$");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    public static void closeConnection() {
        if (connection != null)
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
    }
}
mydsn in the above class is the dsn created to connect to sql server using jdbc-odbc connection.

The dsn  creating process can be found at : Create SQL Server dsn


Create Folder in Java Example

import java.io.File;
/**
 * @author mallikarjung
 *
 */
public class FolderCreation {
    public static String folderPath = "D:/SampleFolder/";
    /**
     * @param args
     */
    public static void main(String[] args) {
        File folder = new File(folderPath);
        //check whether folder exists or not
        if(!folder.exists()){
            folder.mkdir();
            System.out.println("Folder has been created Successfully ... ");
        }
    }
}

Replace String Example in Java

/**
 * @author Mallikarjun G
 *
 */
public class JavaStringReplaceExample {
    /**
     * @param args
     */
    public static void main(String args[]) {      
        String str = "Replace String";
        System.out.println(str.replace('R', 'A'));// Replaceing R with a in str
        System.out.println(str.replaceFirst("Re", "Ra"));// Replaceing First Re with Ra in str  
        System.out.println(str.replaceAll("Re", "Ra")); // Replaceing All Re with Ra in str   

    }


}