Saturday, 14 May 2016

How to Find Duplicate String in Java

Since we all known HashSet is a part of Collection that will store unique value always 
>  if we are trying to add any duplicate value add method return  false.
> add Method check existing Object Hashcode and compare with  newly added Object
if hashCode match then add method Return False else Return True .
>here we created HashSet<String> Object with generic type data type
>since we Added <String> After HashSet then it only allows to add String value
>generic type is only use to overcome data type casting problem 
..
Please Check below programmer 




/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javainterview;
import java.util.*;

/**
 *
 * @author shiboo
 */
public class Duplicate {
    
    public static void main(String[] args) {
        
        String [] arr= {"Anand","Ajeet","Antrish","Anand"};
        HashSet<String>hset= new HashSet<String>();
        for(String value:arr){
        if(!hset.add(value)){
            System.out.println("Duplicate Value=>"+value);
        }
        }
        
    }
    
}


Thursday, 21 April 2016

parse JSON in Java

How to parse json in java .? Add org.json lib into your project 


public class PraseJSON {
    public static void main(String[] args) throws JSONException {
       String json = "{\n"
                + "   \"Name\": {\n"
                + "         \"Place\": \"Bangalore\",\n"
                + "         \"Age\": \"23\"\n"
                + "    }}";
              
               // + "}";

        PraseJSON classObject = new PraseJSON();
        JSONObject obj = new JSONObject(json);
        String name = obj.getJSONObject("Name").getString("Place");
        System.out.println("Name::"+name);


}}

How to Create JSON in Java ?

we can easily create JSON in java Using org.json.simple library .so build this jar into your application .

  • Create JSONObject  :

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

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("Name", "Anand");
        jsonObject.put("Age", new Integer(23));
        jsonObject.put("Married",new Boolean(false));


     System.out.println(jsonObject); 
/*

{"Married":false,"Age":23,"Name":"Anand"}

*/

}

  • Create JSONArray : 
 
public class JSON{
 public static void main(String[] args) {

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("Name", "Anand");
        jsonObject.put("Age", new Integer(23));
        jsonObject.put("Married",new Boolean(false));

     JSONArray jsonarray = new JSONArray();
        jsonarray.add(jsonObject);//


     System.out.println(jsonarray); 
/*
 [{"Married":false,"Age":23,"Name":"Anand"}]
*/

}


 

Wednesday, 10 February 2016

Full String Class Method is Java

Here is the List of Methods than can be applicable With String class . please Check Below Programme
===============================================================
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Com.interview;

import java.util.Locale;


/**

 *
 * @author anand
 */
public class StringFullMethod {
    
    public static void main(String[] args) {
        
        String s = "Anand";
        System.out.println(s.charAt(1));
        System.out.println(s.chars());
        System.out.println(s.codePointAt(1));
        System.out.println(s.codePointBefore(2));
        System.out.println(s.codePointCount(1, 3));
        System.out.println(s.codePoints());
        System.out.println(s.compareTo("Antrish"));
        System.out.println(s.compareToIgnoreCase("anand"));
        System.out.println(s.concat(" Dwivedi"));
        System.out.println(s.contains("An"));
        System.out.println(s.contentEquals("Anand"));
        System.out.println(s.contentEquals(new StringBuffer("Antrish")));
        System.out.println(s.endsWith("d"));
        System.out.println(s.equals(s));
        System.out.println(s.getBytes().length);
        System.out.println(s.getClass());
        System.out.println(s.hashCode());
        System.out.println(s.indexOf("A"));
        System.out.println(s.indexOf(1));
        System.out.println(s.indexOf("n", 2));
        System.out.println(s.intern());
        System.out.println(s.isEmpty());
        System.out.println(s.lastIndexOf("a"));
        System.out.println(s.lastIndexOf("n", 1));
        System.out.println(s.length());
        System.out.println(s.matches("Anand"));
        System.out.println(s.offsetByCodePoints(1, 2));
        System.out.println(s.replace("A", "a"));
        System.out.println(s.replaceAll("Anand", "Antrish"));
        System.out.println(s.replaceFirst("A", "n"));
        System.out.println(s.split("").length);
        System.out.println(s.toCharArray());
        System.out.println(s.toLowerCase());
        System.out.println(s.toLowerCase(Locale.GERMANY));
        System.out.println(s.toString());
        System.out.println(s.toUpperCase());
        System.out.println(s.toUpperCase(Locale.FRENCH));
        System.out.println(s.trim());
       
    }
}

O/P

n
java.util.stream.IntPipeline$Head@b4c966a
110
110
2
java.util.stream.IntPipeline$Head@4e50df2e
-19
0
Anand Dwivedi
true
true
false
true
true
5
class java.lang.String
63402602
0
-1
3
Anand
false
2
1
5
true
3
anand
Antrish
nnand
5
Anand
anand
anand
Anand
ANAND
ANAND
Anand

BUILD SUCCESSFUL (total time: 0 seconds)


Tuesday, 25 August 2015

Online Book Store Website Using Java

===============================================
Login.html:-
================================================
<html>
    <title>|| Login Page ||</title>
    <body class="bod">
        <form action='login.action'  method="post">
            <table align='center'>
                <tr><td colspan='2' align='center'>
                        <br></br>
                        <h2 style="color: black; font-size: 30px; padding-top: 1%;" class="Head">User Login</h2></td></tr>

