Custom Search

Wednesday 23 October 2013

Write a Java Program to Demonstrate the use of JavaServer Pages Standard Tag Library(JSTL)

Aim: Demonstrate use of JSTL.
Index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSTL DEMO</title>
    </head>
    <body>
        <h1>Hello World!</h1>
        <a href="XMLDemo.jsp">XMLDemo</a>
        <a href="SQLDemo.jsp">SQLDemo</a>
        <a href="COREDemo.jsp">COREDemo</a>
        <a href="FUNCTIONDemo.jsp">FUNCTIONDemo</a>
        <a href="CUSTOMDemo.jsp">CUSTOMDemo</a>
    </body>
</html>

COREDEMO.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>Core Demo</h1><hr>
        <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
        <h4>c-out Demo..<br/>
        <c:out value="6"></c:out></h4>
        <c:set var="x" value="10"></c:set><br/>
        <c:if test="${x eq 10}">
            <h4>If Condition Checked..<br/>
                Value of x is..<br/>
            <c:out value="${x}"></c:out>
            </h4>
        </c:if>
    </body>
</html>
SQLDEMO.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib  prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>SQL Demo</h1>
        <hr>
        <c:catch>
            <sql:setDataSource
                var="datasourceobj"
                driver="com.mysql.jdbc.Driver"
                url="jdbc:mysql://localhost/book"
                user="root"  password="root"/>
<sql:query var="resultsetobj"
                       dataSource="${datasourceobj}">
                Select * from book
            </sql:query>
<table border="1">
                <c:forEach var="row" items="${resultsetobj.rows}" >
                    <br>
                    <tr>
                        <th>Book</th>
    <td> <c:out value="${row.bookname}" /></td>
   <td><c:out value="${row.title}" /></td>
                        <td><c:out value="${row.author}" /></td>
                    </tr>    
            </c:forEach>
        </table>
    </c:catch>
    Exception is : ${e}
</body>
</html>

FUNCTIONDEMO.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>Function Demo</h1>
    <c:set var="string1" value="This is Example of Function."/>
    <p>Original String:${string1}</p><br/>
    <hr>
<c:set var="string2" value="${fn:toUpperCase(string1)}" />
<c:set var="string3" value="${fn:toLowerCase(string1)}" />
<p>toUpper : ${string2}</p>
<p>toLower : ${string3}</p>
<p>Index of 'Example' : ${fn:indexOf(string1, "Example")}</p>
</body>
</html>
XMLDEMO.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/xml" prefix="x" %>
<html>
  <head>
    <title>For Each Examples</title>
  </head>
<body>
      <c:set var="students">
        <students>
   <student id="1">
      <name>
         <first>A</first>
         <last>B</last>
         <middle>T</middle>
      </name>
      <grade>
         <points>88</points>
         <letter>B</letter>
      </grade>
   </student>
   <student id="2">
      <name>
         <first>C</first>
         <last>D</last>
         <middle>K</middle>
      </name>
      <grade>
         <points>92</points>
         <letter>A</letter>
      </grade>
   </student>
   <student id="3">
      <name>
         <first>E</first>
         <last>F</last>
         <middle>A</middle>
      </name>
      <grade>
         <points>72</points>
         <letter>C</letter>
      </grade>
   </student>
</students>
      </c:set>
    <%--<c:import var="students" url="http://localhost:8080/students.xml" />
--%>
<x:parse var="doc" xml="${students}" />
      <table>
      <x:forEach var="student" select="$doc/students/student">
        <tr>
          <td>
            <x:out select="$student/name/first" />
          </td>
<td>
            <x:out select="$student/name/last" />
          </td>
 <td>
            <x:out select="$student/grade/points" />
          </td>
<td>
            <x:out select="$student/grade/letter" />
          </td>
        </tr>
      </x:forEach>
    </table>
  </body>
</html>

CUSTOMDEMO.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<%@taglib prefix="mine" uri="/WEB-INF/tlds/custom" %>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>CUSTOM Demo</h1>
        <hr>
        <mine:custom user="${name}">
         </mine:custom>
    </body>
</html>

Custom tag descriptor:
<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.1" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd">
  <tlib-version>1.0</tlib-version>
  <uri>/WEB-INF/tlds/custom</uri>
  <tag>
  <name>custom</name>
  <tag-class>customClass</tag-class>
  <attribute>
  <name>user</name>
  </attribute>
  </tag>
</taglib>

Custom class
import javax.servlet.jsp.tagext.*;
public class customClass extends SimpleTagSupport{
   public String user;
@Override
public doTag() throws SimpleTagJSPexception,IOexception{
 return getJSPContext().getOut().Write("hello"+user);
}
void setuser(string user){
    this.user=user;
}
}

Write a simple servelet prog which maintain counter for the no of times it has been accessed since its loading , initialize counter using deployment descriptor.

Aim: Write a simple servelet prog which maintain counter for the no of times it has been accessed since its loading , initialize counter using deployment descriptor.

