You are on page 1of 198

J2EE Basics:

1.What is J2EE J2EE Stands for Java 2 Enterprise Edition. J2EE is an environment for developing and deploying enterprise applications. J2EE specification is defined by Sun Microsystems Inc. The J2EE platform is one of the best platform for the development and deployment of enterprise applications. The J2EE platform is consists of a set of services, application programming interfaces (APIs), and protocols, which provides the functionality necessary for developing multi-tiered, web-based applications. You can download the J2EE SDK and development tools from http://java.sun.com/. 2 . What do you understand by a J2EE module? A J2EE module is a software unit that consists of one or more J2EE components of the same container type along with one deployment descriptor of that type. J2EE specification defines four types of modules: a) EJB b) Web c) application client and d) resource adapter In the J2EE applications modules can be deployed as stand-alone units. Modules can also be assembled into J2EE applications. 3 . Tell me something about J2EE component? J2EE component is a self-contained functional software unit supported by a container and configurable at deployment time. The J2EE specification defines the following J2EE components: Application clients and applets are components that run on the client. Java servlet and JavaServer Pages (JSP) technology components are Web components that run on the server. Enterprise JavaBeans (EJB) components (enterprise beans) are business components that run on the server. J2EE components are written in the Java programming language and are compiled in the same way as any program in the language. The difference between J2EE components and "standard" Java classes is that J2EE components are assembled into a J2EE application, verified to be well formed and in compliance with the J2EE specification, and deployed to production, where they are run and managed by the J2EE server or client container. Source: J2EE v1.4 Glossary

4 . What are the contents of web module? A web module may contain: a) JSP files b) Java classes c) gif and html files and d) web component deployment descriptors 5 . Differentiate between .ear, .jar and .war files. These files are simply zipped file using java jar tool. These files are created for different purposes. Here is the description of these files: .jar files: These files are with the .jar extenstion. The .jar files contains the libraries, resources and accessories files like property files. .war files: These files are with the .war extension. The war file contains the web application that can be deployed on the any servlet/jsp container. The .war file contains jsp, html, javascript and other files for necessary for the development of web applications. .ear files: The .ear file contains the EJB modules of the application. 6 . What is the difference between Session Bean and Entity Bean? Session Bean: Session is one of the EJBs and it represents a single client inside the Application Server. Stateless session is easy to develop and its efficient. As compare to entity beans session beans require few server resources. A session bean is similar to an interactive session and is not shared; it can have only one client, in the same way that an interactive session can have only one user. A session bean is not persistent and it is destroyed once the session terminates. Entity Bean: An entity bean represents persistent global data from the database. Entity beans data are stored into database. 7 . Why J2EE is suitable for the development distributed multi-tiered enterprise applications? The J2EE platform consists of multi-tiered distributed application model. J2EE applications allows the developers to design and implement the business logic into components according to business requirement. J2EE architecture allows the development of multi-tired applications and the developed applications can be installed on different machines depending on the tier in the multi-tiered J2EE environment . The J2EE application parts are: a) Client-tier components run on the client machine. b) Web-tier components run on the J2EE server. c) Business-tier components run on the J2EE server and the d) Enterprise information system (EIS)-tier software runs on the EIS servers

