Ph: 239255255255
Enterprise Technology Tips & Solution
Built on J2EE and SOA using opensource
Showing posts with label J2EE. Show all posts
Showing posts with label J2EE. Show all posts

Java J2EE Interview Questions - 8

Posted In: Interview , J2EE , Java , Questions , Tips
By Vishal Sharma

Continuing our Java/J2EE/JEE interview questions and answers series, today's questions are on Networking:

Q What is UDP and how does it work?
A. UDP stands for User Datagram Protocol. UDP provides an unreliable packet delivery system built on top of the IP protocol. As with IP, each packet is an individual, and is handled separately. Because of this, the amount of data that can be sent in a UDP packet is limited to the amount that can be contained in a single IP packet. Thus, a UDP packet can contain at most 65507 bytes (this is the 65535-byte IP packet size minus the minimum IP header of 20 bytes and minus the 8-byte UDP header).java, j2ee enterprise interview tips solutions
UDP packets can arrive out of order or not at all. No packet has any knowledge of the preceding or following packet. The recipient does not acknowledge packets, so the sender does not know that the transmission was successful. UDP has no provisions for flow control--packets can be received faster than they can be used. We call this type of communication connectionless because the packets have no relationship to each other and because there is no state maintained.
The destination IP address and port number are encapsulated in each UDP packet. These two numbers together uniquely identify the recipient and are used by the underlying operating system to deliver the packet to a specific process (application). Each UDP packet also contains the sender's IP address and port number.
One way to think of UDP is by analogy to communications via a letter. You write the letter (this is the data you are sending); put the letter inside an envelope (the UDP packet); address the envelope (using an IP address and a port number); put your return address on the envelope (your local IP address and port number); and then you send the letter.
Like a real letter, you have no way of knowing whether a UDP packet was received. If you send a second letter one day after the first, the second one may be received before the first. Or, the second one may never be received.java, j2ee enterprise interview tips soltions networking
Q What is a Datagram?
A Datagram is another name for a UDP packet.
Java provides two classes for explicitly dealing with datagrams, DatagramSocket and DatagramPacket. These are both found in the java.net package.

Q Why use UDP if it is unreliable?
A. Two main reasons: speed and overhead.

UDP packets have almost no overhead--you simply send them then forget about them. And they are fast, because there is no acknowledgment required for each packet. Keep in mind that unreliable doesn't mean that packets can be lost or misdirected for no reason - it simply means that UDP provides no built-in checking and correction mechanism to gracefully deal with losses caused by network congestion or failure.
UDP is appropriate for the many network services that do not require guaranteed delivery. An example of this is a network time service. Consider a time daemon that issues a UDP packet every second so computers on the LAN can synchronize their clocks. If a packet is lost, it's no big deal--the next one will be by in another second and will contain all necessary information to accomplish the task.
Another common use of UDP is in networked, multi-user games, where a player's position is sent periodically. Again, if one position update is lost, the next one will contain all the required information.
A broad class of applications is built on top of UDP using streaming protocols. With streaming protocols, receiving data in real-time is far more important than guaranteeing delivery. Examples of real-time streaming protocols are real audio and real video which respectively deliver real-time streaming audio and video over the Internet. The reason a streaming protocol is desired in these cases is because if an audio or video packet is lost, it is much better for the client to see this as noise or "drop-out" in the sound or picture rather than having a long pause while the client software stops the playback, requests the missing data from the server. That would result in a very choppy, bursty playback which most people find unacceptable, and which would place a heavy demand on the server.


Q. What is Multicast and how does it work?
A. TCP and UDP are both unicast protocols; there is one sender and one receiver. Multicast packets are a special type of UDP packets. But while UDP packets have only one destination and only one receiver, multicast packets can have an arbitrary number of receivers.
Multicast is quite distinct from broadcast; with broadcast packets, every host on the network receives the packet. With multicast, only those hosts that have registered an interest in receiving the packet get it.
This is similar to the way an AWTEvent and its listeners behave in the Abstract Window Toolkit. In the same way that an AWTEvent is sent only to registered listeners, a multicast packet is sent only to members of the multicast group. AWT events, however, are unicast, and must be sent individually to each listener--if there are two listeners, two events are sent. With a MulticastSocket, only one is sent and it is received by many.

When an application subscribes to a multicast group (host/port), it receives datagrams sent by other hosts to that group, as do all other members of the group. Multiple applications may subscribe to a multicast group and port concurrently, and they will all receive group datagrams.
When an application sends a message to a multicast group, all subscribing recipients to that host and port receive the message (within the time-to-live range of the packet, see below). The application needn't be a member of the multicast group to send messages to it.

Q What are RFCs and where can I find them?
A RFC stands for "Request for Comment". The RFCs form an integral part of the Internet standards; standards are formed by first publishing a specification as an RFC.

Q What is TCP and how does it work?
A Internet Protocol, or IP, provides an unreliable packet delivery system--each packet is an individual, and is handled separately. Packets can arrive out of order or not at all. The recipient does not acknowledge them, so the sender does not know that the transmission was successful. There are no provisions for flow control--packets can be received faster than they can be used. And packet size is limited.
Transmission Control Protocol (TCP) is a network protocol designed to address these problems. TCP uses IP, but adds a layer of control on top. TCP packets are lost occasionally, just like IP packets. The difference is that the TCP protocol takes care of requesting retransmits to ensure that all packets reach their destination, and tracks packet sequence numbers to be sure that they are delivered in the correct order. While IP packets are independent, with TCP we can use streams along with the standard Java file I/O mechanism.
Think of TCP as establishing a connection between the two endpoints. Negotiation is performed to establish a "socket", and the socket remains open throughout the duration of the communications. The recipient acknowledges each packet, and packet retransmissions are performed by the protocol if packets are missed or arrive out of order. In this way TCP can allow an application to send as much data as it desires and not be subject to the IP packet size limit. TCP is responsible for breaking the data into packets, buffering the data, resending lost or out of order packets, acknowledging receipt, and controlling rate of data flow by telling the sender to speed up or slow down so that the application never receives more than it can handle.
There are four distinct elements that make a TCP connection unique:
As you might guess, MulticastSocket is a subclass of DatagramSocket which has the extended ability to join and leave multicast groups. A multicast group consists of both a multicast address and a port number. The only difference between UDP and multicast in this respect is that multicast groups are represented by special internet addresses in the range 224.0.0.1 to 239.255.255.255, inclusive. Just as there are well-known ports for network services, there are reserved, well-known multicast groups for multicast network services.

