Struts 2


The core features of the struts 2 framework:

  1. Pluggable framework architecture that allows request life cycles to be customized for each action.
  2. Flexible validation framework that allows validation rules to be decoupled from action code.
  3. Hierarchical approach to internationalization that simplifies localizing applications.
  4. Integrated dependency injection engine that manages component life cycle and dependencies. (By default, the framework utilizes Spring for dependency injection.)
  5. Modular configuration files that use packages and namespaces to simplify managing large projects with hundreds of actions.
  6. Java 5 annotations that reduce configuration overhead. (Java 1.4 is the minimum platform.)

Struts 2 request Processing:

Each and every request made using struts 2 framework fallows the same request processing as below:

  1. Initially the web browser requests for request. (Ex: /index.acion or /myreport.pdf .. etc)
  2. The filter dispatcher looks at the request and determines the appropriate action.
  3. The interceptors automatically apply common functionality to the request, like work flow, validation, and file upload handling.
  4. The action method executes, usually storing and/or retrieving information from a database.
  5. The request renders the output to the browser, be it HTML, images, pdf, or something else.

The features added in struts2 over the struts1:

  1. Programming the abstract classes instead of interfaces is one of the design problem of struts1 framework that has been resolved in struts2.
  2. Most of the struts2 classes are based on interfaces and most of its core interfaces are HTTP independent.
  3. Unlike ActionForwards, Struts2 results provide flexibility to create multiple type of outputs.
  4. Actions in struts1 have dependencies on the servlet API since HttpServlertRequest and HttpServletResponse objects are passed to the execute() Method. But in struts2 any Java class with execute() method can be used as an Action Class. Actions to be neutral to the underlying framework
  5. ActionForms feature is no more known to the struts2 framework. Simple Java Bean flavored actions are used to put properties directly.
  6. Struts2 actions are HTTP independent and framework neutral. This enables to test struts2 applications very easily with out resorting mock objects.
  7. Struts2 tags enables to add style sheet driven markup capabilities.  ie. You can create consistent pages with less code. Struts2 tag markup can be altered by changing an underlying stylesheet.
  8. Struts tags are more capable and result oriented.
  9. Both JSP and Free maker tags are fully supported.
  10. Java 5 annotations can be used as an alternative to XML and Java properties configuration.
  11. Struts 2 check boxes do not require special handling for false values.
  12. Many changes can be done on fly without restarting the web container.
  13. Struts1 lets to customize the request processor per module. Struts2 lets to customize request handling per action if desired.
  14. Struts 2 Actions are spring aware. Just need to add spring beens.
  15. Struts2 extensions can be added by dropping in jar. No need of any addition XML or properties files. Metadata is expressed through convention and annotations.

Ajax support in Struts2:

  1. AJAX client side validation
  2. Remote form submission support (works with the submit tag as well)
  3. An advanced div template that provides dynamic reloading of partial HTML
  4. An advanced template that provides the ability to load and evaluate JavaScript remotely
  5. An AJAX-only tabbed Panel implementation
  6. A rich pub-sub event model
  7. Interactive auto complete tag

Struts1 and Struts2 at a glance:

Struts 1 vs. Struts 2

  1. Action                                    Action
  2. ActionForm                        Action or POJO
  3. ActionForward                  Result
  4. struts-config.xml              struts.xml
  5. ActionServlet                     FilterDispatcher
  6. RequestProcessor             Interceptors
  7. validation.xml                    Action-validation.xml

JavaMail API usage


  • Below program consits of Steps to send email using javax.mail
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class TestMail {
public static void main(String args[]) throws Exception {
String host = "localhost";
String from = "nani@gmail.com";
String to = "nani@gmail.com";
String user = "mallik";
String password = "mallik";
String content = "Change your password.";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
Session session =Session.getDefaultInstance(properties);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("Test Mail");
message.setText(content);

Transport.send(message);
System.out.println("Message Send Successfully..." + content);

}
}
  • Below program consits of Steps to reading email using javax.mail
