Join us on Facebook

Please wait..10 Seconds Cancel
Showing posts with label Java Program. Show all posts
Showing posts with label Java Program. Show all posts

1.03.2014

// // Leave a Comment

Demonstration of ServletContext in Java.


ServletContext

Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file.
There is one context per "web application" per Java Virtual Machine. (A "web application" is a collection of servlets and content installed under a specific subset of the server's URL namespace such as /catalog and possibly installed via a .war file.)
In the case of a web application marked "distributed" in its deployment descriptor, there will be one context instance for each virtual machine. In this situation, the context cannot be used as a location to share global information (because the information won't be truly global). Use an external resource like a database instead.
The ServletContext object is contained within the ServletConfig object, which the Web server provides the servlet when the servlet is initialized.

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"> 
 
   <context-param> 
    <param-name>filepath</param-name> 
    <param-value>/text.txt</param-value> 
    </context-param> 
    <listener> 
        <listener-class>feeder.init</listener-class> 
    </listener> 
    <servlet> 
        <servlet-name>display</servlet-name> 
        <servlet-class>view.display</servlet-class> 
    </servlet> 

    <servlet-mapping> 
        <servlet-name>display</servlet-name> 
        <url-pattern>/display</url-pattern> 
   </servlet-mapping> 
 
    <session-config> 
        <session-timeout> 
            30 
        </session-timeout> 
    </session-config> 
 
    <welcome-file-list> 
        <welcome-file>display</welcome-file> 
    </welcome-file-list> 
</web-app> 
 

text.txt

This is sample TEXT. 
ABC your line. 
Now this config shows multiple lines that are stored on the single file. 

view.Display class

 
package view; 
 
import java.io.*; 
import java.net.*; 
import javax.servlet.*; 
import javax.servlet.http.*; 
 
 
public class display extends HttpServlet 
 { 
      private int i; 
  protected void processRequest(HttpServletRequest request, HttpServletResponse 
response) 
      throws ServletException, IOException 
  { 
        response.setContentType("text/html;charset=UTF-8"); 
                PrintWriter out = response.getWriter(); 
            try  
    { 
                ServletContext c=getServletContext(); 
                int i1=2; 
                String s = c.getAttribute("i1").toString();      
                i1=Integer.valueOf(s); 
                out.println("<html>");  
                out.println("<head>"); 
                out.println("<title>Display Text</title>");   
                out.println("</head>"); 
                out.println("<body>"); 
                for(i=0;i<i1;i++) 
                { 
                  String val=(String) c.getAttribute("s["+i+"]");  
                  out.println(val); 
                  out.println("<br />"); 
                } 
                out.println("</body>"); 
                out.println("</html>"); 
            } 
    finally 
    {  
                out.close(); 
            } 
      }  
   
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
    throws ServletException, IOException 
  { 
            processRequest(request, response); 
      }  
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
    throws ServletException, IOException  
  { 
            processRequest(request, response); 
      } 
 
    public String getServletInfo() { 
        return "Short description"; 
    } 
} 

feeder.init class

 
package feeder; 
 
import java.io.*; 
import javax.servlet.*; 
 
public class init  implements ServletContextListener 
{ 
    public void contextInitialized(ServletContextEvent arg0) 
    { 
         try  
  { 
                ServletContext c = arg0.getServletContext(); 
                String value = c.getInitParameter("filepath"); 
                InputStream i; 
                BufferedReader br; 
                i = c.getResourceAsStream(value); 
             
                br = new BufferedReader(new InputStreamReader(i)); 
                String line; 
                int i1=0; 
                while ((line=br.readLine()) != null) 
    { 
                  c.setAttribute("s["+i1+"]",line); 
                  i1++; 
                } 
                c.setAttribute("i1",i1); 
          } 
       catch (IOException ex) {} 
        } 
    public void contextDestroyed(ServletContextEvent arg0) 
  { 
          throw new UnsupportedOperationException("Not supported yet."); 
      } 
} 
Read More
// // Leave a Comment

Demonstration of ServletConfig in Java.

ServletConfig

public interface ServletConfig
A servlet configuration object used by a servlet container to pass information to a servlet during initialization.

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"> 
    <servlet> 
        <servlet-name>configdemo</servlet-name> 
        <servlet-class>view.configdemo</servlet-class> 
        <init-param> 
            <param-name>Numbers</param-name> 
             <param-value>1,2,3,4,5,6,7</param-value> 
    </init-param> 
    </servlet> 
    <servlet-mapping> 
        <servlet-name>configdemo</servlet-name> 
        <url-pattern>/configdemo</url-pattern> 
    </servlet-mapping> 
    <session-config> 
        <session-timeout> 
            30 
        </session-timeout> 
    </session-config> 
    <welcome-file-list> 
        <welcome-file>configdemo</welcome-file> 
        </welcome-file-list> 
    </web-app> 

Configdemo.java

 
package view; 
 
import java.io.*; 
import java.net.*; 
 
import javax.servlet.*; 
import javax.servlet.http.*; 
 
public class configdemo extends HttpServlet { 
    protected void processRequest(HttpServletRequest request, HttpServletResponse 
response) 
    throws ServletException, IOException { 
        response.setContentType("text/html;charset=UTF-8"); 
        PrintWriter out = response.getWriter(); 
        try { 
             
            ServletConfig c=getServletConfig(); 
            String course=c.getInitParameter("Numbers"); 
            String s[]=course.split(","); 
             
            out.println("<html>"); 
            out.println("<head>"); 
            out.println("<title>Servlet config demo</title>");   
            out.println("</head>"); 
            out.println("<body>");   out.println("<select name='n1'>"); 
            for(int i=0;i<s.length;i++) 
            { 
            out.println("<option value="+s[i]+" ''>"+s[i]+" </option>"); 
            } 
            out.println("</body>"); 
            out.println("</html>"); 
        } finally {  
            out.close(); 
        } 
    }  
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
    throws ServletException, IOException { 
        processRequest(request, response); 
    }  
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
    throws ServletException, IOException { 
        processRequest(request, response); 
    } 
 
     
    public String getServletInfo() { 
        return "Short description"; 
    } 
} 
 
Read More
// // Leave a Comment

Demonstration the use of JSTL by creating two functionalities of each JSTL tag. (c,xml,fun,sql)

JSTL tag

Core_Tags.jsp

 
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 
<html> 
<head> 
<title>Core Tags</title> 
</head> 
<body> 
    <jsp:text> This Page Shows the Tag from Core Library!!</jsp:text> 
    <br/> 
     
    <br/> 
    <c:forEach var="i" begin="1" end="8"> 
    Lord of The Rings <c:out value="${i}"/><br/> 
    </c:forEach> 
        
    <c:set var="salary" scope="session" value="${2000*2}"/> 
    <c:if test="${salary > 2000}"> 
    <br/> 
    My salary is: <c:out value="${salary}"/> 
    </c:if> 
     
</body> 
</html> 
Read More
// // Leave a Comment

Demostration Of Format Tag In Java

Format Tag

Format_Tags.jsp

 
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> 
<html> 
    <head> 
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
        <title>Format Tags</title> 
    </head> 
    <body> 
         
<c:set var="balance" value="120000.2309" /> 
<h3>Number Format:</h3>  
<b>Original Number : </b> ${balance} 
<p><b>Number_Format (Currency):</b> <fmt:formatNumber value="${balance}"  
            type="currency"/></p> 
<p><b>Number_Format (Max 3 Integers):</b> <fmt:formatNumber type="number"  
            maxIntegerDigits="3" value="${balance}" /></p> 
<p><b>Number_Format (Max 3 Decimals): </b><fmt:formatNumber type="number"  
            maxFractionDigits="3" value="${balance}" /></p> 
 
<br/> 
<br/> 
<br/> 
        <h3> Number Parse:</h3>         
<c:set var="balance" value="12345.89" /> 
<fmt:parseNumber var="i" type="number" value="${balance}" /> 
<p><b>Parsed_Number (Whole Number) : </b><c:out value="${i}" /></p> 
<fmt:parseNumber var="i" integerOnly="true"  
                       type="number" value="${balance}" /> 
<p><b>Parsed_Number (Integer Part Only) : </b><c:out value="${i}" /></p> 
    </body> 
</html> 
Read More
// // Leave a Comment

Demostration Of fn(Function) Tag In Java

fn tag(Function Tag)

Fn_Tags.jsp:

 
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %> 
<html> 
<head> 
<title>Function Tags</title> 
</head> 
<body> 
 
<c:set var="theString" value="This String Contains Aditya"/> 
<c:if test="${fn:contains(theString, 'aditya')}"> 
   <p>Found string with aditya<p> 
</c:if> 
 
<c:if test="${fn:contains(theString, 'Aditya')}"> 
   <p>Found string with Aditya<p> 
</c:if> 
        
<c:set var="string" value="Aditya: This is first String."/> 
<c:if test="${fn:startsWith(string, 'Aditya')}"> 
   This String starts with Aditya 
</c:if> 
<br /> 
<c:if test="${fn:startsWith(string, 'aditya')}"> 
   This String Starts with aditya 
</c:if>        
        
 
</body> 
</html> 
Read More
// // Leave a Comment

Create Client‐Server application using Socket class in Java.

Client‐Server application using Socket class

Simple client

import java.io.*; 
import java.net.*;     
 
public class SimpleClient  
{ 
    public static void main(String[] a) 
    { 
        try 
        { 
            Socket s1=new Socket("192.168.1.117",1567); 
            InputStream is=s1.getInputStream(); 
            BufferedReader br=new BufferedReader(new InputStreamReader(is));             
            int i; 
            System.out.println(""); 
 
            while((i=br.read())!=-1) 
            {                 
                System.out.print((char)i);                 
            } 
             
            br.close(); 
            s1.close(); 
        } 
        catch(IOException e) 
        { 
            e.printStackTrace(); 
            System.out.println("Conncection Problem"); 
        } 
    } 
 
     
} 
 

Simple Server

 
import java.net.*; 
import java.io.*; 
 
public class SimpleServer  
{ 
    public static void main(String[] a) 
    { 
        ServerSocket s=null; 
        try 
        { 
            s=new ServerSocket(1567); 
        } 
        catch(IOException e) 
        { 
            e.printStackTrace(); 
        }  
        while(true) 
        { 
            try 
            { 
                Socket s1=s.accept(); 
                OutputStream out=s1.getOutputStream(); 
                BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(out)); 
                 
                bw.write("Hello net World!\n"); 
                 
                bw.close(); 
                s1.close(); 
            } 
            catch(IOException e) 
            { 
                e.printStackTrace(); 
            } 
        } 
    }     
} 
Read More
// // Leave a Comment

Demonstration of All Factory Methods in Java.


Demonstration of all factory methods. 


import java.net.InetAddress; 
import java.net.UnknownHostException; 
 
public class FactoryDemo 
 { 
 
  public static void main(String[] args) 
 { 
     
    try 
 { 
      InetAddress[] i = InetAddress.getAllByName("www.google.com"); 
      InetAddress  i1= InetAddress.getByName("www.google.com"); 
      InetAddress  i2= InetAddress.getLocalHost (); 
       
      for(int ii=0;ii< i.length;ii++) 
        System.out.println("Get All By Name:"+i[ii]); 
 
      System.out.println("Get By Name:"+i1); 
      System.out.println("Get Localhost:"+i2); 
    } 
 catch (UnknownHostException e) 
 { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
    } 
  } 
} 
Read More
// // Leave a Comment

Demonstration Of RMI Registry, RMI Interface In Java.

RMI Registry, RMI Interface

Client:

 
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); 
    Label rs = new Label("Sum= 0"); 
    JButton b = new JButton("Add"); 
    Panel p = new Panel(new GridLayout(4, 1, 5, 5)); 
  RemoteInterface s; 
 
  public Client() 
 { 
  super("Client Side"); 
    setSize(250, 250); 
  setLocation(300, 300); 
  getContentPane().add(p, "North"); 
  p.add(t1); 
  p.add(t2); 
  p.add(rs); 
  p.add(b); 
 
  try  
{ 
  String ipp = JOptionPane 
  .showInputDialog("Please enter the IP Address to Connect"); 
  String ip = "rmi://" + ipp + "/RMIAPPLICATION"; 
  s = (RemoteInterface) Naming.lookup(ip); 
 
  } 
 catch (Exception exp) 
 { 
  JOptionPane.showMessageDialog(null, exp.getMessage()); 
  } 
 
  b.addActionListener(new ActionListener() 
 { 
    public void actionPerformed(ActionEvent evt)   
 { 
      int a = Integer.parseInt(t1.getText()); 
      int b = Integer.parseInt(t2.getText()); 
      try 
 { 
  int r = s.add(a, b); 
  rs.setText("Sum of two no =" + r); 
      } 
 catch (Exception epx) 
 {   
  } 
  } 
  }); 
  } 
 
  public static void main(String args[]) 
 { 
  Client c = new Client(); 
    c.setDefaultCloseOperation(EXIT_ON_CLOSE); 
    c.setVisible(true); 
  } 
} 
 