IP address of the server IP address of the client Port number of the server Port number of the client
Each requested client socket is assigned a unique port number while the server port number is always the same. If any of these numbers is different, the socket is different. A server can thus listen to one and only one port, and talk to multiple clients at the same time.
So a TCP connection is somewhat like a telephone connection; you need to know not only the phone number (IP address), but because the phone may be shared by many people at that location, you also need the name or extension of the user you want to talk to at the other end (port number). The analogy can be taken a little further. If you don't hear what the other person has said, a simple request ("What?") will prompt the other end to resend or repeat the phrase, and the connection remains open until someone hangs up.

Q. What's a MalformedURLException?
A. When you try to create a new URL by calling its constructor, it will throw a MalformedURLException if the URL string is not parseable or contains an unsupported protocol.

Q. How can I get the real local host IP address in an applet?
Applet security restrictions do not let you get this in an untrusted applet via InetAddress.getLocalHost().
However, you can get this address by creating a Socket connection back to the web server from which you came and asking the Socket for the local address:

URL url = getDocumentBase();
String host = url.getHost();
Socket socket = new Socket(host, 80);
InetAddress addr = socket.getLocalAddress();
String hostAddr = addr.getHostAddress();
System.out.println("Addr: " + hostAddr);


Q. What is the difference between a URI and a URL?
A. URLs are a subset of all URIs.
The term "Uniform Resource Locator" (URL) refers to the subset of URI that identify resources via a representation of their primary access mechanism (e.g., their network "location"), rather than identifying the resource by name or by some other attribute(s) of that resource.

Previous Java, J2EE, JEE Interview Questions can be read here.
Other useful tips on Java, JEE/J2EE
Continue Reading...

Enterprise Technology Tips Speedlinking

Posted In: J2EE , Java , Link
By Vishal Sharma

Background:
In today's enterprise applications their is a big requirement for dynamic generation of PDF documents. These applications range from telecom companies generating phone bills, airlines producing e-tickets, banks generating customer statements for e-mail delivery to readers, book sellers selling books in pdf format.

What is PDF:
The Portable Document Format (PDF) is the file format created by Adobe Systems in 1993 for document exchange. PDF is used for representing two-dimensional documents in a device-independent and display resolution-independent fixed-layout document format. Each PDF file encapsulates a complete description of a 2-D document (and, with Acrobat 3-D, embedded 3-D documents) that includes the text, fonts, images, and 2-D vector graphics that compose the document.

Why PDF:
PDF is an open standard, unlike Microsoft Word, supported by all operating systems, ie; as long as you have an adobe reader you can read a pdf file on any system like Linux, Mac, Solaris, Windows. On virus front, it’s very hard that a PDF file will have some virus. It is is now being prepared for submission as an ISO standard.


Dynamic PDF Generation in Enterprise Application Development :
As mentioned above, in digital age everything is digitized so that end user can access it from anywhere, anytime. As a result new enterprise applications are generating lot of data in pdf formant which can be used by end user.
In Enterprise (Java or J2EE, JEE) application development generating pdf documents on the fly (dynamically) has become a trivial thing, courtesy of lot of third party tools, APIs available. The list of these tools/API's is endless. In this article, we will use the iText Java library to generate PDF documents by merging GIF files. I'll go through an example to show how this is done.

iText :
iText is an open-source Java library that provides API to generate PDF files on the fly. It also supports the generation of HTML, RTF, and XML documents, in addition to generating PDFs. It's available for free under a multiple license: MPL and LGPL.

iText API :

The com.lowagie.text.Document is the main class for PDF document generation. This is the first class to be instantiated. Once the document is created, we would require a writer to write into it. The com.lowagie.text.pdf.PdfWriter is a PDF writer. Other classes which are often used:

com.lowagie.text.Paragraph - represents an indented paragraph. com.lowagie.text.Chapter - represents a chapter in the PDF document. It is created using a Paragraph as title and an int as chapter number. com.lowagie.text.Font - contains all specifications of a font, such as family of font, size, style, and color. Various fonts are declared as static constants in this class. com.lowagie.text.List - represents a list, which, in turn, contains a number of ListItems. com.lowagie.text.Table - represents a table that contains cells, ordered in a matrix.

Example of converting multiple GIF files into PDF :


Pre-requisites :
Download iText and include itext-version.jar into your application or yr classpath.

Code Snippet :
The following code snippet demonstrates how to convert an array (collection) of gif files into a single pdf,
{code}

FileOutputStream fos = null;