import java.io.*;
import java.util.*;
import javax.mail.*;

public class ReadMail {
public static void main(String args[]) throws Exception {
String host = "localhost";
String user = "nani";
String password = "nani";
Properties properties = System.getProperties();
Session session = Session.getDefaultInstance (properties);
Store store = session.getStore("pop3");
store.connect(host, user, password);
Folder folder = store.getFolder("inbox");
folder.open(Folder.READ_ONLY);

Message[] message = folder.getMessages();

for (int i = 0; i < message.length; i++) {
System.out.println("----- Message " + (i + 1) + " ------------");
System.out.println("SentDate : " + message[i]. getSentDate());
System.out.println("From : " + message[i]. getFrom()[0]);
System.out.println("Subject : " + message[i]. getSubject());
System.out.print("Message : ");
InputStream stream = message[i]. getInputStream();
while (stream.available() != 0) {
System.out.print((char) stream.read());
}
}
folder.close(true);
store.close();
}
}
  • Below program consits of Steps to sending email with attachment using javax.mail
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.SendFailedException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class AttachExample {
public static void main (String args[]) throws Exception {
String host = "localhost";
String from = "nani@gmail.com";
String to[] = new String[]{"nani@gmail.com","gopikanthk"};
String filename = "testAttach.txt";
// Get system properties
Properties props = System.getProperties();
props.put("mail.smtp.host", host);
Session session = Session.getInstance(props, null);
System.out.println(session.getProperties());
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));

InternetAddress[] toAddress = new InternetAddress[to.length];
for (int i = 0; i < to.length; i++){
toAddress[i] = new InternetAddress(to[i]);
System.out.println("to address are--------"+toAddress[i]);
}
message.setRecipients(Message.RecipientType.TO, toAddress);
String a=null;
System.out.println("recipent type to----");
message.setSubject("Hello JavaMail Attachment");
System.out.println("After the subject---------");
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("Here's the file");
System.out.println("After the content of the message----");
Multipart multipart = new MimeMultipart();

multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();

DataSource source = new FileDataSource(filename);

messageBodyPart.setDataHandler(new DataHandler(source));
System.out.println("After the data handler----");
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
try{
  System.out.println("In try block-------");
  Transport.send(message);
  System.out.println("messages sent successfully.........");
} catch(SendFailedException sfe) {
  message.setRecipients(Message.RecipientType.TO, sfe.getValidUnsentAddresses());
  Transport.send(message);
}
}
}

Log4j


→ Log4j has three main components: loggers, appenders and layouts. These three types of components work together to enable developers to log messages according to message type and level, and to control at runtime how these messages are formatted and where they are reported.

→ Loggers are named entities. Logger names are case-sensitive and they follow the hierarchical naming rule:

Named Hierarchy :

A logger is said to be an ancestor of another logger if its name followed by a dot is a prefix of the descendant logger name. A logger is said to be a parent of a child logger if there are no ancestors between itself and the descendant logger.

→ For example, the logger named “com.foo” is a parent of the logger named “com.foo.Bar”. Similarly, “java” is a parent of “java.util” and an ancestor of “java.util.Vector”. This naming scheme should be familiar to most developers.
The root logger resides at the top of the logger hierarchy. It is exceptional in two ways:
1.it always exists,
2.it cannot be retrieved by name.

Invoking the class static Logger.getRootLogger method retrieves it. All other loggers are instantiated and retrieved with the class static Logger.getLogger method. This method takes the name of the desired logger as a parameter. Some of the basic methods in the Logger class are listed below.

package org.apache.log4j;

public class Logger {

// Creation & retrieval methods:
public static Logger getRootLogger();
public static Logger getLogger(String name);

// printing methods:
public void trace(Object message);
public void debug(Object message);
public void info(Object message);
public void warn(Object message);
public void error(Object message);
public void fatal(Object message);

// generic printing method:
public void log(Level l, Object message);
}

