Thursday, September 30, 2010

Servlet 3.0 Uploading files

The Internet is becoming more and more about sharing data and uploading files had become nearly universal requirement for a web application. Prior to Servlet 3.0, implementing file upload successfully required external libraries or tedious input processing.

Servlet 3.0 introduces a new API to handle multipart/form-data submissions. Multipart/form-data is a content type used to submit files, non-ASCII and binary data. Here is an example of file upload servlet.

fileupload.jsp: The browser will submit data using multipart/form-data encoding when an HTML form specifies it as a value for its enctype attribute.
<form action="/file-upload" enctype="multipart/form-data" method="POST">
Submitter: <input name="submitter" type="text">
Upload File: <input name="content" type="file">
<input value="Submit" type="submit">
</form>

When submitting a form, the browser will stream the content in, all parts combined, with each part representing a field of a form. Parts are named after the input elements and separated from each other with string delimiters named boundary.

What submitted header data would look like as follows:

POST /file-upload HTTP/1.1
Content-Type: multipart/form-data; boundary=---------------------------8723974127529 Content-Length: 1231

-----------------------------8723974127529 Content-Disposition: form-data; name="submitter"

pulak -----------------------------8723974127529

Content-Disposition: form-data; name="content"; filename="bloggerpoc.txt" Content-Type: application/octet-stream

<<Some data to be uploaded>>

The new Servlet 3.0 API specifies an interface javax.servlet.http.Part for each submission part and javax.servlet.http.HttpServletRequest makes them accessible using two methods:

* getParts()
* getPart(String name)

Since parts are named, method getPart(String name) can be used to access a particular part. Alternatively, method getParts() which returns an Iterable can be used to get an Iterator over all the parts. javax.servlet.http.Part is a really simple interface which provides methods allowing to introspect each part and get its name, size, content-type, query the headers submitted with a part, delete or write part out to a disk.

fileupload servlet: A simple servlet that accepts and saves a file can be as following:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

@WebServlet(name="UploadServlet", urlPatterns={"/file-upload"})
@MultipartConfig(location = "D://tmp")
public class MyServlet extends HttpServlet {
public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

//get the "content" part and save it.
Part part = request.getPart("content");
part.write("file2.txt");
}
}

The Servlet 3.0 Specification introduces a new @javax.servlet.annotation.MultipartConfig annotation that helps the container identify a Servlet as capable of handling multipart/form-data requests. When this annotation is present on a Servlet, the HttpServletRequest makes the parts available.

The annotation can be used to configure location where the container should store temporary files, legal size limits on the entire request and parts, and a threshold size that triggers use of permanent storage.

@MultipartConfig annotation declares the following attributes
* location
* maxFileSize
* maxRequestSize
* fileSizeThreshold

Hope this will help.
I will cover more interesting Servlet 3.0 feature like support for Asynchronous communication next.

Introduction to servlet 3.0 new features

Servlet API is the building block of the Java Web Applications. Almost all the java web application frameworks build on top of the Java Servlet API. Servlet 3.0 is JSR 315 JavaTM Specification. The Servlet API 3.0 Sspecification has come up with many new and exciting features as follows.

1. Programmatic instantiation of Servlets/Filters/listeners
2. Ease of Development through Annotations
3. File upload
4. Modularization of web.xml
5. Asynchronous Servlets and comet support.
6. Pluggable Web framework

1. Programmatic instantiation Filters, servlets, listeners
Servlet 3.0 specification has additional methods to the ServletContext to register dynamically Web components like Servlets or Filters or even Roles.

2. Ease of Development through Annotations
The servlet 3.0, web.xml deployment descriptor is totally optional. Servlet 3.0 specification has made this thing easier through annotations and providing the way to programmatic defination of Filters, servlet, listeners and URL patterns. Deployment descriptor can be used to override the configuration.

For example, you can define a servlet using @WebServlet annotation and put into WEB-INF/classes directory or application's WEB-INF/lib directory. The servlet does not need to be defined into web.xml, at run time container will process classes in WEB-INF/classes and lib directory and identify it based on the annotation.

