J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM Weblogic 8.1 Adminstration Guide http:\\localhost:7001\console adminserver - 7011 mainserver - 7013 mydomain - configuration name system : user id weblogic : password Name: MyJDBC Data Source JNDI Name : MYDSJNDI scott / tiger GDATA Connection Pool Name : MyJDBCConnectionPool C:\bea\user_projects\domains\mydomain startWeblogic (for Admin server) startManagedWeblogic mainserver localhost:7011 (7011 - admin port) ################################################################ ######################## WEBLOGIC 8.1 Excercise : Configure and Start a New Domain (configuration name is "mydomain") and Servers --------------------------------------------------------------------------------------------------------------1. Start the Configuration Wizard 2. Select "Create a new Weblogic Configuration " Click Next 3. Use "Basic Weblogic Server Domain" as the Configuration Template 4. Check the "Custom" radio button for Customer Configuration. Click Next 5. For the Administration Server Configuration , Specify Name: adminserver Listen Addss: localhost 1 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM Listen Port : 7011 SSL Listen Port : 7012 SSL ENABLED : YES CLICK NEXT 6. CHECK Yes on the " Managed Servers, Clusters, and Machine Options" Click Next 7. Click add Icon. Specify a Managed server as Name : mainserver List Addss : localhost List Port : 7013 SSL : 7014 SSL ENABLED : YES CLICK NEXT 8. Click Next on the Configure Clusters 9. Click Next on the Configure Machines 10. Enusre "No" on JDBC 11. Ensure "No' on JMS 12. User Name : system, Password : weblogic 13. Ensure "No" in the radio button and click next 14. Select "No" for Create Start Menu 15. Select the Development Mode radio button as the Weblogic Configuration Startup mode. select SUN JDK 16. specify "mydomain" as the COnfiguration Name 17. Click Done to exit wizard Start Admin server -------------------------------1. goto C:\bea\user_projects\domains\mydomain 2. setenv 3. startWeblogic (for Admin server) 2 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM <server started in Running Mode > Start MainServer -------------------------------1. goto C:\bea\user_projects\domains\mydomain ( Configuration Name is mydomain) 2. setenv 3. startManagedWeblogic mainserver localhost:7011 (7011 - admin port) <server started in Running Mode > Admin Console ------------http://localhost:7011/console system : user id weblogic : password URL ::: jdbc:oracle:thin:@localhost:1521:GDATA Driver Class Name ::: oracle.jdbc.driver.OracleDriver scott / tiger GDATA Connection Pool Name : MyJDBCConnectionPool First Create Connection Pool ---------------------------Mydomain - > services - > Jdbc - > Connection Pool . Click on a new JDBC Connection Pool Choose Database --------------Connection Pool Name : MyJDBC Connection Pool Database Type : Oracle Database Driver : Oracle's Thin Versions: 8.1.7, 9.0.1,9.2.0 Database Name : GDATA Host Name :localhost Database User : scott Database Pass : tiger 3 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM Next Create Datasource -----------------------Mydomain - > services - > Jdbc - > DataSource . Click on a new JDBC Datasource Configure Datasource --------------------Name: MyJDBC Data Source JNDI Name : MYDSJNDI Practical Day This December 2004 JSP StrutsServletJava ScriptJDBC (over) - DriverManager / DataSource - Statement / ResultSet 4 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM EJB- (pending) XML – JDOM (pending) LDAP (over coding, now doc reading pending) MQ Series (NOW) Jan 2004 XMLOracle- Regular Rational Rose Java CoreEJB- Tutorial Link -------------------------------------------------------------------------------------------------------Dos Prompt – EJB Deploy Make Jar the ejb module jar cvf tt.jar classes\com\ejb\stateless\H*.class META-INF\*.xml – wrong bcos package is com.ejb.stateless NOT from classes.com.ejb.* jar cvf tt.jar com\ejb\stateless\H*.class META-INF\*.xml - right Use ejbc java weblogic.ejbc tt.jar mm.jar java weblogic.ejbc -compiler javac tt.jar mm.jar java weblogic.ejbc -compiler javac.exe tt.jar mm.jar -------------------------------------------------------------------------------------------------------- EJB Lecture 5 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM http://www.javaperformancetuning.com/tips/j2ee_ejb.shtml Java Glossary http://mindprod.com/jgloss/anonymousclasses.html Java Lecture http://www.cs.umd.edu/class/spring2002/cmsc433-0201/Lectures/javapart7.pdf http://www.cs.umd.edu/class/spring2002/cmsc433-0201/Lectures/javapart6.pdf -------------------------------------------------------------------------------------------------------- 1. What are the types of Clustering in J2EE? ( J2EE) J2EE clusters usually come in two flavors: shared nothing and shared disk. In a shared-nothing cluster, each application server has its own file systems with its own copy of applications running in the cluster. Application updates and enhancements require updates in every node in the cluster. With this setup, large clusters become maintenance nightmares when code pushes and updates are released. In contrast, a shared-disk cluster employs a single storage device that all application servers use to obtain the applications running in the cluster. Updates and enhancements occur in a single file system and all machines in the cluster can access the changes. -------------------------------------------------------------------------------------------------------2. String Buffer Vs String? ( Core Java ) Strings however are immutable meaning they cannot be modified once created. Whenever you reassign the value of a String variable, in the background you are really creating another String object and telling the JVM to use the newly created String object as the placeholder for a variable. The String object is also the only object which overrides the "+" concatenation operator. This allows for Strings to be created based on the concatenation of one or more String objects. Consider a case where a String variable needs to be modified several times. Each time the value of that String variable is modified a new String object must be created. This will result in several String objects in memory awaiting garbage collection. Not to mention the additional CPU overhead of creating these new String objects. 6 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM The more efficient way to handle this is through the use of a String Buffer object. String Buffer object again stores an array of characters with some subtle differences. 1. It does not overload the "+" concatenation operator. 2. Its contents can be modified without creating a new String Buffer instance. Modifying the code above to take advantage of the String Buffer object requires only a few simple changes. Using the StringBuffer object only one object is used during the lifespan of the for loop. String Buffer acts like a pointer. StringBuffer a = new StringBuffer("ab"); StringBuffer b = a; a.append("cd"); System.out.println(b); OP : - abcd -------------------------------------------------------------------------------------------------------3. What are JSP Scope objects? ( JSP ) scope object are page , request , session , or application scope -------------------------------------------------------------------------------------------------------4. Types of Java.lang.reflect.Modifier in Java? ( Core Java ) Public, Private, Protected, Static, final, synchronized, volatile, transient, native, interface, abstract, strict Transient - You can reduce the size of your serialized object by marking some fields transient. The values of these fields won't be written. When the object is read back, it is up to you to reconstitute the fields. Note that you must manually reconstitute all the transient fields. Volatile (lock) - The volatile keyword is used on variables that may be modified simultaneously(at the same time) by other threads. This warns the compiler to fetch them fresh each time, rather than caching them in registers. This also 7 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM inhibits certain optimizations that assume no other thread will change the values unexpectedly. Since other threads cannot see local variables, there is never any need to mark local variables volatile. Synchronized() - During the execution of a synchronized method, the thread holds the monitor for that method's object, or if the method is static, it holds the monitor for that method's class. If another thread is executing the synchronized method, your thread is blocked until that thread releases the monitor (by either exiting the method or by calling wait()). A crucial method that must not be executed by two threads simultaneously. Only one thread at a time can own the lock for any given object. Thus if more than one thread tries to enter a section of code for which the lock must be acquired then only one thread will get the lock and all other threads will block. Note however that a thread can still execute a non-synchronized method or block of code even if the object is locked. In many applications is safe to have many reader threads simultaneously accessing a data structure, but only one writer thread. If there is a writer thread active, then all other reader and writer threads must be blocked. Arranging this is somewhat trickier that locking the entire datastructure for every read/write. -------------------------------------------------------------------------------------------------------5. What is Reflection in Java? ( Core Java ) Reflection is a feature in the Java programming language. It allows an executing Java program to examine or "introspect" upon itself, and manipulate internal properties of the program. For example, it's possible for a Java class to obtain the names of all its members and display them. import java.lang.reflect.*; public class DumpMethods { public static void main(String args[]) { try { Class c = Class.forName(args[0]); Method m[] = c.getDeclaredMethods(); for (int i = 0; i < m.length; i++) System.out.println(m[i].toString()); 8 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM } catch (Throwable e) { System.err.println(e); } } } -------------------------------------------------------------------------------------------------------6. Where Length , Length() and Size() is used ? ( Core java ) Length() – Returns length of the String & StringBuffer Size() – Returns the number of elements in this list (Array List and Vector) Length – Returns the number of elements in the String or Integer Array 7. What are the default <tld> files available in Struts? ( Struts) Struts-bean.tld Struts-html.tld Struts-logic.tld -----------------------------------------------------------------------------------------------------------------------8. What is start , notify, notifyAll, run in threads? ( Core Java) Start() - Causes this thread to begin execution; the Java Virtual Machine calls the run() method of this thread Yield() - Causes the currently executing thread object to temporarily pause and allow other threads to execute. Sleep() - Causes the currently executing thread to sleep Join() - Waits for this thread to die Destroy() - Destroys this thread, without any cleanup. 9 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM Notify() - Wakes up a single thread that is waiting on this object's monitor Notify All() - Wakes up all thread that are waiting on this object's monitor Wait() - Causes current thread to wait until another thread invokes the notify() or notifyAll() method for this object -----------------------------------------------------------------------------------------------------------------------9. What is cloneable ? ( Core Java) To make a field-for-field copy of instances of that class, using Object. clone() method. Cloneable is a marker interface. ------------------------------------------------------------------------------------------------------------------------ 10. What is marker interface ? ( Core Java) Empty interface (does not have any method definition, used for object cloning ) Eg:- Serializable interface is a marker interface -----------------------------------------------------------------------------------------------------------------------11. What is Synchronization? Why it is required? ( Core Java ) A monitor is simply a lock that serializes access to an object or a class. To gain access, a thread first acquires the necessary monitor, then proceeds. This happens automatically every time you enter a synchronized method. You create a synchronized method by specifying the keyword synchronized in the method's declaration. During the execution of a synchronized method, the thread holds the monitor for that method's object, or if the method is static, it holds the monitor for that method's class. If another thread is executing the synchronized method, your thread is blocked until that thread releases the monitor (by either exiting the method or by calling wait()). 10 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM -----------------------------------------------------------------------------------------------------------------------12. What is Throwable? ( Core Java) Throwable class is the super class of all errors and exceptions in the Java language -----------------------------------------------------------------------------------------------------------------------( Core Java) 13. What is Map, Hashmap, Hashset, Hashtable, Set, List, Hashcode, weakHashMap ? Map - An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value. HashMap / HashSet - It is unsynchronized and permits nulls. Map m = Collections.synchronizedMap(new HashMap(...)); Set s = Collections.synchronizedSet(new HashSet(...)); TreeMap – It is unsynchronized and keys are sorted WeakHashMap - entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. - It is unsynchronized and permits nulls. SortedMap - A map that further guarantees that it will be in ascending key order Set - collection that contains no duplicate elements Hashtable – It is Synchronized and non-null object used as Key or as a value. Properties - Each key and its corresponding value in the property list is a string ---------------------------------------------------------------------------------------------------------------------------- 11 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM 14. Convert String to int, float, double value ( Core Java)? a) String str = "1"; int intValue = Integer.parseInt(str); System.out.println(intValue); b) double dValue = Double.parseDouble(str); System.out.println(dValue); c) float fValue = Float.parseFloat(str); System.out.println(fValue); ---------------------------------------------------------------------------------------------------------------------------. Convert int value to String ? ( Core Java) int intValue = 1; String str = String.valueOf(intValue); System.out.println(str); float fValue = 1.02f; String str = ""; str = Float.toString(fValue); System.out.println(str); 12 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM ----------------------------------------------------------------------------------------------------------------------------------Convert String to Integer Object? ( Core Java) String str = "100"; Integer Inte = null; Inte = Integer.valueOf(str); System.out.println(Inte); ----------------------------------------------------------------------------------------------------------------------------------Convert Integer object to intValue ? ( Core Java) int intValuex = (new Integer(1000)).intValue(); System.out.println(intValuex); ----------------------------------------------------------------------------------------------------------------------------------14. 15. What is multithread and Single Thread in JSP object? (JSP) Single Thread – One user one request Multi Thread – One request for multiple user ----------------------------------------------------------------------------------------------------------------------------16. Difference between Interface and Abstract Class ? ( Core Java) Interfaces provide a form of multiple inheritance. An abstract class can have static methods, protected parts, and a partial implementation. Interfaces are limited to public methods and constants with no implementation allowed. 13 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM If you add a new method to an abstract class, you have the option of providing a default implementation of it. Then all existing code will continue to work without change. If you add a new method to an interface, you must track down all implementations of that interface in the universe and provide them with a concrete implementation of that method. Program - Abstract abstract class abstra { public void getSeconds(){ System.out.println("getSeconds"); getSec(); } public void getSec(){ System.out.println("getSec"); getTime(); } abstract public void getTime(); } public class first extends abstra { public void getTime(){ System.out.println("getTime"); } public static void main(String ss[]){ //first f = new first(); 14 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM abstra f = new first(); f.getSeconds(); } Program - Interface interface abstra { public void getSeconds(); } public class second implements abstra { public void getSeconds(){ System.out.println("getSeconds"); } public void getSec(){ System.out.println("getSec"); } public static void main(String ss[]){ second f = new second(); f.getSeconds(); } } ----------------------------------------------------------------------------------------------------------------------------- 15 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM 17. Difference between Vector and Array List (Core Java) ArrayList will never supercede Vector because Vector is synchronized and ArrayList is not. Therefore if you have an situation with multiple threads / users hitting on the same list then you either need to use Vector or wrap ArrayList in something that IS synchronized. If you want a synchronized ArrayList you can pass it to the Collections.synchronizedList() function and get back a synchronized version of the list you passed in. ----------------------------------------------------------------------------------------------------------------------------18. Difference between Aggregation and Inheritance? (Core Java) Aggregation relates instances. Inheritance relates Classes. ----------------------------------------------------------------------------------------------------------------------------- 19. Which is used for interacting with Mainframe from Java ? (Core Java) 1. 2. 3. 4. Java Adapter for Mainframe (Bea Weblogic) IMS Connector JOLT Java Connector Architecture ----------------------------------------------------------------------------------------------------------------------------20. What is Session Management ? ( JSP) HttpSession (session replication), Cookies, URL rewriting, Hidden Variable 16 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM ----------------------------------------------------------------------------------------------------------------------------21. Difference between Request.getDispatcher() and Response.sendRedirect()? (JSP) ----------------------------------------------------------------------------------------------------------------------------22. Life cycle of Servlet? ( JSP ) 1. Create and initialize the servlet (init() method) When a server loads a servlet, the server runs the servlet's init method. Initialization completes before client requests are handled and before the servlet is destroyed. Even though most servlets are run in multi-threaded servers, servlets have no concurrency issues during servlet initialization. The server calls the init method once, when the server loads the servlet, and will not call the init method again unless the server is reloading the servlet. The server can not reload a servlet until after the server has destroyed the servlet by running the destroy method. 2. Handle zero or more service calls from clients (Service() method) Invokes the service method, passing a request and response object. 3. Destroy the servlet and then garbage collect it (destroy() method) When a server destroys a servlet, the server runs the servlet's destroy method. The method is run once; the server will not run the destroy method again until after the server reloads and reinitializes the servlet. When the server calls the destroy method, another thread might be running a service request ----------------------------------------------------------------------------------------------------------------------------23. Difference between sequential diagram and Colloboration diagram? ( UML) sequential diagrams are used to model sequential logic. 17 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM communication diagrams, formerly known as collaboration diagrams in UML 1.x, can be used for because they provide a birds-eye view of a collection of collaborating objects. A collaboration diagram shows object interactions organized around the objects and their links to each other. Unlike a sequence diagram, a collaboration diagram shows the relationships among the objects independently of the time sequence. Collaboration diagrams and Sequence diagrams express similar information, but show it in different ways. ----------------------------------------------------------------------------------------------------------------------------- 24. What are the SQL Statements ? ( Database ) Statement- It will execute simple query PreparedStatement- It will execute precompiled query CallableStatement- It will execute StoredProcedure ----------------------------------------------------------------------------------------------------------------------------- 25. What is Garbage Collection ? (Automatic Memory Management) ( Core Java ) When such an object is no longer referenced then during garbage collection Java will invoke the finalize method before reclaiming the storage. System.gc(); Note that the finalize method is only called once. Note that finalize methods may be called in any order and from any thread. The main purpose of such methods is to allow the freeing of system (i.e. non-Java) resources associated with the object. Garbage collection cannot be forced. 18 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM The garbage collector runs in low memory situations When it runs it releases the memory allocated by an object. One of the most important features of the Java is garbage collection, also called automatic memory management. In Java while the program is running, the memory is being allocated with new operation. This allocated memory storage is not available until garbage collector sweeps away the unused objects. To make any object unusable make the reference variable pointing to that object as null pointer. In Java all the objects are garbage collected, when you make a null reference to the object. In Java you never explicitly free the memory allocated, instead the Java does automatic garbage collection. Example: public int GarMethod() { String s = new String("Test String"); System.out.println(s"); s = null; } In Java garbage collection is guaranteed only when the objects has null reference to it. The Java runtime system keeps track of the memory allocated and is able to determine whether the memory is still is usable or not. In the above example the object 's' is garbage collected by the Java Runtime System. But there is no guarantee that when the object is garbage collected. In Java, you can call System.gc() and Runtime.gc() methods , if you call these methods explicitly, the JVM makes efforts towards recycling the unused objects, but there is no guarantee that when the objects are garbage collected. In Java, it is a good idea to explicitly assign null into a variable when you have finished with it. Java does allow you to add a finalize() method to the class. The finalize() method will be called before the garbage collector sweeps away the object. In practice, we do not rely on the finalize() method for recycling any resources that are in short supply - you simply cannot know when this method will be called. Note: objects are garbage collected, not the reference 19 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM ----------------------------------------------------------------------------------------------------------------------------- 26. What is MVC ? ( Design Pattern ) Model – Business logic View – JSP Controller – Servlet Advantage :- Code Reusablility ----------------------------------------------------------------------------------------------------------------------------- 27. Define Load Testing, Volume Testing, Regression Testing, Unit Testing, Black box Testing, White Box Testing? ( Quality ) Load Testing – Simulating the Number of Users hit the Application, simulateneously. Volume Testing – Hitting the database Regression Testing – Testing the application before production stage Unit Testing – Testing the each module Black box Testing - Testing without background functionality or program logic White box Testing– Testing the program logic and different conditions scenario. ----------------------------------------------------------------------------------------------------------------------------- 20 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM 28. Define Code Walk through and Code Review ? ( Quality ) Code Review – Inspecting the code formally Code Walk through – Inspecting the code informally. ----------------------------------------------------------------------------------------------------------------------------29. Java Data Types? ( Core Java ) Byte – 8 bits Char (Unicode) , Short int – 16 bits Float , int – 32 bits Long, double – 64 bits --------------------------------------------------------------------------------------------- -------------------------30. What is Serialization? Why it is required in non-Clustering? (Core Java) Serialization is a way of "flattening", "pickling" or "freeze-drying" objects so that they can be stored on disk, and later read back and reconstituted, with all the links between objects intact. ----------------------------------------------------------------------------------------------------------------------30. What is HTTP Load Balancing and Session Replication ? ( J2EE) For Web applications, a hardware- or software-based HTTP load-balancer usually sits in front of the application servers within a cluster. These loadbalancers can be used to decrypt HTTPS requests quickly, distribute the load between nodes in the cluster, and detect server failures. The usual setup is to have a user session live entirely on one server that is picked by the loadbalancer. This is called a "sticky" session. HTTP session replication is expensive for a J2EE application server. If you can live with forcing a user to log in again after a server failure. 21 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM The term session replication is used when the current service state is being replicated across multiple application instances. Session replication occurs when the information stored in an HttpSession is replicated from, in this example, one servlet engine instance to another. This could be data such as items contained in a shopping cart or information being entered on an insurance application. Anything being stored in the session must be replicated for the service to failover without a disruption. The solution chosen for achieving Session replication is called in-memorysession-replication. It uses a group communication protocol written entirely in Java, called JavaGroups. JavaGroups is a communication protocol based on the concept of virtual synchrony and probabilistic broadcasting. To support automatic failover for servlet and JSP HTTP session states, WebLogic Server replicates the session state object in memory. This process creates a primary session state, which resides on the WebLogic Server to which the client first connects, and a secondary replica of the session state on another WebLogic Server instance in the cluster. The replica is always kept up-to-date so that it may be used if the server that hosts the servlet fails. The process of copying a state from one instance to another is called in-memory replication. Session Replication :In a clustered environment, you want session information to be immediately available to other servers in the cluster HTTP load-balancer probably provides all of the fail-over and load-balancing functionality you need, as far as HTTP requests go. ----------------------------------------------------------------------------------------------------------------------31. What is factory method ? (Core Java) is a sort of generic constructor that might produce any of a number of different kinds of objects eg:- Clone() method ------------------------------------------------------------------------------------------------------------------------32. What is Cookies? ( JSP ) 22 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM Creates a cookie, a small amount of information sent by a servlet to a Web browser, saved by the browser, and later sent back to the server. A cookie's value can uniquely identify a client, so cookies are commonly used for session management. The servlet sends cookies to the browser by using the HttpServletResponse.addCookie(javax.servlet.http.Cookie) method, which adds fields to HTTP response headers to send cookies to the browser, one at a time. The browser is expected to support 20 cookies for each Web server, 300 cookies total, and may limit cookie size to 4 KB each. The browser returns cookies to the servlet by adding fields to HTTP request headers. Cookies can be retrieved from a request by using the HttpServletRequest.getCookies() method. Several cookies might have the same name but different path attributes. ------------------------------------------------------------------------------------------------------------------------- 33. Define ActionForward, ActionMappiong, ActionForm? ( Struts ) ActionForm is a JavaBean optionally associated with one or more ActionMappings. Such a bean will have had its properties initialized from 23 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM the corresponding request parameters before the corresponding Action.execute method is called. ActionForms are JavaBeans, subclasses should also implement Serializable, as required by the JavaBean specification An Action is an adapter between the contents of an incoming HTTP request and the corresponding business logic that should be executed to process this request. The controller (RequestProcessor) will select an appropriate Action for each request, create an instance (if necessary), and call the execute method. Actions must be programmed in a thread-safe manner, because the controller will share the same instance for multiple simultaneous requests. This means you should design with the following items in mind. When an Action instance is first created, the controller will call setServlet with a non-null argument to identify the servlet instance to which this Action is attached. When the servlet is to be shut down (or restarted), the setServlet method will be called with a null argument, which can be used to clean up any allocated resources in use by this Action. An ActionForward represents a destination to which the controller, RequestProcessor, might be directed to perform a RequestDispatcher.forward or HttpServletResponse.sendRedirect to, as a result of processing activities of an Action class An ActionMapping represents the information that the controller, RequestProcessor, knows about the mapping of a particular request to an instance of a particular Action class. ActionServlet provides the "controller" in the Model-View-Controller. There can be one instance of this servlet class, which receives and processes all requests that change the state of a user's interaction with the application ------------------------------------------------------------------------------------------------------------------------- 34. Diff VBScript Vs Java Script? ( Script) VBScript – Microsoft ActiveX control can be used. Client side validation can be done only in IE. Java Script – Client side validation can be done in IE and Netscape browser. 24 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM ------------------------------------------------------------------------------------------------------------------------- 35. Package Vs Stored Procedure? ( Database) Package – collection of Function and Procedure Function – must return value Procedure – may or may return value (return using out parameter) Stored Procedure – compiled piece of re-usable procedure. One time compile and execute at any number of time. ------------------------------------------------------------------------------------------------------------------------- 36. What is MQ-Series? ( Messaging) It is used to store messages in a queue. (FIFO). ------------------------------------------------------------------------------------------------------------------------- 37. Diff between ORACLE vs SQL Server ? ( Database) The SQL Server 2000 advantages: SQL Server 2000 is cheaper to buy than Oracle 9i Database. SQL Server 2000 holds the top TPC-C performance and price/performance results. SQL Server 2000 is generally accepted as easier to install, use and manage. 25 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM The Oracle 9i Database advantages: Oracle 9i Database supports all known platforms, not only the Windowsbased platforms. PL/SQL is more powerful language than T-SQL. More fine-tuning to the configuration can be done via start-up parameters. Mainframe – Handling Terra data (DB2) ------------------------------------------------------------------------------------------------------------------------- 38. Aggregate Functions in Oracle? ( Database) This table shows the equivalent Microsoft® SQL Server™ function for each Oracle function. Function Average Count Maximum Minimum Standard deviation Summation Variance Oracle AVG COUNT MAX MIN STDDEV SUM VARIANCE SQL Server AVG COUNT MAX MIN N/A SUM N/A ------------------------------------------------------------------------------------------------------------------------- 39. 45. Primary Key, Unique Key, Candidate Key? ( Database) A candidate key is a combination of attributes that can be uniquely used to identify a database record without any extraneous data. Each table may have one or more candidate keys. One of these candidate keys is selected as the table primary key. 26 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM ------------------------------------------------------------------------------------------------------------------------- 40. 46. Data Defination Language and Data Manipulation Language ? ( Database) DDL – (Use - CADro) Use, Create, Alter, Drop, truncate Create CREATE DATABASE employees CREATE TABLE personal_info (first_name char(20) not null, last_name char(20) not null, employee_id int not null) Use The USE command allows you to specify the database you wish to work with within your DBMS. For example, if we're currently working in the sales database and want to issue some commands that will affect the employees database, we would preface them with the following SQL command: USE employees ALTER ALTER TABLE personal_info ADD salary money null DROP The final command of the Data Definition Language, DROP, allows us to remove entire database objects from our DBMS. For example, if we want to permanently remove the personal_info table that we created, we'd use the following command: 27 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM DROP TABLE personal_info Similarly, the command below would be used to remove the entire employees database: DROP DATABASE employees DML – (I-SUDel ) Insert, select, Update, Delete ------------------------------------------------------------------------------------------------------------------------- 42. Oracle Legal Data Types ? ( Database) Legal Data Types VARCHAR2(size) Variable length character string having max. length of size CHAR(size) Fixed length character string with number of bytes equal to size NUMBER(p,s) Number having a precision p and s digits to the right of the decimal. If you leave off p and s (e.g., NUMBER), then it is a floating point number. LONG Character data of variable length up to 2 gigabytes (cannot be a key) DATE A date field RAW(size) Raw binary data of length size. Max. size is 255 bytes LONG RAW Raw binary data up to 2 gigabytes (cannot be a key) ------------------------------------------------------------------------------------------------------------------------- 43. What is USER_TABLES ? ( Database) 28 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM Oracle keeps the names of your tables and other information in a meta table called user_tables ------------------------------------------------------------------------------------------------------------------------44. How to Generate Number in Oracle Database ? ( Database) SELECT (NVL((MAX(TO_NUMBER(SEQ_ID))),0))+1 from GEN_TABLE ------------------------------------------------------------------------------------------------------------------------- 45. Back Page Expiration ? ( Database) response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires",0); ------------------------------------------------------------------------------------------------------------------------46. To_Char in ORACLE (selecting user defined format) ( Database) select to_char(quote_date,'yyyy-dd-mon') from rating_history ------------------------------------------------------------------------------------------------------------------------- 47. To_Date in ORACLE (inserting user date format) ( Database) insert into datetimer values ( to_date('2/april/2002','dd/mon/yyyy') ) 29 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM 48. What is JMS Vs MQSeries? ( Messaging ) The JMS server guarantees that it will keep the message in a persistent storage until the receiver becomes online or when the message has expired (using the expiration date). MQSeries provides a consistent multi-platform, applicationprogramming interface. A key factor is time-independent processing. This means that messages are dealt with promptly, even if one the recipient is temporarily unavailable. An application that implements the JMS specification must guarantee the delivery of the message. So, either if you use MQ Series, Fiorano, OpenJMS, and so on, they all must provide this feature. OpenJMS uses JDBM as a persistant storage, but you can use MySQL, Oracle, etc.). ------------------------------------------------------------------------------------------------------------------------- 49. What are the delivery modes in JMS? ( Messaging ) Persistent means that the message is delivered once and only once. On persistant mode we need to store all messages in a DB. Non_persistent means that messages are delivered "at most once". ------------------------------------------------------------------------------------------------------------------------- 50. What is JMS API ? ( Messaging ) The Java Message Service is a Java API that allows applications to create, send, receive, and read messages. 30 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM Asynchronous. A JMS provider can deliver messages to a client as they arrive; a client does not have to request messages in order to receive them. Reliable. The JMS API can ensure that a message is delivered once and only once ------------------------------------------------------------------------------------------------------------------------- 51. what is Message Driven Bean ? ( EJB) The message-driven bean, enables the asynchronous consumption of messages. A JMS provider may optionally implement concurrent processing of messages by message-driven beans. ------------------------------------------------------------------------------------------------------------------------- 52. What is Messaging? ( Messaging ) 1 What Is Messaging? Messaging is a method of communication between software components or applications. A messaging system is a peer-to-peer facility: A messaging client can send messages to, and receive messages from, any other client. Each client connects to a messaging agent that provides facilities for creating, sending, receiving, and reading messages. Messaging enables distributed communication that is loosely coupled. A component sends a message to a destination, and the recipient can retrieve the message from the destination. However, the sender and the receiver do not have to be available at the same time in order to communicate. In fact, the sender does not need to know anything about the receiver; nor does the receiver need to know anything about the sender. The sender and the receiver need to know only what message format and what destination to use. In this respect, messaging differs from tightly coupled technologies, such as Remote Method Invocation (RMI), which require an application to know a remote application's methods. 31 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM Messaging also differs from electronic mail (e-mail), which is a method of communication between people or between software applications and people. Messaging is used for communication between software applications or software components. ------------------------------------------------------------------------------------------------------------------------- 53. What are the types in Messaging? ( Messaging ) Point-to-Point Messaging Domain Each message has only one consumer. A sender and a receiver of a message have no timing dependencies. The receiver can fetch the message whether or not it was running when the client sent the message. The receiver acknowledges the successful processing of a message. Use PTP messaging when every message you send must be processed successfully by one consumer. A point-to-point (PTP) product or application is built around the concept of message queues, senders, and receivers. Each message is addressed to a specific queue, and receiving clients extract messages from the queue(s) established to hold their messages. Queues retain all messages sent to them until the messages are consumed or until the messages expire. publisher and Subscriber Domain Publishers and subscribers are generally anonymous and may dynamically publish or subscribe to the content hierarchy. The system takes care of distributing the messages arriving from a topic's multiple publishers to its multiple subscribers. Topics retain messages only as long as it takes to distribute them to current subscribers. Pub/sub messaging has the following characteristics. Each message may have multiple consumers. Publishers and subscribers have a timing dependency. A client that subscribes to a topic can consume only messages published after the client has created a subscription, and the 32 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM subscriber must continue to be active in order for it to consume messages. Use PTP messaging when every message you send must be processed successfully by one consumer ------------------------------------------------------------------------------------------------------------------------- 54. What are the Messaging Consumption? ( Messaging) Asynchronous - Whenever a message arrives at the destination, the JMS provider delivers the message(Loosely coupled) Synchronous - A subscriber or a receiver explicitly fetches the message from the destination (Tightly coupled) ------------------------------------------------------------------------------------------------------------------------- 55. What is JNDI? ( Core Java) In the JNDI, all naming and directory operations are performed relative to a context. There are no absolute roots. Therefore the JNDI defines an initial context, InitialContext , which provides a starting point for naming and directory operations. Once you have an initial context, you can use it to look up other contexts and objects. The javax.naming package defines a Context interface, which is the core interface for looking up, binding/unbinding, renaming objects and creating and destroying subcontexts. The most commonly used operation is lookup() . You supply lookup() the name of the object you want to look up, and it returns the object bound to that name. A binding is a tuple containing the name of the bound object, the name of the object's class, and the object itself. The JNDI architecture consists of an API and a service provider interface (SPI). Java applications use the JNDI API to access a variety 33 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM of naming and directory services. The SPI enables a variety of naming and directory services to be plugged in transparently, thereby allowing the Java application using the JNDI API to access their services. See the following figure. ------------------------------------------------------------------------------------------------------------------------56. Diff doGet vs doPost()? ( Servlet ) Difference between them are with get method, the query string is passed along with the request URL of the page so one can see the query string at the address bar of the browser. There is a limitation on the size of the Query String. As get method passes form input elements with its URL so there is a limited amount of information that can be passed with this method. The amount of information depends upon the browser. If parameters is a Query String use getParameter. If it was sent in the body, you may use getParameter or getInputStream. doGet is called in response to an HTTP GET request ex: <form name=sample action="url" method=get> or from a URL While in Post the query string is passed at the end of request header. So the request parameters can not be seen at the address or status bar. So post is secure while taking password or Credit card information. But with Post method you can send as much amount as you want. POST sends parameters in the body of the request. Large objects/data can be passed this way. doPost is called in response to an HTTP POST request ex: <form name=sample action="url" method=post> POST has no limit on the amount of data you can send and because the data does not show up on the URL you can send passwords. But this does not mean that POST is truly secure. For real security you have to look into encryption which is an entirely different topic ------------------------------------------------------------------------------------------------------------------------- 34 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM 57. What is Trigger ? ( Database) Automatic execution at the time of DML operation, issued against table level Before and After TriggerBefore Trigger and After Trigger has Row Level and Statement Level Trigger – Input, Update and Delete ------------------------------------------------------------------------------------------------------------------------58. What is View? ( Database) It is a mirror of the table. DML and DDL operation can be done except Reference Table (cascading is not permitted) ------------------------------------------------------------------------------------------------------------------------59. What is Stored Procedure? ( Database) Stored Procedure is one time compiled and stored in anonymous block ------------------------------------------------------------------------------------------------------------------------60. What is Sequence? Creating user defined automatic number insert in the column for each record level insert ------------------------------------------------------------------------------------------------------------------------61. What is Indexing? For faster access of records in the table. Automatic Index can be done while inserting the record or after storing records in the table , then indexing the table. ------------------------------------------------------------------------------------------------------------------------- 35 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM 62. What is B-Tree and B-MAP indexing? (Data ware housing) B-Tree is in OLTP (mainly reports-select statement, less insert and update) B-MAP is in OLAP (mainly trill – down reports) ------------------------------------------------------------------------------------------------------------------------63. Diff CMP v BMP? ( EJB ) CMP (+) Tx behavior in beans are defined in transaction attributes of the methods Tuned CMP entity beans offer better performance than BMP entity beans. Database independence since it does not contain any database storage APIs within it. CMP, the container handles the implementation of the code necessary to insert, read, and update an object in a data source. CMP is the ideal way to develop an application because it requires less code changes by the application developer when the data model changes. CMP is Portable across all DB’s (-) Since the container performs database operations on behalf of the CMP entity bean, they are harder to Debug 36 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM BMP A programmer has to write a code that implements Tx behaviour to the bean class. BMP beans offer more control and flexibility that CMP beans. In BMP you will take care of all the connection and you write the SQL code inside the bean whereas in CMP the container will take care of it. The BMP is not portable across all DB's. Developer creates the implementation for the insert, read, and update of an object. If performance is the only factor, BMP performs a million times faster than CMP. Well, may be not that much faster, but you get the point. CMP is for ease of development, basically the container does all the work for you, but it is not as flexible and you cannot fine tune the query like you can do in BMP. ------------------------------------------------------------------------------------------------------------------------64. Diff Home Interface V Remote Interface ? ( EJB ) Home interface is an interface to the container used to create or accesses an instance of an EJB. Remote Interface is an interface to the EJB Instance used to call business logic methods of the Bean class. Metadata Interface used to perform dynamic invocation of the methods of the bean (e.g. to find new services from beans installed after client compilation) ------------------------------------------------------------------------------------------------------------------------65. Diff EJB 2.0 V EJB 1.1 ? ( EJB ) 37 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM EJB 1.1 Specification provided EJB clients with a remote interface and a remote home interface (Java RMI interfaces, compatible with RMI – IIOP ) to interact with EJB instances, achieving location transparency Request comes from a remote host. In a similar fashion, the EJB 2.0 specification now provides EJB clients with a local interface and local home interface to interact with EJB instances that share the same Java Virtual Machine (JVM). Not RMI Interface and not compatible with RMI-IIOP. javax.ejb.EJBLocalObject and javax.ejb.EJBLocalHome Request comes from a LOCAL host. EJB2.0 has Containter – Managed Relationships, EJB QL, Local Interface, Message Driven Bean Message Driven Bean – Transaction aware component of asynchronous message Loosely coupling between sender and receiver. Similar to stateless session bean in operation. ------------------------------------------------------------------------------------------------------------------------66. Define JNDI? ( Core Java ) Java Naming and Directory Interface (JNDI) is a naming service that allows a program or container to register a "popular" name that is bound to an object ------------------------------------------------------------------------------------------------------------------------67. Diff EJB v Java Beans? Java Beans can do processing -- like XML-parsing or database access, and can access Java Enterprise APIs. It will run with in JVM Enterprise Java Beans it will run within EJB Server and has Transaction Management. 68. What is EJB Architecture? 38 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM Build once, access any where Business methods accessible via: RMI-IIOP, RMI-JRMP, Servlets and JSPs. Other language via CORBA ------------------------------------------------------------------------------------------------------------------------- 69. Diff Stateful and Stateless ? Stateless has create method without argument and session will not be maintained. Stateful has create method with argument and session maintained. ----------------------------------------------------------------------------------------------------------------------70. Diff between CMP 2.0 and BMP ? CMP 2.0 potentially simpler and portable (especially with CMR and EJB QL). BMP 2.0 has more detailed control. Avoid excessive Remote Interface Calls. Use EJB 2.0 for CMP and Local interface. ----------------------------------------------------------------------------------------------------------------------------71. What are Transaction Attributes Values ? TX_BEAN_MANAGED ---- programmatically controls transaction TX_REQUIRED - always required new or existing transaction TX_SUPPORTS - if there is a transaction then run, otherwise run with out transaction TX_REQUIRES_NEW - only new transaction TX_MANDATORY - must have transaction already 39 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM TX_NOT_SUPPORTED – no need of transaction ----------------------------------------------------------------------------------------------------------------------------72. What is EJB QL and CMR ? CMR makes it much easier for bean developers to build applications based on tightly-coupled entities such as employees and departments or customers-orders-line items. Using a syntax similar to SQL, EJB QL enables you to write queries based on Entity Beans without knowing anything about the underlying relational schema. ------------------------------------------------------------------------------------------73. What is Exception Handling? Throwable class is a super class for Exception and Error in Java language. Errors may include the VM running out of resources, dependency classes being incompatible, or the AWT native methods failing to operate correctly. Exceptions being thrown and caught without the user’s knowledge. IOException - you perform any communication or file work InterruptedException - thread-related OutOfBoundsException – Vector related For instance, an endlessly recursive nesting of the same class will cause a StackOverflowError. ----------------------------------------------------------------------------------------------------------------------------74. What is ‘finally’ block? 40 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM finally is rarely necessary. Even when it can be useful, it is often just as easy to clean up your references. (Closing file, closing connection, making referenced object null). After the catch completes, the finally will run. But if you call System.exit(0) in the catch block, the finally will not run. Likewise, if there is code in the catch block that executes indefinitely, the Java runtime will never get around to executing the part in finally. These are pretty extreme examples, however. In any logical programming situation, you can count on the finally block running once the catch block finishes. This includes the case where the catch block does something to throw a new exception ---------------------------------------------------------------------------------------------------------------------------75. If a abstract method is defined in abstract class, abstract method should be implemented in the extended class. abstract class abstra { public void getSeconds(){ System.out.println("abstra"); } abstract public void getTime(); } public class first extends abstra { public void getSeconds(){ System.out.println("first"); } public static void main(String ss[]){ first f = new first(); f.getSeconds(); 41 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM } } compile time error , since the abstract method is not implemented in child class ----------------------------------------------------------------------------------------------------------------------------76. It is not necessary to have at least one abstract method in a abstract class abstract class abstra { public void getSeconds(){ System.out.println("abstra"); } } public class first extends abstra { public void getSeconds(){ System.out.println("first"); } public static void main(String ss[]){ first f = new first(); f.getSeconds(); } } ----------------------------------------------------------------------------------------------------------------------------77. Abstract class can be defined with out method or abstract method. 42 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM ----------------------------------------------------------------------------------------------------------------------------78. Abstract class can’t be instantiated abstract class abstra { public void getSeconds(){ System.out.println("abstra"); } } public class first extends abstra { public void getSeconds(){ System.out.println("first1"); } public static void main(String ss[]){ //abstra f = new first(); - ok first f = new abstra(); - abstract class can’t be instantiated f.getSeconds(); } } ----------------------------------------------------------------------------------------------------------------------------------79. Interface will allow only public method and default it is final static variable in interface. Abstract class will allow protected, private or public method and variable will be protected or public. It allows final static variable also, but it is not default in abstract class. 43 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM ----------------------------------------------------------------------------------------------------------------------------------80. What is the output in the following code? interface abstra { void getSeconds(); final static int a = 10; } public class second implements abstra { public void getSeconds(){ System.out.println("getSeconds"); } public static void main(String ss[]){ final int a= 100; System.out.println("value of a <<" + a + ">>"); second f = new second(); f.getSeconds(); } } out put is a = 100 ----------------------------------------------------------------------------------------------------------------------------------80. What is the output of following code ? interface abstra { void getSeconds(); static int a = 10; } public class second implements abstra { public void getSeconds(){ a = 109; System.out.println("value of a <<" + a + ">>"); } public static void main(String ss[]){ second f = new second(); f.getSeconds(); } } out put is error, since variable a is declared in interface and default it is final static variable ----------------------------------------------------------------------------------------------------------------------------------81. What is the output of following code ? 44 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM interface abstra { void getSeconds(); static int a = 10; } public class second implements abstra { int a ; public void getSeconds(){ a = 109; System.out.println("value of a <<" + a + ">>"); } public static void main(String ss[]){ second f = new second(); f.getSeconds(); } } output is a = 109 ----------------------------------------------------------------------------------------------------------------------------------82. What is the output of the code ? interface abstra { void getSeconds(); int a = 10; } public class second implements abstra { int a ; public void getSeconds(){ System.out.println("value of a <<" + a + ">>"); } public static void main(String ss[]){ second f = new second(); f.getSeconds(); } } output a =0; 83. Final variable should be assigned a value. Static Variable assign default value Zero. ----------------------------------------------------------------------------------------------------------------------------------84. what is the out put? abstract class abstra { private void getSeconds(){ System.out.println("abstra"); 45 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM } } public class first extends abstra { private void getSeconds(){ System.out.println("first"); } public static void main(String ss[]){ first f = new first(); f.getSeconds(); } } Output is “first” -----------------------------------------------------------------------------------------------------------------------85. what is the out put? abstract class abstra { private void getSeconds(){ System.out.println("abstra"); } } public class first extends abstra { public static void main(String ss[]){ first f = new first(); f.getSeconds(); } } Compile time error – parent method is private Note := Parent method is public or protected, child class can access it. ----------------------------------------------------------------------------------------------------------------------------------86. what is the out put? abstract class abstra { private void getSeconds(){ System.out.println("abstra"); } } 46 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM public class first extends abstra { void getSeconds(){ System.out.println("first"); } public static void main(String ss[]){ abstra f = new first(); //Note child class object is referenced by Parent class f.getSeconds(); } } Out put is compile time error. ----------------------------------------------------------------------------------------------------------------------------------What is the output? 87. In Overriding, Parent class and Child class has same (100%) method signature with modifier may be public or protected and Parent c = new Child(). object always refer Child Class method ----------------------------------------------------------------------------------------------------------------------------------- 88. In Overriding, Parent class and Child class has same (100%) method signature with modifier may be private or protected and Child c = new Child(). Child object always refer Child Class method ----------------------------------------------------------------------------------------------------------------------------------- In Abstract Class and Simple Class Overriding having (parent p = new child or child c = new child) object reference, then Modifier rule will be Private Modifier > Protected Modifier > Public Modifier > Empty modifier Child Modifier always >= Parent Modifier in Overriding In Parent class and Child class Overriding having (parent p = new child) object reference, then Modifier rule will be Private Modifier > Protected Modifier > Public Modifier > Empty modifier Child Modifier always >= Parent Modifier in Overriding 47 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM ----------------------------------------------------------------------------------------------------------------------------------- 89. Abstract Method should not have private modifier ----------------------------------------------------------------------------------------------------------------------------------90. What are the Types of Servlet? Types of Servlets Servlets must implement the interface javax.servlet.Servlet. There are two main types of servlets: Generic servlets extend javax.servlet.GenericServlet. Generic servlets are protocol independent, meaning that they contain no inherent support for HTTP or any other transport protocol. HTTP servlets extend javax.servlet.HttpServlet. These servlets have built-in support for the HTTP protocol and are much more useful in an Browser environment Servlets that extend HttpServlet are much more useful in an HTTP environment, since that is what they were designed for. We recommend that all Servlets extend from HttpServlet rather than from GenericServlet in order to take advantage of this built-in HTTP support. For both types of Servlets, you can implement the constructor method init() and/or the destructor method destroy() if you need to initialize or deallocate resources. All Servlets must implement a service() method. This method is responsible for handling requests made to the Servlet. For generic Servlets, you simply override the service() method to provide routines for handling requests. HTTP Servlets provide a service method that automatically routes the request to another method in the servlet based on which HTTP transfer method is used, so for HTTP Servlets you would override doPost() to process POST requests, doGet() to process GET requests, and so on. 91. servlets run on an application server or web server rather than in a web browser. ---------------------------------------------------------------------------------------------------------------------------191919 48 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM 19 [ 19th Nov 2004 onwards ] 92. Generic Servlet You must implement abstract method – service() HttpServlet No need of implementing service() method ---------------------------------------------------------------------------------------------------------------------------93. Steps of a JSP Request 1. 2. 3. 4. Client Requests a JSP Page The JSP Engine Compiles the JSP into a Servlet The generated Servlet is compiled and loaded The compiled servlet services the request and sends a response back to the client ---------------------------------------------------------------------------------------------------------------------------93. Primordial Class Loaders and Class Loader objects. Primordial Class Loaders provides Java with the ability to bootstrap itself and provide essential functions. The Java API class files (stored by default in the classes.zip file) are usually the first files loaded by the VM. The Primordial Class Loader also typically loads any classes a user has located in the CLASSPATH Class Loader objects load classes that are not needed to bootstrap the VM into a running Java environment. The VM treats classes loaded through Class Loader objects as untrusted by default. Class Loaders are objects just like any other Java object-they are written in Java, compiled into byte code, and loaded by the VM (with the help of some other class loader). These Class Loaders give Java its dynamic loading capabilities. There are three distinct types of Class Loader objects defined by the JDK itself: Applet Class Loaders, RMI Class Loaders, and Secure Class Loaders 49 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM Applet Class Loaders are responsible for loading classes into a browser and are defined by the vendor of each Java-enabled browser. RMI Class Loaders are very similar to Applet Class Loaders in that they load classes from a remote machine. Secure Class Loaders can only be used by classes found in the java.security package and are extensively used by the Java 2 access control mechanisms. ---------------------------------------------------------------------------------------------------------------------------- 95. Internationalization is the process of designing an application so that it can be adapted to various languages Localization is the process of adapting software for a specific region or language by adding locale-specific components and translating text. Resource bundles contain locale-specific objects. java.util.Resource Bundle MyResources_en.properties: hello=Hello bye=Goodbye String baseName = "MyResources"; ResourceBundle rb = ResourceBundle.getBundle(baseName); String key = "hello"; String s = rb.getString(key); ---------------------------------------------------------------------------------------------------------------------------96. Uncommited transaction will be there in TLog 50 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM ---------------------------------------------------------------------------------------------------------------------------- 97. - Transaction Level ACID Atomicity Consistency Isolation Durabliity 98. – Transaction Atrributes TX_REQUIRED – Client can provide transaction or new transaction TX_MANDATORY – Client should have transaction TX_REQUIRES_NEW – Suspend client transaction. Generate new Transaction TX_SUPPORTS – Transaction is optional TX_NOT_SUPPORTED TX_BEAN_MANAGED – Code level transaction control ---------------------------------------------------------------------------------------------------------------------------99. – EJB Transaction EJB transactions are a set of concepts and a set of mechanisms that attempt to insure the integrity and consistency of a database for which multiple clients may attempt to access it and/or update it simultaneously. ---------------------------------------------------------------------------------------------------------------------------100. – Isolation level TRANSACTION_SERIALIZABLE It prevents other users from updating or inserting rows into the data set until the transaction is complete. TRANSACTION_REPEATABLE_READ - 51 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM It means that locks will be placed on all data that is used in a query, and another transactions cannot update the data. TRANSACTION_READ_COMMITTED will never read data that another application has changed and not yet committed TRANSACTION_READ_UNCOMMITTED you can read an uncommitted transaction that might get rolled back later. This isolation level is also called dirty read. This is the lowest isolation level. TRANSACTION_NON_REPEATABLE_READ When a transaction reads the same row more than one time, and between the two (or more) reads, a separate transaction modifies that row. Because the row was modified between reads within the same transaction, each read produces different values, which introduces inconsistency. ---------------------------------------------------------------------------------------------------------------------------- 101.- Different Model Incremental Model - Big System development Water fall Model - Go back to each phase Spiral Model – Requirement is not clear ---------------------------------------------------------------------------------------------------------------------------[20th Nov 2004 onwards] HONEY WELL INTERVIEW QUESTION - NOT SELECTED 20th Nov 2004 (NO Session Façade Externalization & Serialization Abstract & Interface Session Tracking Transient & Volatile ACID & Transaction Isolation Level 52 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM File Writer Servlet Context and Servlet Config LOG 4j Logger.setLevel) 102. Connection class has commit and roll back method ---------------------------------------------------------------------------------------------------------------------------- 103. Instance Variable and Class Variable Variable which is declared inside the method is LOCAL variable Static variable which is declared in Class level is CLASS variable (We can’t assign diff. value for diff. Instance) Non-static variable is Instance variable (we can assign different value for different instance) ---------------------------------------------------------------------------------------------------------------------------- 104. What is the output ? public class Test1 { static int a = 10; public static void main(String ss[]){ Test1 t1 = new Test1(); Test1 t2 = new Test1(); t1.a = 10; t2.a = 100; System.out.println("Value of t1.a is "+ t1.a); System.out.println("Value of t2.a is "+ t2.a); } } Value of t1.a is 100 Value of t2.a is 100 Since a variable is static 105. 53 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM dirty read A transaction reads data written by a concurrent uncommitted transaction. nonrepeatable read A transaction re-reads data it has previously read and finds that data has been modified by another transaction (that committed since the initial read). ( Data Change) phantom read A transaction re-executes a query returning a set of rows that satisfy a search condition and finds that the set of rows satisfying the condition has changed due to another recently-committed transaction. (Row Change) --------------------------------------------------------------------------------------------------------------------------- String Append in a File import java.io.*; public class Test { public static void main(String ss[]) throws Exception{ FileOutputStream fos = new FileOutputStream("c:/test.txt",true); Writer fWriter = new OutputStreamWriter(fos); fWriter.write("hi man"); fWriter.close(); } } Or public class Test { public static void main(String ss[]) throws Exception{ FileWriter fWriter = new FileWriter("c:/test.txt",true); fWriter.write("hi man"); fWriter.close(); } } 54 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM ---------------------------------------------------------------------------------------------------------------------------107. Static method should have static variable static int a = 10; public static void getY(){ System.out.println(" Y value" + a); } } Output :- value10 int a = 10; ( ERROR ) declare static since it is used in static method public static void getY(){ System.out.println(" Y value" + a); } } 108. ABSTRACT Abstract class must have atleast one abstract method definition – FALSE (need not be) 86. Non-abstract methods need not to be implemented in Class - TRUE 109. INTERFACE All the methods in Interface are default abstract methods – TRUE All the methods in Interface MUST BE implemented in the Class (implementing class) - TRUE Only public methods are allowed in Interface – TRUE All the variables in the interface are default static final variable TRUE ---------------------------------------------------------------------------------------------------------------------------- 55 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM 110. Servlet configuration Vs ServletContext public interface ServletContext Defines a set of methods that a servlet uses to communicate with its servlet container The ServletContext object is contained within the ServletConfig object, getAttribute() getAttributeName() getContext() getRealPath() getServlet() getServletInfo() A servlet configuration object used by a servlet container to pass information to a servlet during initialization. getServletName() getServletContext() getInitParameterNames() getInitParameter() ---------------------------------------------------------------------------------------------------------------------------111. Object Persistence and Serialization uses the Serializable and Externalizable interfaces. Each object to be stored is tested for the Externalizable interface If the object supports Externalizable, the writeExternal method is called. If the object does not support Externalizable and does implement Serializable, the object is saved using ObjectOutputStream. Serializable objects are restored by reading them from an ObjectInputStream. 56 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM Externalizable objects are restored by reading them using readExternal method is called Externalization: The writeExternal and readExternal methods of the Externalizable interface are implemented by a class to give the class complete control over the format and contents of the stream for an object and its supertypes Serializability of a class is enabled by the class implementing the java.io.Serializable interface. Classes that do not implement this interface will not have any of their state serialized or deserialized. All subtypes of a serializable class are themselves serializable. The serialization interface has no methods or fields and serves only to identify the semantics of being serializable. Classes that require special handling during the serialization and deserialization process must implement special methods with these exact signatures: private void writeObject(java.io.ObjectOutputStream out) throws IOException private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException The writeObject method is responsible for writing the state of the object for its particular class so that the corresponding readObject method can restore it. ---------------------------------------------------------------------------------------------------------------------------- 112. Session Facade Session facade is one design pattern that is often used while developing enterprise applications. It is implemented as a higher level component (i.e.: Session EJB), and it contains all the iteractions between low level components (i.e.: Entity EJB). It then provides a single interface for the functionality of an application or part of it, and it decouples lower level components simplifying the design. 57 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM Think of a bank situation, where you have someone that would like to transfer money from one account to another. In this type of scenario, the client has to check that the user is authorized, get the status of the two accounts, check that there are enough money on the first one, and then call the transfer. The entire transfer has to be done in a single transaction otherwise is something goes south, the situation has to be restored. As you can see, multiple server-side objects need to be accessed and possibly modified. Multiple fine-grained invocations of Entity (or even Session) Beans add the overhead of network calls, even multiple transaction. In other words, the risk is to have a solution that has a high network overhead, high coupling, poor reusability and mantainability. The best solution is then to wrap all the calls inside a Session Bean, so the clients will have a single point to access (that is the session bean) that will take care of handling all the rest. Obviously you need to be very careful when writing Session Facades, to avoid the abusing of it (often called "God-Bean"). Session Facade performs the role of a broker to decouple the entity beans from their clients When implementing the Session Facade, you must first decide whether the facade session bean is a stateful or a stateless session bean. The Session Facade is a business-tier controller object that controls the interactions between the client and the participant business data and business service objects. The SessionFacade is implemented as a session bean. The SessionFacade manages the relationships between numerous BusinessObjects and provides a higher level abstraction to the client. It not only enforces reusable application architecture design but also provides many advantages, including reduced network overhead, centralized security management and transaction control, coarse-grained abstraction of business data and service objects, and reduced coupling between clients and business objects. The Session Façade design pattern uses an enterprise session bean as a façade, which abstracts the underlying business object interactions and provides a uniform, coarse-grained service access layer to clients. 58 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM ---------------------------------------------------------------------------------------------------------------------------- 113. Logger Level DEBUG, INFO, WARN , ERROR, FATAL // Log logger = LogFactory.getLog(getClass()); // Logger logger = Logger.getLogger(Logging.class.getName()); Logger logger = Logger.getLogger("com.foo.Bar"); logger.setLevel(Level.INFO) log4j speak, an output destination is called an appender Console Appender File Appender – Daily Rolling File Appender, Rolling File Appender Socket Appender 59 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM LOG4J.xml ---------------- <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration> <appender name="Stdout" class="org.apache.log4j.ConsoleAppender"> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%-d [%t] %-5p %c - %m%n"/> </layout> </appender> <appender name="FA" class="org.apache.log4j.DailyRollingFileAppender"> <param name="DatePattern" value="'.'dd-MM-yyyy-HHmm"/> <param name="File" value="D:/jakarta-tomcat5.0.27/webapps/Classic1.0.0/WEB-INF/classic.log" /> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%-d [%t] %-5p %c - %m%n"/> </layout> </appender> <appender name="clientLOG" class="org.apache.log4j.DailyRollingFileAppender"> <param name="File" value="D:/jakarta-tomcat5.0.27/webapps/Classic1.0.0/WEB-INF/clientLOG.log"/> <param name="DatePattern" value="'.'yyyy-MM-dd"/> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d{yyyyMM-dd HH:mm:ss} %-5p (%F:%L)[%t] - %m%n"/> </layout> </appender> <logger name="classic.stringarray" additivity="false"> <level value="DEBUG"/> <appender-ref ref="FA"/> </logger> 60 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM <logger name="classic" additivity="false"> <level value="DEBUG"/> <appender-ref ref="clientLOG"/> </logger> <root> <priority value="debug"/> <appender-ref ref="FA"/> <appender-ref ref="Stdout"/> </root> </log4j:configuration> ---------------------------------------------------------------------------------------------------------------------------114. Sequence Diagram Vs Collaboration Diagram Collaboration Diagram Represents Interaction of objects and relationship. Sequential Diagram Represents flow of events in a sequential order Both Express similar information but shows in a different ways. It allows to 114. find flow of controls, 115. identify the objects, classes, interactions and 116. help to validate the architecture ---------------------------------------------------------------------------------------------------------------------------- 61 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM 115. Poor Practices in Software Development Inaccurate understanding of End user needs Inability to deal with Change Requirements Software that hard to maintain or extend Unacceptable software performances Poor software Quality Untrustworthy build and release process ---------------------------------------------------------------------------------------------------------------------------- 116. Software Best practices Develop Software iteratively Manage Requirements Use Component based Architecture Continuously verify software quality Control changes to software ---------------------------------------------------------------------------------------------------------------------------117. RUP has four phases o Inception - Scope of the project o Elaboration – Plan project, specify features, baseline Architecture o Construction – Build the project o Transition – Transition the product to the End user ---------------------------------------------------------------------------------------------------------------------------118. What is Model and Object? Model: Simplification of reality Object: Set of Attributes and operations Class: set of objects that share same attributes, operations, relationships and semantics ---------------------------------------------------------------------------------------------------------------------------119. Object Orientation Abstraction: Any model that includes most important aspect 62 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM Encapsulation: Hides implementation details from Clients Modularity: Logical decomposition. Hierarchy: Ranking of Abstraction ---------------------------------------------------------------------------------------------------------------------------120. Signature of Perform method in Action Class public ActionForward perform(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { 121. Typical Structs-Config . xml file <struts-config> <form-beans> <form-bean name="generatepromotioncodeform" type="com.fedex.chronos.mma.promotion.beans.formbean.GeneratePromotio nCodeFB"/> </form-beans> <global-forwards> <forward name="failure" path="/jsp/ErrorPage.jsp"/> </global-forwards> <action-mappings> <action path="/promotioncodemain" type="com.fedex.chronos.mma.promotion.action.PromotionCodeMainAction" name="promotioncodemainform" scope="session" > <forward name="promotioncodemainjsp" path="/jsp/PromotionCodeMain.jsp"/> <forward name="expire" path="/jsp/PromotionCodeMain.jsp"/> <forward name="success" path="/jsp/PromotionCodeMain.jsp"/> <forward name="failure" path="/jsp/PromotionCodeMain.jsp"/> 63 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM <forward name="logout" path="/jsp/PromotionCodeEntry.jsp"/> </action> </action-mappings> </struts-config> ---------------------------------------------------------------------------------------------------------------------------- 122. What is Polymorphism? Hiding different implementation behind single interface ---------------------------------------------------------------------------------------------------------------------------- 123. Association Relationship between objects connectivity Aggregation Relationship between whole part and its part Generalization Relationship between Parent and child objects <|____________________ Dependency Relationship between model elements where a change in one element will cause a change in another element o - - - -- - > ---------------------------------------------------------------------------------------------------------------------------124. Analysis Class – Handle primarily functional requirements. To capture early draft of the object of the system 64 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM Boundary Class – intermediates between interface and outside the system Entity Class – Key abstraction of the system Control Class - Use case behaviors coordinator. One per use case ---------------------------------------------------------------------------------------------------------------------------125. Activity Diagram – is used to find the activity in the use case. It is a flow chart showing flow of control from activity to activity ------------------------------------------------------------------------------------------------------------------------126. 2 Phase Commit Transaction Coordinator will send ‘ Prepare to Commit’ to Transaction Manager. TM will send message to Resource Manager (RM). RM will send back message to TM. TM will inform to TC about the readiness to commit. TC will commit. Uncommitted Transaction will be stored in TLOG. ------------------------------------------------------------------------------------------------------------------------- 127. Architectural Pattern Layers, Pipe and Filter, MVC and Blackboard It provides set of Subsystems, specifies their responsibilities and includes rules and guidelines for organizing the relationship between them. ------------------------------------------------------------------------------------------------------------------------128. Subsystem – provide interface to access its behaviour Package – help to organize class. (Configuration Management) 65 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM ---------------------------------------------------------------------------------------------------------------------------- 129. Session Context Vs Entity Context Session Context is the gateway for the EJB Bean to interact with the Container. (Transaction State and Security State ). No need of user implementation EJB Context – where EJBean will perform call back methods to the container. It will help bean to ascertain their status. ---------------------------------------------------------------------------------------------------------------------------- 130. Local Interface ---------------------------------------------------------------------------------------------------------------------------- 131. Life cycle of Entity Bean Does not exist state – Create new instance (Container will call on Bean Class) Set entity Context (not at client call , only to increase pool size) Pool State (Bean is ready – but no database storage) ejbFind Pool State – Read State ejbCreate ejbActivate ejbLoad Ready state – Business method call Ready State – Pool state ejbRemove Pool state – Does not exist state Unset entity context JVM will garbage and call finalize () method 66 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM ---------------------------------------------------------------------------------------------------------------------------132. EJB Container and Server EJB Container – Play ground where EJBean will run. EJB object and Home object are part of the container EJB Server – Run time Environment for the Container ---------------------------------------------------------------------------------------------------------------------------- 133. Beans in EJB Stateful Session Bean – implements BLogic, Brule and workflow ( Shopping Cart) – handle Business Process Stateless Session Bean – Credit Card verification Entity Bean – represents persistent data ---------------------------------------------------------------------------------------------------------------------------134. Home Object Vs EJB Object EJB Object EJB Object – it exposes every business method that the bean itself exposes (it is between client and bean). It delegates all client request to beans. Client code deals with EJB object and never with beans directly Client cannot instantiate an EJB object directly Home Object To acquire reference to the EJB object. Client will ask from EJB object factory (Home object – according to EJB Spec) Create EJB object Find existing EJB object Remove EJB object 67 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM ---------------------------------------------------------------------------------------------------------------------------135. EjbPostCreate – container will call this method when bean instance is associated with EJB object pass bean instance reference to other. Initialize the values Reset Transaction values ---------------------------------------------------------------------------------------------------------------------------- Gap Gemini Interview on 21 nov 2004) - SELECTED Exception Handling MVC MV2 Architecture Struts Architecture Design Pattern DB Form Synchronizations Primary Key Session Synchronization Front Controller Object methods ---------------------------------------------------------------------------------------------------------------------------136. Java.lang.Object has following methods Class Object is the root of the class hierarchy. Every class has Object as a super class. All objects, including arrays, implement the methods of this class. Clone() Equals() Finalize() getClass() hashCode() notify() notifyAll() wait() toString() ---------------------------------------------------------------------------------------------------------------------------- 68 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM 137.. List list = Collections.synchronizedList(new ArrayList(...)); Set s = Collections.synchronizedSet(new HashSet(...)); ---------------------------------------------------------------------------------------------------------------------------- 138. hashCode – converting to primitive type ---------------------------------------------------------------------------------------------------------------------------139. Why Struts? Model 2 – MVC Session Façade Front Controller JSP Model 2 Architecture MVC Internalization Rich JSP Tag Based on JSP, Servlet, XML and Java Supports Different model implementation (Java Bean, EJB) JSP, XSL, XSLT Exception Handling Validation Tiles ---------------------------------------------------------------------------------------------------------------------------140. Action Servlet and Request Processor? Action Servlet – handle request, automatically populate java bean, handle Locale and Content Type Request Processor – which Action should be invoked ---------------------------------------------------------------------------------------------------------------------------- 141. What is SssionSynchronization and where it is used? 69 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM SessionSynchronization is implemented by session bean for Container to callback and notify this session bean about state of a transaction and callback methods such as afterBegin(), afterCompletion() and beforeCompletion() methods are used for this purpose. afterBegin() - a new transaction has started and all the business methods invoked, shall be within this transaction boundary. afterCompletion(Boolean committed) tells the session bean that either the transaction is successfully executed (true)or roll backed (false). beforeCompletion() - whether a transaction is about to be committed. 142. MVC1, MVC2 MVC1 - combines controller and View together MVC2 or Model 2 - seperates them out. ---------------------------------------------------------------------------------------------------------------------------143. Front Controller While the Front Controller pattern suggests centralizing the handling of all requests, it does not limit the number of handlers in the system, as does a Singleton. An application may use multiple controllers in a system, each mapping to a set of distinct services. The controller provides a centralized entry point that controls and manages Web request handling. By centralizing decision points and controls, the controller also helps reduce the amount of Java code, called scriptlets, embedded in the JavaServer Pages (JSP) page. Centralizing control in the controller and reducing business logic in the view promotes code reuse across requests. It is a preferable approach to the alternative-embedding code in multiple views-because that approach may lead to a more error-prone, reuse-by-copy- and-paste environment. 70 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM Typically, a controller coordinates with a dispatcher component. Dispatchers are responsible for view management and navigation. Thus, a dispatcher chooses the next view for the user and vectors control to the resource. Dispatchers may be encapsulated within the controller directly or can be extracted into a separate component. 144. Action Errors ( Struts) ActionErrors errors = null; errors = new ActionErrors(); errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(PromotionCodeConstants.ERROR_CODE_90001, "Your current session has been expired. Please login again.")); saveErrors(request, errors); ActionErrors actionErrors = null; Iterator iterator = null; String errorMessage = null; actionErrors = (ActionErrors)request.getAttribute(Action.ERROR_KEY); if(actionErrors != null && !actionErrors.empty()){ out.println("<br><font color='Red'><b>"); iterator = actionErrors.get(); while (iterator.hasNext()) { ActionError actionError = (ActionError )iterator.next(); errorMessage = (String)(actionError.getValues())[0]; out.println(" - " + errorMessage + "</font><br>"); } } ---------------------------------------------------------------------------------------------------------------------------145. Implicit Objects config Out 71 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM pageContext page exception request response application session ---------------------------------------------------------------------------------------------------------------------------- 146. javax.servlet Interface SingleThreadModel a. Ensures that servlets handle only one request at a time b. This interface has no methods c. Session attributes and static variables can still be accessed by multiple requests on Multiple threads at the same time, even when SingleThreadModel servlets are used ---------------------------------------------------------------------------------------------------------------------------- 147. In JSP isThreadSafe = true (Multiple request at one time) ---------------------------------------------------------------------------------------------------------------------------148. Action include Vs Directive Include <jsp:include page=”” flues=”true”/> Load Dynamic or Static pages Can’t set cookies and Set Headers Not Parsed It will include file during Request processing Time <%@ include file=”header.jsp” %> Evaluated at JSP Translation Time or Compilation Time Only Static page Parsed 72 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM ---------------------------------------------------------------------------------------------------------------------------149. Byte Code All Java programs are compiled into class files, which contain bytecodes, the machine language of the Java virtual machine. ---------------------------------------------------------------------------------------------------------------------------150. Cloneable Interface public class Clona implements Cloneable { public void get(){ System.out.println("Hi " + getClass().getName()); } public static void main(String ss[]) throws CloneNotSupportedException{ Clona c1 = new Clona(); c1.get(); System.out.println(" Say What " + (c1.clone() == c1) ); //FALSE System.out.println(" Say What " + (c1.clone().getClass() == c1.getClass()) ); // TRUE System.out.println(" Say What " + (c1.clone().equals(c1))); // FALSE } } ---------------------------------------------------------------------------------------------------------------------------151. URL Rewriting Example < a href = “ /mydir/mypage.jsp”> Click here <a> Can be re-written as < a href = <%=response.encodeURL(“ /mydir/mypage.jsp“) %> Click here <a> Response.sendRedirect(“ /mydir/mypage.jsp”); Can be re-written as 73 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM Response.sendRedirect( response.encodeRedirectUrL(“ /mydir/mypage.jsp”)); ---------------------------------------------------------------------------------------------------------------------------- 152. JSP Scope Types Page Scope Request Scope - Object is distinct for every client request Session Scope - Object is distinct for every client request and available as long as session is valid Application Scope - All client access same object - Object exist for every client request ---------------------------------------------------------------------------------------------------------------------------153. Session Tracking There are 2 common ways of passing session keys from server to client and back. Cookies – which used default URL rewriting – if Cookies are disabled or not supported URL rewriting – URL encoded with Session Key during Server response. Session key can carry from one server to another Back button or different page which is not part of session, leads to session key lost Session key will be included only in jsp or Servlet not in HTML or XML static pages --------------------------------------------------------------------------------------------------------------------------154. 74 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM Static Variable , Transient variable, Session Attribute can’t be serialized and can’t be synchronized. --------------------------------------------------------------------------------------------------------------------------155. Action Servlet , Action Form, Action Class, Request Processor ( Struts ) o Action Servlet per web Application (Automatically populate Java Bean, Handle Content Type, Locale)and o Request Processor (Invoke proper Action instance) are FRAME WORK PROVIDED o Action class is part of Controller not Model o DYNAMIC ACTION FORM – Define action form in Struts-Config.xml o ActionForm – provides ability to validate the user input, Captures user data from the HTTP Request Stores data temporarily Extends org.apache.struts.action.ActionForm Struts-config.xml Web.xml Add servlet Element, Servlet Mapping Element, Tag Lib Elements 156. Struts Includes Pre-built Action Classes Forward Action Dispatch Action LookupDispatch Action Include Action Swtich Action Struts supports EJB MODEL, CORBA, JAVA BEANS --------------------------------------------------------------------------------------------------------------------------- 75 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM 157. Overiding Concepts class AAA{ public void getAAA(){ System.out.println("AAA"); } public class Clona extends AAA{ public void getAAA(){ System.out.println("Clona"); super.getAAA(); } public static void main(String ss[]) { AAA c = new AAA(); c.getAAA(); } } Output ::: AAA ================= class AAA{ AAA(){ System.out.println("AAA constructor"); } void getAAA(){ System.out.println("AAA"); } } public class Clona extends AAA{ Clona(){ System.out.println("clona constructor"); } public void getAAA(){ System.out.println("Clona"); super.getAAA(); // super is non-static variable } public static void main(String ss[]) { AAA c = new Clona(); // Parent object = new Child() 76 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM c.getAAA(); } } Output ::: AAA Constructor Clona Constructor Clona AAA --------------------------------------------------------------------------------------------------------------------------- 158. Extended Parent classes constructor are invoked first (Hierarchically) , when child class instantiated Main.java -------------class Main { Main(){ System.out.println("Main Constructor"); } void getAAA(){ System.out.println("Main"); } } AAA.java -------------class AAA extends Main{ AAA(){ System.out.println("AAA Constructor"); } void getAAA(){ System.out.println("AAA"); super.getAAA(); } } 77 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM Clona.java --------------public class Clona extends AAA{ Clona(){ System.out.println("Clona Constructor"); } public void getAAA(){ System.out.println("Clona11"); super.getAAA(); } public static void main(String ss[]) { Clona c = new Clona(); // Line 11 c.getAAA(); } } Output Main Constructor AAA Constructor Clona Constructor Clona11 AAA Main // Even though Clona instantiated (at Line 11), Constructors of Main, AAA and Cloan classes are invoked Ofirst --------------------------------------------------------------------------------------------------------------------------- 159. Super and this variable ( Core Java ) Super – is non static variable Super – is used to call Parent method This – is used to call constructor of a class from a constructor This – denotes class variable in order to distinguish from passing argument or variable 78 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM --------------------------------------------------------------------------------------------------------------------------- 160. What are Directives in JSP (JSP) 1. Serves as messages to JSP container from JSP Have scope to JSP file 2. Page , Include and Taglib <%@ page language=”” import = “” %> <%@ import file=”” %> <%@ taglib uri=”” prefix=”” %> --------------------------------------------------------------------------------------------------------------------------161. What are Scripting Elements ? ( JSP) Declaration Scriptlets Expression --------------------------------------------------------------------------------------------------------------------------- 162. What are Standard Actions? (JSP) Runtime behavior of the JSP <jsp:useBean> <jsp:setProperty> <jsp:getProperty> 79 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM <jsp:param> <jsp:include> - at run time, it will load static or dynamic page <jsp:forward> - it will forward the request to next page <jsp:plugin> - it will generate client browser specific HTML --------------------------------------------------------------------------------------------------------------------------- 163. What is implicit objects? (JSP) Implicit objects do not need to be declared Available only in scriptlet or expressions not available in declarations Implicit objects are only available in _jspService () method of the generated servlet. --------------------------------------------------------------------------------------------------------------------------164. Life cycle of JSP ( JSP) Page will be initialized by invoking jspInit () method _jspService() method is for processing the request which comes from JSP and response is taken by the container from JSP and pass back to the client jspDestroy() method is invoked when JSP is destroyed by the server NOTE 165. JSP page is executed by JSP Engine or container , which is installed in Web server or Application Server --------------------------------------------------------------------------------------------------------------------------166. What is Element Data in JSP? Elements which are processed on the Server a. b. c. d. Stand. Action Directives Declaration Scriptlet 80 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM e. Expression --------------------------------------------------------------------------------------------------------------------------- 167. (Synchronization) http://www.cs.umd.edu/class/spring2002/cmsc433-0201/Lectures/javapart7.pdf Synchronized in methods and statement All objects can be locked Only one thread can hold lock on a object A method can be synchronized Add synchronized modifier before return type For a static synchronized method locks the class object Synchronize access to share data Don’t hold a lock on more than one object at time – could cause DEADLOCK Notify() – thread resume to start Join() - wait for a thread to die Wait() - release the lock and adds Thread to wait and suspends thread --------------------------------------------------------------------------------------------------------------------------168. What is a Thread? a. All the threads share the same memory space b. Run concurrently in multiprocessor Eg – WEB BROWER c. One thread for I/O Operation d. One thread for download the file e. One thread for rendering web pages --------------------------------------------------------------------------------------------------------------------------- 81 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM 169. Extending Class Thread ( Core Java) Extend java.lang.Thread for Class to be Thread Class Supply public void run() method Start a thread by invoking the start() method When thread starts, executes run() method When run() returns, thread is finished / dead Simple thread methods() Start() IsAlive() SetPriority() Join() Simple static thread methods() Yield() Sleep() CurrentThread() http://www.cs.umd.edu/class/spring2002/cmsc433-0201/Lectures/javapart6.pdf --------------------------------------------------------------------------------------------------------------------------170. Extending Class Thread ( Core Java) Daemon Thread which is running countinuously in background You can set a thread as daemon thread using the method setDaemon(boolean). That will run continuously in the background. If there are no other threads running in the application then the main thread will stop the daemon thread and exits the application --------------------------------------------------------------------------------------------------------------------------171. Anonymous Class ( Core Java) A type of inner class that has no name. It does not use the keywords class, implements or extends 82 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM These anonymous inner classes can access the static and instance variables of the enclosing outer class. WindowAdapter is a anonymous class --------------------------------------------------------------------------------------------------------------------------- 172. Class which extends Thread class public class MyClass extends Thread{ String messg; MyClass(String str){ messg = str; start(); } public void run(){ System.out.println("[ " + messg); try{ Thread.sleep(100000); }catch(InterruptedException excep){} System.out.println("] "); } public static void main(String ss[]){ new MyClass("Say Hello111"); new MyClass("Say Hello222"); new MyClass("Say Hello333"); } } --------------------------------------------------------------------------------------------------------------------------HP Singapore Interview Q on 23rd Nov 2004 BMP v CMP Trasaction Attributes EJB object V Home Object Local interface 83 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM --------------------------------------------------------------------------------------------------------------------------- 173. Class which implements Runnable Interface public class Runna implements Runnable { String str; Runna(String str){ this.str = str; } public void run(){ for( int i = 0; i < 5 ; i++){ System.out.println("[ "+ str + " " + i); try{ Thread.sleep(1000); }catch(Exception excep){} System.out.println("] "); } } public static void main(String ss[]){ Thread t1 = new Thread(new Runna("hi")); Thread t2 = new Thread(new Runna("wi")); t1.start(); t2.start(); } } NOTE 174. Servlet is a platform independent. It is hosted in JSP/Servlet Container. --------------------------------------------------------------------------------------------------------------------------- 84 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM 175. Servlet Architecture 2 Packages make up the servlet architecture : javax.servlet and javax.servlet.http javax.servlet.Servlet , javax.servlet.ServletConfig, java.io.Serializable are interfaces implemented by javax.servlet.GenericServlet javax.servlet.Servlet interface has init() service() getServletConfig() destroy() getServletInfo javax.servlet.ServletConfig interface has getServletContext() getInitParameter() getInitParameterNames() javax.servlet.GenericServlet interface has init() service() getServletConfig() destroy() getServletInfo getServletContext() getInitParameter() getInitParameterNames() 85 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM javax.servlet.HttpServlet interface has service() getLastModified() doDelete() doPut() doGet() doPost() doOptions() doTrace() --------------------------------------------------------------------------------------------------------------------------176. Life cycle of servlet Init() – initialize the servlet Service() – handle client request and responds back Destroy() – performs clean up --------------------------------------------------------------------------------------------------------------------------- NOTE 177. Service method is a abstract method in Generic servlet but it is not in HttpServlet. --------------------------------------------------------------------------------------------------------------------------- 178. Implicit Objects Available to use in all jsp documents. Parsed by JSP Engine Inserted in to the Generated Servlet ( _jspService() method) ---------------------------------------------------------------------------------------------------------------------------- 86 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM 179. <jsp:forward> - Standard Action enables the JSP engine to execute a runtime dispatch of the current request to another resources. ---------------------------------------------------------------------------------------------------------------------------- 180. JSP Error Handling <%@ page errorPage=”xy.jsp” %> <% If(true){ Throw new Exception(“An exception occurred”); } %> Xy.jsp <%@ page isErrorPage=”true” %> Error is : <%= exception.getMessage() %> has been reported ---------------------------------------------------------------------------------------------------------------------------181. Using Servlet to Retrieve HTTP Data public String ServletRequest.getParameter(String name); public Enumeration ServletRequest.getParameterNames(); public String [] ServletRequest.getParameterValues(String name); ---------------------------------------------------------------------------------------------------------------------------182. Resource Bundle ResourceBundle.getBundle will automatically look for the appropriate properties file and create a PropertyResourceBundle that refers to it. 87 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM The Java 2 platform provides two subclasses of ResourceBundle, ListResourceBundle and PropertyResourceBundle, - that provide a fairly simple way to create resources. ListResourceBundle manages its resource as a List of key/value pairs. PropertyResourceBundle uses a properties file to manage its resources. Example for ResourceBundle import java.util.*; public class ResourceBundleX { public ResourceBundleX(){ try { String baseName = "MyResources"; ResourceBundle rb; rb = ResourceBundle.getBundle(baseName,new Locale("telugu")); System.out.println(" value is " +rb.getString("hello")); } catch(Exception excep){ excep.printStackTrace(); } } public static void main(String ss[]){ new ResourceBundleX(); } } MyResources_telugu.properties hello=Namaste bye=ellosthe 88 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM ----------------------------------------------------------------------------------------------------------------------183. Normalization ----------------------------------------------------------------------------------------------------------------------184. Life Cycle and Design patter ----------------------------------------------------------------------------------------------------------------------- 185. XML ----------------------------------------------------------------------------------------------------------------------186. EJB Tutorial http://www.javaperformancetuning.com/tips/j2ee_ejb.shtml http://www.jguru.com/faq/topicindex.jsp?topic=EJ B ----------------------------------------------------------------------------------------------------------------------189. What is Scalability ? ...scalable..." An application is scalable if the system that hosts it can be expanded or upgraded to support a higher client load, without significant modification to the software. Scalable does not necessarily mean 'high performance,' despite a common belief that this is the case. EJB applications support scalability because they lend themselves to distribution; they support high performance because they allow the sharing of resources and minimize overheads, as we shall see. EJB run in a framework that supports distribution, load sharing, fault tolerance, security, and transaction management. To their clients they 'look like' ordinary Java objects, and can be used similarly. --------------------------------------------------------------------------------------190. What is ear file 89 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM An .ear file is an "Enterprise Archive" file. The file has the same format as a regular .jar file (which is the same as ZIP, incidentally). The .ear file contains everything necessary to deploy an enterprise application on an application server. It contains both the .war (Web Archive) file containing the web component of the application as well as the .jar file. In addition there are some deployment descriptor files in XML. http://java.sun.com/j2ee/j2sdkee/techdocs/guides/ejb/html/Overview.fm.html contains additional information. ---------------------------------------------------------------------------------------------------------------------- 191. Why CMP is better than BMP? Use CMP except in specific cases when BMP is necessary: fields use stored procedures; persistence is not simple JDBC (e.g. JDO); One bean maps to multiple tables; non-standard SQL is used. CMP can make many optimizations: optimal locking; optimistic transactions; efficient lazy loading; efficiently combining multiple queries to the same table (i.e. multiple beans of the same type can be handled together); optimized multi-row deletion to handle deletion of beans and their dependents. http://www.javaperformancetuning.com/tips/j2ee_ejb.shtml#REF13 ---------------------------------------------------------------------------------------------------------------------- 192. Stateful to Stateless Bean : Stateless session beans are much more efficient than stateful session beans. Stateless session bean have no state. Most containers have pools of stateless beans. Each stateless bean instance can serve multiplw clients, so the bean pool can be kept small, and doesn't need to change in size avoiding the main pooling overheads. A separate stateful bean instance must exist for every client, making bean pools larger and more variable in size. 90 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM [Article discusses how to move a stateful bean implementation to stateless bean implementtaion]. http://www.javaperformancetuning.com/tips/j2ee_ejb.shtml#REF13 ---------------------------------------------------------------------------------------------------------------------- 193. EJB performance tips EJB calls are expensive. A method call from the client could cover all the following: get Home reference from the NamingService (one network round trip); get EJB reference (one or two network roundtrips plus remote creation and initialization of Home and EJB objects); call method and return value on EJB object (two or more network rountrips: client-server and [mutliple] server-db; several costly services used such as transactions, persistence, security, etc; multiple serializations and deserializations). If you don't need EJB services for an object, use a plain Java object and not an EJB object. Use Local interfaces (from EJB2.0) if you deploy both EJB Client and EJB in the same JVM. (For EJB1.1 based applications, some vendors provide pass-by-reference EJB implementations that work like Local interfaces). Wrap multiple entity beans in a session bean to change multiple EJB remote calls into one session bean remote call and several local calls (pattern called SessionFacade). Change multiple remote method calls into one remote method call with all the data combined into a parameter object. Control serialization by modifying unnecessary data variables with 'transient' key word to avoid unnecessary data transfer over network. Cache EJBHome references to avoid JNDI lookup overhead (pattern called ServiceLocator). Declare non-transactional methods of session beans with 'NotSupported' or 'Never' transaction attributes (in the ejb-jar.xml deployment descriptor file). Transactions should span the minimum time possible as transactions lock database rows. Set the transaction time-out (in the ejb-jar.xml deployment descriptor file). Use clustering for scalability. Tune the EJB Server thread count. Use the HttpSession object rather than a Stateful session bean to maintain client state. Use the ECperf benchmark to help differentiate EJB server performances. 91 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM Tune the Stateless session beans pool size to minimize the creation and destruction of beans. Use the setSessionContext() or ejbCreate() method to cache bean specific resources. Release acquired resources in the ejbRemove() method. Tune the Stateful session beans cache size to and time-out minimize activations and passivations. Allow stateful session beans to be removed from the container cache by explicitly using the remove() method in the client. Tune the entity beans pool size to minimize the creation and destruction of beans. Tune the entity beans cache size to minimize the activation and passivation of beans (and associated database calls). Use the setEntityContext() method to cache bean specific resources and release them from the unSetEntityContext() method. Use Lazy loading to avoid unnecessary pre-loading of child data. Choose the lowest cost transaction isolation level that avoids corrupting the data. Transaction levels in increasing cost are: TRANSACTION_READ_UNCOMMITED, TRANSACTION_READ_COMMITED, TRANSACTION_REPEATABLE_READ, TRANSACTION_SERIALIZABLE. Use the lowest cost locking available from the database that is consistent with any transaction. Create read-only entity beans for read only operations. Use a dirty flag where supported by the EJB server to avoid writing unchanged EJBs to the database. Commit the data after the transaction completes rather than after each method call (where supported by EJB server). Do bulk updates to reduce database calls. Use CMP rather than BMP to utilize built-in performance optimization facilities of CMP. Use ejbHome() methods for global operations (from EJB2.0). Tune the connection pool size to minimize the creation and destruction of database connections. Use JDBC directly rather than using entity beans when dealing with large amounts of data such as searching a large database. Combine business logic with the entity bean that holds the data needed for that logic to process. Tune the Message driven beans pool size to optimize the concurrent processing of messages. Use the setMesssageDrivenContext() or ejbCreate() method to cache bean specific resources, and release those resources from the ejbRemove() method. 92 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM ---------------------------------------------------------------------------------------------------------------------194. Pattern performance tips The ServiceLocator/EJBHomeFactory Pattern reduces the expensive JNDI lookup process by caching EJBHome objects. The SessionFacade Pattern reduces network calls by combining accesses to multiple Entity beans into one access to the facade object. The MessageFacade/ServiceActivator Pattern moves method calls into a separate object which can execute asynchronously. The ValueObject Pattern combines remote data into one serializable object, thus reducing the number of network transfers required to access multiple items of remote data. The ValueObjectFactory/ValueObjectAssembler Pattern combines remote data from multiple remote objects into one serializable object, thus reducing the number of network transfers required to access multiple items of remote data. The ValueListHandler Pattern: avoids using multiple Entity beans to access the database, using Data Access Objects which explicitly query the database; and returns the data to the client in batches (which can be terminated) rather than in one big chunk, according to the Page-by-Page Iterator pattern. The CompositeEntity Pattern reduces the number of actual entity beans by wrapping multiple java objects (which could otherwise be Entity beans) into one Entity bean. ---------------------------------------------------------------------------------------------------------------------195. Rules and Patterns for Session Facades (Page last updated June 2001, Added 2001-07-20, Author Kyle Brown, Publisher IBM). Tips: Use the Facade pattern, and specifically Value objects, to transfer all the subset of data needed from an entity bean in one transfer. 93 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM ---------------------------------------------------------------------------------------------------------------------- 196. EJB performance tips (Page last updated December 2001, Added 2001-1226, Author Krishna Kothapalli and Raghava Kothapalli, Publisher JavaPro). Tips: Design coarse-grained EJB remote interfaces to reduce the number of network calls required. Combine remote method calls into one call, and combine the data required for the calls into one transfer. Reduce the number of JNDI lookups: cache the home handles. Use session bean wrapper for returning multiple data rows from an entity bean, rather than returning one row at a time. Use session beans for database batch operations, entity beans typically operate only one row at a time. Use container-managed persistence (CMP) rather than bean-managed persistence (BMP). Use entity beans when only a few rows are required for the entity, and when rows need to be frequently updated. Use the lowest impact isolation (transaction) level consistent with maintaining data coherency. Highest impact down: TRANSACTION_SERIALIZABLE, TRANSACTION_REPEATABLE_READ, TRANSACTION_READ_COMMITED, TRANSACTION_READ_UNCOMMITED. Correctly simulate the production environment to tune the application, and use profiling and other monitroing tools to identify bottlenecks. Tune the underlying system, e.g. TCP/IP parameters, file limits, connection pool parameters, EJB pools sizes, thread counts, number of JVMs, JVM heap size, shared pool sizes, buffer sizes, indexes, SQL queries, keep/alive parameters, connection backlogs. Use clustering to meet higher loads or consider upgrading the hardware. 94 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM ---------------------------------------------------------------------------------------------------------------------- 197. Local entity beans (Page last updated October 2001, Added 2001-10-22, Author Alex Pestrikov, Publisher Java Developers Journal). Tips: Local entity beans do not need to be marshalled, and do not incur any marshalling overhead for method calls either: parameters are passed by reference. Local entity beans are an optimization for beans which it is known will be on the same JVM with their callers. Facade objects (wrappers) allow local entity beans to be called remotely. This pattern incurs very little overhead for remote calls, while at the same time optimizing local calls between local beans which can use local calls. ---------------------------------------------------------------------------------------------------------------------198. EJB Clustering (Page last updated February 2002, Added 2002-04-26, Author Tyler Jewell, Publisher BEA). Tips: Four locations that can provide clustering logic for an EJB are: the JNDI naming server where the home stub is bound, the container, the home stub, and the remote stub. ---------------------------------------------------------------------------------------------------------------------199. Clustering should allow failover if a machine/process crashes. For stateful sessions, this requires state replication. 95 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM To support distributed sessions, make sure: all session referenced objects are serializable; store session state changes in a central repository. ---------------------------------------------------------------------------------------------------------------------. HTTP sessions vs. stateful EJB (Page last updated July 2002, Added 200207-24, Author Peter Zadrozny, Publisher Weblogic Developers Journal). Tips: The comparative costs of storing data in an HTTP session object are roughly the same as storing the same data in a stateful session bean. Failure to remove an EJB that should have been removed (from the HTTP session) carries a very high performance price: the EJB will be passivated which is a very expensive operation. ---------------------------------------------------------------------------------------------------------------------201. Optimizing entity beans (Page last updated May 2001, Added 2001-05-21, Author Akara Sucharitakul, Publisher Sun). Tips: Use container-managed persistence when you can. An efficient container can avoid database writes when no state has changed, and reduce reads by retrieving records at the same time as find() is called. Minimize database access in ejbStores. Use a "dirty" flag to avoid writing tee bean unless it has been changed. Always cache references obtained from lookups and find calls. Always define these references as instance variables and look them up in the setEntityContext (method setSessionContext for session beans). Avoid deadlocks. Note that the sequence of ejbStore calls is not defined, so the developer has no control over the access/locking sequence to database records. ---------------------------------------------------------------------------------------------------------------------202. 96 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM EJB 2.0 Container-Managed Persistence provides local interfaces which can avoid the performance overheads of remote interfaces ---------------------------------------------------------------------------------------------------------------------203. Avoid stateful sessions for Performance Tuning ---------------------------------------------------------------------------------------------------------------------204. Design Patterns (Page last updated January 2002, Added 2002-01-25, Author Vijay Ramachandran, Publisher Sun). Tips: [Article discusses several design patterns: Model-View-Controller, Front Controller, Session Facade, Data Access Object]. Use the Front Controller pattern to channel all client requests through a single decision point, which allows the application to be balanced at runtime. Use a Session Facade to provide a simple interface to a complex subsystem of enterprise beans, and to reduce network communication requirements. Use Data Access Objects to decouple the business logic from the data access logic, allowing data access optimizations to be decoupled from other types of optimizations. Use the Data Access Object pattern to decouple business logic from data access logic, allowing for optimizations to be made in how data is managed. Use the Fast-Lane Reader pattern to accelerate read-only data access by not using enterprise beans. Use the Front Controller pattern to centralize incoming client requests, allowing optimizations to be made in aggregating the resulting view. Use the Page-by-Page Iterator pattern to efficiently access a large, remote list by retrieving its elements one sublist of value objects at a time. Use the Session Facade pattern to provide a unified, workflow-oriented interface to a set of enterprise beans, thus minimizing client calls to server EJBs. Use the Value Object pattern to efficiently transfer remote, fine-grained data by sending a coarse-grained view of the data. ---------------------------------------------------------------------------------------------------------------------- 97 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM 205. J2EE Performance tuning (Page last updated October 2001, Added 2001-10-22, Author James McGovern, Publisher Java Developers Journal). Tips: Always access entity beans from session beans. If only using an entity bean for data access, use JDBC directly instead. Use read-only in the deployment descriptor. Cache access to EJB homes. Use local entity beans when beans are co-located in the same JVM. Proprietary stubs can be used for caching and batching data. Use a dedicated remote object to generate unique primary keys. 206. Abstract class can’t be instantiated like Interface 207. How many Jar files are used in EJB? Ejb-jar.xml, weblogic-ejb-jar.xml and weblogic-cmp-rdbms-jar.xml 208. How many Jar files are used in EJB? Ejb-jar.xml, weblogic-ejb-jar.xml and weblogic-cmp-rdbms-jar.xml 209. How can you optimize in Java Creating object is costly 98 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM Reuse the object Avoid Synchronization Use Final modifier where ever required 210. Struts is the defecto standard for MVC patten Struts can’t access Database Struts can’t provide Transaction, Load Balancing and Security 211. Ant is a make file based on Java and XML 212. Final Class can’t be extended Final Variable can’t be altered (MUST INTIALISE) Final Method can’t be overridden in subclass 213. Inheritance is nothing but, re-usable of methods and variables 214. Non static variable can’t be used in side the Static Method – TRUE A Static variable can be used in side the normal or simple Method - TRUE 215. Use static method – WHEN you need only single UNIQUE COPY of a variable 216. EXPLICIT CASTING WRONG 99 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM Object obj = new Object; String str = Obj; // WRONG CORRECT Object obj = new Object; String str = (String) Obj; 217. Resonse.sendRedirect() – Http Parameter information is lost Request.requestDispatcher() – forward the request Jsp:forward()– forward the request Jsp:include() 218. What is Singleton Class class Singla { private static Singla sx; private Singla(){} private String aa; protected String getMe(){ aa = "ALL ARE WELCOME TO singleton"; return aa; } protected static synchronized Singla getSingla(){ if(sx == null){ System.out.println("SINGLE10 instance is created freshly"); sx = new Singla(); } return sx; } }; 100 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM public class StringDay { public static void main(String ss[]){ Singla sxx = Singla.getSingla(); System.out.println(" from singleton " +sxx.getMe()); } } 219. If it is private constructor, than 1. If a class has private Constructor, than it can ‘t be instantiated from any other class. 2. That class can’t be extended 3. Its method can be accessed by its public member methods 220 . Serialization 1. Serialized objects’s conversational state can be stored in the disk or file 2. Used for Session Replication 3. Serialization normally done for Simple persistence or Network Communication 101 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM 4. Synchronization objects are using Serializations for load balancing 5. Session objects are serialized for Clustering 221. What is javap ? Javap is used in dos prompt to see Java API C:> javap java.util.Hashtable 222. java.sql.Date Java.sql.Date = Date.valueOf(“2004-12-31”); 223. What is Normalization? Normalization – enables to design and judge the quality of Database design First Normalization – Records are stored in the Table Second Normalization – All other attributes are fully or functionally depends on Primary Key or Composite Primary Key Third NormalizationThere is should not be trasnsitively interdependy on attributes Boyce Codd’s Normalization All fields are depends on Primary Key and Primary Key is the super key. 102 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM 224. Design Pattern Session Façade MVC MVC 2 Business Delegate Front Controller DAO DTO Print Out - > 225. SAX Vs DOM XML was created so that richly structured documents could be used over the web Users must be able to view XML documents as quickly and easily as HTML documents. -legible and reasonably clear XSL - Defines the standard stylesheet language for XML (XLink), which allows elements to be inserted into XML documents in order to create and describe links between resources. XPointer), the language to be used as the basis for a fragment identifier for any URI reference that locates a resource whose Internet media type is one of text/xml, application/xml. 226. SAX, the Simple API for XML, is a standard interface for event-based XML parsing, DOM rograms to dynamically access and update the content and structure of documents 103 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM Accenture Questions on 28th Nov 2004 - SELECTED 1. Design your FedEx Project 2. Design and Planning Skills 3. What is DAO? 4. What is XSLT , XML and JSP? 5. Session Façade 6. Session Bean – how you used in Project Scandent chennai, Questions on 29th Nov 2004 – NOT SELECTED 1. Functinal Points 2. Business Requirement Doc 3. System Requirment Doc 4. High Level Design 5. Lower Level Design 6. Sequence Diagram ( How will you arriave based on Use Case) 7. Dependency Class 8. Runnable Interface V Thread Class 9. Class | Interface | Abstract 10. Struts Frame Work 11. What is EJB QL and CMR 12. What are new Exceptions in EJB 2.0 13. What is Message Driven Bean 227. local home interface defines the methods that allow local clients to create, find, and remove EJB objects, as well as home business methods that are not specific to a bean instance local interface provides the local client view of an EJB object. An enterprise Bean's local interface defines the business methods callable by local clients 228. java.lang.Runnable Interface Runnable interface should be used if you are only planning to override the run() method and no other Thread methods. 104 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM Run() – Being active simply means that a thread has been started and has not yet been stopped. When an object implementing interface Runnable is used to create a thread, starting the thread causes the object's run method to be called in that separately executing thread. Destroy() - Destroys this thread, without any cleanup. Sleep() –Causes the currently executing thread to sleep (temporarily cease execution) Join() – Waits for this thread to die. Yield() – Causes the currently executing thread object to temporarily pause and allow other threads to execute. Resume() – Depricated Start() – Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread. Stop() – Depricated Suspend() – Depricated VERY IMPORTANT Class Diagram Representation of Aggregation, Association, Generalization and Dependency How will you drive out Sequence Diagram? What is Funcational Points? What is BRD, SRS and HLD? What is LLD? 229. Exceptions in EJB 2.0 105 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM An AccessLocalException is thrown to indicate that the caller does not have permission to call the method. This exception is thrown to local clients. CreateException exception is used as a standard application-level exception to report a failure to create an entity EJB object. The DuplicateKeyException exception is thrown if an entity EJB object cannot be created because an object with the same key already exists The EJBException exception is thrown by an enterprise Bean instance to its container to report that the invoked business method or callback method could not be completed because of an unexpected error The FinderException is used as a standard application-level exception to report a failure to find the requested EJB object(s). This NoSuchEntityException may be thrown by the bean class methods that implement the business methods defined in the bean's component interface; and by the ejbLoad and ejbStore methods. (Normal Method) NoSuchObjectLocalException is thrown if an attempt is made to invoke a method on an object that no longer exists. (Finder Method)The ObjectNotFoundException exception is thrown by a finder method to indicate that the specified EJB object does not exist. The RemoveException exception is thrown at an attempt to remove an EJB object when the enterprise Bean or the container does not allow the EJB object to be removed. TransactionRequiredLocalException indicates that a request carried a null transaction context, but the target object requires an activate transaction. This TransactionRolledbackLocalException indicates that the transaction associated with processing of the request has been rolled back, or marked to roll back. Thus the requested operation either could not be performed or was not performed because further computation on behalf of the transaction would be fruitless 106 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM 230. Exceptions Hierarchy java.lang.Object | +--java.lang.Throwable | +--java.lang.Exception | +--java.lang.RuntimeException | +--javax.ejb.EJBException 241. Example of Dependency and Aggregation diagram example of aggregation -----------------------------public class Money{} public class Wallet { private Money money; public Wallet(Money money) { this.money = money; } } The instance of aggregated class can be shared by many other classes. While those classes are deleted, the instance of aggregated class won't be deleted." hence, i create money object outside the wallet, the passed the money into the wallet to make them "has a" relationship. example of composite (dependency) -------------------------------public class Heart {} public class Human { private Heart heart; 107 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM private Human() { heart = new Heart(); } } the instance of composited class can only be used by one other class. While that class is deleted. The composited class will also be deleted." the composite class is a dependency class for any classes. it leads to high coupling. Composition is implicitly a bi-directional relationship. Example of Generalization Parent / Child class http://pigseye.kennesaw.edu/~dbraun/csis4650/A&D/UML_tutorial/class.ht m 108 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM Nov 30, 2004 242. Mock Exam Java Questions public class Q1 { public static void main(String ss[]){ float f = (float)1.3; // default floatint point value is double double d = 12.41; byte b= 100 + 27; // max 127 NOT > 127 Byte bb = new Byte(b); boolean bool = true; //always true or false NOT null value char ch= 'a'; System.out.println("value of f is "+ f); System.out.println("value of d is "+ d); System.out.println("value of b is "+ bb.intValue()); System.out.println("value of bool is "+ bool); System.out.println("value of ch is "+ ch); } } 109 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM 243. Mock Exam Java Questions public class Q2 { public static void main(String ss[]){ hi(); } public void hi(){ System.out.println("welcome to q2"); } } Hi () method should be static since it is residing or calling from static reference Like : Public static void hi(){} 244. Mock Exam Java Questions public class Q3 { static int a_classVariable = 1; // class variable int b_localVariable = 2; // local variable public static void main(String ss[]){ int c_instanceVariable = 3; //local or member variable System.out.println("value of c is from main() " + c_instanceVariable); //System.out.println("value of b is from classMethod() " + b_localVariable); Q3.classMethod(); new Q3().instanceMethod(); } public static void classMethod(){ System.out.println("value of a is from classMethod() " + a_classVariable); // System.out.println("value of b is from classMethod() " + b_localVariable); //non static variable can't be referenced from static context } public void instanceMethod(){ 110 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM int d_localvariable = 4; System.out.println("value of a is from instanceMethod() " + a_classVariable); System.out.println("value of b is from instanceMethod() " + b_localVariable); } } 245. Mock Exam Java Questions public class Q4 { static int a; //class variable default value is 0 public static void main(String ss[]){ int b ; //ERROR - Local variable must explicitly assign or initialize value System.out.println(" value of a is " + b); } } 246. Mock Exam Java Questions abstract class AbstraClass { //abstract public void getMe1(); //instance method - will not work , method names are same but modifier are different //abstract public void getMe(); //instance method - will work , method name are not same and child class also abstract public static void getMe1(){ System.out.println(" welcome to AbstraClass getMe1() method "); } } abstract public class Abstra extends AbstraClass{ public static void getMe1(){ //static method System.out.println(" welcome to Child class method "); } 111 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM public static void main(String ss[]){ Abstra.getMe1(); } } 247. Mock Exam Java Questions In overriding, Parent class or Parent Abstract class can have private method in OVER RIDING Child class cannot have private modifier in OVER RIDING method if Parent Abstract class or Parent calss modifier is public or protected or packageLocal. 248. Mock Exam Java Questions import java.io.*; public class Mine { public static void main(String ss[]){ Mine m = new Mine(); System.out.println(m.amethod()); } public int amethod(){ try{ FileInputStream fis = new FileInputStream("hello.txt"); }catch(FileNotFoundException fnfe){ System.out.println("No Such file found"); return -1; }catch(IOException ioe){ System.out.println("io exception area"); return -2; }finally{ System.out.println("inside finally"); } return 0; } 112 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM } Out put is No Such file found inside finally -1 Finally will execute irrespective of return statement at any stage ( Even before finally block – return statement executes ) 249. Mock Exam Java Questions SUPER() – method (non static variable) // should used inside the child constructor for calling parent constructor // should be the first statement in side the child constructor // super can be used to call parent class method like ClassName.staticMethod 250. Mock Exam Java Questions this() – method ( non static variable) // should used inside the class or child constructor for calling child or class constructor // should be the first statement in side the child constructor // it is used to distinguish passing argument with class variable ( this.parentid = parentid in setter method of java bean) 251. Mock Exam Java Questions In OVER LOADING, Method name should be same but different argument or modifer. 252. Mock Exam Java Questions 113 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM Skeleton – A server-side representation of a remote object. The server-side skeleton is responsible for deserializing and unpacking the request from its companion client-side stub. submits it as a method call to be invoked on the object's implementation. Stub A client-side representation of a remote object that is used to invoke methods on the implementation of the remote object. Defines the interface to the remote object implementation of an object. The stub is responsible for packaging up the client request, serializing it, and shipping it to the companion skeleton on the server side. 253. Mock Exam Java Questions In OVER RIDING, Method name should be same butt modifer can represent in hierarchy level Like Child Class can’t have private method overriding if parent method is public modifer 254. Mock Exam Java Questions public class GrandParent { GrandParent(){ System.out.println("GrandParent NULL CONSTRUCTOR "); } public static void getTest(){ System.out.println("getTest of GrandParent class "); } } public class Parent extends GrandParent { Parent(){ System.out.println("PARENT NULL CONSTRUCTOR "); } public static void getTest(){ 114 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM System.out.println("getTest of parent class "); //GrandParent.getTest(); } } public class Child extends Parent { Child(){ System.out.println("CHILD NULL CONSTRUCTOR "); } public static void getTest(){ System.out.println("getTest of CHILD class "); //Parent.getTest(); } public static void main(String ss[]){ //Child c = new Child(); //Parent c = new Child(); - ERROR //GrandParent c = new Child(); - ASSIGN CHILD OBJECT if methods are non-static GrandParent c = new Parent() ASSIGNS PARENT OBJECT, if methods are non-static in both parent and GrandParent class (overriding) ASSIGNS GRANDPARENT OBJECT, if methods are static in both parent and GrandParent class (overriding) c.getTest(); } } GrandParent c = new Parent() c.getTest() if methods are static Output is 115 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM GrandParent NULL CONSTRUCTOR PARENT NULL CONSTRUCTOR getTest of GrandParent class GrandParent c = new Parent() c.getTest() if methods are non-static Output is GrandParent NULL CONSTRUCTOR PARENT NULL CONSTRUCTOR getTest of Parent class Child c = new Child() c.getTest() if methods are non-static Output is GrandParent NULL CONSTRUCTOR PARENT NULL CONSTRUCTOR CHILD NULL CONSTRUCTOR getTest of CHILD class 255. Mock Exam Java Questions import java.io.*; public class FileWriterx { public static void main(String args[]){ try{ System.out.println("....Pls Type....end to exit"); FileWriter fw = new FileWriter("c:/tt.txt",true); BufferedReader bufferReader = new BufferedReader(new InputStreamReader(System.in)); String a = ""; System.out.println(" File writing...." ); while (!((a = bufferReader.readLine()).equalsIgnoreCase("END"))){ fw.write(a + "\t"); 116 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM } fw.close(); bufferReader.close(); FileReader fr = new FileReader("c:/tt.txt"); BufferedReader in = new BufferedReader(fr); System.out.println(" File Reading...." + in.readLine()); fr.close(); in.close(); }catch(Exception e){ e.printStackTrace(); } } } From Here – NEW PRINT DEC 1, 2004 256. Mock Exam Java Questions If method is non-static, Local variable can be Final or int variable will be declared Eg. Public void getDemo(){ Int a = 10; //ALLOWED Final int b = 20; // ALLOWED Static int a = 10; //DECLARATION NOT ALLOWED, but we can use in non-static method Public int a= 100; // NOT ALLOWED } 257. Mock Exam Java Questions 117 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM A class may be abstract If it has abstract methods or not A class must be abstract If a class does not want to implement abstract methods, al though it is extending abstract class. Note : Abstract class can’t be instantiated 258. Mock Exam Java Questions Employee e = new Salesman(); e.getSalary(); If methods are static ( overriding method) e.getSalary() will invoke from Employee Class If methods are normal( overriding method) e.getSalary() will invoke from Salesman Class But, both cases, Constructor Employee and Constructor Salemsman () will invoke 259. Mock Exam Java Questions In Over-riding, When I Should USE below method - for Calling Parent Method in OVER RIDING ClassName.getMethodName() - IF METHOD IS STATIC Super.getMethodName() for calling Parent - IF METHOD IS NON – STATIC, since super is static method. NOTE : super should be used before RETURN statement 260. Mock Exam Java Questions 118 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM public class Manager { static int bonus = 5000; public Manager() { System.out.println("Manager() Constructor"); } public int getSalary() { return bonus; } } public class Employee extends Manager{ private static int salary = 1000; public Employee() { System.out.println("Employee() Constructor"); } public int getPrivateSalary(){ return salary; } public int getSalary() { System.out.println("Employee Salary is "+ salary); return salary; } } public class Salesman extends Employee{ static int commission = 100; public Salesman() { System.out.println("Salesman() Constructor"); } public int getSalary() { VALID // int a = commission + bonus + new Employee().getPrivateSalary(); VALID // int a = commission + bonus + getPrivateSalary(); VALID // return commission + bonus + super.getPrivateSalary(); 119 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM } public static void main(String ss[]){ Salesman e = new Salesman(); System.out.println(e.getSalary()); } } 261. Mock Exam Java Questions Example of Overloading Same method name and same argument passings type and number of arguments in the method public class OLoading { public OLoading() { System.out.println("welcome to OLoading default constructor"); } public static void get(int a){ } public void get(long a){ } protected void get(long a,long b){ } private static void get(String a,long aa,long b){ } public static void main(String ss[]) { } } 120 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM 261. Mock Exam Java Questions Example of Overriding Same Method name and same modifier and same return type and no of arugment passing and argument type and public class ORidingBase { public ORidingBase() { } public static void get(int a){ //over ridden method System.out.println("welcome to Base"); } } public class ORiding extends ORidingBase{ public ORiding() { } public static final void get(int b){ System.out.println("welcome to Subclass"); ORidingBase.get(1); } // final is allowed in over – riding method // final is allowed in over –ridden method public static void main(String ss[]) { ORiding o = new ORiding(); //ORidingBase o = new ORidingBase(); o.get(1); } } 262. Mock Exam Java Question 121 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM Static – only one instance exist for any amount of class instances - static can be used in method and variable level - inner class can’t have static declaration Final - final method can’t be over-ridden - once created can’t be altered - final class can’t be subclassed or can’t be inherited or can’t be extended 263. Mock Exam Java Question Constructor – Can be Overloaded Defaut constructor will be created once object is created Can’t have return type Can’t pass void argument Can’t have void as default return type Can’t be overridden 264. Mock Exam Java Question public class DConstra { 122 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM public DConstra(int a) { System.out.println("oNe Constructor " ); } public static void main(String ss[]) { DConstra d = new DConstra(); } } Output is ERROR since there is no default constructor 265. Mock Exam Java Question Inner Class public class OuterInner { int a = 10; final float b = 20.0f; private static int c = 30; String str = "raj"; char ch='c'; public OuterInner() { System.out.println("Default Constructor OuterInner class is invoked "); } private class inner{ int k = 100; public inner(){ System.out.println("Default Constructor inner is invoked "); } public void getMe(){ System.out.println("getMe - inner is invoked " + c); } public int returnK(){ return k; } } 123 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM public void getMe(){ System.out.println("getMe - outer is invoked " + new inner().returnK()); } public static void main(String ss[]) { OuterInner o = new OuterInner(); o.getMe(); inner i = new OuterInner().new inner(); i.getMe(); } } Output; Default Constructor OuterInner class is invoked Default Constructor inner is invoked getMe - outer is invoked 100 Default Constructor OuterInner class is invoked Default Constructor inner is invoked getMe - inner is invoked 30 4Dec2004 266. What is Class Loader 267. What is Design Pattern? 268. Why UML Diagram? 269. What is HLD, SRS, LLD, BRD? 270. What is Checked and Unchecked Exceptions? 271. What is Error? 272. What are JVM and What for Registers, Stack, Method Area and Heap? 124 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM Dec 5, 2004 SUNDAY, IBM INTERVIEW – NOT SELECTED Core Java 1. What is Interface and Abstract Class 2. Shall Interface can have inner class? 3. Shall Interface extend a Class? 4. Shall Interface extend Interface 5. Below class will compile or not Class A {} 6. Below class will compile or not Private or proteced class A { } 7. What is Vector and ArrayList? 8. How will you increase ArrayList ? (ArrayList arrayList.ensureCapacity(100);) 9. Shall ArrayList will have null value 10. What is HashTable and HashMap? (both have loadfactor and rehash) 11. Shall HashTable hold null value and null key? 12. Collection, Map, List, Set are all Class or Interface? 13. Which has ordered elements ? ( List, Sorted Map, Sorted List) 14. How will you synchronize ArrayList 15. what will be the output? Class A { Public static void main(){….} } Class B extends Class A{ Public static void main(){ SOP (..) Super.main() // ERROR since super non-static variable This.Main() // this reserve word is non static 125 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM } TRY 32. Error can be catched in try-catch block 33. Finally will execute after return or system.exit() statement EJB 16. What are algorithm is Used in Passivation and Activation technique? LRU, JIT for Passivation and Activation 17. why stateless has null argument in Create() method 18. what is sessionsynchronization? 19. What is Declarative and Programatic Transaction 20. What are Transaction Attributes are there? 21. Shall Entity bean will have TX_Supports Transaction Attributes? 22. what is JNDI Architechture? 23. During Transaction, shall we do passivation – NO 24. How will distinguish Stateless or Stateful during coding level 25. which is important .xml file for EAR ? 26 What EAR, JAR, WAR? 27. During Deployment, How jar will interact or communicate? 28. web.xml is important xml file for WAR 29. What is MANIFEST file JSP and SERVLET 30. <jsp: include >and <declarative include > 31. What is Application Scope and how ill you code in servlet? ServletContext context = getServletContext(); Context.setAttribute(“KE”,”VALUE”); Application scope will die during Servlet/JSP container shut downs Other scopes are : page, session , request 273. what is Multiple Inheritance? A class which has 2 base class. Not supported in Java 126 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM 274. Primary Storage – file system Secondary Storage – Oracle Database 275. Javax.servlet.http.ServletRequest request; Javax.servlet.http.HttpSession session = request.getSession() Returns the current session associated with this request, or if the request does not have a session, creates new session HttpSession session = request.getSession(true) Returns the current session associated with this request, or if the request does not have a session, creates new session if it is true HttpSession session = request.getSession(false) Returns the current session associated with this request, or if the request does not have a session, it will not create new session 276. Rehash() – Increases the capacity of and internally reorganizes this hashtable, in order to accommodate and access its entries more efficiently. 277. Javax.servlet.http.HttpSession session; Session. setAttribute(String name, Object value) 278. Hashtable 127 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM Java.util.Hashtable hastable; Hastable. put(Object key, Object value) 279. About Finally public class Finall { public Finall() { System.out.println("Default Constructor - CLASS Finall is invoked "); } public static void main(String ss[]) { System.out.println(" Value of return type is " + main()); } public static int main() { try{ throw new Exception("1"); }catch(Exception e){ // System.exit(0); return 1; } finally{ System.out.println("FINALLY BLOCK"); } } } OUTPUT FINALLY BLOCK Value of return type is 1 IF System.exit(0) is used , then out put is nothing will displayed 280. What is Error Class? 128 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. The ThreadDeath error, though a "normal" condition, is also a subclass of Error because most applications should not try to catch it. Internal ErrorThrown to indicate some unexpected internal error has occurred in the Java Virtual Machine. StackOverFlowThrown when a stack overflow occurs because an application recurses too deeply. ClassFormatError Thrown when the Java Virtual Machine attempts to read a class file and determines that the file is malformed or otherwise cannot be interpreted as a class file. 281. Different Types of Inner Class Nested Top Level Member Class Local Class Anonymous Class 281. Shall Abstract Class have Constructor and inner class abstract class AbstraClass { static int aaa= 1; static int getMe1(){ System.out.println(" welcome to AbstraClass getMe1() method "); return aaa; } AbstraClass(){ System.out.println(" AbstraClass Constructor "); new A().gg(); } class A { public void gg(){ System.out.println(" inner class is A "); } } } public class Abstra extends AbstraClass{ 129 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM static int aaa = 100; public Abstra(){ System.out.println(" Child Constructor "); } static int getMe1(){ //static method System.out.println(" welcome to Child class method "); return aaa; } public static void main(String ss[]){ Abstra aaa = new Abstra(); System.out.println(aaa.getMe1()); System.out.println(aaa.aaa); } } Output AbstraClass Constructor inner class is A Child Constructor welcome to Child class method 100 100 282. Shall Inner Class can be accommodated in Interface interface Interfaca1{ class A { public static void gg(){ System.out.println(" inner class is A "); } } } public class Interfaca implements Interfaca1{ public Interfaca(){ System.out.println(" Child Constructor "); A.gg(); } 130 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM void getMe1(){ System.out.println(" welcome to Child class method "); } public static void main(String ss[]){ Interfaca aaa = new Interfaca(); aaa.getMe1(); } } Output Child Constructor inner class is A welcome to Child class method 283. Class AAA{ Int a; Static int b; Public static void main(){ Int c = 10; } } Class Variable - b Member Variable - a Local Variable - c 284. Tricky Program ( in Over Riding) abstract class AbstraClass { //abstract public void getMe1(); //instance method - will not work , method names are same but modifier are different //abstract public void getMe(); //instance method - will work , method name are not same and child class also abstract 131 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM int aaa= 1; int getMe1(){ System.out.println(" welcome to AbstraClass getMe1() method "); return aaa; } AbstraClass(){ System.out.println(" AbstraClass Constructor "); } } public class Abstra extends AbstraClass{ int aaa = 100; public Abstra(){ System.out.println(" Child Constructor "); } int getMe1(){ //static method System.out.println(" welcome to Child class method "); return aaa; } public static void main(String ss[]){ AbstraClass aaa = new Abstra(); System.out.println(aaa.getMe1()); System.out.println(aaa.aaa); } } OutPUT: 1 100 OutPut : if all overriding methods are static 1 1 285. What is System , out and println() ? System.out.println() – oldest way of Debugiging the statement to display in Standard output System is a final class 132 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM Out is a static final field variable of PrintStream Println() is a method in PrintStream System.err.println System.in System.exit(-1) System.setProperty() System.load() System.gc() System.currentTimeMillis() 286. Tricky Program EAR file need – application.xml WAR file need – web.xml 287. Cookie java.lang.Object javax.servlet.http.Cookie Creates a cookie, a small amount of information sent by a servlet to a Web browser, saved by the browser, and later sent back to the server. A cookie's value can uniquely identify a client, so cookies are commonly used for session management. The servlet sends cookies to the browser by using the HttpServletResponse.addCookie(javax.servlet.http.Cookie) method, which adds fields to HTTP response headers to send cookies to the browser, one at a time. The browser is expected to support 20 cookies for each Web server, 300 cookies total, and may limit cookie size to 4 KB each. default, cookies are created using Version 0 to ensure the best interoperability. This class supports both the Version 0 (by Netscape) and Version 1 (by RFC 2109) cookie specifications The browser returns cookies to the servlet by adding fields to HTTP request headers. Cookies can be retrieved from a request by using the 133 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM HttpServletRequest.getCookies() method. Several cookies might have the same name but different path attributes. 288. Request Header and Response Header Javax.servlet.http.HTTPServletResponse Javax.servlet.http.HTTPServletRequest 289. import sun.security.util.Debug; public class dd { public dd() { System.err.println("Default Constructor - CLASS dd is invoked "); } public static void main(String ss[]) { int a= 100; String s = "raja"; Debug.println("hi","venkat " + a + s); } } 290. System.getProperty() import java.util.Properties; import java.util.Enumeration; ublic class SystemX { public SystemX() { Properties pros = System.getProperties(); Enumeration enum = pros.propertyNames(); while(enum.hasMoreElements()){ String str = (String)enum.nextElement(); System.out.println(" Key - Property " + str); 134 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM System.out.println(" Value " + System.getProperty(str)); } //System.out.println(" Value " + System.getProperty("computer.name")); } public static void main(String ss[]) { SystemX x = new SystemX(); } } java.lang.Object java.lang.Throwable java.lang.Exception javax.ejb.FinderException javax.ejb.ObjectNotFoundException 291. ObjectNotFoundException Only the finder methods that are declared to return a single EJB object use this exception Note: Only the finder methods that are declared to return a single EJB object use this exception. This exception should not be thrown by finder methods that return a collection of EJB objects 292. Checked Exception CreateException, FinderException, RemoveException, ObjectNotFoundException, DuplicateKeyException 293. EJB 2.0 Exception ( RUN TIME EXCEPTION) 135 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM java.lang.Object java.lang.Throwable java.lang.Exception java.lang.RuntimeException javax.ejb.EJBException javax.ejb.AccessLocalException An AccessLocalException is thrown to indicate that the caller does not have permission to call the method. This exception is thrown to local clients. public class NoSuchObjectLocalException extends EJBException A NoSuchObjectLocalException is thrown if an attempt is made to invoke a method on an object that no longer exists. TransactionRequiredLocalException indicates that a request carried a null transaction context, but the target object requires an active transaction. TransactionRolledbackLocalException indicates that the transaction associated with processing of the request has been rolled back 294. Why Exceptions are Class? In order catch the reference of the Exception , we are throwing through (new Exception()) or object. 295. FANTASTIC QUESTION about EXCEPTION and FInally public class Finall { public Finall() { System.out.println("Default Constructor - CLASS Finall is invoked "); } public static void main(String ss[]) { try{ System.out.println(" Value of return type is " + main()); }catch(Exception e){ System.out.println(e.getMessage()); 136 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM } } public static int main()throws Exception { try{ throw new Exception("1"); }catch(Exception e){ //System.exit(0); System.out.println(e.getMessage()); throw new Exception("2"); (like return type) } finally{ System.out.println("FINALLY BLOCK"); } } } Output : 1 Finally Block 2 296. Exception and Finally public class Finall { public Finall() { System.out.println("Default Constructor - CLASS Finall is invoked "); } public static void main(String ss[]) throws Exception{ try{ System.out.println(" Value of return type is " + main()); }catch(Exception e){ //e.printStackTrace(); System.out.println(e.getMessage()); throw new Exception("100"); } } public static int main()throws Exception { 137 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM try{ throw new Exception("1"); }catch(Exception e){ //System.exit(0); System.out.println(e.getMessage()); throw new Exception("2"); } finally{ System.out.println("FINALLY BLOCK"); } } } Output 1 FINALLY BLOCK 2 java.lang.Exception: 100 at Finall.main(Finall.java:21) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:3 9) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorIm pl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:78) Exception in thread "main" Process finished with exit code 1 297. Difference between RemoveException and NoSuchEntityException The RemoveException exception is thrown at an attempt to remove an EJB object when the enterprise Bean or the container does not allow the EJB object to be removed. 138 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM The NoSuchEntityException exception is thrown by an Entity Bean instance to its container to report that the invoked business method or callback method could not be completed because of the underlying entity was removed from the database. Monday, Dec 13, 2004 298. Logger (Log4J) 139 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM /** * Created by IntelliJ IDEA. * User: aaa1 * Date: Aug 2, 2004 * Time: 4:10:40 AM * To change this template use File | Settings | File Templates. */ import org.apache.log4j.Logger; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Level; import org.apache.log4j.PropertyConfigurator; import org.apache.log4j.xml.DOMConfigurator; public class Hello { public static void main(String argv[]) { Logger logger; logger = Logger.getLogger(Hello.class.getName()); BasicConfigurator.configure(); //PropertyConfigurator.configure(argv[0]); logger.setLevel(Level.ERROR); // DOMConfigurator.configure(argv[0]); 140 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM logger.debug("Hello world."); logger.info("What a beatiful day."); } } 299. Log4j.properties # Set root logger level to DEBUG and its only appender to A1. log4j.rootLogger=DEBUG, Stdout , RFA # DRFA and Stdout is set to be a ConsoleAppender. log4j.appender.Stdout=org.apache.log4j.ConsoleAppender log4j.appender.RFA=org.apache.log4j.DailyRollingFileAppender # DRFA and Stdout uses PatternLayout. log4j.appender.Stdout.layout=org.apache.log4j.PatternLayout log4j.appender.Stdout.layout.ConversionPattern=%-d [%t] %-5p %c - %m%n log4j.appender.RFA.layout=org.apache.log4j.PatternLayout log4j.appender.RFA.layout.ConversionPattern=%-d [%t] %-5p %c - %m%n # File name log4j.appender.RFA.DatePattern='.'yyyy-MM-dd log4j.appender.RFA.File=${user.home}/vvv.log 141 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM #log4j.appender.RFA.MaxFileSize=1KB # Truncate 'test' if it aleady exists. #log4j.appender.RFA.Append=true # Keep one backup file #log4j.appender.R.MaxBackupIndex=2 300. Log4j.xml <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration> <appender name="Stdout" class="org.apache.log4j.ConsoleAppender"> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%-d [%t] %-5p %c %m%n"/> </layout> </appender> <appender name="FA" class="org.apache.log4j.DailyRollingFileAppender"> <param name="DatePattern" value="'.'yyyy-MM-dd-HH-mm"/> <param name="File" value="c:/warning.log" /> 142 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%-d [%t] %-5p %c %m%n"/> </layout> </appender> <root> <priority value="debug"/> <appender-ref ref="FA"/> <appender-ref ref="Stdout"/> </root> </log4j:configuration> 301. build.xml <?xml version='1.0'?> <project name="JDK1.4.0_03 compilation " default="compile" basedir="."> 143 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM <!-- set global properties for this build --> <description> simple example build file </description> <property name="version" value="1.8"/> <property name="src" value="src"/> <property name="classes" value="C:\Tomcat 4.1\webapps\PF18\WEBINF\classes"/> <property name="include" value="C:\Tomcat 4.1\webapps\PF18\WEB-INF\lib"/> <property name="tomcatcommon" value="C:\Tomcat 4.1\common\lib"/> <target name="compile"> <echo message="Deleting existing class files " /> <delete dir="${classes}\com"/> <echo message="Compiling Java Files " /> <!-- run javac to compile the source files --> <javac srcdir="${src}" destdir="${classes}"> <classpath> <!-- include all jar files --> <fileset dir="${include}"> 144 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM <include name="**/*.jar"/> </fileset> <fileset dir="${tomcatcommon}"> <include name="**/*.jar"/> </fileset> </classpath> </javac> </target> </project> 2.Another Build.xml (Eg) – Creating Java Doc <?xml version='1.0'?> <project name="PF 18 (Only Dev Env) Build" default="docs" basedir="."> <!-- set global properties for this build --> <description> simple example build file </description> <property name="version" value="1.8"/> <property name="src" value="src"/> <property name="classes" value="C:\Tomcat 4.1\webapps\PF18\WEBINF\classes"/> <property name="docs" value="C:\Tomcat 4.1\webapps\PF18\WEB-INF\docs"/> <property name="include" value="C:\Tomcat 4.1\webapps\PF18\WEB-INF\lib"/> <target name="init" > <!-- Create the directory for the java docs --> <mkdir dir="${docs}" /> </target> 145 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM <target name="compile" depends="init"> <echo message="Deleting existing class files " /> <delete dir="${classes}\com"/> <echo message="Deleting Java Doc files " /> <delete dir="${docs}"/> <!-- run javac to compile the source files --> <javac srcdir="${src}" destdir="${classes}"> <classpath> <!-- include all jar files --> <fileset dir="${include}"> <include name="**/*.jar"/> </fileset> </classpath> </javac> </target> <target name="docs" depends="compile,init"> <!-- create javadocs --> <echo message="Building a java doc for People Finder " /> <javadoc packagenames="* " sourcepath="${src}" defaultexcludes="yes" destdir="${docs}" author="true" version="true" use="true" windowtitle="People Finder API Documentation Version: ${version}"> </javadoc> </target> </project> 3. Another Build.xml (Eg) – Creating Jar file <?xml version='1.0'?> <project name="Ant for Hello World Greetings!!!" default="clean" basedir="."> <!-- set global properties for this build --> <description> 146 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM simple example build file </description> <property name="version" value="8.3"/> <property name="src" value="src"/> <property name="classes" value="classes"/> <property name="lib" value="lib"/> <property name="jarname" value="helloworld.jar"/> <property name="backupjava" value="backupjava"/> <property name="docs" value="docs"/> <property name="include" value="c:\jarbank"/> <property name="runclass" value="com.cfdev.hello.HelloWorld"/> <target name="init" > <!-- Create the build directory structure used by compile --> <mkdir dir="${backupjava}" /> <mkdir dir="${classes}" /> <!-- Create the directory for the jar file --> <mkdir dir="${lib}" /> <!-- Create the directory for the java docs --> <mkdir dir="${docs}" /> </target> <target name="compile" depends="init"> <!-- copy all .java files from ${src} to ${build} --> <copy todir="${backupjava}/"> <fileset dir="${src}" includes="**/*.java"/> <filterset> <filter token="version" value="${version}"/> </filterset> </copy> <!-- run javac to compile the source files --> <javac srcdir="${src}" destdir="${classes}"> <classpath> <!-- use the value of the ${classpath} property in the classpath --> <!-- include all jar files --> <fileset dir="${include}"> <include name="**/*.jar"/> 147 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM </fileset> </classpath> </javac> </target> <target name="jar" depends="compile"> <!-- make a jar file --> <jar jarfile="${lib}/${jarname}" basedir="${classes}/"/> </target> <target name="docs" depends="compile"> <!-- create javadocs --> <javadoc packagenames="com.cfdev.hello.*" sourcepath="${src}" defaultexcludes="yes" destdir="${docs}" author="true" version="true" use="true" windowtitle="Hello World API Documentation Version: ${version}"> </javadoc> </target> <target name="run" depends="jar,docs"> <!-- run the class --> <java classname="${runclass}"> <!-- add a command line arg: <arg value="-h"/> --> <classpath> <!-- use the value of the ${classpath} property in the classpath --> <!-- include all jar files --> <!-- use the value of the ${classpath} property in the classpath --> <pathelement path="${classes}"/> </classpath> </java> </target> <target name="clean" depends="run"> <echo message="hi am in clean" /> <delete dir="${backupjava}"/> </target> 148 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM </project> 3. Another Build.xml (Eg) – Running Java Prog <?xml version='1.0'?> <project name="XML WEBLOGS ANT" default="run" basedir="."> <!-- set global properties for this build --> <description> simple example build file </description> <property name="version" value="8.3"/> <property name="src" value="src2"/> <property name="classes" value="classes"/> <!-- <property name="classpath" value="classes"/> --> <property name="include" value="C:\Documents and Settings\include"/> <property name="runclass" value="Weblogs"/> <target name="init" > <!-- Create the build directory structure used by compile --> <mkdir dir="${classes}" /> <!-- Create the directory for the jar file --> <!-- Create the directory for the java docs --> </target> <target name="compile" depends="init"> <!-- copy all .java files from ${src} to ${build} --> <!-- run javac to compile the source files --> <javac srcdir="${src}" destdir="${classes}"> <classpath> <!-- use the value of the ${classpath} property in the classpath --> <!-- include all jar files --> <fileset dir="${include}"> 149 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM <include name="**/*.jar"/> </fileset> </classpath> </javac> </target> <target name="run" depends="compile"> <!-- run the class --> <java classname="${runclass}"> <!-- add a command line arg: <arg value="-h"/> --> <classpath> <!-- use the value of the ${classpath} property in the classpath --> <!-- include all jar files --> <!-- use the value of the ${classpath} property in the classpath --> <pathelement path="${classes}"/> <fileset dir="${include}"> <include name="**/*.jar"/> </fileset> </classpath> </java> </target> </project> 4. Another Build.xml (Eg) – Running Java Prog with EAR,WAR,JAR creation and argument passing <?xml version='1.0'?> <project name="XML Node Reporter Build" default="run" basedir="."> <!-- set global properties for this build --> <description> simple example build file </description> 150 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM <property name="version" value="1.8"/> <property name="src" value="src"/> <property name="classes" value="C:\TryXMLProClasses"/> <property name="basedir" value="C:\Final"/> <property name="runclass" value="NodeReporter"/> <property name="mylog" value="c:\mylog1.xml"/> <property name="appname" value="NodeReporterFinal"/> <property name="war" value="${appname}.war"/> <property name="jar" value="${appname}.jar"/> <property name="ear" value="${appname}.ear"/> <target name="compile" > <mkdir dir="C:\FinalDelv"/> <echo message="Compiling java file " /> <!-- run javac to compile the source files --> <javac srcdir="${src}" destdir="${classes}"> <classpath> <!-- include all jar files --> <fileset dir="c:\jarbank"> <include name="**/*.jar"/> </fileset> </classpath> </javac> </target> <target name="war" depends="compile"> <echo message="Running war file " /> <war warfile="${war}" webxml="web.xml"> <classes dir="${classes}"> <include name="NodeReporter.class" /> </classes> </war> </target> <target name="jar" depends="compile"> <echo message="Running jar file " /> <jar jarfile="${jar}"> 151 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM <fileset dir="${classes}"> <include name="NodeReporter.class" /> </fileset> </jar> </target> <target name="ear" depends="war, jar"> <echo message="Running war file " /> <ear earfile="${ear}" appxml="web.xml"> <fileset dir="${basedir}" includes="${jar}, ${war}"/> </ear> </target> <target name="build-all" depends="ear"> <echo message="Running ear file " /> <copy file="${ear}" todir="C:\FinalDelv"/> </target> <target name="run" depends="compile, build-all" > <echo message="Running java file " /> <!-- run javac to compile the source files --> <java classname="${runclass}"> <arg file="c:\mylog1.xml" /> <classpath> <pathelement path="${classes}"/> <fileset dir="c:\jarbank"> <include name="**/*.jar"/> </fileset> </classpath> </java> </target> </project> 5. Another Build.xml (Eg) – Running Java Prog with EAR,WAR,JAR creation and argument passing // Copyright © 2002 by Apple Computer, Inc., All Rights Reserved. 152 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM // // You may incorporate this Apple sample code into your own code // without restriction. This Apple sample code has been provided "AS IS" // and the responsibility for its operation is yours. You may redistribute // this code, but you are not permitted to redistribute it as // "Apple sample code" after having made changes. shell> cat build.xml <project name="hello world" default="build-all" basedir="."> <property name="appname" value="HelloWorld"/> <!-- change this to your local jboss installation, if different --> <property name="dist.root" value="/usr/local/jboss/jboss-3.0.2/"/> <property name="jboss.dist" value="${dist.root}/server/default"/> <property name="jboss.deploy.dir" value="${jboss.dist}/deploy"/> <!-- change this if you are not using jetty --> <property name="servlet.jar" value="${dist.root}/jetty/lib/javax.servlet.jar"/> <property name="src.dir" value="${basedir}/src"/> <property name="src.docroot" value="${src}/docroot"/> <property name="build.dir" value="${basedir}/build"/> <property name="build.classes.dir" value="${build.dir}/classes"/> <!-- the build path --> <path id="build.path"> <pathelement location="${jboss.dist}/client/jboss-j2ee.jar"/> <pathelement location="${servlet.jar}"/> <pathelement location="${build.classes.dir}"/> </path> <!-- war, jar, ear files --> <property name="war" value="${appname}.war"/> <property name="jar" value="${appname}.jar"/> <property name="ear" value="${appname}.ear"/> <target name="war" depends="compile"> <war warfile="${war}" webxml="web.xml"> <classes dir="${build.classes.dir}"> <include name="${appname}Servlet.class" /> 153 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM </classes> </war> </target> <target name="jar" depends="compile"> <jar jarfile="${jar}"> <fileset dir="${build.classes.dir}"> <include name="${appname}.class" /> <include name="${appname}Home.class" /> <include name="${appname}EJB.class" /> </fileset> <metainf dir="${basedir}" includes="jboss.xml,ejb-jar.xml"/> </jar> </target> <target name="ear" depends="war, jar"> <ear earfile="${appname}.ear" appxml="application.xml"> <fileset dir="${basedir}" includes="${jar}, ${war}"/> </ear> </target> <!-- compilation options --> <target name="compile"> <mkdir dir="${build.classes.dir}"/> <javac srcdir="${src.dir}" destdir="${build.classes.dir}" debug="on" deprecation="on" classpathref="build.path" optimize="off" includes="*" /> </target> <!-- build all, and copy to the jboss/deploy directory --> <target name="build-all" depends="ear"> <copy file="${ear}" todir="${jboss.deploy.dir}"/> </target> </project> 302. Object Serialization 154 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM Only for Object specific not for class specific. Any non-transient variable and non-static members Members means Variable and methods Two Interfaces used for Object Serialization ObjectInput extends DataInput ObjectOutput extends DataOutput Implementing Classes ObjectInputStream ObjectOutputStream Methods used are WriteObject and ReadObject 304. JVM is 32 bit address Stack – store paramenters of methods Heap – :Live java objects Method area – bytecode Garbage collected heap – greating new objects and garbage collected 305. Reference Variable or Reference Object or Object Reference ClassA classObj ; //classObj is object reference 306. Static, final and private methods and constructor () can’t be overridden 155 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM 307. Synchronization Method Synchronization (Class-specific if static method) Block Level Synchronization Kat era SYSTEMS, BANGALORE ( 2 Dec 2004) – SELECTED 1. What is checked and unchecked Exceptions? 2. How classes are not overlapping in the Application instances 3. EJB2.0 Exceptions 4. Class Loader 5. JVM 6. FINALLY AND FINALIZE 7. INTERFACE AND ABSTRACT CLASS 8. session failover 9. Stateful Vs HTTP Session 156 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM WIPRO TECHNOLOGIES, BANGALORE ( 11 Dec 2004) - SELECTED 1. What is component Diagram 2. How localization implemented in Struts 3. Session Replication and Load Balancing (What is clustering) 4. SAX, DOM, JDOM 5. How will you create clustering in WEBLOGIC 6. When will session replicate in CLUSTERING 7. Logic Diagram 8. Sequential Diagram V Collaborations Diagram (now Communication Diagram) Both are Use Case Specific. Represents in different view SD – illustrates the behaviour of the class objects CD – object interaction and relationship 9. What is Activity Diagram ( Object Sepecific- like DFD but you have Synchronization) 10. What is State Diagram 11. What are the major challenges in Software Development Cycle 12. What is Architechtural Diagram ? Security , Transaction Management, Component Based 13. When Stateful , Stateless, Entity Beans used in Project 14. How will you setup client interaction ( Client CON CALL) 15. JSF – Java Server Faces 16. What is Business Deligate Pattern 17. What is Session Façade 157 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM 18. CTS, Chennai ( 14 Dec 2004) – 1. BMP v CMP 2. Vector or ArrayList 3. How will you deploy ejb files in WEBLOGIC 8.1 4. ejbActivate Vs ejbLoad 5. ejbPassivate Vs ejbStore 6. Triggers 7. PrepareStatement, Statement, CallableStatement 8. Database Design 9. Design Pattern 10. ResultSet 11. DriverManager v Datasource 12. Type of JDBC Drivers 13. JDOM v SAX v DOM 14. ejbLoad and ejbStore is not there in Stateful or Stateless, Why? 15. Which are Managing JDBC drivers? 16. What is ResultSet? 17. Bind Variables in JDBC Staements 18. Communication Diagram V Sequential Diagram 19. Static Initializers 20. String Buffer V String (String buffer is a final class) 158 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM 303. JAVA API StringBuffer is a * Final Class * Thread Safe * Mutable * ensureCapacity – or – double the size Strings are * Final Class * is constant, can’t be changed * is not a wrapper class * String concatenation “+” Operator String and String Buffer are directly extends Object Class 303. Down Casting and UpCasting Upcasting String str=”raja”; Object a = str; Downcasting Str = a; 159 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM Example is public class UpDown { public UpDown() { System.out.println("Default Constructor - CLASS UpDown is invoked "); } public static void main(String ss[]) { System.out.println(" Value of a is "); String str = "raja"; System.out.println("str is " + str); Object obj = str; StringBuffer sb = new StringBuffer(obj.toString()); sb.append("seth"); obj = sb; 160 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM System.out.println("obj is " + obj); sb = (StringBuffer)obj; System.out.println("sb is " + sb); } } 304. DataSource V DataManager Interface - Javax.sql.DataSource (involves in ConnectionPooling, Distributed Transaction) javax.sql.DataSource datasource= (javax.sql.DataSource) initContext.lookup ("MYDSJNDI"); connect = datasource.getConnection(); An object that implements the DataSource interface will typically be registered with a naming service based on the JavaTM Naming and Directory (JNDI) API. 1. produces a standard Connection object 2. Produces a Connection object that will automatically participate in connection pooling. This implementation works with a middle-tier connection pooling manager. 3. produces a Connection object that may be used for distributed transactions and almost always participates in connection pooling. This implementation works 161 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM with a middle-tier transaction manager and almost always with a connection pooling manager. 4. With a basic implementation, the connection obtained through a DataSource object is identical to a connection obtained through the DriverManager facility. 5. DataSource object has properties that can be modified when necessary. For example, if the data source is moved to a different server, the property for the server can be changed. The benefit is that because the data source's properties can be changed, any code accessing that data source does not need to be change 6. It will look up for the binded object in the JNDI for getting data base connection. But Driver Manager will register the driver for getting the connection DRIVER MANAGER Java.sql.DriverManager (interface) DriverManager.registerDriver(new oracle.jdbc.OracleDriver()) When the method getConnection is called, the DriverManager will attempt to locate a suitable driver from amongst those loaded at initialization and those loaded explicitly using the same classloader as the current applet or application. Additional Points Class.forName("my.sql.Driver"); // another way of loading driver – EXPLICIT LOADING To work with Datasource , we need weblogic.jar if WEBLOGIC 8.1 (Server Specific) To work with DriverManager, we need classes12.jar or ojdbc14.jar (Database Specific) 305. Drivers available in Oracle 9i These are the driver versions in the 9.0.1 release: 162 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM - JDBC OCI Driver 9.0.1 Client-side JDBC driver for use on a machine where OCI 9.0.1 is installed. - JDBC Thin Driver 9.0.1 100% Java client-side JDBC driver for use in Java applets and applications. - JDBC Thin Server-side Driver 9.0.1 JDBC driver for use by Java Stored Procedures or by Java CORBA objects running in Oracle 9.0.1. This driver is typically used in a middle tier server. - JDBC Server-side Internal Driver 9.0.1 Server-side JDBC driver for use by Java Stored procedures or by Java CORBA objects running in Oracle 9.0.1. This driver used to be called the "JDBC Kprb Driver". For complete documentation, please refer to "JDBC Developer's Guide and Reference". 163 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM 306. Type of Drivers available in JDBC 2.0 Type 1: JDBC – ODBC Bridge Driver – This Driver Connects Java Program to Microsoft ODBC data source. Development Purpose. Type 2: Native API – Partly Java Driver This Driver enables JDBC to use Database Specific API to access database. Type 3: JDBC – NET – Pure Java Driver This Driver translates JDBC request to Network Protocol and Server translates the database request into a database specific protocol Type 4: Native Protocol pure Java Driver Java Program can connect directly to ta Database. Translates JDBC request to Database specific / Network Protocol. 307. LDAP Programming (Search, Update, Delete, Modify) import javax.naming.*; import javax.naming.directory.*; import java.util.Hashtable; import java.util.Enumeration; class DomainCon { 164 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM //user id credential private static final String userId = "uid=vishnu,cn=peoplefinder,ou=hp,dc=unicenter"; private static String userPwd= "vishnu"; //directory manager credential private static final String dmId = "cn=Directory Manager"; private static final String dmPwd = "password"; //administrator credential private static final String adminId = "admin,ou=administrators,ou=topologymanagement,o=netscaperoot"; private static final String adminPwd = "admin"; //destroy dn, create dn, search dn, modify dn private static final String destroy_DN = "uid=usa,cn=peoplefinder,ou=hp,dc=unicenter"; private static final String create_DN = "uid=sri1,cn=peoplefinder,ou=hp,dc=unicenter"; private static final String modify_DN = "uid=vishnu,cn=peoplefinder,ou=hp,dc=unicenter"; public static void main(String args[]) 165 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM { DomainCon dc = new DomainCon(); /* Connection from LDAP */ //System.out.println(" LDAP Connection Status is " + dc.getLDAPConnection()); /* Destory DN or Subcontext */ //System.out.println(" destorySubContext status is " + dc.getDestroySubcontext()); /* Create Subcontext */ //System.out.println(" createSubContext status is " + dc.getCreateSubcontext()); /* Modify Subcontext */ //System.out.println(" modify SubContext status is " + dc.getModifySubcontext()); /* Search Subcontext */ dc.getSearchSubcontext(); } private void getSearchSubcontext() { try{ DirContext dc = (InitialDirContext)getInitialDirContext(); 166 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM //Attributes attrs = new BasicAttributes(); //Attribute sn = new BasicAttribute("sn","vas"); //attrs.put(sn); String str1[] = {"uid","sn","cn","telephoneNumber","mail","fax","userpassword","givenna me"}; SearchControls scont = new SearchControls(); scont.setSearchScope(SearchControls.SUBTREE_SCOPE); scont.setReturningAttributes(str1); NamingEnumeration na = dc.search("dc=unicenter","(uid=venkat)",scont); while(na.hasMore()){ // System.out.println("tt"); SearchResult sr = (SearchResult)na.next(); if(sr.getName().indexOf("uid=") != -1){ String uid = sr.getName().substring(sr.getName().indexOf("uid=")+4,sr.getName().index Of(",")); System.out.println(" U I D is " + uid); String cnn = sr.getName().substring(sr.getName().indexOf("cn=")+3,sr.getName().lastInd exOf(",")); System.out.println(" C N N is " + cnn); 167 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM String ouu = sr.getName().substring(sr.getName().lastIndexOf("=")+1); System.out.println(" O U U is " + ouu); } System.out.println(" DN is " + sr.getName()); Attributes attrsFetched = sr.getAttributes(); if(attrsFetched == null){ System.out.println(" No attributes"); continue; } NamingEnumeration na1 = attrsFetched.getAll(); while(na1.hasMore()){ Attribute attr = (Attribute)na1.next(); String id = attr.getID(); //System.out.println("id " + id); Enumeration na2 = attr.getAll(); while(na2.hasMoreElements()){ System.out.println( "Attribute {{ " + id + " }} value is " + na2.nextElement()); } 168 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM } } na.close(); }catch(Exception e){ e.printStackTrace(); } } private boolean getModifySubcontext() { boolean modifySubcontextFlag = false; try{ //Modify attribute using BasicAttributes Class DirContext dc = (InitialDirContext)getInitialDirContext(); Attributes attrs = new BasicAttributes(); Attribute mail = new BasicAttribute("mail","gdddg@gg.com",true); attrs.put(mail); dc.modifyAttributes(modify_DN,2,attrs); //Modify attribute using ModificationItem Class //Very important - Modification array should be equal to no. of attribute 169 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM // 1 - add new attribute value //2 - modify existing attribute value //3 - delete existing attribute value // we can't create / delete attribute object - it is part of LDAP implementation /* BasicAttribute givenName = new BasicAttribute("mail","fff@hp.com"); ModificationItem modifyItem[] = new ModificationItem[1]; modifyItem[0] = new ModificationItem(2,givenName); //System.out.println( "modifyItems.length " + modifyItem[0].getAttribute()); dc.modifyAttributes(modify_DN,modifyItem); */ modifySubcontextFlag = true; dc.close(); //idc.close(); }catch(Exception e){ modifySubcontextFlag = false; e.printStackTrace(); } return modifySubcontextFlag; } private boolean getCreateSubcontext() { 170 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM boolean createSubcontextStatusFlag = false; try{ DirContext dc=(InitialDirContext)getInitialDirContext(); Attributes attrs = new BasicAttributes(); Attribute objectClassAttr = new BasicAttribute("objectClass",true); objectClassAttr.add("top"); objectClassAttr.add("person"); objectClassAttr.add("organizationalPerson"); objectClassAttr.add("inetorgperson"); // we can create new object class objectClassAttr.add("hpproject"); Attribute sn = new BasicAttribute("sn","venkatesh",true); Attribute cn = new BasicAttribute("cn","devi venaktesh",true); Attribute fax = new BasicAttribute("facsimileTelephoneNumber","123",true); Attribute phone = new BasicAttribute("telephoneNumber","3333",true); Attribute givenName = new BasicAttribute("givenName","devi",true); Attribute userPassword = new BasicAttribute("userPassword","devi",true); Attribute uid = new BasicAttribute("uid","devi",true); 171 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM Attribute mail = new BasicAttribute("mail","devi",true); //update later Attribute creatorsName = new BasicAttribute("creatorsName","devi",true); Attribute title = new BasicAttribute("title","PF1.8 Enhancement",true); // we can't create / delete attribute object - it is rule of LDAP implementation //Attribute title2 = new BasicAttribute("title2","PF1.8 Enhancement",true); attrs.put(sn); attrs.put(cn); attrs.put(fax); attrs.put(phone); attrs.put(givenName); attrs.put(userPassword); attrs.put(uid); attrs.put(mail); attrs.put(creatorsName); attrs.put(title); //attrs.put(title2); attrs.put(objectClassAttr); 172 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM /*attrs.put("givenName","kriti"); attrs.put("sn","kriti"); attrs.put("cn","kriti"); attrs.put("uid","kriti"); attrs.put("userpassword","kriti"); attrs.put("mail","kriti"); //attrs.put("phonenumber","kriti"); */ dc.createSubcontext(create_DN,attrs); dc.close(); createSubcontextStatusFlag = true; }catch(Exception e){ createSubcontextStatusFlag = false; e.printStackTrace(); } return createSubcontextStatusFlag; } private boolean getDestroySubcontext(){ boolean destroySubcontextStatusFlag = false; try{ 173 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM InitialDirContext idc=(InitialDirContext)getInitialDirContext(); idc.destroySubcontext(destroy_DN); destroySubcontextStatusFlag = true; idc.close(); }catch(Exception e){ destroySubcontextStatusFlag = false; e.printStackTrace(); } return destroySubcontextStatusFlag; } private boolean getLDAPConnection(){ boolean LDAPConnectionStatusFlag = false; try{ InitialDirContext idc=(InitialDirContext)getInitialDirContext(); DirContext dc = (DirContext)idc.lookup(userId); LDAPConnectionStatusFlag = true; idc.close(); dc.close(); }catch(Exception e){ LDAPConnectionStatusFlag = false; e.printStackTrace(); 174 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM } return LDAPConnectionStatusFlag; } private InitialDirContext getInitialDirContext(){ Hashtable env= new Hashtable(11); InitialDirContext ctx = null; try { env.put(Context.SECURITY_AUTHENTICATION,"none"); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL,"ldap://venkatesh.unicenter:57176"); env.put(Context.SECURITY_PRINCIPAL,adminId);//User env.put(Context.SECURITY_CREDENTIALS,adminPwd);//Password //env.put("java.naming.ldap.version", "2"); //env.put("com.sun.jndi.ldap.connect.pool", "true"); ctx = new InitialDirContext(env); } catch(Exception e) { System.err.println("Problem getting attribute: " + e); } 175 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM return ctx; } } 308. SASL and SSL 309. java.util.Collection 310. java.sql.Statement, PreparedStatement, CallableStatement Statement (Super Interface for all Statement ) Statement object used for executing a static SQL statement and returning the results it produces. By Default, only one ResultSet object per Statement object can be open at the same time. All execution methods in the Statement interface implicitly close a statment's current ResultSet object if an open one exists. Statement st = connection.createsStatement(); St.executeQuery(“Select * from tablename”) PreparedStatement (BATCH UP the SQL STATEMENTS ) 176 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM An object that represents a precompiled SQL statement. A SQL statement is precompiled and stored in a PreparedStatement object. This object can then be used to efficiently execute this statement multiple times. It will bind Variables as in Paramenter PreparedStatement pstmt = con.prepareStatement("UPDATE EMPLOYEES SET SALARY = ? WHERE ID = ?"); pstmt.setBigDecimal(1, 153833.00) pstmt.setInt(2, 110592) CallableStatement The interface used to execute SQL stored procedures. It will bind Variables as in Paramenter It will return one or more ResultSet object CallableStatement cs = connect.prepareCall("{call vbankpro(?,?)}"); cs.setString(1,"1"); cs.registerOutParameter(2,Types.FLOAT); cs.executeUpdate(); System.out.println("" + cs.getDouble(2)); Additional Points 177 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM Java.sql.Result Set A ResultSet object maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the first row. The next method moves the cursor to the next row, and because it returns false when there are no more rows in the ResultSet object, it can be used in a while loop to iterate through the result set. A default ResultSet object is not updatable and has a cursor that moves forward only. Thus, you can iterate through it only once and only from the first row to the last row. It is possible to produce ResultSet objects that are scrollable and/or updatable Statement stmt = con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = stmt.executeQuery("SELECT a, b FROM TABLE2"); // rs will be scrollable, will not show changes made by others, // and will be updatable rs.absolute(5); // moves the cursor to the fifth row of rs rs.updateString("NAME", "AINSWORTH"); // updates the // NAME column of row 5 to be AINSWORTH rs.updateRow(); // updates the row in the data source rs.moveToInsertRow(); // moves cursor to the insert row rs.updateString(1, "AINSWORTH"); // updates the // first column of the insert row to be AINSWORTH rs.updateInt(2,35); // updates the second column to be 35 rs.updateBoolean(3, true); // updates the third column to true rs.insertRow(); rs.moveToCurrentRow(); A ResultSet object is automatically closed when the Statement object that generated it is closed, re-executed, or used to retrieve the next result from a sequence of multiple results. The number, types and properties of a ResultSet object's columns are provided by the ResulSetMetaData object returned by the ResultSet.getMetaData method. 311. DataSource Example 178 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM import javax.naming.Context; import javax.naming.InitialContext; import javax.sql.DataSource; import javax.rmi.PortableRemoteObject; import java.util.Hashtable; import java.sql.Statement; import java.sql.ResultSet; import java.sql.Connection; public class TestDataSource { public static void main(String ss[]){ InitialContext initContext = null; Hashtable hashtablex = null; Statement stmt = null; ResultSet rset = null; Connection connect = null; try{ hashtablex = new Hashtable(); 179 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM hashtablex.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WL InitialContextFactory"); hashtablex.put(Context.PROVIDER_URL,"t3://localhost:7011"); initContext = new InitialContext(hashtablex); javax.sql.DataSource datasource= (javax.sql.DataSource) initContext.lookup ("MYDSJNDI"); connect = datasource.getConnection(); stmt = connect.createStatement(); stmt.executeQuery("SELECT vaccountId,vaccountBalance,vaccountType,vaccountName from vbank"); rset = stmt.getResultSet(); while(rset.next()){ System.out.println("- - - - - - - - - - - - - - "); System.out.println("Id is <<"+rset.getString("vaccountId")+">>"); System.out.println("Balance is <<"+rset.getDouble("vaccountBalance")+">>"); System.out.println("vaccountType is <<"+rset.getString("vaccountType")+">>"); System.out.println("Name is <<"+rset.getString("vaccountName")+">>"); System.out.println("- - - - - - - - - - - - - - "); } 180 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM }catch(Exception excep){ try{ rset.close(); stmt.close(); connect.close(); initContext.close(); }catch(Exception excep1){ excep1.printStackTrace(); } excep.printStackTrace(); } } }/* end of client */ 312. Driver Manager Example public class TestDriverManager { public static void main(String ss[]){ InitialContext initContext = null; Hashtable hashtablex = null; Statement stmt = null; ResultSet rset = null; 181 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM Connection connect = null; try{ // Class.forName("oracle.jdbc.driver.OracleDriver"); DriverManager.registerDriver(new oracle.jdbc.OracleDriver()); connect = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:GDATA","scott", "tiger"); stmt = connect.createStatement(); stmt.executeQuery("SELECT vaccountId,vaccountBalance,vaccountType,vaccountName from vbank"); rset = stmt.getResultSet(); while(rset.next()){ System.out.println("- - - - - - - - - - - - - - "); System.out.println("Id is <<"+rset.getString("vaccountId")+">>"); System.out.println("Balance is <<"+rset.getDouble("vaccountBalance")+">>"); System.out.println("vaccountType is <<"+rset.getString("vaccountType")+">>"); 182 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM System.out.println("Name is <<"+rset.getString("vaccountName")+">>"); System.out.println("- - - - - - - - - - - - - - "); } }catch(Exception excep){ try{ rset.close(); stmt.close(); connect.close(); initContext.close(); }catch(Exception excep1){ excep1.printStackTrace(); } excep.printStackTrace(); } } } 313. MQ Series with JAVA Well, IBM provides two types of Java Bindings 183 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM 1. MQI Java Bindings 2. JMS Implementation Down load the MQI for Java. MQSeries SupportPac MA88: MQSeries classes for Java and MQSeries classes for Java Messaging http://www14.software.ibm.com/webapp/download/product.jsp?cat=ts&s=s&id=T DUN-49EVER&pf=&presb=&type=s&postsb= Message Driven Bean with MQSeries JMS impl or Session beans can invoke helper classes which actually connect to MQSeries and do a put and get message (two famous operation on MOM)." http://www.capitalware.biz/sample_mqseries.html#javacode http://www14.software.ibm.com/webapp/download/product.jsp?s=p&id=TD UN49EVER&type=b&presb=n&postsb=n&cat=&fam=&rs=&S_TACT=&S_CMP= &q=text+to+search+for&k=any&pf=&dt=TRIAL&v=5.3&x=27&y=9 184 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM http://www.objectinnovations.com/CourseOutlines/516.html 314. JMS Description Messaging is a powerful programming paradigm that makes it easier to decouple different parts of an enterprise application. Messaging clients work by sending messages to a message server, which is responsible for delivering the messages to their destination. Message delivery is asynchronous, meaning that the client can continue working without waiting for the message to be delivered. The contents of the message can be anything from a simple text string to a serialized Java object or an XML document. Java Message Service (JMS) is a standard Java Application Programming Interface (API) from Sun Microsystems that provides a common interface for Java programmers to invoke any messaging services such as WebLogic's JMS Service, IBM's MQSeries, Progress Software's SonicMQ, etc. JMS is part of Java 2 Enterprise Edition (J2EE). Objectives This course teaches students the why, what, and how of the messaging paradigm and JMS. On completion, attendees will be able to: Write both message consumers and providers using WebLogic's JMS Use transactions with JMS Set up and deploy JMS applications in WebLogic Server 8.1 Write message-driven EJB and deploy it in WebLogic Server 8.1 Define and use JMS connection pool in WebLogic Server 8.1 Course Outline Understanding Messaging Paradigm and JMS 185 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM JMS Message Constituents Publish-and-Subscribe Messaging Model Point-to-Point Messaging Model Guaranteed Messaging, Transactions, Acknowledgments, and Failures JMS and EJB 2.0 Deployment Considerations Using WebLogic JMS JMS in a Clustered Environment Overview of Other Popular Messaging Products 315. Duration: 3 days Audience This course is designed for architects and developers who already have experience in Java development. Prerequisites Java Architects Consultants Developers Description Messaging is a powerful programming paradigm that makes it easier to decouple different parts of an enterprise application. Messaging clients work by sending messages to a message server, which is responsible for delivering the messages to their destination. Message delivery is asynchronous, meaning that the client can continue working without waiting for the message to be delivered. The contents of the message can be anything from a simple text string to a serialized Java object or an XML document. Java Message Service (JMS) is a standard Java Application Programming Interface (API) from Sun Microsystems that provides a common interface for Java programmers to invoke any messaging services such as WebLogic's JMS Service, IBM's WebSphere MQ, Progress Software's SonicMQ, etc. JMS is part of Java 2 Enterprise Edition (J2EE). 186 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM Objectives This course aims to teach students the why, what, and how of the messaging paradigm and JMS. On completion, attendees will be able to: Write both message consumers and providers using JMS and IBM WebSphere MQ Use transactions with JMS Set up and deploy JMS applications in IBM WebSphere MQ Course Outline Overview of WebSphere MQ WebSphere MQ Architecture Messages in WebSphere MQ Objects Queues MQI Introduction to Java Messaging Services (JMS) WebSphere MQ Intercommunication WebSphere MQ Security Enterprise Messaging Systems Message-Oriented Middleware (MOM) Overview of JMS Messaging Models Sending Messages to Remote Queue Manager Distributed Queuing Components Message Channels Transmission Queues Cryptography, Encryption, Decryption, etc. Ciphers Message Digest Digital Signatures Security Goals Authorization JMS Messages Message Header Fields Message Properties Message Selection Message Body WebSphere MQ Classes for Java MQ Java and MQI MQ Java Classes MQ Java Interfaces JMS Common Facilities WebSphere MQ Connector Destination ConnectionFactory Connection Session MessageConsumer Connector Common Connector Framework (CCF) Architecture 187 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM MessageProducer JMSException Publish/Subscribe Model Connecting to Topics Create Publisher and Subscriber Publish Messages Temporary Topic Durable Subscriber Point-to-Point Model (PTP) JMS Common Facilities in PTP Model Queue Browser Complete PTP Example CCF Interfaces WebSphere MQ Connector Classes (MQConnectionSpec, MQCommuncation, MQInteractionSpec Rollback and Commit Advanced Topics in JMS Guaranteed Messaging Message Acknowledgment Transacted Messaging JMS and J2EE Overview of J2EE Architecture JMS Usage in J2EE JMS and EJB 2.0's Message-driven Bean 317. 318. http://www.ss64.com/ora/database_c.html 319. Simple Java to PDF conversion using itext-1.1.jar file 188 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM package com.lowagie.examples.general; import java.io.FileOutputStream; import java.io.IOException; import com.lowagie.text.*; import com.lowagie.text.pdf.PdfWriter; /** * Generates a simple 'Hello World' PDF file. * * @author blowagie */ public class HelloWorld { /** * Generates a PDF file with the text 'Hello World' * * @param args no arguments needed here */ public static void main(String[] args) { 189 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM System.out.println("Hello World"); // step 1: creation of a document-object Document document = new Document(); try { // step 2: // we create a writer that listens to the document // and directs a PDF-stream to a file PdfWriter.getInstance(document, new FileOutputStream("HelloWorld.pdf")); // step 3: we open the document document.open(); // step 4: we add a paragraph to the document document.add(new Paragraph("Hello World")); } catch (DocumentException de) { System.err.println(de.getMessage()); } catch (IOException ioe) { System.err.println(ioe.getMessage()); } // step 5: we close the document 190 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM document.close(); } } 320. oracle learning PL Tutorial http://www-db.stanford.edu/~ullman/fcdb/oracle/or-plsql.html#procedures Oracle/SQL Tutorial http://www.db.cs.ucdavis.edu/teaching/sqltutorial/ http://oldweb.uwp.edu/academic/mis/baldwin/sqlplus.htm http://www.oraclecoach.com/oracle9i.htm select * from tab; select * from user_tables; select * from user_objects; select * from dict; select * from USER_OBJECTS WHERE object_type like 'P%' 191 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM select object_name,object_type from user_objects where object_name like 'V%'; delete from user_objects where object_name like 'VB%' AND OBJECT_TYPE = 'PROCEDURE' sho err; show error procedure procedurename 321. URL and URLConnection import java.net.URL; import java.net.MalformedURLException; import java.net.URLConnection; import java.io.InputStream; import java.io.FileInputStream; import java.io.InputStreamReader; 192 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM import java.io.File; /** * Created by IntelliJ IDEA. * User: aaa * Date: Nov 19, 2004 * Time: 11:26:50 PM * To change this template use File | Settings | File Templates. */ public class URLConnect { public static void main(String ss[]) { try{ // URL urlpath = new URL("http://venkatsyntel.tripod.com/mycv/VenkateshRajendranCV.com"); URL urlpath = new URL("http://localhost:7011/teststruts/Success.html"); URLConnection urlConnect = urlpath.openConnection(); InputStream inputstream = null; inputstream = urlConnect.getInputStream(); InputStreamReader inputStreamReader= new InputStreamReader(inputstream); int i = inputStreamReader.read(); while( i != -1){ System.out.println("char is " + (char) i); i = inputStreamReader.read(); } 193 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM }catch(MalformedURLException maURLExcep){ maURLExcep.printStackTrace(); }catch(Exception excep){ excep.printStackTrace(); } } } 322. STATIC VARIABLE and FINAL VARIABLE in side LOCAL method public class TestStat { static int a ; final int aaaa ; //Compile time error – Final variable not initialized static String b; static char c; static int aa[] = new int[]{1,2}; public static void TestStat() { final int aaaa ; //Run time error 194 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM Static int kk; // Not possible , but static variable will be used inside static //method or non static method int a; } public static void main(String ss[]) { TestStat t = new TestStat(); t.TestStat(); } } 323. Loading the Property file using java.util.Properties class import java.util.Properties; import java.io.*; public class PropertiesRead { public static void main(String ss[]) { Properties properties = new Properties(); InputStream instream; try{ 195 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM instream = new FileInputStream(new File("C:/teststruts/WEBINF/classes/com/Test.properties")); properties.load(instream); }catch(FileNotFoundException fnfExcep){ fnfExcep.printStackTrace(); }catch(IOException ioExcep){ ioExcep.printStackTrace(); } System.out.println(properties.getProperty("prompt.submit1")); } } 324. Using <a href=#> and <a name=#> <html> <head> <title> Concepts of A href</title> </head> <body> <p> <hr width="100%"> <a name="#index">Content </a> <p><a href="#first">CoreGroupTechnology,Trichy</a></p> 196 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM <p><a href="#second">Syntel India Ltd, Chennai</a></p> <p><a href="#third">Hewlett Packard India Ltd, Bangalore</a></p> <p><a href="#fourth">WiproTechnolgy,Chennai</a></p> <p><a href="#fifth">Projects</a></p> </p> <p> <hr width="100%"> <a name="#first"></a> <b><font famggkce="Arial">1. Core Group Technology, Trichy</font></b> <p> <blockquote> My first Company. Worked from Nov ,1998 as Programmer in J2EE Technolgy. </blockquote> </p> <hr width="100%"> <a name="#second"></a> <b><font face="Arial">2. Syntel India Ltd, Chennai</font></b> <p> <blockquote> My Second Company. Worked from Sep 2000 as Programmer Analyst in J2EE Technolgy. 197 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM </blockquote> </p> <hr width="100%"> <a name="#third"></a> <b><font face="Arial">3. Hewlett Packard India Ltd, Bangalore</font></b> <p> <blockquote> My Third Company. Worked from May 2004 as Senior Software Engineer in J2EE Technolgy. </blockquote> </p> <hr width="100%"> <a name="#fourth"></a> <b><font face="Arial">4. Wipro Technology, Chennai</font></b> <p> <blockquote> My Fourth Company. Working from Jan 2005 as Module Lead in J2EE Technolgy. </blockquote> </p> <hr width="100%"> 198 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM <a name="#fifth"></a> <b><font face="Arial">5. Projects</font></b> <p> <blockquote> <ol> <li> Gulf Based Company projects </li> <li> iPLANET based Internal Project </li> <li> GMAC Client projects ( Logistics & Insurance) </li> <li> HAP (Health Alliance Plan ) Client project (HealthCare) </li> <li> FedEx Client projects (Logistics) </li> <li> Unilever Client project (Portal) </li> 199 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM </ol> </blockquote> </p> <a href="#index">go top</a> </body> <script language="JavaScript"> document.writeln("<BR><I>This page last updated: " + document.lastModified + "</I>"); </script> </html> 325. Using Driver …connect DB import java.util.Hashtable; import java.util.Properties; 200 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM import java.sql.*; /** * Created by IntelliJ IDEA. * User: aaa * Date: Dec 17, 2004 * Time: 7:15:52 AM * To change this template use File | Settings | File Templates. */ public class TestDriverManager { public static void main(String ss[]){ InitialContext initContext = null; Hashtable hashtablex = null; Statement stmt = null; ResultSet rset = null; Connection connect = null; Properties probs = new Properties(); probs.put("user","scott"); probs.put("password","tiger"); probs.put("server","localhost:1521:GDATA"); try{ 201 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM // Driver driver = (Driver)Class.forName("oracle.jdbc.driver.OracleDriver").newInstance(); // connect = driver.connect("jdbc:oracle:thin:",probs); //below line - load the driver and register driver with Register Manager Class.forName("oracle.jdbc.driver.OracleDriver"); //below line - load the driver and register driver with Register Manager DriverManager.registerDriver(new oracle.jdbc.OracleDriver()); connect = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:GDATA","scott", "tiger"); stmt = connect.createStatement(); stmt.executeQuery("SELECT vaccountId,vaccountBalance,vaccountType,vaccountName from vbank"); rset = stmt.getResultSet(); while(rset.next()){ System.out.println("- - - - - - - - - - - - - - "); 202 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM System.out.println("Id is <<"+rset.getString("vaccountId")+">>"); System.out.println("Balance is <<"+rset.getDouble("vaccountBalance")+">>"); System.out.println("vaccountType is <<"+rset.getString("vaccountType")+">>"); System.out.println("Name is <<"+rset.getString("vaccountName")+">>"); System.out.println("- - - - - - - - - - - - - - "); } }catch(Exception excep){ try{ rset.close(); stmt.close(); connect.close(); initContext.close(); }catch(Exception excep1){ excep1.printStackTrace(); } excep.printStackTrace(); } } 203 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM } 326. public class TestStaticV { int a ; public void getMethod(){ a = -1; System.out.println("value of a 1 is "+ a); a = 1; get(); System.out.println("value of a 2 is "+ a); } public void get(){ a = 1000; System.out.println("value of a3 is "+ a); } public static void main(String arg[]){ //System.out.println(" hi "); TestStaticV v = new TestStaticV(); v.getMethod(); } } output value of a 1 is -1 value of a3 is 1000 value of a 2 is 1000 327. public class TestStaticV { int a ; 204 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM public void getMethod(){ a = -1; System.out.println("value of a 1 is "+ a); a = 1; get(); a = 33; System.out.println("value of a 2 is "+ a); } public void get(){ a = 1000; System.out.println("value of a3 is "+ a); } public static void main(String arg[]){ //System.out.println(" hi "); TestStaticV v = new TestStaticV(); v.getMethod(); } } output value of a 1 is -1 value of a3 is 1000 value of a 2 is 33 328. What is XSL and XSLT and XSL Processor 329. What is SAX , DOM and JAX (what are their APIs) 330. Who is creating Stub and Skeleton in EJB? And Why 331. What is Instance Pooling and Instance Passivation 205 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM 332. What is Aggregation, Association, Composition, Inheritance , Specialization? Inheritance – common methods and Specialization – Generalization – relationship between parent and child classes 333. What is Object Model, Dynamic Model and Functional Model? Object Model – all class diagram, Aggregation, Assocation, Composition, Generalization and Colloboration and Sequential Diagram Colloboration – and - Sequenctial Diagram – models the interaction of class objects and its relationship. But sequential talks about object messaging behaviour in chronology order. Dynamic Model – State Diagram (depicts dynamic part of the system flow) Functional Model – Data Flow Diagram 334. <xsl:variable> and <xsl:if > & <xsl:value-of select=”@attribute”> 206 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/"> <ol> <xsl:apply-templates select="forum/message"/> </ol> </xsl:template> <xsl:template match="message"> <li> <xsl:if test="@name='EJB' or @name='ejb'"> <xsl:variable name='skill'> <xsl:value-of select="@name"/> </xsl:variable> <xsl:value-of select="$skill" /> </xsl:if> </li> </xsl:template> </xsl:stylesheet> 207 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM XML <?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet href="forum.xsl" type="text/xsl"?> <forum> <message id="1" name="java"></message> <message id="2" name="ejb"></message> <message id="3" name="cpp"></message> <message id="4" name="oracle"></message> </forum> 335. <xsl:value-of select=”element”> <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/"> <ol> <xsl:apply-templates select="school"/> </ol> </xsl:template> <xsl:template match="school"> <xsl:value-of select="name"/> is located in <xsl:value-of select="location"/>, 208 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM <xsl:value-of select="state"/> </xsl:template> </xsl:stylesheet> <?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet href="school.xsl" type="text/xsl"?> <school> <name> Arivalayam </name> <location> Madurai </location> <state> Tamil Nadu </state> </school> 336. <xsl:sort> <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 209 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM <xsl:output method="xml" /> <xsl:template match="/"> <xsl:for-each select="presidents/president"> <xsl:sort select="name/first" /> <xsl:apply-templates select="name" /> <hr/> </xsl:for-each> </xsl:template> <xsl:template match="name"> <xsl:value-of select="first" /> <xsl:text disable-outputescaping="yes">&amp;nbsp;</xsl:text> <xsl:value-of select="last" /> </xsl:template> </xsl:stylesheet> 210 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM <?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/xsl" href="presidents.xsl"?> <presidents> <president> <name> <first> aaa </first> <last> AAA </last> </name> </president> <president> <name> <first> zzz </first> <last> ZZZ </last> </name> </president> <president> <name> <first> bbb </first> <last> BBB </last> 211 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM </name> </president> </presidents> 337. In EJB Equals, hashcode and toString are the 3 methods required for PK class. It is required for Container. Container will look for PK in String format Container will look for hashcode, since it stores Bean in Hashtable or alike structure. Equals for comparing the PK when Two bean has same data 338. JUnit TestCase - A test case defines the fixture to run multiple tests TestSuite- . It runs a collection of test cases 212 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM 339. Code Optimization in order to have Scalability Avoid Synchronization Avoid creating objects Declare variables inside the method Release the resource after every usage Use static methods when ever u need single copy Use Wrapper methods Use PrepareStatement and JNDI lookup based DataSource (connection pooling) 340. Junit Sample Code public class Sample1 extends TestCase { int a ; int b; public void testEmptyCollection() { Collection collection = new ArrayList(); assertTrue(collection.isEmpty()); } public void testName(){ assertEquals("venus",Sample2.getName()); } 213 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM public void testAmount(){ assertTrue(1000.0f == Sample2.getAmount()); } public void testVariable(){ assertEquals(a,b); } public void setUp(){ a = 20; b = 20; } public Sample1(String name) { super(name); } public static Test suite() { //return new TestSuite(Sample1.class); //TestSuite suite= new TestSuite(Sample1.class); TestSuite suite= new TestSuite(); suite.addTest(new Sample1("testEmptyCollection")); 214 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM suite.addTest(new Sample1("testVariable")); suite.addTest(new Sample1("testName")); suite.addTest(new Sample1("testAmount")); suite.addTest(Sample3.suite()); return suite; } public static void main(String ss[]) { junit.textui.TestRunner.run(suite()); } } public class Sample2 { public static String getName(){ return "venus"; } 215 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM public static float getAmount(){ return 1000.0f; } } public class Sample3 extends TestCase { protected int a; protected int b; Collection collection = null; public Sample3(String name){ super(name); } protected void setUp(){ collection = new ArrayList(); collection.add(new Integer(1)); } public static Test suite(){ return new TestSuite(Sample3.class); 216 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM } public void testCollection(){ assertTrue(1 == collection.size()); } public static void main(String args[]){ junit.textui.TestRunner.run(suite()); } } 341. XML APIs Org.jdom. Org.w3c.dom Org.xml.sax Javax.xml.parser 217 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM 342. Why Optimization? Premature optimization is the root of all evils A program is that it requires simply too many resources, and these resources (memory, CPU cycles, network bandwidth, or a combination) may be limited. Code fragments that occur multiple times throughout a program are likely to be size-sensitive, while code with many execution iterations may be speed-sensitive. double x = d * (lim / max) * sx; double y = d * (lim / max) * sy; the common sub expression is calculated once and used for both calculations: double depth = d * (lim / max); double x = depth * sx; double y = depth * sy; for (int i = 0; i < x.length; i++) x[i] *= Math.PI * Math.cos(y); becomes double picosy = Math.PI * Math.cos(y); for (int i = 0; i < x.length; i++) x[i] *= picosy; 343. OPTIMIZATION IN JAVA In Java, code should be reused and inherited wherever it is applicable 218 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM Initialize Array at Run Time Avoid using String, Use String Buffer Avoid Date class, which consumes more space, use Long Declare static final variable in Interface, which will avoid redundancy in class Avoid Run time String Concatenation In the JDK interpreter, calling a synchronized method is typically 10 times slower than calling an unsynchronized method. With JIT compilers, this performance gap has increased to 50-100 times (see Java microbenchmarks). Avoid synchronized methods if you can -- if you can't, synchronizing on methods rather than on code blocks is slightly faster (tip and benchmarks from Doug Lea). You should only use exceptions where you really need them--not only do they have a high basic cost, but their presence can hurt compiler analysis The String concatenation operator + looks innocent but involves a lot of work: a new StringBuffer is created, the two arguments are added to it with append(), and the final result is converted back with a toString(). This costs both space and time. In particular, if you're appending more than one String, consider using a StringBuffer directly instead (tip from Jason Marshall, see also space aspects in Optimizing for Size). Avoid Vector, Use Array Avoid 2 dimensional Array Use Hashtable and rehash the hashtable Inner class object instantiation is about 2x as expensive (time-wise) as normal object creation. If you are going to be creating a lot of inner class objects, you may be better off making a support class in the same package and which is not public. Use Local variable OPTIMIZATION 219 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM Reserving StringBuffer capacity Avoiding premature object creation Creating an efficient vector class Designing caching into your API The cost of synchronization Parallel subtasks JNI efficiency Varying the server workload and RMI network plumbing Using ServletOutputStream Caching JDBC(TM) connections 344. String Buffer is Thread Safe java.lang.StringBuffer StringBuffer in a non-multithreaded environment (or you at least know that nobody will be modifying the StringBuffer at the same time you are, which is essentially a single-threaded environment) you will want to write your own StringBuffer (I use one called SuperStringBuffer) that does not synchronize it's methods. Calling a synchronized method is about 4x slower than calling one that's not synchronized). StringBuffer b = new StringBuffer(); b.append(foo); b.append(bar); b.append(baz); it's considerably faster to do it like this: StringBuffer b = new StringBuffer(); synchronized (b) { b.append(foo); b.append(bar); b.append(baz); } because the former has to obtain three object locks, where as the latter only has to obtain one. 220 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM 345. Which method should use in OPTIMIZATION static (class) methods These are the fastest to call, taking around 220ns. final methods These are somewhere between static and instance methods, taking around 300ns. instance methods These are a little slower, taking around 550ns. interface methods These are surprisingly slow, taking on the order of 750ns to call. synchronized methods These are by far the slowest, since an object lock has to be obtained, and take around 1,500ns. The moral of the story is that if you can get away with it, use static final methods, and don't use interfaces. This is too bad, since most good OO design involves interfaces and for the most part, static methods are only useful in "library" classes that are just a collection on useful methods. 221 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM From Wipro 23rd March 2005 346. Abstract Class and Interface can’t be instantiated Abstract class should have word “abstract” for the abstract method (which is not implemented in abstract class itself) , not necessary for Interface. Interface methods are relatively slow. Interface allow public method and static final variable or constant variable Abstract allows public or protected methods and variables Abstract class can have constructor. It will be invoked when ever extending class got INSTANTIATED abstract class abstractA { public static int a = 10; protected int b = 100; abstract protected void getA(); abstractA(){ System.out.println("aaaa"); } } public class abstract1 extends abstractA{ 222 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM public void getA(){ System.out.println("value is AA" + a); } public static void main(String ss[]){ abstract1 a1 = new abstract1(); a1.getA(); } } 347. Concrete Class A class which has method implementations and able to instantiate. 348. You can serialize any instance of the class with the defaultWriteObject method in ObjectOutputStream You can deserialize any instance of the class with the defaultReadObject method in ObjectInputStream Default serialization can be slow, and a class might want more explicit control over the serialization. Customizing Serialization customize serialization for your classes by providing two methods for it: writeObject and readObject transient and static fields are not serialized or deserialized 223 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM Particularly sensitive classes should not be serialized. To accomplish this, the object should not implement either the Serializable or Externalizable interface. The class should implement writeObject and readObject methods to save and restore only the appropriate state Externalizable Interface Reading and Writing its content. Object state is saved in the stream. If externally defined format is being written, the writeExternal and readExternal methods are solely responsible for that format. 349. Remote Method Invocation (RMI)--communication between objects via sockets 350. When to implement Runnable vs subclassing Thread Whenever your class has to extend another class, use Runnable. This is particularly true when using Applets Start - Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread. In most cases, the Runnable interface should be used if you are only planning to override the run() method and no other Thread methods 224 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM 351. Project planning, feasibility study: Establishes a high-level view of the intended project and determines its goals. Systems analysis, requirements definition: Refines project goals into defined functions and operation of the intended application. Analyzes end-user information needs. Systems design: Describes desired features and operations in detail, including screen layouts, business rules, process diagrams, pseudocode and other documentation. Implementation: The real code is written here. Integration and testing: Brings all the pieces together into a special testing environment, then checks for errors, bugs and interoperability. Acceptance, installation, deployment: The final stage of initial development, where the software is put into production and runs actual business. Maintenance: What happens during the rest of the software's life: changes, correction, additions, moves to a different computing platform and more. This, the least glamorous and perhaps most important step of all, goes on seemingly forever 352. A collaboration diagram describes interactions among objects in terms of sequenced messages. Collaboration diagrams represent a combination of information taken from class, sequence, and use case diagrams describing both the static structure and dynamic behavior of a system. A statechart diagram shows the behavior of classes in response to external stimuli. This diagram models the dynamic flow of control from state to state within a system. An activity diagram illustrates the dynamic nature of a system by modeling the flow of control from activity to activity. An activity represents an operation on some class in the system that results in a change in the state of the system. Typically, activity diagrams are used to model workflow or business processes and internal operation. Because an activity diagram is a special kind of statechart diagram, it uses some of the same modeling conventions. 225 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM 353. Pass reference by value public class passbyref { String s; passbyref(String ss){ s = ss; } public static void main(String ss[]){ passbyref p = new passbyref("11"); System.out.println(" before value of s "+p.s ); foo(p); System.out.println(" after value of s "+ p.s ); } public static void foo(passbyref p){ p.s = "222"; } } 354. Pass by value public class Pass { public static void main(String ss[]){ String bar = "bar"; foo( bar ); System.out.println( bar ); } static void foo(String bar ) { 226 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM bar = "foo"; } } 355. What is Clone() The most likely reason for making a local copy of an object is if you’re going to modify that object and you don’t want to modify the caller’s object. If you decide that you want to make a local copy, you simply use the clone( ) method to perform the operation public class passbyref implements Cloneable{ String s; passbyref(String ss){ s = ss; } public static void main(String ss[]) throws CloneNotSupportedException{ passbyref p = new passbyref("11"); System.out.println(" before value of s "+p.s ); foo((passbyref)p.clone()); 227 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM System.out.println(" after value of s "+ p.s ); } public static void foo(passbyref p){ System.out.println(" inside foo value of s "+ p.s ); p.s = "222"; } } 356 A) if("".equals(myString)) { ... } B) if(myString.equals("")) { ... } 228 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM A is best 357 http://www.jchq.net/tutorial/05_02Tut.htm The creation of two strings with the same sequence of letters without the use of the new keyword will create pointers to the same String in the Java String pool. The String pool is a way Java conserves resources. To illustrate the effect of this String s = "Hello"; String s2 = "Hello"; if (s==s2){ System.out.println("Equal without new operator"); } String t = new String("Hello"); string u = new String("Hello"); if (t==u){ System.out.println("Equal with new operator"); } From the previous objective you might expect that the first output "Equal without new operator" would never be seen as s and s2 are different objects, and the == operator tests what an object points to, not its value. However because of the way Java conserves resources by re-using identical strings that are created without the new operator s and s2 have the same "address" and the code does output the string "Equal without new operator" However with the second set of strings t and u, the new operator forces Java to create separate strings. Because the == operator only compares the address of the object, not the value, t and u have different addresses and thus the string "Equal with new operator" is never seen. 229 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM /////////////////////////////////////////////////////////////////////////////////// 358. Frame Properties <!-- align=position class=name dir=(rtl,ltr) direction frameborder=value height=number lang=language id=name longdesc=url marginheight=number marginwidth=number name=name scrolling=type src=url style=style title=string width=number --> 230 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM Window Properties //win = window.open("","win1","width=700, height=400, top=90, left=300, toolbar=0, menubar=0, location=0, status=0, scrollbars=1, resizable=0,directories=no") ; ShowModalDialog Properties var MyValue = window.showModalDialog("url", "arguments", "properties"); "dialogHeight: 200; resizable: no; center: yes;" Property Value Description center the screen yes/no Specifies whether or not to display the box in the center of dialogHeight x The height (in pixels) of the box dialogWidth dialogLeft screen dialogTop y The width (in pixels) of the box x The distance (in pixels) from the box to the left edge of the y The distance to the top of the screen help yes/no Whether or not to display the ?-button on the titlebar resizable yes/no Specifies if the box should be resizable by users status yes/no Specifies if the box should have a statusbar 231 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM /////////////////////////////////////////////////////////////////////////////////// 359. Date currentDate = new Date(); SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yy"); String defaultDate = dateFormat.format(currentDate); //Date Formating String dbDate = membershipDetailsRecord[9]; if((dbDate.trim() != null) && (dbDate.indexOf("9999-01-01 00:00:00") == 1)){ //2005-06-01 00:00:00.0 SimpleDateFormat dbDateFormat = new SimpleDateFormat("yyyyMM-dd HH:mm:ss"); SimpleDateFormat indiaDateFormat = new SimpleDateFormat("dd/MM/yyyy"); try{ Date dbDateParsed = dbDateFormat.parse(dbDate); String formattedDate = indiaDateFormat.format(dbDateParsed); membershipForm.setDatebox(formattedDate); }catch(Exception ex){ ex.printStackTrace(); } 232 J2EE Concepts by Venkatesh Rajendran 3/8/2016 5:23 AM // 233