Sunday 1 December 2013

Spring Mail Sender example

Sample Mail Sending Implementation  Using spring 3.0

hello friends i am going to present you a simple example of  how to send mail using spring.however you can also use java mail api to send mails.but spring is also providing inbuilt classes and interfaces through which you can send mail.

i am going to show you simple example of sending mail using gmail server .here it is:






package org.demo.mail;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import javax.naming.InitialContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailParseException;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Service;




@Service("mailService")
public class MailSendingService
{
   
     
    @Autowired
    private MailSender mailSender;
   
 
    private SimpleMailMessage preConfiguredMessage;
   
   
   
   
   
    public void sendMail(String to,String subject,String body)
    {
   
       
        SimpleMailMessage message=new SimpleMailMessage();
       
       
   
        message.setTo(to);
        message.setSubject(subject);
        message.setText(body);
       
        mailSender.send(message);
       
               
       
       
    }
   
    public void sendPreConfiguredMail(String message)
    {
        SimpleMailMessage sm=new SimpleMailMessage(preConfiguredMessage);
       
       
        sm.setText(message);
        mailSender.send(sm);
       
       
       
    }
   
   
   
   

}


Client class:
package org.demo.mail;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MailClient
{
   
    public static void main(String args[])
    {
   
        ApplicationContext context=new ClassPathXmlApplicationContext("Spring-Config.xml");
   
    MailSendingService mailer=(MailSendingService)context.getBean("mailService");
   
    mailer.sendMail("*******@gmail.com", "hi", "Done");
   
   
    mailer.sendPreConfiguredMail("Exception,try again ...!!! ");
   
   
 ;
   
   
   
   
    }

}


<?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:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd


http://www.springframework.org/schema/context


http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<context:component-scan base-package="org.demo.mail">

</context:component-scan>




<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">

         <property name="host" value="smtp.gmail.com"/>
        <property name="port" value="25"/>
        <property name="username" value="*********@gmail.com"/>
        <property name="password" value="**********"/>
        <property name="javaMailProperties">   
            <props>
                <prop key="mail.transport.protocol">smtp</prop>
                <prop key="mail.smtp.auth">true</prop>
                <prop key="mail.smtp.starttls.enable">true</prop>
                <prop key="mail.debug">true</prop>
            </props>
        </property>
       
        </bean>
       
       
       
       
       

<bean id="preConfiguredMessage" class="org.springframework.mail.SimpleMailMessage">

<property name="to" value="********@gmail.com"></property>
<property name="from" value="*******@gmail.com"></property>
<property name="subject" value="Fatal"></property>
</bean>

</beans>

thanks
for any query ping me @  pathak.nisarg@yahoo.com

Wednesday 27 November 2013

Javax.sql.DataSource implementation

Javax.Sql.DatSource implementation

Hello friends ..today i am going to demonstrate you implementation of javax.sql.DataSource. Apache do have its own connection pooling implementation called as BasicDataSource.you can use this implementation for defining  DataSource Configuration & inject it into SessionFactory .

in this example i am demonstarting the implementation of DataSource which is commonly used for Connection Pooling purpose.it reduces number of active connections required .every time Application gets deployed into application server ,it is the responsibility of container to provide Connection  whenever required . well i am referring this concept as caching.simply because whenever you need connection object ,container have it ,what it is doing is simply giving you copy of connection object back.

DataSource implementation is Container Manged Object.in this example i am defining Connection object into server.xml which will be placed in META-INF.


Pojo Class
package org.demo;

public class Customer
{
   
    private int id;
    private String name;
    private String address;
   
   
    public int getId()
    {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
   
   

}

Context.xml file
<?xml version="1.0" encoding="UTF-8"?>

<context>

<Resource name="jdbc/Mydb" auth="Container" type="javax.sql.DataSource"
               maxActive="50" maxIdle="30" maxWait="10000"
               username="app" password="app"
               driverClassName="org.apache.derby.jdbc.ClientDriver "
               url="jdbc:derby://localhost:1527/sample"/>
   </context>




web.xml file 
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Jndiq1</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
 