8 . Why do understand by a container? Normally, thin-client multi-tiered applications are hard to write because they involve many lines of intricate code to handle transaction and state management, multithreading, resource pooling, and other complex low-level details. The component-based and platform-independent J2EE architecture makes J2EE applications easy to write because business logic is organized into reusable components. In addition, the J2EE server provides underlying services in the form of a container for every component type. Because you do not have to develop these services yourself, you are free to concentrate on solving the business problem at hand (Source: http://java.sun.com/j2ee/1.3/docs/tutorial/doc/Overview4.html ). In short containers are the interface between a component and the low-level platform specific functionality that supports the component. The application like Web, enterprise bean, or application client component must be assembled and deployed on the J2EE container before executing. Question: What are the services provided by a container? Answer: The services provided by container are as follows: a) Transaction management for the bean b) Security for the bean c) Persistence of the bean d) Remote access to the bean e) Lifecycle management of the bean f) Database-connection pooling g) Instance pooling for the bean 9 . What are types of J2EE clients? J2EE clients are the software that access the services components installed on the J2EE container. Following are the J2EE clients: a) Applets b) Java-Web Start clients c) Wireless clients d) Web applications 10 . What is Deployment Descriptor? A deployment descriptor is simply an XML(Extensible Markup Language) file with the extension of .xml. Deployment descriptor describes the component deployment settings. Application servers reads the deployment descriptor to deploy the components contained in the deployment unit. For example ejb-jar.xml file is used to describe the setting of the EJBs. > 11 . What do you understand by JTA and JTS?
3

JTA stands for Java Transaction API and JTS stands for Java Transaction Service. JTA provides a standard interface which allows the developers to demarcate transactions in a manner that is independent of the transaction manager implementation. The J2EE SDK uses the JTA transaction manager to implement the transaction. The code developed by developers does not calls the JTS methods directly, but only invokes the JTA methods. Then JTA internally invokes the JTS routines. JTA is a high level transaction interface used by the application code to control the transaction. 12 . What is JAXP? The Java API for XML Processing (JAXP) enables applications to parse and transform XML documents independent of a particular XML processing implementation. JAXP or Java API for XML Parsing is an optional API provided by Javasoft. It provides basic functionality for reading, manipulating, and generating XML documents through pure Java APIs. It is a thin and lightweight API that provides a standard way to seamlessly integrate any XML-compliant parser with a Java application. More at http://java.sun.com/xml/ 13 . What is J2EE Connector architecture? J2EE Connector Architecture (JCA) is a Java-based technology solution for connecting application servers and enterprise information systems (EIS) as part of enterprise application integration (EAI) solutions. While JDBC is specifically used to connect Java EE applications to databases, JCA is a more generic architecture for connection to legacy systems (including databases). JCA was developed under the Java Community Process as JSR 16 (JCA 1.0) and JSR 112 (JCA 1.5). As of 2006, the current version of JCA is version 1.5. The J2EE Connector API is used by J2EE tools developers and system integrators to create resource adapters. Home page for J2EE Connector architecture http://java.sun.com/j2ee/connector/. 14 . What is difference between Java Bean and Enterprise Java Bean? Java Bean as is a plain java class with member variables and getter setter methods. Java Beans are defined under JavaBeans specification as Java-Based software component model which includes the features like introspection, customization, events, properties and persistence. Enterprise JavaBeans or EJBs for short are Java-based software components that comply with Java's EJB specification. EJBs are delpoyed on the EJB container and executes in the EJB container. EJB is not that simple, it is used for building distributed applications. Examples of EJB are Session Bean, Entity Bean and Message Driven Bean. EJB is used for server side programming whereas java bean is a client side. Bean is only development but the EJB is developed and then deploy on EJB Container.

15 . What is the difference between JTS and JTA?


4

In any J2EE application transaction management is one of the most crucial requirements of the application. Given the complexity of today's business requirements, transaction processing occupies one of the most complex segments of enterprise level distributed applications to build, deploy and maintain. JTS specifies the implementation of a Java transaction manager. JTS specifies the implementation of a Transaction Manager which supports the Java Transaction API (JTA) 1.0 This transaction manager supports the JTA, using which application servers can be built to support transactional Java applications. Internally the JTS implements the Java mapping of the OMG OTS 1.1 specifications. The Java mapping is specified in two packages: org.omg.CosTransactions and org.omg.CosTSPortability. The JTS thus provides a new architecture for transactional application servers and applications, while complying to the OMG OTS 1.1 interfaces internally. This allows the JTA compliant applications to interoperate with other OTS 1.1 complaint applications through the standard IIOP. Java-based applications and Java-based application servers access transaction management functionality via the JTA interfaces. The JTA interacts with a transaction management implementation via JTS. Similarly, the JTS can access resources via the JTA XA interfaces or can access OTS-enabled non-XA resources. JTS implementations can interoperate via CORBA OTS interfaces. The JTA specifies an architecture for building transactional application servers and defines a set of interfaces for various components of this architecture. The components are: the application, resource managers, and the application server. The JTA specifies standard interfaces for Java-based applications and application servers to interact with transactions, transaction managers, and resource managers JTA transaction management provides a set of interfaces utilized by an application server to manage the beginning and completion of transactions. Transaction synchronization and propagation services are also provided under the domain of transaction management. In the Java transaction model, the Java application components can conduct transactional operations on JTA compliant resources via the JTS. The JTS acts as a layer over the OTS. The applications can therefore initiate global transactions to include other OTS transaction managers, or participate in global transactions initiated by other OTS compliant transaction managers. 16 . Can Entity Beans have no create() methods? Entity Beans can have no create() methods. Entity Beans have no create() method, when entity bean is not used to store the data in the database. In this case entity bean is used to retrieve the data from database. 17 . What are the call back methods in Session bean? Callback methods are called by the container to notify the important events to the beans in its life cycle. The callback methods are defined in the javax.ejb.EntityBean interface.The callback methods example are ejbCreate(), ejbPassivate(), and ejbActivate(). 18 . What is bean managed transaction?
5

In EJB transactions can be maintained by the container or developer can write own code to maintain the transaction. If a developer doesnt want a Container to manage transactions, developer can write own code to maintain the database transaction. 19 . What are transaction isolation levels in EJB? Thre are four levels of transaction isolation are: * Uncommitted Read * Committed Read * Repeatable Read * Serializable The four transaction isolation levels and the corresponding behaviors are described below: Isolation Level Dirty Read Non-Repeatable Read Phantom Read Possible Possible Possible Read Uncommitted Not possible Possible Possible Read Committed Not possible Not possible Possible Repeatable Read Not possible Not possible Not possible Serializable

dDw tMTg5MDU4M 52

J2EE - Core Java


1 . Language Fundamentals How many number of non-public class definitions can a source file have A source file can contain unlimited number of non-public class definitions

What types of values does boolean variables take It only takes values true and false Which primitive datatypes are signed All except char and Boolean Is char type signed or unsigned char type is integral but unsigned. It range is 0 to 2^7-1 What forms an integral literal can be decimal, octal and hexadecimal, hence example it can be 28, 034 and 0x1c respectively What is the default value of Boolean False Why is the main method static So that it can be invoked without creating an instance of that class What is the difference between class variable, member variable and automatic(local) variable class variable is a static variable and does not belong to instance of class but rather shared across all the instances
7

member variable belongs to a particular instance of class and can be called from any method of the class automatic or local variable is created on entry to a method and has only method scope When are static and non static variables of the class initialized The static variables are initialized when the class is loadedNon static variables are initialized just before the constructor is called When are automatic variable initialized Automatic variable have to be initialized explicitly How is an argument passed in java, by copy or by reference If the variable is primitive datatype then it is passed by copy. If the variable is an object then it is passed by reference What is garbage collection The runtime system keeps track of the memory that is allocated and is able to determine whether that memory is still useable. This work is usually done in background by a low-priority thread that is referred to as garbage collector. When the gc finds memory that is no longer accessible from any live thread it takes steps to release it back to the heap for reuse Does System.gc and Runtime.gc() guarantee garbage collection No

2 . Operators and assignment What are different types of operators in java Uniary ++, --, +, -, |, ~, () Arithmetic *, /, %,+, Shift <<, >>, >>> Comparison =, instanceof, = =,!=Bitwise &, ^, |Short Circuit &&, ||Ternary ?:Assignment =

How does bitwise (~) operator work It converts all the 1 bits in a binary value to 0s and all the 0 bits to 1s, e.g 11110000 coverts to 00001111 What is a modulo operator % This operator gives the value which is related to the remainder of a divisione.g x=7%4 gives remainder 3 as an answer Can shift operators be applied to float types. No, shift operators can be applied only to integer or long types What happens to the bits that fall off after shifting They are discarded What values of the bits are shifted in after the shift In case of signed left shift >> the new bits are set to zero But in case of signed right shift it takes the value of most significant bit before the shift, that is if the most significant bit before shift is 0 it will introduce 0, else if it is 1, it will introduce 1

3 . Modifiers What are access modifiers These public, protected and private, these can be applied to class, variables, constructors and methods. But if you don't specify an access modifier then it is considered as Friendly Can protected or friendly features be accessed from different packages No when features are friendly or protected they can be accessed from all the classes in that package but not from classes in another package

How can you access protected features from another package You can access protected features from other classes by subclassing the that class in another package, but this cannot be done for friendly features What are the rules for overriding Private method can be overridden by private, friendly, protected or public methods Friendly method can be overridden by friendly, protected or public methods Protected method can be overridden by protected or public methods Public method can be overridden by public method Explain modifier final Final can be applied to classes, methods and variables and the features cannot be changed. Final class cannot be subclassed, methods cannot be overridden Can you change the reference of the final object No the reference cannot be change, but the data in that object can be changed Can abstract modifier be applied to a variable No it is applied only to class and methods Can abstract class be instantiated No abstract class cannot be instantiated i.e you cannot create a new object of this class When does the compiler insist that the class must be abstract If one or more methods of the class are abstract. If class inherits one or more abstract methods from the parent abstract class and no implementation is provided for that method If class implements an interface and provides no implementation for those methods

10

How is abstract class different from final class Abstract class must be subclassed and final class cannot be subclassed Where can static modifiers be used They can be applied to variables, methods and even a block of code, static methods and variables are not associated with any instance of class When are the static variables loaded into the memory During the class load time

4 . Modifiers When are the non static variables loaded into the memory They are loaded just before the constructor is called How can you reference static variables Via reference to any instance of the class Computer comp = new Computer (); comp.harddisk where hardisk is a static variable comp.compute() where compute is a method Via the class name Computer.harddisk Computer.compute() Can static method use non static features of there class No they are not allowed to use non static features of the class, they can only call static methods and can use static data What is static initializer code

11

A class can have a block of initializer code that is simply surrounded by curly braces and labeled as static e.g. public class Demo{ static int =10; static{ System.out.println("Hello world'); } } And this code is executed exactly once at the time of class load Where is native modifier used It can refer only to methods and it indicates that the body of the method is to be found else where and it is usually written in non java language What are transient variables A transient variable is not stored as part of objects persistent state and they cannot be final or static

What is synchronized modifier used for It is used to control access of critical code in multithreaded programs What are volatile variables It indicates that these variables can be modified asynchronously

12

5 . Conversion Casting and Promotion What are wrapped classes Wrapped classes are classes that allow primitive types to be accessed as objects.

What are the four general cases for Conversion and Casting Conversion of primitives Casting of primitives Conversion of object references Casting of object references When can conversion happen It can happen during Assignment Method call Arithmetic promotion What are the rules for primitive assignment and method call conversion A boolean can not be converted to any other type A non Boolean can be converted to another non boolean type, if the conversion is widening conversion A non Boolean cannot be converted to another non boolean type, if the conversion is narrowing conversion See figure below for simplicity

What are the rules for primitive arithmetic promotion conversion

13

For Unary operators : If operant is byte, short or a char it is converted to an int If it is any other type it is not converted For binary operands : If one of the operands is double, the other operand is converted to double Else If one of the operands is float, the other operand is converted to float Else If one of the operands is long, the other operand is converted to long Else both the operands are converted to int

What are the rules for casting primitive types You can cast any non Boolean type to any other non boolean type You cannot cast a boolean to any other type; you cannot cast any other type to a Boolean What are the rules for object reference assignment and method call conversion

An interface type can only be converted to an interface type or to object. If the new type is an interface, it must be a superinterface of the old type A class type can be converted to a class type or to an interface type. If converting to a class type the new type should be superclass of the old type. If converting to an interface type new type the old class must implement the interface An array maybe converted to class object, to the interface cloneable, or to an array. Only an array of object references types may be converted to an array, and the old element type must be convertible to the new element What are the rules for Object reference casting Casting from Old types to Newtypes Compile time rules

When both Oldtypes and Newtypes are classes, one should be subclass of the other When both Oldtype ad Newtype are arrays, both arrays must contain reference types (not primitive),

and it must be legal to cast an element of Oldtype to an element of Newtype

14

You can always cast between an interface and a non-final object

Runtime rules If Newtype is a class. The class of the expression being converted must be Newtype or must inherit from Newtype If NewType is an interface, the class of the expression being converted must implement Newtype

6 . Flow Control and exception What is the difference between while and do while loop Do while loop walways executes the body of the loop at least once, since the test is performed at the end of the body When do you use continue and when do you use break statements When continue statement is applied it prematurely completes the iteration of a loop. When break statement is applied it causes the entire loop to be abandoned. What is the base class from which all exceptions are subclasses All exceptions are subclasses of a class called java.lang.Throwable How do you intercept and thereby control exceptions We can do this by using try/catch/finally blocks You place the normal processing code in try block You put the code to deal with exceptions that might arise in try block in catch block Code that must be executed no matter what happens must be place in finally block

15

When do we say an exception is handled When an exception is thrown in a try block and is caught by a matching catch block, the exception is considered to have been handled When do we say an exception is not handled There is no catch block that names either the class of exception that has been thrown or a class of exception that is a parent class of the one that has been thrown, then the exception is considered to be unhandled, in such condition the execution leaves the method directly as if no try has been executed

7 . Flow Control and exception In what sequence does the finally block gets executed If you put finally after a try block without a matching catch block then it will be executed after the try block If it is placed after the catch block and there is no exception then also it will be executed after the try block If there is an exception and it is handled by the catch block then it will be executed after the catch block What can prevent the execution of the code in finally block

The death of thread Use of system.exit() Turning off the power to CPU An exception arising in the finally block itself

What are the rules for catching multiple exceptions A more specific catch block must precede a more general one in the source, else it gives compilation error Only one catch block, that is first applicable one, will be executed What does throws statement declaration in a method indicate This indicates that the method throws some exception and the caller method should take care of handling it

16

What are checked exception Checked exceptions are exceptions that arise in a correct program, typically due to user mistakes like entering wrong data or I/O problems What are runtime exceptions Runtime exceptions are due to programming bugs like out of bond arrays or null pointer exceptions. What is difference between Exception and errors Errors are usually compile time and exceptions can be runtime or checked How will you handle the checked exceptions You can provide a try/catch block to handle it. OR Make sure method declaration includes a throws clause that informs the calling method an exception might be thrown from this particular method When you extend a class and override a method, can this new method throw exceptions other than those that were declared by the original method No it cannot throw, except for the subclasses of those exceptions Is it legal for the extending class which overrides a method which throws an exception, not o throw in the overridden class Yes it is perfectly legal Explain the user defined Exceptions? User defined Exceptions are the separate Exception classes defined by the user for specific purposed. An user defined can created by simply sub-classing it to the Exception class. This allows custom exceptions to be generated (using throw) and caught in the same way as normal exceptions. Example: class myCustomException extends Exception { // The class simply has to exist to be an exception }

17

8 . Objects and Classes What's the difference between constructors and other methods Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times. What is the difference between Overloading and Overriding Overloading : Reusing the same method name with different arguments and perhaps a different return type is called as overloading Overriding : Using the same method name with identical arguments and return type is know as overriding What do you understand by late binding or virtual method Invocation. (Example of runtime polymorphism) When a compiler for a non object oriented language comes across a method invocation, it determines exactly what target code should be called and build machine language to represent that call. In an object oriented language, this is not possible since the proper code to invoke is determined based upon the class if the object being used to make the call, not the type of the variable. Instead code is generated that will allow the decision to be made at run time. This delayed decision making is called as late binding Can overriding methods have different return types No they cannot have different return types If the method to be overridden has access type protected, can subclass have the access type as private No, it must have access type as protected or public, since an overriding method must not be less accessible than the method it overrides Can constructors be overloaded Yes constructors can be overloaded What happens when a constructor of the subclass is called A constructor delays running its body until the parent parts of the class have been initialized. This commonly happens because of an implicit call to super() added by the compiler. You can provide your own call to
18

super(arguments..) to control the way the parent parts are initialized. If you do this, it must be the first statement of the constructor.

If you use super() or this() in a constructor where should it appear in the constructor It should always be the first statement in the constructor

9 . Objects and Classes What is an inner class An inner class is same as any other class, but is declared inside some other class How will you reference the inner class To reference it you will have to use OuterClass$InnerClass Can objects that are instances of inner class access the members of the outer class Yes they can access the members of the outer class What modifiers may be used with an inner class that is a member of an outer class? A (non-local) inner class may be declared as public, protected, private, static, final, or abstract Can inner classes be static Yes inner classes can be static, but they cannot access the non static data of the outer classes, though they can access the static data Can an inner class be defined inside a method Yes it can be defined inside a method and it can access data of the enclosing methods or a formal parameter if it is final

19

What is an anonymous class Some classes defined inside a method do not need a name, such classes are called anonymous classes What are the rules of anonymous class The class is instantiated and declared in the same place The declaration and instantiation takes the form new Xxxx () {// body} Where Xxxx is an interface name. An anonymous class cannot have a constructor. Since you do not specify a name for the class, you cannot use that name to specify a constructor

10 . Threads Where does java thread support reside It resides in three places The java.lang.Thread class (Most of the support resides here) The java.lang.Object class The java language and virtual machine

What is the difference between Thread and a Process Threads run inside process and they share data. One process can have multiple threads, if the process is killed all the threads inside it are killed, they dont share data What happens when you call the start() method of the thread This registers the thread with a piece of system code called thread scheduler The schedulers determines which thread is actually running Does calling start () method of the thread causes it to run No it merely makes it eligible to run. The thread still has to wait for the CPU time along with the other threads, then at some time in future, the scheduler will permit the thread to run
20

When the thread gets to execute, what does it execute The thread executes a method call run(). It can execute run() method of either of the two choices given below : The thread can execute it own run() method. The thread can execute the run() method of some other objects For the first case you need to subclass the Thread class and give your subclass a run() method For the second method you need to have a class implement the interface runnable. Define your run method. Pass this object as an argument to the Thread constructor How many methods are declared in the interface runnable The runnable method declares only one method : public void run(); Which way would you prefer to implement threading , by extending Thread class or implementing Runnable interface The preferred way will be to use Interface Runnable, because by subclassing the Thread class you have single inheritance i.e you wont be able to extend any other class

11 . Threads What happens when the run() method returns When the run() method returns, the thread has finished its task and is considered dead. You can't restart a dead thread. You can call the methods of dead thread What are the different states of the thread They are as follows: Running: The state that all thread aspire to be Various waiting states : Waiting, Sleeping, Suspended and Bloacked Ready : Waiting only for the CPU Dead : All done

21

What is Thread priority Every thread has a priority, the higher priorit thread gets preference over the lower priority thread by the thread scheduler What is the range of priority integer It is from 1 to 10. 10 beings the highest priority and 1 being the lowest What is the default priority of the thread The default priority is 5 What happens when you call Thread.yield() It caused the currently executing thread to move to the ready state if the scheduler is willing to run any other thread in place of the yielding thread. Yield is a static method of class Thread What is the advantage of yielding It allows a time consuming thread to permit other threads to execute

12 . Threads What happens when you call Thread.sleep() It passes time without doing anything and without using the CPU. A call to sleep method requests the currently executing thread to cease executing for a specified amount of time. Does the thread method start executing as soon as the sleep time is over No, after the specified time is over the thread enters into ready state and will only execute when the scheduler allows it to do so. What do you mean by thread blocking If a method needs to wait an indeterminable amount of time until some I/O occurrence takes place, then a thread executing that method should graciously step out of the Running state. All java

22

I/O methods behave this way. A thread that has graciously stepped out in this way is said to be blocked What threading related methods are there in object class wait(), notify() and notifyAll() are all part of Object class and they have to be called from synchronized code only What is preemptive scheduling In preemptive scheduling there are only two ways for the thread to leave the running state without ecplicitly calling wait() or suspended() It can cease t be ready to execute ()by calling a blocking I/O method) It can get moved out by CPU by a higher priorit thread that becomes ready to execute What is non-preemptive or Time sliced or round robin scheduling With time slicing the thread is allowd to execute for a limited amount of time. It is then moved to ready state, where it must contend with all the other ready threads. What are the two ways of synchronizing the code Synchronizing an entire method by putting the synchronized modifier in the methods declaration. To execute the method, a thread must acquire the lock of the object that owns the method Synchronize a subset of a method by surrounding the desired lines of code with curly brackets and inserting the synchronized expression before the opening curly. This allows you to synchronize the block on the lock of any object at all, not necessarily the object that owns the code What happens when the wait() method is called The calling thread gives up CPU The calling thread gives up the lock The calling thread goes into the monitor's waiting pool What happens when the notify() method is called One thread gets moved out of monitors waiting pool and into the ready state The thread that was notified ust reacquire the monitors locl before it can proceed

23

Using notify () method how you can specify which thread should be notified You cannot specify which thread is to be notified, hence it is always better to call notifyAll() method

13 . java.lang & java.util Packages What is the ultimate ancestor of all java classes Object class is the ancestor of all the java classes What are important methods of Object class wait(), notify(), notifyAll(), equals(), toString(). What is the difference between "= =" and "equals()" "= =" does shallow comparison, It retuns true if the two object points to the same address in the memory, i.e if the same the same reference "equals()" does deep comparison, it checks if the values of the data in the object are same What would you use to compare two String variables - the operator == or the method equals()? I'd use the method equals() to compare the values of the Strings and the == to check if two variables point at the same instance of a String object Give example of a final class Math class is final class and hence cannot be extended What is the difference between String and StringBuffer String is an immutable class, i.e you cannot change the values of that class Example : String str = "java"; // address in memory say 12345 And now if you assign a new value to the variable str then str = "core java"; then the value of the variable at address 12345 will not change but a new memory is allocated for this variable say 54321 So in the memory address 12345 will have value "java" And the memory address 54321 will have value "core java" and the variable str will now be pointing to address

24

54321 in memory StringBuffer can be modified dynamically Example: StringBuffer strt ="java" // address in memory is say 12345 And now if you assign a new value to the variable str then Str = "core java"; then value in the address of memory will get replaced, a new memory address is not allocated in this case.

> 14 . java.lang & java.util Packages What will be the result if you compare StringBuffer with String if both have same values It will return false as you cannot compare String with StringBuffer What is Collection API The Collection API is a set of classes and interfaces that support operation on collections of objects. These classes and interfaces are more flexible, more powerful, and more regular than the vectors, arrays, and hashtables if effectively replaces. Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap. Example of interfaces: Collection, Set, List and Map. What are different types of collections A collection has no special order and does not reject duplicates A list is ordered and does not reject duplicates A set has no special order but rejects duplicates A map supports searching on a key field, values of which must be unique Tell me something about Arrays Arrays are fast to access, but are inefficient if the number of elements grow and if you have to insert or delete an element

25

Difference between ArrayList and Vector Vector methods are synchronized while ArrayList methods are not Iterator a Class or Interface? What is its use? Iterator is an interface which is used to step through the elements of a Collection Difference between Hashtable and HashMap Hashtable does not store null value, while HashMap does Hashtable is synchronized, while HashMap is not

J2EE - Java 1 . Why do we need public static void main(String args[]) method in Java We needpublic: The method can be accessed outside the class / package static: You need not have an instance of the class to access the method void: Your application need not return a value, as the JVM launcher would return the value when it exits main(): This is the entry point for the application If the main() was not static, you would require an instance of the class in order to execute the method. If this is the case, what would create the instance of the class? What if your class did not have a public constructor? 2 . What is the difference between an Interface and an Abstract class In abstract class you can define as well as declare methods, the methods which are declared are to be marked as abstract. In interface all we just declare methods and the definition is provided by the class which is implementing it

26

3 . Explain serialization Serialization means storing a state of a java object by coverting it to byte stream 4 . What are the rules of serialization

Rules: 1. Static fileds are not serialized because they are not part of any one particular object 2. Fileds from the base class are handled only if hose are serializable 3. Transient fileds are not serialized

5 . What is difference between error and exception Error occurs at runtime and cannot be recovered, Outofmemory is one such example. Exceptions on the other hand are due conditions which the application encounters such as FileNotFound exception or IO exceptions

6 . What do you mean by object oriented programming In object oriented programming the emphasis is more on data than on the procedure and the program is divided into objects. The data fields are hidden and they cant be accessed by external functions. The design approach is bottom up. The functions operate on data that is tied together in data structure 7 . What are 4 pillars of object oreinted programming 1. Abstraction It means hiding the details and only exposing the essentioal parts 2. Polymorphism Polymorphism means having many forms. In java you can see polymorphism when you have multiple methods with the same name 3. Inheritance Inheritance means the child class inherits the non private properties of the parent class

27

4. Encapsulation It means data hiding. In java with encapsulate the data by making it private and even we want some other class to work on that data then the setter and getter methods areprovided

8 . Difference between procedural and object oreinted language In procedural programming the instructions are executed one after another and the data is exposed to the whole program In OOPs programming the unit of program is an object which is nothing but combination of data and code and the data is not exposed outside the object

9 . What is the difference between constructor and method Constructor will be automatically invoked when an object is created whereas method has to be called explicitly. 10 . What is the difference between parameters and arguments While defining method, variables passed in the method are called parameters. While using those methods, values passed to those variables are called arguments. > 11 . What is reflection in java Reflection allows Java code to discover information about the fields, methods and constructors of loaded classes and to dynamically invoke them 12 . What is a cloneable interface and how many methods does it contain It is not having any method because it is a TAGGED or MARKER interface 13 . What's the difference between a queue and a stack Stacks works by last-in-first-out rule (LIFO), while queues use the FIFO rule 14 . Can you make an instance of abstract class No you cannot create an instance of abstract class

28

15 . What are parsers Parsers are used for processing XML documents. There are 2 types of parsers DOM parser and SAX Parser 16 . Difference between SAX and DOM parser DOM parsers are Object based and SAX parsers are event based DOM parsers creates Tree in the memory whereas SAX parser does not and hence it is faster than DOM DOM parser are useful when we have to modify the XML, with SAX parser you cannot modify the xml, it is read only

17 . What is the difference between Java Bean and Java Class Basically a Bean is a java class but it has getter and setter method and it does not have any logic in it, it is used for holding data. On the other hand the Java class can have what a java bean has and also has some logic inside it

18 . What are null or Marker interfaces in Java The null interfaces are marker interfaces, they do not have function declarations in them, they are empty interfaces, this is to convey the compiler that they have to be treated differently 19 . Does java Support multiple inheritance Java does not support multiple inheritance directly like C++, because then it is prone to ambiguity, example if a class extends 2 other classes and these 2 parent classes have same method names then there is ambiguity. Hence in Java Multiple inheritance is supported using Interfaces 20 . What are virtual function In OOP when a derived class inherits from a base class, an object of the derived class may be referred to (or cast) as either being the base class type or the derived class type. If there are base class functions overridden by the derived class, a problem then arises when a derived object has been cast as the base class type. When a derived object is
29

referred to as being of the base's type, the desired function call behavior is ambiguous. The distinction between virtual and not virtual is provided to solve this issue. If the function in question is designated "virtual" then the derived class's function would be called (if it exists). If it is not virtual, the base class's function would be called. > 21 . Does java support virtual functions No java does not support virtual functions direclty like in C++, but it supports using Abstract class and interfaces 22 . Describe what happens when an object is created in Java Several things happen in a particular order to ensure the object is constructed properly: 1. Memory is allocated from heap to hold all instance variables and implementation -specific data of the object and its superclasses. Implemenation-specific data includes pointers to class and method data. 2. The instance variables of the objects are initialized to their default values. 3. The constructor for the most derived class is invoked. The first thing a constructor does is call the consctructor for its superclasses. This process continues until the constrcutor for java.lang.Object is called, as java.lang.Object is the base class for all objects in java. 4. Before the body of the constructor is executed, all instance variable initializers and initialization blocks are executed. Then the body of the constructor is executed. Thus, the constructor for the base class completes first and constructor for the most derived class completes last.

30

23 . What is the purpose of System Class The purpose of the system class is to provide the access to the System reources 24 . What is instanceOf operator used for It is used to if an object can be cast into a specific type without throwing Class cast exception 25 . Why we should not have instance variable in an interface Since all data fields and methods in an Interface are public by default, then we implement that interface in our class then we have public members in our class and this class will expose these data members and this is violation of encapsulation as now the data is not secure 26 . What is JVM When we install a java package. It contains 2 things * The Java Runtime Environment (JRE) * The Java Development Kit (JDK) The JRE provides runtime support for Java applications. The JDK provides the Java compiler and other development tools. The JDK includes the JRE. Both the JRE and the JDK include a Java Virtual Machine (JVM). This is the application that executes a Java program. A Java program requires a JVM to run on a particular platform 27 . Can abstract class be final No, abstract class cannot be final 28 . When a new object of derived Class is created, whose constructor will be called first, childs or parents Even when the new object of child class is created, first the Base class constructor gets executed and then the child classes constructor

31

29 . What is a singleton class A singleton is an object that cannot be instantiated. The restriction on the singleton is that there can be only one instance of a singleton created by the Java Virtual Machine (JVM) - by prevent direct instantiation we can ensure that developers don't create a second copy.

30 . Can an abstract class have final method Yes 31 . Can a final class have an abstract method No, the compiler will give an error 32 . What is the difference between Authentication and Authorization Authentication is a process for verifying that an individual is who they say they are. Authorization is an additional level of security, and it means that a particular user (usually authenticated), may have access to a particular resource say record, file, directory or script.

Short for Java Database Connectivity, a Java API that enables Java programs to execute SQL statements. This allows Java programs to interact with any SQL-compliant database. Since nearly all relational database management systems (DBMSs) support SQL, and because Java itself runs on most platforms, JDBC makes it possible to write a single database application that can run on different platforms and interact with different DBMSs.

32

J2EE-JDBC
What is JDBC JDBC is similar to ODBC, but is designed specifically for Java programs, whereas ODBC is language-independent. 2 . What are the components of JDBC JDBC Components-Connection Pools, Data Sources, and MultiPools 3 . How to you load the drivers Class.forName() method is used in JDBC to load the JDBC drivers dynamically 4 . What are the different types of JDBC drivers 1. A JDBC-ODBC bridge provides JDBC API access via one or more ODBC drivers. Note that some ODBC native code and in many cases native database client code must be loaded on each client machine that uses this type of driver. Hence, this kind of driver is generally most appropriate when automatic installation and downloading of a Java technology application is not important. 2. A native-API partly Java technology-enabled driver converts JDBC calls into calls on the client API for Oracle, Sybase, Informix, DB2, or other DBMS. Note that, like the bridge driver, this style of driver requires that some binary code be loaded on each client machine. 3. A net-protocol fully Java technology-enabled driver translates JDBC API calls into a DBMSindependent net protocol which is then translated to a DBMS protocol by a server. This net server middleware is able to connect all of its Java technology-based clients to many different databases. The specific protocol used depends on the vendor. In general, this is the most flexible JDBC API alternative. It is likely that all vendors of this solution will provide products suitable for Intranet use. In order for these products to also support Internet access they must handle the additional requirements for security, access through firewalls, etc., that the Web imposes. Several vendors are adding JDBC technology-based drivers to their existing database middleware products. 4. A native-protocol fully Java technology-enabled driver converts JDBC technology calls into the network protocol used by DBMSs directly. This allows a direct call from the client machine to the DBMS server and is a practical solution for Intranet access. Since many of these protocols are proprietary the database vendors themselves will be the primary source for this style of driver. Several database vendors have these in progress. 5 . What are the pros and cons of all the 4 drivers Type 1: JDBC-ODBC Bridge The type 1 driver, JDBC-ODBC Bridge, translates all JDBC calls into ODBC (Open DataBase Connectivity) calls and sends them to the ODBC driver. As such, the ODBC driver, as well as, in many
33

cases, the client database code, must be present on the client machine. Figure 1 shows a typical JDBCODBC Bridge environment. Figure 1. Type 1: JDBC-ODBC Bridge Pros The JDBC-ODBC Bridge allows access to almost any database, since the database's ODBC drivers are already available. Type 1 drivers may be useful for those companies that have an ODBC driver already installed on client machines. Cons The performance is degraded since the JDBC call goes through the bridge to the ODBC driver, then to the native database connectivity interface. The result comes back through the reverse process. Considering the performance issue, type 1 drivers may not be suitable for large-scale applications. The ODBC driver and native connectivity interface must already be installed on the client machine. Thus any advantage of using Java applets in an intranet environment is lost, since the deployment problems of traditional applications remain. Type 2: Native-API/partly Java driver JDBC driver type 2 -- the native-API/partly Java driver -- converts JDBC calls into database-specific calls for databases such as SQL Server, Informix, Oracle, or Sybase. The type 2 driver communicates directly with the database server; therefore it requires that some binary code be present on the client machine.

Figure 2. Type 2: Native-API/partly Java driver Pros Type 2 drivers typically offer significantly better performance than the JDBC-ODBC Bridge. Cons The vendor database library needs to be loaded on each client machine. Consequently, type 2 drivers cannot be used for the Internet. Type 2 drivers show lower performance than type 3 and type 4 drivers. Type 3: Net-protocol/all-Java driver JDBC driver type 3 -- the net-protocol/all-Java driver -- follows a three-tiered approach whereby the JDBC database requests are passed through the network to the middle-tier server. The middle-tier server then translates the request (directly or indirectly) to the database-specific native-connectivity interface to further the request to the database server. If the middle-tier server is written in Java, it can use a type 1 or type 2 JDBC driver to do this.
34

Figure 3. Type 3: Net-protocol/all-Java driver Pros The net-protocol/all-Java driver is server-based, so there is no need for any vendor database library to be present on client machines. Further, there are many opportunities to optimize portability, performance, and scalability. Moreover, the net protocol can be designed to make the client JDBC driver very small and fast to load. Additionally, a type 3 driver typically provides support for features such as caching (connections, query results, and so on), load balancing, and advanced system administration such as logging and auditing. Cons Type 3 drivers require database-specific coding to be done in the middle tier. Additionally, traversing the recordset may take longer, since the data comes through the backend server. Type 4: Native-protocol/all-Java driver The native-protocol/all-Java driver (JDBC driver type 4) converts JDBC calls into the vendor-specific database management system (DBMS) protocol so that client applications can communicate directly with the database server. Level 4 drivers are completely implemented in Java to achieve platform independence and eliminate deployment administration issues.

Figure 4. Type 4: Native-protocol/all-Java driver Pros Since type 4 JDBC drivers don't have to translate database requests to ODBC or a native connectivity interface or to pass the request on to another server, performance is typically quite good. Moreover, the native-protocol/all-Java driver boasts better performance than types 1 and 2. Also, there's no need to install special software on the client or server. Further, these drivers can be downloaded dynamically. Cons With type 4 drivers, the user needs a different driver for each database. 6 . How to you establish a connection Loading Drivers Class.forName("Driver"); Getting connection Connection con = DriverManager.getConnection(url,myLogin", "myPassword");

35

7 . What are different types of statements in JDBC java.sql.Statement - Top most interface which provides basic methods useful for executing SELECT, INSERT, UPDATE and DELETE SQL statements. java.sql.PreparedStatement - An enhanced verion of java.sql.Statement which allows precompiled queries with parameters. It is more efficient to use java.sql.PreparedStatement if you have to specify parameters to your SQL queries. java.sql.CallableStatement - Allows you to execute stored procedures within a RDBMS which supports stored procedures (MySQL doesn't support stored procedures at the moment). 8 . When do we used prepared statements If you want to execute a Statement object many times, it will normally reduce execution time to use a PreparedStatement object instead. The main feature of a PreparedStatement object is that, unlike a Statement object, it is given an SQL statement when it is created. The advantage to this is that in most cases, this SQL statement will be sent to the DBMS right away, where it will be compiled. As a result, the PreparedStatement object contains not just an SQL statement, but an SQL statement that has been precompiled. This means that when the PreparedStatement is executed, the DBMS can just run the PreparedStatement 's SQL statement without having to compile it first. Although PreparedStatement objects can be used for SQL statements with no parameters, you will probably use them most often for SQL statements that take parameters. The advantage of using SQL statements that take parameters is that you can use the same statement and supply it with different values each time you execute it. You will see an example of this in the following sections. 9 . How do you create JDBC statements Connection con = null; Statement st = null; // Obtain connection here st = con.createStatement(); ResultSet rs = null; rs = st.executeQuery("SELECT * FROM users"); int recordsUpdated; recordsUpdated = st.executeUpdate("DELETE FROM users WHERE user_id = 1"); 10 . How do you retrieve data from a result set
36

Example: Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(SELECT COF_NAME, PRICE FROM COFFEES"); while (rs .next() ) { //Iam assuming there are 3 columns in the table. System.out.println ( rs.getString(1)); System.out.println(rs.getString(2)); System.out.println(rs.getString(3)); } //don't forget to close the resultset, statement & connection rs.close(); //First stmt.close(); //Second con.close(); //Last System.out.println("You are done"); 11 . What is a stored procedure A stored procedure is a group of SQL statements that form a logical unit and perform a particular task. Stored procedures are used to encapsulate a set of operations or queries to execute on a database server. For example, operations on an employee database (hire, fire, promote, lookup) could be coded as stored procedures executed by application code. Stored procedures can be compiled and executed with different parameters and results, and they may have any combination of input, output, and input/output parameters. 12 . What are the tasks of JDBC Following are the tasks of JDBC

Load the JDBC drivers Register the drivers Specify a database Open a connection to database Submit a query to database Gets the results

13 . What do you mean by batch updates if you want to execute a set of statements, i.e. SQL statements at a time then we use batch update statement. resultset=pst.batchUpdate();

37

14 . Why do we need batch updates Let's say there are 100 records need to be insert. If we execute normal statemets the no of transactions will be 100 (in terms of connection making to DB). using batch updates we can add 100 rec to batch and the no of transactions will be only one in this case. This will reduce the burdon on db, which is very costly in terms of resources. 15 . How do you call a stored procedure from java You can call a stored procedure using Callable statements CallableStatement cs = con.prepareCall("{call StoredProc}"); ResultSet rs = cs.executeQuery(); 16 . What packages are being used by JDBC Following packages are used in JDBC java.sql javax.sql 17 . Explain how to get the resultset of Stored procedure CallableStatement cstmt; ResultSet rs; int i; String s; ... cstmt.execute();// Call the stored procedure 1 rs = cstmt.getResultSet();// Get the first result set 2 while (rs.next()) { // Position the cursor 3 i = rs.getInt(1); // Retrieve current result set value System.out.println("Value from first result set = " + i); // Print the value } cstmt.getMoreResults(); // Point to the second result set 4a // and close the first result set rs = cstmt.getResultSet(); // Get the second result set 4b while (rs.next()) { // Position the cursor 4c s = rs.getString(1); // Retrieve current result set value System.out.println("Value from second result set = " + s); // Print the value } rs.close(); // Close the result set cstmt.close(); // Close the statement

38

18 . What do we use setAutoCommit() for The DML operations by default are committed. If we wish to avoid the commit by default, setAutoCommit(false) has to be called on the Connection object. Once the statements are executed, commit() has to be called on the Connection object explicitly. 19 . Difference between Resultset and Rowset RowSet The interface that adds support to the JDBC API for the JavaBeansTM component model. A rowset, which can be used as a JavaBeans component in a visual Bean development environment, can be created and configured at design time and executed at run time. The RowSet interface provides a set of JavaBeans properties that allow a RowSet instance to be configured to connect to a JDBC data source and read some data from the data source. A group of setter methods (setInt, setBytes, setString, and so on) provide a way to pass input parameters to a rowset's command property. This command is the SQL query the rowset uses when it gets its data from a relational database, which is generally the case. The RowSet interface supports JavaBeans events, allowing other components in an application to be notified when an event occurs on a rowset, such as a change in its value. The RowSet interface is unique in that it is intended to be implemented using the rest of the JDBC API. In other words, a RowSet implementation is a layer of software that executes "on top" of a JDBC driver. Implementations of the RowSet interface can be provided by anyone, including JDBC driver vendors who want to provide a RowSet implementation as part of their JDBC products. A RowSet object may make a connection with a data source and maintain that connection throughout its life cycle, in which case it is called a connected rowset. A rowset may also make a connection with a data source, get data from it, and then close the connection. Such a rowset is called a disconnected rowset. A disconnected rowset may make changes to its data while it is disconnected and then send the changes back to the original source of the data, but it must reestablish a connection to do so. ResultSet A table of data representing a database result set, which is usually generated by executing a statement that queries the database. 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.
39

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. The following code fragment, in which con is a valid Connection object, illustrates how to make a result set that is scrollable and insensitive to updates by others, and that is updatable. See ResultSet fields for other options. 20 . How do we retrieve warning SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the execution of an application, as exceptions do. They simply alert the user that something did not happen as planned. A warning can be reported on a Connection object, a Statement object (including PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these classes has a getWarnings method, which you must invoke in order to see the first warning reported on the calling object. E.g. SQLWarning warning = stmt.getWarnings(); if (warning != null) { while (warning != null) { System.out.println("Message: " + warning.getMessage()); System.out.println("SQLState: " + warning.getSQLState()); System.out.print("Vendor error code: "); System.out.println(warning.getErrorCode()); warning = warning.getNextWarning(); } } >

40

21 . How many statements can we create with one connection There is no such limit on number of statements to be created 22 . How to Make Updates to Updatable Result Sets Using JDBC 2.0 API we have the ability to update rows in a result set. For this we need to create a ResultSet object that is updatable. For this, we pass the ResultSet constant CONCUR_UPDATABLE to the createStatement method. Connection con = DriverManager.getConnection(url, "myLogin", "myPassword"); Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet uprs = stmt.executeQuery("SELECT NAME, SALARY FROM EMPLOYEES"); 23 . How can you move the cursor in scrollable result sets In JDBC 2.0 API we have the ability to move a result set's cursor backward as well as forward. We can also move the cursor to a particular row and check the position of the cursor. Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet srs = stmt.executeQuery("SELECT NAME, SALARY FROM EMPLOYEES"); The first argument is one of three constants added to the ResultSet API to indicate the type of a ResultSet object: TYPE_FORWARD_ONLY, TYPE_SCROLL_INSENSITIVE , and TYPE_SCROLL_SENSITIVE. The second argument is one of two ResultSet constants for specifying whether a result set is read-only or updatable: CONCUR_READ_ONLY and CONCUR_UPDATABLE. Make sure that when you specify a type, you must also specify whether it is read-only or updatable. Specifying the constant TYPE_FORWARD_ONLY creates a nonscrollable result set, that is, one in which the cursor moves only forward. If you do not specify any constants for the type and updatability of a ResultSet object, you will automatically get one that is TYPE_FORWARD_ONLY and CONCUR_READ_ONLY.

41

24 . What's the difference between TYPE_SCROLL_INSENSITIVE , and TYPE_SCROLL_SENSITIVE You will get a scrollable ResultSet object if you specify one of these ResultSet constants.The difference between the two has to do with whether a result set reflects changes that are made to it while it is open and whether certain methods can be called to detect these changes. Generally speaking, a result set that is TYPE_SCROLL_INSENSITIVE does not reflect changes made while it is still open and one that is TYPE_SCROLL_SENSITIVE does. All three types of result sets will make changes visible if they are closed and then reopened: Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet srs = stmt.executeQuery("SELECT NAME, SALARY FROM PERSON"); srs.afterLast(); while (srs.previous()) { String name = srs.getString("NAME"); float salary = srs.getFloat("SALARY"); System.out.println(name + " " + salary); } 25 . How do you insert images in Database using JDBC We can store images in the databse using the BLOB datatype where in the image is stored as a byte stream 26 . What is Metadata It is information about one of two things: Database information (java.sql.DatabaseMetaData), or Information about a specific ResultSet (java.sql.ResultSetMetaData). Use DatabaseMetaData to find information about your database, such as its capabilities and structure. Use ResultSetMetaData to find information about the results of an SQL query, such as size and types of columns 27 . What is a data source A DataSource class brings another level of abstraction than directly using a connection object. Data source can be referenced by JNDI. Data Source may point to RDBMS, file System , any DBMS etc.

42

J2EE-SERVLET
1.What is Servlet? Servlet is a script, which resides and executes on server side, to create dynamic HTML. In servlet programming we will use java language. A servlet can handle multiple requests concurrently 2 . What is the architechture of servlet package? Servlet Interface is the central abstraction. All servlets implements this Servlet Interface either direclty or indirectly ( may implement or extend Servlet Interfaces sub classes or sub interfaces) Servlet | Generic Servlet | HttpServlet ( Class ) -- we will extend this class to handle GET / PUT HTTP requests | MyServlet 3 . What is the difference between HttpServlet and GenericServlet? A GenericServlet has a service() method to handle requests. HttpServlet extends GenericServlet added new methods doGet() doPost() doHead() doPut() doOptions() doDelete() doTrace() methods Both these classes are abstract. 4 . What's the difference between servlets and applets? Servlets executes on Servers. Applets executes on browser. Unlike applets, however, servlets have no graphical user interface. 5 . What are the uses of Servlets? A servlet can handle multiple requests concurrently, and can synchronize requests. Servlets can forward requests to other servers and servlets. Thus servlets can be used to balance load among several servers.

43

6 . When doGET() method will going to execute? When we specified method='GET' in HTML Example : < form name='SSS' method='GET'> 7 . When doPOST() method will going to execute? When we specified method='POST' in HTML < form name='SSS' method='POST' > 8 . What is the difference between Difference between doGet() and doPost()? GET Method : Using get method we can able to pass 2K data from HTML All data we are passing to Server will be displayed in URL (request string). POST Method : In this method we does not have any size limitation. All data passed to server will be hidden, User cannot able to see this info on the browser. 9 . What is the servlet life cycle? When first request came in for the servlet , Server will invoke init() method of the servlet. There after if any user request the servlet program, Server will directly executes the service() method. When Server want to remove the servlet from pool, then it will execute the destroy() method 10 . Which code line must be set before any of the lines that use the PrintWriter? setContentType() method must be set. > 11 . Which protocol will be used by browser and servlet to communicate ? HTTP 12 . In how many ways we can track the sessions? Method 1) By URL rewriting Method 2) Using Session object Getting Session form HttpServletRequest object HttpSession session = request.getSession(true); Get a Value from the session session.getValue(session.getId());
44

Adding values to session cart = new Cart(); session.putValue(session.getId(), cart); At the end of the session, we can inactivate the session by using the following command session.invalidate(); Method 3) Using cookies Method 4) Using hidden fields 13 . How Can You invoke other web resources (or other servlet / jsp ) ? Servelt can invoke other Web resources in two ways: indirect and direct. Indirect Way : Servlet will return the resultant HTML to the browser which will point to another Servlet (Web resource) Direct Way : We can call another Web resource (Servelt / Jsp) from Servelt program itself, by using RequestDispatcher object. You can get this object using getRequestDispatcher("URL") method. You can get this object from either a request or a Context. Example : RequestDispatcher dispatcher = request.getRequestDispatcher("/jspsample.jsp"); if (dispatcher != null) dispatcher.forward(request, response); } 14 . How Can you include other Resources in the Response? Using include method of a RequestDispatcher object. Included WebComponent (Servlet / Jsp) cannot set headers or call any method (for example, setCookie) that affects the headers of the response. Example : RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/banner"); if (dispatcher != null) dispatcher.include(request, response); }

45

15 . What is the difference between the getRequestDispatcher(String path) ServletRequest interface and ServletContext interface? The getRequestDispatcher(String path) method of ServletRequest interface accepts parameter the path to the resource to be included or forwarded to, which can be relative to the request of the calling servlet. If the path begins with a "/" it is interpreted as relative to the current context root. The getRequestDispatcher(String path) method of ServletContext interface cannot accepts relative paths. All path must sart with a "/" and are interpreted as relative to curent context root. If the resource is not available, or if the server has not implemented a RequestDispatcher object for that type of resource, getRequestDispatcher will return null. Your servlet should be prepared to deal with this condition. 16 . What is the use of ServletContext ? Using ServletContext, We can access data from its environment. Servlet context is common to all Servlets so all Servlets share the information through ServeltContext. 17 . Is there any way to generate PDF'S dynamically in servlets? We need to use iText. A open source library for java. Please refer sourceforge site for sample servlet examples. 18 . What is the difference between using getSession(true) and getSession(false) methods? getSession(true) - This method will check whether already a session is existing for the user. If a session is existing, it will return that session object, Otherwise it will create new session object and return taht object. getSession(false) - This method will check existence of session. If session exists, then it returns the reference of that session object, if not, this methods will return null.

46

J2EE-JSP
1.What is JSP?Describs its concepts? JSP is a technology that combines HTML/XML markup languages and elements of Java programming Language to return dynamic content to the Web client, It is normally used to handle Presentation logic of a web application, although it may have business logic. 2 . What are the lifecycle phases of a JSP? JSP page looks like a HTML page but is a servlet. When presented with JSP page the JSP engine does the following 7 phases. 1. 2. 3. 4. 5. 6. 7. Page translation: -page is parsed, and a java file which is a servlet is created. Page compilation: page is compiled into a class file Page loading : This class file is loaded. Create an instance :- Instance of servlet is created jspInit() method is called _jspService is called to handle service calls _jspDestroy is called to destroy it when the servlet is not required.

3 . What is a translation unit? JSP page can include the contents of other HTML pages or other JSP files. This is done by using the include directive. When the JSP engine is presented with such a JSP page it is converted to one servlet class and this is called a translation unit, Things to remember in a translation unit is that page directives affect the whole unit, one variable declaration cannot occur in the same unit more than once, the standard action jsp:useBean cannot declare the same bean twice in one unit. 4 . How is JSP used in the MVC model JSP is usually used for presentation in the MVC pattern (Model View Controller ) i.e. it plays the role of the view. The controller deals with calling the model and the business classes which in turn get the data, this data is then presented to the JSP for rendering on to the client. 5 . What are context initialization parameters Context initialization parameters are specified by the in the web.xml file, these are initialization parameter for the whole application and not specific to any servlet or JSP.

47

6 . What is a output comment A comment that is sent to the client in the viewable page source. The JSP engine handles an output comment as un-interpreted HTML text, returning the comment in the HTML output sent to the client. You can see the comment by viewing the page source from your Web browser. 7 . What is a Hidden Comment A comment that documents the JSP page but is not sent to the client. The JSP engine ignores a hidden comment, and does not process any code within hidden comment tags. A hidden comment is not sent to the client, either in the displayed JSP page or the HTML page source. The hidden comment is useful when you want to hide part of your JSP page. 8 . What is a Expression Expressions are act as place holders for language expression, expression is evaluated each time the page is accessed. 9 . What is a Declaration It declares one or more variables or methods for use later in the JSP source file. A declaration must contain at least one complete declarative statement. You can declare any number of variables or methods within one declaration tag, as long as semicolons separate them. The declaration must be valid in the scripting language used in the JSP file. 10 . What is a Scriptlet A scriptlet can contain any number of language statements, variable or method declarations, or expressions that are valid in the page scripting language. Within scriptlet tags, you can declare variables or methods to use later in the file, write expressions valid in the page scripting language, use any of the JSP implicit objects or any object declared with a <?xml:namespace prefix = jsp />.

11 . What are the implicit objects List them. Certain objects that are available for the use in JSP documents without being declared first. These objects are parsed by the JSP engine and inserted into the generated servlet. The implicit objects are: 1. 2. 3. 4. 5. request response pageContext session application
48

6. 7. 8. 9.

out config page exception

12 . What's the difference between forward and sendRedirect When you invoke a forward request, the request is sent to another resource on the server, without the client being informed that a different resource is going to process the request. This process occurs completely with in the web container And then returns to the calling method. When a sendRedirect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. Because the browser issues a completely new request any object that are stored as request attributes before the redirect occurs will be lost. This extra round trip a redirect is slower than forward. 13 . What are the different scope values for the The different scope values for <?XML:NAMESPACE PREFIX = JSP />are:

1. 2. 3. 4.

page request session application

14 . Why are JSP pages the preferred API for creating a web-based client program Because no plug-ins or security policy files are needed on the client systems(applet does). Also, JSP pages enable cleaner and more module application design because they provide a way to separate applications programming from web page design. This means personnel involved in web page design do not need to understand Java programming language syntax to do their jobs. 15 . Is JSP technology extensible Yes, it is. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries. 16 . What is difference between custom JSP tags and beans Custom JSP tag is a tag you defined. You define how a tag, its attributes and its body are interpreted, and then group your tags into collections called tag libraries that can be used in any number of JSP files. Custom tags and beans accomplish the same goals ?" encapsulating complex behavior into simple and accessible forms. There are several differences:
49

Custom tags can manipulate JSP content; beans cannot. Complex operations can be reduced to a significantly simpler form with custom tags than with

beans. Custom tags require quite a bit more work to set up than do beans. Custom tags usually define relatively self-contained behavior, whereas beans are often defined in one servlet and used in a different servlet or JSP page. Custom tags are available only in JSP 1.1 and later, but beans can be used in all JSP 1.x versions.

17 . How can I implement a thread-safe JSP page? What are the advantages and Disadvantages of using it? You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive <%@ page isThreadSafe="false" %> within your JSP page. With this, instead of a single instance of the servlet generated for your JSP page loaded in memory, you will have N instances of the servlet loaded and initialized, with the service method of each instance effectively synchronized. You can typically control the number of instances (N) that are instantiated for all servlets implementing SingleThreadModel through the admin screen for your JSP engine. More importantly, avoid using the tag for variables. If you do use this tag, then you should set isThreadSafe to true, as mentioned above. Otherwise, all requests to that page will access those variables, causing a nasty race condition. SingleThreadModel is not recommended for normal use. There are many pitfalls, including the example above of not being able to use <%! %>. You should try really hard to make them thread-safe the old fashioned way: by making them thread-safe 18 . How does JSP handle run-time exceptions You can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error processing page. For example: <%@ page errorPage="error.jsp" %> redirects the browser to the JSP page error.jsp if an uncaught exception is encountered during request processing. Within error.jsp, if you indicate that it is an error-processing page, via the directive: <%@ page isErrorPage="true" %> Throwable object describing the exception may be accessed within the error page via the exception implicit object. Note: You must always use a relative URL as the value for the errorPage attribute. 19 . How do I prevent the output of my JSP or Servlet pages from being cached by the browser You will need to set the appropriate HTTP header attributes to prevent the dynamic content output by the JSP page from being cached by the browser. Just execute the following scriptlet at the beginning of your JSP pages to prevent them from being cached at the browser. You need both the statements to take care of some of the older browser versions.
50

<% response.setHeader("Cache-Control","no-store"); //HTTP 1.1 response.setHeader("Pragma","no-cache"); //HTTP 1.0 response.setDateHeader ("Expires", 0); //prevents caching at the proxy server %> 20 . How do I use comments within a JSP page You can use JSP-style comments to selectively block out code while debugging or simply to comment your scriptlets. JSP comments are not visible at the client. For example: <%-- the scriptlet is now commented out <% out.println("Hello World"); %> --%> You can also use HTML-style comments anywhere within your JSP page. These comments are visible at the client. For example: <!-- (c) 2004 --> Of course, you can also use comments supported by your JSP scripting language within your scriptlets. For example, assuming Java is the scripting language, you can have: <% //some comment /** yet another comment **/ %> > 21 . Response has already been commited error. What does it mean This error show only when you try to redirect a page after you already have written something in your page. This happens because HTTP specification force the header to be set up before the lay out of the page can be shown (to make sure of how it should be displayed, content-type="text/html" or "text/xml" or "plain-text" or "image/jpg", etc.) When you try to send a redirect status (Number is line_status_402), your HTTP server cannot send it right now if it hasn't finished to set up the header. If not starter to set up the header, there are no problems, but if it's already begin to set up the header, then
51

your HTTP server expects these headers to be finished setting up and it cannot be the case if the stream of the page is not over.. In this last case it's like you have a file started with some output (like testing your variables.) Before you indicate that the file is over (and before the size of the page can be setted up in the header), you try to send a redirect status. It s simply impossible due to the specification of HTTP 1.0 and 1.1

22 . How do I use a scriptlet to initialize a newly instantiated bean A jsp:useBean action may optionally have a body. If the body is specified, its contents will be automatically invoked when the specified bean is instantiated. Typically, the body will contain scriptlets or jsp:setProperty tags to initialize the newly instantiated bean, although you are not restricted to using those alone. The following example shows the "today" property of the Foo bean initialized to the current date when it is instantiated. Note that here, we make use of a JSP expression within the jsp:setProperty action. value="<%=java.text.DateFormat.getDateInstance().format(new java.util.Date()) %>"/ > <%-- scriptlets calling bean setter methods go here --%>"

23 . How can I enable session tracking for JSP pages if the browser has disabled cookies We know that session tracking uses cookies by default to associate a session identifier with a unique user. If the browser does not support cookies, or if cookies are disabled, you can still enable session tracking using URL rewriting. URL rewriting essentially includes the session ID within the link itself as a name/value pair. However, for this to be effective, you need to append the session ID for each and every link that is part of your servlet response. Adding the session ID to a link is greatly simplified by means of of a couple of methods: response.encodeURL() associates a session ID with a given URL, and if you are using redirection, response.encodeRedirectURL() can be used by giving the redirected URL as input. Both encodeURL() and encodeRedirectedURL() first determine whether cookies are supported by the browser; if so, the input URL is returned unchanged since the session ID will be persisted as a cookie. Consider the following example, in which two JSP files, say hello1.jsp and hello2.jsp, interact with each other. Basically, we create a new session within hello1.jsp and place an object within this session. The user can then traverse to hello2.jsp by clicking on the link present within the page.Within hello2.jsp, we simply extract the object that was earlier placed in the session and display its contents. Notice that we invoke the encodeURL() within hello1.jsp on the link used to invoke hello2.jsp; if cookies are disabled, the session ID is automatically appended to the URL, allowing hello2.jsp to still retrieve the session object. Try this example first with cookies enabled. Then disable cookie support, restart the brower, and try again. Each time you should see the maintenance of the session across pages. Do note that to get this example to work with cookies disabled at the browser,
52

your JSP engine has to support URL rewriting. hello1.jsp <%@ page session="true" %> <% Integer num = new Integer(100); session.putValue("num",num); String url =response.encodeURL("hello2.jsp"); %> hello2.jsp <%@ page session="true" %> <% Integer i= (Integer )session.getValue("num"); out.println("Num value in session is "+i.intValue()); 24 . How can I declare methods within my JSP page You can declare methods for use within your JSP page as declarations. The methods can then be invoked within any other methods you declare, or within JSP scriptlets and expressions. Do note that you do not have direct access to any of the JSP implicit objects like request, response, session and so forth from within JSP methods. However, you should be able to pass any of the implicit JSP variables as parameters to the methods you declare. For example: <%! public String whereFrom(HttpServletRequest req) { HttpSession ses = req.getSession(); ... return req.getRemoteHost(); } %> <% out.print("Hi there, I see that you are coming in from "); %> <%= whereFrom(request) %> Another Example file1.jsp: <%@page contentType="text/html"%> <%! public void test(JspWriter writer) throws IOException{ writer.println("Hello!"); } %> file2.jsp
53

<%@include file="file1.jsp"%>

<%test(out);% > 25 . Is there a way I can set the inactivity lease period on a per-session basis Typically, a default inactivity lease period for all sessions is set within your JSP engine admin screen or associated properties file. However, if your JSP engine supports the Servlet 2.1 API, you can manage the inactivity lease period on a per-session basis. This is done by invoking the HttpSession.setMaxInactiveInterval() method, right after the session has been created. For example: <% session.setMaxInactiveInterval(300); %> would reset the inactivity period for this session to 5 minutes. The inactivity interval is set in seconds. 26 . How can I set a cookie and delete a cookie from within a JSP page A cookie, mycookie, can be deleted using the following scriptlet: <% //creating a cookie Cookie mycookie = new Cookie("aName","aValue"); response.addCookie(mycookie); //delete a cookie Cookie killMyCookie = new Cookie("mycookie", null); killMyCookie.setMaxAge(0); killMyCookie.setPath("/"); response.addCookie(killMyCookie); %> 27 . How does a servlet communicate with a JSP page The following code snippet shows how a servlet instantiates a bean and initializes it with FORM data posted by a browser. The bean is then placed into the request, and the call is then forwarded to the JSP page, Bean1.jsp, by means of a request dispatcher for downstream processing. public void doPost (HttpServletRequest request, HttpServletResponse response) { try { govi.FormBean f = new govi.FormBean(); String id = request.getParameter("id"); f.setName(request.getParameter("name")); f.setAddr(request.getParameter("addr"));
54

f.setAge(request.getParameter("age")); //use the id to compute //additional bean properties like info //maybe perform a db query, etc. // . . . f.setPersonalizationInfo(info); request.setAttribute("fBean",f); getServletConfig().getServletContext().getRequestDispatcher ("/jsp/Bean1.jsp").forward(request, response); } catch (Exception ex) { ... } } The JSP page Bean1.jsp can then process fBean, after first extracting it from the default request scope via the useBean action. jsp:useBean id="fBean" class="govi.FormBean" scope="request" / jsp:getProperty name="fBean" property="name" / jsp:getProperty name="fBean" property="addr" / jsp:getProperty name="fBean" property="age" / jsp:getProperty name="fBean" property="personalizationInfo" / 28 . How do I have the JSP-generated servlet subclass my own custom servlet class, instead of the default One should be very careful when having JSP pages extend custom servlet classes as opposed to the default one generated by the JSP engine. In doing so, you may lose out on any advanced optimization that may be provided by the JSP engine. In any case, your new superclass has to fulfill the contract with the JSP engine by: Implementing the HttpJspPage interface, if the protocol used is HTTP, or implementing JspPage otherwise Ensuring that all the methods in the Servlet interface are declared final Additionally, your servlet superclass also needs to do the following: The service() method has to invoke the _jspService() method The init() method has to invoke the jspInit() method The destroy() method has to invoke jspDestroy() If any of the above conditions are not satisfied, the JSP engine may throw a translation error. Once the superclass has been developed, you can have your JSP extend it as follows: <%@ page extends="packageName.ServletName" %>
55

29 . How can I prevent the word "null" from appearing in my HTML input text fields when I populate them with a resultset that has null values You could make a simple wrapper function, like <%! String blanknull(String s) { return (s == null) ? "" : s; } %> then use it inside your JSP form, like <input type="text" name="shoesize" value="<%=blanknull(shoesize)% >" > 30 . How can I get to print the stacktrace for an exception occuring within my JSP page By printing out the exception?Ts stack trace, you can usually diagonse a problem better when debugging JSP pages. By looking at a stack trace, a programmer should be able to discern which method threw the exception and which method called that method. However, you cannot print the stacktrace using the JSP out implicit variable, which is of type JspWriter. You will have to use a PrintWriter object instead. The following snippet demonstrates how you can print a stacktrace from within a JSP error page: <%@ page isErrorPage="true" %> <% out.println(" "); PrintWriter pw = response.getWriter(); exception.printStackTrace(pw); out.println(" "); %> > 31 . How do you pass an InitParameter to a JSP The JspPage interface defines the jspInit() and jspDestroy() method which the page writer can use in their pages and are invoked in much the same manner as the init() and destory() methods of a servlet. The example page below enumerates through all the parameters and prints them to the console. <%@ page import="java.util.*" %> <%! ServletConfig cfg =null; public void jspInit(){ ServletConfig cfg=getServletConfig(); for (Enumeration e=cfg.getInitParameterNames(); e.hasMoreElements();) {
56

String name=(String)e.nextElement(); String value = cfg.getInitParameter(name); System.out.println(name+"="+value); } } %> 32 . How can my JSP page communicate with an EJB Session Bean The following is a code snippet that demonstrates how a JSP page can interact with an EJB session bean: <%@ page import="javax.naming.*, javax.rmi.PortableRemoteObject, foo.AccountHome, foo.Account" %> <%! //declare a "global" reference to an instance of the home interface of the session bean AccountHome accHome=null; public void jspInit() { //obtain an instance of the home interface InitialContext cntxt = new InitialContext( ); Object ref= cntxt.lookup("java:comp/env/ejb/AccountEJB"); accHome = (AccountHome)PortableRemoteObject.narrow(ref,AccountHome.class); } %> <% //instantiate the session bean Account acct = accHome.create(); //invoke the remote methods acct.doWhatever(...); // etc etc... %> 33 . Can we implement an interface in a JSP No 34 . What is the difference between ServletContext and PageContext ServletContext: Gives the information about the container. PageContext: Gives the information about the Request

57

35 . What is the difference in using request.getRequestDispatcher() and context.getRequestDispatcher() request.getRequestDispatcher(path): In order to create it we need to give the relative path of the resource, context.getRequestDispatcher(path): In order to create it we need to give the absolute path of the resource. 36 . How to pass information from JSP to included JSP Using <%jsp:param> tag. 37 . What is the difference between directive include and jsp include <%@ include>: Used to include static resources during translation time. JSP include: Used to include dynamic content or static content during runtime. 38 . What is the difference between RequestDispatcher and sendRedirect RequestDispatcher: server-side redirect with request and response objects. sendRedirect : Client-side redirect with new request and response objects. 39 . How do I mix JSP and SSI #include If you're just including raw HTML, use the #include directive as usual inside your .jsp file. But it's a little trickier if you want the server to evaluate any JSP code that's inside the included file. If your data.inc file contains jsp code you will have to use <%@ vinclude="data.inc" %> The is used for including non-JSP files.

J2EE-EJB
58

1.What is EJP? EJB stands for Enterprise JavaBean and is a widely-adopted server side component architecture for J2EE. It enables rapid development of mission-critical application that are versatile, reusable and portable across middleware while protecting IT investment and preventing vendor lock-in. 2 . What is session Facade? Session Facade is a design pattern to access the Entity bean through local interface than accessing directly. It increases the performance over the network. In this case we call session bean which on turn call entity bean. 3 . What is EJB role in J2EE? EJB technology is the core of J2EE. It enables developers to write reusable and portable server-side business logic for the J2EE platform. 4 . What is the difference between EJB and Java beans? EJB is a specification for J2EE server, not a product; Java beans may be a graphical component in IDE 5 . What are the key features of the EJB technology? 1. EJB components are server-side components written entirely in the Java programming language 2. EJB components contain business logic only - no system-level programming & services, such as transactions, security, life-cycle, threading, persistence, etc. are automatically managed for the EJB component by the EJB server. 3. EJB architecture is inherently transactional, distributed, portable multi-tier, scalable and secure. 4. EJB components are fully portable across any EJB server and any OS. 5. EJB architecture is wire-protocol neutral--any protocol can be utilized like IIOP,JRMP, HTTP, DCOM,etc. 6 . What are the key benefits of the EJB technology? 1. Rapid application development 2. Broad industry adoption 3. Application portability 4. Protection of IT investment 7 . How many enterprise beans? There are three kinds of enterprise beans: 1. session beans, 2. entity beans, and 3. message-driven beans.
59

8 . What is message-driven bean? A message-driven bean combines features of a session bean and a Java Message Service (JMS) message listener, allowing a business component to receive JMS. A message-driven bean enables asynchronous clients to access the business logic in the EJB tier. 9 . What is Entity Bean and Session Bean ? Entity Bean is a Java class which implements an Enterprise Bean interface and provides the implementation of the business methods. There are two types: Container Managed Persistence(CMP) and Bean-Managed Persistence(BMP). Session Bean is used to represent a workflow on behalf of a client. There are two types: Stateless and Stateful. Stateless bean is the simplest bean. It doesn't maintain any conversational state with clients between method invocations. Stateful bean maintains state between invocations. 10 . How EJB Invocation happens? Retrieve Home Object reference from Naming Service via JNDI. Return Home Object reference to the client. Create me a new EJB Object through Home Object interface. Create EJB Object from the Ejb Object. Return EJB Object reference to the client. Invoke business method using EJB Object reference. Delegate request to Bean (Enterprise Bean). > 11 . Is it possible to share an HttpSession between a JSP and EJB? What happens when I change a value in the HttpSession from inside an EJB? You can pass the HttpSession as parameter to an EJB method, only if all objects in session are serializable.This has to be consider as passed-by-value, that means that it's read-only in the EJB. If anything is altered from inside the EJB, it won't be reflected back to the HttpSession of the Servlet Container.The pass-by-reference can be used between EJBs Remote Interfaces, as they are remote references. While it is possible to pass an HttpSession as a parameter to an EJB object, it is considered to be bad practice in terms of object-oriented design. This is because you are creating an unnecessary coupling between back-end objects (EJBs) and front-end objects (HttpSession). Create a higher-level of abstraction for your EJBs API. Rather than passing the whole, fat, HttpSession (which carries with it a bunch of http semantics), create a class that acts as a value object (or structure) that holds all the data you need to pass back and forth between front-end/back-end. Consider the case where your EJB needs to support a non HTTP-based client. This higher level of abstraction will be flexible enough to support it.

60

12 . The EJB container implements the EJBHome and EJBObject classes. For every request from a unique client, does the container create a separate instance of the generated EJBHome and EJBObject classes? The EJB container maintains an instance pool. The container uses these instances for the EJB Home reference irrespective of the client request. while refering the EJB Object classes the container creates a separate instance for each client request. The instance pool maintenance is up to the implementation of the container. If the container provides one, it is available otherwise it is not mandatory for the provider to implement it. Having said that, yes most of the container providers implement the pooling functionality to increase the performance of the application server. The way it is implemented is, again, up to the implementer. 13 . Can the primary key in the entity bean be a Java primitive type such as int? The primary key can't be a primitive type. Use the primitive wrapper classes, instead. For example, you can use java.lang.Integer as the primary key class, but not int (it has to be a class, not a primitive). 14 . Can you control when passivation occurs? The developer, according to the specification, cannot directly control when passivation occurs. Although for Stateful Session Beans, the container cannot passivate an instance that is inside a transaction. So using transactions can be a a strategy to control passivation. The ejbPassivate() method is called during passivation, so the developer has control over what to do during this exercise and can implement the require optimized logic. Some EJB containers, such as BEA WebLogic, provide the ability to tune the container to minimize passivation calls. Taken from the WebLogic 6.0 DTD -The passivation-strategy can be either default or transaction. With the default setting the container will attempt to keep a working set of beans in the cache. With the transaction setting, the container will passivate the bean after every transaction (or method call for a non-transactional invocation). 15 . What is the advantage of using Entity bean for database operations, over directly using JDBC API to do database operations? When would I use one over the other? Entity Beans actually represents the data in a database. It is not that Entity Beans replaces JDBC API. There are two types of Entity Beans Container Managed and Bean Mananged. In Container Managed Entity Bean - Whenever the instance of the bean is created the container automatically retrieves the data from the DB/Persistance storage and assigns to the object variables in bean for user to manipulate or use them. For this the developer needs to map the fields in the database to the variables in deployment descriptor files (which varies for each vendor). In the Bean Managed Entity Bean - The developer has to specifically make connection, retrive values, assign them to the objects in the ejbLoad() which will be called by the container when it instatiates a bean object. Similarly in the ejbStore() the container saves the object values back the the persistance storage. ejbLoad and ejbStore
61

are callback methods and can be only invoked by the container. Apart from this, when you use Entity beans you dont need to worry about database transaction handling, database connection pooling etc. which are taken care by the ejb container. 16 . What is EJB QL? EJB QL is a Query Language provided for navigation across a network of enterprise beans and dependent objects defined by means of container managed persistence. EJB QL is introduced in the EJB 2.0 specification. The EJB QL query language defines finder methods for entity beans with container managed persistenceand is portable across containers and persistence managers. EJB QL is used for queries of two types of finder methods: Finder methods that are defined in the home interface of an entity bean and which return entity objects. Select methods, which are not exposed to the client, but which are used by the Bean Provider to select persistent values that are maintained by the Persistence Manager or to select entity objects that are related to the entity bean on which the query is defined. 17 . Brief description about local interfaces? EJB was originally designed around remote invocation using the Java Remote Method Invocation (RMI) mechanism, and later extended to support to standard CORBA transport for these calls using RMI/IIOP. This design allowed for maximum flexibility in developing applications without consideration for the deployment scenario, and was a strong feature in support of a goal of component reuse in J2EE. Many developers are using EJBs locally, that is, some or all of their EJB calls are between beans in a single container. With this feedback in mind, the EJB 2.0 expert group has created a local interface mechanism. The local interface may be defined for a bean during development, to allow streamlined calls to the bean if a caller is in the same container. This does not involve the overhead involved with RMI like marshalling etc. This facility will thus improve the performance of applications in which co-location is planned. Local interfaces also provide the foundation for container-managed relationships among entity beans with container-managed persistence. 18 . What are the special design care that must be taken when you work with local interfaces? It is important to understand that the calling semantics of local interfaces are different from those of remote interfaces. For example, remote interfaces pass parameters using call-by-value semantics, while local interfaces use call-by-reference. This means that in order to use local interfaces safely, application developers need to carefully consider potential deployment scenarios up front, then decide which interfaces can be local and which remote, and finally, develop the application code with these choices in mind. While EJB 2.0 local interfaces are extremely useful in some situations, the long-term costs of these choices, especially when changing requirements and component reuse are taken into account, need to be factored into the design decision.

62

19 . What happens if remove( ) is never invoked on a session bean? In case of a stateless session bean it may not matter if we call or not as in both cases nothing is done. The number of beans in cache is managed by the container. In case of stateful session bean, the bean may be kept in cache till either the session times out, in which case the bean is removed or when there is a requirement for memory in which case the data is cached and the bean is sent to free pool. 20 . What is the difference between Message Driven Beans and Stateless Session beans? In several ways, the dynamic creation and allocation of message-driven bean instances mimics the behavior of stateless session EJB instances, which exist only for the duration of a particular method call. However, message-driven beans are different from stateless session EJBs (and other types of EJBs) in several significant ways: Message-driven beans process multiple JMS messages asynchronously, rather than processing a serialized sequence of method calls. Message-driven beans have no home or remote interface, and therefore cannot be directly accessed by internal or external clients. Clients interact with message-driven beans only indirectly, by sending a message to a JMS Queue or Topic. Only the container directly interacts with a message-driven bean by creating bean instances and passing JMS messages to those instances as necessary. The Container maintains the entire lifecycle of a message-driven bean; instances cannot be created or removed as a result of client requests or other API calls 21 . How can I call one EJB from inside of another EJB? EJBs can be clients of other EJBs. It just works. Use JNDI to locate the Home Interface of the other bean, then acquire an instance reference, and so forth. 22 . What is an EJB Context? EJBContext is an interface that is implemented by the container, and it is also a part of the beancontainer contract. Entity beans use a subclass of EJBContext called EntityContext. Session beans use a subclass called SessionContext. These EJBContext objects provide the bean class with information about its container, the client using the bean and the bean itself. They also provide other functions. See the API docs and the spec for more details. 23 . Is it possible for an EJB client to marshal an object of class java.lang.Class to an EJB? Technically yes, spec. compliant NO! - The enterprise bean must not attempt to query a class to obtain information about the declared members that are not otherwise accessible to the enterprise bean because of the security rules of the Java language.

63

24 . Is it legal to have static initializer blocks in EJB? Although technically it is legal, static initializer blocks are used to execute some piece of code before executing any constructor or method while instantiating a class. Static initializer blocks are also typically used to initialize static fields - which may be illegal in EJB if they are read/write - In EJB this can be achieved by including the code in either the ejbCreate(), setSessionContext() or setEntityContext() methods. 25 . Is it possible to stop the execution of a method before completion in a SessionBean? Stopping the execution of a method inside a Session Bean is not possible without writing code inside the Session Bean. This is because you are not allowed to access Threads inside an EJB. 26 . What is the default transaction attribute for an EJB? There is no default transaction attribute for an EJB. Section 11.5 of EJB v1.1 spec says that the deployer must specify a value for the transaction attribute for those methods having container managed transaction. In WebLogic, the default transaction attribute for EJB is SUPPORTS. 27 . What is the difference between session and entity beans? When should I use one or the other? An entity bean represents persistent global data from the database; a session bean represents transient user-specific data that will die when the user disconnects (ends his session). Generally, the session beans implement business methods (e.g. Bank.transferFunds) that call entity beans (e.g. Account.deposit, Account.withdraw) 28 . Is there any default cache management system with Entity beans ? In other words whether a cache of the data in database will be maintained in EJB ? - Caching data from a database inside the AAApplication Server are what Entity EJB's are used for.The ejbLoad() and ejbStore() methods are used to synchronize the Entity Bean state with the persistent storage(database). Transactions also play an important role in this scenario. If data is removed from the database, via an external application - your Entity Bean can still be alive the EJB container. When the transaction commits, ejbStore() is called and the row will not be found, and the transaction rolled back. 29 . Why is ejbFindByPrimaryKey mandatory? An Entity Bean represents persistent data that is stored outside of the EJB Container/Server. The ejbFindByPrimaryKey is a method used to locate and load an Entity Bean into the container, similar to a SELECT statement in SQL. By making this method mandatory, the client programmer can be assured that if they have the primary key of the Entity Bean, then they can retrieve the bean without having to
64

create a new bean each time - which would mean creating duplications of persistent data and break the integrity of EJB. 30 . Why do we have a remove method in both EJBHome and EJBObject? With the EJBHome version of the remove, you are able to delete an entity bean without first instantiating it (you can provide a PrimaryKey object as a parameter to the remove method). The home version only works for entity beans. On the other hand, the Remote interface version works on an entity bean that you have already instantiated. In addition, the remote version also works on session beans (stateless and stateful) to inform the container of your loss of interest in this bean. > 31 . How can I call one EJB from inside of another EJB? EJBs can be clients of other EJBs. It just works. Use JNDI to locate the Home Interface of the other bean, then acquire an instance reference, and so forth. 32 . What is the difference between a Server, a Container, and a Connector? An EJB server is an application, usually a product such as BEA WebLogic, that provides (or should provide) for concurrent client connections and manages system resources such as threads, processes, memory, database connections, network connections, etc. An EJB container runs inside (or within) an EJB server, and provides deployed EJB beans with transaction and security management, etc. The EJB container insulates an EJB bean from the specifics of an underlying EJB server by providing a simple, standard API between the EJB bean and its container. A Connector provides the ability for any Enterprise Information System (EIS) to plug into any EJB server which supports the Connector architecture. See Sun's J2EE Connectors for more in-depth information on Connectors. 33 . How is persistence implemented in enterprise beans? Persistence in EJB is taken care of in two ways, depending on how you implement your beans: container managed persistence (CMP) or bean managed persistence (BMP) For CMP, the EJB container which your beans run under takes care of the persistence of the fields you have declared to be persisted with the database - this declaration is in the deployment descriptor. So, anytime you modify a field in a CMP bean, as soon as the method you have executed is finished, the new data is persisted to the database by the container. For BMP, the EJB bean developer is responsible for defining the persistence routines in the proper places in the bean, for instance, the ejbCreate(), ejbStore(), ejbRemove() methods would be developed by the bean developer to make calls to the database. The container is responsible, in BMP, to call the appropriate method on the bean. So, if the bean is being looked up, when the create() method is called on the Home interface, then the container is responsible
65

for calling the ejbCreate() method in the bean, which should have functionality inside for going to the database and looking up the data. 34 . What is an EJB Context? EJBContext is an interface that is implemented by the container, and it is also a part of the beancontainer contract. Entity beans use a subclass of EJBContext called EntityContext. Session beans use a subclass called SessionContext. These EJBContext objects provide the bean class with information about its container, the client using the bean and the bean itself. They also provide other functions. See the API docs and the spec for more details. 35 . Is method overloading allowed in EJB? Yes you can overload methods 36 . Should synchronization primitives be used on bean methods? No. The EJB specification specifically states that the enterprise bean is not allowed to use thread primitives. The container is responsible for managing concurrent access to beans at runtime. 37 . Are we allowed to change the transaction isolation property in middle of a transaction? No. You cannot change the transaction isolation level in the middle of transaction. 38 . For Entity Beans, What happens to an instance field not mapped to any persistent storage, when the bean is passivated? The specification infers that the container never serializes an instance of an Entity bean (unlike stateful session beans). Thus passivation simply involves moving the bean from the ready to the pooled bin. So what happens to the contents of an instance variable is controlled by the programmer. Remember that when an entity bean is passivated the instance gets logically disassociated from it's remote object. Be careful here, as the functionality of passivation/activation for Stateless Session, Stateful Session and Entity beans is completely different. For entity beans the ejbPassivate method notifies the entity bean that it is being disassociated with a particular entity prior to reuse or for dereference. 39 . What is a Message Driven Bean, what functions does a message driven bean have and how do they work in collaboration with JMS? Message driven beans are the latest addition to the family of component bean types defined by the EJB specification. The original bean types include session beans, which contain business logic and maintain a state associated with client sessions, and entity beans, which map objects to persistent data.
66

Message driven beans will provide asynchrony to EJB based applications by acting as JMS message consumers. A message bean is associated with a JMS topic or queue and receives JMS messages sent by EJB clients or other beans. Unlike entity beans and session beans, message beans do not have home or remote interfaces. Instead, message driven beans are instantiated by the container as required. Like stateless session beans, message beans maintain no client-specific state, allowing the container to optimally manage a pool of message-bean instances. Clients send JMS messages to message beans in exactly the same manner as they would send messages to any other JMS destination. This similarity is a fundamental design goal of the JMS capabilities of the new specification. To receive JMS messages, message driven beans implement the javax.jms.MessageListener interface, which defines a single onMessage() method. When a message arrives, the container ensures that a message bean corresponding to the message topic/queue exists (instantiating it if necessary), and calls its onMessage method passing the client's message as the single argument. The message bean's implementation of this method contains the business logic required to process the message. Note that session beans and entity beans are not allowed to function as message beans. 40 . Does RMI-IIOP support code downloading for Java objects sent by value across an IIOP connection in the same way as RMI does across a JRMP connection? Yes. The JDK 1.2 support the dynamic class loading. The EJB container implements the EJBHome and EJBObject classes. For every request from a unique client 41 . Does the container create a separate instance of the generated EJBHome and EJBObject classes? The EJB container maintains an instance pool. The container uses these instances for the EJB Home reference irrespective of the client request. while refering the EJB Object classes the container creates a separate instance for each client request. The instance pool maintainence is up to the implementation of the container. If the container provides one, it is available otherwise it is not mandatory for the provider to implement it. Having said that, yes most of the container providers implement the pooling functionality to increase the performance of the application server. The way it is implemented is again up to the implementer 42 . What is the advantage of putting an Entity Bean instance from the Ready State to Pooled state? The idea of the Pooled State is to allow a container to maintain a pool of entity beans that has been created, but has not been yet synchronized or assigned to an EJBObject. This mean that the instances do represent entity beans, but they can be used only for serving Home methods (create or findBy), since those methods do not relay on the specific values of the bean. All these instances are, in fact, exactly the same, so, they do not have meaningful state. Jon Thorarinsson has also added: It can be looked at it this way: If no client is using an entity bean of a particular type there is no need for cachig it (the data is
67

persisted in the database). Therefore, in such cases, the container will, after some time, move the entity bean from the Ready State to the Pooled state to save memory. Then, to save additional memory, the container may begin moving entity beans from the Pooled State to the Does Not Exist State, because even though the bean's cache has been cleared, the bean still takes up some memory just being in the Pooled State.

J2EE-JMS
1.What is JMS? Java Message Service: An interface implemented by most J2EE containers to provide point-to-point queueing and topic (publish/subscribe) behavior. JMS is frequently used by EJB's that need to start another process asynchronously. For example, instead of sending an email directly from an Enterprise JavaBean, the bean may choose to put the message onto a JMS queue to be handled by a Message-Driven Bean (another type of EJB) or another system in the enterprise. This technique allows the EJB to return to handling requests immediately instead of waiting for a potentially lengthy process to complete. 2 . What are the advantages of JMS? You can use it in the context of mutithreading but it means JMS is not meant for Multithreading. Its basically meant for object communication. It will be useful when you are writing some event based applications like Chat Server which needs a publish kind of event mechanism to send messages between the server to the clients who got connected with the server. Moreover JMS gives Loosely-coupled kind of mechanism when compared with RMI which is tightlycoupled. In JMS there is no need for the destination object to be available online while sending a message from the client to the server. But in RMI it is necessary. So we can use JMS in place of RMI where we need to have loosely-coupled mechanism. 3 . What are major JMS products available in the market? IBM's MQ Series, SonicMQ, iBus etc. All the J2EE compliant application servers come built with thier own implementation of JMS. 4 . What are the different types of messages available in the JMS API?

68

Message, TextMessage, BytesMessage, StreamMessage, ObjectMessage, MapMessage are the different messages available in the JMS API. 5 . What is the difference between Point to Point and Publish/Subscribe Messaging Domains 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 In a publish/subscribe (pub/sub) product or application, clients address messages to a topic. 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. 6 . What is the diffrence between JAVA Mail and JMS Queue Java Mail - API siting on top of email protocols like SMTP, POP, IMAP - essentially same stuff e-mail clients like MS outlook use .. hence make sense if at least on one side of conversation we have human. JMS Queue - is asynchronous point-to-point communication between systems 7 . What is the difference between ic and queue? A ic is typically used for one to many messaging i.e. it supports publish subscribe model of messaging. While queue is used for one-to-one messaging i.e. it supports Point to Point Messaging. 8 . What is the role of JMS in enterprise solution development? JMS is typically used in the following scenarios 1. Enterprise Application Integration: - Where a legacy application is integrated with a new application via messaging. 2. B2B or Business to Business: - Businesses can interact with each other via messaging because JMS allows organizations to cooperate without tightly coupling their business systems. 3. Geographically dispersed units: - JMS can ensure safe exchange of data amongst the geographically dispersed units of an organization. 4. One to many applications: - The applications that need to push data in packet to huge number of clients in a one-to-many fashion are good candidates for the use JMS. Typical such applications are Auction Sites, Stock Quote Services etc. 9 . What is the use of Message object?

69

Message is a light weight message having only header and properties and no payload. Thus if the receivers are to be notified about an event, and no data needs to be exchanged then using Message can be very efficient. 10 . What are the three components of a Message ? A JMS message consists of three parts: Message header For message identification. For example, the header is used to determine if a given message is appropriate for a "subscriber" Properties For application-specific, provider-specific, and optional header fields Body Holds the content of the message. Several formats are supported, including TextMessage, which wrap a simple String, that wrap arbitrary Java objects (which must be serializable). Other formats are supported as well. > 11 . What kind of information found in the header of a Message ? The header of a message contains message identification and routing information. This includes , but is not limited to : JMSDestination JMSDeliveryMode JMSMessageID JMSTimeStamp JMSExpiration JMSReplyTO JMSCorrelationID JMSType JMSRedelivered 12 . What is the basic difference between Publish Subscribe model and P2P model? Publish Subscribe model is typically used in one-to-many situation. It is unreliable but very fast. P2P model is used in one-to-one situation. It is highly reliable. 13 . What is the use of BytesMessage? BytesMessage contains an array of primitive bytes in it's payload. Thus it can be used for transfer of data between two applications in their native format which may not be compatible with other Message
70

types. It is also useful where JMS is used purely as a transport between two systems and the message payload is opaque to the JMS client. Whenever you store any primitive type, it is converted into it's byte representation and then stored in the payload. There is no boundary line between the different data types stored. Thus you can even read a long as short. This would result in erroneous data and hence it is advisable that the payload be read in the same order and using the same type in which it was created by the sender. 14 . What is the use of StreamMessage? StreamMessage carries a stream of Java primitive types as it's payload. It contains some conveient methods for reading the data stored in the payload. However StreamMessage prevents reading a long value as short, something that is allwed in case of BytesMessage. This is so because the StreamMessage also writes the type information alonwgith the value of the primitive type and enforces a set of strict conversion rules which actually prevents reading of one primitive type as another. 15 . What is the use of TextMessage? TextMessage contains instance of java.lang.String as it's payload. Thus it is very useful for exchanging textual data. It can also be used for exchanging complex character data such as an XML document. 16 . What is the use of ObjectMessage? ObjectMessage contains a Serializable java object as it's payload. Thus it allows exchange of Java objects between applications. This in itself mandates that both the applications be Java applications. The consumer of the message must typecast the object received to it's appropriate type. Thus the consumer should before hand know the actual type of the object sent by the sender. Wrong type casting would result in ClassCastException. Moreover the class definition of the object set in the payload should be available on both the machine, the sender as well as the consumer. If the class definition is not available in the consumer machine, an attempt to type cast would result in ClassNotFoundException. Some of the MOMs might support dynamic loading of the desired class over the network, but the JMS specification does not mandate this behavior and would be a value added service if provided by your vendor. And relying on any such vendor specific functionality would hamper the portability of your application. Most of the time the class need to be put in the classpath of both, the sender and the consumer, manually by the developer.

17 . What is the use of MapMessage? A MapMessage carries name-value pair as it's payload. Thus it's payload is similar to the java.util.Properties object of Java. The values can be Java primitives or their wrappers.
71

18 . What is the difference between BytesMessage and StreamMessage? BytesMessage stores the primitive data types by converting them to their byte representation. Thus the message is one contiguous stream of bytes. While the StreamMessage maintains a boundary between the different data types stored because it also stores the type information along with the value of the primitive being stored. BytesMessage allows data to be read using any type. Thus even if your payload contains a long value, you can invoke a method to read a short and it will return you something. It will not give you a semantically correct data but the call will succeed in reading the first two bytes of data. This is strictly prohibited in the StreamMessage. It maintains the type information of the data being stored and enforces strict conversion rules on the data being read. 19 . What is point-to-point messaging? With point-to-point message passing the sending application/client establishes a named message queue in the JMS broker/server and sends messages to this queue. The receiving client registers with the broker to receive messages posted to this queue. There is a one-to-one relationship between the sending and receiving clients.

20 . Can two different JMS services talk to each other? For instance, if A and B are two different JMS providers, can Provider A send messages directly to Provider B? If not, then can a subscriber to Provider A act as a publisher to Provider B? The answers are no to the first question and yes to the second. The JMS specification does not require that one JMS provider be able to send messages directly to another provider. However, the specification does require that a JMS client must be able to accept a message created by a different JMS provider, so a message received by a subscriber to Provider A can then be published to Provider B. One caveat is that the publisher to Provider B is not required to handle a JMSReplyTo header that refers to a destination that is specific to Provider A. > 21 . What is the advantage of persistent message delivery compared to nonpersistent delivery? If the JMS server experiences a failure, for example, a power outage, any message that it is holding in primary storage potentially could be lost. With persistent storage, the JMS server logs every message to secondary storage. (The logging occurs on the front end, that is, as part of handling the send operation from the message producing client.) The logged message is removed from secondary storage only after it has been successfully delivered to all consuming clients . 22 . Give an example of using the publish/subscribe model.
72

JMS can be used to broadcast shutdown messages to clients connected to the Weblogic server on a module wise basis. If an application has six modules, each module behaves like a subscriber to a named ic on the server. 23 . Why doesn't the JMS API provide end-to-end synchronous message delivery and notification of delivery? Some messaging systems provide synchronous delivery to destinations as a mechanism for implementing reliable applications. Some systems provide clients with various forms of delivery notification so that the clients can detect dropped or ignored messages. This is not the model defined by the JMS API. JMS API messaging provides guaranteed delivery via the once-and-only-once delivery semantics of PERSISTENT messages. In addition, message consumers can ensure reliable processing of messages by using either CLIENT_ACKNOWLEDGE mode or transacted sessions. This achieves reliable delivery with minimum synchronization and is the enterprise messaging model most vendors and developers prefer. The JMS API does not define a schema of systems messages (such as delivery notifications). If an application requires acknowledgment of message receipt, it can define an application-level acknowledgment message. 24 . What are the various message types supported by JMS? Stream Messages -- Group of Java Primitives Map Messages -- Name Value Pairs. Name being a string& Value being a java primitive Text Messages -- String messages (since being widely used a separate messaging Type has been supported) Object Messages -- Group of serialize able java object Bytes Message -- Stream of uninterrupted bytes 25 . How is a java object message delivered to a non-java Client? It is according to the specification that the message sent should be received in the same format. A non-java client cannot receive a message in the form of java object. The provider in between handles the conversion of the data type and the message is transferred to the other end. 26 . What is MDB and What is the special feature of that? MDB is Message driven bean, which very much resembles the Stateless session bean. The incoming and out going messages can be handled by the Message driven bean. The ability to communicate asynchronously is the special feature about the Message driven bean.

73

27 . What are the types of messaging? There are two kinds of Messaging. Synchronous Messaging: Synchronous messaging involves a client that waits for the server to respond to a message. Asynchronous Messaging: Asynchronous messaging involves a client that does not wait for a message from the server. An event is used to trigger a message from a server. 28 . What are the core JMS-related objects required for each JMS-enabled application? Each JMS-enabled client must establish the following: . A connection object provided by the JMS server (the message broker) . Within a connection, one or more sessions, which provide a context for message sending and receiving . Within a session, either a queue or ic object representing the destination (the message staging area) within the message broker . Within a session, the appropriate sender or publisher or receiver or subscriber object (depending on whether the client is a message producer or consumer and uses a point-to-point or publish/subscribe strategy, respectively) Within a session, a message object (to send or to receive)

74

J2EE-Structs
1.Describs jakarata Structs Framwork? It implements Model-View-Controller pattern in the framework and it is an open source code. It saves time in design and implementation of a web based application due to this framework and pattern as I is highly robust, scalable and reliable. 2 . What are the components of Struts? Struts is based on the MVC design pattern. Struts components can be categories into Model, View and Controller. Model: Components like business logic / business processes and data are the part of Model. View: JSP, HTML etc. are part of View Controller: Action Servlet of Struts is part of Controller components which works as front controller to handle all the requests. 3 . Describe is ActionServlet ActionServlet provides the "controller" in the Model-View-Controller (MVC) design pattern for web applications that is commonly known as "Model 2". This nomenclature originated with a description in the JavaServerPages Specification, version 0.92, and has persisted ever since (in the absence of a better name).Controller is responsible for handling all the requests. 4 . What is an Action Class used for? 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 (ActionServlet) will select an appropriate Action for each request, create an instance (if necessary), and call the perform method. Actions must be programmed in a thread-safe manner, because the controller will share the same instance for multiple simultaneous requests. In this means you should design with the following items in mind: . Instance and static variables MUST NOT be used to store information related to the state of a particular request. They MAY be used to share global resources across requests for the same action. . Access to other resources (JavaBeans, session variables, etc.) MUST be synchronized if those resources require protection. (Generally, however, resource classes should be designed to provide their own protection where necessary. When an Action instance is first created, the controller servlet will call setServlet() with a non-null argument to identify the controller servlet instance to which this Action is attached. When the controller 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.

75

5 . What is ActionForm? An ActionForm is a JavaBean optionally associated with one or more ActionMappings. Such a bean will have had its properties initialized from the corresponding request parameters before the corresonding action's perform() method is called. When the properties of this bean have been populated, but before the perform() method of the action is called, this bean's validate() method will be called, which gives the bean a chance to verify that the properties submitted by the user are correct and valid. If this method finds problems, it returns an error messages object that encapsulates those problems, and the controller servlet will return control to the corresponding input form. Otherwise, the validate() method returns null(), indicating that everything is acceptable and the corresponding Action's perform() method should be called. This class must be subclassed in order to be instantiated. Subclasses should provide property getter and setter methods for all of the bean properties they wish to expose, plus override any of the public or protected methods for which they wish to provide modified functionality. 6 . What is Struts Validator Framework? Struts Framework provides the functionality to validate the form data. It can be use to validate the data on the users browser as well as on the server side. Struts Framework emits the java scripts and it can be used validate the form data on the client browser. Server side validation of form can be accomplished by sub classing your From Bean with DynaValidatorForm class. 7 . What are the core classes of the Struts Framework? Core classes of Struts Framework are ActionForm, Action, ActionMapping, ActionForward, ActionServlet etc. 8 . What are Tag Libraries provided with Struts? Struts provides a number of tag libraries that helps to create view components easily. These tag libraries are: a) Bean Tags: Bean Tags are used to access the beans and their properties. b) HTML Tags: HTML Tags provides tags for creating the view components like forms, buttons, etc.. c) Logic Tags: Logic Tags provides presentation logics that eliminate the need for scriptlets. d) Nested Tags: Nested Tags helps to work with the nested context. 9 . What are difference between ActionErrors and ActionMessage? ActionMessage: A class that encapsulates messages. Messages can be either global or they are specific to a particular bean property. Each individual message is described by an ActionMessage object, which contains a message key (to be looked up in an appropriate message resources database), and up to four placeholder arguments used
76

for parametric substitution in the resulting message. ActionErrors: A class that encapsulates the error messages being reported by the validate() method of an ActionForm. Validation errors are either global to the entire ActionForm bean they are associated with, or they are specific to a particular bean property (and, therefore, a particular input field on the corresponding form). 10 . How you will handle exceptions in Struts? In Struts you can handle the exceptions in two ways: a) Declarative Exception Handling: You can either define global exception handling tags in your strutsconfig.xml or define the exception handling tags within .. tag. Example: key="database.error.duplicate" path="/UserExists.jsp" type="mybank.account.DuplicateUserException"/> b) Programmatic Exception Handling: Here you can use try{}catch{} block to handle the exception. > 11 . Can I setup Apache Struts to use multiple configuration files? Yes Struts can use multiple configuration files. Here is the configuration example: <servlet> <servlet-name>banking</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> <init-param> <param-name>config</param-name> <param-value>/WEB-INF/struts-config.xml, /WEB-INF/struts-authentication.xml, /WEB-INF/struts-help.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> 12 . How you will make available any Message Resources Definitions file to the Struts Framework Environment? Message Resources Definitions file are simple .properties files and these files contains the messages that can be used in the struts project. Message Resources Definitions files can be added to the strutsconfig.xml file through tag.

77

13 . What is Struts Flow? Struts Flow is a port of Cocoon's Control Flow to Struts to allow complex workflow, like multi-form wizards, to be easily implemented using continuations-capable JavaScript. It provides the ability to describe the order of Web pages that have to be sent to the client, at any given point in time in an application. The code is based on a proof-of-concept Dave Johnson put together to show how the Control Flow could be extracted from Cocoon. (Ref: http://struts.sourceforge.net/struts-flow/index.html ) 14 . What is LookupDispatchAction? An abstract Action that dispatches to the subclass mapped execute method. This is useful in cases where an HTML form has multiple submit buttons with the same name. The button name is specified by the parameter property of the corresponding ActionMapping. 15 . What do you understand by DispatchAction? DispatchAction is an action that comes with Struts 1.1 or later, that lets you combine Struts actions into one class, each with their own method. The org.apache.struts.action.DispatchAction class allows multiple operation to mapped to the different functions in the same Action class. For example: A package might include separate RegCreate, RegSave, and RegDelete Actions, which just perform different operations on the same RegBean object. Since all of these operations are usually handled by the same JSP page, it would be handy to also have them handled by the same Struts Action. A very simple way to do this is to have the submit button modify a field in the form which indicates which operation to perform.

<?XML:NAMESPACE PREFIX = HTML />SAVE SAVE AS NEW DELETE Then, in the Action you can setup different methods to handle the different operations, and branch to one or the other depending on which value is passed in the dispatch field. String dispatch = myForm.getDispatch(); if ("create".equals(dispatch)) { ... if ("save".equals(dispatch)) { ... The Struts Dispatch Action [org.apache.struts.actions] is designed to do exactly the same thing, but without messy branching logic. The base perform method will check a dispatch field for you, and invoke the indicated method. The only catch is that the dispatch methods must use the same signature as perform. This is a very modest requirement, since in practice you usually end up doing that anyway. To convert an Action that was switching on a dispatch field to a DispatchAction, you simply need to
78

create methods like this public ActionForward create( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { ... public ActionForward save( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { ... Cool. But do you have to use a property named dispatch? No, you don't. The only other step is to specify the name of of the dispatch property as the "parameter" property of the action-mapping. So a mapping for our example might look like this: path="/reg/dispatch" type="app.reg.RegDispatch" name="regForm" scope="request" validate="true" parameter="dispatch"/> If you wanted to use the property "o" instead, as in o=create, you would change the mapping to path="/reg/dispatch" type="app.reg.RegDispatch" name="regForm" scope="request" validate="true" parameter="o"/> Again, very cool. But why use a JavaScript button in the first place? Why not use several buttons named "dispatch" and use a different value for each? You can, but the value of the button is also its label. This means if the page designers want to label the button something different, they have to coordinate the Action programmer. Localization becomes virtually impossible.

79

16 . Is struts threadsafe?Give an example? Struts is not only thread-safe but thread-dependant. The response to a request is handled by a lightweight Action object, rather than an individual servlet. Struts instantiates each Action class once, and allows other requests to be threaded through the original object. This core strategy conserves resources and provides the best possible throughput. A properly-designed application will exploit this further by routing related operations through a single Action 17 . What are the uses of tiles-def.xml file, resourcebundle.properties file, validation.xml file? tiles-def.xml is is an xml file used to configure tiles with the struts application. You can define the layout / header / footer / body content for your View. 18 . What is the difference between perform() and execute() methods? Perform method is the method which was deprecated in the Struts Version 1.1. In Struts 1.x, Action.perform() is the method called by the ActionServlet. This is typically where your business logic resides, or at least the flow control to your JavaBeans and EJBs that handle your business logic. As we already mentioned, to support declarative exception handling, the method signature changed in perform. Now execute just throws Exception. Action.perform() is now deprecated; however, the Struts v1.1 ActionServlet is smart enough to know whether or not it should call perform or execute in the Action, depending on which one is available. 19 . What is Struts actions and action mappings? A Struts action is an instance of a subclass of an Action class, which implements a portion of a Web application and whose perform or execute method returns a forward. An action can perform tasks such as validating a user name and password. An action mapping is a configuration file entry that, in general, associates an action name with an action. An action mapping can contain a reference to a form bean that the action can use, and can additionally define a list of local forwards that is visible only to this action. An action servlet is a servlet that is started by the servlet container of a Web server to process a request that invokes an action. The servlet receives a forward from the action and asks the servlet container to pass the request to the forward's URL. An action servlet must be an instance of an org.apache.struts.action.ActionServlet class or of a subclass of that class. An action servlet is the primary component of the controller. 20 . How Struts relates to J2EE? Struts framework is built on J2EE technologies (JSP, Servlet, Taglibs), but it is itself not part of the J2EE standard.
80

J2EE-JSF
1.What is java-server Faces? JavaServer Faces (JSF) is a user interface (UI) framework for Java web applications. It is designed to significantly ease the burden of writing and maintaining applications that run on a Java application server and render their UIs back to a target client. JSF provides ease-of-use in the following ways: Makes it easy to construct a UI from a set of reusable UI components Simplifies migration of application data to and from the UI Helps manage UI state across server requests Provides a simple model for wiring client-generated events to server-side application code Allows custom UI components to be easily built and re-used

Most importantly, JSF establishes standards which are designed to be leveraged by tools to provide a developer experience which is accessible to a wide variety of developer types, ranging from corporate developers to systems programmers. A "corporate developer" is characterized as an individual who is proficient in writing procedural code and business logic, but is not necessarily skilled in object-oriented programming. A "systems programmer" understands object-oriented fundamentals, including abstraction and designing for re-use. A corporate developer typically relies on tools for development, while a system programmer may define his or her tool as a text editor for writing code. Therefore, JSF is designed to be tooled, but also exposes the framework and programming model as APIs so that it can be used outside of tools, as is sometimes required by systems programmers. 2 . How to pass a parameter to the JSF application using the URL string? if you have the following URL: http://your_server/your_app/product.jsf?id=777, you access the passing parameter id with the following lines of java code:

FacesContext fc = FacesContext.getCurrentInstance(); String id = (String) fc.getExternalContext().getRequestParameterMap().get("id"); From the page, you can access the same parameter using the predefined variable with name param. For example, <h:outputText value="#{param['id']}" /> Note: You have to call the jsf page directly and using the servlet mapping.

81

3 . How to add context path to URL for outputLink? Current JSF implementation does not add the context path for outputLink if the defined path starts with '/'. To correct this problem use #{facesContext.externalContext.requestContextPath} prefix at the beginning of the outputLink value attribute. For example: <h:outputLink value="#{facesContext.externalContext.requestContextPath}/myPage.faces"> 4 . How to get current page URL from backing bean? You can get a reference to the HTTP request object via FacesContext like this: FacesContext fc = FacesContext.getCurrentInstance(); HttpServletRequest request = (HttpServletRequest) fc.getExternalContext().getRequest(); and then use the normal request methods to obtain path information. Alternatively, context.getViewRoot().getViewId(); will return you the name of the current JSP (JSF view IDs are basically just JSP path names). 5 . How to access web.xml init parameters from java code? You can get it using externalContext getInitParameter method. For example, if you have: <context-param> <param-name>connectionString</param-name> <paramvalue>jdbc:oracle:thin:scott/tiger@cartman:1521:O901DB</param-value></context-param> You can access this connection string with:

FacesContext fc = FacesContext.getCurrentInstance(); String connection = fc.getExternalContext().getInitParameter("connectionString"); 6 . How to terminate the session? In order to terminate the session you can use session invalidate method. This is an example how to terminate the session from the action method of a backing bean: public String logout() { FacesContext fc = FacesContext.getCurrentInstance(); HttpSession session = (HttpSession) fc.getExternalContext().getSession(false); session.invalidate(); return "login_page"; }
82

The following code snippet allows to terminate the session from the jsp page: <% session.invalidate(); %> <c:redirect url="loginPage.jsf" /> 7 . How to implement "Please, Wait..." page? The client-side solution might be very simple. You can wrap the jsp page (or part of it you want to hide) into the DIV, then you can add one more DIV that appears when user clicks the submit button. This DIV can contain the animated gif you speak about or any other content. Scenario: when user clicks the button, the JavaScript function is called. This function hides the page and shows the "Wait" DIV. You can customize the look-n-fill with CSS if you like. This is a working example: <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <f:loadBundle basename="demo.bundle.Messages" var="Message"/> <html> <head> <title>Input Name Page</title> <script> function gowait() { document.getElementById("main").style.visibility="hidden"; document.getElementById("wait").style.visibility="visible"; } </script> </head> <body bgcolor="white"> <f:view> <div id="main"> <h1><h:outputText value="#{Message.inputname_header}"/></h1> <h:messages style="color: red"/> <h:form id="helloForm"> <h:outputText value="#{Message.prompt}"/> <h:inputText id="userName" value="#{GetNameBean.userName}" required="true"> <f:validateLength minimum="2" maximum="20"/> </h:inputText> <h:commandButton onclick="gowait()" id="submit" action="#{GetNameBean.action}" value="Say Hello" />
83

</h:form> </div> <div id="wait" style="visibility:hidden; position: absolute; top: 0; left: 0"> <table width="100%" height ="300px"> <tr> <td align="center" valign="middle"> <h2>Please, wait...</h2> </td> </tr> </table> </div> </f:view> </body> </html>

If you want to have an animated gif of the "Wait" Page, the gif should be reloaded after the form is just submitted. So, assign the id for your image and then add reload code that will be called after some short delay. For the example above, it might be: <script> function gowait() { document.getElementById("main").style.visibility="hidden"; document.getElementById("wait").style.visibility="visible"; window.setTimeout('showProgress()', 500); } function showProgress(){ var wg = document.getElementById("waitgif"); wg.src=wg.src; } </script> .... .... .... <img id="waitgif" src="animated.gif"> 8 . How to reload the page after ValueChangeListener is invoked? At the end of the ValueChangeListener, call FacesContext.getCurrentInstance().renderResponse()

84

9 . How to download PDF file with JSF? This is an code example how it can be done with action listener of the backing bean. Add the following method to the backing bean: public void viewPdf(ActionEvent event) { String filename = "filename.pdf"; // use your own method that reads file to the byte array byte[] pdf = getTheContentOfTheFile(filename); FacesContext faces = FacesContext.getCurrentInstance(); HttpServletResponse response = (HttpServletResponse) faces.getExternalContext().getResponse(); response.setContentType("application/pdf"); response.setContentLength(pdf.length); response.setHeader( "Content-disposition", "inline; filename=\""+fileName+"\""); try { ServletOutputStream out; out = response.getOutputStream(); out.write(pdf); } catch (IOException e) { e.printStackTrace(); } faces.responseComplete(); } This is a jsp file snippet: <h:commandButton immediate="true" actionListener="#{backingBean.viewPdf}" value="Read PDF" /> 10 . How to show Confirmation Dialog when user Click the Command Link? h:commandLink assign the onclick attribute for internal use. So, you cannot use it to write your own code. This problem will fixed in the JSF 1.2. For the current JSF version you can use onmousedown event that occurs before onclick. <script language="javascript"> function ConfirmDelete(link) { var delete = confirm('Do you want to Delete?'); if (delete == true) { link.onclick(); } } </script> . . . . <h:commandLink action="delete" onmousedown="return ConfirmDelete(this);"> <h:outputText value="delete it"/> </h:commandLink> >
85

11 . What is the different between getRequestParameterMap() and getRequestParameterValuesMap() getRequestParameterValuesMap() similar to getRequestParameterMap(), but contains multiple values for for the parameters with the same name. It is important if you one of the components such as <h:selectMany>. 12 . Is it possible to have more than one Faces Configuration file? Yes. You can define the list of the configuration files in the web.xml. This is an example: <context-param> <param-name>javax.faces.CONFIG_FILES</param-name> <paramvalue>/WEB-INF/faces-config-navigation.xml,/WEB-INF/faces-beans.xml</param-value></contextparam> Note: Do not register /WEB-INF/faces-config.xml file in the web.xml . Otherwise, the JSF implementation will process it twice. 13 . How to mask actual URL to the JSF page? You'll need to implement your own version of javax.faces.ViewHandler which does what you need. Then, you register your own view handler in faces-config.xml. Here's a simple abstract ViewHandler you can extend and then implement the 3 abstract methods for. The abstract methods you override here are where you'll do your conversions to/from URI to physical paths on the file system. This information is just passed right along to the default ViewHandler for JSF to deal with in the usual way. For example, you could override these methods to add and remove the file extension of an incoming view id (like in your example), for extension-less view URIs.

import java.io.IOException; import java.util.Locale; import javax.faces.FacesException; import javax.faces.application.ViewHandler; import javax.faces.component.UIViewRoot; import javax.faces.context.FacesContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /**
86

* A facade view handler which maps URIs into actual physical views that the * underlying implementation can deal with regularly. * * Therefore, all internal references to view ids, for example in faces-config, * will use the path to the physical files. Everything publicized, however, will * see a "converted" / facade url. */ public abstract class SimpleConverterViewHandler extends ViewHandler { private static final Log LOG = LogFactory .getLog(SimpleConverterViewHandler.class); private final ViewHandler base; public SimpleConverterViewHandler(ViewHandler base) { this.base = base; } /** * Distinguishes a URI from a physical file view. * * Tests if a view id is in the expected format -- the format corresponding * to the physical file views, as opposed to the URIs. * * This test is necessary because JSF takes the view ID from the * faces-config navigation, and calls renderView() on it, etc. */ public abstract boolean isViewFormat(FacesContext context, String viewId); /** * Convert a private file path (view id) into a public URI. */ public abstract String convertViewToURI(FacesContext context, String viewId); /** * Convert a public URI into a private file path (view id) * * note: uri always starts with "/"; */ public abstract String convertURIToView(FacesContext context, String uri);

87

public String getActionURL(FacesContext context, String viewId) { // NOTE: this is used for FORM actions. String newViewId = convertViewToURI(context, viewId); LOG.debug("getViewIdPath: " + viewId + "->" + newViewId); return base.getActionURL(context, newViewId); } private String doConvertURIToView(FacesContext context, String requestURI) { if (isViewFormat(context, requestURI)) { return requestURI; } else { return convertURIToView(context, requestURI); } } public void renderView(FacesContext context, UIViewRoot viewToRender) throws IOException, FacesException { if (null == context || null == viewToRender) throw new NullPointerException("null context or view"); String requestURI = viewToRender.getViewId(); String newViewId = doConvertURIToView(context, requestURI); LOG.debug("renderView: " + requestURI + "->" + newViewId); viewToRender.setViewId(newViewId); base.renderView(context, viewToRender); } public UIViewRoot restoreView(FacesContext context, String viewId) { String newViewId = doConvertURIToView(context, viewId); LOG.debug("restoreView: " + viewId + "->" + newViewId); return base.restoreView(context, newViewId); } public Locale calculateLocale(FacesContext arg0) { return base.calculateLocale(arg0);
88

} public String calculateRenderKitId(FacesContext arg0) { return base.calculateRenderKitId(arg0); } public UIViewRoot createView(FacesContext arg0, String arg1) { return base.createView(arg0, arg1); } public String getResourceURL(FacesContext arg0, String arg1) { return base.getResourceURL(arg0, arg1); } public void writeState(FacesContext arg0) throws IOException { base.writeState(arg0); } } 14 . How to print out html markup with h:outputText? The h:outputText has attribute escape that allows to escape the html markup. By default, it equals to "true". It means all the special symbols will be replaced with '&' codes. If you set it to "false", the text will be printed out without ecsaping. For example, <h:outputText value="<b>This is a text</b>"/> will be printed out like: <b>This is a text</b> In case of <h:outputText escape="false" value="<b>This is a text</b>"/> you will get: This is a text 15 . h:inputSecret field becomes empty when page is reloaded. How to fix this? Set redisplay=true, it is false by default.

89

J2EE-RMI
1.Explain RMI Architecture? RMI uses a layered architecture, each of the layers could be enhanced or replaced without affecting the rest of the system. The details of layers can be summarised as follows: Application Layer: The client and server program Stub & Skeleton Layer: Intercepts method calls made by the client/redirects these calls to a remote RMI service. Remote Reference Layer: Understands how to interpret and manage references made from clients to the remote service objects. Transport layer: Based on TCP/IP connections between machines in a network. It provides basic connectivity, as well as some firewall penetration strategies. 2 . Explain about RMI and it's usage RMI is one of the distributed computing technology alternative powered by Java . RMI stands for Remote Method Invocation ,to keep it simple it means accessing a service from different node ( i.e., accessing a service provided by an object on server machine , here an object in client JVM talks with object in the server JVM ). Java provides an API and base some classes ( in package java.rmi ) to perform these kind of operations . We basically use this methodology when we need to publish an object at server side which exposes set of services ( as methods in Object oriented programming terminology ) and where in one or more clients access these services from remote machines. By this we are distibuting a common code in two different JVM's and we are able to access the code on different JVM. 3 . How do RMI clients contact remote RMI servers? For an RMI client to contact a remote RMI server, the client must first hold a reference to the server. The Naming.lookup method call is the most common mechanism by which clients initially obtain references to remote servers. Remote references may be obtained by other means, for example: all remote method calls can return remote references. This is what Naming.lookup does; it uses a wellknown stub to make a remote method call to the rmiregistry, which sends back the remote reference to the object requested by the lookup method. Every remote reference contains a server hostname and port number that allow clients to locate the VM that is serving a particular remote object. Once an RMI client has a remote reference, the client will use the hostname and port provided in the reference to open a socket connection to the remote server. Please note that with RMI the terms client and server can refer to the same program. A Java program that acts as an RMI server contains an exported remote object. An RMI client is a program that invokes one or more methods on a remote object in another virtual machine. If a VM performs both of these functions, it may be referred to as an RMI client and an RMI server.
90

4 . Why do I get the exception "java.net.SocketException: Address already in use" when I try to run the registry? This exception means that the port that the RegistryImpl uses (by default 1099) is already in use. You may have another registry running on your machine and will need to stop it. 5 . How can I make outgoing RMI calls through a local firewall? There are three main methods: HTTP tunnelling, SOCKS, and downloaded socket factories. HTTP tunnelling This well-worn method is popular since it requires almost no setup, and works quite well in firewalled environments which permit you to handle HTTP through a proxy, but disallow regular outbound TCP connections. If RMI fails to make a normal (or SOCKS) connection to the intended server, and it notices that a HTTP proxy server is configured, it will attempt to tunnel RMI requests through that proxy server, one at a time. There are two forms of HTTP tunnelling, tried in order. The first is http-to-port; the second is http-tocgi. In http-to-port tunneling, RMI attempts a HTTP POST request to a http: URL directed at the exact hostname and port number of the target server. The HTTP request contains a single RMI request. If the HTTP proxy accepts this URL, it will forward the POST request to the listening RMI server, which will recognize the request and unwrap it. The result of the call is wrapped in a HTTP reply, which is returned through the same proxy. Often, HTTP proxies will refuse to proxy requests to unusual port numbers. In this case, RMI will fall back to http-to-cgi tunneling. The RMI request is encapsulated in a HTTP POST request as before, but the request URL is of the form http://hostname:80/cgi-bin/java-rmi.cgi?port=n (where hostname and n are the hostname and port number of the intended server). There must be a HTTP server listening on port 80 on the server host, which will run the java-rmi.cgi script (supplied with the JDK), which will in turn forward the request to an RMI server listening on port n. RMI can unwrap a HTTP-tunneled request without help from a http server, CGI script, or any other external entity. So, if the client's HTTP proxy can connect directly to the server's port, then you don't need a java-rmi.cgi script at all. To trigger the use of HTTP tunneling, the standard system property http.proxyHost must be set to the hostname of the local HTTP proxy. (There are reports that some Navigator versions do not set this property.) The major disadvantage of HTTP tunneling is that it does not permit inward calls or multiplexed connections. A secondary disadvantage is that the http-to-cgi method opens a dramatic security hole on the server side, since without modification it will redirect any incoming request to any port.

91

SOCKS The default implementation of sockets in the JDK will use a SOCKS server if available and configured. The system property socksProxyHost must have been set to the hostname of the SOCKS server; if the port number of the SOCKS server is not 1080, it must be specified in the socksProxyPort property. This approach would appear to be the most generally useful solution. As yet, ServerSockets do not use SOCKS, so incoming calls must use another mechanism. Downloaded socket factories This is an innovation in the Java 2 SDK, allowing the server to specify the socket factory that the clients must use. The clients must be running Java 2 SDK, Standard Edition, v1.2 or later. See the tutorial Using a Custom RMI Socket Factory for details. The disadvantage of this approach is that the traversal of the firewall must be done by code provided by the RMI server side, which does not necessarily know how that traversal must be done, nor does it automatically have sufficient privilege to traverse the firewall. 6 . How can I receive incoming RMI calls through a local firewall? There are three main methods: known ports, transport-level bridges, and application-level proxies. Known Ports If the exported objects are all exported on a known port on a known host, then that host and port can be explicitly permitted at the firewall. Normally, RMI asks for port 0 (which is code for "any port"). In the Java 2 SDK, there is an extra argument to the exportObject method to specify the exact port number. In JDK v1.1, the server must subclass the RMISocketFactory and intercept requests to createServerSocket(0), replacing it with a request to bind to a specific port number. This approach has the disadvantage that it requires the assistance of the network administrator responsible for the local firewall. If the exported object is being run in a different location (because code was downloaded to that site), then the local firewall may be run by network administrators who don't know who you are. Transport-level bridges A transport-level bridge is a program that reads bytes from one TCP connection and writes them to another (and vice versa) without knowing or caring what the bytes represent. The idea here is to export objects in such a way that anyone outside the firewall who wants to call remote methods on that object instead contacts a different port (perhaps on a different machine). That different port has a running program which makes a second connection to the real server and then pumps bytes each way. The tricky part is convincing the client to connect to the bridge. A downloadable socket factory (Java 2 SDK, v1.2 or later) can do this efficiently; otherwise, it is possible to set the java.rmi.server.hostname property to name the bridge host and arrange for port numbers to be the same.

92

Application-level proxies This approach is quite a bit of work, but leads to a very secure arrangement. A proxy program runs on a firewall host (one which can be accessed from outside as well as inside). When an internal server intends to make an exported object available to the world, it contacts the proxy server and gives it a remote reference. The proxy server creates a proxy object (a new remote object residing in the proxy server) which implements the same remote interfaces as the original. The proxy server returns a remote reference for the new proxy object to the internal server, which communicates it to the outside world (somehow). When an outsider makes a call on the proxy, the proxy immediately forwards the call to its original object on the internal server. The use of the proxy is transparent to the outsider (but not to the internal server, who has to decide whether to pass the original reference or the proxy reference when talking to anyone). Needless to say, this requires considerable setup and the cooperation of the local network administrators. 7 . Does RMI handle "out" and "inout" parameters (like CORBA)? RMI does not support "out" or "inout" parameters, just like the rest of the core Java programming language. All remote calls are methods of a remote object. Local objects are passed by copy and remote objects are passed by reference to a stub. 8 . Normally in the Java programming language, it is possible to cast an interface instance to an instance of the class from which it was created and use the result. Why doesn't this work in RMI? In RMI the client sees only a stub for the original object. The stub implements only the remote interfaces and their remote methods and cannot be cast back to the original implementation class because it's just a stub. So, you cannot pass a remote object reference from a server to a client, and then send it back to the server and be able to cast it back to the original implementation class. You can, though, use the remote object reference on the server to make a remote call to the object. If you need to find the implementation class again, you'll need to keep a table that maps the remote reference to the implementation class. 9 . What is the difference between RMI & Corba ? The most significant difference between RMI and CORBA is that CORBA was made specifically for interoperability across programming languages. That is CORBA fosters the notion that programs can be built to interact in multiple languages. The server could be written in C++, the business logic in Python, and the front-end written in COBOL in theory. RMI, on the other hand is a total Java solution, the interfaces, the implementations and the clients--all are written in Java.
93

RMI allows dynamic loading of classes at runtime. In a multi-language CORBA environment, dynamic class loading is not possible. The important advantage to dynamic class loading is that it allows arguments to be passed in remote invocations that are subtypes of the declared types. In CORBA, all types have to be known in advance. RMI (as well as RMI/IIOP) provides support for polymorphic parameter passing, whereas strict CORBA does not. CORBA does have support for multiple languages which is good for some applications, but RMI has the advantage of being dynamic, which is good for other applications.

10 . What are the services in RMI ? An RMI "service" could well be any Java method that can be invoked remotely. The other service is the JRMP RMI naming service which is a lookup service. > 11 . Does RMI-IIOP support code downloading for Java objects sent by value across an IIOP connection in the same way as RMI does across a JRMP connection? Yes. The JDK 1.2 and above support the dynamic class loading. 12 . How many types of protocol implementations does RMI have? RMI has at least three protocol implementations: Java Remote Method Protocol(JRMP), Internet Inter ORB Protocol(IIOP), and Jini Extensible Remote Invocation(JERI). These are alternatives, not part of the same thing, All three are indeed layer 6 protocols for those who are still speaking OSI reference model. 13 . Does RMI-IIOP support dynamic downloading of classes? No, RMI-IIOP doesn't support dynamic downloading of the classes as it is done with CORBA in DII (Dynamic Interface Invocation).Actually RMI-IIOP combines the usability of Java Remote Method Invocation (RMI) with the interoperability of the Internet Inter-ORB Protocol (IIOP).So in order to attain this interoperability between RMI and CORBA,some of the features that are supported by RMI but not CORBA and vice versa are eliminated from the RMI-IIOP specification. 14 . Can RMI and Corba based applications interact ? Yes they can. RMI is available with IIOP as the transport protocol instead of JRMP

94

15 . Explain lazy activation Lazy activation of remote objects is implemented using a faulting remote reference (sometimes referred to as a fault block). A faulting remote reference to a remote object "faults in" the active object's reference upon the first method invocation to the object. Each faulting reference maintains both a persistent handle (an activation identifier) and a transient remote reference to the target remote object. The remote object's activation identifier contains enough information to engage a third party in activating the object. The transient reference is the actual "live" reference to the active remote object that can be used to contact the executing object. In a faulting reference, if the live reference to a remote object is null, the target object is not known to be active. Upon method invocation, the faulting reference (for that object) engages in the activation protocol to obtain a "live" reference, which is a remote reference (such as a unicast remote reference) for the newly-activated object. Once the faulting reference obtains the live reference, the faulting reference forwards method invocations to the underlying remote reference which, in turn, forwards the method invocation to the remote object. In more concrete terms, a remote object's stub contains a "faulting" remote reference type that contains both: an activation identifier for a remote object, and a "live" reference (possibly null) containing the "active" remote reference type of the remote object (for example, a remote reference type with unicast semantics). 16 . Why does the RMI implementation create so many sockets when my application uses custom socket factories; or why are stubs (using a custom socket factory) that refer to the same remote object not equal; or why does the RMI implementation not reuse server-side ports when I use a custom server socket factory? The RMI implementation attempts to reuse open sockets where possible for remote invocations. When a remote method is invoked on a stub that uses a custom socket factory, the RMI implementation will reuse an open connection (if any) as long as that socket was created by an equivalent socket factory. Since client socket factories are serialized to clients, a single client may have several distinct copies of the same logical socket factory. To ensure that the RMI implementation will reuse sockets created by custom socket factories, make sure your custom client socket factory classes implement the hashCode and equals methods appropriately. If the client socket factory does not implement these methods correctly, another ramification is that stubs (using the client socket factory) that refer to the same remote object will not be equal. The RMI implementation attempts to reuse server-side ports as well. It will only do so if there is an existing server socket for the port created by an equivalent socket factory. Make sure the server socket factory class implements the hashCode and equals methods too. If your socket factory has no instance state, a trivial implementation of the hashCode and equals methods are the following:
95

public int hashCode() { return 57; } public boolean equals(Object o) { return this.getClass() == o.getClass() }

17 . What is difference RMI registry and OSAgent ? RMI Registry The rmiregistry command creates and starts a remote object registry on the specified port on the current host. If port is omitted, the registry is started on port 1099. The rmiregistry command produces no output and is typically run in the background. For example: start rmiregistry A remote object registry is a bootstrap naming service that is used by RMI servers on the same host to bind remote objects to names. Clients on local and remote hosts can then look up remote objects and make remote method invocations. The registry is typically used to locate the first remote object on which an application needs to invoke methods. That object in turn will provide application-specific support for finding other objects. The methods of the java.rmi.registry.LocateRegistry class are used to get a registry operating on the local host or local host and port. The URL-based methods of the java.rmi.Naming class operate on a registry and can be used to look up a remote object on any host, and on the local host: bind a simple (string) name to a remote object, rebind a new name to a remote object (overriding the old binding), unbind a remote object, and list the URLs bound in the registry. OSAgent The osagent is a process that allows CORBA servers to register their objects and assists client applications in the location of objects. To avoid a single point of failure, the osagent is designed to be operated on more than one node. Osagent processes (and the clients and servers that access them) follow a set of rules to discover each other and cooperate in the location of registered objects. 18 . Difference in between Unicast and Multicast object ? A unicast packet is the complete opposite: one machine is talking to only one other machine. All TCP connections are unicast, since they can only have one destination host for each source host. UDP packets are almost always unicast too, though they can be sent to the broadcast address so that they reach every single machine in some cases. A multicast packet is from one machine to one or more. The difference between a multicast packet and a broadcast packet is that hosts receiving multicast packets can be on different lans, and that each multicast data-stream is only transmitted between networks once, not once per machine on the remote

96

network. Rather than each machine connecting to a video server, the multicast data is streamed pernetwork, and multiple machines just listen-in on the multicast data once it's on the network. 19 . What is the main functionality of the Remote Reference Layer ? RRL exists in both the RMI client and server. It is used by the stub or skeleton protocol layer and uses the transport layer. RRL is reponsible for transport-independent functioning of RMI, such as connection management or unicast/multicast object invocation.

J2EE Performance
1 . What are common optimizing practices for a class? Use primitive data types instead of objects as instance variables Keep constructors simple and inheritance hierarchies shallow Avoid initializing instance variable more than once Eliminate unnecessary type casts Enumerators are faster than Iterators due to the specific implementation Ints are the fastest datatype Use static variables for fields that only need to be assigned once Final classes can be faster Use interfaces, so that the actual underlying data structure can be actually changed without impacting the client program Null out references when they are no longer needed so that gc can collect them when it is running. Avoid character processing using methods like charAt(), setCharAt() methods Use local variables in preference to class variables Compound operators such as n += 4; are faster than n = n + 4; because fewer bytecodes are generated. Shifting by powers of two is faster than multiplying. Multiplication is faster than exponentiation. int increments are faster than byte or short increments. Floating point increments are much slower than any integral increment. It can help to copy slower-access vars to fast local vars if you are going to operate on them repeatedly, as in a loop. For some applications that access the date a lot, it can help to set the local timezone to be GMT, so that no conversion has to take place. Minimize creation of short-lived objects. Avoid excessive writing to the Java console Minimize the number of JNI calls Avoid unnecessary instanceof operation
97

Avoid using long divides. Persistency adds overheads that make persistent objects slower. Use pipelining and parallelism. Designing applications to support lots of parallel processes working on easily distinguished subsets of the work makes the application faster. If there are multiple steps to processing, try to design your application so that subsequent steps can start working on the portion of data that any prior process has finished, instead of having to wait until the prior process is complete. Use bitshift instead of multiplying or dividing by powers of 2. Scope of variables can impact performance. Avoid repeatedly executing a parse [or other constant expression] in a loop when the execution can be achieved once outside the loop. Use exception only where you need them

2 . How do you optimize methods in a class? Avoid creating temporary objects within frequently called methods Define methods that accept reusable objects to be filled in with data, rather than methods that return objects holding that data. Use methods that alter objects without making copies Eliminate repeatedly called methods where alternatives are possible [For example, if you are processing a vector in a loop, get the size of the vector in the beginning in a length local variable rather than calling size() method on the vector in the condition part of the for loop] Use private and static methods and final classes to encourage inlining by the compiler Inline methods manually where it is appropriate Keep methods short and simple to make them automatic inlining candidates Access to private member by the inner classes to the enclosing class goes by a method call even if it is not intended to. Keep synchronized methods out of loops if you possibly can.

3 . How do you optimize loops and conditional statements? Reduce the number of temporary objects being used,especially in loops. Use short-circuit Boolean operators instead of normal Boolean operators Eliminate unnecessary repeated method calls from loops Move loop invariants outside the loop. Perform the loop backwards (this actually performs slightly faster than forward loops do). [Actually it is converting the test to compare against 0 that makes the difference]. It can help to copy slower-access vars to fast local vars if you are going to operate on them repeatedly, as in a loop.
98

Use exception terminated infinite loops for long loops. Whatever can be calculated outside of a loop should be calculated outside of the loop. For multidimensional arrays store a reference for the currently accessed row in a variable. Cache the size of the collection in a local variable to use in a loop instead of repeatedly calling collection.size().

4 . How do you optimize Strings? Use StringBuffer instead of String concat '+' operator Formatting numbers using java.text.DecimalFormat is always slower than Double.toString(double) method, because internally java.text.DecimalFormat() calls Double.toString(double) then parses and converts the results. Convert String to char[] arrays to process characters rather than accessing one at a time using String.charAt() method Creating Double from string is slow Intern() Strings to enable (==) comparisions Use char arrays for all character processing in loops, rather than using String or StringBuffer classes Set the initial string buffer size to maximum if it known. StringTokenizer is very inefficient, and can be optimized by storing the string and delimiter in a character array instead of in String DON'T create static strings via new(). Where the compiler cannot resolve concatenated strings at compile time, the code should be converted to StringBuffer appends, and the StringBuffer should be appropriately sized rather than using the default size. The compiler concatenates strings where they are fully resolvable, so don t move these concatenations to runtime with StringBuffer. 5 . How do you optimize arrays, vectors and collections? Create copies of simple array by initializing them through loops or by using System.arraycopy(), create copies of complex arrays by cloning them Iterator.hasNext() and Enumerator.hasMoreElements() need not be repeatedly called when the size of the collection is known. Use collection.size() and a loop counter instead. ArrayList is faster than Vector Go for a non-synchronized version of collection unless used in a threaded application LinkedList is faster than ArrayList for inserting elements to the front of the array, but slower at indexed lookup Accessing arrays is much faster than accessing vectors, String, and StringBuffer Vector is convenient to use, but inefficient. Ensure that elementAt() is not used inside a loop. Re-use Hashtables by using Hashtable.clear(). Removing elements from a Vector will necessitate copying within the Vector if the element is removed from anywhere other than the end of the collection. Presizing collections to the expected size is more efficient than using the default size and

99

letting the collection grow.


For multidimensional arrays store a reference for the currently accessed row in a variable. When adding multiple items to a collection, add them all in one call if possible.

6 . How do you optimize threads? Avoid synchronization where possible Code a multi-thread for multi-processor machine. Synchronizing on method rather than code blocks is slightly faster Polling is only acceptable when waiting for outside events and should be performed in a "side" thread. Use wait/notify instead. Prioritize threads. Use notify instead of notifyAll. Use synchronization sparingly. Keep synchronized methods out of loops if you possibly can. Maximize thread lifetimes and minimize thread creation/destruction cycles. Use Thread pools where these improve performance. Use Thread.sleep() instead of a for loop for measured delays. Use a separate timer thread to timeout socket operations Use more server threads if multiple connections have high latency. 7 . How do you optimize IO?

Use Buffered IO classes File information such as file length requires a system call and can be slow. Don't use it often. Similarly, System.currentTimeMillis() uses a native call to get current time. Make sure your production code does not have this statement. Many java.io.File methods are system calls which can be slow Use BufferedIO streams to access URLConnection sInput/Output streams. Use the transient keyword to define fields to avoid having those fields serialized. Examine serialized objects to determine which fields do not need to be serialized for the application to work. Increase server listen queues for high load or high latency servers.

8 . How do you optimize exceptions?


Be specific while handling the exception in your catch block. Be specific while throwing exception in your throws clause. Do not use Exception Handling to control programming flow. Very little overhead is imposed by using exception handling mechanism unless an exception

100

occurs or thrown a new exception object explicitly.


Always use the finally block to release the resources to prevent resource leaks. Handle exceptions locally wherever possible. Do not use Exception handling in loops.

9 . How will you optimize performance in JDBC? Use batch transactions. Choose right isolation level as per your requirement. TRANSACTION_READ_UNCOMMITED gives best performance for concurrent transaction based applications. TRANSACTION_NONE gives best performance for non-concurrent transaction based applications. Use PreparedStatement when you execute the same statement more than once. Use CallableStatement when you want result from multiple and complex statements for a single request. Use batch update facility available in Statements. Use batch retrieval facility available in Statements or ResultSet. Set up proper direction for processing rows. Use proper getXXX() methods. Close ResultSet, Statement and Connection whenever you finish your work with them. Write precise SQL queries. Cache read-only and read-mostly tables data. Fetch small amount of data iteratively rather than whole data at once when retrieving large amount of data like searching database etc. 10 . How do you optimize servlets?

Use init() method to cache static data Use StringBuffer rather than using + operator when you concatenate multiple strings Use print() method rather than println() method Use ServletOutputStream rather than PrintWriter to send binary data Initialize the PrintWriter with proper size Flush the data partly Minimize code in the synchronized block Set the content length Release resources in destroy() method. Implement getLastModified() method to use browser cache and server cache Use application server caching facility Use Mixed session mechanisms such as HttpSession with hidden fields Remove HttpSession objects explicitly in your program whenever you finish the task
101

Reduce session time out value as much as possible Use 'transient' variables to reduce serialization overhead if your HttpSession tracking mechanism uses serialization process. Disable servlet auto reloading feature. Use thread pool for your servlet engine and define the size as per application requirement.

11 . How do you optimize a JSP page? Use jspInit() method to cache static data Use StringBuffer rather than using + operator when you concatenate multiple strings Use print() method rather than println() method Use ServletOutputStream instead of JSPWriter to send binary data Initialize the 'out' object (implicit object) with proper size in the page directive. Flush the data partly Minimize code in the synchronized block Set the content length Release resources in jspDestroy() method. Give 'false' value to the session in the page directive to avoid session object creation. Use include directive instead of include action when you want to include the child page content in the translation phase. Avoid giving unnecessary scope in the 'useBean' action. Do not use custom tags if you do not have reusability. Use application server caching facility Use Mixed session mechanisms such as 'session' with hidden fields Use 'session' and 'application' as cache. Use caching tags provided by different organizations like openSymphony.com Remove 'session' objects explicitly in your program whenever you finish the task Reduce session time out value as much as possible Use 'transient' variables to reduce serialization overhead if your session tracking mechanism uses serialization process. Disable JSP auto reloading feature. Use thread pool for your JSP engine and define the size of thread pool as per application requirement.

12 . What are common optimizing practices for EJB?

102

Use Local interfaces that are available in EJB2.0 if you deploy both EJB Client and EJB in the same EJB Server. Use Vendor specific pass-by-reference implementation to make EJB1.1 remote EJBs as Local EJBs if you deploy both EJB Client and EJB in the same EJB Server. Wrap entity beans with session beans to reduce network calls and to promote declarative transactions. Optionally, make entity beans as local beans where appropriate. Make coarse grained session and entity beans to reduce network calls. 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. Avoid transaction overhead for non-transactional methods of session beans by declaring 'NotSupported' or 'Never' transaction attributes that avoid further propagation of transactions. Set proper transaction age(time-out) to avoid large transaction. Use clustering for scalability. Tune thread count for EJB Server to increase EJB Server capacity. Choose servlet's HttpSession object rather than Stateful session bean to maintain client state if you don't require component architecture and services of Stateful session bean. Choose best EJB Server by testing with ECperf tool kit. Choose normal java object over EJB if you don't want built-in services such as RMI/IIOP, transactions, security, persistence, resource pooling, thread safe, client state etc..

13 . How do you optimize stateless session beans?


Tune the Stateless session beans pool size to avoid overhead of creation and destruction of beans. Use setSessionContext() or ejbCreate() method to cache bean specific resources. Release acquired resources in ejbRemove() method

14 . How do you optimize stateful session beans?


Tune Stateful session beans cache size to avoid overhead of activation and passivation process. Set optimal Stateful session bean age(time-out) to avoid resource congestion. Use 'transient' key word for unnecessary variables of Stateful session bean to avoid serialization overhead. Remove Stateful session beans explicitly from client using remove() method.

103

15 . How do you optimize entity beans?


Tune the entity beans pool size to avoid overhead of creation and destruction of beans. Tune the entity beans cache size to avoid overhead of activation, passivation and database calls. Use setEntityContext() method to cache bean specific resources. Release acquired resources in unSetEntityContext() method Use Lazy loading to avoid unnecessary pre-loading of child data. Choose optimal transaction isolation level to avoid blocking of other transactional clients. Use proper locking strategy. Make read-only entity beans for read only operations. Use dirty flag to avoid unchanged buffer data updation. Commit the data after the transaction completes to reduce database calls in between transaction. 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. Tune connection pool size to reduce overhead of creation and destruction of database connections. Use JDBC tuning techniques in BMP. Use direct JDBC rather than using entity beans when dealing with huge data such as searching a large database. Use business logic that is specific to entity bean data.

16 . How do you optimize message driven beans?


Tune the Message driven beans pool size to promote concurrent processing of messages. Use setMesssageDrivenContext() or ejbCreate() method to cache bean specific resources. Release acquired resources in ejbRemove() method. Use JMS tuning techniques in Message driven beans.

17 . How do you optimize Java Message Service (JMS) Start producer connection after you start consumer. Use concurrent processing of messages. Close the Connection when finished. Choose either DUPS_OK_ACKNOWLEDGE or AUTO_ACKNOWLEDGE rather than CLIENT_ACKNOWLEDGE. Control transactions by using separate transactional session for transactional messages and non-transactional session for non-transactional messages. Close session object when finished. Make Destination with less capacity and send messages accordingly.
104

Set high Redelivery delay time to reduce network traffic. Set less Redelivery limit for reducing number of message hits. Choose non-durable messages wherever appropriate to avoid persistence overhead. Set optimal message age (TimeToLive value). Receive messages asynchronously. Close Producer/Consumer when finished. Choose message type carefully to avoid unnecessary memory overhead. Use 'transient' key word for variables of ObjectMessage which need not be transferred.

105

J2EE-Tomcat
1.How do You create Multiple virtual Hosts? If you want tomcat to accept requests for different hosts e.g., www.myhostname.com then you must 0. create ${catalina.home}/www/appBase , ${catalina.home}/www/deploy, and ${catalina.home}/conf/Catalina/www.myhostname.com 1. add a host entry in the server.xml file <Host appBase="www/appBase" name="www.myhostname.com"/> 2. Create the the following file under conf/Catalina/www.myhostname.com/ROOT.xml <?xml version="1.0" encoding="UTF-8"?> <Context path="/" docBase="www/deploy/mywebapp.war" reloadable="true" antiJARLocking="true"> </Context> Add any parameters specific to this hosts webapp to this context file 3. put your war file in ${catalina.home}/www/deploy When tomcat starts, it finds the host entry, then looks for any context files and will start any apps with a context To add more sites just repeat and rinse, all webapps can share the same war file location and appbase 2 . How will you load properties file? Use a ResourceBundle. See the Java docs for the specifics of how the ResourceBundle class works. Using this method, the properties file must go into the WEB-INF/classes directory or in a jar file contained in the WEB-INF/lib directory. Another way is to use the method getResourceAsStream() from the ServletContext class. This allows you update the file without having to reload the webapp as required by the first method. Here is an example code snippet, without any error trapping: // Assuming you are in a Servlet extending HttpServlet // This will look for a file called "/more/cowbell.properties" relative // to your servlet Root Context InputStream is = getServletContext().getResourceAsStream("/more/cowbell.properties");
106

Properties p = new Properties(); p.load(is); is.close(); 3 . Can I set Java system properties differently for each webapp? No. If you can edit Tomcat's startup scripts, you can add "-D" options to Java. But there is no way to add such properties in web.xml or the webapp's context. 4 . How do I configure Tomcat to work with IIS and NTLM? Follow the standard instructions for when the isapi_redirector.dll Configure IIS to use "integrated windows security" In server.xml, make sure you disable tomcat authentication: <Connector port="8009" enableLookups="false" redirectPort="8443" protocol="AJP/1.3" tomcatAuthentication="false" /> 5 . How can I access members of a custom Realm or Principal? When you create a custom subclass of RealmBase or GenericPrincipal and attempt to use those classes in your webapp code, you'll probably have problems with ClassCastException. This is because the instance returned by request.getUserPrincipal() is of a class loaded by the server's classloader, and you are trying to access it through you webapp's classloader. While the classes maybe otherwise exactly the same, different (sibling) classloaders makes them different classes. This assumes you created a My``Principal class, and put in Tomcat's server/classes (or lib) directory, as well as in your webapp's webinf/classes (or lib) directory. Normally, you would put custom realm and principal classes in the server directory because they depend on other classes there. Here's what you would like to do, but it throws ClassCastException: MyPrincipal p = request.getUserPrincipal(); String emailAddress = p.getEmailAddress(); Here are 4 ways you might get around the classloader boundary:

107

1) Reflection Principal p = request.getUserPrincipal(); String emailAddress = p.getClass().getMethod("getEmailAddress", null).invoke(p, null); 2) Move classes to a common classloader You could put your custom classes in a classloader that is common to both the server and your webapp - e.g., either the "common" or bootstrap classloaders. To do this, however, you would also need to move the classes that your custom classes depend on up to the common classloader, and that seems like a bad idea, because there a many of them and they a core server classes. 3) Common Interfaces Rather than move the implementing custom classes up, you could define interfaces for your customs classes, and put the interfaces in the common directory. You're code would look like this: public interface MyPrincipalInterface extends java.security.Principal { public String getEmailAddress(); } public class MyPrincipal implements MyPrincipalInterface { ... public String getEmailAddress() { return emailAddress; } } public class MyServlet implements Servlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { MyPrincipalInterface p = (MyPrincipalInterface)request.getUserPrincipal(); String emailAddress = p.getEmailAddress(); ... } Notice that this method gives you pretty much the webapp code you wanted in the first place 4) Serializing / Deserializing You might want to try serializing the response of 'request.getUserPrincipal()' and deserialize it to an instance of
108

[webapp]MyPrincipal.

6 . How do I override the default home page loaded by Tomcat? After successfully installing Tomcat, you usually test it by loading http://localhost:8080 . The contents of that page are compiled into the index_jsp servlet. The page even warns against modifying the index.jsp files for this reason. Luckily, it is quite easy to override that page. Inside $TOMCAT_HOME/conf/web.xml there is a section called <welcome-file-list> and it looks like this: <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> </welcome-file-list> The default servlet attempts to load the index.* files in the order listed. You may easily override the index.jsp file by creating an index.html file at $TOMCAT_HOME/webapps/ROOT. It's somewhat common for that file to contain a new static home page or a redirect to a servlet's main page. A redirect would look like: <html> <head> <meta http-equiv="refresh" content="0;URL=http://mydomain.com/some/path/to/servlet/homepage/"> </head> <body> </body> </html> This change takes effect immediately and does not require a restart of Tomcat. > 7 . How do I enable Server Side Includes (SSI)? Two things have to be done for tomcat to aknowledge SSI scripts: 1. Rename $CATALINA_BASE/server/lib/servlets-ssi.renametojar to $CATALINA_BASE/server/lib/servlets-ssi.jar. 2. Uncomment the section of web.xml found in $CATALINA_BASE/conf/web.xml that deals with SSI. it looks like this when it is uncommented:
109

<servlet> <servlet-name>ssi</servlet-name> <servlet-class> org.apache.catalina.ssi.SSIServlet </servlet-class> <init-param> <param-name>buffered</param-name> <param-value>1</param-value> </init-param> <init-param> <param-name>debug</param-name> <param-value>0</param-value> </init-param> <init-param> <param-name>expires</param-name> <param-value>666</param-value> </init-param> <init-param> <param-name>isVirtualWebappRelative</param-name> <param-value>0</param-value> </init-param> <load-on-startup>4</load-on-startup> </servlet> 8 . How do I use DataSources with Tomcat? When developing J2EE web applications, the task of database connection management can be daunting. Best practice involves using a J2EE DataSource to provide connection pooling, but configuring DataSources in web application servers and connecting your application to them is often a cumbersome process and poorly documented. The usual procedure requires the application developer to set up a DataSource in the web application server, specifying the driver class, JDBC URL (connect string), username, password, and various pooling options. Then, the developer must reference the DataSource in his application's web.xml configuration file, and then access it properly in his servlet or JSP. Particularly during development, setting all of this up is tedious and error-prone. With Tomcat 5.5, the process is vastly simplified. Tomcat allows you to configure DataSources for your J2EE web application in a context.xml file that is stored in your web application project. You don't have to mess with configuring the DataSource separately in the Tomcat server.xml, or referencing it in your application's web.xml file. Here's how:

110

Install the JDBC Driver Install the .jar file(s) containing the JDBC driver in Tomcat's common/lib folder. You do not need to put them in your application's WEB-INF/lib folder. When working with J2EE DataSources, the web application server manages connections for your application. Create META-INF/context.xml In the root of your web app directory structure, create a folder named META-INF (all caps). Inside that folder, create a file named context.xml that contains a Resource like this: <?xml version="1.0" encoding="UTF-8"?> <Context> <Resource name="jdbc/WallyDB" auth="Container" type="javax.sql.DataSource" username="wally" password="wally" driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver" url="jdbc:sqlserver://localhost;DatabaseName=mytest;SelectMethod=cursor;" maxActive="8" /> </Context> This example shows how to configure a DataSource for a SQL Server database named mytest located on the development machine. Simply edit the Resource name, driverClassName, username, password, and url to provide values appropriate for your JDBC driver. Access the DataSource in Your Application From a Servlet Here's how you might access the data in a servlet: InitialContext ic = new InitialContext(); DataSource ds = (DataSource) ic.lookup("java:comp/env/jdbc/WallyDB"); Connection c = ds.getConnection(); ... c.close(); Notice that, when doing the DataSource lookup, you must prefix the JNDI name of the resource with java:comp/env/

111

J2EE-Weblogic 1.How do I provide user credentials for starting server? When you create a domain, the Configuration Wizard prompts you to provide the username and password for an initial administrative user. If you create the domain in development mode, the wizard saves the username and encrypted password in a boot identity file. A WebLogic Server instance can refer to a boot identity file during its startup process. If a server instance does not find such a file, it prompts you to enter credentials. If you create a domain in production mode, or if you want to change user credentials in an existing boot identity file, you can create a new boot identity file. 2 . Can I start a Managed Server if the Administration Server is unavailable? By default, if a Managed Server is unable to connect to the specified Administration Server during startup, it can retrieve its configuration by reading a configuration file and other files directly. You cannot change the server's configuration until the Administration Server is available. A Managed Server that starts in this way is running in Managed Server Independence mode. 3 . What is the function of T3 in WebLogic Server? T3 provides a framework for WebLogic Server messages that support for enhancements. These enhancements include abbreviations and features, such as object replacement, that work in the context of WebLogic Server clusters and HTTP and other product tunneling. T3 predates Java Object Serialization and RMI, while closely tracking and leveraging these specifications. T3 is a superset of Java Object. Serialization or RMI; anything you can do in Java Object Serialization and RMI can be done over T3. T3 is mandated between WebLogic Servers and between programmatic clients and a WebLogic Server cluster. HTTP and IIOP are optional protocols that can be used to communicate between other processes and WebLogic Server. It depends on what you want to do. For example, when you want to communicate between a browser and WebLogic Server-use HTTP, or an ORB and WebLogic Server-IIOP. 4 . How do you set the classpath? WebLogic Server installs the following script that you can use to set the classpath that a server requires: WL_HOME\server\bin\setWLSEnv.cmd (on Windows) WL_HOME/server/bin/setWLSEnv.sh (on UNIX) where WL_HOME is the directory in which you installed WebLogic Server.

5 . How do stubs work in a WebLogic Server cluster? Clients that connect to a WebLogic Server cluster and look up a clustered object obtain a replica-aware stub for the
112

object. This stub contains the list of available server instances that host implementations of the object. The stub also contains the load balancing logic for distributing the load among its host servers. 6 . What happens when a failure occurs and the stub cannot connect to a WebLogic Server instance? When the failure occurs, the stub removes the failed server instance from its list. If there are no servers left in its list, the stubb uses DNS again to find a running server and obtain a current list of running instances. Also, the stub periodically refreshes its list of available server instances in the cluster; this allows the stub to take advantage of new servers as they are added to the cluster. 7 . How does a server know when another server is unavailable? WebLogic Server uses two mechanisms to determine if a given server instance is unavailable. Each WebLogic Server instance in a cluster uses multicast to broadcast regular "heartbeat" messages that advertise its availability. By monitoring heartbeat messages, server instances in a cluster determine when a server instance has failed. The other server instances will drop a server instance from the cluster, if they do not receive three consecutive heartbeats from that server instance WebLogic Server also monitors socket errors to determine the availability of a server instance. For example, if server instance A has an open socket to server instance B, and the socket unexpectedly closes, server A assumes that server B is offline. 8 . How are notifications made when a server is added to a cluster? The WebLogic Server cluster broadcasts the availability of a new server instance each time a new instance joins the cluster. Cluster-aware stubs also periodically update their list of available server instances. 9 . How do clients handle DNS requests to failed servers? If a server fails and DNS continues to send requests to the unavailable machine, this can waste bandwidth. For a Java client application, this problem occurs only during startup. WebLogic Server caches the DNS entries and removes the unavailable ones, to prevent the client from accessing a failed server twice. Failed servers can be more of a problem for browser-based clients, because they always use DNS. To avoid unnecessary DNS requests with browser-based clients, use a third-party load-balancer such as Resonate, BigIP, Alteon, and LocalDirector. These products mask multiple DNS addresses as a single address. They also provide more sophisticated load-balancing options than round-robin, and they keep track of failed servers to avoid routing unnecessary requests.

113

10 . How many WebLogic Servers can I have on a multi-cpu machine? There are many possible configurations and each has its own advantages and disadvantages. BEA WebLogic Server has no built-in limit for the number of server instances that can reside in a cluster. Large, multi-processor servers such as Sun Microsystems, Inc. Sun Enterprise 10000, therefore, can host very large clusters or multiple clusters. In most cases, WebLogic Server clusters scale best when deployed with one WebLogic Server instance for every two CPUs. However, as with all capacity planning, you should test the actual deployment with your target web applications to determine the optimal number and distribution of server instances. > 11 . How can I set deployment order for applications? WebLogic Server allows you to select the load order for applications. WebLogic Server deploys server-level resources (first JDBC and then JMS) before deploying applications. Applications are deployed in this order: connectors, then EJBs, then Web Applications. If the application is an EAR, the individual components are loaded in the order in which they are declared in the application.xml deployment descriptor. 12 . Can I refresh static components of a deployed application without having to redeploy the entire application? Yes. You can use weblogic.Deployer to specify a component and target a server, using the following syntax:

java weblogic.Deployer -adminurl http://admin:7001 -name appname -targets server1,server2 -deploy jsps/*.jsp 13 . When should I use the -nostage option? Set the staging mode to -nostage (using weblogic.Deployer or the Administration Console) if you don't want to copy deployment files but want to deploy an application from its present location. All target servers must be able to access the same set of deployment files. 14 . When should I use the external_stage option? Set -external_stage using weblogic.Deployer if you want to stage the application yourself, and prefer to copy it to its target by your own means. 15 . Can I set the deployment order for application modules? For standalone modules? The Load Order attribute controls the deployment order of standalone modules and applications relative to other modules and applications of the same type. For example, standalone EJBs with smaller Load Order values are deployed
114

before those with higher values. Modules that are deployed as part of an Enterprise Application (EAR file or directory) are deployed in the order in which they are specified in the application.xml deployment descriptor. 16 . What is the difference between the WL_HOME/config/examples/applications folder and the WL_HOME/config/examples/stage folder? The applications folder is intended for applications that are not yet ready for a production environment. WebLogic Server dynamically deploys the contents of the applications folder. The stage folder (or a folder that you create for the same purpose) is for storing copies of deployment files that are ready for deployment in a production environment (deployments that use the stage or external_stage deployment modes). 17 . How do I turn the auto-deployment feature off? The auto-deployment feature checks the applications folder every three seconds to determine whether there are any new applications or any changes to existing applications and then dynamically deploys these changes. The auto-deployment feature is enabled for servers that run in development mode. To disable auto-deployment feature, use one of the following methods to place servers in production mode: In the Administration Console, click the name of the domain in the left pane, then select the Production Mode checkbox in the right pane. At the command line, include the following argument when starting the domain's Administration Server: -Dweblogic.ProductionModeEnabled=true Production mode is set for all WebLogic Server instances in a given domain. 18 . Must EJBs be homogeneously deployed across a cluster? Why? Yes. In WebLogic Server 6.0 and later, EJBs must be homogeneously deployed across a cluster for the following reasons: To keep clustering EJBs simple To improve performance by avoiding cross-server calls. If EJBs are not deployed on all servers, cross-server calls are more likely. To ensure that every EJB is available locall.y To ensure that all classes are loaded in an undeployable way. Every server must have access to each EJB's classes so that it can be bound into the local JNDI tree. If only a subset of the servers deploys the bean, the other servers will have to load the bean's classes in their respective system classpaths which makes it impossible to undeploy the

115

beans.

J2EE-Ant
1.What is ant? J2EE Ant

116

1 . Ant Interview Questions What is ant? Ant is a small animal who can build magnificent buildings. Ant builds! ANT is a Java based building tool, which is similar to make, and so much better than make. ANT, what a smart name for a building tool, even the original author of ANT, James Duncan Davidson, meant "Another Neat Tool". A win-win ant learning method There is a shortcut. If you download a small jakarta project, such as Log4J, which is built by ant. It is a good and simple example for you to learn ant. Actually, you hit two birds with one stone. Ant is easy! The hard part is how to make a very complicated diversified system work very simple and elegant. Knowledge about ant is not enough, you need an elegant and simple design, you need great naming convention, you need to optimize the code reusability and flexibility, you need a least maintenance system... Then it is not easy now .. How do I get started to use ant? Can you give me a "Hello World" ant script? Simple. * Download the most recent version of ant from Apache; unzip it some where on your machine. * Install j2sdk 1.4 or above. * Set JAVA_HOME and ANT_HOME to the directory your installed them respectively. * Put %JAVA_HOME%/bin;%ANT_HOME%/bin on your Path. Use ${JAVA_HOME}/bin:${ANT_HOME}/bin on UNIX. Yes, you can use forward slash on windows.
117

* Write a "Hello world" build.xml <project name="hello" default="say.hello" basedir="." > <property name="hello.msg" value="Hello, World!" /> <target name="say.hello" > <echo>${hello.msg}</echo> </target> </project>

* Type ant in the directory your build.xml located. * You are ready to go!!!! How to delete files from a directory if it exists? The following code fails when directory does not exist! <delete quiet="true" dir="${classes.dir}" includes="*.class"/> Your code has many problems. 1. You should not use implicit fileset, which is deprecated. You should use nested fileset. 2. If dir does not exist, the build will fail, period! 3. If you are not sure, use a upper level dir, which exists for sure. See the following fileset. <delete> <fileset dir="${upperdir.which.exists}"> <include name="${classes.dir}/*.class" /> </fileset> </delete>

2 . Ant Interview Questions How do I set classpath in ant? Here is some snippet of code <path id="build.classpath">

118

<fileset dir="${build.lib}" includes="**/*.jar"/> <fileset dir="${build.classes}" /> </path> <target....> <javac ....> <classpath refid="build.classpath" /> </java> </target> <target....> <java ....> <classpath refid="build.classpath" /> </java> </target>

How does ant read properties? How to set my property system? Ant sets properties by order, when something is set, the later same properties cannot overwrite the previous ones. This is opposite to your Java setters. This give us a good leverage of preset all properties in one place, and overwrite only the needed. Give you an example here. You need password for a task, but don't want to share it with your team members, or not the developers outside your team. Store your password in your ${user.home}/prj.properties pswd=yourrealpassword In your include directory master prj.properties pswd=password In your build-common.xml read properties files in this order 1. The commandline will prevail, if you use it: ant -Dpswd=newpassword 2. ${user.home}/prj.properties (personal) 3. yourprojectdir/prj.properties (project team wise) 4. your_master_include_directory/prj.properties (universal) <cvsnttask password="${pswd} ... /> Problem solved!

119

How to modify properties in ant? No, you can't! Properties in Ant are immutable. There is a good reason behind this, see this FAQ item for more details. Q. How to use ant-contrib tasks? A: Simple, just copy ant-contrib.jar to your ant*/lib directory And add this line into your ant script, all ant-contrib tasks are now available to you! <taskdef resource="net/sf/antcontrib/antcontrib.properties" /> 3 . Ant Interview Questions > 4 . Ant Interview Questions How can I use ant to run a Java application? Here is a real world example. <target name="run" depends="some.target,some.other.target"> <java classname="${run.class}" fork="yes"> <classpath> <path refid="classpath" /> </classpath> <jvmarg line="${debug.jvmargs}" /> <jvmarg line="${my.jvmargs}" /> <jvmarg value="-Dname=${name}" /> <jvmarg line="${run.jvmargs}" /> <arg line="${run.args}" /> </java> </target> How to use ant to run commandline command? How to get perl script running result?

120

Use exec ant task. Don't forget ant is pure Java. That is why ant is so useful, powerful and versatile. If you want ant receive unix command and result, you must think Unix. So does in MS-Windows. Ant just helps you to automate the process. How do I debug my ant script? Many ways * Do an echo on where you have doubt. You will find out what is the problem easily. Just like the old c printf() or Java System.println() * Use project.log("msg") in your javascript or custom ant task * Run Ant with -verbose, or even -debug, to get more information on what it is doing, and where. However, you might be tired with that pretty soon, since it give you too much information.

How to exclude multi directories in copy or delete task? Here is an example. <copy todir="${to.dir}" > <fileset dir="${from.dir}" > <exclude name="dirname1" /> <exclude name="dirname2" /> <exclude name="abc/whatever/dirname3" /> <exclude name="**/dirname4" /> </fileset> </copy> How to use Runtime in ant? You don't need to use Runtime etc. Ant have exec task. The class name is org.apache.tools.ant.taskdefs.ExecTask. You can create the task by using the code in your customized ant Task.
121

ExecTask compile = (ExecTask)project.createTask("exec"); 5 . Ant Interview Questions How to rearrange my directory structure in my jar/war/ear/zip file? Do I need to unarchive them first? No, you don't need to unarchive them first. * You don't need to unzip the files from archive to put into your destination jar/ear/war files. * You can use zipfileset in your jar/war/ear task to extract files from old archive to different directory in your new archive. * You also can use zipfileset in your jar/war/ear task to send files from local directory to different directory in your new archive. See the follow example: <jar destfile="${dest}/my.jar"> <zipfileset src="old_archive.zip" includes="**/*.properties" prefix="dir_in_new_archive/prop"/> <zipfileset dir="curr_dir/abc" prefix="new_dir_in_archive/xyz"/> </jar>

Why did I get such warning in ant? compile: [javac] Warning: commons-logging.properties modified in the future. [javac] Warning: dao\\DAO.java modified in the future. [javac] Warning: dao\\DBDao2.java modified in the future. [javac] Warning: dao\\HibernateBase.java modified in the future. System time problem, possible reasons:

122

* You changed the system time * I had the same problem before, I checked out files from cvs to windows, and transfer them to a unix machine, somehow, I got huge amount of such warnings because the system timing issue. * If you transfer files from Australia/China/India to the United States, you will get the problem too. True enough, I did and met the problem once.

How can I write my own ant task? Easy! Writing Your Own Task How-To from ant. In your own $ANT_HOME/docs/manual directory, there also is tutorial-writing-tasks-src.zip Use them! Use taskdef to define it in your script, define it before using it. How to copy files without extention? If files are in the directory: <include name="a,b,c"/> If files are in the directory or subdirectories: <include name="**/a,**/b,**/c"/> If you want all files without extension are in the directory or subdirectories: <exclude name="**/*.*"/> 6 . Ant Interview Questions How do I use two different versions of jdk in ant script?

123

The followings are what I'm doing. 1. Don't define java.home by yourself. Ant uses an internal one derived from your environment var JAVA_HOME. It is immutable. 2. I do the followings: * In my build.properties (read first) jdk13.bin=${tools.home}/jdk1.3.1_13/bin jdk14.bin=${tools.home}/j2sdk1.4.2_08/bin/ * In my master properties file (read last), set default javac.location=${jdk13.bin} * In my prj.properties, if I need to use 1.4 javac.location=${jdk14.bin} * in my javac task executable="${javac.location}/javac.exe" How to pass -Xlint or -Xlint:unchecked to 1.5 javac task? pass it as compilerarg nested <compilerarg> to specify. <compilerarg value="-Xlint"/> <!-- or --> <compilerarg value="-Xlint:unchecked"/> Can you give me a simple ant xslt task example? Here is a working one! <xslt style="${xslfile}" in="${infile}" out="${outfile}" > <classpath> <fileset dir="${xml.home}/bin" includes="*.jar" /> </classpath> </xslt> How to hide password input? Override ant Input task. Response every user input with a backspace. Not the best, but it works

124

How do I add elements to an existing path dynamically? Yes, it is possible. However, you need to write a custom ant task, get the path, and add/modify it, and put it in use. What I am doing is that I define a path reference lib.classpath, then add/modify the lib.classpath use my own task. How to do conditional statement in ant? There are many ways to solve the problem. * Since target if/unless all depend on some property is defined or not, you can use condition to define different NEW properties, which in turn depends on your ant property values. This makes your ant script very flexible, but a little hard to read. * Ant-contrib has <if> <switch> tasks for you to use. * Ant-contrib also has <propertyregex> which can make very complicate decisions. 7 . Ant Interview Questions Can I change/override ant properties when I use ant-contrib foreach task? <foreach> is actually using a different property space, you can pass any property name/value pair to it. Just use <param> nested tag inside foreach How to let auto-detect platform and use platform specific properties? Tell you a great trick, it works excellent. In your major build-include.xml, put in this line

<property file="${antutil.includes}/${os.name}-${os.arch}.properties" /> This will auto-detect your platform, and you write one file for each environment specific variables. For example: HP-UX-PA_RISC2.0.properties SunOS-sparc.properties Windows XP-x86.properties ... They work great!!! How to make ant user interactive? I tried to use BufferedReader to get user input, it hangs. See here.

125

Use this class TimedBufferedReader instead of your BufferedReader will work. This is a working one in our installation process. The original author is credited in the code. I've made some improvement. TimedBufferedReader.java package setup; import java.io.Reader; import java.io.BufferedReader; import java.io.IOException; /** * Provides a BufferedReader with a readLine method that * blocks for only a specified number of seconds. If no * input is read in that time, a specified default * string is returned. Otherwise, the input read is returned. * Thanks to Stefan Reich * for suggesting this implementation. * @author: Anthony J. Young-Garner * @author: Roseanne Zhang made improvement. */ public class TimedBufferedReader extends BufferedReader { private int timeout = 60; // 1 minute private String defaultStr = ""; /** * TimedBufferedReader constructor. * @param in Reader */ TimedBufferedReader(Reader in) { super(in); } /** * TimedBufferedReader constructor. * @param in Reader * @param sz int Size of the input buffer.
126

*/ TimedBufferedReader(Reader in, int sz) { super(in, sz); } /** * Sets number of seconds to block for input. * @param seconds int */ public void setTimeout(int timeout) { this.timeout=timeout; } /** * Sets defaultStr to use if no input is read. * @param str String */ public void setDefaultStr(String str) { defaultStr = str; } /** * We use ms internally * @return String */ public String readLine() throws IOException { int waitms = timeout*1000; int ms = 0; while (!this.ready()) { try { Thread.currentThread().sleep(10); ms += 10; } catch (InterruptedException e)
127

{ break; } if (ms >= waitms) { return defaultStr; } } return super.readLine(); } }

> 8 . Ant Interview Questions What is a good directory structure for main code and junit test code? Dev |_src | |_com | |_mycom | |_mypkg | |_A.java |_test |_src |_com |_mycom |_mypkg |_ATest.java 9 . Ant Interview Questions What is a good directory structure for main code and junit test code? Dev |_src | |_com | |_mycom
128

| |_mypkg | |_A.java |_test |_src |_com |_mycom |_mypkg |_ATest.java

> How to loop on a list or fileset? Use ant-contrib <for> <foreach> tasks General to say, use <for> is better than use <foreach> since for each is actually open another ant property space, use more memory too. Why do I get en exception when I use location="D:\\Code\\include" as attribute of includepath? See here. You need to escape the string to "D:\\\\Code\\\\include" or use "D:/Code/include" instead! Believe me or not? Forward slash works on windows in all ant or java code. It also works in windows environment variables. It does not work in cmd (dos) window before XP. It also works in XP dos window now! Can I put the contents of a classpath or fileset into a property? Yes, you can. This is very similar to the call of Java class toString() method and actually it is calling the toString() method inside ant. For example <fileset id="fs1" dir="t1" includes="**/*.java"/> <property name="f1.contents" refid="fs1"/>
129

<echo>f1.contents=${f1.contents}</echo> J2EE - XML 1 . XML Interview Questions

Where can I find the javadoc for ant API? Download apache ant src version. Use ant javadocs command to see generated javadoc for ant in build/docs directory. Describe the differences between XML and HTML.

It's amazing how many developers claim to be proficient programming with XML, yet do not understand the basic differences between XML and HTML. Anyone with a fundamental grasp of XML should be able describe some of the main differences outlined in the table below. Differences Between XML and HTML XML User definable tags Content driven HTML Defined set of tags designed for web display Format driven

End tags required for well formed End tags not required documents Quotes required around attributes Quotes not required values Slash required in empty tags Slash not required Describe the role that XSL can play when dynamically generating HTML pages from a relational database. Even if candidates have never participated in a project involving this type of architecture, they should recognize it as one of the common uses of XML. Querying a database and then formatting the result set so that it can be validated as an XML document allows developers to translate the data into an HTML table using XSLT rules. Consequently, the format of the resulting HTML table can be modified without changing the database query or application code since the document rendering logic is isolated to the XSLT rules. 2 . XML Interview Questions Slash not required

130

Give a few examples of types of applications that can benefit from using XML. There are literally thousands of applications that can benefit from XML technologies. The point of this question is not to have the candidate rattle off a laundry list of projects that they have worked on, but, rather, to allow the candidate to explain the rationale for choosing XML by citing a few real world examples. For instance, one appropriate answer is that XML allows content management systems to store documents independently of their format, which thereby reduces data redundancy. Another answer relates to B2B exchanges or supply chain management systems. In these instances, XML provides a mechanism for multiple companies to exchange data according to an agreed upon set of rules. A third common response involves wireless applications that require WML to render data on hand held devices. What is DOM and how does it relate to XML? The Document Object Model (DOM) is an interface specification maintained by the W3C DOM Workgroup that defines an application independent mechanism to access, parse, or update XML data. In simple terms it is a hierarchical model that allows developers to manipulate XML documents easily Any developer that has worked extensively with XML should be able to discuss the concept and use of DOM objects freely. Additionally, it is not unreasonable to expect advanced candidates to thoroughly understand its internal workings and be able to explain how DOM differs from an event-based interface like SAX. What is SOAP and how does it relate to XML? The Simple Object Access Protocol (SOAP) uses XML to define a protocol for the exchange of information in distributed computing environments. SOAP consists of three components: an envelope, a set of encoding rules, and a convention for representing remote procedure calls. Unless experience with SOAP is a direct requirement for the open position, knowing the specifics of the protocol, or how it can be used in conjunction with HTTP, is not as important as identifying it as a natural application of XML.

> 3 . XML Interview Questions Can you walk us through the steps necessary to parse XML documents? Superficially, this is a fairly basic question. However, the point is not to determine whether candidates understand the concept of a parser but rather have them walk through the process of parsing XML documents step-by-step. Determining whether a non-validating or validating parser is needed, choosing the appropriate parser, and handling errors are all important aspects to this process that should be included in the candidate's response. Give some examples of XML DTDs or schemas that you have worked with. Although XML does not require data to be validated against a DTD, many of the benefits of using the technology are derived from being able to validate XML documents against business or technical architecture rules. Polling for

131

the list of DTDs that developers have worked with provides insight to their general exposure to the technology. The ideal candidate will have knowledge of several of the commonly used DTDs such as FpML, DocBook, HRML, and RDF, as well as experience designing a custom DTD for a particular project where no standard existed. Using XSLT, how would you extract a specific attribute from an element in an XML document? Successful candidates should recognize this as one of the most basic applications of XSLT. If they are not able to construct a reply similar to the example below, they should at least be able to identify the components necessary for this operation: xsl:template to match the appropriate XML element, xsl:value-of to select the attribute value, and the optional xsl:apply-templates to continue processing the document. Extract Attributes from XML Data Example 1. <xsl:template match="element-name"> Attribute Value: <xsl:value-of select="@attribute"/> <xsl:apply-templates/> </xsl:template> 4 . XML Interview Questions When constructing an XML DTD, how do you create an external entity reference in an attribute value? Every interview session should have at least one trick question. Although possible when using SGML, XML DTDs don't support defining external entity references in attribute values. It's more important for the candidate to respond to this question in a logical way than than the candidate know the somewhat obscure answer. How would you build a search engine for large volumes of XML data? The way candidates answer this question may provide insight into their view of XML data. For those who view XML primarily as a way to denote structure for text files, a common answer is to build a full-text search and handle the data similarly to the way Internet portals handle HTML pages. Others consider XML as a standard way of transferring structured data between disparate systems. These candidates often describe some scheme of importing XML into a relational or object database and relying on the database's engine for searching. Lastly, candidates that have worked with vendors specializing in this area often say that the best way the handle this situation is to use a third party software package optimized for XML data. Obviously, some important areas of XML technologies were not included in this list -- namespaces, XPointer, XLink, and so on -- and should be added to the interviewer's set of questions if applicable to the particular position that the candidate is applying for. However, these questions in conjunction with others to assess soft skills (communication skills, ability to work on teams, leadership ability, etc.) will help determine how well candidates understand the fundamental principles of XML.

132

Why is XML such an important development? It removes two constraints which were holding back Web developments:<br> 1. dependence on a single, inflexible document type (HTML) which was being much abused for tasks it was never designed for;<br> 2. the complexity of full SGML, whose syntax allows many powerful but hard-to-program options.<br> XML allows the flexible development of user-defined document types. It provides a robust, non-proprietary, persistent, and verifiable file format for the storage and transmission of text and data both on and off the Web; and it removes the more complex options of SGML, making it easier to program for. Is it possible to write the contents of org.w3c.dom.Document object into an .xml file? Yes its possible. One to achieve this is by using Xerces. Xerces is an XML parser. You would use the following code org.apache.xml.serialize.OutputFormat format = new org.apache.xml.serialize.OutputFormat(myDocument); org.apache.xml.serialize.XMLSerializer output = new org.apache.xml.serialize.XMLSerializer(new FileOutputStream(new File("test.xml")), format); output.serialize(myDocument);

> 5 . XML Interview Questions What is the difference between DOM and SAX? What would you use if an option is given? DOM parses an XML document and returns an instance of org.w3c.dom.Document. This document object's tree must then be "walked" in order to process the different elements. DOM parses the ENTIRE Document into memory, and then makes it available to you. The size of the Document you can parse is limited to the memory available. SAX uses an event callback mechanism requiring you to code methods to handle events thrown by the parser as it encounters different entities within the XML document. SAX throws events as the Document is being parsed. Only the current element is actually in memory, so there is no limit to the size of a Document when using SAX. The specific parser technology that will be used will be determined by the requirements of your application. If you need the entire document represented, you will most likely use DOM builder implementation. If you only care about parts of the XML document and/or you only need to parse the document once, you might be better served using SAX implementation.

133

What is SOAP? The Simple Object Access Protocol (SOAP) uses XML to define a protocol for the exchange of information in distributed computing environments. SOAP consists of three components: an envelope, a set of encoding rules, and a convention for representing remote procedure calls. What is DOM? The Document Object Model (DOM) is an interface specification maintained by the W3C DOM Workgroup that defines an application independent mechanism to access, parse, or update XML data. In simple terms it is a hierarchical model that allows developers to manipulate XML documents easily. Can you walk us through the steps necessary to parse XML file? DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(true); DocumentBuilder domBuilder = factory.newDocumentBuilder(); Document doc = domBuilder.parse(XMLFile); Is it necessary to validate XML file against a DTD? Although XML does not require data to be validated against a DTD, many of the benefits of using the technology are derived from being able to validate XML documents against business or technical architecture rules. 6 . XML Interview Questions What is XPath? XPath stands for XML Path Language XPath is a syntax for defining parts of an XML document XPath is used to navigate through elements and attributes in an XML document XPath contains a library of standard functions XPath is a major element in XSLT XPath is designed to be used by both XSLT and XPointer XPath is a W3C Standard What is XSL? XSLT - a language for transforming XML documents XSLT is used to transform an XML document into another XML document, or another type of document that is recognized by a browser, like HTML and XHTML.

134

Normally XSLT does this by transforming each XML element into an (X)HTML element. What is a DTD and a Schema? The XML Document Type Declaration contains or points to markup declarations that provide a grammar for a class of documents. This grammar is known as a document type definition or DTD. The DTD can point to an external subset containing markup declarations, or can contain the markup declarations directly in an internal subset, or can even do both. A Schema is: XML Schemas express shared vocabularies and allow machines to carry out rules made by people. They provide a means for defining the structure, content and semantics of XML documents. Schemas are a richer and more powerful of describing information than what is possible with DTDs.

135

J2EE UML 1 . UML Interview Questions What is UML? UML is Unified Modeling Language. It is a graphical language for visualizing specifying constructing and documenting the artifacts of the system. It allows you to create a blue print of all the aspects of the system, before actually physically implementing the system. What is modeling? What are the advantages of creating a model? Modeling is a proven and well-accepted engineering technique which helps build a model. Model is a simplification of reality; it is a blueprint of the actual system that needs to be built. Model helps to visualize the system. Model helps to specify the structural and behavior of the system. Model helps make templates for constructing the system. Model helps document the system. What are the different views that are considered when building an object-oriented software system? Normally there are 5 views. Use Case view - This view exposes the requirements of a system. Design View - Capturing the vocabulary. Process View - modeling the distribution of the systems processes and threads. Implementation view - addressing the physical implementation of the system. Deployment view - focus on the modeling the components required for deploying the system. What are diagrams? Diagrams are graphical representation of a set of elements most often shown made of things and associations. What are the major three types of modeling used? Major three types of modeling are structural, behavioral, and architectural.

136

Mention the different kinds of modeling diagrams used? Modeling diagrams that are commonly used are, there are 9 of them. Use case diagram, Class Diagram, Object Diagram, Sequence Diagram, statechart Diagram, Collaboration Diagram, Activity Diagram, Component diagram, Deployment Diagram.

> 2 . UML Interview Questions What is Architecture? Architecture is not only taking care of the structural and behavioral aspect of a software system but also taking into account the software usage, functionality, performance, reuse, economic and technology constraints. What is SDLC? SDLC is Software Development Life Cycle. SDLC of a system included processes that are Use case driven, Architecture centric and Iterative and Incremental. This Life cycle is divided into phases. Phase is a time span between two milestones. The milestones are Inception, Elaboration, Construction, and Transition. Process Workflows that evolve through these phase are Business Modeling, Requirement gathering, Analysis and Design, Implementation, Testing, Deployment. Supporting Workflows are Configuration and change management, Project management. What are Relationships? There are different kinds of relationships: Dependencies, Generalization, and Association. Dependencies are relations ships between two entities that that a change in specification of one thing may affect another thing. Most commonly it is used to show that one class uses another class as an argument in the signature of the operation. Generalization is relationships specified in the class subclass scenario, it is shown when one entity inherits from other. Associations are structural relationships that are: a room has walls, Person works for a company. Aggregation is a type of association where there is a has a relation ship, That is a room has walls, if there are two classes room and walls then the relation ship is called a association and further defined as an aggregation. How are the diagrams divided? The nine diagrams are divided into static diagrams and dynamic diagrams. Static Diagrams (Also called Structural Diagram): Class diagram, Object diagram, Component Diagram,
137

Deployment diagram. Dynamic Diagrams (Also called Behavioral Diagrams): Use Case Diagram, Sequence Diagram, Collaboration Diagram, Activity diagram, Statechart diagram. What are Messages? A message is the specification of a communication, when a message is passed that results in action that is in turn an executable statement. What is a Use Case? A use case specifies the behavior of a system or a part of a system, Use cases are used to capture the behavior that need to be developed. It involves the interaction of actors and the system

>

J2EE - DB2 & SQL 1 . DB2 and SQL Interview Questions How would you find out the total number of rows in a DB2 table? Use SELECT COUNT(*) . in db2 query How do you eliminate duplicate values in DB2 SELECT ? Use SELECT DISTINCT . in db2 query How do you select a row using indexes in DB2? Specify the indexed columns in the WHERE clause of db2 query. How do you find the maximum value in a column in db2? Use SELECT MAX(.) .. in db2 query

138

How do you retrieve the first 5 characters of FIRSTNAME column of DB2 table EMP ? SQL Query : SELECT SUBSTR(FIRSTNAME,1,5) FROM EMP; What are aggregate functions? Bulit-in mathematical functions for use in SELECT clause. Can you use MAX on a CHAR column? YES. My SQL statement SELECT AVG(SALARY) FROM EMP yields inaccurate results. Why? Because SALARY is not declared to have NULLs and the employees for whom the salary is not known are also counted. 2 . DB2 and SQL Interview Questions How do you concatenate the FIRSTNAME and LASTNAME from EMP table to give a complete name? SELECT FIRSTNAME || ' ' || LASTNAME FROM EMP; What is the use of VALUE function? 1. Avoid -ve SQLCODEs by handling nulls and zeroes in computations 2. Substitute a numeric value for any nulls used in computation What is UNION,UNION ALL? UNION : eliminates duplicates UNION ALL: retains duplicates Both these are used to combine the results of different SELECT statements. Suppose I have five SQL SELECT statements connected by UNION/UNION ALL, how many times should I specify UNION to eliminate the duplicate rows? - Once.

139

What is the restriction on using UNION in embedded SQL? It has to be in a CURSOR. In the WHERE clause what is BETWEEN and IN? BETWEEN supplies a range of values while IN supplies a list of values. Is BETWEEN inclusive of the range values specified? Yes. What is 'LIKE' used for in WHERE clause? What are the wildcard characters? LIKE is used for partial string matches. '%' ( for a string of any character ) and '_' (for any single character ) are the two wild card characters.

3 . DB2 and SQL Interview Questions When do you use a LIKE statement? To do partial search e.g. to search employee by name, you need not specify the complete name; using LIKE, you can search for partial string matches. What is the meaning of underscore ( '_' ) in the LIKE statement? Match for any single character. What do you accomplish by GROUP BY . HAVING clause? GROUP BY partitions the selected rows on the distinct values of the column on which you group by. HAVING selects GROUPs which match the criteria specified Consider the employee table with column PROJECT nullable. How can you get a list of employees who are not assigned to any project? SELECT EMPNO FROM EMP WHERE PROJECT IS NULL; What is the result of this query if no rows are selected:

140

SELECT SUM(SALARY) FROM EMP WHERE QUAL='MSC'; NULL Why SELECT * is not preferred in embedded SQL programs? For three reasons: If the table structure is changed ( a field is added ), the program will have to be modified Program might retrieve the columns which it might not use, leading on I/O over head. The chance of an index only scan is lost. What are correlated subqueries? A subquery in which the inner ( nested ) query refers back to the table in the outer query. Correlated subqueries must be evaluated for each qualified row of the outer query that is referred to. 4 . DB2 and SQL Interview Questions What is a cursor? why should it be used? Cursor is a programming device that allows the SELECT to find a set of rows but return them one at a time. Cursor should be used because the host language can deal with only one row at a time. How would you retrieve rows from a DB2 table in embedded SQL? Either by using the single row SELECT statements, or by using the CURSOR. Apart from cursor, what other ways are available to you to retrieve a row from a table in embedded SQL? Single row SELECTs. Where would you specify the DECLARE CURSOR statement? See answer to next question. How do you specify and use a cursor in a COBOL program? -

141

Use DECLARE CURSOR statement either in working storage or in procedure division(before open cursor), to specify the SELECT statement. Then use OPEN, FETCH rows in a loop and finally CLOSE. What happens when you say OPEN CURSOR? If there is an ORDER BY clause, rows are fetched, sorted and made available for the FETCH statement. Other wise simply the cursor is placed on the first row. Is DECLARE CURSOR executable? No. Can you have more than one cursor open at any one time in a program ? Yes. When you COMMIT, is the cursor closed? - drona questions Yes. 5 . DB2 and SQL Interview Questions How do you leave the cursor open after issuing a COMMIT? ( for DB2 2.3 or above only ) Use WITH HOLD option in DECLARE CURSOR statement. But, it has not effect in psuedo-conversational CICS programs. Give the COBOL definition of a VARCHAR field. A VARCHAR column REMARKS would be defined as follows: 10 REMARKS. 49 REMARKS-LEN PIC S9(4) USAGE COMP. 49 REMARKS-TEXT PIC X(1920). What is the physical storage length of each of the following DB2 data types: DATE, TIME, TIMESTAMP?
142

DATE: 4bytes TIME: 3bytes TIMESTAMP: 10bytes What is the COBOL picture clause of the following DB2 data types: DATE, TIME, TIMESTAMP? DATE: PIC X(10) TIME : PIC X(08) TIMESTAMP: PIC X(26)

What is the COBOL picture clause for a DB2 column defined as DECIMAL(11,2)? PIC S9(9)V99 COMP-3. Note: In DECIMAL(11,2), 11 indicates the size of the data type and 2 indicates the precision.

> 6 . DB2 and SQL Interview Questions What is DCLGEN ? DeCLarations GENerator: used to create the host language copy books for the table definitions. Also creates the DECLARE table. What are the contents of a DCLGEN? 1. EXEC SQL DECLARE TABLE statement which gives the layout of the table/view in terms of DB2 datatypes. 2. A host language copy book that gives the host variable definitions for the column names.

143

Is it mandatory to use DCLGEN? If not, why would you use it at all? It is not mandatory to use DCLGEN. Using DCLGEN, helps detect wrongly spelt column names etc. during the pre-compile stage itself ( because of the DECLARE TABLE ). DCLGEN being a tool, would generate accurate host variable definitions for the table reducing chances of error.

Is DECLARE TABLE in DCLGEN necessary? Why it used? It not necessary to have DECLARE TABLE statement in DCLGEN. This is used by the pre-compiler to validate the table-name, view-name, column name etc., during pre-compile. Will precompile of an DB2-COBOL program bomb, if DB2 is down? No. Because the precompiler does not refer to the DB2 catalogue tables. 7 . DB2 and SQL Interview Questions How is a typical DB2 batch pgm executed ? Use DSN utility to run a DB2 batch program from native TSO. An example is shown: DSN SYSTEM(DSP3) RUN PROGRAM(EDD470BD) PLAN(EDD470BD) LIB('ED 01T.OBJ.LOADLIB') END Use IKJEFT01 utility program to run the above DSN command in a JCL. Assuming that a site's standard is that pgm name = plan name, what is the easiest way to find out which pgms are affected by change in a table's structure ? Query the catalogue tables SYSPLANDEP and SYSPACKDEP. Name some fields from SQLCA. SQLCODE, SQLERRM, SQLERRD

144

How can you quickly find out the # of rows updated after an update statement? Check the value stored in SQLERRD(3). What is EXPLAIN? EXPLAIN is used to display the access path as determined by the optimizer for a SQL statement. It can be used in SPUFI (for single SQL statement ) or in BIND step (for embedded SQL ). 8 . DB2 and SQL Interview Questions What do you need to do before you do EXPLAIN? Make sure that the PLAN_TABLE is created under the AUTHID. Where is the output of EXPLAIN stored? In userid.PLAN_TABLE EXPLAIN has output with MATCHCOLS = 0. What does it mean? a nonmatching index scan if ACCESSTYPE = I. How do you do the EXPLAIN of a dynamic SQL statement? 1. Use SPUFI or QMF to EXPLAIN the dynamic SQL statement 2. Include EXPLAIN command in the embedded dynamic SQL statements How do you simulate the EXPLAIN of an embedded SQL statement in SPUFI/QMF? Give an example with a host variable in WHERE clause.) Use a question mark in place of a host variable ( or an unknown value ). e.g. SELECT EMP_NAME FROM EMP WHERE EMP_SALARY > ?

145

9 . DB2 and SQL Interview Questions What are the isolation levels possible ? CS: Cursor Stability RR: Repeatable Read What is the difference between CS and RR isolation levels? CS: Releases the lock on a page after use RR: Retains all locks acquired till end of transaction

Where do you specify them ? ISOLATION LEVEL is a parameter for the bind process. When do you specify the isolation level? How? During the BIND process. ISOLATION ( CS/RR ). I use CS and update a page. Will the lock be released after I am done with that page? No. What are the various locking levels available? PAGE, TABLE, TABLESPACE How does DB2 determine what lock-size to use? 1. Based on the lock-size given while creating the tablespace 2. Programmer can direct the DB2 what lock-size to use 3. If lock-size ANY is specified, DB2 usually chooses a lock-size of PAGE

146

What are the disadvantages of PAGE level lock? High resource utilization if large updates are to be done 10 . DB2 and SQL Interview Questions What is lock escalation? Promoting a PAGE lock-size to table or tablespace lock-size when a transaction has acquired more locks than specified in NUMLKTS. Locks should be taken on objects in single tablespace for escalation to occur.

What are the various locks available? SHARE, EXCLUSIVE, UPDATE Can I use LOCK TABLE on a view? No. To lock a view, take lock on the underlying tables. What is ALTER ? SQL command used to change the definition of DB2 objects. What is a DBRM, PLAN ? DBRM: DataBase Request Module, has the SQL statements extracted from the host language program by the pre-compiler. PLAN: A result of the BIND process. It has the executable code for the SQL statements in the DBRM. What is ACQUIRE/RELEASE in BIND? Determine the point at which DB2 acquires or releases locks against table and tablespaces, including intent locks. What else is there in the PLAN apart from the access path? PLAN has the executable code for the SQL statements in the host program

147

What happens to the PLAN if index used by it is dropped? Plan is marked as invalid. The next time the plan is accessed, it is rebound. What are PACKAGES ? They contain executable code for SQL statements for one DBRM.

> 11 . DB2 and SQL Interview Questions What are the advantages of using a PACKAGE? 1. Avoid having to bind a large number of DBRM members into a plan 2. Avoid cost of a large bind 3. Avoid the entire transaction being unavailable during bind and automatic rebind of a plan 4. Minimize fallback complexities if changes result in an error. What is a collection? a user defined name that is the anchor for packages. It has not physical existence. Main usage is to group packages. In SPUFI suppose you want to select max. of 1000 rows , but the select returns only 200 rows. What are the 2 sqlcodes that are returned? 100 ( for successful completion of the query ), 0 (for successful COMMIT if AUTOCOMMIT is set to Yes). How would you print the output of an SQL statement from SPUFI? Print the output dataset. How do you pull up a query which was previously saved in QMF ? -

148

Looks like index page split has occurred. DO a REORG of the indexes. What is dynamic SQL? Dynamic SQL is a SQL statement created at program execution time. When is the access path determined for dynamic SQL? At run time, when the PREPARE statement is issued. Suppose I have a program which uses a dynamic SQL and it has been performing well till now. Off late, I find that the performance has deteriorated. What happened? Probably RUN STATS is not done and the program is using a wrong index due to incorrect stats. Probably RUNSTATS is done and optimizer has chosen a wrong access path based on the latest statistics. How does DB2 store NULL physically? as an extra-byte prefix to the column value. physically, the nul prefix is Hex '00' if the value is present and Hex 'FF' if it is not. 12 . DB2 and SQL Interview Questions How do you retrieve the data from a nullable column? Use null indicators. Syntax . INTO :HOSTVAR:NULLIND What is the picture clause of the null indicator variable? S9(4) COMP. What does it mean if the null indicator has -1, 0, -2? -1 : the field is null 0 : the field is not null -2 : the field value is truncated

149

How do you insert a record with a nullable column? To insert a NULL, move -1 to the null indicator To insert a valid value, move 0 to the null indicator What is RUNSTATS? A DB2 utility used to collect statistics about the data values in tables which can be used by the optimizer to decide the access path. It also collects statistics used for space management. These statistics are stored in DB2 catalog tables. When will you chose to run RUNSTATS? After a load, or after mass updates, inserts, deletes, or after REORG.

13 . DB2 and SQL Interview Questions Give some example of statistics collected during RUNSTATS? # of rows in the table Percent of rows in clustering sequence # of distinct values of indexed column # of rows moved to a nearby/farway page due to row length increase What is REORG? When is it used? REORG reorganizes data on physical storage to reclutser rows, positioning overflowed rows in their proper sequence, to reclaim space, to restore free space. It is used after heavy updates, inserts and delete activity and after segments of a segmented tablespace have become fragmented. What is IMAGECOPY ? It is full backup of a DB2 table which can be used in recovery. When do you use the IMAGECOPY? 150

To take routine backup of tables After a LOAD with LOG NO After REORG with LOG NO What is COPY PENDING status? A state in which, an image copy on a table needs to be taken, In this status, the table is available only for queries. You cannot update this table. To remove the COPY PENDING status, you take an image copy or use REPAIR utility. 14 . DB2 and SQL Interview Questions What is CHECK PENDING ? When a table is LOADed with ENFORCE NO option, then the table is left in CHECK PENDING status. It means that the LOAD utility did not perform constraint checking. What is QUIESCE? A QUIESCE flushes all DB2 buffers on to the disk. This gives a correct snapshot of the database and should be used before and after any IMAGECOPY to maintain consistency. What is a clustering index ? Causes the data rows to be stored in the order specified in the index. A mandatory index defined on a partitioned table space. How many clustering indexes can be defined for a table? Only one. What is the difference between primary key & unique index ? Primary : a relational database constraint. Primary key consists of one or more columns that uniquely identify a row in the table. For a normalized relation, there is one designated primary key. Unique index: a physical object that stores only unique values. There can be one or more unique indexes on a table.

151

What is sqlcode -922 ? Authorization failure What is sqlcode -811? SELECT statement has resulted in retrieval of more than one row. 15 . DB2 and SQL Interview Questions What does the sqlcode of -818 pertain to? This is generated when the consistency tokens in the DBRM and the load module are different. Are views updateable ? Not all of them. Some views are updateable e.g. single table view with all the fields or mandatory fields. Examples of non-updateable views are views which are joins, views that contain aggregate functions(such as MIN), and views that have GROUP BY clause. If I have a view which is a join of two or more tables, can this view be updateable? No. What are the 4 environments which can access DB2 ? TSO, CICS, IMS and BATCH What is an inner join, and an outer join ? Inner Join: combine information from two or more tables by comparing all values that meet the search criteria in the designated column or columns of on e table with all the clause in corresponding columns of the other table or tables. This kind of join which involve a match in both columns are called inner joins. Outer join is one in which you want both matching and non matching rows to be returned. DB2 has no specific operator for outer joins, it can be simulated by combining a join and a correlated sub query with a UNION. What is FREEPAGE and PCTFREE in TABLESPACE creation? PCTFREE: percentage of each page to be left free
152

FREEPAGE: Number of pages to be loaded with data between each free page

> 16 . DB2 and SQL Interview Questions What are simple, segmented and partitioned table spaces ? Simple Tablespace: Can contain one or more tables Rows from multiple tables can be interleaved on a page under the DBAs control and maintenance Segmented Tablespace: Can contain one or more tables Tablespace is divided into segments of 4 to 64 pages in increments of 4 pages. Each segment is dedicated to single table. A table can occupy multiple segments Partitioned Tablespace: Can contain one table Tablespace is divided into parts and each part is put in a separate VSAM dataset. What is filter factor? one divided by the number of distinct values of a column. What is index cardinality? The number of distinct values a column or columns contain. What is a synonym ? Synonym is an alternate name for a table or view used mainly to hide the leading qualifier of a table or view.. A

153

synonym is accessible only by the creator. What is the difference between SYNONYM and ALIAS? SYNONYM: is dropped when the table or tablespace is dropped. Synonym is available only to the creator. ALIAS: is retained even if table or tablespace is dropped. ALIAS can be created even if the table does not exist. It is used mainly in distributed environment to hide the location info from programs. Alias is a global object & is available to all. What do you mean by NOT NULL WITH DEFAULT? When will you use it? This column cannot have nulls and while insertion, if no value is supplied then it wil have zeroes, spaces or date/time depending on whether it is numeric, character or date/time. Use it when you do not want to have nulls but at the same time cannot give values all the time you insert this row. 17 . DB2 and SQL Interview Questions What do you mean by NOT NULL? When will you use it? The column cannot have nulls. Use it for key fields. When would you prefer to use VARCHAR? When a column which contains long text, e.g. remarks, notes, may have in most cases less than 50% of the maximum length. What are the disadvantages of using VARCHAR? 1. Can lead to high space utilization if most of the values are close to maximum. 2. Positioning of VARCHAR column has to be done carefully as it has performance implications. 3. Relocation of rows to different pages can lead to more I/Os on retrieval. How do I create a table MANAGER ( EMP#, MANAGER) where MANAGER is a foreign key which references to EMP# in the same table? Give the exact DDL.

154

First CREATE MANAGER table with EMP# as the primary key. Then ALTER it to define the foreign key. When is the authorization check on DB2 objects done - at BIND time or run time? At run time. What is auditing? Recording SQL statements that access a table. Specified at table creation time or through alter. J2EE - CORBA I 1 . Corba Interview Questions What is CORBA? What does it do? CORBA is the acronym for Common Object Request Broker Architecture, OMG's open, vendor-independent architecture and infrastructure that computer applications use to work together over networks. Using the standard protocol IIOP, a CORBA-based program from any vendor, on almost any computer, operating system, programming language, and network, can interoperate with a CORBA-based program from the same or another vendor, on almost any other computer, operating system, programming language, and network. What is CORBA good for? CORBA is useful in many situations. Because of the easy way that CORBA integrates machines from so many vendors, with sizes ranging from mainframes through minis and desktops to hand-helds and embedded systems, it is the middleware of choice for large (and even not-so-large) enterprises. One of its most important, as well most frequent, uses is in servers that must handle large number of clients, at high hit rates, with high reliability. CORBA works behind the scenes in the computer rooms of many of the world's largest websites; ones that you probably use every day. Specializations for scalability and fault-tolerance support these systems. But it's not used just for large applications; specialized versions of CORBA run real-time systems, and small embedded systems. 2 . Corba Interview Questions Can you give me high-level technical overview? CORBA applications are composed of objects, individual units of running software that combine functionality and data, and that frequently (but not always) represent something in the real world. Typically, there are many instances of an object of a single type - for example, an e-commerce website would have many shopping cart object

155

instances, all identical in functionality but differing in that each is assigned to a different customer, and contains data representing the merchandise that its particular customer has selected. For other types, there may be only one instance. When a legacy application, such as an accounting system, is wrapped in code with CORBA interfaces and opened up to clients on the network, there is usually only one instance. For each object type, such as the shopping cart that we just mentioned, you define an interface in OMG IDL. The interface is the syntax part of the contract that the server object offers to the clients that invoke it. Any client that wants to invoke an operation on the object must use this IDL interface to specify the operation it wants to perform, and to marshal the arguments that it sends. When the invocation reaches the target object, the same interface definition is used there to unmarshal the arguments so that the object can perform the requested operation with them. The interface definition is then used to marshal the results for their trip back, and to unmarshal them when they reach their destination. The IDL interface definition is independent of programming language, but maps to all of the popular programming languages via OMG standards: OMG has standardized mappings from IDL to C, C++, Java, COBOL, Smalltalk, Ada, Lisp, Python, and IDLscript. For more on OMG IDL, click here. This separation of interface from implementation, enabled by OMG IDL, is the essence of CORBA - how it enables interoperability, with all of the transparencies we've claimed. The interface to each object is defined very strictly. In contrast, the implementation of an object - its running code, and its data - is hidden from the rest of the system (that is, encapsulated) behind a boundary that the client may not cross. Clients access objects only through their advertised interface, invoking only those operations that that the object exposes through its IDL interface, with only those parameters (input and output) that are included in the invocation.

Figure 1 shows how everything fits together, at least within a single process: You compile your IDL into client stubs and object skeletons, and write your object (shown on the right) and a client for it (on the left). Stubs and skeletons serve as proxies for clients and servers, respectively. Because IDL defines interfaces so strictly, the stub on the client side has no trouble meshing perfectly with the skeleton on the server side, even if the two are compiled into different programming languages, or even running on different ORBs from different vendors. In CORBA, every object instance has its own unique object reference, an identifying electronic token. Clients use the object references to direct their invocations, identifying to the ORB the exact instance they want to invoke (Ensuring, for example, that the books you select go into your own shopping cart, and not into your neighbor's.) The client acts as if it's invoking an operation on the object instance, but it's actually invoking on the IDL stub which acts as a proxy. Passing through the stub on the client side, the invocation continues through the ORB (Object Request Broker), and the skeleton on the implementation side, to get to the object where it is executed.

3 . Corba Interview Questions How do remote invocations work?

156

Figure 2 diagrams a remote invocation. In order to invoke the remote object instance, the client first obtains its object reference. (There are many ways to do this, but we won't detail any of them here. Easy ways include the Naming Service and the Trader Service.) To make the remote invocation, the client uses the same code that it used in the local invocation we just described, substituting the object reference for the remote instance. When the ORB examines the object reference and discovers that the target object is remote, it routes the invocation out over the network to the remote object's ORB. (Again we point out: for load balanced servers, this is an oversimplification.)

How does this work? OMG has standardized this process at two key levels: First, the client knows the type of object it's invoking (that it's a shopping cart object, for instance), and the client stub and object skeleton are generated from the same IDL. This means that the client knows exactly which operations it may invoke, what the input parameters are, and where they have to go in the invocation; when the invocation reaches the target, everything is there and in the right place. We've already seen how OMG IDL accomplishes this. Second, the client's ORB and object's ORB must agree on a common protocol - that is, a representation to specify the target object, operation, all parameters (input and output) of every type that they may use, and how all of this is represented over the wire. OMG has defined this also - it's the standard protocol IIOP. (ORBs may use other protocols besides IIOP, and many do for various reasons. But virtually all speak the standard protocol IIOP for reasons of interoperability, and because it's required by OMG for compliance.) Although the ORB can tell from the object reference that the target object is remote, the client can not. (The user may know that this also, because of other knowledge - for instance, that all accounting objects run on the mainframe at the main office in Tulsa.) There is nothing in the object reference token that the client holds and uses at invocation time that identifies the location of the target object. This ensures location transparency - the CORBA principle that simplifies the design of distributed object computing applications. CAN CORBA ALLOW SERVERS TO CAUSE CLIENT SIDE EVENTS OR NOTIFICATIONS? CORBA communication is inherently asymmetric. Request messages originate from clients and responses originate from servers. The important thing to realize is that a CORBA server is a CORBA object and a CORBA client is a CORBA stub. A client application might use object references to request remote service, but the client application might also implement CORBA objects and be capable of servicing incoming requests. Along the same lines, a server process that implements CORBA objects might have several object references that it uses to make requests to other CORBA objects. Those CORBA objects might reside in client applications. By implementing a CORBA object within an client application, any process that obtains its object reference can "notify" it by performing an operation on the client-located object.

> 4 . Corba Interview Questions

157

WHY WOULD APPLICATIONS REQUIRE ASYNCHRONOUS COMMUNICATIONS? Performance is the most common reason. Applications that perform a series of tasks that must be done sequentially cannot benefit from asynchronous communication. Applications that make only short duration remote operations have little need for asynchronous communication. Asynchronous communication can allow an application to perform additional tasks instead of waiting for tasks to complete. Applications that have a number of tasks that can be performed in any order can often benefit from distributed asynchronous communication. This becomes more important for applications that call lengthy remote operations. In order to benefit from asynchronous communication, an application must be able to perform some task after the request is issued but before the response is available. Tasks might include prompting for additional user input, displaying information, or making additional remote operation requests. Typical asynchronous communication candidates include applications that need to perform several lengthy database queries or complex calculations. DOES CORBA SUPPORT ASYNCHRONOUS COMMUNICATION? Kind of. At the lowest level CORBA supports two modes of communication: A synchronous request/response which allows an application to make a request to some CORBA object and then wait for a response. A deferred synchronous request/response which allows an application to make a request to some CORBA object. An empty result will be returned immediately to the application. It can then perform other operations and later poll the ORB to see if the result has been made available. At the lowest level, the CORBA deferred synchronous communication does allow a certain degree of asynchronous communication. Polling for responses represents only one form of asynchronous communication. Other more sophisticated asynchronous communication can only be achieved by developing an architecture on top of the lowest levels of CORBA. ARE APPLICATION THREADING AND ASYNCHRONOUS COMMUNICATION RELATED? Theoretically, no. They come from different families but hang out together a lot. Each has its own identity, but sometimes they can work together to make things go much more smoothly. Applications that wish to perform multiple concurrent tasks can use multiple threads instead of multiple asynchronous or deferred requests. Just as the distribution of operations across processes can allow for concurrent processing, performing tasks in different threads can allow for concurrent processing. Distribution supports concurrent processing across a network and threading supports concurrent processing within a particular machine. An application that needs to perform concurrent distributed requests can issue requests in different threads or issue asynchronous requests. The use of threading adds complex synchronization issues to the development process. 5 . Corba Interview Questions

158

ARE THERE IMPORTANT FORMS OF ASYNCHRONOUS COMMUNICATION THAT AREN'T SUPPORTED DIRECTLY BY CORBA? Yeah, but you can fake it pretty easily. While CORBA does support a deferred synchronous request/response, it does not directly support distributed requests with a callback driven response. A callback driven response allows an application to perform an operation on a distributed object, associate a callback with the response, continue with other processing. When the server responds, the associated callback is automatically executed within the original caller's application. CAN CORBA APPLICATIONS BE MULTI-THREADED? The CORBA specification does not currently address multi-threaded architectures. Provided that the CORBA product is thread safe, threaded CORBA applications can be developed. CORBA clients and servers can both be multi-threaded. Daemon processes provided with CORBA products may be implemented as multi-threaded servers by the CORBA vendor. Different multi-threaded models or multi-threaded architectures may be supported by a particular CORBA product. A particular ORB may provide frameworks to simplify the development of multithreaded CORBA applications. WHY WOULD I DECIDE TO IMPLEMENT A CORBA CLIENT APPLICATION WITH MULTITHREADING? Client-side CORBA applications might require multi-threading to allow it to perform other tasks while it is waiting for a synchronous remote invocation to return. It might desire this functionality for several different reasons. A client application might wish to leverage the static request/response style of invocation but achieve some degree of asynchronous communication. Perhaps the client wishes to perform several synchronous invocations within their own application threads. This would allow a client to obtain results from several remote servers more quickly. There are several reasons the use of multi-threading might be preferred over the use of DII. DII might be complicate application source code. Application polling associated with the deferred synchronous invocation might result in a performance bottleneck. A client-side CORBA application might need to respond to events such as incoming invocations, connect requests, or GUI events (mouse clicks, etc.) CORBA products that support only blocking style remote invocations will be unable to process any of these events. This would mean that a client-side application would be unable to respond to GUI events for the duration of any remote CORBA invocations. This is not an issue for short duration invocations but becomes a problem for longer invocations or in failure or time-out situations. Performing remote invocations within dedicated threads can avoid this issue. WHY WOULD I DECIDE TO IMPLEMENT A CORBA SERVER APPLICATION WITH MULTITHREADING? CORBA server applications may be multi-threaded for serveral reasons.
159

A particular CORBA object may support an operation whose implementation performs some blocking routine. This may be a disk read or database query. Let us assume that the server application processes all CORBA events within a single main thread. This means that the server will be unable to respond to incoming connection requests or invocation requests while the blocking operation is in progress. Multi-threading can be used to avoid these sorts of situations. The server can be more accessible if multiple threads are allowed to process (an block during) incoming CORBA events. A single multi-threaded server process supporting many (>25) clients is much more efficient that many (>25) single-threaded server processes each supporting its own client. Running a single application with multiple threads requires less machine resources than running multiple applications. This advantage can be seen even if the operation invocations are of short duration and non-blocking. 6 . Corba Interview Questions ARE THERE DIFFERENT THREADING MODELS THAT CAN BE USED WITHIN CORBA SERVERS? There are several different common architectures that can be used within multi-threaded CORBA servers. A server process needs the ability to process CORBA messages. These messages are processed by one or more threads, as determined by the application architecture. The CORBA specification does not specifically address threading capabilities within CORBA compliant ORBs. An ORB vendor is free to support only single-threaded application or to support multi-threaded applications. If the ORB does support the development of multi-threaded applications, the ORB might only support a subset of the threading models listed below. Significant threading code might still need to be developed to achieve one of the models. For example, the ORB vendor might support a set of application hooks (i.e., interceptors or filters) and allow you to implement threading code with the native OS thread API. On the other hand, the ORB product might provide a built-in feature so no custom thread development needs to be done. The CORBA specification does not address this issue. When you consider different threading models, it is important to consider what kind of concurrency is desired. While it may be advantageous that two or more threads can be concurrent, it may also be disadvantageous. Also, the resources consumed by idle or active threads, and also the resources consumed for thread creation and deletion, need to be considered. Thread-Per-Request: With this architecture, the CORBA server ensures that each incoming message is processed in its own thread. This means that multiple requests will be processed concurrently. There are concurrency issues. If two or more requests (threads) are using the same object, then some form of concurrency control (locking) is needed. Also, if two or more requests (threads) are from the same client, then perhaps the requests should be serialized instead of allowed to execute concurrently. Thread-Per-Client: With this architecture, the CORBA server ensures that each incoming message from a distinct client is processed in its own thread. This is similar to Thread-Per-Request except multiple requests from the same client are serialized. Requests from distinct clients are concurrent. The way that one client is distinguished from

160

another is an interesting problem. Typically, this is done by looking a the network connection and determining that the clients are the same or different. The server needs the ability to monitor client connections and the inception and termination of this connections (typically at a network level, not an application level). Thread-Per-Server-Object: With this architecture, the CORBA server ensures that each object in the server gets it own thread of execution. This means that multiple requests will be processed concurrently provided they are using different objects. Multiple requests using the same object are serialized. There are concurrency issues, and some locking strategy is needed. Also, deadlock is very possible. It may be that threading or locking at each object is too fine a grain, and a more appropriate choice is putting the thread/lock boundary around a group of coordinating objects. For each of the above threading architectures, the required server threads can be either created on demand or recycled through a thread pool. The advantage of creating threads on demand is that an arbitrary number of threads can be supported. A thread is created, used, and then reaped. The Thread-Per-Request model would create/reap a thread for each request; the Thread-Per-Client model would create/reap a thread for each client connection; the Thread-Per-Server-Object model would create/reap a thread for each CORBA object instantiated in the server. Thread creation and reaping has some cost, which may be large or small depending on the operating system thread support. A thread pool is an alternative to creating threads on demand. In this approach, a fixed number of threads are created and cycled in turn to meet the demand for threads. If the demand for threads exceeds the pool size, then further requests for threads are blocked until one of the existing threads is recycled. This approach has the advantage of capping the server resources. ARE THERE REASONS TO AVOID THE DEVELOPMENT OF MULTI-THREADED CORBA APPLICATIONS ? Building multi-threaded applications requires an additional efforts in the area of design, development and testing. Issues like concurrency and synchronization become more critical. Difficult to find software bugs are unfortunately easy to introduce. A specific set of application requirements can often be met without resorting to the use of threaded clients or servers. This is not true with all applications. Some do require multi-threading to achieve their desired level of concurrency, performance or scalability. 7 . Corba Interview Questions DOES CORBA DEFINE HIGH LEVEL APPLICATION ARCHITECTURES? No, it's infrastructure. Which is good because the history of high-level "one size fits all" architectures hasn't been very good, has it? CORBA provides low level request/response communication. It also provides general services that are implemented on top of request/response communication. The actual architecture used within a given application is not defined by

161

CORBA. CORBA leaves these decisions up the application architect. DO COMMON APPLICATION ARCHITECTURES EXIST? There are many common application architectures that can be used within a CORBA based application. Some architectures are related to the way in which a CORBA object is referenced, and a few of these are described below. NON-EXCLUSIVE OBJECTS VS. EXCLUSIVE OBJECTS: Non-Exclusive Objects: A non-exclusive object is typically used to provide a common service to many client applications. A server process creates a single instance of a distributed object. This object can be named or is defined as an initial service. Clients obtain an object reference to the CORBA object by using the CORBA name service or by calling ORB::resolve_initial_references(). The non-exclusive object also provides an excellent mechanism to share data or information between connected clients. This is what EJB calls an EntityBean. Exclusive objects: An exclusive object is an object that is referred to by only one client application. Exclusive object can live in their own server process or many exclusive objects can live in the same server process. The Object Adapter can be used to control the process boundaries. The deprecated BOA unshared activation policies can be used to ensure that each exclusive object lives in its own process. The POA and POA Locator can be used to control which objects are in which processes. Exclusive objects can ensure that no data or event conflict exists between clients. For example, let us assume that a CORBA object will perform a lengthy database query. By deploying the exclusive object in its own process, client applications will completely control the behavior of the server. The combination of an exclusive object and the unshared activation policy ensure that a server can provide its total attention to its client. The CORBA object will never need to share server side processing with some other CORBA object. It is the responsibility of the applications to ensure that an exclusive object is refereed to by only one client application. This is what EJB calls a SessionBean. Note: Object level properties such as "non-exclusive" or "exclusive" are orthogonal to the the Object Adapter used to make the CORBA object available to the system. OTHER ARCHITECTURAL DISTINCTIONS MADE AT THE OBJECT LEVEL: Stateful Objects: A stateful object is an object that maintains and changes internal state over time. If an object consists of data and methods, a stated object is an object who maintains and alters its data during the invocation of its methods. Stateful objects can exhibit behavior that varies based upon what the object has already done. For example, a get_next_item() method maintains returns the next item each time it is called. This behavior is enabled by saving state associated with the current record. State is specific to the object. Different objects in the same server process maintain their own state. In the case of an exclusive stateful object, state is specific to a given client application. Stateful non-exclusive object maintain a common state across a set of client applications. While stateful objects are very powerful, server-side failures can present problems. For example, let us assume that a client is scrolling through a set of records maintained by a CORBA object. If the CORBA server fails its state could be lost. The CORBA object is capable of being reactivated but the appropriate record would not be returned when the get_next_item() operation was called. Client applications might need to recreate their state within the new object. Another option would be for the object to persist its state and retrieve its state upon reactivation. In EJB, EntityBeans are implicitly stateful and SessionBeans are designated as either stateless or stateful.
162

Stateless Objects: A stateless object is an object that does not maintain any internal state specific to the invocation of methods. Stateless objects are not suitable for all applications. Stateless objects may perform the same functions as a stateful object. They might require "state" information to be passed as parameters. Stateless objects can allow for more flexibility with respect to fail- over, scaling across servers or dynamic load balancing. In the case of failure, servers and objects can be easily reactivate without worrying about prior state changes. With stateless objects, a client can perform operations on any object of the correct type. This means that it is possible for a collection of servers supporting the same interface to servicing clients. This can increase system scaling dramatically. In EJB, EntityBeans are implicitly stateful and SessionBeans are designated as either stateless or stateful.

8 . Corba Interview Questions CAN CORBA APPLICATIONS HAVE CALLBACKS? Yes. The words client and server are really only applicable in the context of a remote call. In other words, the "client process" can also receive calls on CORBA objects that it implements and hands out the references to. WHAT IS AN OBJECT REFERENCE? A transient, opaque handle that identifies an object instance in your ORB. An object reference is the identifier needed to invoke methods on objects. Object references are not global identifiers that are valid across all machines in a distributed network. Their scope is limited to your local ORB. WHY A HANDLE RATHER THAN A "HARD" ADDRESS? CORBA is a dynamic environment and objects move around in an unpredictable manner. You need a soft locator rather than something static and brittle. FOR HOW LONG IS AN OBJECT REFERENCE VALID? Only during the session while your client is connected to the ORB. If a target object moves during a session, the ORB will provide the equivalent of a transparent forwarding mechanism. WHAT IF I WANT A PERSISTENT REFERENCE? Stringify the object reference and save it in a persistent medium. But, we have to warn you, you're about to get into deep water. Maybe you should just skip to the section on Naming Service, unless you want to be an "expert".

163

HOW DO I STRINGIFY AN OBJECT REFERENCE? Use object_to_string(), and reverse the process using string_to_object(). There is some magic in string_to_object(); it not only does the necessary string-to-pointer conversion, it ensures that you get a currently valid object reference that is equivalent to the original reference that was stringified (i.e., both refer to the same object instance). WHAT IS THE FORMAT OF AN OBJECT REFERENCE? We can't tell you because there is no standard for this. OMG wanted to give ORB implementers as much freedom as possible to develop efficient, possibly platform-dependent schemes. Thus, the references are opaque and should be thought of as an interface without regard for their implementation. 9 . Corba Interview Questions WHO CREATES OBJECT REFERENCES? Some ORB calls such as resolve_initial_references() and string_to_object() generate an object reference. The object it refers to might or might not exist (the act of using the object reference can result in the creation of the actual object). Also, a factory might create an object reference by creating an object implementation within the same process. The factory could generate the object reference and cause an object to be created (as above), or the factory could obtain the object reference from some other source (NameService, TraderService). HOW DO I COMPARE REFERENCES? Use is_equivalent(), but don't take it too seriously. This method never lies to you, if it says two references are equivalent, then they are. But they might be equivalent but not identical and is_equivalent() can potentially return false. See the October 1996 column by Steve Vinoski and Doug Schmidt in C++ Report. WHAT OTHER SURPRISES ARE THERE WITH IS_EQUIVALENT()? Remember that is_equivalent() is invoked on one of the two objects, and there are cases where this can cause deadlock. The following example illustrates how this can happen on one particular single-threaded ORB that won't allow a server to invoke a method on the client (contributed by Jeff Stewart, jstewart+@andrew.cmu.edu; used with permission): Suppose a server receives updates from cached clients and then has to update all clients except for the one that reported (updating the reporting client would cause a deadlock on this ORB). So, as the server iterates through its client list it must ensure that it does not invoke the reporting client. But it can't use is_equivalent() because this will

164

eventually cause an invocation on the reporting client just to do the is_equivalent() check, inadvertently creating a deadlock. IS THAT ALL OF THE BAD NEWS ABOUT IS_EQUIVALENT()? Not really. You also have to remember that it typically requires network traffic. It's easy to fall into the wishful thinking that the ORB can handle is_equivalent() for you, but, in general, it doesn't. SO WHY DON'T WE JUST COMPARE STRINGIFIED REFERENCES? First, the object may have moved in between the times that its references were stringified, so the strings may not be identical. Also, there are potential problems if you have multiple vendors because stringified object references can be quite ORB-specific. 10 . Corba Interview Questions THIS SOUNDS TOO COMPLICATED. SHOULD I JUST LEARN DCOM INSTEAD? No, not at all. We've taken you into the depths of a topic that has deep philosophical roots, which has been the focus of arguments for many years. Most people never need this kind of knowledge. We warned you earlier, didn't we? And you just had to know, didn't you? WHY DO YOU SAY, "MOST PEOPLE NEVER NEED THIS KIND OF KNOWLEDGE"? From a practical standpoint, these considerations don't come up all that often, even for people who have to work at this level. Fortunately, most users can merely use the Naming Service and work with (essentially) character strings for names, and avoid all the complexity above. THEN WHY DID YOU JUST DRAG US THROUGH THE MUD? You're the one who wanted to be an expert. We just wanted to raise your awareness so that you'll think twice when comparing object references. Besides, this is a good way to illustrate how CORBA requires a little learning on your part. WHEN DO I USE _VAR INSTEAD OF _PTR? Use _var when you can, because they are simpler. Use _ptr when you have to, usually for performance reasons. Sometimes there are critical windows you can't afford to let the system take over memory management. As a very rough guide, think about _ptr when you have many fine-grained objects and known timing or performance

165

problems. WHAT IF I WANT TO INVOKE METHODS ON AN OBJECT IN ANOTHER ORB? Then you need to know about interoperable object references (IOR). DOES AN IOR HAVE A DEFINED FORMAT AND, IF SO, WHY? Yes, because this is something that inherently requires cooperation between different vendors and ORBs. Ordinary object references exist within an ORB so there was no compelling reason to standardize formats. WHAT IS THE FORMAT OF AN IOR? The specific details can be found at the OMG web site, and probably shouldn't matter to you. But it doesn't hurt to know that an IOR consists of a type ID and one or more tagged profiles.

> 11 . Corba Interview Questions WHAT IS A TAG? A tag indicates the protocol ID from the most recent protocol change as the IOR flowed from its home ORB to your local ORB (we'll discuss what this is all about when we get into more detail on bridges and interoperability), and is something that is registered with OMG; for instance, IIOP has an ID of zero. WHAT IS A PROFILE? A high-performance way for an ORB to tell another ORB what it needs to know to use the IOR properly. There are two types, single- and multiple-component. Both typically contain information about the presence of ORB services such as Transaction Service. WHAT IS THE DIFFERENCE BETWEEN THE TWO TYPES OF PROFILES? It depends. Profiles are defined by the people who developed the protocol and registered its tag with OMG. IIOP uses a single-component profile, while DCE CIOP uses a multiple-component profile. WHY DID YOU SAY THAT THE SPECIFIC DETAILS PROBABLY SHOULDN'T MATTER? You'll probably never need them because you'll probably never see an example of an IOR. These only exist in the
166

nether world between ORBs. BUT HOW DOES MY PROGRAM USE AN IOR? It doesn't. Your local ORB creates a local proxy for the remote object represented by the IOR. All your program ever sees directly is the object reference for the proxy. The ORB takes care of everything else. WHAT ABOUT STRINGIFYING AN IOR? You never learn, do you? Let's discuss this at another time. When you are in a position where you need this knowledge, you won't be getting your information from this document. In the meantime, learn all about Naming Service. WHEN I OBTAIN AN OBJECT REFERENCE, WHAT DETERMINES IF IT IS AN IOR OR JUST AN OR? If you create the object reference from a string via a CORBA 2.0 compliant library then the object reference is an IOR. If you create the object reference via resolve_initial_references() the ORB libraries might create an OR or an IOR. Some ORBs from companies such as Expersoft and Visigenic ORBs support only native IIOP and thus all references are IORs. On the other hand, some commericial vendors who shipped ORBS that supported IDL before IIOP existed pass around references that are not IORs and thus these referencesmight not always be IORs. Many cases an ORB vendor might support a proprietary protocol in addition to IIOP. Note: even if resolve_initial_references() returns and IOR, the IOR almost always refers to an object implemented with the same ORB environment as the application calling resolve_initial_references(). If the object reference is obtained from a server, a NameContext, or from a factory, the process and ORB libraries that originially created the object reference, determine if the reference is an OR or an IOR. 12 . Corba Interview Questions WHAT IS A FACTORY? A factory is a CORBA Object that returns another CORBA object via one of its CORBA operations. There are many different types of factories with many different purposes. In fact, the OMG has defined several services that are actually factories. WHAT ARE SOME TYPICAL TYPES OF FACTORIES? There are several types of factories:

167

Generic: A generic factory is a factory (CORBA Object) that is capable of returning other CORBA Objects. These CORBA Objects are generic. This means that they can be of any type, rather than a specific type. The SomeFactory::GenericCreate() operation causes the SomeFactory interface to be a generic factory. The NamingContext object defined as part of the CORBA Naming Service is a classic example of a generic factory. Specific: A specific factory is a factory (CORBA Object) that is capable of returning a specific type of pre-defined CORBA Object. The SomeFactory::SpecificCreate() operation causes the SomeFactory interface to be a specific (or typed) factory. In-process: An in-process factory is a factory which is implemented in the same process as the object which is created or managed by it. Out-process: An out-process factory is a factory which is implemented in a process different from the one of the object which is created or managed by it. interface AnObject { boolean ping(); }; interface SomeFactory { CORBA::Object GenericCreate(); AnObject SpecificCreate(); }; DOES THE CORBA SPECIFICATION DEFINE ANY SPECIFIC CAPABILITIES FOR A FACTORY OBJECT? The CORBA Lifecycle specification defines a GenericFactory interface from which all factories should inherit, but this is not required. The CORBA specification also defines a factory for factories, known as a factory finder. The factory finder is a just a CORBA factory which act as a factory for other factory interfaces. WHAT IS A DISTRIBUTED REFERENCE COUNTING ARCHITECTURE? Distributed reference counting is something typically performed either by a remote object, the factory for the remote object or possibly by the ORB itself. The key concept is that something is tracking the number of connections to a particular remote object. The counter is incremented when a new reference to the remote object is created. The counter is decremented when a reference to the remote object is destroyed. The idea is that by looking at the counter, one can determine if the remote object is still in use.

168

13 . Corba Interview Questions WHY WOULD AN APPLICATION IMPLEMENT A DISTRIBUTED REFERENCE COUNTING ARCHITECTURE? There are several reasons why reference counting might be important. Clean-up: An application might like to know that a remote object no longer has active references. The typical reason is that object that are no longer in use can be removed from memory. This allows resources associated with a remote object to be reclaimed. This is especially important if a distinct remote object exists for each client application. Reporting: In many cases it might be helpful to know the usage patterns for a particular remote object. Without reference counting, an object could only report the total number of method invocations performed. Information regarding the number of connected clients or average usage per client would only be available if a reference counting architecture was in place. Load Balancing: In some cases, a client might gain access to a remote object via an out-of-process factory. The goal of the factory might be to support clients via a pool of remote objects hosted on different machines. The factory can choose which remote object to return based on actual usage. Reference counting might be one mechanism for determining a remote object's "load". DOES CORBA SUPPORT DISTRIBUTED REFERENCE COUNTING ARCHITECTURES? CORBA does not directly support distributed reference counting. This was a conscious decision on the part of its designers. While CORBA does not directly support reference counting, it is possible to build reference counting into a particular distributed object architecture. This can be done through an explicit session management facility which can be exposed through factories or other remote interfaces. While it is possible to design reference counting into an application, it is the burden of the application designer/developer to ensure that such an approach is implemented correctly. WHAT PROBLEMS MIGHT BE ASSOCIATED WITH A DISTRIBUTED REFERENCE COUNTING ARCHITECTURE? The designers of the CORBA specification chose not to support distributed reference counting for several specific reasons. Error prone: Distributed reference counting relies upon the developer to properly increment and decrement the reference counting mechanism. Failure to do so can result in disappearing objects or orphaned objects that have no users. Performance problems: In some cases, clients terminate abnormally without properly releasing references. This results in reference counts not being decremented. In order to survive such situations without leaving remote object orphaned, objects must occasionally ping clients to determine if they are alive. This can result in excessive network traffic and cause performance problems. No support for persistent object references: CORBA allows object references to be stringified, stored, and
169

objectified without losing their remote context. An object reference can be considered valid even if its connection terminates or if the remote object is destroyed. Supporting both persistent object references and reference counting is very difficult since counting stringified object references may not be possible. Some distributed frameworks such as DCOM are built around a distributed reference counting architecture. 14 . Corba Interview Questions IS THERE AN ALTERNATIVE TO DISTRIBUTED REFERENCE COUNTING ARCHITECTURES? Yes: connection-less architectures. With a connection-less architecture, an object does not "know" any thing about the object references which refer to it, including the number of references. This is the style found most often on the World Wide Web. CAN CORBA APPLICATIONS BE TUNED FOR BETTER PERFORMANCE? There are a number of ways to tune CORBA applications for better performance. Remember that distribution should only be used if a reason to do so exists. Distribution does not make sense for the sake of distribution. If distribution does not serve a purpose then it should be avoided. Avoiding excessive distribution can result in better performance. Care should be taken when introducing distribution into an applications object model. IDL interfaces can be tuned to minimize network latency. Invoking remote operations requires transmitting data across the network. Network performance is typically optimized by ensuring adequate bandwidth. Once the required bandwidth is achieved raw network performance cannot be increased. One key to tuning an IDL interface is to reduce the number of network transfers that need to occur. Calling an operation that returns 100 bytes might take 5 milliseconds. Calling an operation that returns 200 bytes of data might take around 6 milliseconds. Calling 2 operations that return 100 bytes might take a total of 10 milliseconds. One key to tuning IDL operations is to avoid implementing several get operations and to combine them into a single get operation which returns the appropriate combination of data. Caching results of remote operations can avoid network overhead associated with calling the same remote methods more than once. Many applications can perform remote operations upon startup rather than during normal usage. Users are often more willing to wait at startup time rather than during application usage. Many performance problems are associated with serialization and blocking conditions. For example, Let us assume that clients will be making remote operations to a single server. A single client's request causes the server to block for a extended period of time, the entire client community might have to wait. Make sure that multiple distributed operations are not becoming serialized within a single server process. Utilize multiple server processes or threaded servers instead. DO DIFFERENT CORBA IMPLEMENTATIONS PERFORM AT SIGNIFICANTLY DIFFERENT

170

LEVELS? They can. Different CORBA implementations can vary significantly in performance. Good implementations should be fairly similar since network performance defines the maximum achievable performance characteristics. Network latency does represent the significant portion of distributed invocation latency. 15 . Corba Interview Questions WHAT TYPES OF PERFORMANCE SHOULD I BE CONCERNED WITH? There are many different performance characteristics that are important. Performance should also scale linearly as connections or objects increase. While raw throughput between one client and one server is important, it is not the only or the most critical characteristic. Many characteristics of the CORBA implementation should be considered. As always, actual application requirements to the relative importance of these different characteristics. With the high speed nature of most CORBA implementations, raw client/server throughput is often not a bottleneck. It is also important that factors such as the number of operations does not slow down individual remote invocations. Here is a list of some important performance characteristics.

Scalability across connected client applications. Scalability across objects within a CORBA server. Raw throughout between one client and one server. Activation time of server processes. Activation time of CORBA objects. Streaming time for different IDL types. Connection time associated with the first remote Minimum memory consumed by a CORBA object. Number of file descriptors consumed by a complex

operation, _narrow call, _is_a call etc.


network of distributed objects. WHAT IS INTEROPERABILITY? Interoperability describes whether or not two components of a system that were developed with different tools or different vendor products can work together. CORBA addresses interoperability at various levels. HOW DOES CORBA SUPPORT INTEROPERABILITY? CORBA's goal is to address interoperability at various levels. There is a history to this.

171

In the early versions of CORBA, interoperability between platforms and programming languages was addressed. This included the standardization of IDL and the mapping of IDL to a programming language. While a client and server developed with the same vendor's ORB could talk to one another, a client and server developed with different vendors' ORBs were not likely to interoperate. CORBA 2.0 introduced interoperability between different ORB vendors. This resulted from the introduction of a standard wire protocol called General Inter-ORB Protocol (GIOP), and the incarnation for GIOP for the internet, known as Internet Inter-ORB Protocol (IIOP). So CORBA 2.0 compliant ORBs will interoperate. This means a client using ORB vendor A can talk to a server using ORB vendor B. Interoperability is actually a broader issue than just have ORB vendor A talking to ORB vendor B. Fuller interoperability means that various services interoperate. For example, while a CORBA object can talk to a DCOM object via a protocol bridge, can the CORBA Transaction Service talk to the Microsoft Transaction Service to have a seamless transaction between systems? This broader interoperability at the service level is being addressed now. SHOULD I USE UNDERSCORES ("_") IN THE NAMES OF INTERFACES AND/OR METHODS? In other words, when representing the concept of a "foreign exchange rate" in IDL, should the IDL interface be called ForeignExchangeRate or Foreign_Exchange_Rate? Similarly should a method to "execute the trade" be called executeTheTrade() or execute_the_trade()? There are many stylistic issues that boil down to "I think it looks better this way or that way." But from a development/maintenance cost perspective, these have little if any value. However there are some nits that can bite you if you choose one over the other. If you expect to interoperate with Smalltalk, the underscore can create an ambiguity, particularly if you mix the two styles. For example, the IDL names execute_the_trade() and executeTheTrade() both are mapped into the Smalltalk name executeTheTrade(), which could create an ambiguity if the styles are mixed. In this case, it is best to avoid the underscores. Similarly if you expect to interoperate with the C language, the IDL :: token is mapped to an _ in C, which can create ambiguities. In this case it is best to avoid the underscores. It's a small point, to be sure, but it can catch up to you in the long run. 16 . Corba Interview Questions WHAT IS THE BASIC CORBA ARCHITECTURE? The CORBA architecture is designed to support the distribution of objects implemented in a variety of programming languages. This is achieved by defining an interface definition language that can be mapped to a number of existing languages. IDL is used to define the services offered by a particular distributed object. CORBA defines a wire protocol for making requests to an object and for the object to respond to the application making the request. The IIOP protocol ensures interoperability between client applications and server based objects. CORBA then extends on this basic set of functionality by defining a set of low level services. These services are required by

172

applications regardless of the exact nature of the applications. These services are defined in CORBA IDL. CORBA vendors preprocess the service IDL and then implement the service with varying degrees of robustness. HOW ARE CORBA OBJECTS DEFINED? CORBA objects are defined as Interfaces in IDL. WHAT CAPABILITIES DO CORBA OBJECTS POSSESS? CORBA objects support operations that take and return simple and complex IDL types. WHAT ARE CORBA PSEUDO OBJECTS? CORBA Pseudo Objects are not real CORBA objects. A CORBA Object has an Object Reference, and can be accessed remotely. Pseudo objects do not have Object References and cannot be accessed remotely. WHY ARE PSEUDO OBJECTS NEEDED? Keep in mind the CORBA is primarily a specification for accessing remote objects. There is support for location transparency and the case where CORBA objects can be accessed locally, but there is a bias in the specification for remote objects. There is a need, however, to describe local objects, such as the ORB itself in the local process. In keeping with CORBA, the description of this local object is done in IDL, so that the description is programming language independent. To distinguish the use of IDL to describe a potentially remote object (the normal use of IDL), and the use of IDL to describe an exclusively local object, the concept of a Pseudo Object was introduced. Pseudo objects use Pseudo IDL (also called PIDL) to describe their interfaces. PIDL is indentical to IDL, except the intention is that the object of a PIDL interface is not associated with an Object Reference for the purposes of remote access. WHAT IS THE PURPOSE OF IDL? IDL stands for Interface Definition Language. Its purpose is to define the capabilities of a distributed service along with a common set of data types for interacting with those distributed services. IDL meets a number of objectives:

Language Independence: Distributed service specification: Definition of complex data types: Hardware Independence

173

17 . Corba Interview Questions DO I PROGRAM IN IDL? No, it is an interface language. Applications are not programmed in IDL. IDL is used to define two basic types of entities: Complex Data types shared between clients and servers: IDL supports 8 basic data types and allows complex data types to be composed of the basic types. Capabilities of Distributed Objects (CORBA Interfaces): IS IDL A SPECIFICATION LANGUAGE, AN IMPLEMENTATION LANGUAGE, OR BOTH? A specification language. IDL makes a strong separation between the specification of an object and the implementation of that object. Programmers who use the interface of an object have no idea whatsoever how that object is implemented. For example, the object doesn't even need to be implemented using an OO programming language. This is called "Separation of Interface from Implementation," and is a very important concept in OO in general and in CORBA in particular. DOES MY IMPLEMENTATION NEED TO USE INHERITANCE JUST BECAUSE MY IDL INTRERFACE USES INHERITANCE? Nope. Even though a CORBA interface might utilize inheritance, the object implementation is not required to utilize inheritance. For example, given the following two IDL interfaces: interface Base { void f(); }; interface Derived : Base { void g(); }; Suppose interface Base is implemented by class Base_impl and interface Derived is implemented by class Derived_impl. The key insight of this FAQ is that class Derived_impl does not need to inherit from class Base_impl. For example, Derived_impl could implement method f() directly, or it could contain a pointer to a Base_impl object and delegate f() to that object, or it could use some other technique. This is an example of the separation of interface from implementation. HOW DO I EXPRESS AGGREGATION IN IDL? The aggregation of two objects is a very common OO design concept. Aggregation is also known as has-a and contains. Since IDL doesn't support "public data," a programmer that is using an IDL interface cannot tell whether an aggregation is actually implemented using aggregation or by some other technique. In other words, IDL is a specification language that separates interface from implementation. In particular, IDL does not support implementation constructs such as aggregation. However logical aggregation is supported by IDL: IDL lets you specify an operation that returns another interface,
174

and this second interface could represent an object that is logically contained within the first object. Whether it's actually implemented using aggregation or not is an implementation issue, not a specification issue, and the implementer can do it either way without requiring any changes to the IDL interface. Note that DCOM directly supports aggregation since DCOM combines implementation issues with specification issues. The COM<->CORBA interworking specification actually maps aggregation to and from inheritance (CORBA IDL supports inheritance directly, and DCOM supports aggregation directly).

> 18 . Corba Interview Questions HOW ARE OBJECT REFERENCES OBTAINED BY APPLICATIONS? Object references allow applications to issue distributed requests. How does an application acquire an object reference? CORBA provides a number of ways for this to occur. They basically fall into two categories, mechanisms to obtain initial object references and mechanisms to obtain subsequent object references. CORBA provides two standard ways to obtain an initial object reference: ORB::resolve_initial_references(string): CORBA defines a vendor specific mechanism for obtaining an initial set of object references. While CORBA defines the interface for the mechanism, internals required to drive the functionality are not standardized. CORBA specifies that an application can obtain an object reference by calling resolve_initial_references(), but vendor specific configurations files, command line arguments, of environmental variable might be required for the call to succeed. Object references obtained in this way can most likely be implemented only within the same vendors ORB. ORB::string_to_object(string): CORBA provides a vendor independent mechanism for obtaining an object reference. The string_to_object() operation returns an object reference directly from a particular string. The object reference is actually an interoperable object reference and thus can be implemented within an ORB supporting IIOP. Strings are basically encoded identifiers and are not human readable. The string can be hard coded into an application, stored and retrieved from a file, or obtained through some other IPC mechanism. Strings are initially created by calling object_to_string() on an actual object reference. Once an application obtains an object reference, it can obtain subsequent objects by calling any remote operations on the original object reference that happen to return a CORBA object. CORBA refers to an object capable of returning an object reference as a factory. CORBA defines two services that are basically mechanisms by which subsequent object references can be obtained. These are listed below: CORBA NameService CORBA TraderService WHAT IS A LANGUAGE MAPPING? CORBA IDL is used to describe application and system interfaces in a manner that is independent of

175

programming language and computer platform. A language mapping is a standard to convert the IDL to a particular programming language, like C, C++ or Java. 19 . Corba Interview Questions WHAT ARE THE CURRENT LANGUAGE MAPPINGS FOR CORBA? The OMG has standardized the following language mappings for IDL: C C++ Smalltalk Java Ada Cobol COM-based language bridge, e.g., Visual Basic There is also a standardized reverse mapping from Java to IDL. There are other language mappings that are available from various vendors: Tcl PL/1 LISP Python. Perl WHAT IS THE STATIC INVOCATION INTERFACE? The CORBA specification defines two mechanisms for invoking operations on a CORBA Object. Functionaly, the two mechanisms provide the same capabilities. They allow basically the IDL defined operations on the CORBA object to be invoked, allow program variables to be passed to the operation as inbound parameters, and allow return values or out parameters to be passed from the server to the client. The first mechanism is known as the Static Invocation Interface (SII), the other is known as Dynamic Invocation Interface . Developers of client applications which use SII must know the name of the operation, and all parameters/return types prior to program compilation. The actual operation names and parameters/return values are in effect hard coded into the application source code. WHICH IS THE BEST MECHANISM TO INVOKE OPERATIONS ON AN OBJECT? Generally speaking, SII is the easiest mechanism which can be used to invoke operations on a CORBA object. All applications which use SII could be implemented with DII. Not all applications which use DII can be implemented with SII. If an application can be developed with SII then it probably should be. This is because

176

developing code with SII requires less code and is much more straight forward. The language compiler can be used to validate types and optimize code. There are certain conditions which make DII a better alternative. 20 . Corba Interview Questions HOW DOES A ORB SUPPORT STATIC INVOCATION INTERFACE? Implementations of the CORBA specification (i.e. a CORBA ORB) support SII in the following way. The ORB will provide an IDL compiler which is specific to that particular ORB product. When a developer compiles their IDL with the ORB vendor's IDL compiler, stubs and skeletons are created. These stubs and skeletons are static. This is because they do not change. If changes are made to the IDL, the stubs and skeletons must be regenerated by running the IDL compiler again. The IDL compiler generates a stub and skeleton based on the structure of the appropriate IDL interfaces. The stubs and skeletons are statically generated at IDL compilation time. These stubs are then either imported or included into the application which needs access to the CORBA Objects. The stubs and skeletons will have been generated to either directly or indirectly utilize IIOP to communicate. In many cases, the IDL compiler, will generate stubs to utilize Dynamic Invocation Interface to interact with the skeletons. The IDL compiler may also generate skeletons which utilize Dynamic Skeleton Interface to interact with the stubs. WHAT IS THE STATIC INVOCATION INTERFACE? The CORBA specification defines two mechanisms for invoking operations on a CORBA Object. Functionaly, the two mechanisms provide the same capabilities. They allow the IDL defined operations on any CORBA object to be invoked, they allow program variables to be passed to the operation as inbound and in/out parameters, and allow return values or out and in/out parameters to be passed from the server to the client. The first mechanism is known as the Static Invocation Interface (SII, the other is known as Dynamic Invocation Interface (DII). Developers of client applications which use DII do not need to know the name of the operation or any of the parameter or return types when writing the program. The developer will utilize the DII mechanism which is part of the CORBA specification to make invocations of operations. DII also provides a facility to set up the parameters and return values of the particular invocation. DII is similiar to Java's introspection features and RTTI in C++. UNDER WHAT CONDITIONS IS DII APPROPRIATE? The dynamic nature of DII provides certain advantages over SII. The following types of applications would require or benefit from DII: Browsers for CORBA services (Naming, IR) Application browsers Bridges (protocol converters) Applications accessing huge numbers of different interfaces Monitoring applications

177

Applications which utilize DII do not need to include or import stubs generated by an IDL compiler in order to access a service. Applications like object browsers or monitors can access ANY objects without previous (complile time) knowledge of the interface. Using DII is more tedious than coding w/ SII. The DII interfaces must be used to specify the operation and each parameter's type and value. Type checking must be done by the developer using CORBA defined typecodes. WHAT IS THE DEFERRED SYNCHRONOUS INVOCATION? DII also provides a deferred synchronous invocation. This feature is not part of CORBA 2.0's SII. Deferred synchronous invocations are submitted without having to wait for a response. This is similiar to a one-way operation except a return values and out parameters are possible, but must be polled for. CORBA 3.0 will support this type of invocation for both static and dynamic modes via the Asynchronous Messaging Service. WHAT IS THE DYNAMIC SKELETON INTERFACE? The CORBA specification defines two mechanisms for implementations of a CORBA Object to service its operation invocations. One is the static mechanism and the other is dynamic. The static mechanism requires that the implementation support the specific methods as required by statically known IDL interfaces. Implementations can do this through either a delegated or derived approach (i.e. inheritance or delegation/TIE). If the dynamic approach is taken, the implementation of the Object deals with the request generically and in a sense, has one "do-it" method for dealing with all requests. The implementatin must inforce type safety as apposed to relying on an IDL compiler or Language compiler to do it. DSI is much more complicated for a developer then relying on the IDL compiler to generate static request dispatching code.

J2EE - CORBA II 1 . Corba Interview Questions UNDER WHAT CONDITIONS IS DSI APPROPRIATE? The dynamic nature of DSI provides certain advantages over static request dispatching. The following types of applications would require or benefit from DSI: Server side bridges (protocol converters) Monitoring applications Interpreted or script driven services Applications which utilize DSI do not need to include or import skeletons generated by an IDL compiler

178

in order to provide a service. These serices can support request generically and must enforce type safety. WHAT IS AN ANY? An any is an IDL type that can represent "any" other IDL type. An any is the most abstract type. It requires runtime information to determine what type (and value) it really is. HOW DOES AN ANY REPRESENT ITS RUNTIME TYPE? This is where typecodes come in. See the section on typecodes. WHEN WOULD I USE AN ANY? An any comes in handy whenever you need to write IDL and do not know which CORBA type is appropriate. This ambiguity rarely occurs in application IDL. Usually you know what you are dealing with and you use that type explicitly. Or, if you have an operation that may handle one of a couple of types (e.g., a float or a short), then a union is a possible type. Note, if you have an operation that is needs an abstract interface representation, then interface inheritance can be used. The ultimate base interface is CORBA::Object. There are some cases, though, where an any is needed in application IDL. There are also some places where an any is used in system and service IDL. This is because the operation has to be generic enough to work with a broad range of types. For example, imagine the need to represent a generic property, which is a name-value pair. We have three choices: Force all values to be strings, and then use a single struct. This approach has the advantage of being simple IDL. However, this potentially falls apart if it is difficult to represent the value as a string. Even if the representation is not a problem, the representation conversion is a hassle: struct Property { string name; string value; }; interface Foo { Property getElement(in string key); }; Write a lot of different structs, one for each type of value. This approach has the advantage of explicit typing with no conversion. However, this falls apart if we have to represent a type that we don't know of, e.g., a user-defined struct. Also this would lead to a lot of variants of the same operation, one that handled each kind of struct:
179

struct FloatProperty { string name; float value; }; struct ShortProperty { string name; short value; }; //more and more interface Foo { FloatProperty getFloatElement(in string key); ShortProperty getShortElement(in string key); }; Use an any. This approach has the advantage of simple IDL. Also, it is completely expandable to all types, including user-defined types. Additionally, the application does not have to do conversions (this is essentially done in the marshalling/unmarshalling code). The disadvantage of this approach is the runtime typing - this impacts both the application code and the speed of the ORB communication: struct Property { string name; any value; }; interface Foo { Property getElement(in string key); };

2 . Corba Interview Questions

180

OKAY, SO WHY NOT USE ANYS ALL THE TIME? Sometimes the genericism of an any is appealing. But make sure you need this feature. The disadvantages of using an any include: There is no compile-time type information. This makes the application code harder to write, debug, maintain, etc. Communicating an any is relatively expensive for the ORB. AN ANY SEEMS VERY DYNAMIC, SO WHAT'S A DYNAMIC ANY? A Dynamic Any (DynAny) is not an IDL type, like an any. A DynAny solves a technical glitch in the role of the IDL compiler. A DynAny provides an API to construct an any even when the application code does not have benefit of the IDL (really the IDL generated code) that defines the type of the any. WHAT IS A TYPECODE? A typecode is a type, whose values represent the types of other things. It is a meta-type. For example, a given typecode might have the value of XXX, which represents the type "float". In details of XXX are not particularly important. DO ALL TYPES HAVE A TYPECODE? Yes. WHAT ARE THE TYPECODES FOR THE BUILT-IN IDL TYPES? This depends on the language mapping. For example, in C++, there is a const instance of the TypeCode class for each of the built-in types. WHAT ARE THE TYPECODES FOR THE USER-DEFINED TYPES? Sticking with the above C++ example, there is a const instance of the TypeCode class for each user type. The IDL compiler generates this. HOW DO I GET AN OBJECT'S TYPECODE An interface's typecode can be determined by calling _get_interface() on the object reference (IOR). This will return an InterfaceDef (Interface Definition) reference from the Interface Repository (IFR). The typecode for things like float and string are well known in the language mapping. The typecode for things like structs are generated by the IDL compiler. An any supports a call to determine its typecode. Note, the complete support for this requires Dynamic
181

Anys. 3 . Corba Interview Questions WHAT IS THE INTERFACE REPOSITORY? The CORBA specification defines IDL as a mechanism for describing a set of interfaces and data types. These interface definitions can represented within a textual IDL representation. They can also be managed by, or stored within a repository service. IDL can be compiled into a running interface repository serice. This sercices can then provide information about other objects interfaces. The Interface Repository service is (of course) defined in IDL. WHY DOES CORBA NEED THE INTERFACE REPOSITORY? The CORBA specification support self desribing data types. These are supported by the ANY data type and its associated typecodes. The CORBA specification also provides Dynamic Invocation Interface and Dynamic Skeleton Interface . Since the IIOP specification does not provide self descirbing messages, an objects interface must be accessible via the Interface Repository. This capability is also critical for supporting up and down casting of super and sub interfaces types. WHAT IS THE BOA? NOTE: The BOA has been deprecated by the OMG and replaced by the POA. ORB vendors may support both the BOA and POA or either. The CORBA specification defines the BOA pseudo object in PIDL. BOA stands for Basic Object Adapter. The BOA's main purpose is to allow an object server to interact with the ORB. A server process uses the BOA to tell the ORB when an object is ready to perform operations. WHAT ARE THE FOUR BOA ACTIVATION POLICIES FOR A CORBA SERVER? NOTE: The BOA has been deprecated by the OMG and replaced by the POA. ORB vendors may support both the BOA and POA or either. CORBA defines four activation policies for objects. Activation policies are specific to the server process that "owns" the CORBA object. The activation policy defines how objects are created within a server process. The BOA object ensures that these activation policies are enforced. Enforcement of these rules can simplify application development. Note: The CORBA activation policies are specific to creation. This means that the activation policy does not manage the connection policy of a CORBA object. A particular un-shared server might have only one CORBA object in its address space. The activation policy does not forbid several client applications from

182

having object references that point to the same CORBA object. An application is always free to _duplicate an object reference and pass it to some other application. Shared Server: A shared server is a server process that is shared by many CORBA objects. This means that a shared server could have more than one instance of a particular CORBA object in its address space. This implies that different object references of the same type refer to different CORBA object implemented within the same process. Un-Shared Server: An un-shared server is allowed to construct at most one CORBA object (of a given type) within its address space. This implies that different object references of the same type refer to CORBA objects implemented within different server processes. Persistent Server: A persistent server is a shared server that manages the activation of objects itself. The BOA is not involved with enforcement of the activation policy. A persistent server might start up at boot time and create a fixed number of CORBA objects of varied types. Per-Method Server: The per-method policy results in a separate server for each request made on the specified object. The BOA activates a per-method server for each and every request made on the object. The server runs only until the request has been serviced. 4 . Corba Interview Questions WHAT IS THE POA? The Portable Object Adapter (POA) superceeds the Basic Object Adapter (BOA) as the primary way of making implementation objects available to the ORB for servicing requests. All object adapters are concerned with the mechanisms to create CORBA objects and associate the CORBA objects with programming language objects that can actually do the work. The POA provides an expanded set of mechanisms for doing this. WHY IS THE POA NEEDED? The POA was added to the CORBA specification for a number of reasons: The BOA was under-specified. This meant that each ORB vendor provided different APIs and different extensions to make the BOA useful. The POA fixes this by being more completely specified. The POA, itself, is specified in IDL, and addresses complex issues in more detail than the BOA did. The BOA was insufficient for large-scale systems. The POA provides a lot more functionality than the POA with respect to implementing large-scale systems. Servers can better handle connections and requests from multiple clients through automatic, policy-driven behavior. Servers are better able to manage thousands, if not millions, of fine-grained objects via the POA's ability to manage lifecycles and associations of CORBA objects and implementation objects. The BOA was not completely location transparent. Whereas some semantics of the BOA changed if the implementation object was actually in the same process as the caller (client) vs. being remotely located,

183

the POA makes the semantics much more consistent. In fact, a CORBA call on a local object will still go through the POA. This allows the POA to uniformly apply policy and service decisions. In this sense, the POA is more like the "container" concept in EJB. DOES THE POA AFFECT CLIENTS? No. No object adapter or server-side concept affects clients. CORBA-compliant clients that used BOA-based servers should be able to use POA-based servers. 5 . Corba Interview Questions DOES THE POA AFFECT SERVERS? Yes. Transitioning from a BOA-based server to a POA-based server needs to be done with some forethought. It is not necessarily a difficult task, but should be done carefully. The POA is policy based with lots of policy choices. The task is to determine the set of policy decisions that give you the functionality you want. Since the POA superceeds most of the BOA functionality, if you want to simply migrate a BOAbased server to a POA-based server without changing behavior, then this can be done rather easily. There are some API changes. See POA Policies. Chances are, though, if you are using the POA, you are going to want to take advantage of some of its benefits. HOW DOES THE POA BENEFIT NON-DISTRIBUTED OBJECTS? The POA is very consistent in the treatment of local and remote objects. Specifically, all CORBA calls on a CORBA object go through the POA, even if the target object is local (in the same address space). This allows the POA to uniformly apply the POA Policies. HOW DOES THE POA MANAGE OBJECT LIFECYCLE? The POA distinguishes between the CORBA object reference (IOR) and the implementation object that does the work. This implementation object is called a servant. A BOA-based approach has the IOR and servant existing at the same time. A POA-based approach can support this, but can also support IORs existing without being associated with servants, and also servants existing without being associated with IORs. Obviously, the association between an IOR and a servant has to be made at some point, to make the servant a useable CORBA object. But this association can be done on-demand. Consider the following example scenarios to motivate the advantages of on-demand association: A pool of servants can be instantiated, and then associated in turn with IORs, as needed.

184

A set of IORs can be created for the purposes of publishing the references to the Name Service, without going through the work to actually instantiate the servants. Moreover, the POA allows a single servant to simultaneously support several IORs. All of the above significantly contribute to scalable applications. HOW DOES THE POA MAKE THE ASSOCIATION BETWEEN SERVANTS AND CORBA OBJECTS? This is where the Object ID and and POA Active Object Map come in. So, for a given POA, the Object ID identifies a specific CORBA object, which is used in the Active Object Map to identify the servant. HOW ARE MULTIPLE POAS DISTINGUISHED? Each POA has a name. HOW ARE MULTIPLE POAS ORGANIZED? This is up to the application developer, but a POA hierarchy is supported. Each POA has a parent POA. There is an implicit Root POA.

> 6 . Corba Interview Questions WHAT ARE THE SEMANTICS OF THE POA HIERARCHY? This is better answered by describing what the semantics of the POA hierarchy are not. The POAs deal with policies, and the POA hierarchy is not a policy hierarchy. The POA hierarchy does not imply any default policies. The POA hierarchy does not imply any factoring of the servants by IDL interface or servant class. In most cases, each servant is associated with at most one POA. The POA "owns" the servant and there are deletion responsibilities the POA will take. Deleting a POA will cause its servants to be deleted. Hence, the semantics of the POA hierarchy are only a containment hierarchy for POA deletion. WHERE DOES THE POA MANAGER FIT IN? The POA Manager is really a different beast all together. The POA Manager groups one or more POAs and provides common system resources, such as a network connection, to its POAs.

185

WHAT ARE THE POA POLICES? The POA policies are used to configure the POA for a particular application design or scalability optimization. For example, if you have lots of a fine-grain objects, you may want one kind of optimization, whereas if you have lots of long-duration operations, you may want another kind of optimization. The list of POA policies includes: Thread Policy ORB_CTRL_MODEL - the ORB controls how threads are dispatched. SINGLE_THREAD_MODEL - the is only one thread. Lifespan Policy TRANSIENT - the POA's object references are transient (i.e., likely conversational objects). PERSISTENT - the POA's object references are persistent, which means the POA should be registered with an locator/activator (i.e., likely entity objects). ID Uniqueness Policy UNIQUE_ID - the POA does not allow a servant to be associated with more than one CORBA Object (Object ID). MULTIPLE_ID - the POA will allow a servant to be associated with more than one CORBA Object (Object ID). NOTE: The name of this policy is potentially confusing. The Object IDs are always unique for a given POA. This policy is describing the uniqueness or non-uniqueness of the association between Object IDs and servants. ID Assignment Policy USER_ID - the application code can/will determine Object IDs for the POA's CORBA Objects. SYSTEM_ID - the POA will determine Object IDs for its CORBA Objects. Implicit Activation Policy IMPLICIT_ACTIVATION - Allows the POA to add the servant to the AOM under conditions where the association is implicit, e.g., calling servant_to_reference(). NO_IMPLICIT_ACTIVATION - Servants can only be associated with an Object ID through an explicit call to do so. Servant Retention Policy RETAIN - The POA uses an Active Object Map (AOM). NON_RETAIN - The POA does not use an Active Object Map (AOM). NOTE: The name of this policy is potentially confusing. The policy influences whether the POA has an Active Object Map (AOM) or not to track which servants are associated with Object IDs. The application is always in control of making and breaking this association. The NON_RETAIN policy means that no AOM is used, and hence the application has supplied a Servant Manager. Request Processing Policy USE_ACTIVE_OBJECT_MAP_ONLY - The POA relies on its Active Object Map (AOM) only to determine which Object IDs are valid and associated with servants.
186

USE_DEFAULT_SERVANT - The POA will use a default servant for requests to Object IDs that are not in the AOM. USE_SERVANT_MANAGER - The POA will use a servant manager to activate an Object ID/servant that is not in the AOM. Note, there are some cases where the policies are inter-related in most practical situations. For example, a PERSISTENT Lifespan Policy probably implies a USER_ID ID Assignment Policy. Also, the use of the USE_ACTIVE_OBJECT_MAP_ONLY requires the use of RETAIN, and the use of IMPLICIT_ACTIVATION requires the use of SYSTEM_ID and RETAIN. Since the POA and its policies are defined in IDL, this list may be extended, or features within a particular policy may be expanded. 7 . Corba Interview Questions WHAT IS A SERVANT MANAGER? The Servant Manager is application code that essentially replaces the functionality of the POA's Active Object Map (AOM). A servant manager is needed for sophisticated schemes to map Object IDs to servants. HOW DOES A REQUEST GET TO THE RIGHT POA AND RIGHT SERVANT? The POA's name is part of the IOR. Also, of course, the Object ID is in the IOR. So once the request gets delivered to the right machine (part of the request's IOR), and to the right port (part of the request's IOR), the POA Manager listening on that port looks at the object key (part of the request's IOR). The object key contains the POA name and the Object ID. The POA Manager uses the object key to deliver the request to the right POA, and the POA uses the object key to determine the Object ID. Depending on the POA's policies, it directly or indirectly uses that Object ID to deliver the request to the right servant. HOW DOES THE POA SUPPORT OBJECT RELOCATION? Very well, indeed. The POA is the unit of location and activation. This means the POA is the unit of relocation. This is powerful. Since a POA can one object, a few objects, or a lot of objects, by design, then objects can be relocated individually are in groups. A great way to think of the POA is as a named, logical endpoint. HOW DO I MIGRATE FROM BOA TO POA? There is no specific answer. The migration impacts will depend on the system complexity. In particular, many large systems developed with the BOA needed to do POA-like things any way to scale.

187

There will be some emerging case studies. It is likely that POA migration is one of those things that is not overly difficult, but should not be done without a thought. An important thing to understand is that the migration can be an evolutionary thing as the use of the POA does not affect clients, and mixed POA and BOA systems interoperate at the network (IIOP) level. WHAT IS IMPORTANT FOR INTEROPERABILITY BESIDES IIOP? The IIOP specification provides resolve initial references as a mechanism to obtain an initial object reference. This object referenced must be implemented with the same ORB product as the client. If this is not the case, then string to object can be used. CORBA 2.0 does not provide a mechanism to transport this string or provide direct access to "foreign objects" The Interoperable Name Service specification will address this and other related problems. 8 . Corba Interview Questions WHAT IS AN IOR? An IOR is an Interoperable Object Reference. It is a specialized object reference. An IOR is used by an application in the exact same way that an object reference is used. An IOR allows an application to make remote method calls on a CORBA object. Once an application obtains an IOR, it can access the remote CORBA object via IIOP. The CORBA object can be implemented with any CORBA 2.0 compliant product that supports IIOP. The application that obtains the IOR can be developed with a different CORBA 2.0 product. The application constructs a GIOP message and sends it. The IOR contains all the information needed to route the message directly to the appropriate server. ARE IORS OBTAINED IN THE SAME MANNER AS OBJECT REFERENCES? Obtaining IORs is exactly the same as obtaining object references. The one caveat is that ORB::resolve_initial_references returns an IOR but it usually must be implemented within the same CORBA product environment. CAN AN APPLICATION REFER TO OBJECTS IMPLEMENTED WITH MULTIPLE CORBA PRODUCTS? Well, they're sure supposed to be able to do so. Here's how. Let us assume that an application needs to access two objects. Object A is implemented with CORBA product Aa and object B is implemented with CORBA product Bb. Let us look at several scenarios: The front-end application will be implemented with CORBA product Aa: The simplest approach is for the front-end application to obtain an object reference to A by calling ORB::resolve_initial_references().

188

Since the front-end application is implemented with product Aa it cannot obtain an object reference to B by calling ORB::resolve_inital_references(). It can acquire the stringified object reference to B and convert it to an IOR by calling ORB::string_to_object(). How does it obtain the stringified object reference? Object B's constructor could be implement to stringify itself and write the string to a file that is accessible to the front end application (access might be provided by NFS). Every CORBA product that supports IIOP should be support ORB::string_to_object(). The front-end application will be implemented with CORBA product Cc: This scenario is very similar to the first. The application can not use ORB::resolve_initial_references() since neither object A or B are implemented with product Cc. The front end application will obtain an IOR to A and an IOR to B by first acquiring stringified object references. It will then converting the strings to IORs by calling to ORB::string_to_object(). Every CORBA product that supports IIOP should be support ORB::string_to_object(). The front-end application will be implemented with CORBA product Cc. It will obtain IORs A and B from product Cc's implementation of the CORBA NameService. It will not need to acquire any stringified object references. The real question is how are IOR A and IOR B bound within product Cc's CORBA NameService. The processes implementing object A and Object B must acquire an object reference to product Cc's CORBA NameService. This can only occur by obtaining a stringified object reference to product Cc's CORBA NameService. How is the stringified object reference to product Cc's NameService initially created? A simple application implemented with product Cc obtains the NameService by calling ORB::resolve_inital_references(), it then stringifies it by calling ORB::object_to_string(), once this has been done it externalizes the string so that it can be accessed by the processes implementing object A and B. Note: Stringified objects cannot be exchanged using CORBA based communication. This is your classic catch 22 situation 9 . Corba Interview Questions CAN CORBA VENDORS SIMPLIFY INTEROPERABILITY AND THE PROCESS OF OBTAINING OTHER VENDOR'S OBJECT REFERENCES? CORBA vendors can simplify the process of obtaining external object references by providing small pieces of code designed only to create external IORs. This might be a function called ExternalORB::create_external_references(). Vendors could provide this code to the public or directly to other ORB vendors. 10 . Corba Interview Questions WHAT IS THE INITIALIZATION SERVICE?

189

The Initialization Service is used to find well-known system and user-defined services. The Initialization Service is best understood in the catch-22 presented by the Name Service: If the Name Service holds the system's application object references (IOR)... ...and the Name Service, itself, is composed of NamingContext objects (IORs) for storing and retreiving application IORs... ...and a client cannot access an object until it has its IOR... ...then, how does a client get a reference to a root NamingContext? The answer to the above question is that the reference has to be supplied to the client administratively. The Initialization Service provides a simple interface into this administrative information. The method is named "resolve_initial_reference()" and takes a string representing the name of the service, and returns a CORBA::Object accessing that service. WHAT ARE THE IDL INTERFACES DEFINED WITHIN THE COSNAMING MODULE? The CORBA Name Service is composed of two basic interfaces. The NameContext and the Binding Iterator. Remember that since the NameContext and the Binding Iterator are both CORBA interfaces, they are accessed via object references and are distributed. The NameContext contains "named" object references or other "named" NameContexts. It is similar to a directory that can contain named files or other named directories. NameContexts and Binding Iterators are usually implemented in the same Name Server process, but this is not a requirement. The CORBA NameService can be constructed as a set of interconnected NameContext objects and NameService processes. The BindingIterator is used to iterate across object references contained within a particular NameContext. It basically provides a mechanism to get the number of named object references within a NameContext. It also provides a next_one and a next_n operation to retrieve individual named object references or contexts. Continuing with the directory analogy, The BindingIterator is a mechanism to do a ls or dir operation on a directory. HOW DO I USE A NAMECONTEXT? The NameContext interfaces supports two main operations, bind and resolve. Once a NameContext object reference is obtained, it can be used to "name" some other CORBA object, or retrieve an object reference by name. This means that you can call the bind method on a NameContext passing it an object reference and a name. This will place a named object reference into the NameContext for future resolve calls. If an application wishes to obtain an object reference by name is simply obtains the appropriate NameContext and call resolve with the particular name. This will cause the named object reference to be returned to the application making the resolve invocation.

>

190

11 . Corba Interview Questions WHAT IF I DO NOT KNOW THE NAME OF THE OBJECT? The CORBA NameService was designed to allow object references to be obtained by name. Names need to be either agreed upon between servers or clients, or perhaps passed between components in the distributed application. It is also possible to use the BindingIterator interface to connect to any name object reference. The CORBA trading service might be more appropriate if the CORBA NameService is too limiting. Other architectures such as factories might be appropriate mechanisms to obtain object references. WHAT IS THE INTEROPERABLE NAME SERVICE (INS)? The Interoperable Name Service (INS) fixes a technical glitch in the original CORBA Name Service. The original Name Service did not truly allow object references from different ORB vendors to be stored and accessed from within a single Name Server. This is fixed by the INS. There are no API or IDL changes, so application developers should not notice a difference. WHAT IS THE EVENT SERVICE? The CORBA event service provides support for the producer/consumer pattern. It support a channel which provides the producer with the ability to create "events" and the consumers with the ability to receive these "events". Events are any valid IDL defined interface or data type. Both consumer and producer applications must be a CORBA server. There may be multiple channels in use. A single channel may have multiple producers and multiple consumers. A consumer receives all the events on the channel. ARE THERE MORE THAN ONE TYPE OF EVENT SERVICE? The Event Service specification supports two types of event reception. One is push and one is pull. The push model allows consumers to receive ongoing events by just connecting. The pull model requires that the consumer poll for all events sent to the channel since the last pull. The Event service also allow the events to be either typed or in typed. In the typed model, the Event service ensures that the channel support a specific IDL datatypes. In the untyped model the Chnnel distributes events as an ANY. In this case, it is up to the consumer to enforce type safety. 12 . Corba Interview Questions WHAT IS THE QUALITY OF SERVICE PROVIDED BY THE EVENT SERVICE? The Event Service specification does not require a specific quality of service. It is up to the
191

implementor of the event service to determine what the provided level is. For example, an event service implentation may ensure that events are deliver even if some piece to the event service fails. An event service could also support transactional events using OTS. An event service could also provide deliver via a non IIOP transport such as UDP broadcast or multicast. This could, of course, limit interoperability. An event service could also ensure that connections to a channel are persistent. This would mean that consumers would not have to re-connect if the server failed and then came back online. WHAT IS NOTIFICATION SERVICE? The Notification Service extends the Event Service and adds several new kinds of functionality. CORBA has defined the Notification Service model that allows applications to send messages to objects in other applications without any knowledge of that receiving objects. The Notification model is an extension to the CORBA Event Service model. Applications that are providing messages to other applications are called suppliers and applications receiving the messages supplied are called consumers. The suppliers and consumers are completely decoupled thus having no knowledge of their location. In addition, suppliers have no idea of how many consumers are listening to the messages being supplied. HOW DOES THE NOTIFICATION SERVICE WORK? The Notification model uses an architectural element called an event channel which allows messages to be transfered between suppliers and consumers. Consumers register with the event channel and express an interest of certain events. The channel receives events from suppliers and forwards the events to the interested consumers for that event. Suppliers and Consumers connect to the event channel and not directly to each other. HOW DOES THE NOTIFICATION SERVICE EXTEND THE EVENT SERVICE? The Notification Service extends the Event Service in two areas: Event Filtering - Event filtering allows that Notification channel to deliver only certain types of events to interested consumers. In the much simpler Event Service model all events are sent to all consumers. Quality of Service - Quality of Service (QoS) allows an applications to change some of the elements defined in the Notification Channel, such as event delivery. 13 . Corba Interview Questions WHAT DOES THE QUALITY OF SERVICE GIVE ME? The Quality of Service, or QoS, allows you to set and tune your service to the demands of your

192

business. Notification defines the following QoS properties:


Reliability Priority Expiery Time Earliest delivery time Order policy Discard policy Maximum batch size Pacing interal Proxy push supplier properties These properties can be applied at cartain levels of the Notification service: Notification Channel Supplier or Consumer admin objects Proxy suppliers and consumers Individual event messages

The QoS is a very powerful extension that allows you to modify the service according to your requirements both from an administrative and an application requirement perspective. WHEN DO I NEED A SERVICE LIKE NOTIFICATION? It depends on what your business requirements dictate. We can see a need for Notification in a scenario where you are interested in receiving certain information which another source owns. The example that always comes to mind is the stock market. Information about stocks flows rapidly, and frequently. This information can be supplied through a Notification channel to which many consumers can register their interest in certain stocks. As new information about the stocks is collected, a supplier can push that information to the Notification channel which will pass this information to all the interested consumers on that channel. There are many more examples but the bottom line here is that it can be used in a variety of scenarios and they will have to be analyzed to see where Notification fits in. HOW DO I DEFINE NOTIFICATION EVENTS? Notification events are defined using standard IDL. There are two types of events: Structured Events Untyped Events Structured events provide a well-defined data structure into which messages can be inserted and sent to
193

interested consumers. Messages can be defined using standard IDL structs and provide, both consumers and suppliers, with a much strongly typed event. In addition, a sequence of these events can be transmitted between suppliers and consumers that can increase the efficiency of communications between them. With the sequence you can batch any number of events and trasmit them all at once. Structured Events can constain all IDL types that are defined in the standard IDL. Here's an example:

struct Message { long messageType; string messageBody; }; typedef sequence<Message> MessageSeq; Suppliers would fill the contents of this messages and supply them to interested consumers that have registered with the notification channel. The untyped event is simply a CORBA::any into which the event is inserted and sent to consumers. So the above example can be inserted into the CORBA::Any type and sent to any consumers on the channel. 14 . Corba Interview Questions CAN I FEDERATE NOTIFICATION CHANNELS? Yes. You will have to do this within your program but the concept becomes clear once you have done it. The way you do the federation is to create two channels and essentially connect them together logically. The consumer proxy of one channel, channel A, is supplied to the supplier proxy of the other channel, channel B. The reverse is done with the supplier proxy of channel B where it's exchanged with channel A and voila we are now federated. So essentially what you have is a channel that becomes a consumer and which will forward the events to its consumers. WHAT IS THE PURPOSE OF THE LIFECYCLE SERVICE? The basic purpose of the Lifecycle Service is to provide basic capabilities to CORBA Objects, such as the ability to create, copy, move and destroy themselves. More than any other service, the Lifecycle

194

Service is tied to the actual ORB implementation used to provide CORBA support. WHAT IS THE PURPOSE OF THE OBJECT TRANSACTION SERVICE? The OTS provides a mechanism for distributed CORBA Objects to participate in a distributed transaction through a two phase commit protocol. WHAT IS THE PURPOSE OF THE COS TRADER SERVICE? The Trader Service was designed to provide access to CORBA objects based upon capabilities as opposed to name or interface type. The Trader Service is a factory since its purpose is to return other CORBA Objects. Unlike the Naming Service, a global name or identifier is NOT used to specify the CORBA Object to return. The Trader Service has been likened to the Yellow Pages, while the Naming Service is more like the White Pages. WHAT IS THE PURPOSE OF THE PERSISTENT OBJECT SERVICE? The Persistent Object Service was designed to provide two things: A database like access to CORBA objects. This provided CORBA clients with IDL control interfaces to a CORBA object's underlying storage. A means for CORBA objects to uniformly save their state into a database. This was an internal API for implementation objects (the objects that really have the state) to save their data into a database. The Persistent Object Service was not widely received and potentially never implemented by any vendor. As a specification, it has been retracted. The Persistant State Service (PSS) superceedes the POS.

> 15 . Corba Interview Questions WHAT IS THE PURPOSE OF THE PERSISTENT STATE SERVICE? The Persistent State Service (PSS) is designed to be a CORBA-friendly form of persistence management. The PSS superceeds the POS. Unlike the POS that attempted to provide both a client IDL interface for persistence control and a serverside layer for allowing CORBA implementation objects to save their state, the PSS focuses on only the latter. At a high-level the PSS is an IDL defined abstraction layer of data storage. It needs to be implemented for a particular datastore, such as a file system, a relational database, or an OODB. This allows CORBA implementation objects to be abstracted from their storage mechanisms, much like ODBC/JDBC abstract

195

relational databases. WHAT ARE OBJECTS BY VALUE? The Objects By Value (OBV) defintion includes semantics of pass-by-value similar to that of standard programming languages. The current CORBA specification only defines object reference semantics. The Objects By Value specification defines extensions to CORBA (and IDL) that allows designers the flexibility to allow the receiving side of a parameter to receive a new instance of the object. HOW CAN I USE OBV? The valuetype definition supports both data members and operations, similar to C++ and Java class definitions. The receiving side creates its own copy of the object and all operations invoked on valuetypes are always local to the receiving process. So, how can you use OBV? In our opinion, very carefully :-). This extension offers some flexibilities and a lot of rope to hang oneself. In particular, there are several very complex edge effects of the OBV specification, such as when interface references and valuetypes are intermixed. By focusing on a few, simple valuetypes that provide operations that are basic functionality (such as edit rules, data validations, conversions and queries (e.g., what day is 1/1/2000), and other utility operations), the use of valuetypes will be clearer to those that use them. WHAT DOES OBV REALLY PROVIDE? From the OBV specification: Valuetypes provide semantics that bridge between CORBA structs and CORBA interfaces: They support description of complex state (i.e arbitrary graphs). Their instances are always local to the context in which they are used (because they are always copied when passed in a remote call). They support both public and private (to the implementation) data members. They can be used to specify the state of an object implementation, i.e they can support an interface. They support single inheritance (of valuetypes) and can support multiple interfaces. They may be also be abstract.

16 . Corba Interview Questions

196

WHAT IS A VALUE TYPE? A Value Type is an object whose semantics lie between a CORBA interface and a structure. There are two types a Value Types that can be declare: Concrete Value Types Abstract Value Types Concrete Value Types define state (properties) and the implementation is always local. Abstract Value Types do not define properties. Both Concrete and Abstract Value Types can define operations (interface) and inherit from other Value Types and interfaces. IN WHAT CASES DO I NEED A VALUE TYPE? In some cases it is desirable to have a receiving party instantiate a copy of an object. This implies that the receiver knows how to implement the object (instantiate it, initialize it, provide implementations of the operations). More importantly, this also implies the receiver knows something about the semantics of the object and can utilize those semantics locally. The new instance created by the receiving side has a separate identity from the original object, and once the parameter passing operation is complete, there is no relationship between the two instances. HOW DOES A VALUE TYPE DIFFER FROM AN INTERFACE TYPE? An Value Type differs from an interface in that it potentially carries additional properties that define state and that the operation implementation are executed locally. If you recall, when we pass or receive an interface type ( an object reference ) and execute operations on it, these operations end up as remote invocations to the "real" implementation object. Again, Value Types are not meant to replace interface types, and should be used in very specific instances in which the receiving side can benefit from not making remote invocations. WHAT IS AN ABSTRACT VALUE TYPE? An Abstract Value Type is a Value Type that may not be instantiated. Only Concrete Types can be instantiated and implemented. Also, no state information may be specified in an Abstract Type. WHAT IS THE PURPOSE OF THE ASYNCHRONOUS MESSAGING INTERFACE? The AMI extends the request/response nature of CORBA into messaging services. The messaging services are richer than the "oneway" or "deferred synchronous" functionalities in the core CORBA specification, and also pull in elements from the Event and Notification Services. The AMI works with the notion of "implied IDL". The means that although the IDL for an interface, Foo, has a single operation, bar, there are other implied operations, e.g., try_bar, that are used to support
197

asynchronous communications. CAN CORBA BE INTEGRATED WITH XML? INDEX:XML@Integration with CORBA INDEX:CORBA@Integration with XML Yes. And in a number of ways, depending on the need and approach. Using IDL to communicate XML. This means setting up simple interfaces to communicate the XML Document Type Description (DTD) and the XML document itself. Obviously, there may be a repository of DTDs, and the actual communication of the XML document simply refer to its DTD. Using XML as a transport. This means there is a DTD for, essentially, IIOP. A CORBA request or response is communicated in XML. A variation on the previous item, once the XML to CORBA request/response conversion is in place, a gateway can take XML or CORBA requests from various sources and map them into XML or CORBA requests on various services. Using XML as an abstract system description language. XML could be used to describe a system interfaces, workflow, API mapping logic, data definitions, other semantics, etc., and then this XML is used to produce IDL. Chances are the XML would also be used to code generate supporting system integration class libraries and potentially entire clients/servers.

198

You might also like