try {

fos = new FileOutputStream (
new File(pDestinationFolder + File.separator
+ pTargetFileNamePrefix + ".pdf")
);

// Create a document which is the container for all the elements of a PDF document.
Document doc = new Document();

// Line -1
PdfWriter writer = PdfWriter.getInstance(doc, fos);

doc.open();

for (File aFile : gifFiles) {

Image image = Image.getInstance(aFile.getAbsolutePath());

// Line -2
image.scaleToFit(doc.getPageSize().getWidth(), doc.getPageSize().getHeight());

// Line -3
image.setAlignment(Image.ALIGN_CENTER);
doc.add(image);
doc.newPage();
}

doc.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
finally {

if (fos != null) {
try {
fos.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}

{code}

Code Demystified :
Line - 1 is important to create an instance of PdfWriter that associates a document object with the output stream. For our code snippet, we choose com.lowagie.text.pdf.PdfWriter. Other writers are HtmlWriter, RtfWriter, XmlWriter, and several others for obvious reasons. Line - 2 is very useful methods that will scale the current image to fit the width and height specified. Gif images can vary in sizes and this allows the method to scale down to the default size of the PDF page. Line-3 is to align the image so that it is located at the center of the page.

Other opensource libraries for generating pdf documents are :
FOP Gnujpdf JFreeReport JPedal jPod PDF Box PDFjet PJX
Continue Reading...

Java J2EE Interview Questions - 7

Posted In: Interview , J2EE , Java , Questions , Tips
By Vishal Sharma

Continuing our Java/J2EE/JEE interview questions and answers series, today's questions are:

Q Describe the principles of OOPS.
A There are three main principals of oops which are called Polymorphism, Inheritance and Encapsulation.

Q Explain the Encapsulation principle.
A Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a single entity. This keeps the data safe from outside interface and misuse. One way to think about encapsulation is as a protective wrapper that prevents code and data from being arbitrarily accessed by other code defined outside the wrapper.

Q Explain the Inheritance principle.
A Inheritance is the process by which one object acquires the properties of another object.

Q Explain the Polymorphism principle.
A The meaning of Polymorphism is something like one name many forms. Polymorphism enables one entity to be used as general category for different types of actions. The specific action is determined by the exact nature of the situation. The concept of polymorphism can be explained as "one interface, multiple methods".

Q Explain the different forms of Polymorphism.
Answer: From a practical programming viewpoint, polymorphism exists in three distinct forms in Java:
Method overloading
Method overriding through inheritance
Method overriding through the Java interface

Q What are Access Specifiers available in Java?
A Access specifiers are keywords that determines the type of access to the member of a class. These are:
Public
Protected
Private
Defaults

Q Describe the wrapper classes in Java.
A Wrapper class is wrapper around a primitive data type. An instance of a wrapper class contains, or wraps, a primitive value of the corresponding type.

Q What's the difference between J2SDK 1.5 and J2SDK 5.0?
A There's no difference, Sun Microsystems just re-branded this version.

Q What would you use to compare two String variables - the operator == or the method equals()?
A I'd use the method equals() to compare the values of the Strings and the == to check if two variables point at the same instance of a String object.

Q Does it matter in what order catch statements for FileNotFoundException and IOExceptipon are written?
A Yes, it does. The FileNoFoundException is inherited from the IOException. Exception's subclasses have to be caught first.

Q Can an inner class declared inside of a method access local variables of this method?
A It's possible if these variables are final.

Q What can go wrong if you replace && with & in the following code:
String a=null; if (a!=null && a.length()>10) {...}
A A single ampersand here would lead to a NullPointerException.

Q What's the main difference between a Vector and an ArrayList
A Java Vector class is internally synchronized and ArrayList is not.

Q When should the method invokeLater()be used?
A This method is used to ensure that Swing components are updated through the event-dispatching thread.

Q How can a subclass call a method or a constructor defined in a superclass?
A Use the following syntax: super.myMethod(); To call a constructor of the superclass, just write super(); in the first line of the subclass's constructor.

Q You can create an abstract class that contains only abstract methods. On the other hand, you can create an interface that declares the same methods. So can you use abstract classes instead of interfaces?
A Sometimes. But your class may be a descendent of another class and in this case the interface is your only option.

Q What comes to mind when you hear about a young generation in Java?
A Garbage collection.

Q What comes to mind when someone mentions a shallow copy in Java?
A Object cloning.

Q If you're overriding the method equals() of an object, which other method you might also consider?
A hashCode()

Q You are planning to do an indexed search in a list of objects. Which of the two Java collections should you use:
ArrayList or LinkedList?
A ArrayList

Q How would you make a copy of an entire Java object with its state?
A Have this class implement Cloneable interface and call its method clone().

Q How can you minimize the need of garbage collection and make the memory use more effective?
A Use object pooling and weak object references.

Previous Java, J2EE, JEE Interview Questions can be read here.

Other useful tips on Java, JEE/J2EE
Continue Reading...

Continuing in series of What is Service Oriented Architecture or SOA

Effective Planning :
As organizations begin to plan for their SOA journey, they must strike a balance between the technical and non-technical elements. SOA requires the IT organizations and the business to operate in new and ever changing manners. A framework is needed that addresses each of the above practices. The Service-Oriented Architecture Framework (SOAF) is comprised of jurisdictions, each with equal focus, which speak to the practices. The jurisdictions are interrelated and interdependent. The success of an enterprise SOA journey is dependent upon applying equal focus to each of the jurisdictions of concern.

Business Approach Business Value Architecture SOA Legos Projects Relationships and Outcome Management

The explosion of these stream will begin by addressing three of these jurisdictions specifically business approach, business value, and architecture.

One of the goals of SOA is to provide better alignment between business processes and the IT functions that delivery those processes. This mapping enables process, and ultimately enterprise, improvement long term. In order to perform this mapping one must 1) Examine current enterprise processes and identify the required support functionality, 2) Cultivate functionality from existing systems and assets, give birth to new functionality where required, and guarantee that all services provide clear service-level agreements (SLAs) and 3) Exploit the enterprise services by orchestrating services into processes, measure the alignment to the enterprise strategy, and recognize maturity opportunities.

