Вы находитесь на странице: 1из 32

1 POTHURAI Miscellaneous classes <app-conf> <drvcls>----</drvcls> <url> ---- </url> <uname> --- </uname> <pwd> --- </pwd> </app-conf>

XML parser Java app

ac.xml A java developer can use JAXP (java API xml processing, JAXB (java API xml binding), XML beans for reading the data from XML documents. JAXP is internally used by JAXB & XML beans. Java soft has provided 2 types of parsers as part of JAXP. The parser is responsible for reading the XML document, splitting the XML document & picking up the information about various tags available in XML document. 1) SAX ----- simple API for XML 2) DOM ----- document object model. SAX parser takes less amount of memory & gives better performance compare to the DOM parser. But writing the code with DOM parser is easy. XML beans JAXB

JAXP SAX parser DOM parser

As part of the project the developers may use the XML tags designed by their company on the XML tags design by other companies. We can use XML schemas for the design of our own XML tags. Xml spy new choose xsd (ourtags.xsd)

Save:- d:\xmlb Xml spy new choose xml document (ac.xml) Select schema browse ourtags.xsd ok <?xml version="1.0" encoding="UTF-8"?> SUDHEER REDDY

2 POTHURAI <app-conf xmlns="http://students.org" xmlns:xsi="http://www.w3.org/2001/XML Schema-instance" xsi:schemaLocation="http://students.org D:\Pskr\xmlb\ ourtags.xsd"> <drvcls>oracle.jdbc.driver.OracleDriver</drvcls> <uname>scott </uname> <pwd>tiger</pwd> <url>jdbc:oracle:thin:@localhost:1521:xe</url> </app-conf> Save:- d:\xmlb In order to use XML beans extract the context of xmlbeans-2.3.0.zip. When the above file is extracted we will get a schema compiler (scomp.cmd), a set of jar files xbean.jar, jsr173_1.0_api.jar, xbean_xpath.jar .etc scomp ourtags.xsd javac .java files

D:\xmlb

Working directory .class files ourtags.xsd ac.xml source classes

Steps for using schema compiler: 1) Copy the xsd file in the working directory. 2) Create classes directory, source directory under working directory. 3) Using cd command move to the working directory. D:\Pskr>cd xmlb 4) Set the environment variable path pointing to the directory that contains the schema compiler. D:\Pskr\xmlb>set PATH=D:\Pskr\xmlb\xmlbeans-2.3.0\bin;%PATH% 5) Run scomp using the command shown below D:\Pskr\xmlb>scomp -src source -d classes ourtags.xsd SUDHEER REDDY

3 POTHURAI Time to build schema type system: 2.547 seconds Time to generate code: 0.141 seconds Time to compile code: 3.921 seconds D:\Pskr\xmlb> The schema compiler generates an interface with the name XxxDocument. Xxx is the root element. For every complex element an interface will be generated by the schema compiler. Inside the interfaces a class with the name Factory will be generated. For that above schema the following interfaces will be generated. AppConfDocument, AppConfDocument.AppConf import org.students.*; import java.io.*; public class RXDoc { public static void main(String[ ] args) throws Exception { AppConfDocument acdoc; AppConfDocument.AppConf ac; File f1=new File("ac.xml"); acdoc=AppConfDocument.Factory.parse(f1); ac=acdoc.getAppConf( ); String vdrvcls=ac.getUname( ); String vuname=ac.getDrvcls( ); String vpwd=ac.getPwd( ); String vurl=ac.getUrl( ); System.out.println(vdrvcls); System.out.println(vuname); System.out.println(vpwd); System.out.println(vurl); } } D:\Pskr\xmlb>set CLASSPATH=.;classes;xbean.jar;jsr173_1.0_api.jar; D:\Pskr\xmlb>javac RXDoc.java D:\Pskr\xmlb>java RXDoc scott oracle.jdbc.driver.OracleDriver tiger jdbc:oracle:thin:@localhost:1521:xe import org.students.*; import java.io.*; public class WXDoc { public static void main(String[ ] args) throws Exception { AppConfDocument acdoc; SUDHEER REDDY

4 POTHURAI AppConfDocument.AppConf ac; acdoc=AppConfDocument.Factory.newInstance(); ac=acdoc.addNewAppConf( ); ac=acdoc.getAppConf( ); ac.setUname("yyy"); ac.setDrvcls("ddd"); ac.setPwd("xxx"); ac.setUrl("uuuu"); System.out.println(acdoc); FileWriter fw=new FileWriter("test.xml"); fw.write(acdoc.toString( )); fw.close( ); } } D:\Pskr\xmlb>javac WXDoc.java D:\Pskr\xmlb>java WXDoc <app-conf xmlns="http://students.org"> <drvcls>ddd</drvcls> <uname>yyy</uname> <pwd>xxx</pwd> <url>uuuu</url> </app-conf> What is the difference between PrintWriter & JspWriter? A) PrintWriter was designed by java soft before the design of JSP technology. In this class the methods print, println are designed not to throw IOException even if there is a problem. But the methods of JspWriter throw IOException to indicate a failure. JspWriter supports buffering where as PrintWriter is not support buffering. <%@ page buffer="5kb" %> <%@ page autoFlush="false" %> <% for(int i=0;i<10000;i++) { out.println("A"); } %> http://localhost:8000/jsp/buffer.jsp java.io.IOException: Error: JSP Buffer overflow When the browser sends the request for the above JSP, the server will start the execution of a servlet. The servlet uses the JspWriter object. The object allocates 5kb memory of buffer. When the JSP generates the output will be collected in the buffer. In the above application after collecting 5kb buffer will be followed & it leads to buffer overflow. To solve this problem we can increase the size or we set autoFlush="true". <%@ page buffer="5kb" %> <%@ page autoFlush="true" %> <% for(int i=0;i<10000;i++) { out.println("A"); } SUDHEER REDDY