Loggers may be assigned levels. The set of possible levels, that is:

TRACE,
DEBUG,
INFO,
WARN,
ERROR and
FATAL

Logging requests are made by invoking one of the printing methods of a logger instance. These printing methods are debug, info, warn, error, fatal and log.

A logging request is said to be enabled if its level is higher than or equal to the level of its logger. Otherwise, the request is said to be disabled. A logger without an assigned level will inherit one from the hierarchy. This rule is summarized below.

Basic Selection Rule
A log request of level p in a logger with (either assigned or inherited, whichever is appropriate) level q, is enabled if p >= q.

This rule is at the heart of log4j. It assumes that levels are ordered. For the standard levels, we have DEBUG < INFO < WARN < ERROR < FATAL.

Configuration of the log4j environment is typically done at application initialization. The preferred way is by reading a configuration file.

AJAX


What is Ajax?
Asynchronous JavaScript and XML.
Ajax is not a new programming language but a new way to use existing standards.

Basic requirements to learn Ajax:
HTML or XHTML and Java Script.

Ajax applications are browser and platform independent.
Advantages:
These applications make the user to communicate asynchronously between browser and server.

With AJAX, a JavaScript can communicate directly with the server, with the XMLHttpRequest object. With this object, a JavaScript can trade data with a web server, without reloading the page.

AJAX uses asynchronous data transfer (HTTP requests) between the browser and the web server, allowing web pages to request small bits of information from the server instead of whole pages.

The AJAX technique makes Internet applications smaller, faster and more user-friendly.

JMS


Message is a method of communication between a software component or application. A messaging client can send a message to other client and can receive a message from other client. Each client connects the Messaging agent to creating, sending , receiving and reading a Message.

The difference between E-mail and Messaging is :
E-mail is communication between people or between software applications and people.
Messaging is used for communication between software applications and software components.

Java Messaging Service is a Java API that allows applications to create, send, receive and read messages.

JMS applications features are:
1)Loosely coupled: A component sends a message to a destination, and the recipient can retrieve the message from the destination. However, the sender and the receiver do not have to be available at the same time in order to communicate. In fact, the sender does not need to know anything about the receiver; nor does the receiver need to know anything about the sender. The sender and the receiver need to know only what message format and what destination to use.
2)Asynchronous: A JMS provider can deliver messages to a client as they arrive; a client does not have to request messages in order to receive them.
3)Reliable: The JMS API can ensure that a message is delivered once and only once. Lower levels of reliability are available for applications that can afford to miss messages or to receive duplicate messages.

You can use the Java API in the fallowing situations:
I)The you want the components not to depend on information about other components’ interfaces, so that components can be easily replaced.
II)The provider wants the application to run whether or not all components are up and running simultaneously.
III)The application business model allows a component to send information to another and to continue to operate without receiving an immediate response.

JMS application is composed of fallowing parts:
1) JMS provider: It is a messaging system that implements JMS interfaces and provides administrative and control features.
2)JMS Clients: These are the programs or components written in Java programing language, that produce and consume messages.
3)Messages: These are the objects that communicate information between JMS clients.
4)Administered objects: These are preconfigured JMS objects created by an administer for the use of clients. The two kinds of Administered objects are destinations and connection factories.
5)Native Clients: these are the programs that use a messaging product’s native client api instead of JMS api.

Fallowing figure illustrate the way these parts interacts:

JMS provides the two types of domain applications
1)Point- to- Point Messaging domain.
2)Publish/Subscribe Messaging domain.

1)Point-to-point Messaging domain:
PTP messaging have fallowing characteristics
→ Each message has only one consumer.
→ A sender and receiver of a message have no timing dependencies. The receiver can fetch the message whether or not it was running when the client sends the message.
→ The receiver acknowledges the successful processing of message.
Use PTP when every message you send must be processed successfully by one consumer.