Business Value :
Providing the business case for an SOA journey is unlike defending traditional software projects. This is due to the realization of SOA benefits on an enterprise-wide scale. SOA provides opportunities for increased value that are excessively higher than those of traditional software efforts. This is accomplished through the optimization of business processes utilizing shared services. Innovation through SOA is a key differentiator in building a business case.
It is important to prioritize the development of services so that the SOA exhibits ROI from the start. The “on-ramping” cost can largely be immersed into existing budgets. The business case must account for these initial “on-ramping” costs yield benefits that accumulate and accelerate in the long term.
Initial SOA investment impact can be reduced by methodically selecting the appropriate capabilities to spearhead the SOA journey. Reuse of assets and capabilities will ensure lower on-ramp cost for new application. The IT funding model will change over time due to increased ROI. Traditional IT investment continues to increase as over time and as the number of capabilities increases, which is drastically different from the funding mode l for an SOA delivery mechanism. As the level of SOA adoption penetrates the enterprise and the level of reuse increase the investment level will begin to stabilize and increased at a predictable rate.
Architecture
Enterprises typically providing funding for and construct IT based upon each line of business. A Reference Architecture (RA) is essential for an enterprise SOA. This is a long term vision of evolution, two to three years, for the enterprise. An enterprise should spend time and effort in defining architectural guiding principles and policies. The guidelines must NOT be an endpoint unto themselves.
The RA must be service-centric, standards based and enterprise focused. Traditionally IT is obtained or developed as a response to the requirements of a particular domain within the enterprise and deployed for utilization by that domain. Shared capability approaches stemming from code or component reuse have failed due to the project-by-project focus of development efforts. Many times functionality is replicated through project-by-project development approaches due to the fact that each project addresses a specific set of requirements. A service-centric approach to delivery IT requires a shift in the development and deployment mindset. Capabilities are designed, developed, and delivered once for reuse at all levels within the enterprise. This leads to the SOA promises of reduced cost, fast time-to-market, and agility in order to respond to changing requirements.
and share information. There have been previous attempts to provide standards-based component models, for example Common Object Request Broker Architecture (IT projects are typically delivered through the most expedient approach that will satisfy stakeholder requirements. This often leads to the proliferation of technologies throughout the enterprise. This leads to serious integration issues when the technologies have to interoperateCORBA) and Distributed Component Object Model (DCOM). These types of models experienced failure due to the implementation technology required and supporting standards stalling in development. XML (Extensible Markup Language), Web Services, and UDDI (Universal Description, Discovery and Integration) are the foundation for a standards-based SOA for supporting re-use. The technology for supporting this approach is readily available and truly platform agnostic.
As mentioned earlier traditionally IT has been delivered on a project-by-project basis within the individual lines of business of an enterprise, the response of many enterprises to this approach has been to institute enterprise architecture organizations. These organizations were focused on technology selection for the enterprise and were not authorized to enforce other recommendations. An enterprise SOA requires that organizations of this type be provided with the authority required for full lifecycle management of the SOA, a standards-based mechanism for defining, deploying, monitoring, and managing functionality at the appropriate granularity and visibility levels. The required provisioning ecosystem must be constructed from service-centric enterprise architecture (EA) which contains the appropriately enforced governance principles and policies.

Tomorrow : Requirements for a SOA Strategy

Other useful tips on Java, JEE/J2EE
Continue Reading...

Continuing our Java/J2EE/JEE interview questions and answers series, today's questions are:

Q How do you call a Stored Procedure from JDBC?

The first step is to create a CallableStatement object. As with Statement and PreparedStatement objects, this is done with an open Connection object. A CallableStatement object contains a call to a stored procedure.



CallableStatement cs =
con.prepareCall("{call SHOW_SUPPLIERS}");
ResultSet rs = cs.executeQuery();


Q Is the JDBC-ODBC Bridge multi-threaded? –

No. The JDBC-ODBC Bridge does not support concurrent access from different threads. The JDBC-ODBC Bridge uses synchronized methods to serialize all of the calls that it makes to ODBC. Multi-threaded Java programs may use the Bridge, but they won’t get the advantages of multi-threading.

Q Does the JDBC-ODBC Bridge support multiple concurrent open statements per connection?

No. You can open only one Statement object per connection when you are using the JDBC-ODBC Bridge.

Q. What is cold backup, hot backup, warm backup recovery?

Cold backup - means all the files must be backed up at the same time, before the database is restarted.
Hot backup called online backup and is a backup taken of each tablespace while the database is running and is being accessed by the users.

When we will Denormalize data?

Data denormalization is reverse procedure, carried out purely for reasons of improving performance. It maybe efficient for a high-throughput system to replicate data for certain data.

Q. What is the advantage of using PreparedStatement?

If we are using PreparedStatement the execution time will be less. The PreparedStatement object contains not just an SQL statement, but the SQL statement that has been precompiled. This means that when the PreparedStatement is executed,the RDBMS can just run the PreparedStatement’s Sql statement without having to compile it first.

Q What is a dirty read?

Quite often in database processing, we come across the situation wherein one transaction can change a value, and a second transaction can read this value before the original change has been committed or rolled back. This is known as a dirty read scenario because there is always the possibility that the first transaction may rollback the change, resulting in the second transaction having read an invalid value. While you can easily command a database to disallow dirty reads, this usually degrades the performance of your application due to the increased locking overhead. Disallowing dirty reads also leads to decreased system concurrency.

Q. What is Metadata and why should I use it?

Metadata is data about data. This data is information about one of two things:
Database information (java.sql.DatabaseMetaData), or Information about a specific ResultSet (java.sql.ResultSetMetaData). Use DatabaseMetaData to find information about your database, such as its capabilities and structure. Use ResultSetMetaData to find information about the results of an SQL query, such as size and types of columns

Q. Different types of Transaction Isolation Levels?

The isolation level describes the degree to which the data being updated is visible to other transactions. This is important when two transactions are trying to read the same row of a table. Imagine two transactions: A and B. Here three types of inconsistencies can occur:
Dirty-read: A has changed a row, but has not committed the changes. B reads the uncommitted data but his view of the data may be wrong if A rolls back his changes and updates his own changes to the database.
Non-repeatable read: B performs a read, but A modifies or deletes that data later. If B reads the same row again, he will get different data.
Phantoms: A does a query on a set of rows to perform an operation. B modifies the table such that a query of A would have given a different result. The table may be inconsistent.