5 POTHURAI %> http://localhost:8000/jsp/buffer.jsp AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA A A A A A A A A . .AAAAAAAAAAAAAAAAAAAAAAAA When autoFlush="true" the buffer will be flushed (the content will be sent to the browser) when the buffer is full. Sending the output to the browser is called as committing the response. A Listener is an object that is responsible for listening / waiting for an event. Once an event takes place, the listener carries out some tasks. There are various interfaces with the naming pattern XxxListener & the methods. In these interfaces takes a parameter of type XxxEvent. As part of servlet API various listener interfaces are provided. Some of them are ServletContextListener, ServletRequestListener, HttpSessionListener . Etc. In servlet API, creation & removal of ServletContext, creation & removal of request object, creation & removal of session object etc are called as events. A Listener class is a class that provides the implementation of XxxListener interface & the objects based on these classes are called as Listener objects. D:\Pskr>set CLASSPATH=.;servlet-api.jar D:\Pskr>javap javax.servlet.ServletContextListener >OLType.java Compiled from "ServletContextListener.java" public interface javax.servlet.ServletContextListener extends java.util.EventListener{ public abstract void contextInitialized(javax.servlet.ServletContextEvent); public abstract void contextDestroyed(javax.servlet.ServletContextEvent); } import javax.servlet.*; public class OLOne implements ServletRequestListener { public void requestDestroyed(ServletRequestEvent sre) { System.out.println("-- requestDestroyed --"); } public void requestInitialized(ServletRequestEvent sre) { System.out.println("-- requestInitialized --"); } public OLOne( ) { System.out.println("-- OLOne created --"); } } SUDHEER REDDY

6 POTHURAI D:\Pskr>javac OLOne.java <% System.out.println("-- one.jsp --"); %> op of one.jsp <% System.out.println("-- two.jsp --"); %> op of two.jsp in order to use a Listeners we must copy the Listener class in WEB-INF/classes directory & we must provide the information about the Listener in web.xml as shown below. <web-app> <listener> <listener-class>OLOne</listener-class> </listener> </web-app> Start the server -- OLOne created -http://localhost:8000/ser/one.jsp -- requestInitialized --- one.jsp --- requestDestroyed op of one.jsp http://localhost:8000/ser/two.jsp -- requestInitialized --- two.jsp --- requestDestroyed op of two.jsp when a browser sends a request for a resource (ex: - one.jsp), the container carries out the following ssteps. 1) Web container creates the request object. 2) Web container calls requestInitialized method 3) Web container executes one.jsp 4) Web container calls requestDestroyed method 5) Web container removes the request object. As part of ServletContextListener the following 2 methods are provided. 1) contextInitialized --- called after creating ServletContext object (while starting web app).

SUDHEER REDDY