2)Publish/Subscribe Messaging domain:
pub/sub messaging have fallowing characteristics.
→ Each message may have multiple consumers
→ Publishers and subscribers have a timing dependency. A client that subscribes to a topic can consume only messages published after the client has created a subscription, and the subscriber must continue to be active in order for it to consume messages.

The basic building blocks of a JMS application consist of
Administered objects:Connection factories and destinations Connections
Sessions
Message producers
Message consumers
Messages

These building blocks explained one by one as fallows.

1)Administered Objects:

Web Services


Web Services provide loosely coupled communication between enterprise systems.
Web Services also enables the enterprise systems to expose business functions to Web-enabled clients.
Web Services can be accessed by wider variety of Clients.
Web Services provide Security and quality services such as availability, reliability and transactions.

There are two principle models in web services. These are:
Document oriented Model.
Remote procedure call oriented Model.

Web Services can be implemented by two ways
Synchronous Web Services
Asynchronous Web Services.

Web Services should be used when you need interoperability across heterogeneous platforms. That is, When you need to expose all or part of your application to other applications on different platforms.
Implementing Web Service make sense when your web services clients are potentially non J2EE enterprise applications.

Invoking the Web Service:

1.As we said before, a client may have no knowledge of what Web Service it is going to invoke. So, our first step will be to discover a Web Service that meets our requirements. For example, we might be interested in locating a public Web Service which can give me the weather forecast in US cities. We’ll do this by contacting a discovery service (which is itself a Web service)
2.The discovery service will reply, telling us what servers can provide us the service we require.
3.We now know the location of a Web Service, but we have no idea of how to actually invoke it. Sure, we know it can give me the forecast for a US city, but how do we perform the actual service invocation? The method I have to invoke might be called “string getCityForecast(int CityPostalCode)”, but it could also be called “string getUSCityWeather(string cityName, bool isFarenheit)”. We have to ask the Web Service to describe itself (i.e. tell us how exactly we should invoke it)
4.The Web Service replies in a language called WSDL.
5.We finally know where the Web Service is located and how to invoke it. The invocation itself is done in a language called SOAP. Therefore, we will first send a SOAP request asking for the weather forecast of a certain city.
6.The Web Service will kindly reply with a SOAP response which includes the forecast we asked for, or maybe an error message if our SOAP request was incorrect.

Web Services Architecture
So, what exactly are SOAP and WSDL? They’re essential parts of the Web Services Architecture:
Fig: The Web Services architecture

Service Processes: This part of the architecture generally involves more than one Web service. For example, discovery belongs in this part of the architecture, since it allows us to locate one particular service from among a collection of Web services.
Service Description: One of the most interesting features of Web Services is that they are self-describing. This means that, once you’ve located a Web Service, you can ask it to ‘describe itself’ and tell you what operations it supports and how to invoke it. This is handled by the Web Services Description Language (WSDL).
Service Invocation: Invoking a Web Service (and, in general, any kind of distributed service such as a CORBA object or an Enterprise Java Bean) involves passing messages between the client and the server. SOAP (Simple Object Access Protocol) specifies how we should format requests to the server, and how the server should format its responses. In theory, we could use other service invocation languages (such as XML-RPC, or even some ad hoc XML language). However, SOAP is by far the most popular choice for Web Services.
Transport: Finally, all these messages must be transmitted somehow between the server and the client. The protocol of choice for this part of the architecture is HTTP (HyperText Transfer Protocol), the same protocol used to access conventional web pages on the Internet. Again, in theory we could be able to use other protocols, but HTTP is currently the most used one.
A Typical Web Service Invocation (redux)
So, let’s suppose that we’ve already located the Web Service we want to use (either because we consulted a discovery service, or because the Web service URI was given to us), and we’ve generated the client stubs from the WSDL description. What exactly happens when we want to invoke a Web service operation from a program?
Figure: A typical Web Service invocation (more detailed)

