53513323-44648785-Java - Topics in Enterprise Architecture...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Topics in Enterprise Architecture 07MCA41 UNIT- I Introduction to JAVA Java is a programming language originally developed by Sun Microsystems and released in 1995 as a core component of Sun Microsystem s Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities. Java applications are typically compiled to bytecode (class file) that can run on any Java Virtual Machine (JVM) regardless of computer architecture. Java was initially called as OAK later it was renamed as JAVA in the year 1995. Write Once Run Anywhere Editions of Java 1.) Java SE 2.) Java EE 3.) Java ME JDK(Java Development Kit) 1.) Java Loader 2.) Javac - Compiler 3.) JAR Java ARchiver 4.) Jdb Java Debugger 5.) Javap Class file Disassembler 6.) Javah C header and stub generator 7.) Applet viewer 8.) Javaws Java Web Start 9.) Javadoc Java Documentation Java Applications 1.) Mobiles 2.) Games 3.) Blu Ray Disc 4.) NASA 5.) Web Sites Creating, Compiling and Executing a Java Program Create / Modify Source code Source code Compile Source code Bytecode Run Byte code Result any compilation errors JVM(Java Virtual Machine) A Java Virtual Machine (JVM) is a set of computer software programs and data structures that use a virtual machine model for the execution of other computer programs and scripts. The model used by a JVM accepts a form of computer intermediate Language commonly referred to as Java bytecode . JVM is an Interpreter for bytecode. Translating a Java program into bytecode makes it much easier to run a program in a wide variety of environments. JVM(Java Virtual Machine) In Java a program will be written once and the source program can be compiled into a special type of machine language code known as bytecode. Java Bytecode JVM Any Computer JVM Architecture Class loader subsystem Class files Method Area Heap Java Stacks PC Registers Native Method Stack Runtime Data Area Execution Engine Native Method Interface Native method libraries Java Buzzwords or Features 1.) Simple 2.) Secure 3.) Portable 4.) Object Oriented 5.) Robust 6.) Multithreaded 7.) Architecture Neutral 8.) Interpreted & High Performance 10.) Distributed 11.) Dynamic A Simple Program in Java import java.io.*; class Simple { public static void main(String args) { System.out.println( a simple program ); } } Compilation of Java Program 1.) After writing the source code 2.) Save it with .java extension. 3.) To Compile:javac pgmname.java 4.) Execution or Interpreting or Running:java pgmname or classname Polymorphism Static (Method Overloading) Dynamic (Method Overriding) 1.)Static /(Early Binding)/(Compile Time) 2.) Dynamic/(Late Binding)/(Run Time) Datatypes and Other Tokens, Boolean Variables Datatypes Integers Byte Int Short long Floating-point Characters Boolean Float Char Boolean Double Datatypes and Sizes Datatypes Width(in Bits) 1.)Long 2.)Int 3.)Short 4.)Byte 5.)Double 6.)Float 7.)Char 8.)Boolean 64(8) 32(4) 16(2) 8 (1) 64(8) 32(4) 16(2) True/False Identifiers, Literals Identifiers in Java are used as:(i) Class Names (ii) Method Names (iii) Variable Names Literals:Any constant value in java is created by using a literal representation. E.g:- int a=100; char c= x Tokens In a Java program, all characters are grouped into symbols called tokens. There are six kinds of Tokens available in Java. Each Token should be identified in Java programs. Token <= identifier | keyword | separator | operator | literal | comment 1.)Identifiers: names the programmer chooses 2.)Keywords: names already in the programming language 3.)Separators (also known as punctuators): punctuation characters and paired-delimiters 4.)Operators: symbols that operate on arguments and produce results 5.)Literals (specified by their type) 6.)Comments Last Whitespaces. OOP ( Object Oriented Programming) 1.) Encapsulation 2.) Inheritance 3.) Polymorphism Access Specifiers Private No Modifier Protected Public Same Class Yes Yes Yes Yes Same Package Subclass No Yes Yes Yes Same Package non subclass No Yes Yes Yes Different Package Subclass No No Yes Yes Different Package non Subclass No No Nos Yes Streams There are Two types of Streams:1.) Byte Streams 2.) Character Streams InputStream Byte Stream Classes OutputStream Reader Character Stream Classes Writer Streams Input Stream ------------------------- System.in Print Stream -----------System.out, System.err Streams Print() Output Println() Buffered Reader Read() Readline() Buffer Input Stream Reader Input Java Program Control Statements Control Statements Selection(conditional) if Nested if s if-else-if Switch Nested Switch Iteration(loops) Jump For Return While Break Dowhile Continue Type Conversion and Type Casting Rules are:1.) The two types should be compatible 2.) The destination type should be larger than the source type Range increases Byte, short, int, long, float, double Java Escape Sequences CharacterEscapeSequence \b \t \n \f \r \\ \ \ Name Backspace Tab Linefeed Formfeed Carriage Return Backslash Single Quote Double Quote Operators and Expressions Operator + * / % ++ += -= *= /= %= -- Result Addition Subtraction Multiplication Division Modulus Increment Addition Assignment Subtraction Assignment Multiplication Assignment Division Assignment Modulus Assignment Decrement Bitwise Operators Operator ~ & | ^ >> >>> << &= |= ^= >>= >>>= <<= Result Bitwise unary NOT Bitwise AND Bitwise OR Bitwise exclusive OR Shift right Shift right zero fill Shift left Bitwise AND assignment Bitwise OR assignment Bitwise exclusive OR assignment Shift right assignment Shift right zero fill assignment Shift left assignment Relational Operators Operator == != > < >= <= Result Equal to Not equal to Greater than Less than Greater than or equal to Less than or equal to Boolean Logical Operators Operator & | ^ || && == != ! &= |= ^= ?: Result Logical AND Logical OR Logical XOR( exclusive OR) Short circuit OR Short circuit AND Equal to Not equal to Logical Unary NOT AND assignment OR assignment XOR assignment Ternary if-then-else The Assignment Operator Var=expression; e.g:- int a,b,c; a=b=c=54; The ? Operator:- (Ternary Operator) Expression ? Expression2 : Expression3 Operator Precedence. Highest:(),,.,++,--,~,!,*,/,%,+,-,>>,>>>, <<,>,>=,<,<=, ==,!=,&,^,|,&&,||,?:,=,op= Lowest. String Handling Methods in String Handling are:1.)length(); 2.)concat(); 3.)toString(); Character Extraction Methods:1.)charAt(); 2.)getChars(); 3.)getBytes(); 4.)toCharArray(); String Handling String Comparison Methods are:1.)equals() and equalsIgnoreCase() 2.)regionMatches() 3.)startsWith() , endsWith() 4.)compareTo() Searching of Strings:1.)indexOf() 2.)lastIndexOf() String Handling Modifying a String:1.)substring() 2.)concat() 3.)replace() 4.)trim() Data conversion using valueOf(). Changing the case of characters with in a String:1.)toLowerCase() 2.)toUpperCase() II -UNIT Classes A Class is a Template for an Object, an Object is an instance of a Class. The base class for all classes in Java is Object Class. All other classes are subclasses of Object class. The Object class defines few methods, that implies they are available in every object. Classes Syntax:Class classname{ type instance-variable1; type iv2; type methodname1() {} type methodname2(parameter-list) {} } Object Class Method 1.)Object clone() Purpose - creates a new object same as the object being cloned. 2.)boolean equals(Object object) checks whether one object is equal to another. 3.)void finalize() - called before an unused object is recycled. Object Class Method Purpose 4.)Class getClass() Obtains the class of an object at run time. 5.) int hashCode() Returns the hashcode associated with the invoking object. 6.) void notify() - Resumes execution of a thread waiting on the invoking object. Object Class Method Purpose 7.) void notifyAll() - Resumes execution of all threads waiting on the invoking object. 8.)String toString() Returns a string that describes the object. 9.)void wait() 10.)void wait(long milliseconds) 11.)void wait(long milliseconds, int nanoseconds) waits on another thread of execution Constructors A class contains constructors that are invoked to create objects from the class blueprint. Constructor declarations look like method declarations except that they use the name of the class and have no return type. As with methods, the Java platform differentiates constructors on the basis of the number of arguments in the list and their types. we cannot write two constructors that have the same number and type of arguments for the same class, because the platform would not be able to tell them apart. Doing so causes a compile-time error. You don't have to provide any constructors for your class, but you must be careful when doing this. The compiler automatically provides a no-argument, default constructor for any class without constructors. This default constructor will call the no-argument constructor of the superclass. In this situation, the compiler will complain if the superclass doesn't have a no-argument constructor so you must verify that it does. If your class has no explicit superclass, then it has an implicit superclass of Object, which does have a no-argument constructor. You can use access modifiers in a constructor's declaration to control which other classes can call the constructor. Rules for Constructors:1.) Constructors can use any access modifier, including private. 2.) the constructor name must match the name of the class. 3.)constructors must not have a return type. 4.)A method will have a return type but constructor will not have any return type. E.g:- Constructor 1.)class Foo { Foo() {} } 2.)class Foo { int size; String name; Foo(String name,int size) { this.name=name; this.size=size; } } Method Overloading When a class has more than one method with same name but with different parameters we call it as Method Overloading. Method Overriding When a method in the subclass has the same name and type signature as a method in the super class than the method in the subclass is said to be as over ridden method. Arrays An array is used to store a collection of data. It is a collection of homogeneous elements. Array is used to store a fixed size sequential collection of elements of the same type. Packages A Package is a container for a group of classes that are used to keep the class name space compartmentalized. They are stored in a hierarchical manner and are explicitly imported into new class definitions. Packages Hierarchy of Packages in Java:Java Lang Util IO AWT Packages 1.)When the programs are with in the package to compile we have to specify at that package level a.)javac *.java b.)Java class name(where main method exists) 2.) When main method is outside the package Compile with in the package but run or execute the program outside the package. 3.)To create the package javac d . Clsname .java While compiling:- java pkgname.clsname Abstract Methods A Method with complete body is called as Concrete Method, with out body is called as Abstract Method. Methods which are incomplete are called as Abstract Methods. A class which contains Abstract Methods must be declared as Abstract which is a keyword in Java. By using Abstract methods we cannot create any objects only references can be created. Abstract Methods Notation:abstract class A { abstract void m1(); void m2()---- Concrete Method {} } Interfaces In Interfaces all the methods must be Abstract Methods. Interfaces are syntactically similar to classes but all the methods are declared with out body. Interfaces are declared by using Interface keyword. Once the interfaces are defined any number of classes cam implement that interface. By default all the methods in interface are public, abstract. By default all the variables in interface are static, final. Interfaces Java allows only single inheritance for class extension, but multiple extensions for interfaces. E.g:Public class Newclass extends Baseclass implements Int1,Int2 ..Intn An interface can inherit other interfaces using the extends keyword such an interface is called as a subinterface. E.g:- interface iface3 extends iface1,iface2 .ifacen Interfaces E.g:Interface iface1 { void method1(); void method2(); } Class A implements iface1 { public void method1(){} public void method2(){} } Differences - Interfaces and Abstract Classes 1.)All the methods in interface are abstract methods where as abstract classes can contain both abstract methods and concrete methods. 2.) In interfaces all the variables are by default public, static and final where as in abstract classes we have to declare explicitly. 3.)In interfaces all methods are by default public and abstract where as in abstract classes we have to explicitly declare the methods as abstract. Exception Handling An Exception is an abnormal condition that disturb the normal program flow execution. Difference between Error and Exception is Error signify drastic failures which cannot be handled by the programmer. E.g:- Stack Overflow Exception Handling Throwable Error Exception Checked Unchecked Exception CheckedExceptions UncheckedExceptions IOException NullPointerException ClassNotFound ArrayIndexOutOfBounds CloneNotSupported ArithMeticException NoSuchMethod ClassCastException NoSuchFieldException SQLException Exception Handling Different types of exceptions available in Java are :1) ArithmeticException ex:- division by zero 2)IOException :- which are frequently occured at Input Output Operations time. 3) ArrayIndexOutofBounds:-Occurs when you are trying to access the element whose index is greater than length of our array. Exception Handling 4) NullPointerException:-Occurs when you are trying to perform operations on the values not yet initialized. 5) StringIndexOutofBounds:- Same as ArrayIndexOutofBounds 6) FileNotFoundException:- If you are trying to access the file which is not available. Exception Handling 7)NumberFormatException:- Occurs when we are trying to assign value to the variable which is of different type. 8)ClassNotFoundException:- If the accesing class is not available in the current directory. 9)NoSuchMethodException:- Occurs when you call the method which is not available in the current class. Exception Handling Exception Handling in Java is managed by Five keywords:1.)try 2.)catch 3.)throw 4.)throws 5.)finally INNER CLASSES Inner classes are also called as Nested classes. It is a class which is declared in another class. Some properties of Inner classes are:1.)We can use the classname only with in the defined scope, the name of the inner class must be different from the outer class. 2.)the inner class can use both class and instance variables of enclosed classes and final local variables of enclosing blocks. INNER CLASSES 3.)the inner class can be defined as abstract. 4.)the inner class can have any access specifier. 5.)the inner class can act as an interface implementer. 6.)Same type of variables can be called from both inner and outer classes. Applets Applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as a part of a web document. Applets are created to distribute Java code they are default GUI's. They will be loaded as documents which can be executed either using the Browser or AppletViewer utility. Applets Life Cycle of an Applet:Init() Start() paint() Stop() destroy() Applets When applet is loaded for the first time the init() method is going to be invoked from there the flow will be transferred to the start() which executes the paint() if exists. If Applet got focus the start() is going to be executed, the stop() is going to be executed when ever the focus lost. If Applet is terminated the Stop() and destroy() are going to be executed. Applets 1.)init()- The init() is invoked after the applet is created. If a subclass of Applet has an initialization to perform, it should override this method. It is the first method called in every Applet. 2.)start()- The start() is invoked after the init(). It is also called when user returns to the Web page containing the applet after surfing the pages. 3.)stop()- The stop() is invoked when user leaves the page. Applets 4.)destroy()- the destroy() is invoked when the browser exits normally to inform the applet that it is no longer needed and should release any resources it has allocated. Applets are Event Driven. The execution of an Applet will not start with main method. Applets Two types of applets are:1.)Applet Class(which uses AWT) 2.)Swing Class(JApplet) AWT-stands for Abstract Window Toolkit. AWT components can be decorated directly over Frame or Applet. Two types of Executable programs in Java are:1.)Java Applications(standalone) 2.)Java Applets(Distributed) Applets To Load Applet:<applet code=name width=XXX height=XXX> </applet> 1.)Applets dont need a main method. 2.)Applets must be run under an applet viewer or a Java compatible browser. 3.)User I/O is not accomplished with Java's Stream IO Classes.Instead,applets use the interface provided by the AWT. Hierarchy of Applets and Swing Object Component Container Window Panel Frame Applet JFrame JApplet Applets The HTML Applet Tags are:1.)codebase 2.)code 3.)alt 4.)name 5.)width, height 6.)align 7.)vspace, hspace 8.)<param name=name value= somename > Applet Display Methods 1.)update() 2.)paint() 3.)setBackground() 4.)setForeground() 5.)getBackground() 6.)getForeground() The default foreground color is black, background color is light gray. Event Handling and Delegation An event is an unexpected external happening in the context of hardware.Forexample when we press a key the electronic device inside the keyboard interrupt the system to send the keycode . So that the system respond immediately by halting whatever it was doing. In this EventDrivenProgramming, the user control the sequence of operations that the application executes.In event driven application the program will construct the various GUI Components displayed those components and then enters into a tightly loop weighting for user events to request an operation. In java all the events are objects which describes the state change in a source , the java.awt.event package defines a set of event classes for the respective event type through this package ,the objects of various event classes are constructed when ever the user activates the respective GUI components. Event Handling and Delegation The Programmer has to handle these generated events for example when the user clicks on the button, the JVM constructs an object of an action event class in which it stores all the details like when and where the event is generated. If we donot handle this generated event then the event is simply ignore .In GUI program the generated events are handled with the concept of event delegation. EventDelegation: The process of assigning an object to handle the events is called event delegation,the event handling objects are called listeners. for example to inform a button component that it should delegate action event to some listener, we call the add actionListener method of button class by passing a reference of the desired listener. every component class in awt has addlistener method to each event type that the component generates. when a button with actionlistener is clicked then the listener receives an action event object and executes its action performed method .there are two ways of delegating an event to the listener 1)delegating an event to an external object 2)delegating to some object The Delegation Event Model has two parts:1.)Sources and Listeners. Event Sources are:1.)Button 2.)Checkbox 3.)Choice 4.)List 5.)Menu Item 6.)Scrollbar 7.)Text Components 8.)Window Event types and interfaces Available An Event is an object that describes a state change in a Source. A source is an Object that generates an Event. A Listener is an object that is notified when an event occurs. java.awt.event package contains the following classes for the respective event type. 1)ActionEvent 2)TextEvent 3)ItemEvent 4)WindowEvent 5)KeyEvent 6)FocusEvent 7)AdjustmentEvent 8)MouseEvent 9)Component Event 10)Container Event 11)Input Event 12)MouseWheelEvent the following are the interfaces available in java.awt.event package to handle the respective event types i.e 1)ActionListener 2)TextListener 3)ItemListener 4)WindowListener 5)KeyListener 6)FocusListener 7)AdjustmentListener 8)MouseListener 9)MouseMotionListener 10)Component Listener 11)Container Listener 12)MouseWheelListener 13)WindowFocusListener the following are the respective methods that are declared in the respective interfaces 1)ActionListener----->(Buttons,TextField,TextArea,List) public void actionPerformed(ActionEvent ae) 2)TextListener----->(TextFields,TextArea) public void textChanged(TextEvent te) 3)ItemListener------>( Checkbox,CheckboxGroup) public void itemStateChanged(ItemEvent ie) 4)WindowListener------>(Frames) public void windowOpened(WindowEvent we) public void windowClosed(WindowEvent we) public void windowClosing(WindowEvent we) public void windowActivated(WindowEvent we) public void windowDeactivated(WindowEvent we) public void windowIconified(WindowEvent we) public void windowDeiconified(WindowEvent we) 5)keyListener-------->(Buttons) public void KeyPressed(KeyEvent ke); public void keyReleased(KeyEvent ke); public void KeyTyped(KeyEvent ke); 6)FocusListener-------->(TextField,TextArea,Frames) public void FocusGained(FocusEvent fe); public void FocusLost(FocusEvent fe); 7)AdjustmentListener-------->(ScrollBar) public void adjustmentValueChanged(AdjustmentEvent ae); 8)MouseListener------------> public void mousePressed(MouseEvent me); public void mouseRelease(MouseEvent me); public void mouseClicked(MouseEvent me); public void mouseEntered(MouseEvent me); public void mouseExited(MouseEvent me); 9)MouseMotionListener--------->(ScrollBar) public void mouseMoved(MouseEvent me); public void mouseDragged(MouseEvent me); 10)ComponentListener---------> public void componentResized(ComponentEvent ce); public void componentMoved(ComponentEvent ce); public void componentShown(ComponentEvent ce); public void componentHidden(ComponentEvent ce); 11)ContainerListener---------> public void containerAdded(ContainerEvent ce); public void containerRemoved(ContainerEvent ce); 12)MouseWheelListener------------> public void mouseWheelMoved(MouseWheelEvent mwe); 13)WindowFocusListener------> public void windowGainedFocus(WindowEvent we) public void windowLostFocus(WindowEvent we) Layouts 1.)Flow Layout 2.)Border Layout 3.)Card Layout 4.)Grid Layout 5.)Grid Bag Layout 6.)Box Layout Layout Managers A layout manager is a Java object associated with a particular component.The layout manager controls the components contained with in it. Border Layout is the default Layout manager for a Frame. FlowLayout is the default layout manager for a Panel. 1)Flow Layout: This layout manager is the simplest layout manager in the awt,as the name says it will layout all the GUI elements in a flowing.Which is similar to word processor arranges words in a paragraph. the setLayout method of the container class is used to set the respective layout for the container.the constructors of this flowlayout class are 1)FlowLayout() ---->default alignment is center 2) BorderLayout: This layout manager will divide the entire space of the container into five zones i.e North,South,East,West,Center. This Layout manager is the default layout manager for the frame class,this border layout sizes its individual component so that automaticaly expand to fill the space available for them.The add method of the container class is use to add the individual components by specifiying the respective position such as f.add("North",b1); where f-> Frame Object b1->button Component So that button b1 is added at the north of the frame this BorderLayout can deal with only five components i.e for component located against four edges of the container, and one located centrally an occupies the entire space of the center of the container. 3)GridLayout:This enforces a gridbag layout for all the components of a container.we specify the number of gridrows and gridcolumns to the constructor of this gridlayout class such as f.setLayout(new GridLayout(2,2)); All the components will be added to the container with respect to the specific grid dimension so that the components are visible as matrix form, all the individual components will be added to the container with add methods such as f.add(b1); f.add(b2); etc....... GridLayout :GridLayout(int rows,int cols); GridLayout(int rows,int cols,int hs,int vs); add(Component); Box layout :public static Box createVerticalBox(); public static Box createHorizontalBox(); public static void createVerticalGlue(); public static void createHorizontalGlue(); Card Layout By using Card layout many screens or components can be displayed but only one at a time by selecting that particular component. First(container),previous(container), Next(container),last(container) Swing Swings are GUI(Graphical User Interface) based Application. Look and feel is the concept of Swing and the appearance of the Swing application is same in different platforms. AWT applications appearance is different in different platforms because Java depends on OS level to overcome this problem Netscape and other Scientists developed a set of classes called as JFC(Java Foundation Classes) java.awt.Graphics methods drawLine(x1,y1,x2,y2); drawRect(x,y,w,h)& fillRect(x,y,w,h) drawOval(x,y,w,h);&fillOval(x,y,w,h); drawRoundRect(x,y,w,h,xarc,yarc);& fillRoundRect(x,y,w,h,xarc,yarc); draw3DRect(x,y,w,h,boolean raised); fill3DRect(x,y,w,h,boolean raised); drawArc(x,y,w,h,stangle,total angle); fillArc(x,y,w,h,stangle,total angle); drawPolyline(x,y,int n); drawPolygon(x,y,int n);& fillPolygon(x,y,int n); drawString(String,x,y); setColor(Color); java.awt.Component class public void setSize(w,h); public void setBounds(x,y,w,h); public void setVisible(boolean); public setTitle(String); public void setBackground(Color); public void setForeground(Color); public Color getBackground(); public Color getForeground(); public void setPreferredSize(Dimension); public Dimension getPreferredSize(); public void setEnabled(boolean); public int isEnabled(); Icon Icon is an interface implemented in a class ImageIcon. Icon i1=new ImageIcon("image path"); Adapter classes MouseAdapter MouseMotionAdapter ComponentAdapter ContainerAdapter KeyAdapter WindowAdapter FocusAdapter javax.swing Both swing and awt packages are used to create the forms.AWT follows Event delegation model. awt methods internally call the native methods . Native methods which are written in other languages like c and c++.They are system dependent and awt components are heavy weight components . It requires more Memory ,Resources and more processing time. Look & feel of awt components are different for Heterogeneous operating systems. look means appearance and feel means interaction with user. For the above reasons java soft people provided another api that is JavaFoundationClasses(JFC). It is system independent. JFC is an extension to awt. So it is not replacement of awt. JFC contains so many packages. JFC contains :---> 1) javax.swing:-->(x - means extension) To develop components like buttons , menus etc, to access windows like Jframe, Jpanel etc 2.)javax.event :- To access various events like mouse,keyboard,etc .. 3.)java.awt:- to access various layouts like flow,grid,border etc .. Features of JFC 1) JFC components are light -weight components . They use less System resourses. 2) JFC components have same look & feel on all platforms By using javax.swing.plaf package the programmer can change the look & feel of components. 3) JFC offers a rich set of components with lot of features. 4) JFC does not replace awt ,it is an extension. javax.swing components follow the model-view-control model --> represents state of the component. view --> How the component is represented graphically control-> Control view & model. 1) model stores the data that defines the state of the button or text present in the text field. 2) view creates visual representation of the component from the data in the model. 3) control deals with the users interaction with the components and modifies the model or the view in response to user action. JTabbedPane :JTabbedPane(); JTabbedPane(int orientation); JTabbedPane.TOP,BOTTOM,LEFT,RIGHT SwingConstants. TOP,BOTTOM,LEFT,RIGHT addTab(String label, Icon obj, Component, String tooltiptext); insertTab(String label, Icon obj, Component,String tooltiptext, int index); Annonymous Inner classes new xxxxListener() obj.addxxxxListener(new xxxAdapter() { methods... }); Multi Threaded Programming A Thread is a small process with in a program. To create a thread either we have to extend the Thread Class or implement the Runnable Interface. Methods in Thread class are:1.)getName 2.)getPriority 3.)isAlive() 4.)join Multi Threaded Programming Methods in Thread class are:5.)run 6.)sleep 7.)start Syntax java.lang.Thread class | public static Thread currentThread(); public void setName(String); public String getName(); public static void sleep(long ms) throws InterruptedException Syntax Thread(); Thread(String tname); Thread(Object obj,String tname); public void start(); public void run(); public boolean isAlive(); public void join() throws InterruptedException Syntax >>>>> thread priorities : Thread.MIN_PRIORITY 1 Thread.NORM_PRIORITY 5 (default) Thread.MAX_PRIORITY 10 public void setPriority(int); public int getPriority(); Threads A thread is a process or execution of a task,Performing only one task is called a Single Thread . In multitasking there are 2 types. 1) Process based multitasking:- Executing more than oneprogram ----------------------------------------simultaneously is called Process based Multitasking. 2) Thread based Multitasking:----------------------------------------Executing the different parts of the same program simultaneously is called Thread based Multitasking. Round Robin Executing the first program after the second program is called as Round Robin System. Threads are useful in two ways:------------------------------------------1) creation of animation and games. 2) Threads are used in an internet server to serve several clients simultaneously. Important Points 1) A thread is a sequential flow of control with in a program . Every program has at least one thread that is called the primaryThread. 2) Applications having only one thread is called single thread model. 3) The currentThread () method retrieves the reference of the currentthread. 4) Multithreaded applications have more than one thread. 5) The Thread class is used to create and manipulate the threads in a program. 6) You can use the Thread class or the runnable interface to implement the threads. Important Points 7) A thread can have the following states. a) New Thread : When an instance of Thread class is created,the thread enters into the newthread state. b) Runnable : When the start() method is invoked,the thread enters into the runnable state. c) NotRunnable : The thread is said to be in not runnable state if it is in * Sleeping. * Waiting. * Being blocked by another thread. d) Dead : A thread can be either die naturally or killed. A natural death when the loop in the run() method is complete. Important Points 1) The start() method of the Thread class is used to start the thread. 2) The run() method contains the code which the thread executes. 3) A thread can be put to sleep using the sleep() method. 4) The threads are scheduled based on the priorities. 5) The synchronized keyword is used to ensure that no threads access the same object simultaneously. 6) The methods wait(), notify(), notifyAll() are used for inter-thread communication. 7) Mutex : It is an object that is locked till a thread completes execution. JDBC JDBC JDBC stands for Java DataBase Connectivity PROCEDURE FOR ESTABLISHING THE DATABASE CONNECTION:1) Loading(Registering) the driver software into the memory 2) Establishing the connection from the front end application to the server.(Database) 3) Creating the statements corresponding to the connection generated. 4) Execute the created statements 5) Closing all the statements. Types of Drivers in JDBC are:1.)Jdbc-Odbc Bridge driver 2.)Native API Partly Java Driver 3.)Jdbc-Net Pure Java Driver 4.)Native Protocol Pure Java Driver Database connection 1) java.lang.Class class public static void forName("classname") throws java.lang.ClassNotFoundException; Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); >>>> DriverManager class public static Connection getConnection("url",["uname"],"[pwd]")throws SQLException uniform resource locator :"jdbc:odbc:datasourcename" Connection cn=DriverManager.getConnection("jdbc:odbc:oradsn1", "scott","tiger"); Java.sql package 1.)Driver Manager 2.)Connection 3.)Statement 4.)Resultset 5.)Resultsetmetadata 6.)Databasemetadata 7.)Prepared Statement 8.)Callable Statement Explanation ODBC API is a specification that is accessible to everyone as part of this specification. Microsoft design the functions like sqlConnect , sqldisconnect, sqlparse and sqlexecute. These functions can be used by the programmer to deal with different databases. So many companies has provided the implementation ofODBC API.These implementations are known as ODBC drivers. On windows we can get the files with the extension .DLL (Dynamic Link Library) which contains the implementation of functions. JDBC is an open specification which can be implemented by any one.The implementation of JDBC API is known as JDBC driver. All most all the JDBC driver vendors supplies a set of classes as part of JAR file Explanation A Java programmer need not learn different set of API s to write the programs to deal with different databases. As part of JDBC API specification java soft has specify different interfaces like Java.sql.driver Java.sql.conncection Java.sql.statement Java.sql.prepared Statement Java.sql.blob Java.sql.callable Statement ================================== And a set of classes like DriverManager ================================== Java.sql.Date Java.sql.Time Java.sql.TimeStamp , Java.sql.Types Explanation Any one can provide the implementation of above interfaces ex :Oracle Corp has provided the implementation of those interfaces to access oracle. A java programmer needs to know the following information to access a specific Database. a) The name of class that provides the implementation of java.sql.Driver interface. b)The format of jdbc URL NOTE :we can obtain the information from the documents provided by JDBC Driver vendor Classes12.jar is a JDBC Driver provided by oracle corporation as part of oracle PARSING The DataBase Servers are responsible for PARSING the sql statements submitted by the client. PARSING : Breaking up the sql statement into multiple pieces(tokens) for analyzing whether the statement follows the sql syntax or not. And checking the availability of different database objects used in sql statement. PREPARED STATEMENT :Prepared Statement stmt = con.preparedStatement( insert into tablename Values(?,?); Stmt.setInt(1,1); Stmt.setInt(2,1); Stmt.ExecuteUpdate(); PREPARED STATEMENT Prepared Statement stmt = con.preparedStatement( insert into MyTab Values(?,?); Stmt.SetInt(1,1); Stmt.SetInt(2,1); Stmt.ExecuteUpdate(); PROCEDURE FOR USING PREPARED STATEMENT 1) prepared statement stmt = con.preparedstatement( deleted from mytab where col1=?); 2.)Set the values of parameter using Stmt.setInt(1,1); method 3)To execute the statement using executeUpdate(); or by using executeQuery() method. Eg:- Prepared Statement stmt = con.preparedStatement( insert into emp(empno,ename) values(?,?); Stmt.SetInt(1,1); Stmt.SetString(2,Sone); Stmt.executeUpdate(); Explanation *) To get the information about a table we can use an interface ResultSetMetaData *) To execute the select statements we can use executeQuery(). It is not recommeneded to use executeUpdate(). 1) ExecuteQuery must be used for executing select statements and the return value is a Resultset object which can be used to fetch the rows from the database. 2) ExecuteUpdate has to be used for the execution of non-select statements and the return value is a integer.The return value gives the number of rows affected or changed or modified. ex :A ResultSet r1= Stmt.executeQuery( Select * from emp ); A JDBC programmer can access only one row at a time from the ResultSet when the ResultSet is created it will be pointing to before first row. SERVLETS Servlets Servlets are used to dynamically extend the functionality of a web server. Every Servlet is a class in Java. Server side applets are called as Servelts. They need to be deployed in a Web Server or Application Server. Servlets are small programs that are designed to execute on the server side of a Web Connection. They are platform independent. Server side programming can be develped using components like Servlets and JSP s. Servlets Life Cycle of a Servlet:1.)init() 2.)service() 3.)destroy(). Servlets need a Web server to deploy the Servlets. Apache Tomcat is used to deploy the Server side components which is a Web server to maintain Web Components of java. Web applications must be created to represent Servlets. Servlets The two important packages that are required to build Servlets are:1.)javax.servlet 2.)javax.servlet.http. The above two packages contains the classes and interfaces that are required to develop Servlets in Java. javax.servlet package The javax.servlet package includes the following interfaces:Interfaces Description 1.)Servlet 2.)ServletConfig 3.)ServletContext Declares life cycle methods for a Servlet. Allows Servlets to get initialization parameters Enables Servlets to log events and access information about their environment. 4.)ServletRequest Used to read data from a client request. 5.)ServletResponse Used to read data from a client response. 6.)SingleThreadModel Indicates that the Servlet is thread safe. javax.servlet package The javax.servlet package includes the following classes:Classes Description 1.)GenericServlet Implements the Servlet and ServletConfig interfaces. 2.)ServletInputStream Provides an Input Stream for reading requests from a client. 3.)ServletOutputStream Provides an Output Stream for writing responses to a client 4.)ServletException Indicates a Servlet error occurred. 5.)UnavailableException Indicates a Servlet is Unavailable. javax.servlet.http package The javax.servlet.http package includes the following interfaces:Interfaces Description 1.)HttpServlet Request Enables Servlets to read data from an Http request. 2.)HttpServletResponse Enables Servlets to write data to an Http response. 3.)HttpSession Allows session data to be read and written. 4.)HttpSessionBindingListener Informs an object that it is bound to or unbound from a session. javax.servlet.http package The javax.servlet.http package includes the following classes:Classes Description 1.)Cookie Allows state information to be stored on a client machine. 2.)HttpServlet Provides methods to handle Http requests and responses. 3.)HttpSessionEvent Encapsulates a session change event. 4.)HttpSessionBindingEvent Indicates when a listener is bound to or unbound from a value, or that a session attribute changed. Servlets 1.)Session Tracking (i)Cookies (ii)Http Session (iii)URL Rewriting (iv)Hidden form fields 2.)Request Dispatcher (i)include (ii)forward Java Server Pages(JSP) Client1 Client2 W E B S E R V E R JSP jspInit() Client1 _jspService() jspDestroy() JSP(Java Server Pages) Life Cycle of JSP:1.)JSP is translated into a Servlet. 2.)Translated Servlet is compiled. 3.)Loads into memory the compiled code. 4.)Creates object of the Servlet 5.)Executes jspInit() 6.) Executes _jspService() 7.)Finally executes the jspdDestroy() Java Server Pages(JSP) 1.)Scripting Elements of JSP are:a.)Scriplets b.)Declarations c.)Expressions 2.)Directives a.)Page Directive b.)include Directive c.)Taglib Directive Java Server Pages(JSP) Default Objects in JSP:1.)HttpServletRequest 2.) HttpServletResponse 3.)Page Context 4.)HttpSession 5.)ServletConfig 6.)ServletContext 7.)Object 8.)Throwable 9.)JSPwriter Request Response PageContext Session Config Context Page Exception Out Java Server Pages(JSP) JSP actions:1.)jsp:actionname 2.)jsp:forward 3.)jsp:include 4.)jsp:useBean 5.) jsp:setProperty 6.) jsp:getProperty 7.) jsp:plugin 8.)jsp:param Remote Method Invocation Remote Method Invocation RMI is a Specification to enable one JVM to invoke methods in an object of other JVM. The two JVM s may be in the same system or in different systems. RMI server can be implemented as Middle tier of 3-tier architecture, that enables us to invoke distributed components among network systems. RMI Server(Middle Tier) RMI Client Registers remote objects in RMI registry Searches for Remote Objects Database Remote Method Invocation Distributed Components of RMI:1.)RMI Server 2.)RMI Client 1.)RMI Server:- RMI Server is an application to register remote objects in RMI Registry. RMI Registry is a service in Java to maintain remote objects with unique name. 2.)RMI Client:-RMI Client is an application to search remote objects in RMI Registry. If search found then remote methods will be invoked. Remote Method Invocation RMI Architecture:1.)Skeleton/Stub Layer 2.)Remote Reference Layer 3.)Transport Layer RMI Architecture:Look up Client Application Stub Server Application Skeleton Remote Reference Layer Remote Reference Layer Transport Layer Transport Layer RMI Client RMI Server Explanation 1.)The client request will be received by stub, which is represented to the server application at client side. 2.)Stub requests will be interpreted by Remote Reference Layer 3.)The request will be sent to the remote network system through transport layer 4.)Client requests will be received by the Skeleton at server side and executes the original method. ServerSideProgramming (i)Creating Remote Interface:(a)Create one interface as sub interface of Remote there are no methods in the Remote Interface. (b)Declare all Remote methods(which will be invoked from any network system) in the interface and each method must throw Remote Exception. (ii)Create Implementation Class:(a)Create a class as subclass of UnicastRemoteObject implementation of Remote Interface .URO belongs to java.rmi.server.*; (b)Invoke Superclass constructor from implementation class(URO is superclass) (c)Define all Remote Interface methods in the class. ServerSideProgramming (iii)Create Server Application:(a) Create a class to register remote object in Rmi Registry. Naming Class:-to Register Public static void rebind( url ,remoteobject); url-rmi:://hostname[:port]/bindname Port-1099(default,optional) To Compile:1.)javac *.java 2.)rmic implclass 3.)start rmiregistry 4.)java serverapplication ClientSideProgramming (i) Create RMI Client application to search remote objects and to invoke remote methods. RMI Specifications 1)Create One Interface 2)Give the Implementation for that interface. 3)Binding 4)create client Application Rules For Creating Interface a) Our Interface must extends java.rmi.RemoteInterface. b) declare all the Business Logic methods . c) All the Business logic methods Should throws java.rmi.RemoteException Rules While Implementing the Interface a) our implementation class should extends java.rmi.server.UnicastRemoteObject b) Should provide non-argument constructor which throws java.rmi.RemoteException c) Should implements all the Business logic methods declared in our remote interface Enterprise JavaBeans Explanation EJB components are server-side components written entirely in the Java programming language EJB components contain business logic only - no system-level programming & services, such as transactions, security, life-cycle, threading, persistence, etc. are automatically managed for the EJB component by the EJB server. EJB architecture is inherently transactional, distributed, portable multi-tier, scalable and secure. EJB components are fully portable across any EJB server and any OS. EJB architecture is wire-protocol neutral--any protocol can be utilized like IIOP, JRMP, HTTP, DCOM, etc. Rapid application development Broad industry adoption Application portability Protection of IT investment EJBContainer:It contains set of applications to interact with our service object.Which provides a runtime environment for our EJB Components in the form of frameWork. Here FrameWork is nothing but libraries.The only difference is Libraries are used with in our application where as in frame work they are used our application. so FrameWork has to Know our application specification. so comming to the EJB EjbContainer is the FrameWork and application is nothing but EJBComponents. -> In EJB we are provide with different Components Like .Session Bean .Entity Bean .Message Driven Beans RemoteInterface:it contains all our Bussiness Logic Methods which throws java.rmi.RemoteException; it should extends javax.ejb.EJBObject HomeInterface:it contains life cycle methods which should throws java.rmi.RemoteException,javax.ejb.CreateExcep tion; it should extends javax.ejb.EJBHome BeanClass:it Should implements one of our EJBComponents that is (SessionBean,EntityBean) or MessageDrivenBean)should not implement our remote or home interface Should provide the definition for all our Business Logic Methods .Should give the corresponding definition for the life cycle methods define in home interface. Enterprise JavaBeans There are three kinds of Enterprise Beans: (i)Session Beans, (ii)Entity Beans, and (iii)Message-Driven Beans. A message-driven bean combines features of a session bean and a Java Message Service (JMS) message listener, allowing a business component to receive JMS. A message-driven bean enables asynchronous clients to access the business logic in the EJB tier. Entity Bean is a Java class which implements an Enterprise Bean interface and provides the implementation of the business methods. There are two types: Container Managed Persistence (CMP) and Bean-Managed Persistence (BMP). Session Bean is used to represent a workflow on behalf of a client. There are two types: Stateless and Stateful. Stateless bean is the simplest bean. It doesn't maintain any conversational state with clients between method invocations. Stateful bean maintains state between invocations. ...
View Full Document

This note was uploaded on 12/14/2011 for the course ENPM 603 taught by Professor Kumar during the Winter '09 term at Indian Institute of Technology, Kharagpur.

Ask a homework question - tutors are online