TRANSACTION_READ_UNCOMMITTED : DIRTY READS, NON-REPEATABLE READ AND PHANTOMS CAN OCCUR.
TRANSACTION_READ_COMMITTED : DIRTY READS ARE PREVENTED, NON-REPEATABLE READ AND PHANTOMS CAN OCCUR.
TRANSACTION_REPEATABLE_READ : DIRTY READS , NON-REPEATABLE READ ARE PREVENTED AND PHANTOMS CAN OCCUR.
TRANSACTION_SERIALIZABLE : DIRTY READS, NON-REPEATABLE READ AND PHANTOMS ARE PREVENTED.

Q. What is two phase commit?

Two phase commit is an algorithm used to ensure the integrity of a committing transaction. In Phase 1, the transaction coordinator contacts potential participants in the transaction. The participants all agree to make the results of the transaction permanent but do not do so immediately. The participants log information to disk to ensure they can complete In phase 2 f all the participants agree to commit, the coordinator logs that agreement and the outcome is decided. The recording of this agreement in the log ends in Phase 2, the coordinator informs each participant of the decision, and they permanently update their resources.

q. How do you handle your own transaction ?

Connection Object has a method called setAutocommit(Boolean istrue) Default is true. Set the Parameter to false and begin your transaction

Q. What is the normal procedure followed by a java client to access the database?

The database connection is created in 3 steps:

Find a proper database URL
Load the database driver
Ask the Java DriverManager class to open a connection to your database
In java these steps are carried out as shown below:

Create a properly formatted JDBR URL for your database.

A JDBC URL has the form
jdbc:someSubProtocol://myDatabaseServer/theDatabaseName

Class.forName(”my.database.driver”);

Connection conn = DriverManager.getConnection(”a.JDBC.URL”, “databaseLogin”,”databasePassword”);

Q. What is a data source?

A DataSource class brings another level of abstraction than directly using a connection object. Data source can be referenced by JNDI. Data Source may point to RDBMS, file System or others.

Q. What are collection pools?

A connection pool is a cache of database connections that is maintained in memory, so that the connections may be reused

Previous Java, J2EE, JEE Interview Questions can be read here.
Other useful tips on Java, JEE/J2EE
Continue Reading...

Security is always a challenging exercise in enterprise applications. Securing Java or J2EE/JEE based applications can be done in various ways. As far as web applications are concerned there are four known authentication mechanisms.

HTTP Basic Authentication :
An authentication protocol defined within the HTTP protocol (and based on headers). It indicates the HTTP realm for which access is being negotiated and sends passwords with base64 encoding, which cab cracked easily, hence not very secure. For further details refer RFC2068.
HTTP Digest Authentication :
Like HTTP Basic Authentication, but with the password transmitted in an encrypted form. It is more secure than Basic, but less then HTTPS Authentication which uses private keys. Yet it is not currently in widespread use.

Seurity, Secure, Authentication, J2EE, Development, HTTP

HTTPS Authentication :
It also known as SSL Mutual authentication. This security mechanism provides end user authentication using HTTPS (HTTP over SSL - Secure Socket Layer). It performs mutual (which means - client and server) certificate based authentication with a set of different cipher suites.

Form Based Authentication or Login : A standard HTML form (generated via Servlet/JSP, script or a static) for logging in. It can be associated with protection or user domains and is used to authenticate previously unauthenticated users. The major advantage of form based authentication is, that the look and feel of the login screen can be controlled in comparison to the HTTP browser's built in mechanisms.

According to J2EE Specifications, Basic, HTTPS and Form based are mandatory requirement for any J2EE compliant application server (web container here). HTTP Digest Authentication is not a requirement, but web containers are encouraged to support it.

Example: Tomcat web container - is the reference implementation of the Java Servlet API and provides these discussed methods.

NB : Image sourced from Sun J2EE Tutorial - Security

Other useful tips on Java, JEE/J2EE

Continue Reading...

J2EE Interview Questions - 5

Posted In: EJB , Interview , J2EE , Java , Jboss , JMS , Questions
By Vishal Sharma

Continuing our Java/J2EE/JEE interview questions and answers series, today's questions are:

Q. Why an onMessage call in Message-driven bean is always a seperate transaction?
A. EJB 2.0 specification says: "An onMessage call is always a separate transaction, because there is never a transaction in progress when the method is called." When a message arrives, it is passed to the Message Driven Bean through the onMessage() method, that is where the business logic goes.Since there is no guarantee when the method is called and when the message will be processed, is the container that is responsible of managing the environment, including transactions.

Q. Why are ejbActivate() and ejbPassivate() included for stateless session bean even though they are never required as it is a non conversational bean?
A. To have a consistent interface, so that there is no different interface that you need to implement for Stateful Session Bean and Stateless Session Bean.Both Stateless and Stateful Session Bean implement javax.ejb.SessionBean and this would not be possible if stateless session bean is to remove ejbActivate and ejbPassivate from the interface.
Static variables in EJB should not be relied upon as they may break in clusters.Why?
Static variables are only ok if they are final. If they are not final, they will break the cluster. What that means is that if you cluster your application server (spread it across several machines) each part of the cluster will run in its own JVM.
Say a method on the EJB is invoked on cluster 1 (we will have two clusters - 1 and 2) that causes value of the static variable to be increased to 101. On the subsequent call to the same EJB from the same client, a cluster 2 may be invoked to handle the request. A value of the static variable in cluster 2 is still 100 because it was not increased yet and therefore your application ceases to be consistent. Therefore, static non-final variables are strongly discouraged in EJBs.

Q. If I throw a custom ApplicationException from a business method in Entity bean which is participating in a transaction, would the transaction be rolled back by container?
A. EJB Transaction is automatically rolled back only when a SystemException (or a subtype of it) is thrown. Your ApplicationExceptions can extend from javax.ejb.EJBException, which is a sub class of RuntimeException. When a EJBException is encountered the container rolls back the transaction. EJB Specification does not mention anything about Application exceptions being sub-classes of EJBException.You can tell the container to rollback the transaction, by using setRollBackOnly on SessionContext/EJBContext object as per type of bean you are using.

Q. Does Stateful Session bean support instance pooling?
A. Stateful Session Bean conceptually doesn't have instance pooling.