File Name:Counter.java

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Counter extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{     response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet Counter</title>");
out.println("</head>");
           out.println("<body>");
           out.println("<h1>"+"No. Of Visitors:");
           out.println(RequestHandler.getreqcnt()+"</h1>");
           out.println("<h1>"+"No. Of activated Sessoin:");
           out.println(RequestHandler.getreqsc() +"</h1>");
           out.println("</body>");
           out.println("</html>");
            }  finally {
 out.close();
        }
   }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
    @Override
    public String getServletInfo() {
        return "Short description";
    }
}

File Name: RequestHandler.java

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class RequestHandler implements ServletRequestListener,HttpSessionListener{
    static int cnt ,sc;
    public void requestDestroyed(ServletRequestEvent sre) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
    public void requestInitialized(ServletRequestEvent sre) {
          cnt++;
    }
    public void sessionCreated(HttpSessionEvent se) {
               sc++;
    }
    public void sessionDestroyed(HttpSessionEvent se) {
           sc--;
    }
  public static int getreqcnt() {
        return cnt;
    }
    public static int getreqsc() {
        return sc;
    }
}


Web.XML
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <listener>
        <listener-class>RequestHandler</listener-class>
    </listener>
    <servlet>
        <servlet-name>Counter</ servlet-name>
        <servlet-class>Counter</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Counter</servlet-name>
        <url-pattern>/Copunter</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

Write an RMI application where client supplies a string and server responds by sending the string in upper case. (Topics covered: Distributed application using java.rmi package )

Aim: Write an RMI application where client supplies a string and server responds by sending the string in upper case. (Topics covered: Distributed application using java.rmi package )

Client.java
import java.rmi.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
public class Client extends JFrame {
    TextField t1 = new TextField(30);
    TextField t2 = new TextField(30);
   
    JButton b = new JButton("Uppercase");
    Panel p = new Panel(new GridLayout(4, 1, 5, 5));
    RemoteInterface2 s;
     public Client() {
        super("Client Side");
        setSize(250, 250);
        setLocation(300, 300);
        getContentPane().add(p, "North");
        p.add(t1);
        p.add(t2);
        p.add(b);
      try {
            String ipp = JOptionPane.showInputDialog("Please enter the IP Address to Connect");
            String ip = "rmi://" + ipp + "/RMIAPPLICATION";
            s = (RemoteInterface2) Naming.lookup(ip);

        } catch (Exception exp) {
            JOptionPane.showMessageDialog(null, exp.getMessage());
        }
    b.addActionListener(new ActionListener() {
       public void actionPerformed(ActionEvent evt) {
            String a = t1.getText();
try {
                        String r = s.upper(a);
                        t2.setText("String in  =" + r);
                 } catch (Exception epx) {
                }
            }
        });
    }
     public static void main(String args[]) {
        Client c = new Client();
        c.setDefaultCloseOperation(EXIT_ON_CLOSE);
        c.setVisible(true);
    }
}

Server.java
import java.rmi.*;
import java.net.*;

public class Server {