                <tr>
                    <td><h2>UserName</h2></td>
                    <td><input type='text' name='UserName' placeholder="UserName" autocomplete="off" required=""/></td></tr>
                <tr>
                    <td><h2>password</h2></td>
                    <td><input type='password' name='Password' placeholder="password" autocomplete="off" required=""/></td></tr>
                <tr>
                    <td align="center" colspan=2><input type='submit' value='Submit' style="background-color: indianred" class="But"/></td></tr>
            </table>
            <div id="footerbottom">
                <div class="footerwrap">
                    <div id="copyright">2015 - Designed By -Anand Dwivedi.<a href="http://learnjavabyanand.blogspot.in/" target="_blank"><img src="test.png" width="150" height="28" border="0"  /></a></div>

                </div>
            </div>
        </form>
        <style type="text/css">

            .formd{
                background-color: darkcyan;
                text-align: center;
                alignment-adjust: center;
                margin-left: 42%;

            }
            .bod{
                background-color:darkcyan;
                text-align: center;
                margin-top: 13%;
            }
            .tb{
                alignment-adjust: center;
                alignment-baseline: central;
            }
            .But{
                margin-top: 9%;
            }
            .footerwrap{
                background-color: #7a7a7a;
                position:absolute;
                bottom:0;
                width:100%;
                left:  -0.5px;
                height:50px; 
                text-align: center;

            }
            .Head{
                background-color: #7a7a7a;
                position:absolute;
                top: -23px;
                width: 100%;
                left: -0.5;
                height: 50px;
                text-align: center;

            }

        </style>
    </body>
</html>
================================================
Session.html:-
================================================
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
  
    <body>
        <form action="TestBook.action" method="post" >
        <input type="button" name="Click Here to Check Session" value="Click Here to Check Session"/>
    </form>
        </body>
   
</html>
================================================
Index.jsp
================================================
<%--
    Document   : newjspTest
    Created on : Aug 7, 2015, 3:15:17 PM
    Author     : ananddw
--%>


<html>
    <body class="bod">
        <title>|| Select Book || </title>
    <center>
        <h1 style="color: black; font-size: 30px; padding-top: 1%;" class="Head"> BookStore</h1>

        <form action="searchbook.action" method="post" class="formd" >
            <table class="tb">
                <tr>
                    <td style="alignment-adjust: center; text-align:center; color: darkgrey;"><h2>Select Category</h2>
                    </td>
                </tr>
                <tr>
                    <td><select name="category" style="background-color: mediumpurple">
                            <option value="Select">Select</option>
                            <option value="Java">Java</option>
                            <option value="Testing">Testing</option>
                            <option value=".NET">.NET</option>
                            <option value="SAP">SAP</option>
                        </select></td>
                </tr>
                <br></br>
                <tr>
                    <td><input type="submit" value="SearchBooks"  style="background-color: indianred" class="But">
                    </td>
                </tr>
            </table>


            <table class="tb" align="right">
                <tr>
                    <td>
                        <h1>
                            Total Visited :<%=application.getAttribute("TV")%>
                        </h1></td>
                </tr>
                <tr>
                    <td>
                        <h1>
                            Total Active :<%=application.getAttribute("TA")%>
                        </h1></td>
                </tr>
            </table>

            <a href="logout.action" class="logout">LOGOUT</a>