7 POTHURAI 2) contextDestroyed --- called before removing ServletContext (while stoping web app). <app-conf> <hname> hospOne </hname> <haddr> anantapur </haddr> <hlogo> ho.jpg </hlogo> <bgcolor> green </bgcolor> </app-conf> The data available in ac.xml is called as configuration data of the application / application setting / application preferences depending upon the customer requirements this fail can be changed. package org.students; public class AppPref { String hospName, hospAddr, bgColor, logo; public AppPref( ) { // code to read data from ac.xml ( we can use XML Beans for this) System.out.println("-- Reading data from ac.xml --"); hospName="Hosp One"; hospAddr="Anantapur,Andra pradesh"; bgColor="red"; logo="ho.jsp"; System.out.println("-- set the values of various props--"); } public String getHospName( ) { return hospName; } public String getHospAddr( ) { return hospAddr; } public String getBgColor( ) { return bgColor; } public String getLogo( ) { return logo; } } D:\Pskr>javac -d . AppPref.java

SUDHEER REDDY

8 POTHURAI import javax.servlet.*; public class OLTwo implements ServletContextListener { public void contextInitialized(ServletContextEvent sce) { System.out.println("-- contextInitialized --"); org.students.AppPref vap=new org.students.AppPref( ); ServletContext application=sce.getServletContext( ); application.setAttribute("ap",vap); System.out.println("-- stored AppPref in app --"); } public void contextDestroyed(ServletContextEvent sce) { System.out.println("-- contextDestroyed --"); } } D:\Pskr>javac OLTwo.java <web-app> <listener> <listener-class>OLTwo</listener-class> </listener> </web-app> <jsp:useBean id="ap" scope="application" class="org.students.AppPref"/> <html> <body> Welcome to <jsp:getProperty name="ap" property="hospName"/> , <jsp:getProperty name="ap" property="hospAddr"/> <br> </body> </html> op generated by happ.jsp Hospital name, Hospital Address etc used in the above application is same (not specific) for all the clients (browsers) accessing the applications & we have to use this data while processing multiple requests. This is why we have stored AppPref object in ServletContext. Start the server -- contextInitialized --- Reading data from ac.xml --- set the values of various props--- stored AppPref in app http://localhost:8000/happ/happ.jsp

SUDHEER REDDY

9 POTHURAI Welcome to Hosp One , Anantapur,Andra pradesh op generated by happ.jsp ServletContext ap Hosp one Anantapur .. . AppPref Web container When web container starts the web application the following steps will be carried out. 1) Web container creates ServletContext object 2) Web container calls contextInitialized( ) method on OLTwo object. 3) contextInitialized( ) method create AppPref object. 4) The code in the constructor of AppPref reads the data from ac.xml & sets the properties using this data. 5) contextInitialized( ) method stores the AppPref object in ServletContext with the attribute name ap. CVS server --- (Context Versioning)

ac.xml

openCVS, MSVSS, BST etc

IDE IDE mcone mctwo Most of the developers uses the Integrated Development Environment (IDE) like MyEclipse IDE, NetBeans IDE, JBuilder IDE etc for the development of the projects. Most of these IDEs can work with concurrent versoning systems like openCVS, MSVSS (Microsoft Visual Source Safe), BST etc. As shown the above diagram the administrator configures the CVS server on one of the machine in the network. The CVS server will be configured with a repository (a directory that is used to store all the files that are part of a project).

SUDHEER REDDY

10 POTHURAI When a developer creates a file on his machine, the IDE stores the file in his machine & the developer can asked IDE to check in (put the file on the server) the file in the repository. Once the file is checked in it is available for all the developers. Like this the developers can very easily share the files with the other developers. When we make the changes to the files we can ask the server to maintain the information about the differences between different versions of the files. SingleThreadModel: - javax.servlet.SingleThreadModel is a tagged interface (interface without methods). A servlet class can provide the implementation of this interface. When this interface is implemented by a servlet one thread will be using a servlet object at any point of time. import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class MTSrv extends HttpServlet { PrintWriter out=null; public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { out=response.getWriter( ); out.println("Line One <br>"); try { Thread ct=Thread.currentThread( ); System.out.println("--MTStrv--"+ct); ct.sleep(60000); } catch(Exception e) { } out.println("Last Line <br>"); } public MTSrv( ) { System.out.println("--MTStrv created--"); } } D:\Pskr>javac MTSrv.java import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class STSrv extends HttpServlet implements SingleThreadModel { PrintWriter out=null; public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { SUDHEER REDDY

11 POTHURAI out=response.getWriter( ); out.println("Line One <br>"); try { Thread ct=Thread.currentThread( ); System.out.println("--STStrv--"+ct); ct.sleep(60000); } catch(Exception e) { } out.println("Last Line <br>"); } public STSrv( ) { System.out.println("--STStrv created--"); } } D:\Pskr>javac STSrv.java <web-app> <servlet> <servlet-name>mts</servlet-name> <servlet-class>MTSrv</servlet-class> </servlet> <servlet> <servlet-name>sts</servlet-name> <servlet-class>STSrv</servlet-class> </servlet> <servlet-mapping> <servlet-name>mts</servlet-name> <url-pattern>/mts</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>sts</servlet-name> <url-pattern>/sts</url-pattern> </servlet-mapping> </web-app> Browser1 Browser2 http://localhost:8000/stm/mts http://localhost:8000/stm/mts --MTStrv created---MTStrv--Thread[http-8000-Processor25,5,main] --MTStrv--Thread[http-8000-Processor24,5,main] Line one Line One Last Line Last Line Browser1 http://localhost:8000/stm/sts --STStrv created-Browser2 http://localhost:8000/stm/sts