    public static void main(String args[]) {
        try {
            ServerImplements s = new ServerImplements();
            Naming.rebind("RMIAPPLICATION", s);
            System.out.println("Server has been started");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}

Remoteinterface
import java.rmi.*;

public interface RemoteInterface2 extends Remote
{
  public String upper(String x) throws Exception;
}

ServerImplements
import java.rmi.*;
import java.rmi.server.*;


public class ServerImplements extends UnicastRemoteObject implements
        RemoteInterface {

    public ServerImplements() throws Exception {
        super();
    }

public String upper(String x) throws Exception {
        String y = x.toUpperCase();
        return y;
    }
}

Write a java application which implements client and server sockets using TCP protocol.

Aim: Write a java application which implements client and server sockets using TCP protocol.

TCPServer.java
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.net.*;
import java.io.*;
class TCPServerS extends JFrame {
    JTextArea jta;
    JButton btnSend;
    JTextField jtf;
    ServerSocket ss;
    Socket serverSocket;
    JLabel lblIpl;
    JTextField tfIp;
    JLabel lblPort;
    JTextField tfPort;
    TCPServerS() {
        super("Server");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new GridLayout(2, 1));
        setSize(500, 500);
        JPanel p1 = new JPanel(new FlowLayout());
        JPanel p2 = new JPanel(new FlowLayout());
        jta = new JTextArea(10, 20);
        jta.setEditable(false);
        lblPort = new JLabel("Enter Port");
        tfPort = new JTextField(5);
        lblPort.setSize(10, 10);
        tfPort.setSize(10, 10);
        p1.add(lblPort);
        p1.add(tfPort);
        p1.add(new JScrollPane(jta));
        btnSend = new JButton("Send");
        btnSend.addActionListener(new SendHandler());
        jtf = new JTextField(20);
        jtf.addActionListener(new SendHandler());
        p2.add(jtf);
        p2.add(btnSend);
        add(p1);
        add(p2);
        setVisible(true);
        tfPort.addActionListener(new PorHandler());
        while (true) {
            recieve();
        }
    }
 class PorHandler implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            try {
                String s = startServer(Integer.parseInt(tfPort.getText()));
                System.out.println(s);
            } catch (Exception ex) {
            }
        }
    }
    private String startServer(int port) throws Exception {
        ss = new ServerSocket(port);//enter port number.
        serverSocket = ss.accept();
        return "Started";
    }
    private void recieve() {
        try {
            DataInputStream dis = new DataInputStream(serverSocket.getInputStream());
            InetAddress i = serverSocket.getInetAddress();
            String host = i.getHostAddress();
            String str = dis.readUTF();//return string
            jta.append(host+" : "+str + "\n");
        } catch (Exception ex) {
        }
    }
    class SendHandler implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            try {
                DataOutputStream dos = new DataOutputStream(serverSocket.getOutputStream());
                dos.writeUTF(jtf.getText());
                jta.append("Me : "+jtf.getText()+"\n");
                jtf.setText(null);
            } catch (Exception e1) {
            }
        }
    }
}
class ServerMain {
    public static void main(String[] args) {
        TCPServerS ch = new TCPServerS();
    }
}
TCPClient.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.io.*;
class TCPClient extends JFrame {
    JTextArea jta;
    JButton btnSend;
    JButton btnConnect;
    JTextField jtf;
    JLabel lblPort;
    JLabel lblIP;
    JTextField tfPort;
    JTextField tfIp;
    JLabel lblConnect;
    Socket clientSocket;
    TCPClient() {
        super("Client");
        try {
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            setLayout(new GridLayout(1, 2));
            setSize(460, 320);
            JPanel p1 = new JPanel();
            lblConnect = new JLabel();
            lblIP = new JLabel("IP Address :");
            lblPort = new JLabel("Port :");
            tfIp = new JTextField(10);
            tfPort = new JTextField(10);
            jta = new JTextArea(10, 35);
            jta.setEditable(false);
            btnConnect = new JButton("Connect");
            btnSend = new JButton("Send");
            btnSend.addActionListener(new SendHandler());
            btnConnect.addActionListener(new ConnectHandler());
            jtf = new JTextField(20);
            jtf.addActionListener(new SendHandler());
            p1.add(lblIP);
            p1.add(tfIp);
            p1.add(lblPort);
            p1.add(tfPort);
            p1.add(btnConnect);
            p1.add(lblConnect);
            p1.add(new JScrollPane(jta));
            p1.add(jtf);
            p1.add(btnSend);
            add(p1);
            setVisible(true);
            while (true) {
                recieve();
            }
        } catch (Exception e3) {
        }
   }
    public String connect(String ip, int port) throws Exception {
        clientSocket = new Socket(ip, port);
        return "connected";
    }
 public void recieve() {
        try {
            DataInputStream dis = new DataInputStream(clientSocket.getInputStream());
            InetAddress i = clientSocket.getInetAddress();
            String h = i.getCanonicalHostName();
            String str = dis.readUTF();
            jta.append(h + ": " + str + "\n");
        } catch (Exception e5) {
        }
    }
    class SendHandler implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            try {
                DataOutputStream dos = new DataOutputStream(clientSocket.getOutputStream());
                dos.writeUTF(jtf.getText());
                jta.append("Me:" + jtf.getText() + "\n");
                jtf.setText(null);
            } catch (Exception e1) {
            }
        }
    }
    class ConnectHandler implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            try {
                String str = connect(tfIp.getText(), Integer.parseInt(tfPort.getText()));
                lblConnect.setText(str);
                System.out.print(str);
            } catch (Exception e2) {
            }
        }
    }
}
class ClientMain {
    public static void main(String[] args) {
        TCPClient c = new TCPClient();
    }
}

Write a java application which implements client and server sockets using UDP protocol


Aim: Write a java application which implements client and server sockets using UDP protocol
UDPclient.java
import javax.swing.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
public class UDPClient {
    JFrame frame;
    JPanel panel;
    JTextField field1, field2;
    JTextArea area;
    JScrollPane pane;
    JLabel label;
    JButton button;
     public static void main(String[] args) {
        UDPClient u = new UDPClient();
    }
        public UDPClient() {
        frame = new JFrame("Text Client");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setUndecorated(true);
        frame.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
        panel = new JPanel();
        panel.setLayout(null);
        label = new JLabel("Desination IP:");
        label.setBounds(10, 20, 100, 30);
        panel.add(label);
        field1 = new JTextField(20);
        field1.setBounds(125, 25, 150, 20);
        panel.add(field1);
        label = new JLabel("Destination Port:");
        label.setBounds(10, 50, 100, 30);
        panel.add(label);
        field2 = new JTextField(10);
        field2.setBounds(125, 55, 100, 20);
        panel.add(field2);
        area = new JTextArea();
        pane = new JScrollPane(area);
        pane.setBounds(10, 100, 300, 200);
        panel.add(pane);
        button = new JButton("Send");
        button.setBounds(235, 310, 75, 30);
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                new SendRequest();
            }
        });
        panel.add(button);
        frame.add(panel);
        frame.setSize(400, 400);
        frame.setVisible(true); }
