Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Thursday, July 3, 2014

java.lang.NoClassDefFoundError: Lorg/apache/commons/logging/Log

Please ensure that you have included standred.jar in classpath. Click here to download  standred.jar - See more at: http://makecodeeasy.blogspot.in/2014/07/javautilconcurrentexecutionexception.html#sthash.0Um7PGLr.dpuf
Exception :- java.lang.NoClassDefFoundError: Lorg/apache/commons/logging/Log

First ensure that you have included commons-logging-xxx.jar in classpath.
Click here to download 
commons-logging-xxx.jar

If you are using maven then add following dependency in pom.xml
<dependency> 
    <groupId>commons-logging</groupId> 
    <artifactId>commons-logging</artifactId> 
    <version>1.1.1</version> 
</dependency>
The Commons Logging provides a Log interface that is intended to be both light-weight and an independent abstraction of other logging toolkits. It provides the middleware/tooling developer with a simple logging abstraction, that allows the user (application developer) to plug in a specific logging implementation.

java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina]

Exception :- java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina]

Please ensure that you have included standred.jar in classpath.
Click here to download  standred.jar

If you are using maven then add following dependency in pom.xml
 <dependency>  
   <groupId>taglibs</groupId>  
   <artifactId>standard</artifactId>  
   <version>1.1.2</version>  
 </dependency>  

standard.jar (taglib) library is used to enable the JSTL expression language in JSP page, and it’s always used together with the jstl.jar together.
 
 <dependency> 
    <groupId>taglibs</groupId> 
    <artifactId>standard</artifactId> 
    <version>1.1.2</version> 
</dependency> 

Saturday, June 1, 2013

Two Datasource in Spring/Hiberate

We can create two datasource in a single spring/hibernate application.

There are following steps required to implement this:-

Create JNDI Datasource while using Tomcat :- 
  1. Resource entry in server.xml under <GlobalNamingResources> for both datasources
    You can find server.xml in following path in Tomcat folder :-
     c://Tomcat/conf/server.xml
  2. <globalnamingresources>
        <resource name="jdbc/first"  driverclassname="com.microsoft.sqlserver.jdbc.SQLServerDriver" maxwait="5000" password="makecodeeasy" type="javax.sql.DataSource" url="jdbc:sqlserver://localhost:1433;DatabaseName=DataTest" username="makecodeeasy" validationquery="select 1">
        </resource>
    
     <resource name="jdbc/second"  driverclassname="com.microsoft.sqlserver.jdbc.SQLServerDriver" maxwait="5000" password="123" type="javax.sql.DataSource" url="jdbc:sqlserver://192.182.21.66:1433;DatabaseName=Second" username="sa" validationquery="select 1">
        </resource>
     </globalnamingresources>
    
    Note :- Database used here in MS Sql server 2008. You can use any database. You need to change driverClassname, url, username and password according to  database.
  3. Do the entry in web.xml for both resources
    You can find web.xml in WEB-INF folder of your application
  4. <resource-ref>
      <description>DB Connection Pooling</description> 
      <res-ref-name>java:comp/env/jdbc/first</res-ref-name> 
      <res-type>javax.sql.DataSource</res-type> 
      <res-auth>Container</res-auth> 
      <res-sharing-scope>Shareable</res-sharing-scope> 
    </resource-ref>
    
    
    <resource-ref>
      <description>DB Connection Pooling</description> 
      <res-ref-name>java:comp/env/jdbc/second</res-ref-name> 
      <res-type>javax.sql.DataSource</res-type> 
      <res-auth>Container</res-auth> 
      <res-sharing-scope>Shareable</res-sharing-scope> 
    </resource-ref>
    
  5. Use datasource in applicationContext or spring context file
  6. <bean id="firstDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
      <property name="jndiName" value="java:comp/env/jdbc/first" /> 
      <property name="resourceRef" value="true" /> 
    </bean>
    <bean id="secondDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
      <property name="jndiName" value="java:comp/env/jdbc/second" /> 
      <property name="resourceRef" value="true" /> 
    </bean> 
  7. Create two session factory for using two datasource.
    <bean id="firstSessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" p:dataSource-ref="firstDataSource" p:configLocation="${hib.config}" p:packagesToScan="com.org.xyz.domain">
    </bean>
    <bean id="secondSessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" p:dataSource-ref="secondDataSource" p:configLocation="${hib.config}" p:packagesToScan="com.org.abc.domain">
    </bean>

  8. Now these session factories can be used in Hibernate application.

Sunday, May 19, 2013

JNDI Datasource in spring

There are two sources of database connections - either a  DataSource or a  DriverManager.