Remote Interface

 
import java.rmi.*; 
public interface RemoteInterface extends Remote 
{ 
  public int add(int x,int y)throws Exception; 
} 
 

Server:

 
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()); 
      } 
      } 
} 
 

Server Implements:

 
import java.rmi.*; 
import java.rmi.server.*; 
import java.lang.String; 
 
interface RemoteInterface extends Remote 
 { 
    public int add(int x, int y) throws Exception; 
 } 
public class ServerImplements extends UnicastRemoteObject implements RemoteInterface 
 { 
    public ServerImplements() throws Exception 
 { 
  super(); 
    } 
  public int add(int x, int y) 
 { 
  return (x + y); 
    } 
 } 

Read More

11.30.2013

// // Leave a Comment

Create three buttons and perform action event on that.

Action Event

An Event representing some type of action. This event type is widely used to represent a variety of things, 
such as when a Button has been fired, when a KeyFrame has finished, and other such usages.
import javax.swing.*; 
import java.awt.event.*; 
package button_demo; 
public class Button_Demo extends JFrame 
 { 
    public Button_Demo()  
   { 
        initComponents();  
    } 
    private void initComponents() 
   { 
        JButton jButton1 = new JButton(); 
        JButton jButton2 = new JButton(); 
        JButton jButton3 = new JButton(); 
        JLabel jLabel1 = new JLabel(); 
 
        setDefaultCloseOperation(EXIT_ON_CLOSE); 
 
        jButton1.setText("Alpha"); 
        jButton1.addActionListener(new ActionListener()  
           { 
              public void actionPerformed(ActionEvent evt) 
                 { 
                    jButton1ActionPerformed(evt); 
                 } 
           }); 
 
        jButton2.setText("Beta"); 
        jButton2.addActionListener(new ActionListener()  
          { 
              public void actionPerformed(ActionEvent evt) 
                  { 
                    jButton2ActionPerformed(evt); 
                  } 
          }); 
        jButton3.setText("Gamma"); 
        jButton3.addActionListener(new ActionListener() 
         { 
              public void actionPerformed(ActionEvent evt) 
                  { 
                    jButton3ActionPerformed(evt); 
                  } 
          }); 
        GroupLayout layout = new GroupLayout(getContentPane()); 
        getContentPane().setLayout(layout); 
        pack(); 
    } 
    private void jButton1ActionPerformed(ActionEvent evt)  
         { 
            jLabel1.setText("You have pressed Alpha"); 
         } 
    private void jButton2ActionPerformed(ActionEvent evt)  
         { 
            jLabel1.setText("You have pressed Beta"); 
         }    
 
    private void jButton3ActionPerformed(ActionEvent evt)  
       { 
            jLabel1.setText("You have pressed Gamma"); 
       } 
    public static void main(String args[]) 
       { 
                new Button_Demo().setVisible(true); 
       } 
}  
Read More