SUDHEER REDDY

12 POTHURAI --STStrv created --STStrv--Thread[http-8000-Processor24,5,main] Line one Line One Last Line Last Line MTSrv will fail when multiple browsers sends the request concurrently, but the STSrv works properly. If a servlet class is not implementing SingleThreadModel interface then web container will create only one object (ex:- MTSrv). Web container creates multiple servlet objects if the servlet class implemens SingleThreadModel (ex:-STSrv). Every web container creates multiple Threads for executing the servlets. /mts
service{ . }

Tone

bone /mts

MTSrv obj TTwo Web container btwo When multiple browsers sends request for MTSrv, the web container uses multiple Threads for executing the service method on a single servlet object. If the servlet implements SingleThreadModel then the web container can used only one Thread for accessing a servlet object at any point of time. /sts STSrv obj Tone /sts STSrv obj TTwo Web container btwo When multiple browsers send the request for STSrv, web container uses multiple objects from multiple Threads (one thread will be used to access one object). If we use 4 browsers as send the request & if 2 STSrv objects are available in the container. Then the container can use one of the following 2 solutions. 1) Web container can add 2 more STSrv objects & use 4 objects from 4 Threads for processing the request. 2) If web container can not crate new objects then it will keep 2 requests in the Queue while processing the 2 request. After processing the first 2 request, the web container can deal with the request placed (stored) in the Queue. bone

SUDHEER REDDY

13 POTHURAI For every Thread there will be a stack space. The parameters & the local variables of a method will be placed in the stack space of the Thread that is running the method. The JVM places the java object in the Heap space. Only one copy of MTSrv will be created, so there will be only one copy of the instance variable out. This variable can point to only one PrintWriter object at any point of time (either it can point to b1pw, b2pw). /mts request response SS of TOne b2req b2resp /mts request response SS of TTwo btwo bone

b1req b1pw b1resp

out MTSrv obj b2pw

Heap Space Web container

This is the reason for the failure. MTSrv is not Thread safe (if there is a problems when an object is access from multiple Threads then the object is considered as Thread unsafe). /sts request response SS of TOne out STSrv Obj b2pw b2req b2resp /sts request response SS of TTwo btwo bone

b1pw STSrv Obj out

b1req b1resp

Heap Space Web container

SUDHEER REDDY

14 POTHURAI As multiple servlets objects are used there will be multiple copies of instance variable out. These multiple copies of instance can point to multiple PrintWriter objects. import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class TTSrv extends HttpServlet { public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out=null; out=response.getWriter( ); out.println("Line One <br>"); try { Thread ct=Thread.currentThread(); System.out.println("--TTStrv--"+ct); ct.sleep(60000); } catch(Exception e) { } out.println("Last Line <br>"); } public TTSrv( ) { System.out.println("--TTStrv created--"); } } D:\Pskr>javac TTSrv.java Note: - In the above Servlet out is not an instance variable. It is a local variable of the service method. <web-app> <servlet> <servlet-name>tts</servlet-name> <servlet-class>TTSrv</servlet-class> </servlet> <servlet-mapping> <servlet-name>tts</servlet-name> <url-pattern>/tts</url-pattern> </servlet-mapping> </web-app> Browser1 Browser2 http://localhost:8000/stm/tts http://localhost:8000/stm/tts --TTStrv created---TTStrv--Thread[http-8000-Processor24,5,main] --TTStrv--Thread[http-8000-Processor25,5,main] SUDHEER REDDY

15 POTHURAI Line one Last Line Line One Last Line /tts out request response SS of TOne b2req out request response SS of TTwo btwo /tts bone

b1req b1pw b1resp

TTSrv obj b2pw

b2resp Heap Space Web container

TTSrv is a Thread safe by declaring out variable as local variable (instead of declaring it has instance variable) we are able to make it has Thread safe. By following rules given below, we can make our servlet Thread safe: 1) We must avoid static variables & instance variables. 2) If we need to use a static variable are an instance variable & if the variables points to Thread unsafe objects. Then we must use synchronized blocks for accessing those objects. . public class TUSrv extends HttpServlet { ArrayList al=new ArrayList( ); public void service(. . ) . . { synchronized(al) { al.add(..); . } . } }

SUDHEER REDDY

16 POTHURAI We must use synchronized blocks while accessing Thread unsafe objects available in session, application objects. Ant: The diagram shown below shows the steps that are to be carried out while building a stand alone java application. Cone.java Javac Cone.class CTwo.java javac CTwo.class CThousand.java javac CThousand.class