JNDI
The Java Naming and Directory Interface (JNDI) is part of the Java platform, providing applications based on Java technology with a unified interface to multiple naming and directory services. You can build powerful and portable directory-enabled applications using this industry standard.

Create JNDI Datasource while using Tomcat :- 
  1. Resource entry in server.xml under <GlobalNamingResources>
    You can find server.xml in following path in Tomcat folder :-
     c://Tomcat/conf/server.xml
  2. <globalnamingresources>
        <resource name="jdbc/test"  driverclassname="com.microsoft.sqlserver.jdbc.SQLServerDriver" maxwait="5000" password="makecodeeasy" type="javax.sql.DataSource" url="jdbc:sqlserver://localhost:1433;DatabaseName=DataTest" username="makecodeeasy" validationquery="select 1">
        </resource>
    </globalnamingresources>
    Note :- Database used here in MS Sql server 2008. You can use any database. You need to change driverClassname, url, username and password according to  database.
  3. Do the entry in web.xml
    You can find web.xml in WEB-INF folder of your application
  4. <resource-ref>
      <description>DB Connection Pooling</description> 
      <res-ref-name>java:comp/env/jdbc/test</res-ref-name> 
      <res-type>javax.sql.DataSource</res-type> 
      <res-auth>Container</res-auth> 
      <res-sharing-scope>Shareable</res-sharing-scope> 
    </resource-ref>
    
  5. Use datasource in applicationContext or spring context file
  6. <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
      <property name="jndiName" value="java:comp/env/jdbc/test" /> 
      <property name="resourceRef" value="true" /> 
    </bean>
    
  7. Your Datasource is ready to use. It can also be used in hibernate.

Sunday, May 5, 2013

JNDI

The Java Naming and Directory Interface (JNDI) is part of the Java platform, providing applications based on Java technology with a unified interface to multiple naming and directory services. You can build powerful and portable directory-enabled applications using this industry standard.

Example of creating JNDI Datasource.

Tuesday, April 30, 2013

Iterate a HashMap


HashMap is an object that stores both “key/value” as a pairs.
It is one of the most useful data structures in the Java programming language.

Step by Step Iterating a HashMap :- 

Method 1 :-
Map<Integer, Integer> map = new HashMap<Integer, Integer>();

//iterating over keys only
for (Integer key : map.keySet()) {
System.out.println("Key = " + key);
}

//iterating over values only
for (Integer value : map.values()) {
System.out.println("Value = " + value);
}

Method 2 :-
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}

Saturday, March 23, 2013

Logger in Spring web application


The logging API is designed to let a Java program, servlet, applet, EJB, etc. produce messages of interest to end users, system administrators, field engineers, and software developers. Especially in production situations, where things can't be run in a debugger, or if doing so masks the problem that is occurring (because it is timing related, for example), such logs are frequently the greatest (and sometimes the only) source of information about a running program.

Step by Step implementing Logger in Spring Web Application:-

  1. Download log4j jar and put to application build path / put to WEB-INF lib folder.
    Download JAR link
  2. Create a file name Log4js.properties
  3. log4j.rootCategory=INFO,S,rollingFile
    
    log4j.appender.S =org.apache.log4j.ConsoleAppender
    log4j.appender.S.layout =org.apache.log4j.PatternLayout
    log4j.appender.S.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} %c{1} [%p] %m%n
    log4j.appender.rollingFile = org.apache.log4j.DailyRollingFileAppender
    
    #provide path to your location where you want logs created. For now its logs folder of tomcat.
    log4j.appender.rollingFile.File = ${catalina.home}/logs/loggerDemo.log
    log4j.appender.rollingFile.Append = true
    log4j.appender.rollingFile.Threshold = ALL
    log4j.appender.rollingFile.DatePattern = '.'yyy-MM-dd
    log4j.appender.rollingFile.layout = org.apache.log4j.PatternLayout
    log4j.appender.rollingFile.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} %c{1} [%p] %m%n
    
    
      Here ${catalina.home} :- The Tomcat Web container uses a file system directory, called the catalina home directory, to hold files that are common to the entire container.
      You can also give other path for generating log file.
  4. Entry in web.xml file
  5.  
          log4jConfigLocation
          /WEB-INF/resources/log4j.properties
        
    
         
            org.springframework.web.util.Log4jConfigListener
        
    
  6. JAVA Code for logger.
  7. import org.apache.log4j.Logger;
    public class LoggerController {
    
    	private static final Logger LOGGER = Logger.getLogger(LoggerDemo.class);
    
    	@RequestMapping(method=RequestMethod.GET, value="/login/{id}")
    	@ResponseBody public void getUserName(@PathVariable String id) {
    		LOGGER.info("Calling service User authentication" + id);
    	}
    
    }
    
    
  8. Enjoy :)