Q. Can I map more than one table in a CMP?
A. No, you cannot map more than one table to a single CMP Entity Bean. CMP has been, in fact, designed to map a single table.

Q. Can a Session Bean be defined without ejbCreate() method?
A. The ejbCreate() methods is part of the bean's lifecycle, so, the compiler will not return an error because there is no ejbCreate() method. However, the J2EE spec is explicit, the home interface of a Stateless Session Bean must have a single create() method with no arguments, while the session bean class must contain exactly one ejbCreate() method, also without arguments. Stateful Session Beans can have arguments (more than one create method)

Previous Java, J2EE, JEE Interview Questions can be read here.

Continue Reading...

Background:
In computer science, a cache is a collection of data duplicating original values stored elsewhere or computed earlier, where the original data is expensive to fetch (due to slow access time) or to compute, relative to the cost of reading the cache. In other words, a cache is a temporary storage area where frequently accessed data can be stored for rapid access. Once the data is stored in the cache, future use can be made by accessing the cached copy rather than re-fetching or recomputing the original data, so that the average access time is lower. Cache, therefore, helps expedites data access otherwise the CPU would need to fetch from main memory. Cache have proven to be extremely effective in many areas of computing because access patterns in typical computer applications have locality of reference.

Purpose :
The main purpose of the caching service is to improve server performance by managing static and non static data members. The performance gain is from reducing the number of trips to the database or other external sources of information, avoiding the cost of repeatedly recreating data (objects in java), sharing data between threads in a process and, when possible between processes, and efficient use of process resources.

Advantages:

In a multi-tiered (n-tier) application, data access is an expensive operation, compared to any other task. By keeping the frequently accessed data around and not releasing it after the first use, we can avoid the cost and time required for the reacquisition and release of the data. This results in greatly improved performance, since we won't be hitting the database every time we need the data. Scalability is another reason of using. Since cached data is accessed across multiple tiers, sessions, components, caching can become a big part of a scalable application design.

Disadvantages:
Synchronization complexity: Depending on the kind of data, complexity increases, because consistency between the state of the cached data and the original data in the data source needs to be ensured. Otherwise, the cached data can get out of sync with the actual data, which will lead to data inaccuracies. Durability: Changes to the cached data can be lost when the server crashes. This problem can be avoided if a synchronized cache is used. Memory size: JVM memory size can get unacceptably huge if there is lot of unused data in the cache and the data is not released from memory at regular intervals.

Opensource Caching solutions in Java:
There are lots of caching solution in Java, free and non free. This is a list of opensource caching solutions available in Java/J2EE/JEE domain for software development or developing enterprise applications.
Java, Cache, Hibernate, Jboss, J2EE, Software, Caching, opensource
Bamboo DHT - is a distributed hash table, or DHT, is a building block for peer-to-peer applications. At the most basic level, it allows a group of distributed hosts to collectively manage a mapping from keys to data values, without any fixed hierarchy, and with very little human assistance. This building block can then be used to ease the implementation of a diverse variety of peer-to-peer applications such as file sharing services, DNS replacements, web caches, etc.

cache4j - is a cache for Java objects with a simple API and fast implementation. It features in-memory caching, a design for a multi-threaded environment, both synchronized and blocking implementations, a choice of eviction algorithms (LFU, LRU, FIFO), and the choice of either hard or soft references for object storage.

FreePastry - is a modular, open source implementation of the Pastry p2p routing and location substrate. Pastry is a generic, scalable and efficient substrate for peer-to-peer applications. Pastry nodes form a decentralized, self-organizing and fault-tolerant overlay network within the Internet. Pastry provides efficient request routing, deterministic object location, and load balancing in an application-independent manner. Furthermore, Pastry provides mechanisms that support and facilitate application-specific object replication, caching, and fault recovery. The proponents of Pastry work for Microsoft, however they've made an excellent choice sticking with Java.

EHCache - is a pure Java, in-process cache. It started as a replacement for JCS. EHCache is faster than JCS. It has following features: Fast,Simple, pluggable cache for Hibernate, small foot print, minimal dependencies, fully documented and production tested.

Java Caching System (JCS) - is a distributed caching system written in java for server-side java applications. It is intended to speed up dynamic web applications by providing a means to manage cached data of various dynamic natures. Like any caching system, the JCS is most useful for high read, low put applications. Dynamic content and reporting systems can benefit most. However, any site that repeatedly constructs pages, drop downs, or common search results form a database that is updated at intervals (rather than across categories continuously) can improve performance and scalability by implementing caching. Latency times drop sharply and bottlenecks move away from the database in an effectively cached system.
It provides several important features, necessary for any Enterprise level caching system, features include Memory management, disk overflow, element grouping, quick nested categorical removal, data expiration, extensible framework, fully configurable run time parameters, remote synchronization, remote store recovery, non-blocking "zombie" pattern, optional lateral distribution of elements, remote server clustering and failover. These features provide a framework with no point of failure, allowing for full session failover including session data across up to 256 servers.

JBoss Cache - is a product designed to cache frequently accessed Java objects in order to dramatically improve the performance of e-business applications. By eliminating unnecessary database access, JBoss Cache decreases network traffic and increases the scalability of applications. But JBoss Cache is much more than a simple cache. JBoss Cache provides fully transactional features as well as a highly configurable set of options to deal with concurrent data access in the most efficient manner possible for your application. In addition, it is a clustered cache that replicates contents to other cache instances running on separate JVMs, servers or even entire networks, making JBoss Cache a highly efficient library used by application server developers to implement clustering features.
JBossCache consists of two modules
TreeCache - a replicated transactional tree-structured cache .
TreeCacheAop a subclass of TreeCache using AOP to dynamically replicate Plain Old Java Objects - POJO.

JCache - is an effort to make an Open Source version of JSR-107 JCache. Since the JSR-107 hasn't released any specs for years, This version still builds on the original functional specification. It is implemented by some geeks at ThoughtWorks.