ourapp.jar During the development of an application we need to build application for several times. Manually building the application takes more amount of time. We can automate the build process by using the build tool like ant. We can download the ant tool from www.apache.org or we can use the tool that is supplied as part of a product like web logic. When we install web logic, ant will be as part of the directory d:\bea\weblogic81\ server\bin For running the ant tool set the path environment variable using the command shown below D:\ant>set PATH=d:\bea\weblogic81\server\bin\;%PATH% The ant tool will be able to do various tasks like compiling .java files, running the java application using JVM, creating the jar files etc We need to provide a build file (build.xml) with the information about various tasks that has to carried out by ant <project name="antproj" default="tone"> <target name="tone"> <mkdir dir="done"/> <mkdir dir="dtwo"/> </target> <target name="ttwo"> <delete dir="done"/> <delete dir="dtwo"/> </target> </project> D:\Pskr\ant>ant Buildfile: build.xml SUDHEER REDDY

17 POTHURAI tone: [mkdir] Created dir: D:\Pskr\ant\done [mkdir] Created dir: D:\Pskr\ant\dtwo BUILD SUCCESSFUL Total time: 1 second

D:\Pskr\ant>ant ttwo Buildfile: build.xml ttwo: [delete] Deleting directory D:\Pskr\ant\done [delete] Deleting directory D:\Pskr\ant\dtwo BUILD SUCCESSFUL Total time: 0 seconds

<project name="antproj" default="tone"> <property name="DIRONE" value="lib"/> <property name="DIRTWO" value="classes"/> <target name="tone"> <mkdir dir="${DIRONE}"/> <mkdir dir="${DIRTWO}"/> </target> <target name="ttwo"> <delete dir="${DIRONE}"/> <delete dir="${DIRTWO}"/> </target> </project> D:\Pskr\ant>ant Buildfile: build.xml tone: SUDHEER REDDY

18 POTHURAI [mkdir] Created dir: D:\Pskr\ant\lib [mkdir] Created dir: D:\Pskr\ant\classes BUILD SUCCESSFUL Total time: 0 seconds

D:\Pskr\ant>ant ttwo Buildfile: build.xml ttwo: [delete] Deleting directory D:\Pskr\ant\lib [delete] Deleting directory D:\Pskr\ant\classes BUILD SUCCESSFUL Total time: 0 seconds

We can provide the information about the properties in a saperate file like build.properties & use these properties from build.xml using <property file= "build.properties"/> tag DIRONE=lib DIRTWO=classes build.properties <project name="antproj" default="tone"> <property file="build.properties"/> <target name="tone"> <mkdir dir="${DIRONE}"/> <mkdir dir="${DIRTWO}"/> </target> <target name="ttwo"> <delete dir="${DIRONE}"/> <delete dir="${DIRTWO}"/> </target> </project> D:\Pskr\ant>ant Buildfile: build.xml SUDHEER REDDY

19 POTHURAI tone: [mkdir] Created dir: D:\Pskr\ant\lib [mkdir] Created dir: D:\Pskr\ant\classes BUILD SUCCESSFUL Total time: 0 seconds

Create directory src & save java files in that directory. public class COne { public void methodOne( ) { System.out.println("---method one---"); } } public class CTwo { public void methodTwo( ) { System.out.println("---method two---"); } } public class App { public static void main(String a[ ]) { COne o1=new COne( ); CTwo o2=new CTwo( ); o1.methodOne( ); o2.methodTwo( ); } } BDIR=build LDIR=${BDIR}\\lib CDIR=${BDIR}\\classes SDIR=src

SUDHEER REDDY

20 POTHURAI <project name="antproj" default="all"> <property file="build.properties"/> <target name="all" depends="cdirs,compile,pack"> <echo message="Build process completed"/> </target> <target name="cdirs"> <mkdir dir="${LDIR}"/> <mkdir dir="${CDIR}"/> </target> <target name="compile"> <echo message="Now compiling the classes"/> <javac srcdir="${SDIR}" destdir="${CDIR}" includes="*.java"/> </target> <target name="pack"> <jar basedir="${CDIR}" jarfile="${LDIR}\\ourwapp.jar" /> </target> <target name="run"> <java classname="App" classpath="${LDIR}\\ourwapp.jar" /> </target> <target name="ddirs"> <delete dir="${BDIR}"/> </target> <target name="rebuild" depends="ddirs,all"> </target> </project> D:\Pskr\ant>ant Buildfile: build.xml cdirs: [mkdir] Created dir: D:\Pskr\ant\build\lib [mkdir] Created dir: D:\Pskr\ant\build\classes compile: [echo] Now compiling the classes [javac] Compiling 3 source files to D:\Pskr\ant\build\classes pack: [jar] Building jar: D:\Pskr\ant\build\lib\ourwapp.jar all: [echo] Build process completed BUILD SUCCESSFUL Total time: 4 seconds