            <div id="footerbottom">
                <div class="footerwrap">
                    <div id="copyright">2015 - Designed By -Anand Dwivedi.<a href="http://learnjavabyanand.blogspot.in/" target="_blank"><img src="test.png" width="150" height="28" border="0"  /></a></div>

                </div>
            </div>
        </form>
        <style type="text/css">
            .formd{
                background-color: darkcyan;
                text-align: center;
                alignment-adjust: center;
                margin-left: 42%;

            }
            .bod{
                background-color:darkcyan;
                text-align: center;
                margin-top: 5%;
            }
            .tb{
                alignment-adjust: center;
                alignment-baseline: central;
            }
            .But{
                margin-top: 20%;
            }
            .footerwrap{
                background-color: #7a7a7a;
                position:absolute;
                bottom:0;
                width:100%;
                left:  -0.5px;
                height:50px; 
                text-align: center;

            }
            .Head{
                background-color: #7a7a7a;
                position:absolute;
                top: -23px;
                width: 100%;
                left: -0.5;
                height: 50px;
                text-align: center;
            }
            .logout{

                position:absolute;
                top: -23px;
                width: 10%;
                left: -0.5;
                height: 50px;
               text-decoration-color: aqua;
                margin-left: 88%;
            margin-top: 4%;
            }
        </style>
    </center>
</body>
</html>
================================================
logout.jsp
================================================
<%@ page session="false"%>
<html>
    <body class="bod">
        <table align="right" class="tb">
            <tr>
                <td>
                    <h3>
                        Total Visited :<%=application.getAttribute("TV")%>
                    </h3></td>
            </tr>
            <tr>
                <td>
                    <h3>
                        Total Active :<%=application.getAttribute("TA")%>
                    </h3></td>
            </tr>
        </table>
        <br />
        <br />
        <h2>You have logged out successfully</h2>
        <br />
        <br />
        <a href="Login.html">Go To Login Page</a>

        <div id="footerbottom">
            <div class="footerwrap">
                <div id="copyright">2015 - Designed By -Anand Dwivedi.<a href="http://learnjavabyanand.blogspot.in/" target="_blank"><img src="test.png" width="150" height="28" border="0"  /></a></div>

            </div>
        </div>
    </body>
    <style type="text/css">
        .formd{
            background-color: darkcyan;
            text-align: center;
            alignment-adjust: center;
            margin-left: 42%;

        }
        .bod{
            background-color:darkcyan;
            text-align: center;
            margin-top: 5%;
        }
        .tb{
            alignment-adjust: center;
            alignment-baseline: central;
        }

        .footerwrap{
            background-color: #7a7a7a;
            position:absolute;
            bottom:0;
            width:100%;
            left:  -0.5px;
            height:50px; 
            text-align: center;

        }
        .Head{
            background-color: #7a7a7a;
            position:absolute;
            top: -23px;
            width: 100%;
            left: -0.5;
            height: 50px;
            text-align: center;
        }

    </style>
</html>
==============================================
placeorder.jsp
==============================================
<%--
    Document   : newjspTest
    Created on : Aug 7, 2015, 3:50:05 PM
    Author     : ananddw
--%>

<%@ page import="java.util.*"%>
<html>
    <title>|| Place Order ||</title>
    <body  class="bod">
    <center>

        <h2 class="Head">Book Search</h2>
        <h1 class="Header">Your order has been Done !</h1>
        <%
            session.invalidate();
        %>
        <br /> <a href="index.jsp">GO TO SEARCH PAGE</a>

    </center>
    <div id="footerbottom">
        <div class="footerwrap">
            <div id="copyright">2015 - Designed By -Anand Dwivedi.<a href="http://learnjavabyanand.blogspot.in/" target="_blank"><img src="test.png" width="150" height="28" border="0"  /></a></div>