Note: Classes using annotation will have their annotation processed on if they are located in WEB-INF/classes directory or if they are packaged in a jar file located in WEB-INF/lib directory.

3. File upload support
Servlet API, previously did not provide any built in support for handling file upload. We used various open source/third party libraries like Commons file upload and other APIs. However supporting file upload is so common requirement for any web application that Servlet 3.0 Specification supports it out of the box. Web container itself can parse the multipart request and make mime attachments available through HttpServletRequest object.

Two new methods have been introduced to HttpServletRequest interface are
public Collection getParts()
public Part getPart(String name)

Each part provides access to the headers, content type related with it and also the content via the getInputStream method.

The HTML form must specify multipart/form-data as encoding type and Servlet should be either annotated with @MultiPartConfig or configured with element in deployment descriptor.

4. Modularization of web.xml
The annotations make the web.xml deployment descriptor optional, However web.xml can be used to override the configuration values defined by the annotations. Currently before Servlet 3.0 specification web.xml is a big fat file with all the configuration for entire application. However Servlet 3.0 introduces notion of deployment descriptor fragments. The web.xml can be divided into parts called fragments and bundled in jar file. The fragments must be located into META-INF directory of the jar file.

A web fragment is a logical partitioning of the web application in such a way that the frameworks being used within the web application can define all the artifacts without asking developers to edit or add information in the web.xml. It can include almost all the same elements that the web.xml descriptor does include. However the top level element for the descriptor MUST be web-fragment and the corresponding descriptor file MUST be called web-fragment.xml

5. Asynchronous Servlets and comet support
Servlet 3.0 makes developing Comet applications very easier. Sometime comet is referred as reverse Ajax also.
Servlet 3.0 added new methods into HttpServletRequest class to support the asynchronous request processing and response generation.

public AsyncContext startAsync(ServletRequest req, ServletResponse res) {}

This method puts the request into asynchronous mode and initializes it’s AsyncContext with the given request and response objects.

6.
Pluggable Web Framework support
Almost all the java web application frameworks build on top of the Servlet API. Examples are Spring MVC, Struts, Struts 2, JSF, Webwork, Stripes and the like. In order to hook this frameworks into your web application, you declare a filter or a servlet into your web application deployment descriptor and map URL patterns to that servlet/filter in addition to including it as a dependency in the WEB-INF/lib directory. There was no way that you can just put the jar file into web application lib directory and ready to go with the framework.

For example, when using Spring MVC, you have to declare DispatcherServlet in web.xml and map URLs to it, you cannot just put the Spring MVC jar into lib directory and start using it. Today in a servlet container the application has one monolithic web.xml that defines all the deployment artifacts for the application, including the dependencies of the application on the framework components.

To overcome this issue in Servlet 3.0 Specification, A framework can define it's own deployment descriptor that declares the necessary components for the framework that is then included for use in the web applicaton. At deployment the container is responsible for discovering the web.xml fragments and processing them. A new element is being added to the descriptor schema for web applications - web-fragment that can define servlets, filters and listeners. The above fragment would be included in the META-INF directory of the framework jar file. However the top level element for the descriptor MUST be web-fragment and the corresponding descriptor file MUST be called web-fragment.xml.

Hope this will help.

Tuesday, September 21, 2010

Why SingleThread model is deprecated in Servlets?

SingleThreadModel ensures that servlets handle only one request at a time. This interface has no methods. In Servlet 2.4 SingleThreadModel is deprecated for a good reason mostly because it does not really provide thread safety.

Note that SingleThreadModel does not solve all thread safety issues. For example, session attributes and static variables can still be accessed by multiple requests on multiple threads at the same time, even when SingleThreadModel servlets are used. Also it is really very expensive to creating one instance for each request is time consuming and difficult.