public class SendRequest {
        SendRequest() {
            try {
                DatagramSocket socket;
                DatagramPacket packet;
                InetAddress address;
                socket = new DatagramSocket();
                String dip = field1.getText();
                address = InetAddress.getByName(dip);
                String port = field2.getText();
                int pnum = Integer.parseInt(port);
                String mess = area.getText();
                byte message[] = mess.getBytes();
                System.out.println(mess + "Byte " + message);
                packet = new DatagramPacket(message, message.length, address, pnum);
                socket.send(packet);
                area.setText("");
                socket.close();
            } catch (IOException io) {
            }
        }}
}
UDPserver.java
import javax.swing.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
public class UDPServer {
    JFrame frame;
    JPanel panel;
    JButton button1, button2;
    JTextArea area;
    JScrollPane pane;
    Thread thread;
    DatagramSocket socket;
      public static void main(String[] args) {
        UDPServer u = new UDPServer();
    }
       public UDPServer() {
        frame = new JFrame("Text Server");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setUndecorated(true);
        frame.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
        panel = new JPanel();
        panel.setLayout(null);
        area = new JTextArea();
        button1 = new JButton("Start");
        button1.setBounds(210, 10, 75, 40);
        button1.addActionListener(new ActionListener() {
 public void actionPerformed(ActionEvent ae) {
                new StartThread();   }
        });
        panel.add(button1);
        button2 = new JButton("Stop");
        button2.setBounds(300, 10, 75, 40);
        button2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                Thread.interrupted();
                socket.close();
                area.append("Server is stopped\n");
                button1.setEnabled(true);
                button2.setEnabled(false);
            }
        });
        button2.setEnabled(false);
        panel.add(button2);
        pane = new JScrollPane(area);
        pane.setBounds(10, 60, 365, 250);
        panel.add(pane);
        frame.add(panel);
        frame.setSize(400, 400);
        frame.setVisible(true);
    }
  public class StartThread implements Runnable {
  StartThread() {
            thread = new Thread(this);
            thread.start();
            button1.setEnabled(false);
            button2.setEnabled(true);
        }
public void run() {
            try {
                byte[] buffer = new byte[1024];
                int port = 3333;
                try {
                    socket = new DatagramSocket(port);
                    while (true) {
                        try {
                            area.append("Server is started\n");
                            DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
                            socket.receive(packet);
                            InetAddress client = packet.getAddress();
                            int clientPort = packet.getPort();
                            String message = new String(packet.getData(),0,packet.getLength()) ;
                            area.append(" Received " + message + " from " + client+":"+clientPort);
                        } catch (UnknownHostException ue) {
                        }
                    }
                } catch (java.net.BindException b) {
                }
            } catch (IOException e) {
                System.err.println(e);
            }
        }
    }
}

Output:
     

Create an application in GUI that executes select statement and list all records from DB. Also Update and Delete records according to Student ID. Enter query in text field, create button for executing that query and display result in text field.

Aim: Create an application in GUI that executes select statement and list all records from DB. Also Update and Delete records according to Student ID. Enter query in text field, create button for executing that     query and display result in text field.

File Name:Tabedpan.java
       package tabedpan;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.Statement;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager.*;