SUDHEER REDDY

21 POTHURAI

D:\Pskr\ant>ant rebuild Buildfile: build.xml ddirs: [delete] Deleting directory D:\Pskr\ant\build cdirs: [mkdir] Created dir: D:\Pskr\ant\build\lib [mkdir] Created dir: D:\Pskr\ant\build\classes compile: [echo] Now compiling the classes [javac] Compiling 3 source files to D:\Pskr\ant\build\classes pack: [jar] Building jar: D:\Pskr\ant\build\lib\ourwapp.jar all: [echo] Build process completed rebuild: BUILD SUCCESSFUL Total time: 1 second D:\Pskr\ant>ant run Buildfile: build.xml run: [java] ---method one--[java] ---method two--BUILD SUCCESSFUL Total time: 0 seconds Java Mail: Various companies are provided the java bean components to carrying out the routine tasks like sending & receiving the mails, accepting the credit card payments, sending sms messages etc Information about some of the java bean components can be obtained from the sites like www.jars.com, www.componentsource.com. eone etwo JAMES srv (mail server)

mx of gmail (mail extension) SUDHEER REDDY

22 POTHURAI 196.12.100.1 SMTP POP

java MCOne

java MCTwo

196.12.100.2 196.12.100.3 For sending the mail to a mail server SMTP (Simple Mail Transfer Protocol) can be used & for receiving the mails POP (Post office Protocol) can be used. Procedure for setting up the JAMES mail server: 1) Creating a directory (ex: - d:\mailsrv) 2) Copy james-2.1.3.zip to d:\mailsrv 3) Open the DOS window & use cd command to move to mailsrv directory. 4) Extract the content of the zip file using the command shown below. D:\mailsrv>jar xf james-2.1.3.zip Note: - When the above command is executed a directory with the name james-2.1.3 will be created & various files of the James server will be copied. Procedure to start the JAMES server: 1) Set the environment variable JAVA_HOME to the directory in which the java software is installed D:\mailsrv\james-2.1.3>set JAVA_HOME= D:\java\jdk1.5.0\ 2) Using cd command move to the bin directory which is sub directory of james-2.1.3 D:\mailsrv\james-2.1.3>cd bin 3) For starting the JAMES server use run.bat on windows & run.sh on UNIX / Linux D:\mailsrv\james-2.1.3\bin>run.bat Using PHOENIX_HOME: D:\mailsrv\james-2.1.3 Using PHOENIX_TMPDIR: D:\mailsrv\james-2.1.3\temp Using JAVA_HOME: D:\java\jdk1.5.0 Phoenix 4.0.1 James 2.1.3 Remote Manager Service started plain:4555 POP3 Service started plain:110 SMTP Service started plain:25 NNTP Service started plain:119 Fetch POP Disabled Procedure for creating the accounts on the JAMES server: 1) Start telnet client Start run telnet.exe 2) Run the following command for opening the connection with the JAMES server Microsoft Telnet>open localhost 4555 3) Provide root as username & root as password. 4) Use the following 2 commands for creating two email (user) accounts. SUDHEER REDDY

23 POTHURAI adduser eone passone adduser etwo passtwo 5) Use quit command for disconnecting from the JAMES server.