Alternative to SingleThreadModel:
It is recommended that a developer take other means to resolve those issues instead of implementing this interface, such as avoiding the usage of an instance variable or synchronizing the block of the code accessing those resources.

Singleton Design Pattern

Motivation:
Sometimes it is important to have only one instance of a class in the entire application. Usually singletons are used for centralized management of internal or external resources and they provide a global point of access to the instances of the Objects.

So, our intention is to
* Ensure that only one instance of a class is created.
* Provide a global point of access to the object.

Implementation:
The implementation has a static member in the "Singleton" class, a private constructor and a static public method that returns a reference to the static member.

The Singleton Pattern defines a getInstance operation which exposes the unique instance which is accessed by the clients. getInstance() is a class operation and is responsible for creating its own unique instance in case it is not created yet.

class Singleton
{
private static Singleton m_instance;
private Singleton()
{
...
}

public static synchronized Singleton getInstance()
{
if (m_instance == null)
m_instance = new Singleton();

return m_instance;
}
...
public void doSomething()
{
...
}
}

There are many common situations when singleton pattern is used:
- Logger Classes
- Configuration Classes
- Caching classes
- Accesing resources in shared mode
- Other design patterns implemented as Singletons: Factories and Abstract Factories, Builder, Prototype


Thread-safe implementation in multithreading access/usage of the single object:
1. Lazy instantiation
2. Early instantiation

1. Lazy instantiation using double locking mechanism:
The standard implementation shown in the code above is a thread safe implementation, but it's not the best thread-safe implementation beacuse sinchronization is very expensive when we are talking about the performance. We can see that the syncronized method getInstance does not need to be checked for syncronization after the object is initialized. If we see that the singleton object is already created we just have to return it without using any syncronized block. This optimization consist in checking in an unsincronized block if the object is null and if not, then check again and create it in an syncronized block. This is called double locking mechanism.

In this case case the singleton instance is created when the getInstance() method is called for the first time. This is called lazy instantiation and it ensures that the singleton instance is created only when it is needed.

class Singleton
{
private static Singleton m_instance;

private Singleton()
{
System.out.println("Singleton(): Initializing Instance");
}

public static Singleton getInstance()
{
if (m_instance == null)
{
synchronized(Singleton.class)
{
if (m_instance == null)
{
System.out.println("getInstance(): First time getInstance was invoked!");
m_instance = new Singleton();
}
}
}

return m_instance;
}

public void doSomething()
{
System.out.println("doSomething(): Singleton does something!");
}
}

2. Early instantiation using implementation with static field:
In the following implementattion the singleton object is instantiated when the class is loaded and not when it is first used, due to the fact that the m_instance member is declared static. This is why in this implementation we don't need to syncronize any portion of the code. The class is loaded once this guarantee the unicity of the object.

class Singleton
{
private static Singleton m_instance = new Singleton();

private Singleton()
{
System.out.println("Singleton(): Initializing Instance");
}

public static Singleton getInstance()
{
return m_instance;
}

public void doSomething()
{
System.out.println("doSomething(): Singleton does something!");
}
}

Issues:
Multiple singleton instances if classes loaded by different classloaders accessing a singleton:
If a class(same name, same package) is loaded by 2 diferent classloaders they represents 2 different clasess in memory.

Hope this is useful!

Friday, September 3, 2010

What is J2EE, J2EE Platform and benefits

In the world of software, a platform is a combination of hardware and software necessary to run applications. J2EE is a platform for delivering enterprise applications. But what does it mean to say that J2EE is a platform? J2EE isn't hardware, although it can run on any hardware with an appropriate JVM. And J2EE isn't software exactly, since many vendors provide J2EE-compatible systems, and even provide their own JVMs.

J2EE is a platform-independent, Java-centric environment from Sun for developing, building and deploying Web-based enterprise applications
online.

The J2EE platform is a collection of related technology specifications that describe required APIs and policies. The content of the specifications is controlled by the Java Community Process (JCP). Interested vendors come to consensus on the specifications' contents, and then compete on implementations of those specifications. The J2EE platform consists of a set of services, APIs, and protocols that provide the functionality for developing multitiered, Web-based applications.