1.Whenever the client application needs to invoke the Web Service, it will really call the client stub. The client stub will turn this ‘local invocation’ into a proper SOAP request. This is often called the marshaling or serializing process.
2.The SOAP request is sent over a network using the HTTP protocol. The server receives the SOAP requests and hands it to the server stub. The server stub will convert the SOAP request into something the service implementation can understand (this is usually called unmarshaling or deserializing)
3.Once the SOAP request has been deserialized, the server stub invokes the service implementation, which then carries out the work it has been asked to do.
4.The result of the requested operation is handed to the server stub, which will turn it into a SOAP response.
5.The SOAP response is sent over a network using the HTTP protocol. The client stub receives the SOAP response and turns it into something the client application can understand.
6.Finally the application receives the result of the Web Service invocation and uses it.
Server Requirements for Web Service Application:
Finally, let’s take a close look at what the server looks like, specially what software we should expect to have to get Web services up and running on our server.

Web service: First and foremost, we have our Web service. As we have seen, this is basically a piece of software that exposes a set of operations. For example, if we are implementing our Web service in Java, our service will be a Java class (and the operations will be implemented as Java methods). Obviously, we want a set of clients to be able to invoke those operations. However, our Web service implementation knows nothing about how to interpret SOAP requests and how to create SOAP responses. That’s why we need a…
SOAP engine: This is a piece of software that knows how to handle SOAP requests and responses. In practice, it is more common to use a generic SOAP engine than to actually generate server stubs for each individual Web service (note, however, that we still need client stubs for the client). One good example of a SOAP engine is Apache Axis (this is, in fact, the SOAP engine used by the Globus Toolkit). However, the functionality of the SOAP engine is usually limited to manipulating SOAP. To actually function as a server that can receive requests from different clients, the SOAP engine usually runs within an…

Application server: This is a piece of software that provides a ‘living space’ for applications that must be accessed by different clients. The SOAP engine runs as an application inside the application server. A good example is the Jakarta Tomcat server, a Java Servlet and Java ServerPages container that is frequently used with Apache Axis and the Globus Toolkit.
Many application servers already include some HTTP functionality, so we can have Web services up and running by installing a SOAP engine and an application server. However, when an application server lacks HTTP functionality, we also need an…
HTTP Server: This is more commonly called a ‘Web server’. It is a piece of software that knows how to handle HTTP messages. A good example is the Apache HTTP Server, one of the most popular web servers in the Internet.

Web Services


Web Services provide loosely coupled communication between enterprise systems.
Web Services also enables the enterprise systems to expose business functions to Web-enabled clients.
Web Services can be accessed by wider variety of Clients.
Web Services provide Security and quality services such as availability, reliability and transactions.

There are two principle models in web services. These are:
Document oriented Model.
Remote procedure call oriented Model.

Web Services can be implemented by two ways
Synchronous Web Services
Asynchronous Web Services.

Web Services should be used when you need interoperability across heterogeneous platforms. That is, When you need to expose all or part of your application to other applications on different platforms.
Implementing Web Service make sense when your web services clients are potentially non J2EE enterprise applications.

Web Services Material


Web Services

1)What is web Services ?
Getting the services through the web.
2)What is JAX-RPC?
JAX-RPC means java api for xml based RPC is a java api for developing and using web-services.
An RPC based web-service is a collection of procedures that can be called by remote client over the internet.
Ex: A typical RPC based web service is a stock quote service that takes a SOAP request for the price of a specified stock and returns the price via SOAP.
3)Explain about Web Services
A Web service, a server application that implements the procedures that available for clients to call, deployed on server-side container.
A web service can make itself available to potential clients by describing itself in a Web Service Description Language (WSDL) document.
4)What is WSDL?
WSDL is an XML document that gives all pertinent information about web service, the operation that can be called on it, parameters for those operations, and the location of where to send requests.
A web client can use WSDL document to discover the what the service offers and how to access it.
5)Explain some of the features of the web services?
Some of the features of the web services are:
1.Interoperability
Using JAX-RPC, a client written in a language other than Java programming language can access a web service developed and deployed on the Java platform. Conversely,a client written in the Java programming language can communicate with a service that was developed and deployed using some other platform.
2.Ease of use:
Using JAX-RPC makes the user to feel comfortable over the RPC. The internal complicated infrastructure, like marshaling, unmarshaling, and transmission details..etc, will be taken care automatically.
3.Advanced features