        </div>
    </div>
        <style type="text/css">
            .Head{
                background-color: #7a7a7a;
                position:absolute;
                top: -29px;
                width: 100%;
                left: -0.5;
                height: 50px;
                text-align: center;
                color: black;
                font-size: 30px;
                padding-top: 1%;
                margin-left: -13px;
            }
            .footerwrap{
                background-color: #7a7a7a;
                position:absolute;
                bottom:0;
                width:100%;
                left:  -0.5px;
                height:50px; 
                text-align: center;

            }
            .Header{
                text-align: center;
                text-decoration-color: deeppink;
                margin-top: 17%;
            }
            .bod{
                background-color:darkcyan;
                text-align: center;
                margin-top: 20%;
            }
        </style>
    </body>
</html>
===============================================
showBooks.jsp
===============================================
<%--
    Document   : newjspTest
    Created on : Aug 7, 2015, 3:42:52 PM
    Author     : ananddw
--%>


<%@ page import="java.util.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <title>|| Show Books ||</title>
    <body class="bod">
        <center>
            <h2 class="Head">Book Search</h2>
            <br></br>
            <font color="lightblue" size="6"> ${ADDED} </font>
        </center>
        <br />
        <%
            Object obj = request.getAttribute("MSG");
            if (obj != null) {
        %>
        <br />
        <center>
            <font color="lightgreen" size="6"><%=obj%></font> <br />
            <a href="index.jsp"> <h2>Go To Search Page</h2>
            </a>
        </center>
        <%
        } else {
            obj = session.getAttribute("Books");
            ArrayList<String> blist = (ArrayList<String>) obj;
            for (String bnm : blist) {
        %>
        <form action="addtocart.action" method="post">
            <input type="hidden" name="bname" value="<%=bnm%>" /> <font size="5"><%=bnm%>
                <input type="submit" value="Add to Cart" class="add">
            </font>
        </form>
        <%
            }
        %>
        <br />
        <form action="showcart.action">
            <input type="submit" value="Show Cart" class="But"/>
        </form>
        <%
            }
        %>

        <div id="footerbottom">
            <div class="footerwrap">
                <div id="copyright">2015 - Designed By -Anand Dwivedi.<a href="http://learnjavabyanand.blogspot.in/" target="_blank"><img src="test.png" width="150" height="28" border="0"  /></a></div>

            </div>
            <style type="text/css">
                .footerwrap{
                    background-color: #7a7a7a;
                    position:absolute;
                    bottom:0;
                    width:100%;
                    left:  -0.5px;
                    height:50px; 
                    text-align: center;

                }
                .Head{
                    background-color: #7a7a7a;
                    position:absolute;
                    top: -29px;
                    width: 100%;
                    left: -0.5;
                    height: 50px;
                    text-align: center;
                    color: black;
                    font-size: 30px;
                    padding-top: 1%;
                    margin-left: -13px;
                }
                .bod{
                    background-color:darkcyan;
                    text-align: center;
                    margin-top: 5%;
                }
                .But{
                    margin-top: 5%;
                    background-color: indianred;
                }
                .add{
                    background-color: lightskyblue;
                }
            </style>
    </body>
</html>
==============================================
showcart.jsp
==============================================
<%--
    Document   : newjspTest
    Created on : Aug 7, 2015, 3:48:02 PM
    Author     : ananddw
--%>

<%@ page import="java.util.*"%>
<html>
    <title>|| Show Cart||</title>
    <body  class="bod">
    <center>

        <h2 class="Head">Book Search</h2>
    </center>
    <%Object obj = request.getAttribute("MSG");
        if (obj != null) {
    %>
    <br/><center><font color="red" size="6"><%=obj%> </font></center>
        <%
        } else {
            obj = request.getAttribute("CART");
            ArrayList<String> blist = (ArrayList<String>) obj;
            for (String bnm : blist) {
        %>
    <form action="removefromcart.action" method="post">
        <input type="hidden" name="bname" value="<%=bnm%>"/>
        <font size="5"><%=bnm%><input type="submit"  value="Remove from CART" class="But"/></font>
    </form>
    <%
        }
    %>
    <br/>
    <center><a href="placeorder.jsp">PLACE ORDER</a></center>
        <%
            }
        %><center>
        <br/><a href="showbooks.jsp">ADD TO CART</a>
    </center>

    <div id="footerbottom">
        <div class="footerwrap">
            <div id="copyright">2015 - Designed By -Anand Dwivedi.<a href="http://learnjavabyanand.blogspot.in/" target="_blank"><img src="test.png" width="150" height="28" border="0"  /></a></div>

