Showing posts with label Java Interfaces. Show all posts
Showing posts with label Java Interfaces. Show all posts

Thursday, April 12, 2012

Session Listeners in Apache Tomcat

To implement a SessionListener in java we implement the javax.servlet.http.HttpSessionListener interface.

Here is our implementation of the HttpSessionListener

CountSessionListener
package servletpackage;
import java.sql.*;
import javax.naming.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class CountSessionListener implements HttpSessionListener
{
public void sessionCreated(HttpSessionEvent event)
{
HttpSession session=event.getSession();
try
{

String id=session.getId();
java.util.Date d=new java.util.Date();
System.out.println("Session Created with ID=" + id  + " at  time " + d);
}
catch(Exception ex)
{
System.out.println(ex);
}
}
public void sessionDestroyed(HttpSessionEvent event)
{
HttpSession session=event.getSession();
try
{
String id=session.getId();
java.util.Date d=new java.util.Date();
System.out.println("Session Destroyed with ID=" + id  + " at  time " + d);
}
catch(Exception ex)
{
System.out.println(ex);
}
}
}

To redirect the Standard Output in Apache Tomcat we use the logging tab in the Tomcat Monitor.




To install this session listener the following entries are required in the web.xml file.

web.xml

<web-app>
<listener>
<listener-class>servletpackage.CountSessionListener</listener-class>
</listener>

<session-config>
<session-timeout>2</session-timeout>
</session-config>
</web-app>

The underlined portion is the session listener configuration. We have also set a session timeout of 2 minutes.

To test the listener create two jsp pages. hello.jsp, and bye.jsp. hello.jsp creates a session while bye.jsp destroys it.

Here are the two files:-

hello.jsp

<%
request.getSession(true);
%>

bye.jsp

<%
session.invalidate();
%>



Open the two files and refresh them alternately in the browser.

Here is the output in the out.txt file where the System.out is redirected.



2012-04-12 14:01:32 Commons Daemon procrun stdout initialized
Session Created with ID=EA0AEFF5335E7F8E9B59F99FBDA5157D at  time Thu Apr 12 14:01:44 IST 2012
Session Destroyed with ID=EA0AEFF5335E7F8E9B59F99FBDA5157D at  time Thu Apr 12 14:02:05 IST 2012
Session Created with ID=2BE4BD1A6EFAA45785F63EB5991B46D1 at  time Thu Apr 12 14:24:04 IST 2012
Session Destroyed with ID=2BE4BD1A6EFAA45785F63EB5991B46D1 at  time Thu Apr 12 14:24:04 IST 2012
Session Created with ID=2BFF301ED2C87299CB0E75F51323340D at  time Thu Apr 12 14:24:06 IST 2012

Friday, January 7, 2011

A RMI based Application in Java to capture the Screen and send it.

RMI or Remote Method Invocation is Java technology for implementing remote procedure calls. A RMI application has three parts. An interface that will extend java,rmi.Remote. This has to be shared by both the RMI Server & the RMI Client. An implementation class on the Server that shall implement the above mentioned interface.The implementation class must extend java.rmi.server.UnicastRemoteObject(for stateless calls). A server that shall create and bind a Object of the implementation to the RMI Registry. A RMI Client shall lookup the RMI Registry and create a proxy of the implementation Object and call the methods. Marshalling & unmarshalling of the parameters and return values is done through the stub classes. These again have to be present both on the client and the server.
   The desktop capture is done through the use of the java.awt.Robot. All remotely callable methods must throw the java.rmi.RemoteException.
//*********************************************************************************
The Desktop Server
The interface IDesktop.java
import java.rmi.*;
public interface IDesktop extends Remote
{
public byte[] getDesktop() throws RemoteException;
}



