Tuesday 10 December 2013

Jackson Steaming API

Jackson Steaming API
Hello friends.hope you are fine  .today i am going to demonstrate how to process json data.there are various API's available in market ,here i am going to demonstrate you Jackson Streaming API Code.

it is  API used for processing json data.how ever it process the data/token  in incremental manner. it treats individual token as a element.it is faster & convinient way of processing json data.

below sample code  creates json file using Jackson Streaming API:


package org.demo;
import java.io.File;
import java.io.IOException;

import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;

public class JacksonReader
{

        public static void main(String []args) throws IOException
        {
            JsonFactory jfactory =new JsonFactory();
           
            JsonGenerator jgenerator=jfactory.createJsonGenerator(new File("D:\\ocjp\\Data.json"),JsonEncoding.UTF8);//used to write data in streaming way
           
                jgenerator.writeStartObject();//{
               
                jgenerator.writeStringField("Name","Akshita");//"Name":Akshita
               
                jgenerator.writeNumberField("Age",21);//"Age":21
               
       jgenerator.writeFieldName("hobby");//"messages" 
                jgenerator.writeStartArray(); //[
               
                jgenerator.writeString("Reading");//"Reading"
                jgenerator.writeString("Coding");//"Coding"
                jgenerator.writeString("Surfing");://"Surfing"
               
               
                jgenerator.writeEndArray(); //]
               
               
                jgenerator.close();//close the document
               
       
       
        }
}

Sample data.json file that will be generated after compiliation of the above code:

{ "Name":Akshita
 "Age":21 ,
"hobby":["Reading","Coding","Surfing"]
};

below code show how to read json data from json file:

import java.io.File;
import java.io.IOException;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonToken;
import org.codehaus.jackson.map.JsonMappingException;

public class JacksonStreamExample {
   public static void main(String[] args) {

     try {

    JsonFactory jfactory = new JsonFactory();

    /*** read from file ***/
    JsonParser jParser = jfactory.createJsonParser(new File("D://ocjp//Data.json"));

    // loop until token equal to "}"
    while (jParser.nextToken() != JsonToken.END_OBJECT) {

        String fieldname = jParser.getCurrentName();
        if ("Name".equals(fieldname)) {

         
          jParser.nextToken();
          System.out.println(jParser.getText());

        }

        if ("age".equals(fieldname)) {

         
          jParser.nextToken();
          System.out.println(jParser.getIntValue()); // display 29

        }

        if ("hobyy".equals(fieldname)) {

          jParser.nextToken(); // current token is "[", move next

          // messages is array, loop until token equal to "]"
          while (jParser.nextToken() != JsonToken.END_ARRAY) {

                     // display Reading,Surfing
             System.out.println(jParser.getText());

          }

        }

      }
      jParser.close();

     } catch (JsonGenerationException e) {

      e.printStackTrace();

     } catch (JsonMappingException e) {

      e.printStackTrace();

     } catch (IOException e) {

      e.printStackTrace();

     }

  }

}

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

Saturday 7 December 2013

Resource Injection (Using javax.annotation.Resource)


Resource Injection Using javax.annotation.Resource  



Basically we can inject
(1)Mail Session,
(2)Data Source,
(3)Jndi Resource it can be simple text or it can be beans etc.

Here i am going to Demonstrate MailSession Injection using glashfish server:


Hello friends.hope you all are fine.in this post i am going to demonstrate you how to inject MailSession that has been configured in glashfish server.i hope you are aware of how to define Java MailSession using glashfish server.

if you are not familiar with how to configure java mail session into glashfish than i should advice you to go through http://javaeenotes.blogspot.in/2010/04/using-javamail-api-with-glassfish-and.html.


i am posting sample code you can modify the below code as per the requirement:




package org.demo.Mail;

import javax.annotation.Resource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.util.*;


public class MailSender
{

    /**
     * @param args
     * @throws NamingException
     * @throws MessagingException
     */

//refers to myMailSession that has been configured in glashfish server.
    @Resource(name="mail/myMailSession")
    Session mailSession;
   
    public static void main(String[] args) throws NamingException, MessagingException
    {
       
       
       
               
       
        InitialContext ic = new InitialContext();//create the initcontext object
       

MyMailSession=Java Mail Session that has been configured into  Glashfish server.
        String snName = "java:comp/env/mail/MyMailSession";

       
       
        Session session = (Session)ic.lookup(snName);//get the resource from global JNDI
       
       
        Properties  props=session.getProperties();//get the Properties that you have defined in glashfish
       
       
        props.put("mail.from","********@gmail.com");//append extra property
        //[Note: when you are configuring properties you are configuring it as a mail-session which is interally converted into mail.session by server.so whatever property you want to define you can define it as a property-name pair.
       
        Message msg =new MimeMessage(session);//create message with Session


        msg.setSubject("Reminder");
           
        msg.setSentDate(new Date());
       
        msg.setRecipients(Message.RecipientType.TO,
                   InternetAddress.parse("****@gmail.com", false));
       
   
        msg.setText("hey guyzz");
       
        Transport.send(msg);
       
       
       
       
       
    }

}



Thanks a lot
for any query ping me on pathak.nisarg@yahoo.com

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


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...