Some benefits of deploying to a J2EE-compliant architecture include:

1. A simplified architecture that is based on standard components, services, and clients. The architecture maximizes the write-once, run-anywhere Java technology.

2. Services providing integration with existing systems, including Java DataBase Connectivity (JDBC); Java Message Service (JMS); Java Connector Architecture (JCA); Java Interface Definition Language (Java IDL); the JavaMail API; and Java Transaction API (JTA and JTS) for reliable business transactions.

3. Scalability to meet demand, by distributing containers across multiple systems and using database connection pooling, for example.

4. A better choice of application development tools and components from vendors providing standard solutions.

5. A flexible security model that provides single sign-on support, integration with legacy security schemes, and a unified approach to securing application components.

Hope this is useful!

What is Software Framework

A software framework is an abstraction in which common code providing generic functionality. Frameworks are a special case of software libraries in that they are reusable abstractions of code wrapped in a well-defined Application programming interface (API).

Software frameworks have these distinguishing features.
1. The overall program's flow of control is not dictated by the caller, but by the framework itself.
2. A framework has a default behavior.
3. A framework can be extended by the user usually by selective overriding or specialized by user code providing specific functionality.
4. In general, the framework code is not allowed to be modified. Users can extend the framework, but can not modify its code.
5. It makes it easier to work with complex technologies

A software framework may include support programs, code libraries, a scripting language, or other software to help develop and glue together the different components of a software project. Various parts of the framework may be exposed through an API.

The purpose of a framework is to improve the efficiency of creating new software. Frameworks can improve developer productivity and improve the quality, reliability and robustness of new software. Developer productivity is improved by allowing developers to focus on the unique requirements of their application instead of spending time on application infrastructure. It also helps in modularity, easier maintenance, and shorter development times.

The main idea on frameworks is, that there is an almost ready to go application, which you can use and expand for your own demands.
There are several frameworks. To name a few like - Struts, JSF, Toplink, Spring, Log4J, J2EE, -

Hope this is useful!

What is Design Pattern

In software engineering, a design pattern is a general reusable solution to a commonly occurring problem in software design that occurs within a context. A design pattern is not a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations. Design patterns reside in the domain of modules and interconnections.

Design Patterns is an object-oriented development methodology providing a proven structure and characteristics for building highly maintainable and extendible software. This methodology presents patterns for managing object creation, composing objects into larger structures, and coordinating control flow between objects, thus offering timeless and elegant solutions to common problems in software design. Design Patterns can improve the structure of software, facilitate maintenance, and help avoid architectural drift.

The purpose of Design Patterns is to capture software solutions that have been discovered, developed and evolved over time, and make them reusable. The reusability and flexibility of code allows finding consistent, well-engineered object-oriented designs appropriate for the needs of the particular application instead of having to repeat the problem and solution again and again. Successful reuse of well-designed and well-tested software components improves software productivity, quality and reliability.

Hope this is useful!

What is Software Architecture

The software architecture of a program or computing system is the structure or structures of the system, which comprise software components, the externally visible properties of those components, and the relationships between them.

Architecture serves as the blueprint for both the system and the project developing it, defining the work assignments that must be carried out by design and implementation teams. The architecture is the primary carrier of system qualities, such as performance, modifiability, and security, none of which can be achieved without a unifying architectural vision. Architecture is an artifact for early analysis to make sure that the design approach will yield an acceptable system. Architecture holds the key to post-deployment system understanding, maintenance, and mining efforts. In short, architecture is the conceptual glue that holds every phase of the project together for all its many stakeholders.

Benefits
When you take the time to properly design, implement, document, and evaluate a software architecture, you can