Sunday, December 16, 2012

Checked Vs Unchecked Exception

Checked Exception  in Java is all those Exception which requires being catches and handled during compile time. If Compiler doesn't see try or catch block handling a Checked Exception, it throws Compilation error. All the Exception which are direct sub Class of Exception but not inherit RuntimeException are Checked Exception.
IOException
SQLException
DataAccessException
ClassNotFoundException
InvocationTargetException

Unchecked Exception  in Java is those Exceptions whose handling is not verified during Compile time. Unchecked Exceptions mostly arise due to programming errors like accessing method of a null object, accessing element outside an array bonding or invoking method with illegal arguments. In Java, Unchecked Exception is direct sub Class of RuntimeException. What is major benefit of Unchecked Exception is that it doesn't reduce code readability and keeps the client code clean.
NullPointerException
ArrayIndexOutOfBound
IllegalArgumentException
IllegalStateException

Difference :- Checked Exception is required to be handled by compile time while Unchecked Exception doesn't.
Checked Exception is direct sub-Class of Exception while Unchecked Exception are of RuntimeException.
CheckedException represent scenario with higher failure rate while UnCheckedException are mostly programming mistakes.






Saturday, December 1, 2012

System.out.println


System – is a final class and cannot be instantiated. Therefore all its members (fields and methods) will be static and we understand that it is an utility class. System class are standard input, standard output, and error output streams.

out – is a static member field of System class and is of type PrintStream. Its access specifiers are public final. This gets instantiated during startup and gets mapped with standard output console of the host.

println – Method of PrintStream class. println prints the argument passed to the standard console and a newline. 

Can a top level class be private or protected


No. A top level class can not be private or protected. It can have either "public" or no modifier. If it does not have a modifier it is supposed to have a default access.If a top level class is declared as private the compiler will complain that the "modifier private is not allowed here". This means that a top level class can not be private. Same is the case with protected.

main() method in java


The main function is important function in Java programming language. 
The main method is the first method, which the Java Virtual Machine executes. When you execute a class with the Java interpreter, the run time system starts by calling the class's main() method. The main() method then calls all the other methods required to run your application. It can be said that the main method is the entry point in the Java program and java program can't run without this method.

Public static void main (String args[])
Public is an Access Specifier.

static is a keyword which illustrates that method shared along all the classes.
void illustrates that this method will not have any return type.
main is the method which string has an argument. 
Public specifier makes the method visible outside the Class and because of the static nature of the method, JVM can call this main method without instantiating the class.

Friday, November 30, 2012

Path and Classpath


PATH is nothing but setting up an environment for operating system. Operating System will look in this PATH for executable.


Classpath is nothing but setting up the environment for Java. Java will use to find compiled classes (i.e. .class files).



Path refers to the system while classpath refers to the Developing Envornment.

We keep all "executable files"(like .exe files) and "batch files"(like .bat) in path variable. And we keep all jar files and class files in classpath variables.



For example,assume that Java is installed in C:\jdk1.5.0\ and your code is in C:\Sample\example.java, then your PATH and CLASSPATH should be set to:

PATH = C:\jdk1.5.0\bin;%PATH%

CLASSPATH = C:\Sample










Sunday, August 12, 2012

Paint in Java

Painting Editor/ Drawing Pad in JAVA


/**
 * MakeCodeEasy
 */
import java.awt.*;
import java.awt.event.*;

public class Painting implements MouseMotionListener,MouseListener
{
    Frame f;
    int x,y;
    int px;
    int py;
    int count=0;
    public Painting()
    {
   
    f=new Frame();
           f.setSize(400,400);
           f.setVisible(true);
    
               f.addMouseMotionListener(this);
               f.addMouseListener(this);
               
   
           WindowCloser wc=new WindowCloser();
          f.addWindowListener(wc);
    }
   
    public void mouseDragged(MouseEvent e1)
    {
    }
    
    public void mouseMoved(MouseEvent e2)
    {
        if(count==0)
        {
        x=e2.getX();
            y=e2.getY();
            Graphics g=f.getGraphics();
                 g.setColor(Color.blue);
                 g.drawLine(x,y,x,y);
            px=x;
                 py=y;
                 count=1;
        }
        else
        {
                 x=e2.getX();
            y=e2.getY();
            Graphics g=f.getGraphics();
                 g.setColor(Color.blue);
                 g.drawLine(px,py,x,y);
            px=x;
                 py=y;
        }
     }
    
    public void mouseClicked(MouseEvent e3)
     {
     
     }
     