public class Tabedpan extends JFrame{
private class addhandler implements ActionListener {
 public addhandler() {  
        }
@Override
        public void actionPerformed(ActionEvent e)
        {   try {
                System.out.print("added!!");
   String query ="insert into `student`(`Name`,`ID`,`Phone`) values ( '"+tf2.getText()+"',NULL,'"+   tf4.getText()+"')";
                Statement stmt =(Statement) cn.createStatement();
                stmt.execute(query);
            } catch (SQLException ex) {
                Logger.getLogger(Tabedpan.class.getName()).log(Level.SEVERE, null, ex);
           }
   }
}
private class deletehandler implements ActionListene{
       public deletehandler() {
        }
       @Override
        public void actionPerformed(ActionEvent e) {
            try {
                System.out.print("deleted!!");
                String query ="delete from `student` where `ID`='"+tf5.getText()+"';";
                   PreparedStatement pstmt = (PreparedStatement) cn.prepareStatement(query);
                   pstmt.execute(query);
            } catch (SQLException ex) {
                Logger.getLogger(Tabedpan.class.getName()).log(Level.SEVERE, null, ex);
            }
       }
    }
private class updatehandler implements ActionListener {
        private java.sql.PreparedStatement pstmt;
           private updatehandler() {
          }
@Override
        public void actionPerformed(ActionEvent e) {
            try {
               System.out.print("updated1!!");
       String query ="update `student` set `Name`='"+tf12.getText()+"',`ID`='"+tf13.getText()+"',`Phone`='"+tf14.getText()+"' where `ID`='"+tf13.getText()+"';";
               PreparedStatement pstmt = (PreparedStatement) cn.prepareStatement(query);
               pstmt.execute(query);
               System.out.print(tf12.getText());
               System.out.print(tf14.getText());
            } catch (SQLException ex) {
                Logger.getLogger(Tabedpan.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
 }
    JPanel p1;
    JPanel p2;
    JPanel p3;
    JPanel p4;
     JTextField tf6;
    JTabbedPane tp;
    Connection cn;
    JTextArea ta;
    public Tabedpan() {
        try {
             this.setName("Tabedpane");
             this.setSize(800, 700);
             p1=new JPanel();
            p2=new JPanel();
            p3=new JPanel();
            p4=new JPanel();
            p10=new JPanel();
            p11=new JPanel();
            p12=new JPanel();
            p13=new JPanel();
            p5=new JPanel();
            p6=new JPanel();
            p7=new JPanel();
            p8=new JPanel();
            p9=new JPanel();
            l1=new JLabel("Enter Name");
            l2=new JLabel("Enter ID");
            l3=new JLabel("Enter Phn no");
            l11=new JLabel("Enter Name");
            l12=new JLabel("Enter ID");
            l13=new JLabel("Enter Phn no");
            b1=new JButton("Select");
            b2=new JButton("Update");
            b3=new JButton("Delete");
            b4=new JButton("Add");
            b5=new JButton("Execute");
            tp=new JTabbedPane();
            tf1=new JTextField("Enter select query");
          // tf6=new JTextField("Enter any query");
            tf2=new JTextField("Enter name");
            tf3=new JTextField("Enter id");
            tf4=new JTextField("Enter phn no");
            tf12=new JTextField("Enter name");
            tf13=new JTextField("Enter id");
            tf14=new JTextField("Enter phn no");
            tf5=new JTextField("Enter name");
            ta= new  JTextArea(10, 10);
            p1.add(ta);
            tp.addTab("Select",p1);
            tp.addTab("Update",p6);
            tp.addTab("Delete",p3);
            tp.addTab("Add",p10);
            this.add(tp);
            Class.forName("com.mysql.jdbc.Driver");
            cn = (Connection) DriverManager.getConnection("jdbc:MySql://localhost:3306/student", "root", "root");
            System.out.println("Connection Established");
            p1.setLayout(new FlowLayout(FlowLayout.LEFT, 25, 10));      
            p1.add(tf1);      
            p1.add("Select",b1);
            b1.addActionListener(new Submithandler());
            b2.addActionListener(new updatehandler());
            b3.addActionListener(new deletehandler());
            b4.addActionListener(new addhandler());
            p6.setLayout(new FlowLayout(FlowLayout.LEFT, 20, 10));
            p2.setLayout(new GridLayout(3,1));
            p7.setLayout(new FlowLayout(FlowLayout.LEFT, 55, 10));
            p8.setLayout(new FlowLayout(FlowLayout.LEFT, 75, 10));
            p9.setLayout(new FlowLayout(FlowLayout.LEFT, 50, 10));
            p2.add(p7);
            p2.add(p8);
            p2.add(p9);
            p7.add(l11);
            p8.add(l12);
            p9.add(l13);
            p6.add(p2);
            p7.add(tf12);
            p8.add(tf13);
            p9.add(tf14);
            p6.add("Update",b2);
            p3.setLayout(new FlowLayout(FlowLayout.LEFT, 25, 10));
            p3.add(tf5);
            p3.add("Delete",b3);        
            p10.setLayout(new FlowLayout(FlowLayout.LEFT, 20, 10));
            p4.setLayout(new GridLayout(3,1));
            p11.setLayout(new FlowLayout(FlowLayout.LEFT, 55, 10));
            p12.setLayout(new FlowLayout(FlowLayout.LEFT, 75, 10));
            p13.setLayout(new FlowLayout(FlowLayout.LEFT, 50, 10));
            p4.add(p11);
            p4.add(p12);
            p4.add(p13);
            p11.add(l1);
            p12.add(l2);
            p13.add(l3);
            p10.add(p4);
            p11.add(tf2);
            p12.add(tf3);
            p13.add(tf4);
            p10.add("Add",b4);
            p5.setLayout(new FlowLayout(FlowLayout.LEFT, 25, 10));
//            p5.add(tf6);
            p5.add("Execute",b5);
            this.setVisible(true);
        } catch (SQLException ex) {
            Logger.getLogger(Tabedpan.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Tabedpan.class.getName()).log(Level.SEVERE, null, ex);
         }
}
public class Submithandler implements ActionListener{
 @Override
        public void actionPerformed(ActionEvent e) {
            try {
                String query =tf1.getText();
                Statement stmt = (Statement) cn.createStatement();
                ResultSet rs = stmt.executeQuery(query);
                     while (rs.next()) {
                    String s=ta.getText();
                    String s1=rs.getString(1) + "\n"+rs.getInt(2) +"\n"+ rs.getInt(3)+ "\n"+ "\n";
                    ta.setText(s + s1 +" \n");
                    System.out.print("Name   " + rs.getString("Name") + "\n");
                    System.out.print("Id  " + rs.getInt(2) + "\n");
                    System.out.print("phn No   " + rs.getInt(3) + "\n \n");
                  }
              } catch (SQLException ex) {
                Logger.getLogger(Tabedpan.class.getName()).log(Level.SEVERE, null, ex);
                }
           }
      }
      public static void main(String[] args) {
        Tabedpan td=new Tabedpan();
         }
       }

Create an application to demonstrate the use of following GUI components & event handling. 1)Menu 2) Menuitem 3) Frame 4) FileDialog 5) FileChooser 6) TextField 7) Button 8) RadioButton 9) TextArea 10) Graphics 11) Look & Feel 12) Layout Manager 13) JTable 14) JScrollPanel

Aim: Create an application to demonstrate the use of following GUI components & event handling.
1)Menu  2) Menuitem  3) Frame 4) FileDialog 5) FileChooser 6) TextField  7) Button 8) RadioButton  9) TextArea 10) Graphics 11) Look & Feel 12) Layout Manager 13) JTable 14) JScrollPanel

 Code:-