        </div>
        <style type="text/css">
            .Head{
                background-color: #7a7a7a;
                position:absolute;
                top: -29px;
                width: 100%;
                left: -0.5;
                height: 50px;
                text-align: center;
                color: black;
                font-size: 30px;
                padding-top: 1%;
                margin-left: -13px;
            }
            .footerwrap{
                background-color: #7a7a7a;
                position:absolute;
                bottom:0;
                width:100%;
                left:  -0.5px;
                height:50px; 
                text-align: center;

            }
            .bod{
                background-color:darkcyan;
                text-align: center;
                margin-top: 5%;
                float: left;
                padding-left: 38%;
                padding-top:10%;
            }
            .But{
                margin-top: 5%;
                background-color: indianred;
            }
        </style>
    </body>
</html>


======Server Side Code AddToCartServlet================
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.servlets;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
/**
 *
 * @author ananddw
 */

public class AddToCartServlet extends HttpServlet {
     /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */

    protected void service(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        // Accessing the existing session object
        HttpSession sess = req.getSession(false);
        // Validating session are available or not
        if (sess == null) {
            req.setAttribute("MSG", "Session is Destroyed");
        } else {
            String bnm = req.getParameter("bname");
            // Accessing the client selected Book to session
            sess.setAttribute(bnm, bnm);
            req.setAttribute("ADDED", bnm + " is added to cart");
            System.out.println("Calling ADDtoCart Servlet Class ");
        }
        RequestDispatcher rd = req.getRequestDispatcher("showbooks.jsp");
        rd.forward(req, res);
        System.out.println("Request forward to Showbooks.jsp from Addtocard servlet class");
    }

}

======Server Side Code Loginservlet================

package com.servlets;

import java.io.IOException;
import java.io.Writer;
import javax.servlet.RequestDispatcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class Loginservlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        System.out.println("Calling Method !!");
        //collecting the client submit the data
        String un = req.getParameter("UserName");
        String pwd = req.getParameter("Password");
        String msg = "";
        if (un.equals(pwd)) {
            msg = "<body bgcolor=darkgreen><h1 align=center><font color=red>Login success!!!!!!!!! Welcome to To Book Store </font></h1></body>";

        } else {
            msg = "Invlid login!!!Try again";
        }
       
        RequestDispatcher rd = req.getRequestDispatcher("index.jsp");
       
        rd.forward(req, res);
        System.out.println("Forward Sucessfully ");
        Writer out = res.getWriter();
        out.write(msg);
        HttpSession session = req.getSession();
        System.out.println("Session from Servlet Class===>"+session);
    }
}
======Server Side Code LogoutServlet================
package com.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LogoutServlet extends HttpServlet {
    protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    HttpSession sess=req.getSession(false);
    if(sess!=null)
        sess.invalidate();
    RequestDispatcher rd=req.getRequestDispatcher("logout.jsp");
    rd.forward(req, res);
    }

}
======Server Side Code MyContextListener================

package com.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class MyContextListener implements ServletContextListener {
      public void contextInitialized(ServletContextEvent event) {
    System.out.println("**ContextInitialized***");
    ServletContext ctx=event.getServletContext();
    ctx.setAttribute("TV", 0); 
    ctx.setAttribute("TA", 0); 
    }
    public void contextDestroyed(ServletContextEvent arg0) {
    System.out.println("***contextDestroyed**");
    }
   
}
======Server Side Code MySessionListener================


package com.servlets;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class MySessionListener implements HttpSessionListener {
    public void sessionCreated(HttpSessionEvent event) {
    HttpSession sess=event.getSession();
        System.out.println("session Called===>"+sess);
    ServletContext ctx=sess.getServletContext();
    int tv=(Integer) ctx.getAttribute("TV");
    tv++;
    ctx.setAttribute("TV", tv);
    int ta=(Integer) ctx.getAttribute("TA");
    ta++;
    ctx.setAttribute("TA", ta);
    }
    public void sessionDestroyed(HttpSessionEvent event) {
    HttpSession sess=event.getSession();
    ServletContext ctx=sess.getServletContext();
    int ta=(Integer) ctx.getAttribute("TA");
    ta--;
    ctx.setAttribute("TA",ta);
   
    }
   
}

======Server Side Code RemoveFromCartServlet================

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.servlets;

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

import javax.servlet.*;
import javax.servlet.http.*;
/**
 *
 * @author ananddw
 */

public class RemoveFromCartServlet extends HttpServlet {
     /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void service(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        HttpSession sess = req.getSession(false);
        if (sess == null) {
            req.setAttribute("MSG", "Session is distroyed");
        } else {
            String bnm = req.getParameter("bname");
            // Removing the client selected book from session
            sess.removeAttribute(bnm);
                        System.out.println("Remove Book form Session");
        }
        RequestDispatcher rd = req.getRequestDispatcher("showcart.action");
        rd.forward(req, res);
                System.out.println("request forward to Showcart using RemoveFormCartServlet Class");
    }
       

}