     public void mouseEntered(MouseEvent e4)
     {
     }
     
     public void mouseExited(MouseEvent e5)
     {
      count=0;
     }
     
     public void mousePressed(MouseEvent e6)
     {
      count=0;
     }
     
     public void mouseReleased(MouseEvent e7)
     {
     }
     
    
    public static void main(String args[])
    {
    Painting pnt=new Painting();
    }
    
}

Output :-

    

Thursday, August 9, 2012

FileSpliter in JAVA


Divide a file into multiple parts

import java.util.*;
import java.io.*;

class Spliter
{
public static void main(String args[]) throws Exception
{
 long size;
 
 System.out.println("Enter the file name You want to spilit");
 
 Console con=System.console();
 String str=con.readLine();
 
 File f=new File(str);
 
 
  if(f.exists())
  {
  size=f.length();
  System.out.println(size+" byte");
 
  con.printf("Enter Destination FIle Size :-");
  double l=Integer.parseInt(con.readLine());
 
  int num=(int)(Math.ceil(size/l));
  System.out.println("Number of files = "+(num));
  FileInputStream fis=new FileInputStream(f);
 
 
  int ch,j=1;
  String arr[]=new String[num]; 
  for(int i=0;i<num;i++,j++)
  {
         arr[i]=j+f.getName();
         File f1=new File(arr[i]);
                  FileOutputStream fos=new FileOutputStream(f1);
          
         int k=1;
                                    label1:           
         while((ch=fis.read())!=-1)
         {
          if(k<l)
          {
              fos.write(ch);
                        k++;
                  }
                  else if(k>=l)
                  {
                  fos.write(ch);
                break label1;
                  }
             }
     fos.close();
  }
  fis.close();
 
  }
}
}

Steps :-                                                  Compile


RUN