In order to run the java application MCOne, MCTwo we must set the class path pointing to sinetfactory.jar D:\mailsrv>set CLASSPATH=.;sinetfactory.jar import com.jscape.inet.smtp.*; import com.jscape.inet.email.*; public class MCOne { public static void main(String a[ ])throws Exception { Smtp smtp=new Smtp("localhost"); smtp.setPort(25); smtp.connect( ); EmailMessage em=new EmailMessage( ); em.setTo("eone@localhost"); em.setSubject("First Mail"); em.setFrom("myname@mycomp.com"); em.setBody("This is my first test mail \r\n Thanks \r\n Student \r\n"); smtp.send(em); smtp.disconnect( ); } } D:\mailsrv>javac MCOne.java D:\mailsrv>java MCOne D:\mailsrv>java MCOne import java.util.*; import com.jscape.inet.pop.*; import com.jscape.inet.email.*; public class MCTwo { public static void main(String a[ ])throws Exception { Pop pop=new Pop("localhost","eone","passone"); pop.setPort(110); pop.connect( ); SUDHEER REDDY

24 POTHURAI Enumeration emList=pop.getMessages( ); while(emList.hasMoreElements( )) { Object o=emList.nextElement( ); EmailMessage em=(EmailMessage)o; System.out.println(em.getFrom( )); System.out.println(em.getSubject( )); System.out.println(em.getBody( )); System.in.read( ); System.in.read( ); } pop.disconnect( ); } } D:\mailsrv>javac MCTwo.java D:\mailsrv>java MCTwo myname@mycomp.com First Mail This is my first test mail Thanks Student myname@mycomp.com First Mail This is my first test mail Thanks Student Filter: -A Filter is a java object that provides the implementation of javax.servlet.Filter. As part of the Filter interface 3 life cycle methods are provided 1) void init(FilterConfig filterConfig) throws ServletException . The web container is responsible for calling the init( ) method after creating the Filter object. Generally web container creates a Filter object while stating a web application. 2) void destroy( ) Web container is responsible for calling the destroy( ) method before removing the Filter object. Generally the Filter objects will be removed while stopping the web application. 3) void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException Web container is responsible for calling the doFilter( ) method for processing a request & this method is similar to the service( ) method of a servlet. import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class FOne implements Filter { FilterConfig fconfig; SUDHEER REDDY

25 POTHURAI public void FOne( ) { System.out.println("--- FOne created ---"); } public void init(FilterConfig fconfig) throws ServletException { System.out.println("--- FOne.init ---"); this.fconfig=fconfig; } public void doFilter(ServletRequest req, ServletResponse resp, FilterChain fc) throws IOException, ServletException { System.out.println("--- FOne.doFilter ---"); fc.doFilter(req,resp); } public void destroy( ) { System.out.println("--- FOne.destroy ---"); this.fconfig=null; } } D:\Pskr>javac FOne.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class FTwo implements Filter { FilterConfig fconfig; public void FTwo( ) { System.out.println("--- FTwo created ---"); } public void init(FilterConfig fconfig) throws ServletException { System.out.println("--- FTwo.init ---"); this.fconfig=fconfig; } public void doFilter(ServletRequest req, ServletResponse resp, FilterChain fc) throws IOException, ServletException { System.out.println("--- FTwo.doFilter ---"); fc.doFilter(req,resp); } public void destroy( ) { System.out.println("--- FTwo.destroy ---"); this.fconfig=null; } } D:\Pskr>javac FTwo.java <web-app> <filter> <filter-name>fo</filter-name> <filter-class>FOne</filter-class> SUDHEER REDDY

26 POTHURAI </filter> <filter> <filter-name>ft</filter-name> <filter-class>FTwo</filter-class> </filter> <filter-mapping> <filter-name>fo</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>ft</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app> <% System.out.println("-- one.jsp--"); %> OP of one.jsp <% System.out.println("-- two.jsp--"); %> OP of two.jsp Start the server --- FOne.init ----- FTwo.init --http://localhost:8000/filter/one.jsp --- FOne.doFilter ----- FTwo.doFilter ---- one.jsp-OP of one.jsp http://localhost:8000/filter/two.jsp --- FOne.doFilter ----- FTwo.doFilter ---- two.jsp-OP of two.jsp /one.jsp /* one.jsp FCone Browser /* two.jsp FTwo /two.jsp

SUDHEER REDDY

27 POTHURAI Web container Browser

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class SecFil implements Filter { public void genLoginForm(PrintWriter out) { out.println("<html> <head> <title> login </title>"); out.println("</head> <body>"); out.println("<form action=\"index.html\">"); out.println("User Name"); out.println("<input type=\"text\" name=\"uname\">"); out.println("<br> Password"); out.println("<input type=\"password\" name=\"pwd\">"); out.println("<br> <input type=\"submit\" value=\"Login\">"); out.println("</form> </body> </html>"); } FilterConfig fconfig; public void init(FilterConfig fconfig) throws ServletException { this.fconfig=fconfig; } public void doFilter(ServletRequest req, ServletResponse resp, FilterChain fc) throws IOException, ServletException { HttpServletRequest request=(HttpServletRequest)req; System.out.println("--- SecFil.doFilter ---"); HttpSession session=request.getSession(false); String vuname=request.getParameter("uname"); String vpwd=request.getParameter("pwd"); if(session==null) { if(vuname==null && vpwd==null) { System.out.println("---NLI, no uname/ pwd provided ---"); HttpServletResponse response=(HttpServletResponse)resp; PrintWriter out=response.getWriter( ); genLoginForm(out); } else { if(vuname.equals("usunil") && vpwd.equals("psunil")) { request.getSession(true); System.out.println("--- LI ---"); SUDHEER REDDY

28 POTHURAI fc.doFilter(req,resp); } else { HttpServletResponse response= (HttpServletResponse)resp; PrintWriter out=response.getWriter( ); genLoginForm(out); } } } else { fc.doFilter(req,resp); } } public void destroy( ) { System.out.println("--- SecFil.destroy ---"); this.fconfig=null; } } D:\Pskr>javac SecFil.java <web-app> <filter> <filter-name>sf</filter-name> <filter-class>SecFil</filter-class> </filter> <filter-mapping> <filter-name>sf</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app> <html> <head> <title>index.jsp</title> </head> <body> <a href="one.jsp">one.jsp</a><br> <a href="two.jsp">two.jsp</a><br> <a href="thr.jsp">thr.jsp</a><br> <a href="logout.jsp">logout.jsp</a><br> </body> </html>