======Server Side Code SearchBookServlet================

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.servlets;

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

import javax.servlet.*;
import javax.servlet.http.*;
/**
 *
 * @author ananddw
 */

public class SearchBookServlet extends HttpServlet {
     /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */

    protected void service(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        String cat = req.getParameter("category");
        if (cat != null && cat.equals("Java")) {
            ArrayList<String> blist = new ArrayList<String>();
            blist.add("Java");
            blist.add("Jdbc");
            blist.add("Servlet");
            blist.add("Jsp");
            blist.add("Ejb");
            blist.add("RMI");
            blist.add("HTML");
            HttpSession sess = req.getSession();
            System.out.println("Session Called?" + sess);
            sess.setAttribute("Books", blist);
            System.out.println("Session After set Attribute?" + sess);
        } else {
            req.setAttribute("MSG", "No books found with category" + cat);
        }
        RequestDispatcher rd = req.getRequestDispatcher("showbooks.jsp");
        rd.forward(req, res);
       
        System.out.println("Request Forward to showbooks.jsp page using SearchBooksServlet class");
    }

}

======Server Side Code SessionTrack================

 package com.servlets;


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

// Extend HttpServlet class
public class SessionTrack extends HttpServlet {

    public void doGet(HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException, IOException {
        // Create a session object if it is already not  created.
        HttpSession session = request.getSession(true);
        // Get session creation time.
        Date createTime = new Date(session.getCreationTime());
        // Get last access time of this web page.
        Date lastAccessTime
                = new Date(session.getLastAccessedTime());

        String title = "Welcome Back to my website";
        Integer visitCount = new Integer(0);
        String visitCountKey = new String("visitCount");
        String userIDKey = new String("userID");
        String userID = new String("ABCD");

        // Check if this is new comer on your web page.
        if (session.isNew()) {
            title = "Welcome to my website";
            session.setAttribute(userIDKey, userID);
        } else {
            visitCount = (Integer) session.getAttribute(visitCountKey);
            visitCount = visitCount + 1;
            userID = (String) session.getAttribute(userIDKey);
        }
        session.setAttribute(visitCountKey, visitCount);

        // Set response content type
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        String docType
                = "<!doctype html public \"-//w3c//dtd html 4.0 "
                + "transitional//en\">\n";
        out.println(docType
                + "<html>\n"
                + "<head><title>" + title + "</title></head>\n"
                + "<body bgcolor=\"#f0f0f0\">\n"
                + "<h1 align=\"center\">" + title + "</h1>\n"
                + "<h2 align=\"center\">Session Infomation</h2>\n"
                + "<table border=\"1\" align=\"center\">\n"
                + "<tr bgcolor=\"#949494\">\n"
                + "  <th>Session info</th><th>value</th></tr>\n"
                + "<tr>\n"
                + "  <td>id</td>\n"
                + "  <td>" + session.getId() + "</td></tr>\n"
                + "<tr>\n"
                + "  <td>Creation Time</td>\n"
                + "  <td>" + createTime
                + "  </td></tr>\n"
                + "<tr>\n"
                + "  <td>Time of Last Access</td>\n"
                + "  <td>" + lastAccessTime
                + "  </td></tr>\n"
                + "<tr>\n"
                + "  <td>User ID</td>\n"
                + "  <td>" + userID
                + "  </td></tr>\n"
                + "<tr>\n"
                + "  <td>Number of visits</td>\n"
                + "  <td>" + visitCount + "</td></tr>\n"
                + "</table>\n"
                + "</body></html>");
    }
}
==================Server Side ShowCartServlet============

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.servlets;

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

import javax.servlet.*;
import javax.servlet.http.*;
/**
 *
 * @author ananddw
 */

public class ShowCartServlet extends HttpServlet {
     /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */

    protected void service(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        HttpSession sess = req.getSession();
        if (sess == null) {
            req.setAttribute("MSG", "Session is destroyed");
            RequestDispatcher rd = req.getRequestDispatcher("showbooks.jsp");
            rd.forward(req, res);
        } else {
            Enumeration<String> enms = sess.getAttributeNames();
            List<String> selectedlist = Collections.list(enms);
            selectedlist.remove("Books");
            if (selectedlist.size() == 0) {
                req.setAttribute("MSG", "No Books selected");
            } else {
                req.setAttribute("CART", selectedlist);
            }
            RequestDispatcher rd = req.getRequestDispatcher("showcart.jsp");
            rd.forward(req, res);
            System.out.println("Calling ShowCart Class and revert back on showcart.jsp");
        }
    }
   

}
=======================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_2_5.xsd"
         id="WebApp_ID" version="2.5">
    <display-name>Lab18</display-name>
    <welcome-file-list>
        <welcome-file>Login.html</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>SBServ</servlet-name>
        <servlet-class>com.servlets.SearchBookServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>SBServ</servlet-name>
        <url-pattern>/searchbook.action</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>ATocServ</servlet-name>
        <servlet-class>com.servlets.AddToCartServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ATocServ</servlet-name>
        <url-pattern>/addtocart.action</url-pattern>
    </servlet-mapping>
    <servlet>

        <servlet-name>SCServ</servlet-name>
        <servlet-class>com.servlets.ShowCartServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>SCServ</servlet-name>
        <url-pattern>/showcart.action</url-pattern>
    </servlet-mapping>
    <servlet>

        <servlet-name>RemoveFromCartServlet</servlet-name>
        <servlet-class>com.servlets.RemoveFromCartServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>RemoveFromCartServlet</servlet-name>
        <url-pattern>/RemoveFromCartServlet</url-pattern>
    </servlet-mapping>
    <servlet>

        <servlet-name>RFCServ</servlet-name>
        <servlet-class>com.servlets.RemoveFromCartServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>RFCServ</servlet-name>
        <url-pattern>/removefromcart.action</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>loginservlet</servlet-name>
        <servlet-class>com.servlets.Loginservlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>loginservlet</servlet-name>
        <url-pattern>/login.action</url-pattern>

    </servlet-mapping>
    <servlet>
        <servlet-name>logoutServ</servlet-name>
        <servlet-class>com.servlet.LogoutServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>logoutServ</servlet-name>
        <url-pattern>/logout.action</url-pattern>
    </servlet-mapping>
    <listener>
        <listener-class>com.servlet.MyContextListener</listener-class>
    </listener>
    <listener>
        <listener-class>com.servlet.MySessionListener</listener-class>
    </listener>
</web-app>



Thursday, 13 August 2015

How to Create PDF File Using Java Code

package com.anand;

import com.lowagie.text.Document;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Date;

public class GeneratePDF {

    public static void main(String[] args) {
        try {
            OutputStream file = new FileOutputStream(new File("/home/ananddw/test.pdf"));
            Document document = new Document();
            PdfWriter.getInstance(document, file);
            document.open();
            document.add(new Paragraph("welcome Anand in the World of PDF "));
          
            document.close();
            file.close();

        } catch (Exception e) {

            e.printStackTrace();
        }
    }
}

===============================================
Attach Some Require Jar else you will get error 

Thanks 
Anand Dwivedi

Wednesday, 22 July 2015

How to append Same File name With Date Append in Java?

Please Find Code Below :

==================Append.java=======================
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;

/**
 *
 * @author ananddw
 */
public class Append {

    public static void main(String[] args) throws IOException {
        /*

         Date date = new Date();
        File file1 = new File("/home/ananddw/Anand.json");
        String file2 = file1.getParent().toString();
        System.out.println("file 2 call ===>" + file2);
        boolean b = false;
        if (!(file1.exists())) {
            b = file1.createNewFile();
        }
        if (b) {
            System.out.println("Empty File successfully created");
        } else {

            String fileContent = "";
              String filename = file1.toString() + date;

            try {
                File f = new File(file1.toString());

                FileInputStream inp = new FileInputStream(f);

                byte[] bf = new byte[(int) f.length()];

                inp.read(bf);

                fileContent = new String(bf, "UTF-8");

                System.out.println("file===>" + fileContent);

            } catch (FileNotFoundException e) {

            } catch (IOException e) {
            }
            System.out.println("file name in else===>" + filename);
            FileWriter fw = new FileWriter(filename, true);
            System.out.println("FileWriter===>"+fw);
            String see = null;
            fw.write("Test");
            fw.close();
            System.out.println("Failed to create File");

        }

    }
}

Map class field to map

 import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; public class AutogeneratedClassMapper {     public static M...