OutPut






    Tuesday, August 7, 2012

    Calculator in JAVA


    Basic Calculator in JAVA

    /**
     * Basic Calculator
     * @author : Makecodeeasy
     */

    import java.awt.*;

    import java.awt.event.*;

    public class Calc implements ActionListener 

    {
       TextField tf;
       public Calc()
       {
        //FlowLayout fl=new FlowLayout(FlowLayout.LEFT,0,0);
       
        Font fnt=new Font("Arial",Font.BOLD,20);
       
        GridLayout gl1=new GridLayout(5,0);
       
        Frame f=new Frame();
        f.setLayout(gl1);
        f.setSize(250,250);
          WindowCloser wc=new WindowCloser();
        f.addWindowListener(wc);
        
        ScrollPane sp=new ScrollPane(ScrollPane.SCROLLBARS_NEVER);
        tf=new TextField();
        tf.setFont(fnt);
        //tf.setBackground(Color.yellow);
        sp.add(tf);
        f.add(sp);
        
        GridLayout gl2=new GridLayout(0,4);
        Panel p1=new Panel();
        p1.setLayout(gl2);
        Button b1=new Button("1");  b1.addActionListener(this);
        Button b2=new Button("2");  b2.addActionListener(this);
        Button b3=new Button("3");  b3.addActionListener(this); 
        Button b4=new Button("+");  b4.addActionListener(this);
        b1.setFont(fnt);
        b2.setFont(fnt);
        b3.setFont(fnt);
        b4.setFont(fnt);
        p1.add(b1);
        p1.add(b2);
        p1.add(b3);
        p1.add(b4);
        f.add(p1);
        
        Panel p2=new Panel();
        p2.setLayout(gl2);
        Button b5=new Button("4");   b5.addActionListener(this);
        Button b6=new Button("5");   b6.addActionListener(this);
        Button b7=new Button("6");   b7.addActionListener(this);
        Button b8=new Button("-");   b8.addActionListener(this);
        b5.setFont(fnt);
        b6.setFont(fnt);
        b7.setFont(fnt);
        b8.setFont(fnt);
        p2.add(b5);
        p2.add(b6);
        p2.add(b7);
        p2.add(b8);
        f.add(p2);
        
        Panel p3=new Panel();
        p3.setLayout(gl2);
        Button b9=new Button("7");    b9.addActionListener(this);
        Button b10=new Button("8");   b10.addActionListener(this);
        Button b11=new Button("9");   b11.addActionListener(this);
        Button b12=new Button("*");   b12.addActionListener(this);
        b9.setFont(fnt);
        b10.setFont(fnt);
        b11.setFont(fnt);
        b12.setFont(fnt);
        p3.add(b9);
        p3.add(b10);
        p3.add(b11);
        p3.add(b12);
        f.add(p3);
        
        Panel p4=new Panel();
        p4.setLayout(gl2);
        Button b13=new Button("C");    b13.addActionListener(this);
        Button b14=new Button("0");    b14.addActionListener(this);
        Button b15=new Button("/");    b15.addActionListener(this);
        Button b16=new Button("=");    b16.addActionListener(this);
        b13.setFont(fnt);
        b14.setFont(fnt);
        b15.setFont(fnt);
        b16.setFont(fnt);
        p4.add(b13);
        p4.add(b14);
        p4.add(b15);
        p4.add(b16);
        f.add(p4);
        
        f.setVisible(true);
       }
       
        public static int count=0;
         int temp;
          int temp1,sum,sub,div,mul;
        String op,result;
       public void actionPerformed(ActionEvent e)
       {
        String str=e.getActionCommand();
       

       
        if(str.equals("1"))
        {
        tf.setText("1");
        if(count==0)
        {
         temp=Integer.parseInt(str);
         count=1;
        }
        else
        {
        temp1=Integer.parseInt(str);
        count=0;
        }
       
        }
        else if(str.equals("2"))
        {
        tf.setText("2");
        if(count==0)
        {
         temp=Integer.parseInt(str);
         count=1;
        }
        else
        {
        temp1=Integer.parseInt(str);
        count=0;
        }
        }
        else if(str.equals("3"))
        {
        tf.setText("3");
        if(count==0)
        {
         temp=Integer.parseInt(str);
         count=1;
        }
        else
        {
        temp1=Integer.parseInt(str);
        count=0;
        }
        }
        else if(str.equals("4"))
        {
        tf.setText("4");
        if(count==0)
        {
         temp=Integer.parseInt(str);
         count=1;
        }
        else
        {
        temp1=Integer.parseInt(str);
        count=0;
        }
        }
        else if(str.equals("5"))
        {
        tf.setText("5");
        if(count==0)
        {
         temp=Integer.parseInt(str);
         count=1;
        }
        else
        {
        temp1=Integer.parseInt(str);
        count=0;
        }
        }
        else if(str.equals("6"))
        {
        tf.setText("6");
        if(count==0)
        {
         temp=Integer.parseInt(str);
         count=1;
        }
        else
        {
        temp1=Integer.parseInt(str);
        count=0;
        }
        }
        else if(str.equals("7"))
        {
        tf.setText("7");
        if(count==0)
        {
         temp=Integer.parseInt(str);
         count=1;
        }
        else
        {
        temp1=Integer.parseInt(str);
        count=0;
        }
        }
        else if(str.equals("8"))
        {
        tf.setText("8");
        if(count==0)
        {
         temp=Integer.parseInt(str);
         count=1;
        }
        else
        {
        temp1=Integer.parseInt(str);
        count=0;
        }
        }
        else if(str.equals("9"))
        {
        tf.setText("9");
        if(count==0)
        {
         temp=Integer.parseInt(str);
         count=1;
        }
        else
        {
        temp1=Integer.parseInt(str);
        count=0;
        }
        }
        else if(str.equals("0"))
        {
        tf.setText("0");
        if(count==0)
        {
         temp=Integer.parseInt(str);
         count=1;
        }
        else
        {
        temp1=Integer.parseInt(str);
        count=0;
        }
        }
        else if(str.equals("+"))
        {
        tf.setText("+");
           op=str;
        }
        else if(str.equals("-"))
        {
        tf.setText("-");
        op=str;
        }
        else if(str.equals("/"))
        {
        tf.setText("/");
        op=str;
        }
        else if(str.equals("*"))
        {
        tf.setText("*");
        op=str;
        }
        else if(str.equals("="))
        {
           if(op.equals("+"))
           {
            sum=temp+temp1;
            result=sum+"";
            tf.setText(result);
            temp=sum;
            count=1;
           }
           else if(op.equals("-"))
           {
            sub=temp-temp1;
            result=sub+"";
            tf.setText(result);
            temp=sub;
            count=1;
           }
           else if(op.equals("*"))
           {
            mul=temp*temp1;
            result=mul+"";
            tf.setText(result);
            temp=mul;
            count=1;
           }
           else if(op.equals("/"))
           {
            try
            {
              div=temp/temp1;
              result=div+"";
             tf.setText(result);
             temp=div;
            count=1;
            }
            catch(Exception e1)
            {
            tf.setText("Can't divide by Zero");
            }
           
           }
        }
        else if(str.equals("C"))
        {
        tf.setText("0");
        count=1;
        }
       
       }
        
         public static void main(String args[])
         {
          Calc cal=new Calc();
         }
        
        
    }

    Output :- 


    ShareThis