* predict, achieve, and control quality attribute behavior and make practical tradeoffs early
* greatly reduce the failure rates of software projects
* produce a rationale for certain architectural decisions made or not made
* communicate with your stakeholders
* reason about and manage change
* enable more accurate cost and schedule estimates
* create evolutionary prototypes
* predict and mitigate risks
* understand the tradeoffs inherent in the architectures of software-intensive systems
* provides insight into how quality goals interact—that is, how they trade off
* plan your staffing needs

Hope this is useful!

Business Object/Domain Object

A business object is a an entity. That is an actor inside the business layer in a multi-tiered system of object-oriented computer programs. A business object, itself usually does nothing but holds a set of instance variables or properties, known as attributes and associations with other business objects, a map of objects representing the business relationships. It communicates across the tiers in a multi-tiered system.

Business objects are sometimes called domain objects (where the word domain means the business).

Good business objects will encapsulate all of the data and behavior associated with the entity that it represents.
For example, an order object will have the sole responsibility for loading an order from a database, exposing or modifying any data associated with that order (i.e. order number, the order's customer account), and saving the order back to the database.

A domain object is an object from a domain model. It encapsulates only business rules and logic. Domain objects are Java classes that perform operations on data objects and provide data for presentation.

Domain objects contain logic particular to a business domain, such as managing users or credit cards. This logic operates over a persistent data object that contains the state necessary to implement the domain specific logic. Domain objects contain the application logic specific to the domain that require representing persistent state.

The purpose of the DomainObject class is to encapsulate access to one or more types of data objects. A number of methods, such as the save and delete methods, are delegated to the data object. The domain object, part of the application logic layer, is acting as a facade for an operation of the data object, part of the persistence layer. This is an interface between the persistence and application logic layers and one point where the two layers connect.

Domain objects are responsible for providing an interface to create, retrieve, update, and delete (the CRUD methods).

Hope this is useful!

Data Object

Data objects are useful for storing and retrieving data. However, in order to support other behavioral methods, the data object is used within domain objects. A data object does not need to be used within a domain object, and a data object may be used by multiple domain objects.

Java One Liner...

Blog on First Java One Liner
6. Architectural patterns that are larger in scope, usually describing an overall pattern followed by an entire system.
7. In software engineering, a design pattern is a general reusable solution to a commonly occurring problem in software design. A design pattern is not a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations.
8. Object-oriented design patterns typically show relationships and interactions between classes or objects, without specifying the final application classes or objects that are involved.
9. The amount of data transferred from one place to another or processed in a specified amount of time. Data transfer rates for disk drives and networks are measured in terms of throughput. Typically, throughputs are measured in Kbps, Mbps and Gbps.
10. Java Virtual Machine. A software "execution engine" in a browser, application or Oracle database that runs compiled java byte code (in class files).
11. Java Virtual Machine - Also called a "Java Interpreter", "Java Runtime" - Converts bytecode into OS specific commands.
12. A JVM is a piece of software that is responsible for running Java programs.
13. A domain model can be thought of as a conceptual model of a system which describes the various entities involved in that system and their relationships.
14. A use case is a description of a system's behaviour as it responds to a request that originates from outside of that system.
15. Domain objects are Java classes that perform operations on data objects and provide data for presentation.
16. A business object is a an entity. That is an actor inside the business layer in a multi-tiered system of object-oriented computer programs.
17. The delegation pattern means that a method of one object is implemented by relying completely on a method of another object.
18. In the world of software, a platform is a combination of hardware and software necessary to run applications.
19. The use case technique is used in software and systems engineering to capture the functional requirements of a system.
20. Use cases describe the interaction between a primary actor-the initiator of the interaction-and the system itself, represented as a sequence of simple steps.
21. Actors are something or someone which exist outside the system under study, and that take part in a sequence of activities in a dialogue with the system, to achieve some goal: they may be end users, other systems, or hardware devices.
22. The Document Object Model (DOM) is a platform- and language-independent standard object model for representing HTML or XML and related formats.
23. The DOM is required by JavaScript scripts that wish to inspect or modify a web page dynamically. In other words, the Document Object Model is the way JavaScript sees its containing HTML page and browser state.
24. A subset of the Java Development Kit (JDK) that contains the core executables and files that constitutes the standard Java platform. It includes the Java Virtual Machine (JVM), core classes, and supporting files. - Java Runtime Environment
25. A software package that can be used to write, compile, debug, and run Java applets and applications. - JDK
26. a JRE is a specific implementation of the the JVM, including the core libaries.
27. JVM is used for running the java software with the availablity of JRE which is different in a given environment.
28. Framework is a set of well designed components with the help of which applications can be built upon.
29. The main difference being that a framework is a physical and usable piece of code while a pattern is a logical design solution to a given kind of problem.
30. "A design pattern is a proven solution for a recurring design problem that occurs within a context." - Design Pattern
31. A web application framework is a software framework that is designed to support the development of dynamic websites, Web applications and Web services.
32. A software framework may include support programs, code libraries, a scripting language, or other software to help develop and glue together the different components of a software project. Various parts of the framework may be exposed through an API.
33. The software architecture of a program or computing system is the structure or structures of the system, which comprise software components, the externally visible properties of those components, and the relationships between them.
34. A system of principles, practices, and procedures applied to a specific branch of knowledge. - Methodology
35. The methodology includes the methods, procedures, and techniques used to collect and analyze information.
36. Software testing is the process used to assess the quality of computer software with respect to the context in which it is intended to operate.
37. SQA is a means of monitoring the software engineering processes and methods used to ensure quality.
38. This type of testing is also called sanity testing and is done in order to check if the application is ready for further major testing and is working properly without failing up to least expected level. - Smoke Testing
39. The application is tested against heavy load such as complex numerical values, large number of inputs, large number of queries etc. which checks for the stress/load the applications can withstand. - Stress Testing
40. the software is tested for the functional requirements. The tests are written in order to check if the application behaves as expected. - Functional Testing
41. The software is handed over to the user in order to find out if the software meets the user expectations and works as it is expected to. - User Acceptance Testing
42. The users are invited at the development center where they use the application and the developers note every particular input or action carried out by the user. Any type of abnormal behavior of the system is noted and rectified by the developers. - Alpha Testing
43. The software is distributed as a beta version to the users and users test the application at their sites. As the users explore the software, in case if any exception/defect occurs that is reported to the developers. - Beta Testing
44. White box testing strategy deals with the internal logic and structure of the code. White box testing is also called as glass, structural, open box or clear box testing.
45. Regression testing is any type of software testing which seeks to uncover regression bugs. Regression bugs occur whenever software functionality that previously worked as desired, stops working or no longer works in the same way that was previously planned.
46. Validation refers to meeting the needs of the intended end-user or customer.
47. Verification is the act of reviewing, inspecting, testing, etc. to establish and document that a product, service, or system meets the regulatory, standard, or specification requirements.
48. The tester only knows the inputs and what the expected outcomes should be and not how the program arrives at those outputs. - Black Box Testing
49. A method of testing software that tests the functionality of an application as opposed to its internal structures or workings. - Black Box
50. In Black Box, test cases are built around specifications and requirements (what the application is supposed to do). It uses external descriptions of the software, including specifications, requirements, and design to derive test cases.
51. Black Box can be applied to all levels of software testing; such as unit, integration, functional, system and acceptance.
52. White/Glass Box Testing Strategy can be applied to Unit Testing, Static and dynamic Analysis, Statement Coverage, Branch Coverage, Security Testing and Mutation Testing.
53. White-box test design techniques include Control flow testing, Data flow testing, Branch testing and Path testing.
54. Black-box test design techniques include Decision table testing, All-pairs testing, State transition tables, Equivalence partitioning, Boundary value analysis
55. A framework is usually made of several patterns implementation.
56. Every framework provides the basic building blocks for building your own systems according to your needs.
57. In software development, a Framework is a defined support structure in which another software project can be organized and developed.
58. A software framework is a re-usable design for a software system (or subsystem).