The implementation Desktop.java
import java.rmi.*;
import java.rmi.server.*;
import java.awt.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
public class Desktop extends UnicastRemoteObject implements IDesktop
{
public Desktop() throws RemoteException
{

}

public byte[] getDesktop()
{
try
{
GraphicsEnvironment env=GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice screen=env.getDefaultScreenDevice();
Robot robot=new Robot(screen);
Dimension d=Toolkit.getDefaultToolkit().getScreenSize();
BufferedImage img=robot.createScreenCapture(new Rectangle(0,0,d.width,d.height));
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
ImageIO.write(img, "jpg", bytes );
bytes.flush();
byte[] data = bytes.toByteArray();
bytes.close();
return data;
}
catch(Exception ex)
{
System.out.println(ex);
return null;
}
}
}



The Server DesktopServer.java


import javax.naming.*;
import java.rmi.*;
public class DesktopServer
{
public static void main(String[] args)throws RemoteException,NamingException
{
Context cnt=new InitialContext();
cnt.bind("rmi:desktop",new Desktop());
System.out.println("Server is Ready");
}

}



Compile the classes and create the Stub Classes. Here is How .
Start the RMI Registry


The start the Server


//*********************************************************************************


The Desktop Client

Copy the IDesktop.class, and the Desktop_Stub.class files to the client.

DesktopClient.java
import java.rmi.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.naming.*;
import javax.swing.*;
import javax.imageio.*;
public class DesktopClient extends JFrame
{
//*************************************************************
class ImageThreader extends Thread
{
public void run()
{
while(true)
{
try
{
byte[] data = obj.getDesktop();
InputStream in = new ByteArrayInputStream(data);
BufferedImage img = ImageIO.read(in);
setIcon(img);
Thread.sleep(10000);
}

catch(Exception ex)
{
System.out.println(ex);
}
}



}
}

//**************************************************************
private JLabel lbl;
private IDesktop obj;
public DesktopClient()throws RemoteException,NamingException,IOException
{
lbl=new JLabel();
add(lbl);
InitialContext cnt=new InitialContext();
obj=(IDesktop)cnt.lookup("rmi://compaq510/desktop");

//replace compaq510 with the name or IP Address of the computer running the server.
ImageThreader th=new ImageThreader();
th.start();
}



public void setIcon(BufferedImage img)
{
lbl.setIcon(new ImageIcon(img));
}
public static void main(String[] args)throws RemoteException,NamingException,IOException
{

DesktopClient f=new DesktopClient();
f.setVisible(true);
}
}




Wednesday, December 1, 2010

Interfaces with methods in Java



Java Interfaces are not allowed to have Methods. However they are allowed to have variables and Constants(final).

Using this, we can have methods in Java Interfaces. Here is how :-

1)
Develop a class with a method

Programmer.java
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package methodsininterfaces;

import java.lang.reflect.Method;

/**
 *
 * @author Champak
 * Varanasi,India
 * Mob 91-9335874326
 */
public class Programmer  {
public static String getProgrammer(String programmer)
{
//The Method to be accessed via the Interface
   programmer=programmer.trim().toLowerCase();
if(programmer.equals("champak"))
    return "Champak Roy";

return "Unknown";
}


public static Method returnMethod()
{
//Return the Method
try
{
return Programmer.class.getMethod("getProgrammer",String.class);
}
catch(Exception ex)
{
System.out.println(ex);
return null;
}
}
}


The Interface  ProgrammerInterface.java

ProgrammerInterface.java
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package methodsininterfaces;

import java.lang.reflect.Method;

/**
 *
 * @author Champak
 * Varanasi,India
 * Mob 91-9335874326
 */
public interface ProgrammerInterface {
public static Method interfaceMethod=Programmer.returnMethod();
//The Method has been stored in the interface
}


Calling the Interface Method

Main.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package methodsininterfaces;

import java.util.Scanner;



/**
 *
 * @author Champak
 * Varanasi,India
 * Mob 91-9335874326
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)throws Exception {
Scanner sc=new Scanner(System.in);
        System.out.print("Enter the name of the Programmer = ");
        String martyr=sc.nextLine();
        System.out.println(Programmer.interfaceMethod.invoke(null, programmer));
//In the invoke method pass null for a static method, or else pass the object to which the method belongs
    }

}


The Output

run:
Enter the name of the Programmer = champak
Champak Roy
BUILD SUCCESSFUL (total time: 13 seconds)