Jofti - is a simple to use, high-performance object indexing and searching solution for Objects in a Caching layer or storage structure that supports the Map interface. The framework supports EHCache, JBossCache and OSCache and provides for transparent addition, removal and updating of objects in its index as well as simple to use query capabilities for searching. Features include type aware searching, configurable object property indexing, indexing/searching by interfaces as well as support for Dynamic Proxies, primitive attributes, Collections and Arrays

OceanStore - is a global persistent data store designed to scale to billions of users. It provides a consistent, highly-available, and durable storage utility atop an infrastructure comprised of untrusted servers. OceanStore caches data promiscuously; any server may create a local replica of any data object. These local replicas provide faster access and robustness to network partitions. They also reduce network congestion by localizing access traffic. Pond, the OceanStore prototype, is currently available for download.

Open Terracotta - is Open Source Clustering for Java. Features: HTTP Session Replication, Distributed Cache, POJO Clustering, Application Coordination across cluster's JVM's (made using code injection, so you don't need to modify your code)

OSCache - is a caching solution that includes a JSP tag library and set of classes to perform fine grained dynamic caching of JSP content, servlet responses or arbitrary objects. It provides both in memory and persistent on disk caches, and can allow your site to have graceful error tolerance (eg if an error occurs like your db goes down, you can serve the cached content so people can still surf the site almost without knowing). Take a look at the great features of OSCache.

ShiftOne - is a Java Object Cache library that implements several strict object caching policies, as well as a light framework for configuring cache behavior. It's strict in the sense that each cache enforces two limits in a very strict and predictable way.

SwarmCache - is a simple but effective distributed cache. It uses IP multicast to efficiently communicate with any number of hosts on a LAN. It is specifically designed for use by clustered, database-driven web applications. Such applications typically have many more read operations than write operations, which allows SwarmCache to deliver the greatest performance gains. SwarmCache uses JavaGroups internally to manage the membership and communications of its distributed cache. Wrappers have been written that allow SwarmCache to be used with the Hibernate and JPOX persistence engines.

WhirlyCache - is a fast, configurable in-memory object cache for Java. It can be used, for example, to speed up a website or an application by caching objects that would otherwise have to be created by querying a database or by another expensive procedure

NB: Image sourced from blogs.oracle.com/.../2007/09/21

Other useful tips on Java, JEE/J2EE
Continue Reading...

Serialization:

Serialization is the process of persisting the state of an object.
In Java serializing an object involves encoding its state in a structured way within a byte array. Once an object is serialized, the byte array can be manipulated in various ways; it can be written to a file, sent over a network or RMI, or persisted within a database as a BLOB.Java, Programming, J2EE, Framework, Development, Serialization

The serialization process encodes enough information about the object type within the byte stream, allowing the original object to be easily recreated upon deserialization, at a later point in time.
Serialization and Deserialization is same as marshaling and unmarshaling in C/C++.

Where to keep serialized object:

Serialization is a highly versatile mechanism it should be addressed by storing the state in relational or object databases. It does not have transaction management and concurrency control. Nor does it provide any typical database features like indexed access, caching and a query language.

Serializing static variables:

Variables declared as static members are not considered part of the state of an object because they are shared by all instances of that class. Classes which need to preserve the value of static members during serialization should save and restore these values explicitly using private void readObject(ObjectInputStream) and private void writeObject(ObjectOutputStream).

Advantages and Disadvantages:

The advantages of serialization are:

It is easy to use and can be customized. The serialized stream can be encrypted, authenticated and compressed, supporting the needs of secure Java computing. Serialized classes can support coherent versioning and are flexible enough to allow gradual evolution of your application's object schema. Serialization can also be used as a mechanism for exchanging objects between Java and C++ libraries, using third party vendor libraries within C++. Many vital technologies that rely upon serialization, including RMI, JavaBeans and EJB.

Disadvantages:
It should ideally not be used with large-sized objects, as it offers significant overhead. Large objects also significantly increase the memory requirements of your application since the object input/output streams cache live references to all objects written to or read from the stream until the stream is closed or reset. Consequently, the garbage collection of these objects can be inordinately delayed. Serializable interface does not offer fine-grained control over object access - although you can somewhat circumvent this issue by implementing the complex Externalizable interface, instead. Since serialization does not offer any transaction control mechanisms, it is not suitable for use within applications needing concurrent access without making use of additional APIs.
Criteria for a class to be Serializable:
Have access to a no-argument constructor in its first non-serializable superclass Identify non-serializable data members using the transient keyword or explicitly mark data members as serializable using the serialPersistentFields member.
My subclass implements Serializable but my superclass doesn't. Both subclass and superclass contain instance variables that need to be saved as part of the state of the subclass. Will serialization save the superclass fields for me?

When you serialize an object, the serialization mechanism works by chaining up the inheritance hierarchy, saving the sate of each Serializable superclass in turn. When serialization reaches the first non-serializable superclass, the serialization stops.

When deserializing, the state of this first non-serializable superclass is restored not from the stream, but by invoking that class' no-argument constructor. If the no-argument constructor is not adequate for your purposes, you must customize the serialization of your subclass with writeObject() and readObject() in order to write out and restore any information from the non-serializable superclass that you find necessary.

Externalizable instead of Serializable:

By implementing Externalizable yourself you can win performance at the cost of flexibility and extra code to maintain. If you implement Externalizable yourself you stream the data directly without the need for reflection which is used in the case of Serializable

Read and write serialized objects to and from a database:

If your RDBMS supports them, you can store serialized objects as BLOBs.
These are JDBC 2.0 features, but take a look at java.sql.Blob, ResultSet and PreparedStatement for more information.

Collections like Vector or a Hashtable:

Collections like Vector and Hashtable both implements Serializable and have been designed for serialization.
One thing to keep in mind is to watch out for is, that in order to serialize a collection like Vector or Hashtable, you must also be able to serialize all of the objects contained in these collections. Otherwise, the collection would not be able to be completely restored. Your program will throw a NotSerializableException unless all objects stored in the Vector or Hashtable are also serializable.

Other way to save the state of an object of a class which does not implement Serializable or Extenalizable

Write the value of each and every instance variable into the persistent storage. If there are 50 variables, you will have to store each of them individually. If some of the variables are object references, you will have to follow each reference and save the state of that object as well. You can do that, but it would be a proprietary solution and each class that wanted to read your object would also have to know all about your proprietary format.

Role of serialization in RMI:

RMI uses serialization as its basic and only mechanism for sending objects across a network.
If an object implements java.rmi.Remote, then the object's stub is serialized and sent to the client. If the object implements java.io.Serializable, then the object itself is serialized and sent.

Role of serialization in EJB:

A big part of EJB is that it is a framework for underlying RMI: remote method invocation. You're invoking methods remotely from one JVM space 'A' on objects which are in JVM space 'B' -- possibly running on another machine on the network.
To make this happen, all arguments of each method call must have their current state plucked out of JVM 'A' memory, flattened into a byte stream which can be sent over a network connection, and then deserialized for reincarnation on the other end in JVM 'B' where the actual method call takes place.
If the method has a return value, it is serialized up for streaming back to JVM 'A.' Thus the requirement that all EJB methods arguments and return values must be serializable. The easiest way to do this is to make sure all your classes implement java.io.Serializable.
NB: Image is sourced from javaworld

Other useful tips on Java, JEE/J2EE
Continue Reading...

Background :
Spring is an open-source application framework, introduced and developed in 2004. The main ideas were suggested by an experienced J2EE architect, Rod Johnson. He had earlier, written a book titled J2EE Development without using EJB and had introduced the concept of Light-weight container. Primarily, his argument is that while EJB has its merits, it is not always necessary and suitable in all applications.
Just as Hibernate attacked CMP as primitive ORM technology, Spring attacked EJB as unduly complicated and not susceptible to unit-testing. Instead of EJB, Spring suggests that we make use of ordinary Java beans, with some slight modifications, to get all the supposed advantages of EJB environment. Thus, Spring is posed as an alternative to EJB essentially. However, as a concession to the existing EJB investments, Spring is designed to operate with EJB if required.

Much of the philosophy and approach of Spring framework, however, predates, the latest EJB-3. As we know now that EJB-3 has absorbed a number of new ideas suggested by Spring and some more, to answer the criticisms. Their is a debate going on in the Java community about Spring and EJB-3. Spring is not a Persistence technology but a framework which allows plug in of other such technologies. But EJB-3 is primarily focused on Persistence Technology and has now incorporated Hibernate, the best ORM to date.Talks are going on to incorporate another equally nice ORM Technology known as JDO, which provides for Object Database also. Moreover, EJB-3 's Attribute-Oriented Meta tags, help in vastly reducing the size of XML lines. Some have complained that Spring is still too dependent on XML files.
The main aim of Spring is to simplify the J2EE development and testing.

Spring Under The Hood :

Enterprise, Technlogy, Spring Framework, J2EE Development, Hibernate,without EJB
Spring is a great framework for development of Enterprise applications. It is a light-weight framework for the development of enterprise-ready applications. Spring can be used to configure declarative transaction management, remote access to your logic using RMI or web services, mailing facilities and various options in persisting your data to a database. It can be used in modular fashion, allows to use in parts and leave the other components which is not required by the application.

Main Features of Spring Framework:

Transaction Management: Spring framework provides a generic abstraction layer for transaction management. This allowing the developer to add the pluggable transaction managers, and making it easy to demarcate transactions without dealing with low-level issues. Spring's transaction support is not tied to J2EE environments and it can be also used in container less environments.

JDBC Exception Handling: The JDBC abstraction layer of the Spring offers a meaningful exception hierarchy, which simplifies the error handling strategy

Integration with Hibernate, JDO, and iBATIS: Spring provides best Integration services with Hibernate, JDO and iBATIS.

AOP Framework: Spring is one of the best AOP framework

MVC Framework: Spring comes with MVC web application framework, built on core Spring functionality. This framework is highly configurable via strategy interfaces, and accommodates multiple view technologies like JSP, Velocity, Tiles, iText and POI.
But other frameworks can be easily used instead of Spring MVC Framework..

Spring Architecture :
Spring is well-organized architecture consisting of various modules. Modules in the Spring framework are:

1. Spring Aspect Oriented Programming (AOP)
AOP is used in Spring

a) To provide declarative enterprise services, especially as a replacement for EJB declarative services. The most important such service is declarative transaction management, which builds on Spring's transaction abstraction.