SUDHEER REDDY

29 POTHURAI <% System.out.println("-- one.jsp--"); %> OP of one.jsp <br> OP of one.jsp <% System.out.println("-- two.jsp--"); %> OP of two.jsp <br> OP of two.jsp <% System.out.println("-- thr.jsp--"); %> OP of thr.jsp <br> OP of thr.jsp <% System.out.println("-- logout.jsp--"); %> Thank for using this application. http://localhost:8000/filter/index.html --- SecFil.doFilter -----NLI, no uname/ pwd provided --User Name Password Click --- SecFil.doFilter --User Name Password Click --- SecFil.doFilter ----- LI --one.jsp Click two.jsp thr.jsp logout.jsp --- SecFil.doFilter ---- one.jsp-OP of one.jsp OP of one.jsp one.jsp two.jsp thr.jsp logout.jsp Click --- SecFil.doFilter ---- logout.jsp-Thank for using this application. import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class LogFil implements Filter { FilterConfig fconfig; SUDHEER REDDY

30 POTHURAI public void init(FilterConfig fconfig) throws ServletException { this.fconfig=fconfig; } public void doFilter(ServletRequest req, ServletResponse resp, FilterChain fc) throws IOException, ServletException { HttpServletRequest request=(HttpServletRequest)req; System.out.println("--- SecFil.doFilter ---"); ServletContext app=fconfig.getServletContext( ); app.log("-- Start of req details --"); app.log("-- URI --"+request.getRequestURI( )); app.log("-- HOST --"+request.getRemoteHost( )); app.log("-- End of req details --"); fc.doFilter(req,resp); } public void destroy( ) { System.out.println("--- SecFil.destroy ---"); this.fconfig=null; } } <web-app> <filter> <filter-name>lf</filter-name> <filter-class>LogFil</filter-class> </filter> <filter-mapping> <filter-name>lf</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app> http://localhost:8000/filter/thr.jsp --- SecFil.doFilter ---- thr.jsp-OP of thr.jsp OP of thr.jsp http://localhost:8000/filter/index.html --- SecFil.doFilter --one.jsp two.jsp thr.jsp logout.jsp Open the file localhost_log.2008-07-20 available in D:\Tomcat5.0\logs directory

SUDHEER REDDY

31 POTHURAI 2008-07-20 23:23:40 StandardContext[/filter]-- Start of req details -2008-07-20 23:23:40 StandardContext[/filter]-- URI --/filter/thr.jsp 2008-07-20 23:23:40 StandardContext[/filter]-- HOST --127.0.0.1 2008-07-20 23:23:40 StandardContext[/filter]-- End of req details 2008-07-20 23:25:49 StandardContext[/filter]-- Start of req details -2008-07-20 23:25:49 StandardContext[/filter]-- URI --/filter/index.html 2008-07-20 23:25:49 StandardContext[/filter]-- HOST --127.0.0.1 2008-07-20 23:25:49 StandardContext[/filter]-- End of req details

/xxx.jsp xxx.jsp Browser CompFil yyy.jsp Web container Web container can use the Filter for filtering/ modifying the output generated by the servlets (a Filter can be used to compress the output generated by a servlet or we can use a Filter for removing/ adding some of the tags in the content generated by the servlets). public class ClsOne { } D:\Pskr>javac ClsOne.java import java.io.*; import java.util.*; public class App { public static void main(String a[ ]) { ClsOne o1=new ClsOne( ); ClsOne o2=new ClsOne( ); ClsOne o3=new ClsOne( ); System.out.println(o1); System.out.println(o2); System.out.println(o3); } } D:\Pskr>javac App.java D:\Pskr>java App SUDHEER REDDY

32 POTHURAI ClsOne@82ba41 ClsOne@923e30 ClsOne@130c19b In the above program different object values are provided. public class ClsOne { public int hasCode( ) { return 1000; } } D:\Pskr>javac ClsOne.java import java.io.*; import java.util.*; public class App { public static void main(String a[ ]) { ClsOne o1=new ClsOne( ); ClsOne o2=new ClsOne( ); ClsOne o3=new ClsOne( ); System.out.println(o1.hasCode( )); System.out.println(o2.hasCode( )); System.out.println(o3.hasCode( )); } } D:\Pskr>javac App.java D:\Pskr>java App 1000 1000 1000 In the above program same object values are provided. So objects are provided multiple ways. In one case different values are provided & in other case same value is used.

SUDHEER REDDY