  <resource-ref>
    <description>Apache derby DataSource Example</description>
    <res-ref-name>jdbc/Mydb</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
  </resource-ref>
</web-app>


hope you have understand the concept
thanks
for any query ping me on pathak.nisarg@yahoo.com

Tuesday 26 November 2013

JNDI example of org.apache.naming.factory.BeanFactory

Hello friends . i am posting Feature Related to JNDI(Java Naming & Directory Service).i hope you are aware of Bean Factory Design Pattern where as custom object is pooled up & given back to consumer.
you can  do same functionality using Jndi.

before going through the code you should be familiar with org.apache.naming.factory.BeanFactory & basics of server.xml which should be placed in META-INF.


what is required is a single html form inoder to make
I am posting code as given below :

server.xml code

<?xml version="1.0" encoding="UTF-8"?>
<Context>
  ...
  <Resource name="bean/MyBeanFactory" auth="Container"
            type="org.model.MyBean"
            factory="org.apache.naming.factory.BeanFactory"
            bar="23"/>
 
</Context>

here is Traditional example of pojo class :
package org.model;

public class MyBean
{
   
    private String foo = "Default Foo";

      public String getFoo() {
        return (this.foo);
      }

      public void setFoo(String foo) {
        this.foo = foo;
      }

      private int bar = 0;

      public int getBar() {
        return (this.bar);
      }

      public void setBar(int bar) {
        this.bar = bar;
      }


}
By Defining Resource into server.xml you are declaring  JNDI object on server side .inorder to actually get that resource into web application you need to have resource.you can get this resource by writing following code into web.xml :

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
 
  <display-name>ServletJpa</display-name>
 
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
  <servlet>
 
  
 
  <servlet>
    <servlet-name>ResourceFactory</servlet-name>
    <servlet-class>org.model.ResourceFactory</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>ResourceFactory</servlet-name>
    <url-pattern>/resource/</url-pattern>
  </servlet-mapping>
 
  <resource-env-ref>
    <description>Object factory for MyBean instances.</description>
   
    <resource-env-ref-name>bean/MyBeanFactory</resource-env-ref-name>
   
    <resource-env-ref-type>
    org.model.MyBean
  </resource-env-ref-type>
  </resource-env-ref>
 
</web-app>

now you can have bean/MyBeanFactory resource.inorder to actually call that resource you should make a referance to jndi object as follows:

package org.model;

import java.io.IOException;
import java.io.PrintWriter;



import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * Application Lifecycle Listener implementation class ResourceFactory
 *
 */
@WebListener
public class ResourceFactory extends HttpServlet
{

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    /**
     * Default constructor.
     */
    public ResourceFactory() {
        // TODO Auto-generated constructor stub
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
       
        PrintWriter out=response.getWriter();

       
        try
        {
            Context initCtx;
            initCtx = new InitialContext();
            Context envCtx = (Context) initCtx.lookup("java:comp/env");
            MyBean bean = (MyBean) envCtx.lookup("bean/MyBeanFactory");
           
            out.println("foo = " + bean.getFoo() + ", bar = " +
                    bean.getBar());
        } catch (NamingException e)
        {
            // TODO Auto-generated catch block
               e.printStackTrace();
        }
       

       

   
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

   
   
}





Hope you  can understand my post.
thanks
for any query ping me on nppathak90@gmail.com


Monday 25 November 2013

Custom Tag using Tag Library

Custom Tag Full Example 

 

hello friends.i am posting a very simple example of how to make custom  Tag using servlet -jsp code.this is fun..what is required is given below:
(1) you need to define servlet that extends TagSupport class


(2)define .tld file into web-inf.where all configuration related to tag library is placed.

(3) Referance the tag library configuration file into jsp  as given below:

<%@taglib uri="/WEB-INF/demo.tld" prefix="sample" %>

sample  Servlet code :
package org.demo.customtag;

import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
//tag handler

public class Hello extends TagSupport
{

    /**
     *
     */
    private static final long serialVersionUID = 1L;
   
    private String name=null;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    //CALLED BY JSP CONTAINER WHEN IT ENCOUNTER STARTING CUSTOM TAG
    public int doStartTag()
    {
        try
        {
            JspWriter out=pageContext.getOut();
           
           
            out.println("<table border='1'>");
            if(name!=null)
           
                    out.println("<tr><td> Hello"+name+"</td></tr>");
                    else
                        out.println("<tr><td> Hello world </td></tr>");
           
           
        }
        catch(Exception e)
        {
            throw new Error("All is not well dude");
        }
       
        return SKIP_BODY;
    }
   
    //CALLED BY JSP CONTAINER WHEN IT ENCOUNTER CLOSING CUSTOM TAG
    public int  doEndTag()
    {
        try
        {
            JspWriter out = pageContext.getOut();
               out.println("</table>");
           
        }
        catch(Exception e)
        {   
            throw new Error("All not well dude");
        }
       
        return EVAL_PAGE;
    }
   
   

   
   
}
there are two enumerations SKIP_BODY & EVAL_PAGE is used in code :

first enumeration will be used to skip the body straight away after start custom tag is encountered.jsp container will not execute  doStartTag()  after it finds starting of custom tag.
EVAL_PAGE if defined in methdod than rest of the jsp code which is defined will continue to execute.




demo

Demo.xml file under WEB-INF 

<?xml version="1.0" encoding="UTF-8"?>
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.1</jspversion>
<shortname>hello</shortname>
<info>Sample taglib for Substr operation</info>
<uri>http://nisargpathakblogspot.com</uri>
<tag>
    <name>substring</name>
    <tagclass>org.demo.customtag.Hello</tagclass>
    <info>Helloworld Function</info>
   