b) To allow users to implement custom aspects, complementing their use of OOP with AOP

2. Spring ORM
The ORM package is related to the database access. It provides integration layers for popular object-relational mapping APIs, including JDO, Hibernate and iBatis.

3. Spring Context
This package builds on the beans package to add support for message sources and for the Observer design pattern, and the ability for application objects to obtain resources using a consistent API.

4. Spring Web
The Web context module builds on top of the application context module, providing contexts for Web-based applications. As a result, the Spring framework supports integration with Jakarta Struts, JSF and webworks. The Web module also eases the tasks of handling multi part requests and binding request parameters to domain objects.

5. Spring DAO
The Spring's JDBC and DAO abstraction layer offers a meaningful exception hierarchy for managing the database connection, exception handling and error messages thrown by different database vendors. The exception hierarchy simplifies error handling and greatly reduces the amount of code that we need to write, such as opening and closing connections. This module also provide transaction management services for objects in a spring application.

6. Spring Web MVC
The MVC framework is a full-featured MVC implementation for building Web applications. The MVC framework is highly configurable via strategy interfaces and accommodates numerous view technologies including JSP, Velocity, Tiles and the generation of PDF and Excel Files.

7. Spring Core
The Core package is the most import component of the Spring Framework.
This component provides the Dependency Injection features. The BeanFactory provides a factory pattern which separates the dependencies like initialization, creation and access of the objects from your actual program logic.
NB: Image sourced from Google Images

Other useful tips on J2EE

Continue Reading...