File:- guiComponent.java
 package GuiComponent;
import com.sun.java.swing.plaf.motif.MotifLookAndFeel;
import com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel;
import com.sun.java.swing.plaf.windows.WindowsLookAndFeel;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
public class guiComponent extends JFrame implements ActionListener, ItemListener
 {
    MenuBar mb;
    Menu menuFile, menuDraw;
    Menu jmLooknFeel;
    MenuItem miExit, miOpen, miOvel, miCircle, miSqare, i5;
    JLabel lbName, lbAddress, lbSub, lbGender;
    JTextField tfName;
    JTextArea taAddress, ta2;
    JRadioButton rbMale, rbFemale;
    JCheckBox cbDotNet, cbAJT, cbCD, act, cbMC, cbSeminar;
    JButton btnSubmit, btnClear;
    ButtonGroup bgGender;
    JPanel p1, p2, p3, p4, p5, p6;
    String gen;
    String Subjects;
    String fname;
    String fpath;
    MyCanvac m;
    DefaultTableModel dtm;
    JTable tb;
    Vector v;
    MenuItem jmiLookWindow;
    MenuItem jmiLookMatif;
    MenuItem jmiLookNimbus;
    WindowsLookAndFeel windowsLF;
    MotifLookAndFeel motifLF;
    NimbusLookAndFeel nimbusLF;
public guiComponent()
{
        this.setTitle("GUI Component");
        this.setVisible(true);
        this.setSize(500, 500);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLayout(new GridLayout(7, 1, 5, 5));
           //menu item and menus...
        menuFile = new Menu("File");
        menuDraw = new Menu("Draw");
        jmLooknFeel = new Menu("Look And Feel");
        mb = new MenuBar();
        miExit = new MenuItem("Exit");
        miOpen = new MenuItem("Open");
        miOvel = new MenuItem("Ovel");
        miCircle = new MenuItem("Circle");
        miSqare = new MenuItem("Squar");
        windowsLF = new WindowsLookAndFeel();
        motifLF = new MotifLookAndFeel();
        nimbusLF = new NimbusLookAndFeel();
         //Student info
        lbName = new JLabel("Student Name:");
        lbAddress = new JLabel("Address");
        lbSub = new JLabel("Subject Offered");
        tfName = new JTextField(20);
        taAddress = new JTextArea("Address", 5, 30);
        taAddress.setBorder(javax.swing.BorderFactory.createTitledBorder("address"));
        lbGender = new JLabel("Gender");
        bgGender = new ButtonGroup();
        rbMale = new JRadioButton("Male");
        rbFemale = new JRadioButton("Female");
        cbDotNet = new JCheckBox("Dot Net");
        cbAJT = new JCheckBox("Advance Java Technology");
        cbCD = new JCheckBox("Compiler Design");
        cbMC = new JCheckBox("Mobile Computing");
        cbSeminar = new JCheckBox("Seminar");
        btnSubmit = new JButton("SUBMIT");
        btnClear = new JButton("CLEAR");
        jmiLookWindow = new MenuItem("Look 1 - Window");
        jmiLookMatif = new MenuItem("Look 2 - Matif");
        jmiLookNimbus = new MenuItem("Look 3 - Nimbus");
         // Panelwise Adding of Component
        p1 = new JPanel();
        p2 = new JPanel();
        p3 = new JPanel();
        p4 = new JPanel();
        p5 = new JPanel();
        p6 = new JPanel();
        this.setMenuBar(mb);
        mb.add(menuFile);
        mb.add(menuDraw);
        mb.add(jmLooknFeel);
        menuFile.add(miOpen);
        menuFile.add(miExit);
        menuDraw.add(miOvel);
        menuDraw.add(miCircle);
        menuDraw.add(miSqare);
        jmLooknFeel.add(jmiLookWindow);
        jmLooknFeel.add(jmiLookMatif);
        jmLooknFeel.add(jmiLookNimbus);
          //panel 1
        p1.setLayout(new FlowLayout(FlowLayout.LEFT));
        p1.add(lbName);
        p1.add(tfName);
        // panel 2
        p2.setLayout(new FlowLayout(FlowLayout.LEFT));
        p2.add(lbAddress);
        p2.add(taAddress);
        //panel 3
        p3.setLayout(new FlowLayout(FlowLayout.LEFT));
        p3.add(lbGender);
        bgGender.add(rbMale);
        bgGender.add(rbFemale);
        p3.add(rbMale);
        p3.add(rbFemale);
        //Panel 4
        p4.setLayout(new FlowLayout(FlowLayout.LEFT));
        p4.add(lbSub);
        p4.add(cbSeminar);
        p4.add(cbMC);
        p4.add(cbCD);
        p4.add(cbDotNet);
        p4.add(cbAJT);
        // Panel 5
        p5.setLayout(new FlowLayout(FlowLayout.LEFT));
        p5.add(btnSubmit);
        p5.add(btnClear);
        //Panel 6 with Out Put
        dtm = new DefaultTableModel(null, new Object[]{"StudentName", "RollNo", "Gender"});
        tb = new JTable(dtm);
        add(new JScrollPane(tb));
        v = new Vector();
        this.add(p1);
        this.add(p2);
        this.add(p3);
        this.add(p4);
        this.add(p5);
        this.add(p6);
      //Register Listener
        btnSubmit.addActionListener(this);
        btnClear.addActionListener(this);
        rbMale.addItemListener(this);
        rbFemale.addItemListener(this);
        cbAJT.addItemListener(this);
        cbDotNet.addItemListener(this);
        cbMC.addItemListener(this);
        cbSeminar.addItemListener(this);
        cbCD.addItemListener(this);
        miOpen.addActionListener(this);
        miExit.addActionListener(this);
        miOvel.addActionListener(this);
        miSqare.addActionListener(this);
        miCircle.addActionListener(this);
        jmiLookMatif.addActionListener(this);
        jmiLookNimbus.addActionListener(this);
        jmiLookWindow.addActionListener(this);
        m = new MyCanvac(1);
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource().equals(miSqare)) {
            System.out.print("Square is selected");
            m.setV(1);
            m.drawShap();
        } else if (e.getSource().equals(miOvel)) {
            System.out.print("Ovel is selected");
            m.setV(2);
            m.drawShap();
        } else if (e.getSource().equals(miCircle)) {
            System.out.print("Circlel is selected");
            m.setV(3);
            m.drawShap();
        } else if (e.getSource().equals(miExit)) {
            System.exit(0);
        } else if (e.getSource().equals(miOpen)) {
            fileMenuMenuSelected();
        } else if (e.getSource().equals(btnSubmit)) {
            dtm.addRow(new String[]{tfName.getText(), taAddress.getText(), gen});
        } else if (e.getSource().equals(btnClear)) {
            taAddress.setText("");
            tfName.setText("");
            rbMale.setSelected(false);
            rbFemale.setSelected(false);
            cbAJT.setSelected(false);
            cbDotNet.setSelected(false);
            cbCD.setSelected(false);
            cbMC.setSelected(false);
            cbSeminar.setSelected(false);
        } else if (e.getSource().equals(jmiLookWindow)) {
            try {
                System.out.print("windows");
                UIManager.setLookAndFeel(windowsLF);
                SwingUtilities.updateComponentTreeUI(guiComponent.this);
                   } catch (UnsupportedLookAndFeelException ex) {
                Logger.getLogger(guiComponent.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else if (e.getSource()==jmiLookMatif) {
            try {
                System.out.print("Matif");
                UIManager.setLookAndFeel(motifLF);
                SwingUtilities.updateComponentTreeUI(guiComponent.this);
               } catch (UnsupportedLookAndFeelException ex) {
                Logger.getLogger(guiComponent.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else if (e.getSource()==jmiLookNimbus) {
            try {
                System.out.print("Nibus");
                UIManager.setLookAndFeel(nimbusLF);
                SwingUtilities.updateComponentTreeUI(this);
                 } catch (UnsupportedLookAndFeelException ex) {
                Logger.getLogger(guiComponent.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    public void itemStateChanged(ItemEvent e) {
        if (e.getSource().equals(rbMale)) {
            if (rbMale.isSelected()) {
                gen = "Gender:Male";
            }
        } else if (e.getSource().equals(rbFemale)) {
            if (rbFemale.isSelected()) {
                gen = "Gender:Female";
            }
        }
        if (e.getItem().equals(cbDotNet)) {
            if (cbDotNet.isSelected()) {
                Subjects = "Dot Net";}
        }
        if (e.getItem().equals(cbSeminar)) {
            if (cbSeminar.isSelected()) {
                Subjects = Subjects + "\tSeminar";
            }
        }
        if (e.getItem().equals(cbAJT)) {
            if (cbAJT.isSelected()) {
                Subjects = Subjects + "\tAdvance Java";
            }
        }
        if (e.getItem().equals(cbCD)) {
            if (cbCD.isSelected()) {
                Subjects = Subjects + "\tCompiler Design";
            }
        }
        if (e.getItem().equals(cbMC)) {
            if (cbMC.isSelected()) {
                Subjects = Subjects + "\tMobile Computing";
            }
        }
    }
 private void fileMenuMenuSelected() {
        JFileChooser js = new JFileChooser();
        int ret = js.showOpenDialog(this);
        fname = js.getSelectedFile().getName();
        fpath = js.getSelectedFile().getPath();
        System.out.println(fname);
        System.out.println(fpath);
File f = new File(fpath);
        try {
            FileInputStream fo = new FileInputStream(f);
            byte b[] = new byte[(int) f.length()];
            fo.read(b, 0, (int) f.length());
            String s = new String(b);
            JFrame f1 = new JFrame("File " + fname);
            JTextArea ta = new JTextArea(s);
            f1.add(ta);
            f1.setVisible(true);
            f1.setSize(500, 500);
        } catch (Exception e) {
            System.out.println(e);
        }
    }
    public static void main(String args[]) {
        guiComponent g = new guiComponent();
    }
}

MyCanvac.java
package GuiComponent;
import java.awt.Canvas;
import java.awt.Graphics;
import javax.swing.JFrame;
        public class MyCanvac extends Canvas{//extends Canvas{
            int v;
              public int getV() {
                return v;
           }
          public void setV(int v) {
            this.v = v;
          }
           public MyCanvac(int v) {
        this.v = v;
        System.out.print("MyCanvac : v "+ v );
       }

    @Override
        public void paint(Graphics g) {
        if (v ==1) {
            g.drawRect(5, 5, 500, 500);
        }else if(v==2)
        {   g.drawOval(5, 5, 250, 100);}
        else if(v==3){
         g.drawOval(5, 5, 100, 100);
    }
}
 void drawShap()
    { JFrame f = new JFrame();
        f.add(this);
        f.setVisible(true);
        repaint();
    }
}

OUTPUT:
1.File Open
2.Draw->Circle
3. Submit
4. Clear
5.Look And Feel->Nimbus
 

Create a java program to generate random number between 0 to 150.


public class Test {{
public static void main(String args[]){
double random = Math..random(); // Math class is java defined
// class having random method which return random number
random = random * 50;
// as random method is created between 0..0 to 1..0 by multiplying with
// 50 we generated random number between 0..0 to 50..0
int randomInt = (int) random;
// we are explicitly converting double number into int so our random
//number will be between 0 to 50 now.
System.out.println(randomInt);
// printing the random number on the screen.
}
}

Tuesday 22 October 2013

What is Apriori Algorithm, Explain the Techniques for Improving the efficiency of Apriory Alogithum

Apriori Algorithm
Apriori Property: All nonempty subsets of a frequent itemset must also be frequent.
• If itemset I does not satisfy the minimum support threshold then I is not frequent,
P(I)<min_supp
• If A is added to I, then IUA cannot be more frequent than I.
• Hence IUA is not frequent, P(IUA)<min_supp



Antimonotone Property: If a set cannot pass a test, all of its supersets will fail the same test as well.
• LK-1 is used to find Lk for k>=2
• Consists of two actions: Join and Prune
• Join: Join LK-1 with itself, denoted the candidates as Ck.
• Prune: Ck is a superset of Lk. Removing the tuples which do not satisfy the min supp criteria.(Subset Testing) Generating Association Rules from Frequent Itemsets
• Find Frequent itemsets and generate strong association rules.
• Explain Confidence and strong association rules.
• Association rules are generated as:
1. For each frequent itemset l, generate all nonempty subsets of l.
2. For every nonempty subset s of l, output the rule s ⇒ (l-s)

Techniques for Improving the efficiency of Apriory Alogithum
• Hash Based Techniques
• Transaction Reduction
• Partitioning
• Sampling
• Dynamic Item-set Counting

Hash Based Techniques: hash itemsets to corresponding buckets
• Used to reduce size of candidate k-itemsets Ck where k>1.
• Map generated frequent itemset in different buckets and increase corresponding bucket count.
• Itemset below the support threshold cannot be frequent and thus should be removed from the
candidate set.

Transaction Reduction: reduce number of transactions scanned in future iteration
• A transaction that does not contain any frequent k-itemset does not contain any
frequent (k+1)- itemset.
• Hence removed from further considerations.
Partitioning: partition data to find the candidate itemset
• Requires two data base scans to mine frequent itemsets.
• Phase I – algorithm subdivides transactions of D into n overlapping partitions.
• If Min Supp Thr in D is min_supp, then the min supp Thr for partition is min_supp*no of transactions in that partition.

Partitioning: partition data to find the candidate itemset
• Local Frequent Itemsets: frequent itemsets within the partition
• Global Frequent Itemsets: collection of all frequent itemsets from all partition.

Partitioning: partition data to find the candidate itemset
• Phase II: Second scan is done and actual support is assessed in order to determine global frequent itemsets.
• Partition size and number of partitions are set so that each partition can fit to main memory.
Partitioning: partition data to find the candidate itemset.

Sampling: mining on a subset of given data
• Pick up a random sample S of the given data D and search for frequent itemsets in S instead of D.
• Possible to miss some global frequent itemsets, so we use a lower min supp threshold to find local frequent itemsets.

Improving the Efficiency of Apriori
Dynamic itemset counting: adding candidate itemsets at different points during a scan.
• DB is partitioned into blocks marked by start points.
• New candidate can be added at any start point.
• Add new itemset if all of its subset are estimated

What is market basket analysis ? Explain with example


Market Basket Analysis
• Business Decision Making – catalog design, customer behavior analysis and cross marketing.
• Here we can analyze the Customer Behavior –his buying habits and association between different item sets kept in “shopping baskets”
• “Which group of items the customer are likely to buy on a given trip to a store”
• Use this result to plan the marketing strategy or design new catalog.
• Solution proposed for sale:
1. Items frequently purchased together are placed in proximity.
2. Keep items at two different ends.
• Items that are frequently purchased together form association rules.
Computer => antivirus [support = 2% and confidence = 60%]
• Support and Confidence are two measures of rule interesting ness
• Respectively reflect the usefulness and certainty of rules discovered.
• Support – 2% of all transactions under analysis show that computer and antivirus are bought together
• Confidence – 60% of all customers who purchased the computer also bought the antivirus.
Minimum Support Threshold and Minimum Confidence Threshold – set by user domain and experts.
• They make the rules interesting.

Laptops