A client sends requests to two different web components. Both of the components access the session. Will they end up using the same session object or different session ?
Creates only one session i.e., they end up with using same session. Sessions is specific to the client but not the web components. And there is a 1-1 mapping between client and a session.
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 JSPengine 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.
What is use of parseQueryString ?
Parses a query string and builds a hashtable of key-value pairs, where the values are arrays of strings. The query string should have the form of a string packaged by the GET or POST method. (For example, it should have its key-value pairs delimited by ampersands (&) and its keys separated from its values by equal signs (=).)
Note:
public static Hashtable parseQueryString(String s)
How can i create connection pooling in tomcat?
We can create connection pooling using tomcatFor that
We need to download 3 jar files
a. commons-dbcp-1.2.jar
b. commons-collections-3.1.jar
c. commons-pool-1.3.jar
We want to add an entry in server.xml of the tomcat factory org.apache.commons.dbcp.BasicDataSourceFactory driverClassName oracle.jdbc.OracleDriver url jdbc:oracle:thin:@localhost:1521:orcl username anand password pass maxActive 20 maxIdle 10 maxWait -1
How can I pass data from a servlet running in one context (webapp) to a servlet running in another context?
There are three ways I can think of off the top of my head:
Suppose I have 2 servers, server1 and server2. How can I take data in a cookie from server1, and send it to server2?
You'll have to create a (new) similar cookie on server 2.
Have a ReadCookieServlet running on server1 that
When building web applications, what are some areas where synchronization problems arrise?
In general, you will run into synchronization issues when you try to access any shared resource. By shared resource, I mean anything which might be used by more than one request.
Typical examples include:
Can Tomcat be configured to interpret all, or selected, .html files within a given context as JSP? Or, do JSP files have to end with a .jsp extension?
Yes you can do that by modifying the web.xml file. You will have to invoke the org.apache.jasper.runtime.JspServlet for all the requests having extension .html. You can do that by changing the Servlet mapping code:
<servlet-mapping>
<servlet-name>
jsp
</servlet-name>
<url>*.html</url>
</servlet-mapping>
And comment out the following block
<mime-mapping>
<extension>
html
</extension>
<mime-type>
text/html
</mime-type>
</mime-mapping>
I want my servlet page to redirect to a login page if the session has timed out. How can I know if my session has timed out?
If the servlet engine does the time-out, following code should help you:
//assume you have a HttpServletRequest request
if(request.getSession(false)==null) {
//no valid session (timeouted=invalid)
//code to redirect to login page
}
How can my application get to know when a HttpSession is removed (when it time-outs)?
Define a class, say SessionTimeoutNotifier, that implements
javax.servlet.http.HttpSessionBindingListener. Create a SessionTimeoutNotifier object and add it to the user session. When the session is removed, SessionTimeoutNotifier.valueUnbound() will be called by the servlet engine. You can implement valueUnbound() to do whatever you want.
What is the difference between URL encoding, URL rewriting, HTML escaping, and entity encoding?
URL Encoding is a process of transforming user input to a CGI form so it is fit for travel across the network -- basically, stripping spaces and punctuation and replacing with escape characters. URL Decoding is the reverse process. To perform these operations, call java.net.URLEncoder.encode() and java.net.URLDecoder.decode() (the latter was (finally!) added to JDK 1.2, aka Java 2).
Example: changing "We're #1!" into "We%27re+%231%21"
URL Rewriting is a technique for saving state information on the user's browser between page hits. It's sort of like cookies, only the information gets stored inside the URL, as an additional parameter. The HttpSession API, which is part of the Servlet API, sometimes uses URL Rewriting when cookies are unavailable.
Example: changing <A HREF="nextpage.html"> into
<A HREF="nextpage.html;$sessionid$=DSJFSDKFSLDFEEKOE"> (or whatever the actual syntax is; I forget offhand)
(Unfortunately, the method in the Servlet API for doing URL rewriting for session management is called encodeURL(). Sigh...)
There's also a feature of the Apache web server called URL Rewriting; it is enabled by the mod_rewrite module. It rewrites URLs on their way in to the server, allowing you to do things like automatically add a trailing slash to a directory name, or to map old file names to new file names. This has nothing to do with servlets. For more information, see the Apache FAQ (http://www.apache.org/docs/misc/FAQ.html#rewrite-more-config) .
How do I ensure that my servlet is thread-safe?
This is actually a very complex issue. A few guidelines:
public class ThreadPool extends java.lang.Object implements ThreadPoolInt
This class is an generic implementation of a thread pool, which takes the following input
a) Size of the pool to be constructed
b) Name of the class which implements Runnable (which has a visible default constructor)
and constructs a thread pool with active threads that are waiting for activation. once the threads have finished processing they come back and wait once again in the pool.
This thread pool engine can be locked i.e. if some internal operation is performed on the pool then it is preferable that the thread engine be locked. Locking ensures that no new threads are issued by the engine. However, the currently executing threads are allowed to continue till they come back to the passivePool
When and Where not to Use java:comp/env
In this post, I wrote about the need to use the prefix java:comp/env when looking up ejb/resource in the current naming environment. Equally important is to know where/when not to use it.
1. Don't use java:comp/env in standard deployment descriptors, such as web.xml, ejb-jar.xml, and application-client.xml. I can't think of any elements in these descriptors that contain java:comp/env.
2. Don't use java:comp/env in appserver-specific deployment plan files.
3. Don't use java:comp/env in any fields of resource and/or ejb injection, whether it's field or method injection.
4.Don't use java:comp/env when looking up resource/ejb using javax.ejb.EJBContext.lookup (String name). This is a new method in javax.ejb.EJBContext in EJB 3. The lookup name in this case is always relative to java:comp/env.
5. Don't use java:comp/env when looking up certain standard J2EE and JavaEE resources. They reside directly under java:comp/, with no /env. For instance:
java:comp/UserTransaction
java:comp/EJBContext
java:comp/ORB
java:comp/TransactionSynchronizationRegistry
6. Don't use java:comp/env when looking up global resources in a server-dependent way. Some application servers let you look up resources by their global JNDI name. In such case, their lookup name should not contain java:comp/env. For example, java:/defaultDS in jboss. In JavaEE SDK 5/Glassfish/Sun Java System Application Server 9, I can also directly look up jdbc/__default (the default datasource) without configuring it in any descriptors. Note that this style of lookup is not portable. It ties your apps to specifc runtime server environment, and should really be avoided.
7. Don't use java:comp/env in the name of any physical resources inside an application server, like jdbc-resource, jdbc-pool, JMS queue or topic, EJB JNDI name, persistence manager, etc.
What are some of the best practices relating to Java collection?
Use ArrayLists, HashMap etc as opposed to Vector, Hashtable etc, where possible to avoid any
List myList = Collections.synchronizedList (myList);
List list = new ArrayList(100); //program in terms of interface & set the initial capacity.
Instead of:
ArrayList list = new ArrayList();
Avoid storing unrelated or different types of objects into same collection: This is analogous to storing items in pigeonholes without any labelling. To store items use value objects or data objects (as oppose to storing every attribute in an ArrayList or HashMap). Provide wrapper classes around your collection API classes like ArrayList, Hashmap etc as shown in better approach column. Also where applicable consider using composite design pattern, where an object may represent a single object or a collection of objects.
StringBuilder vs StringBuffer StringBuilder was introduced in JDK 1.5. What's the difference between StringBuilder and StringBuffer? According to javadoc, StringBuilder is designed as a replacement for StringBuffer in single-threaded usage. Their key differences in simple term:
/**
* readObject is called to restore the state of the
* StringBuffer from a stream.
*/
private void readObject(java.io.ObjectInputStream s)
Note the above javadoc still refers to StringBuffer where it should be StringBuilder.
In Java, you can sort objects that implement the Collection interface, using either the comparable interface or a comparator class. What's the difference?
A Comparable interfaced class must contain a method called compareTo to compare two objects (one being the object on which it is called and the other being passed as a parameter) which returns an integer, negative for a < b, positive for a > b and 0 otherwise. It must also contain an equals method, returning a boolean, on the same parameters.
A Comparator is a class in its own right, which implements the Comparator interface; that means it must contain a method called compare (two objects as parameters) which returns a negative, zero or positive integer depending on whether the first object is less than, equal to, or greater than the second.
If you want to sort a collection using its comparable interface, you simply call the static Collections.sort method on it ... so if we had an ArrayList called Actable, which implemented Comparable, we could write:
Collections.sort(Actable);
To sort a collection using a Comparator class, you need to pass an extra parameter into the Collections.sortmethod - that parameter being an instance of a Comparator object. Thus:Collections.sort(Actable, new Bynum());
So in effect, using the comparable interface gives you a default sort order of your own making, whereas the comparator is more flexible as it allows you define a whole series of different types of sorting that can be applied to a whole lot of different types of objects.
What are the approaches that you will follow for making a program very efficient? - By avoiding too much of static methods avoiding the excessive and unnecessary use of synchronized methods Selection of related classes based on the application (meaning synchronized classes for multiuser and non-synchronized classes for single user) Usage of appropriate design patterns Using cache methodologies for remote invocations Avoiding creation of variables within a loop and lot more.
What is the difference between shallow copy and deep copy?
Shallow copy shares the same reference with the original object like cloning, whereas the deep copy get a duplicate instance of the original object. If the shallow copy has been changed, the original object will be reflected and vice versa
This class (IncrementImpl) will be used by various threads concurrently; can you see the inherent flaw(s)? How would you improve it?
public class IncrementImpl {
private static int counter = 0;
public synchronized void increment() {
counter++;
}
public int getCounter() {
return counter;
}
}
The counter is static variable which is shared by multiple instances of this class. The increment() method is synchronized, but the getCounter() should be synchronized too. Otherwise the Java run-time system will not guarantee the data integrity and the race conditions will occur. The famous producer/consumer example listed at Sun's thread tutorial site will tell more.
one of solutions
public class IncrementImpl {
private static int counter = 0;
public synchronized void increment() {
counter++;
}
public synchronized int getCounter() {
return counter;
}
}
What kind of security tools are available in J2SE 5.0?
There are three tools that can be used to protect application working within the scope of security policies set at remote sites.
keytool -- used to manage keystores and certificates.
jarsigner -- used to generate and verify JAR signatures.
policytool -- used for managing policy files.
There are three tools that help obtain, list and manage Kerberos tickets.
kinit -- used to obtain Kerberos V5 tickets.
tklist -- used to list entries in credential cache and key tab.
ktab -- used to help manage entries in the key table.
What's the difference between the methods sleep() and wait()
The code sleep(1000); puts thread aside for exactly one second. The code wait(1000), causes a wait of up to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.
Can an Interface have an inner class?
Yes public interface abc { static int i=0; void dd(); class a1 { a1() { int j; System.out.println("in interfia"); }; public static void main(String a1[]) { System.out.println("in interfia"); } } }
I made my class Cloneable but I still get 'Can't access protected method clone. Why?
Yeah, some of the Java books, in particular "The Java Programming Language", imply that all you have to do in order to have your class support clone() is implement the Cloneable interface. Not so. Perhaps that was the intent at some point, but that's not the way it works currently. As it stands, you have to implement your own public clone() method, even if it doesn't do anything special and just calls super.clone().
Name few Garbage collection algorithms?
Here they go:
Mark and Sweep
Reference counting
Tracing collectors
Copying collectors
Heap compaction
Mark-compact collectors
Why we are using such huge code for suspending and resuming. Apart from that we can just use
booean threadActivatedFlag = false;
while(){
initialize all thread..........
start the thread..
add in group...
}
........................
while(threadActivatedFlag )
{
if(threadGroup.activeCount()==0)
threadActivatedFlag = false;
else
Thread.sleep(4000);}
You need to insert huge amount of objects and randomly delete them one by one. Which Collection data structure is best pet?
LinkedList.
What goes wrong if the HashMap key has same hashCode value?
It leads to ‘Collision’ wherein all the values are stored in same bucket. Hence, the searching time increases quad radically.
Write a Java program to create three threads namely A, B, C and make them run one after another. (C has to run after B completes, B has to run after A completes).
Many ways to do it. I prefer join(). When a thrad A calls b.join(), then A runs only after thread b completes. So, for this problem, C has to call b.join() and B has to call a.join()
How will you declare a timer variable that will be accessed by multiple threads very frequently?
Declare the variable as volatile. Every thread caches a copy of instance variable, work with local copy, and then sync it with master copy. But, threads do not cache a copy of volatile instance variable.
How will you synchronize static variables?
Obtain class level lock. synchronized( obj.getClass()) {……..}
Assume a multiplication operation in java takes 10 milliseconds. So, what is the running time of the following for() loop
int k = 10;
for(int i=0; i<100; i++)
{
k = 20 * 100; // this takes 10 millisecond.
}
The for loop iterates only once, not 100 times. So the running time is 10 millisecond. Because, the loop evaluates to a constant result ( that is, k = 20 * 100 will yield same result for 100 times) . So, jvm is smart enough, runs the for() loop once and saves time. I just mention this, because the developer should not worry about expression level optimization, which is taken care by the jvm itself.
You have to write a java program that can read files of varying sizes, ranging from 100 KB (very small) to few GBs (large size).
You can write an intelligent program in this case :). If the file size is smaller, then read the whole file content in one-go. Read an example program given here. But, what if the file size is big? In this case, the program can’t read the whole file in one shot, as it would run out of memory. So, you can write the program in such a way that it reads the file content in byte arrays for several iterations. In this case, the running time of the program will depend on the size of byte array. So, how will you smartly determine the size of byte array?You can use Runtime.getRuntime().freeMemory() to find the freely available heap size. Based on this available memory, your program can create smaller or larger byte arrays at runtime. The larger the byte arrays, the lesser the response time.
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).
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 referring 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.
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 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).
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 Application Server are what Entity EJBs 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.
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 create a new bean each time - which would mean creating duplications of persistent data and break the integrity of EJB.
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.
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 its 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.
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 referring 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.
How does passivation work in stateful session beans?
Unlike entity beans and stateless session beans, stateful session bean are usually evicted from memory when they are passivated. This is not true of all vendors but this view serves as good model for understanding the concepts of passivation in session beans.
When a stateful bean experiences a lull in use -- between client invocations and transactions -- the container may choose to passivate the stateful bean instance. To conserve resources the bean instance is evicted from memory (dereferenced and garbage collected). When the EJB object receives a new client request, a new stateful instance is instantiated and associate with the EJB object to handle the request.
Stateful beans maintain a conversational state, which must be preserved before the bean instance is evicted from memory. To accomplish this, the container will write the conversational state of the bean instance to a secondary storage (usually disk). Only the non-transient serializable instance fields are preserved. When the bean is activated the new instance is populated with the preserved state. References to live resources like the EJBContext, DataSource, JNDI ENC, and other beans must also be maintained somehow -- usually in memory -- by the container.
The javax.ejb.SessionBean interface provides two callback methods that notify the bean instance it is about to passivated or was just activated. The ejbPassivate( ) method notifies the bean instance that it is about have its conversational state written to disk and be evicted from memory. Within this method the bean developer can perform operations just prior to passivation like closing open resources. The ejbActivate( ) method is executed just after a new bean instance has been instantiated and populated with conversational state from disk. The bean developer can use the ejbActivate( ) method to perform operations just prior to servicing client request, like opening resources.
Let's assume I use a JavaBean as a go-between a JSP and an EJB, and have, say, 50 concurrent clients that need to access the EJB functionality. Will the JSP container actually instantiate 50 instances of the bean, or can it reuse a single instance to access the EJB?
It depends on the scope you associate with the JavaBean. If you assign the bean with page (which is the default) scope or request scope, a new bean will be instantiated for each incoming request.
If you assign the bean with session scope, you will still have 50 instances loaded in memory (assuming each incoming request is triggered by a distinct client), although some may have been instantiated from an earlier request from the same client. However, you may not want to use the session scope for a high-volume site as these beans will continue to reside in memory, long after the request has been serviced, consuming valuable resources until they are invalidated either explicitly or due to a session timeout.
You can also assign the bean with application scope, in which case it is instantiated just once before being placed into the servlet context of the container. It can then be accessed at a later time, as long as the server is up and running. Although this may sound like an attractive proposition, do note that you will have to contend with significant multithreading issues. For instance, you'll have to ensure that the bean is accessed in a thread-safe manner from each of the JSP files. While you can do this using explicit synchronization from within the JSP file, do note that your application may take a significant performance hit because of this - especially if you expect tens or hundreds of concurrent clients accessing your pages.
So, in short, your best bet may be to assign the bean with request scope.
How to setup access control in an EJB such that different application clients have different rights to invoke different methods in one EJB?
1) Set up the different users/groups and the methods each can have access to in your deployment descriptor. Note: You don't have to specify different methods for each user, you could also just specify different users to your entire bean - for example if you only wanted another component of your application talking to your bean.
2) Inside your client code, whenever you make your connection to the EJB server (to look up the bean) you need to specify the user and password, in order to set the Identity of the client:
...
Properties p = new Properties();
..
p.put(Context.SECURITY_PRINCIPAL, "user");
p.put(Context.SECURITY_CREDENTIALS, "password");
...
3) Inside your bean, you can do "extra" security checks (if you used 'Role'-based security): (Assuming you have a 'manager' role defined in your deployment descriptor and a user assigned to this role)
public int getAccountBalance(accountId) {
if (ejbContext.isCallerInRole("manager"))
return balance;
}
You could also enforce security to your EJB server. Using Weblogic, you could add the following to your weblogic.properties file:
...
weblogic.password.user=password
...
where "user" is the username you grant access for and "password" (after '=') is the password for this username.
When using a stateful session bean with an idle timeout set, how can the bean receive notification from the container that it is being removed due to timeout?
[Question continues: ? (Through some tests, it looks like none of the standard EJB callback methods are called when a stateful session bean is removed due to idle-timeout.)]
According to the spec, ejbRemove need not (or must not) be called in this case. ejbPassivate is simply the Wrong Thing to be called (the bean is transitioning to the 'does not exist' state, not the 'passive' state).
The EJB 1.1. spec says in section 6.6.3 Missed ejbRemove Calls:
The application using the session bean should provide some clean up mechanism to periodically clean up the unreleased resources.
For example, if a shopping cart component is implemented as a session bean, and the session bean stores the shopping cart content in a database, the application should provide a program that runs periodically and removes “abandoned” shopping carts from the database.
Probably not the answer you're looking for, especially if you allocate some other resource (a Message Queue, for example) that you need to release. Although, if you're using a resource, you really should be getting it when you need it (via JNDI) and returning it back to the pool right away.
When using Primary Keys, why do I have to implement the hashCode() and equals() method in my bean?
Implementing the hashCode() and equals() functions ensure that the primary key object works properly when used with hash tables. Hash tables are the preferred way EJB servers use to store and quickly retrieve instantiated entity beans.
If session #1 uses widget "A" (which is an entity bean) then the server needs to do some work to instantiate and initialize the object. If session #2 then requests the same widget "A", the EJB server will look in its hash table of existing entity beans of type widget to see if widget "A" has already been instantiated.
Can I deploy two beans in a single jar file? If so, how?
Yes, multiple EJBs can be deployed in a single jar file. The deployment is somewhat different between EJB 1.0 and EJB 1.1.
In EJB 1.1 and in the draft EJB 2.0 specification, instead of a manifest and serialized deployment descriptors there is a single shared XML deployment descriptor named META-INF/ejb-jar.xml. Within ejb-jar.xml there must be either a <session> or <entity> element for each bean in the jar file. For example, the following XML fragment is for a jar file that contains one entity and one session bean:
<ejb-jar>
<enterprise-beans>
<session>
<ejb-name>MySessionBean</ejb-name>
... other xml elements describing the bean's deployment properties ...
</session>
<entity>
<ejb-name>MyEntityBean</ejb-name>
... other xml elements describing the bean's deployment properties ...
</entity>
</enterprise-beans>
</ejb-jar>
The EJB 2.0 draft specification for deployment descriptors differs from EJB 1.1 only in the addition of XML elements for describing additional bean properties.
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 statefull) to inform the container of your loss of interest in this bean.
How can I pass init parameters to enterprise beans?
You can specify Environment Entries that are accesssible by your EJB's. Inside your ejb-jar.xml you define the environment entries.
<env-entry>
<env-entry-name>theParameter</env-entry-name>
<enventry-type>java.lang.String</env-entry-type>
<env-entry-value>theValue</env-entry-value>
</env-entry>
You can access the variable inside your EJB using the Environment Naming Context (in EJB 1.1)
Context ctx = new InitialContext();
For session beans, we can use the SessionSynchronization interface. For entity beans, how do we have control over a transaction?
The SessionSynchronization interface is used by the Session beans to Synchronize the Instance variables after a rollback or after a commit operation, because container does not have any other way to inform the bean of these operations.
With Entity beans, this is not a problem as the Container automatically calls the ejbLoad method that refreshed the values from the database.
While deploying CMP entity beans, which fields in the bean are container-managed and how are they identified?
Container-managed fields may be specified in the bean's deployment descriptor. An entity bean, for example, has an XML deployment descriptor containing elements similar to the following:<br/>
<enterprise-beans>
<entity>
<description>This entity bean models an audio compact disc.</description>
<ejb-name>MusicCDBean</ejb-name>
<home>musicstore.MusicCDHome</home>
<remote>musicstore.MusicCD</remote>
<ejb-class>musicstore.MusicCDBean</ejb-class>
<persistence-type>Container</persistence-type>
<prim-key-class>musicstore.MusicCDPK</prim-key-class>
<reentrant>False</reentrant>
<cmp-field><field-name>upc</field-name></cmp-field>
<cmp-field><field-name>title</field-name></cmp-field>
<cmp-field><field-name>artist</field-name></cmp-field>
<cmp-field><field-name>type</field-name></cmp-field>
<cmp-field><field-name>price</field-name></cmp-field>
</entity>
</enterprise-beans>
In the above deployment descriptor, the container-managed fields are specified to be upc, title, artist, type, and price.
While the deployment descriptor provides information about the container-managed fields for use during deployment, the details of how these fields are mapped into the database (or other persistent storage mechanism) are controlled by the container-specific deployment process itself. To learn more about the container-specific deployment process, you will need to consult your container vendor's documentation.
What happens when two users access an Entity Bean concurrently?
Taken from Enterprise JavaBeans by Richard Monson-Haefel, "EJB, by default, prohibits concurrent access to bean instances. In other words, several clients can be connected to one EJB object, but only one client thread can access the bean instance at a time. If, for example, one of the clients invokes a method on the EJB object, no other client can access that bean instance until the method invocation is complete."
So, to answer your question, two users will never access an Entity Bean concurrently.
How can I pass init parameters to enterprise beans?
You can specify Environment Entries that are accesssible by your EJB's. Inside your ejb-jar.xml you define the environment entries.
<env-entry>
<env-entry-name>theParameter</env-entry-name>
<env-entry-type>java.lang.String</env-entry-type>
<env-entry-value>theValue</env-entry-value>
</env-entry>
You can access the variable inside your EJB using the Environment Naming Context (in EJB 1.1)
Context ctx = new InitialContext();
String val = (String)ctx.lookup("java:comp/env/theParameter");
If my session bean with single method insert record into 2 entity beans, how can know that the process is done in same transaction (the attributes for these beans are Required)?
If your session bean is using bean-managed transactions, you can ensure that the calls are handled in the same transaction by :
javax.transaction.UserTransaction tran= null;
try{
tran=ctx.getUserTransaction();
tran.begin();
myBeanHome1.create(....);
myBeanHome2.create(...);
tran.commit();
}catch(...){}
You may want to check if you're already running in a transaction by calling tran.getStatus().
What does ResultSet actually contain? Is it the actual data of the result or some links to databases? If it is the actual data then why can't we access it after connection is closed? A ResultSet is an interface. Its implementation depends on the driver and hence ,what it "contains" depends partially on the driver and what the query returns.
For example with the Odbc bridge what the underlying implementation layer contains is an ODBC result set. A Type 4 driver executing a stored procedure thatreturns a cursor - on an oracle database it actually returns a cursor in the database. The oracle cursor can however be processed like a ResultSet would be from the client.
Closing a connection closes all interaction with the database and releases any locks that might have been obtained in the process.
How do I insert an image file (or other raw data) into a database? All raw data types (including binary documents or images) should be read and uploaded to the database as an array of bytes, byte[]. Originating from a binary file,
setMaxRows(int) sets the limit of the maximum nuber of rows in a ResultSet object. If this limit is exceeded, the excess rows are "silently dropped". That's all the API says, so the setMaxRowsmethod may not help performance at all other than to decrease memory usage. A value of 0 (default) means no limit.
How can I retrieve only the first n rows, second n rows of a database using a particular WHERE clause ? For example, if a SELECT typically returns a 1000 rows, how do first retrieve the 100 rows, then go back and retrieve the next 100 rows and so on ? Use the Statement.setFetchSize method to indicate the size of each database fetch. Note that this method is only available in the Java 2 platform. For Jdk 1.1.X and Jdk 1.0.X, no standardized way of setting the fetch size exists. Please consult the Db driver manual.
What are different ways in which a thread can enter the waiting state?
A thread can enter the waiting state by the following ways:
1. Invoking its sleep() method,
2. By blocking on I/O
3. By unsuccessfully attempting to acquire an object's lock
4. By invoking an object's wait() method.
5. It can also enter the waiting state by invoking its (deprecated) suspend() method.
What is the difference between yielding and sleeping?
When a task invokes its yield() method, it returns to the ready state, either from waiting, running or after its creation. When a task invokes its sleep() method, it returns to the waiting state from a running state.
What is mutual exclusion? How can you take care of mutual exclusion using Java threads?
Mutual exclusion is a phenomenon where no two processes can access critical regions of memory at the same time. Using Java multithreading we can arrive at mutual exclusion. For mutual exclusion, you can simply use the synchronized keyword and explicitly or implicitly provide an Object, any Object, to synchronize on. The synchronized keyword can be applied to a class, to a method, or to a block of code. There are several methods in Java used for communicating mutually exclusive threads such as wait( ), notify( ), or notifyAll( ). For example, the notifyAll( ) method wakes up all threads that are in the wait list of an object.
How would you implement a thread pool?
public class ThreadPool implements ThreadPoolInt
This class is an generic implementation of a thread pool, which takes the following input
a) Size of the pool to be constructed
b) Name of the class which implements Runnable and constructs a thread pool with active threads that are waiting for activation. Once the threads have finished processing they come back and wait once again in the pool.
This thread pool engine can be locked i.e. if some internal operation is performed on the pool then it is preferable that the thread engine be locked. Locking ensures that no new threads are issued by the engine. However, the currently executing threads are allowed to continue till they come back to the passivePool.
Is there a separate stack for each thread in Java?
Yes. Every thread maintains its own separate stack, called Runtime Stack but they share the same memory. Elements of the stack are the method invocations, called activation records or stack frame. The activation record contains pertinent information about a method like local variables.
How do I extract the SQL statements required to move all tables and views from an existing database to another database?
The operation is performed in 9 steps:
1. Open a connection to the source database. Use the DriverManager class.
2. Find the entire physical layout of the current database. Use the DatabaseMetaData interface.
3. Create DDL SQL statements for re-creating the current database structure. Use the DatabaseMetaData interface.
4. Build a dependency tree, to determine the order in which tables must be setup. Use the DatabaseMetaData interface.
5. Open a connection to the target database. Use the DriverManager class.
6. Execute all DDL SQL statements from (3) in the order given by (4) in the target database to setup the table and view structure. Use the PreparedStatement interface.
7. If (6) threw exceptions, abort the entire process.
8. Loop over all tables in the physical structure to generate DML SQL statements for re-creating the data inside the table. Use the ResultSetMetaData interface.
9. Execute all DML SQL statements from (8) in the target database.
What does ResultSet actually contain? Is it the actual data of the result or some links to databases? If it is the actual data then why can't we access it after connection is closed?
A ResultSet is an interface. Its implementation depends on the driver and hence ,what it "contains" depends partially on the driver and what the query returns.
For example with the Odbc bridge what the underlying implementation layer contains is an ODBC result set. A Type 4 driver executing a stored procedure that returns a cursor - on an oracle database it actually returns a cursor in the databse. The oracle cursor can however be processed like a ResultSet would be from the client. Closing a connection closes all interaction with the database and releases any locks that might have been obtained in the process.
What are the new features added to JDBC 4.0?
What’s the difference between TYPE_SCROLL_INSENSITIVE and TYPE_SCROLL_SENSITIVE?
TYPE_SCROLL_INSENSITIVE
TYPE_SCROLL_SENSITIVE
An insensitive resultset is like the snapshot of the data in the database when query was executed.
A sensitive resultset does NOT represent a snapshot of data, rather it contains points to those rows which satisfy the query condition.
After we get the resultset the changes made to data are not visible through the resultset, and hence they are known as insensitive.
After we obtain the resultset if the data is modified then such modifications are visible throughresultset.
Performance not effected with insensitive.
Since a trip is made for every ‘get’ operation, the performance drastically get affected.
Difference between java.sql and javax.sql
java.sql is an API to access and process the data stored in a database, typically a relational database using the java. Different drivers can be installed dynamically for the access of various databases, using a framework which in-built in this JDBC API.
javax.sql is a JDBC API for the server side for accessing and processing the data from the databases typically a relational database using java. It is the essential part for J2EE. This API provides the facilities such as connection pooling, distributed transactions and row sets for the enterprise applications. An interface by name DataSource is provided in this API as an alternative to DriverManager to establish the connection.
DataSource and RowSet usage is direct, for the applications, where as connection pooling, distributed transactions are implemented by an infrastructure called middle-tier.
How do bean-managed transactions work?
When a bean with bean managed transactions is invoked, the container suspends any current transaction in the client’s context. In its method implementation, the bean initiates the transaction through the JTA UserTransaction interface. In stateful beans, the container associates the bean instance with the same transaction context across subsequent method calls until the bean explicitly completes the transaction. However, stateless beans aren’t allowed to maintain transaction context across method calls. Each method invocation must complete any transaction it initiates.
How do enterprise beans handle concurrent and loopback calls on entity beans?
Concurrent calls in the same transaction context on the same Enterprise JavaBean component are illegal and may lead to unpredictable results. A bean can be marked as non-reentrant by its deployment descriptor. This allows the container to detect and prevent illegal concurrent calls from clients. On the other hand, some entity beans may require loopback calls: that is, calls where bean A is invoked, in turn invoking bean B, which then invokes a method call on bean A. This kind of concurrency is tricky and is
best avoided.
TRANSACTION SUPPORT
How does a container manage access from multiple transactions on an entity bean?
Containers manage multiple transactions in one of two ways. First, the container can instantiate multiple instances of the bean and let the transaction management of the DBMS handle transaction processing issues. Or, the container can acquire an exclusive lock on the instance’s state in the database, and serialize access from multiple transactions to this instance.
How do you determine whether two entity beans are the same?
By invoking the EntityBean.isIdentical method. This method should be implemented by the entity bean developer to determine when two references are to the same object. Note that the equals and hashCode methods of Object are undefined for entity beans, since clients don’t directly access bean instances within a container.
How does the client get a reference to an existing entity bean?
a) SB may or may not be used for TX operational operations,
even they are used for TXs bean developer itself responsible to update the bean values into DB.
b)EBs are specially designed for TX operations
where bean develope is only responsible for updating bean values,
where the bean values were updated into DB by executing one additional funtion called ejbStore().
which beans are TX which are not?
*SB are used for TX & Non Tx operations
*EBs are only used for TX operations.
What is the TX operational difference SessionBean and EntityBean?
a) SB may or may not be used for TX operational operations,even they are used for TXs bean developer itself responsible to update the bean values into DB.
b)EBs are specially designed for TX operations where bean develope is only responsible for updating bean values,where the bean values were updated into DB by executing one addditional funtion called ejbStore().
What is "reentrant"? Why we use this in the deployment descriptor? Explain with an example.
The "reentrant " element dictates whether our bean can call itself through another bean.For exmple, take two beans are there in EJB container named "beanA" and "beanB".There is an element " True " in the ejb-jar.xml , deployment descriptor.If it has been set to True, If beanA calls beanB, in turn it (beanB) calls back beanA. this loop back call is possible.If it has been set to False, the above said case is not possible.This is special case of multi threading because it is only one path of execution that happens to loop back on itself.If we would like to support this " reentrant " behaviour, we should set this setting to True, so thatContainer will allow two threads to run inside of a beanA at once.If we wont that behaviour , we should set it to "False" .with regards,santh
Can you call one constructor from another?
Yes, by using this() syntax. E.g.
public Pet(int id) {
this.id = id; // "this" means this object
}
public Pet (int id, String type) {
this(id); // calls constructor public Pet(int id)
this.type = type; // "this" means this object
}
If an Employee class is present and its objects are added in an arrayList. Now I want the list to be sorted on the basis of the employeeID of Employee class. What are the steps?
· Implement Comparable interface for the Employee class and override the compareTo(Object obj) method in which compare the employeeID
· Now call Collections.sort() method and pass list as an argument.
Now consider that Employee class is a jar file.
· Since Comparable interface cannot be implemented, create Comparator and override the compare(Object obj, Object obj1) method .
· Call Collections.sort() on the list and pass comparator as an argument.
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. Implementation-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 constructor for its uppercase. This process continues until the constructor 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.
How do I find whether a parameter exists in the request object?
boolean hasFoo = !(request.getParameter("foo") == null request.getParameter("foo").equals(""));
or
boolean hasParameter = request.getParameterMap().contains(theParameter); //(which works in Servlet 2.3+)
Source Code
final int limit = 4;
Map A = new Hashtable();
Integer[] B = new Integer[limit];
B[0] = new Integer(8);
B[1] = new Integer(8);
B[2] = new Integer(8);
B[3] = new Integer(8);
A.put("Integers" , B);
System.out.println(B);
A.put("Integers" , B);
Object[] B2 = (Object[])A.get("Integers");
for(int i = 0; i< B2.length ;i++)
System.out.println(B2[i]);
How do wait and notify really work?
You can synchronize one or more method of a class (actually even just a block of code but leave it for now). When you synchronize a method it means you are telling the JVM that a thread needs to acquire the lock of the object before it can call this method. Since an object can have only one lock so if a thread is accessing a synchronized method, then no thread can access any of the synchronised method of that object. Though they can call those methods of the object which are not synchronized.Typically, releasing the lock means the thread holding the lock (the thread currently in the synchronized method) exits the synchronized method. At that point, the lock is free until some other thread enters a synchronized method on that object.
Now to understand wait() and notify() you can refer following example which is easy to understand. Here we have two classes named ThreadA and ThreadB. The main method in class ThreadA is printing the sum of i starting from 0 to 100. But this calculation is being done in the run() method of class ThreadB. So obviously main() method should wait for run() to complete so that it can print the total. Here comes the use of wait() method. And now you can understand why wait and notify should by called in synchronized context. When the thread waits it temporarily releases the lock for other threads to use but it will need it again to continue its execution. So once the thread which is waiting is notified (by notified method) it then starts comepting to acquire lock so that it can complete the remaining part of the method.
1. class ThreadA {
2. public static void main(String [] args) {
3. ThreadB b = new ThreadB();
4. b.start();
5.
6. synchronized(b) {
7. try {
8. System.out.println("Waiting for b to complete...");
9. b.wait();
10. } catch (InterruptedException e) {}
11. }
12. System.out.println("Total is: " + b.total);
13. }
14. }
15.
16. class ThreadB extends Thread {
17. int total;
18.
19. public void run() {
20. synchronized(this) {
21. for(int i=0;i<100;i++) {
22. total += i;
23. }
24. notify();
25. }
26. }
27. }
How do I submit a form or a part of a form without a page refresh?
When creating a form make sure that the "form" element "onSubmit" attribute is set to a JavaScript function that returns false.
<form onSubmit="doAJAXSubmit();return false;" >
<input id="tf1" />
<input id="submit1" value="Update"/>
</>
You can also submit data by associating a function with a form button in a similar way.
<form onSubmit="doAJAXSubmit();return false;" >
<input id="tf1" />
<input id="button1" onClick="doAJAXSubmit()" value="Update"/>
</>
Note that the form "onSubmit" attribute is still set. If the user hits the enter key in the text field the form will be submitted so you still need to handle that case.
When updating the page it is recommend you wait to make sure that the AJAX update of the form data was successful before updating the data in the page. Otherwise, the data may not properly update and the user may not know. I like to provide an informative message when doing a partial update and upon a successful AJAX interaction I will then update the page.
Give an example of overriding the equals method.
It is not always necessary to override hashcode and equals. But if you think you need to override one, then you need to override both of them. Let's analyze what whould happen if we override one but not the other and we attempt to use a Map.
Say we have a class like this and that two objects of MyClass are equal if their importantField is equal (with hashCode and equals generated by eclipse)
public class MyClass {
private final String importantField;
private final String anotherField;
public MyClass(final String equalField, final String anotherField) {
this.importantField = equalField;
this.anotherField = anotherField;
}
public String getEqualField() {
return importantField;
}
public String getAnotherField() {
return anotherField;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((importantField == null) ? 0 : importantField.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final MyClass other = (MyClass) obj;
if (importantField == null) {
if (other.importantField != null)
return false;
} else if (!importantField.equals(other.importantField))
return false;
return true;
}
}
Override only hashCode
Imagine you have this
MyClass first = new MyClass("a","first");
MyClass second = new MyClass("a","second");
If you only override hashCode then when you call myMap.put(first,someValue) it takes first, calculates its hashCode and stores it in a given bucket. Then when you callmyMap.put(first,someOtherValue) it should replace first with second as per the Map Documentation because they are equal (according to our definition).
But the problem is that equals was not redefined, so when the map hashes second and iterates through the bucket looking if there is an object k such that second.equals(k) is true it won't find any as second.equals(first) will be false.
Override only equals
If only equals is overriden, then when you call myMap.put(first,someValue) first will hash to some bucket and when you call myMap.put(first,someOtherValue) it will hash to some other bucket. So, although they are equal, as they don't hash to the same bucket (different hashCode) the map can't realize it and both of them stay in the map.
Can I use JavaScript to submit a form?
You can submit a form with a link as below. BTW, the examples below assume you are in an block and 'myForm' is picked up from the struts-config.xml name field of the action.
<a href='javascript:void(document.forms["myForm"].submit()>My Link</a>
Now the trick in the action is to decode what action you intend to perform. Since you are using JavaScript, you could set a field value and look for it in the request or in the form.
... html/javascript part ...
<input 'hidden' value='myAction' />
<input 'button' value='Save Meeeee'
onclick='document.forms["myForm"].myAction.value="save";
document.forms["myForm"].submit();' />
<input 'button' value='Delete Meeeee'
onclick='document.forms["myForm"].myAction.value="delete";
document.forms["myForm"].submit();' />
... the java part ...
class MyAction extends ActionForm implements Serializable {
public ActionForward execute (ActionMapping map, ActionForm form,
HttpServletRequest req, HttpServletResponse) {
String myAction = req.getParameter("myAction");
if (myAction.equals("save") {
// ... save action ...
} else if (myAction.equals("delete") {
// ... delete action ...
}
}
}
}
This is just one of many ways to achieve submitting a form and decoding the intended action. Once you get used to the framework you will find other ways that make more sense for your coding style and requirements. Just remember this example is completely non-functional without JavaScript.
Creates only one session i.e., they end up with using same session. Sessions is specific to the client but not the web components. And there is a 1-1 mapping between client and a session.
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 JSPengine 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.
What is use of parseQueryString ?
Parses a query string and builds a hashtable of key-value pairs, where the values are arrays of strings. The query string should have the form of a string packaged by the GET or POST method. (For example, it should have its key-value pairs delimited by ampersands (&) and its keys separated from its values by equal signs (=).)
Note:
public static Hashtable parseQueryString(String s)
How can i create connection pooling in tomcat?
We can create connection pooling using tomcatFor that
We need to download 3 jar files
a. commons-dbcp-1.2.jar
b. commons-collections-3.1.jar
c. commons-pool-1.3.jar
We want to add an entry in server.xml of the tomcat factory org.apache.commons.dbcp.BasicDataSourceFactory driverClassName oracle.jdbc.OracleDriver url jdbc:oracle:thin:@localhost:1521:orcl username anand password pass maxActive 20 maxIdle 10 maxWait -1
How can I pass data from a servlet running in one context (webapp) to a servlet running in another context?
There are three ways I can think of off the top of my head:
- Store the information you want to share in a persistant format, such as in a file system or database. That way, any servlet that is running in a JVM that can "see" these resources can get to this information.
- If persisting this information is not an option, you can bind this information to a context that is accessible to all servlet contexts, such as the application server's context. This way, you can keep the data you want to share in memory.
- Use the old fashion way of passing information to a servlet - HTTP. One servlet could foward a request to another servlet and include the data that needs to be shared as parameters in the request.
Suppose I have 2 servers, server1 and server2. How can I take data in a cookie from server1, and send it to server2?
You'll have to create a (new) similar cookie on server 2.
Have a ReadCookieServlet running on server1 that
- Reads the cookie, using request.getCookies()
- Redirects to WriteCookieServlet running on server2, passing the cookie name, value and expiration date as request parameters, using response.sendRedirect().
- Have a WriteCookieServlet running on server2 that
- Reads the cookie name, value and expiration date request parameters, using request.getParameter().
- Creates a similar cookie, using response.addCookie().
When building web applications, what are some areas where synchronization problems arrise?
In general, you will run into synchronization issues when you try to access any shared resource. By shared resource, I mean anything which might be used by more than one request.
Typical examples include:
- Connections to external servers, especially if you have any sort of pooling.
- Anything which you include in a HttpSession. (Your user could open many browser windows and make many simultaneous requests within the one session.)
- Log destinations, if you do your own logging from your servlets.
Can Tomcat be configured to interpret all, or selected, .html files within a given context as JSP? Or, do JSP files have to end with a .jsp extension?
Yes you can do that by modifying the web.xml file. You will have to invoke the org.apache.jasper.runtime.JspServlet for all the requests having extension .html. You can do that by changing the Servlet mapping code:
<servlet-mapping>
<servlet-name>
jsp
</servlet-name>
<url>*.html</url>
</servlet-mapping>
And comment out the following block
<mime-mapping>
<extension>
html
</extension>
<mime-type>
text/html
</mime-type>
</mime-mapping>
I want my servlet page to redirect to a login page if the session has timed out. How can I know if my session has timed out?
If the servlet engine does the time-out, following code should help you:
//assume you have a HttpServletRequest request
if(request.getSession(false)==null) {
//no valid session (timeouted=invalid)
//code to redirect to login page
}
How can my application get to know when a HttpSession is removed (when it time-outs)?
Define a class, say SessionTimeoutNotifier, that implements
javax.servlet.http.HttpSessionBindingListener. Create a SessionTimeoutNotifier object and add it to the user session. When the session is removed, SessionTimeoutNotifier.valueUnbound() will be called by the servlet engine. You can implement valueUnbound() to do whatever you want.
What is the difference between URL encoding, URL rewriting, HTML escaping, and entity encoding?
URL Encoding is a process of transforming user input to a CGI form so it is fit for travel across the network -- basically, stripping spaces and punctuation and replacing with escape characters. URL Decoding is the reverse process. To perform these operations, call java.net.URLEncoder.encode() and java.net.URLDecoder.decode() (the latter was (finally!) added to JDK 1.2, aka Java 2).
Example: changing "We're #1!" into "We%27re+%231%21"
URL Rewriting is a technique for saving state information on the user's browser between page hits. It's sort of like cookies, only the information gets stored inside the URL, as an additional parameter. The HttpSession API, which is part of the Servlet API, sometimes uses URL Rewriting when cookies are unavailable.
Example: changing <A HREF="nextpage.html"> into
<A HREF="nextpage.html;$sessionid$=DSJFSDKFSLDFEEKOE"> (or whatever the actual syntax is; I forget offhand)
(Unfortunately, the method in the Servlet API for doing URL rewriting for session management is called encodeURL(). Sigh...)
There's also a feature of the Apache web server called URL Rewriting; it is enabled by the mod_rewrite module. It rewrites URLs on their way in to the server, allowing you to do things like automatically add a trailing slash to a directory name, or to map old file names to new file names. This has nothing to do with servlets. For more information, see the Apache FAQ (http://www.apache.org/docs/misc/FAQ.html#rewrite-more-config) .
How do I ensure that my servlet is thread-safe?
This is actually a very complex issue. A few guidelines:
- The init() method is guaranteed to be called once per servlet instance, when the servlet is loaded. You don't have to worry about thread safety inside this method, since it is only called by a single thread, and the web server will wait until that thread exits before sending any more threads into your service() method.
- Every new client request generates (or allocates) a new thread; that thread calls the service() method of your servlet (which may in turn call doPost(), doGet() and so forth).
- Under most circumstances, there is only one instance of your servlet, no matter how many client requests are in process. That means that at any given moment, there may be many threads running inside the service() method of your solo instance, all sharing the same instance data and potentially stepping on each other's toes. This means that you should be careful to synchronize access to shared data (instance variables) using the synchronized keyword.
- Note that you need not (and should not) synchronize on local data or parameters. And especially you shouldn't synchronize the service() method! (Or doPost(), doGet() et al.)
- A simple solution to synchronizing is to always synchronize on the servlet instance itself using &quot;synchronized (this) { ... }&quot;. However, this can lead to performance bottlenecks; you're usually better off synchronizing on the data objects themselves.
- If you absolutely can't deal with synchronizing, you can declare that your servlet &quot;implements SingleThreadModel&quot;. This empty interface tells the web server to only send one client request at a time into your servlet. From the JavaDoc: &quot;If the target servlet is flagged with this interface, the servlet programmer is guaranteed that no two threads will execute concurrently the service method of that servlet. This guarantee is ensured by maintaining a pool of servlet instances for each such servlet, and dispatching each service call to a free servlet. In essence, if the servlet implements this interface, the servlet will be thread safe.&quot; Note that this is not an ideal solution, since performance may suffer (depending on the size of the instance pool), plus it's more difficult to share data across instances than within a single instance.
- To share data across successive or concurrent requests, you can use either instance variables or class-static variables, or use Session Tracking.
- The destroy() method is not necessarily as clean as the init() method. The server calls destroy either after all service calls have been completed, or after a certain number of seconds have passed, whichever comes first. This means that other threads might be running service requests at the same time as your destroy() method is called! So be sure to synchronize, and/or wait for the other requests to quit. Sun's Servlet Tutorial has an example of how to do this with reference counting.
- destroy() can not throw an exception, so if something bad happens, call log() with a helpful message (like the exception). See the &quot;closing a JDBC connection&quot; example in Sun's Tutorial.
public class ThreadPool extends java.lang.Object implements ThreadPoolInt
This class is an generic implementation of a thread pool, which takes the following input
a) Size of the pool to be constructed
b) Name of the class which implements Runnable (which has a visible default constructor)
and constructs a thread pool with active threads that are waiting for activation. once the threads have finished processing they come back and wait once again in the pool.
This thread pool engine can be locked i.e. if some internal operation is performed on the pool then it is preferable that the thread engine be locked. Locking ensures that no new threads are issued by the engine. However, the currently executing threads are allowed to continue till they come back to the passivePool
When and Where not to Use java:comp/env
In this post, I wrote about the need to use the prefix java:comp/env when looking up ejb/resource in the current naming environment. Equally important is to know where/when not to use it.
1. Don't use java:comp/env in standard deployment descriptors, such as web.xml, ejb-jar.xml, and application-client.xml. I can't think of any elements in these descriptors that contain java:comp/env.
2. Don't use java:comp/env in appserver-specific deployment plan files.
3. Don't use java:comp/env in any fields of resource and/or ejb injection, whether it's field or method injection.
4.Don't use java:comp/env when looking up resource/ejb using javax.ejb.EJBContext.lookup (String name). This is a new method in javax.ejb.EJBContext in EJB 3. The lookup name in this case is always relative to java:comp/env.
5. Don't use java:comp/env when looking up certain standard J2EE and JavaEE resources. They reside directly under java:comp/, with no /env. For instance:
java:comp/UserTransaction
java:comp/EJBContext
java:comp/ORB
java:comp/TransactionSynchronizationRegistry
6. Don't use java:comp/env when looking up global resources in a server-dependent way. Some application servers let you look up resources by their global JNDI name. In such case, their lookup name should not contain java:comp/env. For example, java:/defaultDS in jboss. In JavaEE SDK 5/Glassfish/Sun Java System Application Server 9, I can also directly look up jdbc/__default (the default datasource) without configuring it in any descriptors. Note that this style of lookup is not portable. It ties your apps to specifc runtime server environment, and should really be avoided.
7. Don't use java:comp/env in the name of any physical resources inside an application server, like jdbc-resource, jdbc-pool, JMS queue or topic, EJB JNDI name, persistence manager, etc.
What are some of the best practices relating to Java collection?
Use ArrayLists, HashMap etc as opposed to Vector, Hashtable etc, where possible to avoid any
- synchonization overhead. Even better is to use just arrays where possible. If multiple threads concurrently access a collection and at least one of the threads either adds or deletes an entry into the collection, then the collection must be externally synchronized. This is achieved by:
List myList = Collections.synchronizedList (myList);
- Set the initial capacity of a collection appropriately (e.g. ArrayList, HashMap etc). This is because collection classes like ArrayList, HashMap etc must grow periodically to accommodate new elements. But if you have a very large array, and you know the size in advance then you can speed things up by setting the initial size appropriately.
- For example: HashMaps/Hashtables need to be created with sufficiently large capacity to minimize rehashing (which happens every time the table grows). HashMap has two parameters initial capacity and load factor that affect its performance and space requirements. Higher load factor values (default load factor of 0.75 provides a good trade off between performance and space) will reduce the space cost but will increase the lookup cost of myMap.get(…) and myMap.put(…) methods. When the number of entries in the HashMap exceeds the current capacity * loadfactor then the capacity of the HasMap is roughly doubled by calling the rehash function. It is also very important not to set the initial capacity too high or load factor too low if iteration performance or reduction in space is important.
- Program in terms of interface not implementation: For example you might decide a LinkedList is the best choice for some application, but then later decide ArrayList might be a better choice for performance reason.
List list = new ArrayList(100); //program in terms of interface & set the initial capacity.
Instead of:
ArrayList list = new ArrayList();
Avoid storing unrelated or different types of objects into same collection: This is analogous to storing items in pigeonholes without any labelling. To store items use value objects or data objects (as oppose to storing every attribute in an ArrayList or HashMap). Provide wrapper classes around your collection API classes like ArrayList, Hashmap etc as shown in better approach column. Also where applicable consider using composite design pattern, where an object may represent a single object or a collection of objects.
StringBuilder vs StringBuffer StringBuilder was introduced in JDK 1.5. What's the difference between StringBuilder and StringBuffer? According to javadoc, StringBuilder is designed as a replacement for StringBuffer in single-threaded usage. Their key differences in simple term:
- StringBuffer is designed to be thread-safe and all public methods in StringBuffer are synchronized. StringBuilder does not handle thread-safety issue and none of its methods is synchronized.
- StringBuilder has better performance than StringBuffer under most circumstances.
- Use the new StringBuilder wherever possible.
/**
* readObject is called to restore the state of the
* StringBuffer from a stream.
*/
private void readObject(java.io.ObjectInputStream s)
Note the above javadoc still refers to StringBuffer where it should be StringBuilder.
In Java, you can sort objects that implement the Collection interface, using either the comparable interface or a comparator class. What's the difference?
A Comparable interfaced class must contain a method called compareTo to compare two objects (one being the object on which it is called and the other being passed as a parameter) which returns an integer, negative for a < b, positive for a > b and 0 otherwise. It must also contain an equals method, returning a boolean, on the same parameters.
A Comparator is a class in its own right, which implements the Comparator interface; that means it must contain a method called compare (two objects as parameters) which returns a negative, zero or positive integer depending on whether the first object is less than, equal to, or greater than the second.
If you want to sort a collection using its comparable interface, you simply call the static Collections.sort method on it ... so if we had an ArrayList called Actable, which implemented Comparable, we could write:
Collections.sort(Actable);
To sort a collection using a Comparator class, you need to pass an extra parameter into the Collections.sortmethod - that parameter being an instance of a Comparator object. Thus:Collections.sort(Actable, new Bynum());
So in effect, using the comparable interface gives you a default sort order of your own making, whereas the comparator is more flexible as it allows you define a whole series of different types of sorting that can be applied to a whole lot of different types of objects.
What are the approaches that you will follow for making a program very efficient? - By avoiding too much of static methods avoiding the excessive and unnecessary use of synchronized methods Selection of related classes based on the application (meaning synchronized classes for multiuser and non-synchronized classes for single user) Usage of appropriate design patterns Using cache methodologies for remote invocations Avoiding creation of variables within a loop and lot more.
What is the difference between shallow copy and deep copy?
Shallow copy shares the same reference with the original object like cloning, whereas the deep copy get a duplicate instance of the original object. If the shallow copy has been changed, the original object will be reflected and vice versa
This class (IncrementImpl) will be used by various threads concurrently; can you see the inherent flaw(s)? How would you improve it?
public class IncrementImpl {
private static int counter = 0;
public synchronized void increment() {
counter++;
}
public int getCounter() {
return counter;
}
}
The counter is static variable which is shared by multiple instances of this class. The increment() method is synchronized, but the getCounter() should be synchronized too. Otherwise the Java run-time system will not guarantee the data integrity and the race conditions will occur. The famous producer/consumer example listed at Sun's thread tutorial site will tell more.
one of solutions
public class IncrementImpl {
private static int counter = 0;
public synchronized void increment() {
counter++;
}
public synchronized int getCounter() {
return counter;
}
}
What kind of security tools are available in J2SE 5.0?
There are three tools that can be used to protect application working within the scope of security policies set at remote sites.
keytool -- used to manage keystores and certificates.
jarsigner -- used to generate and verify JAR signatures.
policytool -- used for managing policy files.
There are three tools that help obtain, list and manage Kerberos tickets.
kinit -- used to obtain Kerberos V5 tickets.
tklist -- used to list entries in credential cache and key tab.
ktab -- used to help manage entries in the key table.
What's the difference between the methods sleep() and wait()
The code sleep(1000); puts thread aside for exactly one second. The code wait(1000), causes a wait of up to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.
Can an Interface have an inner class?
Yes public interface abc { static int i=0; void dd(); class a1 { a1() { int j; System.out.println("in interfia"); }; public static void main(String a1[]) { System.out.println("in interfia"); } } }
I made my class Cloneable but I still get 'Can't access protected method clone. Why?
Yeah, some of the Java books, in particular "The Java Programming Language", imply that all you have to do in order to have your class support clone() is implement the Cloneable interface. Not so. Perhaps that was the intent at some point, but that's not the way it works currently. As it stands, you have to implement your own public clone() method, even if it doesn't do anything special and just calls super.clone().
Name few Garbage collection algorithms?
Here they go:
Mark and Sweep
Reference counting
Tracing collectors
Copying collectors
Heap compaction
Mark-compact collectors
Why we are using such huge code for suspending and resuming. Apart from that we can just use
booean threadActivatedFlag = false;
while(){
initialize all thread..........
start the thread..
add in group...
}
........................
while(threadActivatedFlag )
{
if(threadGroup.activeCount()==0)
threadActivatedFlag = false;
else
Thread.sleep(4000);}
You need to insert huge amount of objects and randomly delete them one by one. Which Collection data structure is best pet?
LinkedList.
What goes wrong if the HashMap key has same hashCode value?
It leads to ‘Collision’ wherein all the values are stored in same bucket. Hence, the searching time increases quad radically.
Write a Java program to create three threads namely A, B, C and make them run one after another. (C has to run after B completes, B has to run after A completes).
Many ways to do it. I prefer join(). When a thrad A calls b.join(), then A runs only after thread b completes. So, for this problem, C has to call b.join() and B has to call a.join()
How will you declare a timer variable that will be accessed by multiple threads very frequently?
Declare the variable as volatile. Every thread caches a copy of instance variable, work with local copy, and then sync it with master copy. But, threads do not cache a copy of volatile instance variable.
How will you synchronize static variables?
Obtain class level lock. synchronized( obj.getClass()) {……..}
Assume a multiplication operation in java takes 10 milliseconds. So, what is the running time of the following for() loop
int k = 10;
for(int i=0; i<100; i++)
{
k = 20 * 100; // this takes 10 millisecond.
}
The for loop iterates only once, not 100 times. So the running time is 10 millisecond. Because, the loop evaluates to a constant result ( that is, k = 20 * 100 will yield same result for 100 times) . So, jvm is smart enough, runs the for() loop once and saves time. I just mention this, because the developer should not worry about expression level optimization, which is taken care by the jvm itself.
You have to write a java program that can read files of varying sizes, ranging from 100 KB (very small) to few GBs (large size).
You can write an intelligent program in this case :). If the file size is smaller, then read the whole file content in one-go. Read an example program given here. But, what if the file size is big? In this case, the program can’t read the whole file in one shot, as it would run out of memory. So, you can write the program in such a way that it reads the file content in byte arrays for several iterations. In this case, the running time of the program will depend on the size of byte array. So, how will you smartly determine the size of byte array?You can use Runtime.getRuntime().freeMemory() to find the freely available heap size. Based on this available memory, your program can create smaller or larger byte arrays at runtime. The larger the byte arrays, the lesser the response time.
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).
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 referring 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.
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 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).
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 Application Server are what Entity EJBs 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.
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 create a new bean each time - which would mean creating duplications of persistent data and break the integrity of EJB.
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.
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 its 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.
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 referring 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.
How does passivation work in stateful session beans?
Unlike entity beans and stateless session beans, stateful session bean are usually evicted from memory when they are passivated. This is not true of all vendors but this view serves as good model for understanding the concepts of passivation in session beans.
When a stateful bean experiences a lull in use -- between client invocations and transactions -- the container may choose to passivate the stateful bean instance. To conserve resources the bean instance is evicted from memory (dereferenced and garbage collected). When the EJB object receives a new client request, a new stateful instance is instantiated and associate with the EJB object to handle the request.
Stateful beans maintain a conversational state, which must be preserved before the bean instance is evicted from memory. To accomplish this, the container will write the conversational state of the bean instance to a secondary storage (usually disk). Only the non-transient serializable instance fields are preserved. When the bean is activated the new instance is populated with the preserved state. References to live resources like the EJBContext, DataSource, JNDI ENC, and other beans must also be maintained somehow -- usually in memory -- by the container.
The javax.ejb.SessionBean interface provides two callback methods that notify the bean instance it is about to passivated or was just activated. The ejbPassivate( ) method notifies the bean instance that it is about have its conversational state written to disk and be evicted from memory. Within this method the bean developer can perform operations just prior to passivation like closing open resources. The ejbActivate( ) method is executed just after a new bean instance has been instantiated and populated with conversational state from disk. The bean developer can use the ejbActivate( ) method to perform operations just prior to servicing client request, like opening resources.
Let's assume I use a JavaBean as a go-between a JSP and an EJB, and have, say, 50 concurrent clients that need to access the EJB functionality. Will the JSP container actually instantiate 50 instances of the bean, or can it reuse a single instance to access the EJB?
It depends on the scope you associate with the JavaBean. If you assign the bean with page (which is the default) scope or request scope, a new bean will be instantiated for each incoming request.
If you assign the bean with session scope, you will still have 50 instances loaded in memory (assuming each incoming request is triggered by a distinct client), although some may have been instantiated from an earlier request from the same client. However, you may not want to use the session scope for a high-volume site as these beans will continue to reside in memory, long after the request has been serviced, consuming valuable resources until they are invalidated either explicitly or due to a session timeout.
You can also assign the bean with application scope, in which case it is instantiated just once before being placed into the servlet context of the container. It can then be accessed at a later time, as long as the server is up and running. Although this may sound like an attractive proposition, do note that you will have to contend with significant multithreading issues. For instance, you'll have to ensure that the bean is accessed in a thread-safe manner from each of the JSP files. While you can do this using explicit synchronization from within the JSP file, do note that your application may take a significant performance hit because of this - especially if you expect tens or hundreds of concurrent clients accessing your pages.
So, in short, your best bet may be to assign the bean with request scope.
How to setup access control in an EJB such that different application clients have different rights to invoke different methods in one EJB?
1) Set up the different users/groups and the methods each can have access to in your deployment descriptor. Note: You don't have to specify different methods for each user, you could also just specify different users to your entire bean - for example if you only wanted another component of your application talking to your bean.
2) Inside your client code, whenever you make your connection to the EJB server (to look up the bean) you need to specify the user and password, in order to set the Identity of the client:
...
Properties p = new Properties();
..
p.put(Context.SECURITY_PRINCIPAL, "user");
p.put(Context.SECURITY_CREDENTIALS, "password");
...
3) Inside your bean, you can do "extra" security checks (if you used 'Role'-based security): (Assuming you have a 'manager' role defined in your deployment descriptor and a user assigned to this role)
public int getAccountBalance(accountId) {
if (ejbContext.isCallerInRole("manager"))
return balance;
}
You could also enforce security to your EJB server. Using Weblogic, you could add the following to your weblogic.properties file:
...
weblogic.password.user=password
...
where "user" is the username you grant access for and "password" (after '=') is the password for this username.
When using a stateful session bean with an idle timeout set, how can the bean receive notification from the container that it is being removed due to timeout?
[Question continues: ? (Through some tests, it looks like none of the standard EJB callback methods are called when a stateful session bean is removed due to idle-timeout.)]
According to the spec, ejbRemove need not (or must not) be called in this case. ejbPassivate is simply the Wrong Thing to be called (the bean is transitioning to the 'does not exist' state, not the 'passive' state).
The EJB 1.1. spec says in section 6.6.3 Missed ejbRemove Calls:
The application using the session bean should provide some clean up mechanism to periodically clean up the unreleased resources.
For example, if a shopping cart component is implemented as a session bean, and the session bean stores the shopping cart content in a database, the application should provide a program that runs periodically and removes “abandoned” shopping carts from the database.
Probably not the answer you're looking for, especially if you allocate some other resource (a Message Queue, for example) that you need to release. Although, if you're using a resource, you really should be getting it when you need it (via JNDI) and returning it back to the pool right away.
When using Primary Keys, why do I have to implement the hashCode() and equals() method in my bean?
Implementing the hashCode() and equals() functions ensure that the primary key object works properly when used with hash tables. Hash tables are the preferred way EJB servers use to store and quickly retrieve instantiated entity beans.
If session #1 uses widget "A" (which is an entity bean) then the server needs to do some work to instantiate and initialize the object. If session #2 then requests the same widget "A", the EJB server will look in its hash table of existing entity beans of type widget to see if widget "A" has already been instantiated.
Can I deploy two beans in a single jar file? If so, how?
Yes, multiple EJBs can be deployed in a single jar file. The deployment is somewhat different between EJB 1.0 and EJB 1.1.
In EJB 1.1 and in the draft EJB 2.0 specification, instead of a manifest and serialized deployment descriptors there is a single shared XML deployment descriptor named META-INF/ejb-jar.xml. Within ejb-jar.xml there must be either a <session> or <entity> element for each bean in the jar file. For example, the following XML fragment is for a jar file that contains one entity and one session bean:
<ejb-jar>
<enterprise-beans>
<session>
<ejb-name>MySessionBean</ejb-name>
... other xml elements describing the bean's deployment properties ...
</session>
<entity>
<ejb-name>MyEntityBean</ejb-name>
... other xml elements describing the bean's deployment properties ...
</entity>
</enterprise-beans>
</ejb-jar>
The EJB 2.0 draft specification for deployment descriptors differs from EJB 1.1 only in the addition of XML elements for describing additional bean properties.
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 statefull) to inform the container of your loss of interest in this bean.
How can I pass init parameters to enterprise beans?
You can specify Environment Entries that are accesssible by your EJB's. Inside your ejb-jar.xml you define the environment entries.
<env-entry>
<env-entry-name>theParameter</env-entry-name>
<enventry-type>java.lang.String</env-entry-type>
<env-entry-value>theValue</env-entry-value>
</env-entry>
You can access the variable inside your EJB using the Environment Naming Context (in EJB 1.1)
Context ctx = new InitialContext();
For session beans, we can use the SessionSynchronization interface. For entity beans, how do we have control over a transaction?
The SessionSynchronization interface is used by the Session beans to Synchronize the Instance variables after a rollback or after a commit operation, because container does not have any other way to inform the bean of these operations.
With Entity beans, this is not a problem as the Container automatically calls the ejbLoad method that refreshed the values from the database.
While deploying CMP entity beans, which fields in the bean are container-managed and how are they identified?
Container-managed fields may be specified in the bean's deployment descriptor. An entity bean, for example, has an XML deployment descriptor containing elements similar to the following:<br/>
<enterprise-beans>
<entity>
<description>This entity bean models an audio compact disc.</description>
<ejb-name>MusicCDBean</ejb-name>
<home>musicstore.MusicCDHome</home>
<remote>musicstore.MusicCD</remote>
<ejb-class>musicstore.MusicCDBean</ejb-class>
<persistence-type>Container</persistence-type>
<prim-key-class>musicstore.MusicCDPK</prim-key-class>
<reentrant>False</reentrant>
<cmp-field><field-name>upc</field-name></cmp-field>
<cmp-field><field-name>title</field-name></cmp-field>
<cmp-field><field-name>artist</field-name></cmp-field>
<cmp-field><field-name>type</field-name></cmp-field>
<cmp-field><field-name>price</field-name></cmp-field>
</entity>
</enterprise-beans>
In the above deployment descriptor, the container-managed fields are specified to be upc, title, artist, type, and price.
While the deployment descriptor provides information about the container-managed fields for use during deployment, the details of how these fields are mapped into the database (or other persistent storage mechanism) are controlled by the container-specific deployment process itself. To learn more about the container-specific deployment process, you will need to consult your container vendor's documentation.
What happens when two users access an Entity Bean concurrently?
Taken from Enterprise JavaBeans by Richard Monson-Haefel, "EJB, by default, prohibits concurrent access to bean instances. In other words, several clients can be connected to one EJB object, but only one client thread can access the bean instance at a time. If, for example, one of the clients invokes a method on the EJB object, no other client can access that bean instance until the method invocation is complete."
So, to answer your question, two users will never access an Entity Bean concurrently.
How can I pass init parameters to enterprise beans?
You can specify Environment Entries that are accesssible by your EJB's. Inside your ejb-jar.xml you define the environment entries.
<env-entry>
<env-entry-name>theParameter</env-entry-name>
<env-entry-type>java.lang.String</env-entry-type>
<env-entry-value>theValue</env-entry-value>
</env-entry>
You can access the variable inside your EJB using the Environment Naming Context (in EJB 1.1)
Context ctx = new InitialContext();
String val = (String)ctx.lookup("java:comp/env/theParameter");
If my session bean with single method insert record into 2 entity beans, how can know that the process is done in same transaction (the attributes for these beans are Required)?
If your session bean is using bean-managed transactions, you can ensure that the calls are handled in the same transaction by :
javax.transaction.UserTransaction tran= null;
try{
tran=ctx.getUserTransaction();
tran.begin();
myBeanHome1.create(....);
myBeanHome2.create(...);
tran.commit();
}catch(...){}
You may want to check if you're already running in a transaction by calling tran.getStatus().
What does ResultSet actually contain? Is it the actual data of the result or some links to databases? If it is the actual data then why can't we access it after connection is closed? A ResultSet is an interface. Its implementation depends on the driver and hence ,what it "contains" depends partially on the driver and what the query returns.
For example with the Odbc bridge what the underlying implementation layer contains is an ODBC result set. A Type 4 driver executing a stored procedure thatreturns a cursor - on an oracle database it actually returns a cursor in the database. The oracle cursor can however be processed like a ResultSet would be from the client.
Closing a connection closes all interaction with the database and releases any locks that might have been obtained in the process.
How do I insert an image file (or other raw data) into a database? All raw data types (including binary documents or images) should be read and uploaded to the database as an array of bytes, byte[]. Originating from a binary file,
- Read all data from the file using a FileInputStream.
- Create a byte array from the read data.
- Use method setBytes(int index, byte[] data); of java.sql.PreparedStatement to upload the data.
setMaxRows(int) sets the limit of the maximum nuber of rows in a ResultSet object. If this limit is exceeded, the excess rows are "silently dropped". That's all the API says, so the setMaxRowsmethod may not help performance at all other than to decrease memory usage. A value of 0 (default) means no limit.
How can I retrieve only the first n rows, second n rows of a database using a particular WHERE clause ? For example, if a SELECT typically returns a 1000 rows, how do first retrieve the 100 rows, then go back and retrieve the next 100 rows and so on ? Use the Statement.setFetchSize method to indicate the size of each database fetch. Note that this method is only available in the Java 2 platform. For Jdk 1.1.X and Jdk 1.0.X, no standardized way of setting the fetch size exists. Please consult the Db driver manual.
What are different ways in which a thread can enter the waiting state?
A thread can enter the waiting state by the following ways:
1. Invoking its sleep() method,
2. By blocking on I/O
3. By unsuccessfully attempting to acquire an object's lock
4. By invoking an object's wait() method.
5. It can also enter the waiting state by invoking its (deprecated) suspend() method.
What is the difference between yielding and sleeping?
When a task invokes its yield() method, it returns to the ready state, either from waiting, running or after its creation. When a task invokes its sleep() method, it returns to the waiting state from a running state.
What is mutual exclusion? How can you take care of mutual exclusion using Java threads?
Mutual exclusion is a phenomenon where no two processes can access critical regions of memory at the same time. Using Java multithreading we can arrive at mutual exclusion. For mutual exclusion, you can simply use the synchronized keyword and explicitly or implicitly provide an Object, any Object, to synchronize on. The synchronized keyword can be applied to a class, to a method, or to a block of code. There are several methods in Java used for communicating mutually exclusive threads such as wait( ), notify( ), or notifyAll( ). For example, the notifyAll( ) method wakes up all threads that are in the wait list of an object.
How would you implement a thread pool?
public class ThreadPool implements ThreadPoolInt
This class is an generic implementation of a thread pool, which takes the following input
a) Size of the pool to be constructed
b) Name of the class which implements Runnable and constructs a thread pool with active threads that are waiting for activation. Once the threads have finished processing they come back and wait once again in the pool.
This thread pool engine can be locked i.e. if some internal operation is performed on the pool then it is preferable that the thread engine be locked. Locking ensures that no new threads are issued by the engine. However, the currently executing threads are allowed to continue till they come back to the passivePool.
Is there a separate stack for each thread in Java?
Yes. Every thread maintains its own separate stack, called Runtime Stack but they share the same memory. Elements of the stack are the method invocations, called activation records or stack frame. The activation record contains pertinent information about a method like local variables.
How do I extract the SQL statements required to move all tables and views from an existing database to another database?
The operation is performed in 9 steps:
1. Open a connection to the source database. Use the DriverManager class.
2. Find the entire physical layout of the current database. Use the DatabaseMetaData interface.
3. Create DDL SQL statements for re-creating the current database structure. Use the DatabaseMetaData interface.
4. Build a dependency tree, to determine the order in which tables must be setup. Use the DatabaseMetaData interface.
5. Open a connection to the target database. Use the DriverManager class.
6. Execute all DDL SQL statements from (3) in the order given by (4) in the target database to setup the table and view structure. Use the PreparedStatement interface.
7. If (6) threw exceptions, abort the entire process.
8. Loop over all tables in the physical structure to generate DML SQL statements for re-creating the data inside the table. Use the ResultSetMetaData interface.
9. Execute all DML SQL statements from (8) in the target database.
What does ResultSet actually contain? Is it the actual data of the result or some links to databases? If it is the actual data then why can't we access it after connection is closed?
A ResultSet is an interface. Its implementation depends on the driver and hence ,what it "contains" depends partially on the driver and what the query returns.
For example with the Odbc bridge what the underlying implementation layer contains is an ODBC result set. A Type 4 driver executing a stored procedure that returns a cursor - on an oracle database it actually returns a cursor in the databse. The oracle cursor can however be processed like a ResultSet would be from the client. Closing a connection closes all interaction with the database and releases any locks that might have been obtained in the process.
What are the new features added to JDBC 4.0?
- Auto-loading of JDBC driver class
- Connection management enhancements
- Support for RowId SQL type
- DataSet implementation of SQL using Annotations
- SQL exception handling enhancements
- SQL XML support
What’s the difference between TYPE_SCROLL_INSENSITIVE and TYPE_SCROLL_SENSITIVE?
TYPE_SCROLL_INSENSITIVE
TYPE_SCROLL_SENSITIVE
An insensitive resultset is like the snapshot of the data in the database when query was executed.
A sensitive resultset does NOT represent a snapshot of data, rather it contains points to those rows which satisfy the query condition.
After we get the resultset the changes made to data are not visible through the resultset, and hence they are known as insensitive.
After we obtain the resultset if the data is modified then such modifications are visible throughresultset.
Performance not effected with insensitive.
Since a trip is made for every ‘get’ operation, the performance drastically get affected.
Difference between java.sql and javax.sql
java.sql is an API to access and process the data stored in a database, typically a relational database using the java. Different drivers can be installed dynamically for the access of various databases, using a framework which in-built in this JDBC API.
javax.sql is a JDBC API for the server side for accessing and processing the data from the databases typically a relational database using java. It is the essential part for J2EE. This API provides the facilities such as connection pooling, distributed transactions and row sets for the enterprise applications. An interface by name DataSource is provided in this API as an alternative to DriverManager to establish the connection.
DataSource and RowSet usage is direct, for the applications, where as connection pooling, distributed transactions are implemented by an infrastructure called middle-tier.
How do bean-managed transactions work?
When a bean with bean managed transactions is invoked, the container suspends any current transaction in the client’s context. In its method implementation, the bean initiates the transaction through the JTA UserTransaction interface. In stateful beans, the container associates the bean instance with the same transaction context across subsequent method calls until the bean explicitly completes the transaction. However, stateless beans aren’t allowed to maintain transaction context across method calls. Each method invocation must complete any transaction it initiates.
How do enterprise beans handle concurrent and loopback calls on entity beans?
Concurrent calls in the same transaction context on the same Enterprise JavaBean component are illegal and may lead to unpredictable results. A bean can be marked as non-reentrant by its deployment descriptor. This allows the container to detect and prevent illegal concurrent calls from clients. On the other hand, some entity beans may require loopback calls: that is, calls where bean A is invoked, in turn invoking bean B, which then invokes a method call on bean A. This kind of concurrency is tricky and is
best avoided.
TRANSACTION SUPPORT
How does a container manage access from multiple transactions on an entity bean?
Containers manage multiple transactions in one of two ways. First, the container can instantiate multiple instances of the bean and let the transaction management of the DBMS handle transaction processing issues. Or, the container can acquire an exclusive lock on the instance’s state in the database, and serialize access from multiple transactions to this instance.
How do you determine whether two entity beans are the same?
By invoking the EntityBean.isIdentical method. This method should be implemented by the entity bean developer to determine when two references are to the same object. Note that the equals and hashCode methods of Object are undefined for entity beans, since clients don’t directly access bean instances within a container.
How does the client get a reference to an existing entity bean?
- receiving the bean as a parameter in a method call
- looking the bean up through a finder method of the home interface
- obtaining the bean as a handle, a runtime specific identifier generated for a bean automatically by the container
a) SB may or may not be used for TX operational operations,
even they are used for TXs bean developer itself responsible to update the bean values into DB.
b)EBs are specially designed for TX operations
where bean develope is only responsible for updating bean values,
where the bean values were updated into DB by executing one additional funtion called ejbStore().
which beans are TX which are not?
*SB are used for TX & Non Tx operations
*EBs are only used for TX operations.
What is the TX operational difference SessionBean and EntityBean?
a) SB may or may not be used for TX operational operations,even they are used for TXs bean developer itself responsible to update the bean values into DB.
b)EBs are specially designed for TX operations where bean develope is only responsible for updating bean values,where the bean values were updated into DB by executing one addditional funtion called ejbStore().
What is "reentrant"? Why we use this in the deployment descriptor? Explain with an example.
The "reentrant " element dictates whether our bean can call itself through another bean.For exmple, take two beans are there in EJB container named "beanA" and "beanB".There is an element " True " in the ejb-jar.xml , deployment descriptor.If it has been set to True, If beanA calls beanB, in turn it (beanB) calls back beanA. this loop back call is possible.If it has been set to False, the above said case is not possible.This is special case of multi threading because it is only one path of execution that happens to loop back on itself.If we would like to support this " reentrant " behaviour, we should set this setting to True, so thatContainer will allow two threads to run inside of a beanA at once.If we wont that behaviour , we should set it to "False" .with regards,santh
Can you call one constructor from another?
Yes, by using this() syntax. E.g.
public Pet(int id) {
this.id = id; // "this" means this object
}
public Pet (int id, String type) {
this(id); // calls constructor public Pet(int id)
this.type = type; // "this" means this object
}
If an Employee class is present and its objects are added in an arrayList. Now I want the list to be sorted on the basis of the employeeID of Employee class. What are the steps?
· Implement Comparable interface for the Employee class and override the compareTo(Object obj) method in which compare the employeeID
· Now call Collections.sort() method and pass list as an argument.
Now consider that Employee class is a jar file.
· Since Comparable interface cannot be implemented, create Comparator and override the compare(Object obj, Object obj1) method .
· Call Collections.sort() on the list and pass comparator as an argument.
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. Implementation-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 constructor for its uppercase. This process continues until the constructor 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.
How do I find whether a parameter exists in the request object?
boolean hasFoo = !(request.getParameter("foo") == null request.getParameter("foo").equals(""));
or
boolean hasParameter = request.getParameterMap().contains(theParameter); //(which works in Servlet 2.3+)
Source Code
final int limit = 4;
Map A = new Hashtable();
Integer[] B = new Integer[limit];
B[0] = new Integer(8);
B[1] = new Integer(8);
B[2] = new Integer(8);
B[3] = new Integer(8);
A.put("Integers" , B);
System.out.println(B);
A.put("Integers" , B);
Object[] B2 = (Object[])A.get("Integers");
for(int i = 0; i< B2.length ;i++)
System.out.println(B2[i]);
How do wait and notify really work?
You can synchronize one or more method of a class (actually even just a block of code but leave it for now). When you synchronize a method it means you are telling the JVM that a thread needs to acquire the lock of the object before it can call this method. Since an object can have only one lock so if a thread is accessing a synchronized method, then no thread can access any of the synchronised method of that object. Though they can call those methods of the object which are not synchronized.Typically, releasing the lock means the thread holding the lock (the thread currently in the synchronized method) exits the synchronized method. At that point, the lock is free until some other thread enters a synchronized method on that object.
Now to understand wait() and notify() you can refer following example which is easy to understand. Here we have two classes named ThreadA and ThreadB. The main method in class ThreadA is printing the sum of i starting from 0 to 100. But this calculation is being done in the run() method of class ThreadB. So obviously main() method should wait for run() to complete so that it can print the total. Here comes the use of wait() method. And now you can understand why wait and notify should by called in synchronized context. When the thread waits it temporarily releases the lock for other threads to use but it will need it again to continue its execution. So once the thread which is waiting is notified (by notified method) it then starts comepting to acquire lock so that it can complete the remaining part of the method.
1. class ThreadA {
2. public static void main(String [] args) {
3. ThreadB b = new ThreadB();
4. b.start();
5.
6. synchronized(b) {
7. try {
8. System.out.println("Waiting for b to complete...");
9. b.wait();
10. } catch (InterruptedException e) {}
11. }
12. System.out.println("Total is: " + b.total);
13. }
14. }
15.
16. class ThreadB extends Thread {
17. int total;
18.
19. public void run() {
20. synchronized(this) {
21. for(int i=0;i<100;i++) {
22. total += i;
23. }
24. notify();
25. }
26. }
27. }
How do I submit a form or a part of a form without a page refresh?
When creating a form make sure that the "form" element "onSubmit" attribute is set to a JavaScript function that returns false.
<form onSubmit="doAJAXSubmit();return false;" >
<input id="tf1" />
<input id="submit1" value="Update"/>
</>
You can also submit data by associating a function with a form button in a similar way.
<form onSubmit="doAJAXSubmit();return false;" >
<input id="tf1" />
<input id="button1" onClick="doAJAXSubmit()" value="Update"/>
</>
Note that the form "onSubmit" attribute is still set. If the user hits the enter key in the text field the form will be submitted so you still need to handle that case.
When updating the page it is recommend you wait to make sure that the AJAX update of the form data was successful before updating the data in the page. Otherwise, the data may not properly update and the user may not know. I like to provide an informative message when doing a partial update and upon a successful AJAX interaction I will then update the page.
Give an example of overriding the equals method.
It is not always necessary to override hashcode and equals. But if you think you need to override one, then you need to override both of them. Let's analyze what whould happen if we override one but not the other and we attempt to use a Map.
Say we have a class like this and that two objects of MyClass are equal if their importantField is equal (with hashCode and equals generated by eclipse)
public class MyClass {
private final String importantField;
private final String anotherField;
public MyClass(final String equalField, final String anotherField) {
this.importantField = equalField;
this.anotherField = anotherField;
}
public String getEqualField() {
return importantField;
}
public String getAnotherField() {
return anotherField;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((importantField == null) ? 0 : importantField.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final MyClass other = (MyClass) obj;
if (importantField == null) {
if (other.importantField != null)
return false;
} else if (!importantField.equals(other.importantField))
return false;
return true;
}
}
Override only hashCode
Imagine you have this
MyClass first = new MyClass("a","first");
MyClass second = new MyClass("a","second");
If you only override hashCode then when you call myMap.put(first,someValue) it takes first, calculates its hashCode and stores it in a given bucket. Then when you callmyMap.put(first,someOtherValue) it should replace first with second as per the Map Documentation because they are equal (according to our definition).
But the problem is that equals was not redefined, so when the map hashes second and iterates through the bucket looking if there is an object k such that second.equals(k) is true it won't find any as second.equals(first) will be false.
Override only equals
If only equals is overriden, then when you call myMap.put(first,someValue) first will hash to some bucket and when you call myMap.put(first,someOtherValue) it will hash to some other bucket. So, although they are equal, as they don't hash to the same bucket (different hashCode) the map can't realize it and both of them stay in the map.
Can I use JavaScript to submit a form?
You can submit a form with a link as below. BTW, the examples below assume you are in an block and 'myForm' is picked up from the struts-config.xml name field of the action.
<a href='javascript:void(document.forms["myForm"].submit()>My Link</a>
Now the trick in the action is to decode what action you intend to perform. Since you are using JavaScript, you could set a field value and look for it in the request or in the form.
... html/javascript part ...
<input 'hidden' value='myAction' />
<input 'button' value='Save Meeeee'
onclick='document.forms["myForm"].myAction.value="save";
document.forms["myForm"].submit();' />
<input 'button' value='Delete Meeeee'
onclick='document.forms["myForm"].myAction.value="delete";
document.forms["myForm"].submit();' />
... the java part ...
class MyAction extends ActionForm implements Serializable {
public ActionForward execute (ActionMapping map, ActionForm form,
HttpServletRequest req, HttpServletResponse) {
String myAction = req.getParameter("myAction");
if (myAction.equals("save") {
// ... save action ...
} else if (myAction.equals("delete") {
// ... delete action ...
}
}
}
}
This is just one of many ways to achieve submitting a form and decoding the intended action. Once you get used to the framework you will find other ways that make more sense for your coding style and requirements. Just remember this example is completely non-functional without JavaScript.