6)What makes interoperability is possible?
JAX-RPC support for SOAP and WSDL.
7)What is JAXM?
Java API for Messaging provides a standard way to send XML documents over the Internet from the Java platform. It is based on SOAP 1.1 and SOAP with attachments specifications, which define a basic framework for exchanging XML messages.
8)The features of JAXM over the RPC including JAX-RPC
a) One way(asynchronous)messaging.
b) Routing of message to more than one party.
c) Reliable messaging features such as guarantied delivery.
9)What is JAXR?
Java API for XML registries provides a convenient way to access standard business registries over the Internet. Using JAXR one can register the business registry and one can search for a business registry for other business.
10)Write the difference between XML and HTML?
11)Write the differences bet ween SAX and DOM parsers.

WEB Services Interview Questions


1)What is web Services ?
Getting the services through the web.

2)What is JAX-RPC?
JAX-RPC means java api for xml based RPC is a java api for developing and using web-services.
An RPC based web-service is a collection of procedures that can be called by remote client over the internet.
Ex: A typical RPC based web service is a stock quote service that takes a SOAP request for the price of a specified stock and returns the price via SOAP.

3)Explain about Web Services
A Web service, a server application that implements the procedures that available for clients to call, deployed on server-side container.
A web service can make itself available to potential clients by describing itself in a Web Service Description Language (WSDL) document.

4)What is WSDL?
WSDL is an XML document that gives all pertinent information about web service, the operation that can be called on it, parameters for those operations, and the location of where to send requests.
A web client can use WSDL document to discover the what the service offers and how to access it.

5)Explain some of the features of the web services?
Some of the features of the web services are:
1.Interoperability
Using JAX-RPC, a client written in a language other than Java programming language can access a web service developed and deployed on the Java platform. Conversely,a client written in the Java programming language can communicate with a service that was developed and deployed using some other platform.
2.Ease of use:
Using JAX-RPC makes the user to feel comfortable over the RPC. The internal complicated infrastructure, like marshaling, unmarshaling, and transmission details..etc, will be taken care automatically.
3.Advanced features

6)What makes interoperability is possible?
JAX-RPC support for SOAP and WSDL.

7)What is JAXM?
Java API for Messaging provides a standard way to send XML documents over the Internet from the Java platform. It is based on SOAP 1.1 and SOAP with attachments specifications, which define a basic framework for exchanging XML messages.
8)The features of JAXM over the RPC including JAX-RPC
a) One way(asynchronous)messaging.
b) Routing of message to more than one party.
c) Reliable messaging features such as guarantied delivery.

9)What is JAXR?
Java API for XML registries provides a convenient way to access standard business registries over the Internet. Using JAXR one can register the business registry and one can search for a business registry for other business.

10) What tools do you use to test your Web Services?

 SoapUI tool for SOAP WS and the Firefox “poster” plugin for RESTFul services.

11) What is the difference between SOA and a Web service? 

SOA is a software design principle and an architectural pattern for implementing loosely coupled, reusable and coarse grained services. You can implement SOA using any protocols such as HTTP, HTTPS, JMS, SMTP, RMI, IIOP (i.e. EJB uses IIOP), RPC etc. Messages can be in XML or Data Transfer Objects (DTOs).

Web service is an implementation technology and one of the ways to implement SOA. You can build SOA based applications without using Web services – for example by using other traditional technologies like Java RMI, EJB, JMS based messaging, etc. But what Web services offer is the standards based  and platform-independent service via HTTP, XML, SOAP, WSDL and UDDI, thus allowing interoperability between heterogeneous technologies such as J2EE and .NET.