    <attribute>
      <name>name</name>
      <required>true</required>
  </attribute>
  
</tag>
</taglib>


Hello.html



<%@taglib uri="/WEB-INF/demo.tld" prefix="sample" %>
<html>
        <head>
                <title>Custom Tag Demo </title>
        </head>
        <body bgcolor="#ffffff">
                <hr />
               
           
               <sample:substring name="Akansha Dave"></sample:substring>
              
                <hr />
        </body>
</html>

hope you got it ..
for any query ping me on pathak.nisarg@yahoo.com

Sunday 24 November 2013

Connection Pooling

Connection Pooling Using Hibernate 


Hello friends .Hope you all aware with Connection Pooling .if you are not than i am suggesting you to go through( https://docs.jboss.org/hibernate/core/4.1/devguide/en-US/html/ch01.html ).there are several ways through which we can pool the Connection Object into java Application.i am demonstrating you to pool Connection Resource using Hibernate.C3P0 Utility is used to manage Number of Connections.you need to add it into Classpath.

First of all you need to create Model class.hope you are aware of various annotations provied by hibernate & i am  using apache derby Database.well i am not suggesting you to use Built in Derby that is bundled with java  6.0 .Still to Demonstrate the Concept i am using Apache Derby :

in above example i am using Annotation based Hibernate Configuration.
package org.Model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;


@Entity
@Table(name="Employee")
public class Employee
{
   
   
    @Column
    private int id;
    @Column
    private String name;
    @Column
    private String address;
   
   
    public Employee() { }
    public int getId()
    {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }

 }
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>
<!--Driver class to conenct Derby Database  -->
  <property name="hibernate.connection.driver_class">org.apache.derby.jdbc.ClientDriver</property>
<!--Connection url referring to datatbase MyDb-->
  <property name="hibernate.connection.url">jdbc:derby://localhost:1527/MyDb;create=true</property>
  <property name="hibernate.dialect">org.hibernate.dialect.DerbyDialect</property>
   <property name="show_sql">true</property>
   <property name="hbm2ddl.auto">create</property>
   <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

  <property name="hibernate.c3p0.min_size">5</property>
  <property name="hibernate.c3p0.max_size">20</property>
  <property name="hibernate.c3p0.timeout">300</property>
  <property name="hibernate.c3p0.max_statements">50</property>
  <property name="hibernate.c3p0.idle_test_period">3000</property>

 
  </session-factory>
</hibernate-configuration>

Client Class
package org.Model;

import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;

public class Client
{

   
    @SuppressWarnings("deprecation")
    public static void main(String[] args)
    {
          
        SessionFactory sessionfactory=null;
        Session s=null;
      
        try
        {
        /*AnnotationConfiguration config = new AnnotationConfiguration();
        config.addClass(org.Model.Employee.class);*/
        //SessionFactory sessionFactory = config.buildSessionFactory();
      
      
        sessionfactory=new AnnotationConfiguration().configure().buildSessionFactory();
         s=sessionfactory.openSession();
      
      
            Employee e= new Employee();
            e.setId(1);
            e.setName("Apeksha");
            e.setAddress("Bangalore");
          
            s.beginTransaction();
          
                s.save(e);
              
            s.getTransaction().commit();
          
        }
        catch(Exception e)
        {
                System.out.println("Error in creating  Session Factory");
        }
            if(s!=null)
            {
                s.close();
              
            }
          
   }

}
This is how Connection Pooling will be done.Connection pooling improves the performace of Database by simply reducing number of connections required to connect to Database.

Thanks

for Any Query Please Mail me on nppathak90@gmail.com


Friday 22 November 2013

JDOM Parser full Example

hello friends i am posting here awesome example of  Jdom Parser using which we can Marshall/unmarshall java objects into/from xml .

We can use Differant API's for converting java object tree into xml or vice versa

Jdom parser is java based Document object Model  Parser using which we can parse xml data .i am demostrating simple example which will be used to marshel and unmarshel java objects:

The sample xml file which i am using is as follows:

<?xml version="1.0"?>
<company>
<staff>
<firstname>nisarg</firstname>
<lastname>mook kim</lastname>
<nickname>mkyong</nickname>
<salary>100000</salary>
</staff>
<staff>
<firstname>low</firstname>
<lastname>yin fong</lastname>
<nickname>fong fong</nickname>
<salary>200000</salary>
</staff>
</company>



the class will placed in org.jdom package :

package org.jdom;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import java.io.*;
import java.util.*;

//jdom parser implementation

public class ReadXml
{

public static void main(String args[])
{


SAXBuilder  builder =new SAXBuilder();

File xmlFile=new File("D:\\company.xml");


try
{

Document document =(Document)builder.build(xmlFile);

Element rootNode =document.getRootElement();

List list=rootNode.getChildren();

for(int i=0;i<list.size();i++)
{
Element node =(Element) list.get(i);


  System.out.println("First Name : " + node.getChildText("firstname"));
  System.out.println("Last Name : " + node.getChildText("lastname"));
  System.out.println("Nick Name : " + node.getChildText("nickname"));
  System.out.println("Salary : " + node.getChildText("salary"));








}


}
catch(IOException ie)
{


System.out.println(ie.getMessage());
}
catch(JDOMException e)
{
System.out.println(e.getMessage());
}



}

}

=> example of  converting java object tree into xml file :

package org.demo;

import java.io.FileWriter;
import java.io.IOException;

import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;


//jdom parser(Dom) will load entire document into memory


public class XmlFileCreator
{

public static void main(String args[]) throws IOException
{
final String XmlFilePath="D:\\ocjp\\EmployeeData.xml";

try
{
Element company =new Element("company");
Document document =new Document(company);

Element employee =new Element("employee");

employee.addContent(new Element("firstname").setText("kesha"));
employee.addContent(new Element("lastname").setText("pathak"));
employee.addContent(new Element("department").setText("Computer"));
employee.addContent(new Element("age").setText("23"));



document.getRootElement().addContent(employee);

Element employee1 = new Element("employee");
       
employee1.setAttribute(new Attribute("id", "2"));
        employee1.addContent(new Element("firstname").setText("John"));
        employee1.addContent(new Element("lastname").setText("Filis"));
     employee1.addContent(new Element("department").setText("Human Resources"));
      employee1.addContent(new Element("age").setText("28"));
   
      document.getRootElement().addContent(employee1);
   
      XMLOutputter xml=new XMLOutputter();
   
      xml.setFormat(Format.getPrettyFormat());
   
      xml.output(document,new FileWriter(XmlFilePath));
   

      System.out.println("XML File was created successfully!");
   

}

catch(Exception e)
{

}
}

}


<?xml version="1.0" encoding="UTF-8"?>
<company>
  <employee>
    <firstname>kesha</firstname>
    <lastname>pathak</lastname>
    <department>Computer</department>
    <age>23</age>
  </employee>
  <employee id="2">
    <firstname>John</firstname>
    <lastname>Filis</lastname>
    <department>Human Resources</department>
    <age>28</age>
  </employee>
</company>

this is how JDOM works
The basic differance between Jdom & other parser is it loads entire document into memory.so that if size of xml is small than in that case it is more preferable.
ThAnks

Sunday 17 November 2013

Easy way of Marshalling /unmarshalling JAVA Objects

awesome stuff ..among the most parser this is the very easy way to marshal & unmarshal java object .no need to have sax or dom parser ..you can enjoy this lib
 
 
class Company{
    String name;
    Employee employees[];

    Company(String name, Employee... employees){
        this.name = name;
        this.employees = employees;
    }
}
class Employee{
    String id;
    String name;
    String email;
    int age;

    Employee(String id, String name, String email, int age){
        this.id = id;
        this.name = name;
        this.email = email;
        this.age = age;
    }
}
 
 
 
 
import jlibs.xml.sax.XMLDocument;
import javax.xml.transform.stream.StreamResult;
XMLDocument xml = new XMLDocument(new StreamResult(System.out), false, 4, null);
xml.startDocument();{
    xml.startElement("company");{
        xml.addAttribute("name", company.name);
        for(Employee emp: company.employees){
            xml.startElement("employee");{
                xml.addAttribute("id", emp.id);
                xml.addAttribute("age", ""+emp.age);
                xml.addElement("name", emp.name);
                xml.addElement("email", emp.email);
            }
            xml.endElement("employee");
        }
    }
    xml.endElement("company");
}
xml.endDocument(); 

Spring Boot SSL configuration -Tomcat Server

Hi Friends hope you all are doing well. Today I am going to demonstrate about how to configure SSL in Spring boot web Application. Need o...