1. The UML gives everyone from business analyst to designer to programmer a common vocabulary to talk about software design.
2. Use Case diagrams help you specify the user goals that the system must carry out.
3. Class diagrams show the physical structure of the objects in the system and their static relationships.
4. Sequence and collaboration diagrams show the dynamic interactions between instances used to carry out a single use case.
5. Use case diagrams describe what a system does from the standpoint of an external observer. The emphasis is on what a system does rather than how.
6. A model is an abstraction of the underlying problem.
7. The domain is the actual world from which the problem comes.
8. Models consist of objects that interact by sending each other messages.
9. Objects have things they know (attributes) and things they can do (behaviors or operations). The values of an object's attributes determine its state.
10. Classes are the "blueprints" for objects. A class wraps attributes (data) and behaviors (methods or functions) into a single distinct entity.
11. Objects are instances of classes.
12. An actor is a person, organization, or external system that plays a role in one or more interactions with your system.
13. Use Cases are used to specify the functional requirements of the system.
Thursday, December 23, 2010
Wednesday, December 22, 2010
UML: Unified Modeling Language
Unified Modeling Language or UML is the standard language for describing, visualizing, and documenting the object-oriented (OO) systems. UML is a collection of a variety of diagrams for different purposes and each type of diagram models a particular aspect of OO design in an easy to understand and visual manner.
The UML standard specifies exactly how the diagrams are to be drawn and what each component in the diagram means. UML is not dependent on any particular programming language, instead it focuses one the fundamental concepts and ideas that model a system.
It is a standardized language in which to specify the artefacts and components of a software system, how the diagrams are to be drawn and what each component in the diagram means. It is important to understand that the UML describes a notation and not a process. It does not put forth a single method or process of design, but rather is a standardized tool that can be used in a design process.
The UML gives everyone from business analyst to designer to programmer a common vocabulary to talk about software design.
The UML standard specifies exactly how the diagrams are to be drawn and what each component in the diagram means. UML is not dependent on any particular programming language, instead it focuses one the fundamental concepts and ideas that model a system.
It is a standardized language in which to specify the artefacts and components of a software system, how the diagrams are to be drawn and what each component in the diagram means. It is important to understand that the UML describes a notation and not a process. It does not put forth a single method or process of design, but rather is a standardized tool that can be used in a design process.
The UML gives everyone from business analyst to designer to programmer a common vocabulary to talk about software design.
Friday, October 1, 2010
Programmatic instantiation of Components like servlets, filters, and listeners
With programmatic definition, we can instantiate components programmatically and then configure them. Servlet 3.0 Specification supports dynamic instantiation of servlets and filters.
In this example, we will see how you might programmatically instantiate servlets, filters, and listeners.
@WebListener
public class MyServletContextListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent sce) {
LOG.info("Context Listener Initialized");
doProgrammaticRegistration(sce.getServletContext());
}
private void doProgrammaticRegistration(ServletContext sc) {
// servlet definition
ServletRegistration.Dynamic dynaServlet = sc.addServlet(
"MyProgrammaticServlet",
"com.servlets.MyProgrammaticServlet");
dynaServlet.addMapping("/myprogrammaticservlet");
// filter definition
FilterRegistration.Dynamic dynaFilter = sc.addFilter(
"MyProgrammaticFilter",
"com.filters.MyProgrammaticFilter");
EnumSet dispatcherType = EnumSet.of(
DispatcherType.REQUEST, DispatcherType.FORWARD);
dynaFilter.addMappingForServletNames(dispatcherType, true,
"MyProgrammaticServlet");
}
}
As shown, during context initialization, we instantiate a new servlet and returned class ServletRegistration.Dynamic instance is used to configure the appropriate servlet mapping. We do the similar steps with a filter. These steps are similar to what would have happened when a servlet container encountered the <servlet>, <servlet-mapping>, <filter> and <filter-mapping> elements in a web deployment descriptor.
As it can be seen in the next code listings, the servlet and filter are rather straightforward. Since the configuration occurs programmatically, they do not even need any annotations to be used.
//Note: not even an annotation is required
public class MyProgrammaticFilter implements Filter {
private final Logger LOG = Logger.getLogger("MyProgrammaticFilter");
public void destroy() { }
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws ServletException, IOException {
LOG.info("Filtering: " + ((HttpServletRequest)req).getRequestURI());
chain.doFilter(req, resp);
}
public void init(FilterConfig config) throws ServletException {
LOG.info("Filter: " + "Initializing ProgrammaticFilter");
}
}
//Note: not even an annotation is required.
public class MyProgrammaticServlet extends HttpServlet {
private final Logger LOG = Logger.getLogger("MyProgrammaticServlet");
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
LOG.info("Within request : " + getServletName());
String html = "Added programmatically (no annotation/web.xml entries): " + new Date();
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(html);
}
}
Hope this will help.
In this example, we will see how you might programmatically instantiate servlets, filters, and listeners.
@WebListener
public class MyServletContextListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent sce) {
LOG.info("Context Listener Initialized");
doProgrammaticRegistration(sce.getServletContext());
}
private void doProgrammaticRegistration(ServletContext sc) {
// servlet definition
ServletRegistration.Dynamic dynaServlet = sc.addServlet(
"MyProgrammaticServlet",
"com.servlets.MyProgrammaticServlet");
dynaServlet.addMapping("/myprogrammaticservlet");
// filter definition
FilterRegistration.Dynamic dynaFilter = sc.addFilter(
"MyProgrammaticFilter",
"com.filters.MyProgrammaticFilter");
EnumSet
DispatcherType.REQUEST, DispatcherType.FORWARD);
dynaFilter.addMappingForServletNames(dispatcherType, true,
"MyProgrammaticServlet");
}
}
As shown, during context initialization, we instantiate a new servlet and returned class ServletRegistration.Dynamic instance is used to configure the appropriate servlet mapping. We do the similar steps with a filter. These steps are similar to what would have happened when a servlet container encountered the <servlet>, <servlet-mapping>, <filter> and <filter-mapping> elements in a web deployment descriptor.
As it can be seen in the next code listings, the servlet and filter are rather straightforward. Since the configuration occurs programmatically, they do not even need any annotations to be used.
//Note: not even an annotation is required
public class MyProgrammaticFilter implements Filter {
private final Logger LOG = Logger.getLogger("MyProgrammaticFilter");
public void destroy() { }
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws ServletException, IOException {
LOG.info("Filtering: " + ((HttpServletRequest)req).getRequestURI());
chain.doFilter(req, resp);
}
public void init(FilterConfig config) throws ServletException {
LOG.info("Filter: " + "Initializing ProgrammaticFilter");
}
}
//Note: not even an annotation is required.
public class MyProgrammaticServlet extends HttpServlet {
private final Logger LOG = Logger.getLogger("MyProgrammaticServlet");
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
LOG.info("Within request : " + getServletName());
String html = "Added programmatically (no annotation/web.xml entries): " + new Date();
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(html);
}
}
Hope this will help.
Servlet 3.0 Annotations
Servlet 3.0 Specification has a number of new features and one of them is annotation. When an application loads, all classes into the application are examined for presence of the annotations. When these annotations are found on a particular class, the container registers instances of the classes as Listeners, Servlets, or Filters based on the annotation.
Servlet 3.0 Specification Annotations are as follows.
* @WebServlet
* @WebFilter
* @WebInitParam
* @WebListner
* @MultipartConfig
@WebServlet
This annotation is used to define a Servlet component in a web application and defines the metadata about the servlet being declared.
Classes annotated with @WebServlet annotation must extend javax.servlet.http.HttpServlet class.
@WebServlet annotation annotation has the following attributes.
* name
* description
* value
* urlPatterns
* initParams
* loadOnStartup
* asyncSupported
* smallIcon
* largeIcon
Note: the spec mandates either value or urlPatterns attribute be specififed.
Example:
@WebServlet(name = "myservlet", urlPatterns = { "/myservlet" })
public class MyServletExample extends HttpServlet {
}
@WebFilter
This annotation is used to define a filter in web application. The classes annotated with @WebFilter annotation must implement javax.servlet.Filter interface.
The @WebFilter annotation has the following attributes
* filterName
* description
* displayName
* initParams
* servletNames
* value
* urlPatterns
* dispatcherTypes
* asyncSupported
Example:
@WebFilter(filterName="samplefilter", urlPatterns={"/foo/*", "/bar"})
public class MyServletSampleFilter implements Filter {
}
@WebInitParam
This annotation is used to specify any init parameters that must be passed to the Servlet or the Filter.
The annotation defines the following attributes:
* name
* value
* description
Example:
@WebServlet(value="/hello",
initParams = {
@WebInitParam(name="name1", value="Hello "),
@WebInitParam(name="name2", value=" World!")
})
public class MyHelloServletExample extends HttpServlet {
}
@WebListner
This annotation is used to define a listener. The @WebListener annotation is used to register the following types of listeners
1. Context Listener (javax.servlet.ServletContextListener)
2. Context Attribute Listener (javax.servlet.ServletContextAttributeListener)
3. Servlet Request Listener (javax.servlet.ServletRequestListener)
4. Servlet Request Attribute Listener (javax.servlet.ServletRequestAttributeListener)
5. Http Session Listener (javax.servlet.http.HttpSessionListener)
6. Http Session Attribute Listener (javax.servlet.http.HttpSessionAttributeListener)
@WebListener is the easiest to use. Registering ServletContextListener.
Example:
@WebListener()
public class MySampleContextListner extends ServletContextListner {
public void contextInitialized(ServletContextEvent event) {
//do some thing on application init
}
public void contextDestroyed(ServletContextEvent event) {
//do some thing on application destroy
}
}
@MultipartConfig
Servlet 3.0 specification comes with the built in file upload support. This annotation, when specified on a Servlet, indicates that the request it expects is of type mime/multipart. The HttpServletRequest object of the corresponding servlet makes available the mime attachments via the getParts and getPart methods to iterate over the various mime attachments.
The @MultipartConfig annotation can be used to specify the location where the files can be stored, maximum size of the file being uploaded, maximum request size and the size threshold after which the file will be written to the disk. There is any equivalent element in web.xml that can be used for the same purpose.
@MultipartConfig annotation declares the following attributes:
* location
* maxFileSize
* maxRequestSize
* fileSizeThreshold
Example:
@WebServlet(name="UploadServlet", urlPatterns={"/upload"})
@MultipartConfig(location="d://tmp")
public class MyServletExample extends HttpServlet {
public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//target directory and location are the same.
req.getPart("content").write("file.txt");
}
}
Hope this will help.
Servlet 3.0 Specification Annotations are as follows.
* @WebServlet
* @WebFilter
* @WebInitParam
* @WebListner
* @MultipartConfig
@WebServlet
This annotation is used to define a Servlet component in a web application and defines the metadata about the servlet being declared.
Classes annotated with @WebServlet annotation must extend javax.servlet.http.HttpServlet class.
@WebServlet annotation annotation has the following attributes.
* name
* description
* value
* urlPatterns
* initParams
* loadOnStartup
* asyncSupported
* smallIcon
* largeIcon
Note: the spec mandates either value or urlPatterns attribute be specififed.
Example:
@WebServlet(name = "myservlet", urlPatterns = { "/myservlet" })
public class MyServletExample extends HttpServlet {
}
@WebFilter
This annotation is used to define a filter in web application. The classes annotated with @WebFilter annotation must implement javax.servlet.Filter interface.
The @WebFilter annotation has the following attributes
* filterName
* description
* displayName
* initParams
* servletNames
* value
* urlPatterns
* dispatcherTypes
* asyncSupported
Example:
@WebFilter(filterName="samplefilter", urlPatterns={"/foo/*", "/bar"})
public class MyServletSampleFilter implements Filter {
}
@WebInitParam
This annotation is used to specify any init parameters that must be passed to the Servlet or the Filter.
The annotation defines the following attributes:
* name
* value
* description
Example:
@WebServlet(value="/hello",
initParams = {
@WebInitParam(name="name1", value="Hello "),
@WebInitParam(name="name2", value=" World!")
})
public class MyHelloServletExample extends HttpServlet {
}
@WebListner
This annotation is used to define a listener. The @WebListener annotation is used to register the following types of listeners
1. Context Listener (javax.servlet.ServletContextListener)
2. Context Attribute Listener (javax.servlet.ServletContextAttributeListener)
3. Servlet Request Listener (javax.servlet.ServletRequestListener)
4. Servlet Request Attribute Listener (javax.servlet.ServletRequestAttributeListener)
5. Http Session Listener (javax.servlet.http.HttpSessionListener)
6. Http Session Attribute Listener (javax.servlet.http.HttpSessionAttributeListener)
@WebListener is the easiest to use. Registering ServletContextListener.
Example:
@WebListener()
public class MySampleContextListner extends ServletContextListner {
public void contextInitialized(ServletContextEvent event) {
//do some thing on application init
}
public void contextDestroyed(ServletContextEvent event) {
//do some thing on application destroy
}
}
@MultipartConfig
Servlet 3.0 specification comes with the built in file upload support. This annotation, when specified on a Servlet, indicates that the request it expects is of type mime/multipart. The HttpServletRequest object of the corresponding servlet makes available the mime attachments via the getParts and getPart methods to iterate over the various mime attachments.
The @MultipartConfig annotation can be used to specify the location where the files can be stored, maximum size of the file being uploaded, maximum request size and the size threshold after which the file will be written to the disk. There is any equivalent
@MultipartConfig annotation declares the following attributes:
* location
* maxFileSize
* maxRequestSize
* fileSizeThreshold
Example:
@WebServlet(name="UploadServlet", urlPatterns={"/upload"})
@MultipartConfig(location="d://tmp")
public class MyServletExample extends HttpServlet {
public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//target directory and location are the same.
req.getPart("content").write("file.txt");
}
}
Hope this will help.
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.
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
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.
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
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.
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.
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!
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!
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!
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!
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!
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!
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).
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).
Friday, August 20, 2010
Java Common Mistakes (Part 1)
1. Returning Null, a method which returns a collection or an array,
Null should never be returned from a method returning a collection or an array. Instead return a empty array (a static final empty array) or one of the empty collections (e.g. Collections.EMPTY_LIST assuming the client should not be modifying the collection).
2. Unnecessary use of thread safety of StringBuffer
Use StringBuilder rather then StringBuffer, unless synchronization is required. StringBuilder is not thread safe, and therefore avoids the synchronization overhead of StringBuffer.
3. Not taking advantage of ‘toString()’
Overriding toString() method gives you a cheap way to provide human-readable labels for objects in output.
Bad:
System.out.println("Author: "+person.getName());
Good:
class Person {
...
public String toString() {
return this.getName();
}
}
...
System.out.println("Author: "+person);
4. Instatiation of immutable objects
Creating new instances of immutable primitive type wrappers (such as Number subclasses and Booleans) wastes the memory and time needed for allocating new objects. Static valueOf() method works much faster than a constructor and saves the memory, as it caches frequently used instances.
Bad:
Integer i = new Integer(0);
Boolean b = new Boolean(true);
Good:
Integer i = Integer.valueOf(0);
Boolean b = Boolean.valueOf(true); // or Boolean.TRUE
5. Unbuffered I/O
Reading and writing I/O streams byte-by-byte is too expensive, as every read()/write() call refers to the underlying native (JNI) I/O subsystem. Usage of buffered streams reduces the number of native calls and improves I/O performance considerably.
Bad:
InputStream in = new BufferedInputStream(new FileInputStream(f));
...
6. ‘equals()’ does not check for null argument
If you override equals() method in your class, always check if an argument is null. If a null value is passed, equals() must unconditionally return false (no NullPointerException should be thrown!).
Bad:
class Person {
...
public boolean equals(Object o) {
return (o instanceof Person) &&
this.getName().equals(((Person)o).getName());
}
...
}
Good:
class Person {
...
public boolean equals(Object o) {
return (o != null) &&
(o instanceof Person) &&
this.getName().equals(((Person)o).getName());
}
...
}
class Person {
…
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Person))
return false;
Person that = (Person)o;
….
7. ‘equals()’ is overridden while ‘hashCode()’ is not
If you override equals() in your class, always provide a custom implementation of hashCode() that returns the same hash code value for two or more equal objects:
a.equals(b) ? a.hashCode() == b.hashCode()
This is, in fact, a general contract defined by Java API Specification. Violation of this rule (which is likely the case if equals() method is overridden while hashCode() is inherited from Object) may cause numerous bugs and unexpected behaviours.
Note that the reverse rule: two or more unequal objects must have different hash codes, or
!a.equals(b) ? a.hashCode() != b.hashCode()
8. Difference between == and .Equals() Method
Value Type: == and .Equals() methods compare two objects by value.
Ex: int a = 5; int b = 5;
Console.WriteLine(a==b); Output: true
Console.writeLine(a.Equals(b)); Output: true
Reference Type: == performs an identity comparison, i.e. it will only return true if both references point to the same object.
While Equals() method is expected to perform a value comparison.
Ex: StringBuilder s1 = new StringBuilder(“Yup”);
StringBuilder s2 = new StringBuilder(“Yup”);
Console.WriteLine(s1==s2); Output : false
Console.WriteLine(s1.Equals(s2)); Output: true
In above example, s1 and s2 are different objects hence “==” returns false, but they are equivalent hence “Equals()” method returns true.
Note: There is an exception of this rule, i.e. when you use “==” operator with string class it compares value rather than identity.
When To use:
For value comparison, with Value Tyep use “==” operator and use “Equals()” method while performing value comparison with Reference Type.
Null should never be returned from a method returning a collection or an array. Instead return a empty array (a static final empty array) or one of the empty collections (e.g. Collections.EMPTY_LIST assuming the client should not be modifying the collection).
2. Unnecessary use of thread safety of StringBuffer
Use StringBuilder rather then StringBuffer, unless synchronization is required. StringBuilder is not thread safe, and therefore avoids the synchronization overhead of StringBuffer.
3. Not taking advantage of ‘toString()’
Overriding toString() method gives you a cheap way to provide human-readable labels for objects in output.
Bad:
System.out.println("Author: "+person.getName());
Good:
class Person {
...
public String toString() {
return this.getName();
}
}
...
System.out.println("Author: "+person);
4. Instatiation of immutable objects
Creating new instances of immutable primitive type wrappers (such as Number subclasses and Booleans) wastes the memory and time needed for allocating new objects. Static valueOf() method works much faster than a constructor and saves the memory, as it caches frequently used instances.
Bad:
Integer i = new Integer(0);
Boolean b = new Boolean(true);
Good:
Integer i = Integer.valueOf(0);
Boolean b = Boolean.valueOf(true); // or Boolean.TRUE
5. Unbuffered I/O
Reading and writing I/O streams byte-by-byte is too expensive, as every read()/write() call refers to the underlying native (JNI) I/O subsystem. Usage of buffered streams reduces the number of native calls and improves I/O performance considerably.
Bad:
InputStream in = new FileInputStream(f); int b; while ((b = in.read()) != -1) { ... }Good:
InputStream in = new BufferedInputStream(new FileInputStream(f));
...
6. ‘equals()’ does not check for null argument
If you override equals() method in your class, always check if an argument is null. If a null value is passed, equals() must unconditionally return false (no NullPointerException should be thrown!).
Bad:
class Person {
...
public boolean equals(Object o) {
return (o instanceof Person) &&
this.getName().equals(((Person)o).getName());
}
...
}
Good:
class Person {
...
public boolean equals(Object o) {
return (o != null) &&
(o instanceof Person) &&
this.getName().equals(((Person)o).getName());
}
...
}
class Person {
…
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Person))
return false;
Person that = (Person)o;
….
7. ‘equals()’ is overridden while ‘hashCode()’ is not
If you override equals() in your class, always provide a custom implementation of hashCode() that returns the same hash code value for two or more equal objects:
a.equals(b) ? a.hashCode() == b.hashCode()
This is, in fact, a general contract defined by Java API Specification. Violation of this rule (which is likely the case if equals() method is overridden while hashCode() is inherited from Object) may cause numerous bugs and unexpected behaviours.
Note that the reverse rule: two or more unequal objects must have different hash codes, or
!a.equals(b) ? a.hashCode() != b.hashCode()
8. Difference between == and .Equals() Method
Value Type: == and .Equals() methods compare two objects by value.
Ex: int a = 5; int b = 5;
Console.WriteLine(a==b); Output: true
Console.writeLine(a.Equals(b)); Output: true
Reference Type: == performs an identity comparison, i.e. it will only return true if both references point to the same object.
While Equals() method is expected to perform a value comparison.
Ex: StringBuilder s1 = new StringBuilder(“Yup”);
StringBuilder s2 = new StringBuilder(“Yup”);
Console.WriteLine(s1==s2); Output : false
Console.WriteLine(s1.Equals(s2)); Output: true
In above example, s1 and s2 are different objects hence “==” returns false, but they are equivalent hence “Equals()” method returns true.
Note: There is an exception of this rule, i.e. when you use “==” operator with string class it compares value rather than identity.
When To use:
For value comparison, with Value Tyep use “==” operator and use “Equals()” method while performing value comparison with Reference Type.
HTTP DIGEST Authentication
HTTP digest authentication is performed by the browser upon request by the web server and based on a username, password, and realm. However, in this case your password is digested with the secure MD5 algorithm before it is sent by the browser.
Digest Authentication is just like HTTP BASIC Authentication. The only difference between basic and digest authentication is the specification of the authentication method and password encryption method.
Digest authentication is specified in an application's deployment descriptor as follows:
<login-config>
<auth-method>DIGEST</auth-method>
<realm-name>Digest Authentication Example</realm-name>
</login-config>
Hope this is useful! Enjoy!
Digest Authentication is just like HTTP BASIC Authentication. The only difference between basic and digest authentication is the specification of the authentication method and password encryption method.
Digest authentication is specified in an application's deployment descriptor as follows:
<login-config>
<auth-method>DIGEST</auth-method>
<realm-name>Digest Authentication Example</realm-name>
</login-config>
Hope this is useful! Enjoy!
HTTP Form Authentication
Form-based authentication is defined in the servlet specification. Form-based authentication allows you to control the look and feel of the login page and login-error page. When a client attempts to access a protected web resource, the web container activates the Form based authentication mechanism that has been configured for that resource and a login page is displayed. If the login is successfull then the pretected resource is displayed or an error page is displayed if login fails.
Form-based authentication is not secure because passwords are transmitted as clear text.
Form-based authentication works like basic authentication. Form-based Authentication with Tomcat Server 6 requires the following steps:
1. Create a login page.
In a Form-based authentication, username, password form fields and form action are defined in the Servlet Specification. They are j_username, j_password, and j_security_check respectively. They must be used for Form-based login.
Example /login.jsp:
<form action='j_security_check' method='post'>
<table>
<tr><td>Name:</td>
<td><input type='text' name='j_username'></td></tr>
<tr><td>Password:</td>
<td><input type='password' name='j_password' size='8'></td>
</tr>
</table>
<input type='submit' value='login'>
</form>
2. Create an error page that will be displayed if login fails.
The error page displays an error message and provides a link back to the login page.
Example /error.jsp:
<html> <head> <title>Error!</title></head>
<body>
<font size='4' color='red'>
The username and password you supplied are not valid.
</p>
Click <a href='<%= response.encodeURL("login.jsp") %>'>here</a> to retry login </body> </form> </html> 3. In the deployment descriptor, specify FORM as the authentication method, login page and error page. Page is only accessed by role1 and role2 Example /WEB-INF/web.xml: <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2.2.dtd"> <web-app> <security-constraint>
<web-resource-collection>
<web-resource-name>protected resource page</web-resource-name>
<url-pattern>/protected-page.jsp</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>role1</role-name>
<role-name>role2</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>FORM</auth-method>
<realm-name>Form Authentication Example</realm-name>
<form-login-page>/login.jsp</form-login-page>
<form-error-page>/error.jsp</form-error-page>
</form-login-config>
</login-config>
</web-app>
4. In Tomcat 6 Server, usernames and passwords are associated with roles in $TOMCAT_HOME/conf/tomcat-users.xml,
<tomcat-users>
<user name="user1" password="password" roles="role1" />
<user name="user2" password="passwd" roles="role2" />
</tomcat-users>
5. You are done. Now, restart the Tomcat 6 Server and try to access the protected resource from Browser.
Hope this is useful! Enjoy!
Form-based authentication is not secure because passwords are transmitted as clear text.
Form-based authentication works like basic authentication. Form-based Authentication with Tomcat Server 6 requires the following steps:
1. Create a login page.
In a Form-based authentication, username, password form fields and form action are defined in the Servlet Specification. They are j_username, j_password, and j_security_check respectively. They must be used for Form-based login.
Example /login.jsp:
<form action='j_security_check' method='post'>
<table>
<tr><td>Name:</td>
<td><input type='text' name='j_username'></td></tr>
<tr><td>Password:</td>
<td><input type='password' name='j_password' size='8'></td>
</tr>
</table>
<input type='submit' value='login'>
</form>
2. Create an error page that will be displayed if login fails.
The error page displays an error message and provides a link back to the login page.
Example /error.jsp:
<html> <head> <title>Error!</title></head>
<body>
<font size='4' color='red'>
The username and password you supplied are not valid.
</p>
Click <a href='<%= response.encodeURL("login.jsp") %>'>here</a> to retry login </body> </form> </html> 3. In the deployment descriptor, specify FORM as the authentication method, login page and error page. Page is only accessed by role1 and role2 Example /WEB-INF/web.xml: <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2.2.dtd"> <web-app> <security-constraint>
<web-resource-collection>
<web-resource-name>protected resource page</web-resource-name>
<url-pattern>/protected-page.jsp</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>role1</role-name>
<role-name>role2</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>FORM</auth-method>
<realm-name>Form Authentication Example</realm-name>
<form-login-page>/login.jsp</form-login-page>
<form-error-page>/error.jsp</form-error-page>
</form-login-config>
</login-config>
</web-app>
4. In Tomcat 6 Server, usernames and passwords are associated with roles in $TOMCAT_HOME/conf/tomcat-users.xml,
<tomcat-users>
<user name="user1" password="password" roles="role1" />
<user name="user2" password="passwd" roles="role2" />
</tomcat-users>
5. You are done. Now, restart the Tomcat 6 Server and try to access the protected resource from Browser.
Hope this is useful! Enjoy!
HTTP Basic Authentication
Basic authentication is defined by the HTTP/1.1 specification. It is very simple HTTP authentication method. When a client attempts to access a protected web resource, the web container activates the HTTP authentication mechanism that has been configured for that resource and the server prompts for a username and password. If the server will be able to authenticate client, then provides access to the resource otherwise the it will not be granted access to the resource and the process repeats.
HTTP basic authentication is not particularly secure. It sends user names and passwords over the Internet as text that is uu-encoded (Unix-to-Unix encoded) but not encrypted.
Basic authentication follows the steps below
1. An attempt is made to access a protected JSP page—/protected-page.jsp.
Example JSP page /protected-page.jsp:
<html><head><title>A Protected Page</title></head>
<body>
<p>
User principal: <%= request.getUserPrincipal().getName() %>.<br/>
User name: <%= request.getRemoteUser() %>.<br/>
Request Authenticated with: <%= request.getAuthType() %>.<br/>
</p>
<p>
<% if(request.isUserInRole("role1")) { %>
You are in role1<br/>
<% } else {%>
You are not in role2<br/>
<% } %>
<% if(request.isUserInRole("role2")) { %>
You are in role2<br/>
<% } else {%>
You are not in role1<br/>
<% } %>
</p>
</body>
</html>
The client is presented with a dialog box asking for name and password. The client submits the user name and password to the server. After authentication, the JSP page is displayed.
2. The protected JSP page is specified as a protected resource in the application's deployment descriptor file, web.xml. Also, specified BASIC as the authentication method and page is only accessed by role1 and role2.
Example deployment descriptor /WEB-INF/web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2.2.dtd">
<web-app>
<security-constraint>
<web-resource-collection>
<web-resource-name>protected resource page</web-resource-name>
<url-pattern>/protected-page.jsp</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>role1</role-name>
<role-name>role2</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>Basic Authentication Example</realm-name>
</login-config>
</web-app>
3. In Tomcat 6 Server, usernames and passwords are associated with roles in $TOMCAT_HOME/conf/tomcat-users.xml,
<tomcat-users>
<user name="user1" password="password" roles="role1" />
<user name="user2" password="passwd" roles="role2" />
</tomcat-users>
4. You are done. Now, restart the Tomcat 6 Server and try to access the protected resource from Browser.
Hope this is useful! Enjoy!
HTTP basic authentication is not particularly secure. It sends user names and passwords over the Internet as text that is uu-encoded (Unix-to-Unix encoded) but not encrypted.
Basic authentication follows the steps below
1. An attempt is made to access a protected JSP page—/protected-page.jsp.
Example JSP page /protected-page.jsp:
<html><head><title>A Protected Page</title></head>
<body>
<p>
User principal: <%= request.getUserPrincipal().getName() %>.<br/>
User name: <%= request.getRemoteUser() %>.<br/>
Request Authenticated with: <%= request.getAuthType() %>.<br/>
</p>
<p>
<% if(request.isUserInRole("role1")) { %>
You are in role1<br/>
<% } else {%>
You are not in role2<br/>
<% } %>
<% if(request.isUserInRole("role2")) { %>
You are in role2<br/>
<% } else {%>
You are not in role1<br/>
<% } %>
</p>
</body>
</html>
The client is presented with a dialog box asking for name and password. The client submits the user name and password to the server. After authentication, the JSP page is displayed.
2. The protected JSP page is specified as a protected resource in the application's deployment descriptor file, web.xml. Also, specified BASIC as the authentication method and page is only accessed by role1 and role2.
Example deployment descriptor /WEB-INF/web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2.2.dtd">
<web-app>
<security-constraint>
<web-resource-collection>
<web-resource-name>protected resource page</web-resource-name>
<url-pattern>/protected-page.jsp</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>role1</role-name>
<role-name>role2</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>Basic Authentication Example</realm-name>
</login-config>
</web-app>
3. In Tomcat 6 Server, usernames and passwords are associated with roles in $TOMCAT_HOME/conf/tomcat-users.xml,
<tomcat-users>
<user name="user1" password="password" roles="role1" />
<user name="user2" password="passwd" roles="role2" />
</tomcat-users>
4. You are done. Now, restart the Tomcat 6 Server and try to access the protected resource from Browser.
Hope this is useful! Enjoy!
Thursday, August 19, 2010
HTTP Authentication
In the context of HTTP transaction, when you try to access a protected web resource, the web container activates the authentication mechanism that has been configured for that resource.
You can specify the following authentication mechanisms:
* HTTP basic authentication
* Form-based login authentication
* Client certificate authentication
* Mutual authentication
* Digest authentication
HTTP basic authentication:
As the name implies, it is the simplest method of authentication and for a long time was the most common authentication method used.
Hope this is useful! Enjoy!
With basic authentication, the following steps occur:
1. A client will request to access a protected resource.
2. The web server returns a dialog box as a response to the client request that requests the user name and password.
3. The client submits the user name and password to the server.
4. The server validates the credentials in the specified realm and, if successful, returns the requested protected resource.
HTTP basic authentication is not particularly secure. Basic authentication sends user names and passwords over the Internet as text that is uu-encoded (Unix-to-Unix encoded) but not encrypted.
Form-based login authentication:
Form-based authentication works like basic authentication, except that you specify a login page that is displayed instead of a dialog and an error page that's displayed if login fails. Also form-based authentication allows you to control the look and feel of the login page.
With form-based authentication, the following steps occur:
1. A client will request to access a protected resource.
2. If the client is unauthenticated, the server redirects the client to a login page.
3. The client submits the login form to the server.
4. The server attempts to authenticate the user.
1. If the authentication succeeds, the authenticated user’s principal is checked to ensure it is in a role that is authorized to access the resource. If the user is authorized, the server redirects the client to the resource using the stored URL path.
2. If authentication fails, the client is forwarded or redirected to an error page.
Like basic authentication, form-based authentication is not secure because passwords are transmitted as clear text.
Client certificate authentication:
HTTPS Client Authentication requires the client to possess a Public Key Certificate (PKC). If you specify client authentication, the web server will authenticate the client using the client’s public key certificate.
HTTPS Client Authentication is a more secure method of authentication than either basic or form-based authentication. It uses HTTP over SSL (HTTPS), in which the server authenticates the client using the client’s Public Key Certificate (PKC). Secure Sockets Layer (SSL) technology provides data encryption, server authentication, message integrity, and optional client authentication for a TCP/IP connection. You can think of a public key certificate as the digital equivalent of a passport. It is issued by a trusted organization, which is called a certificate authority (CA), and provides identification for the bearer.
Mutual authentication:
The server and the client authenticate each other in mutual authentication. There are two types of mutual authentication:
1. Certificate-based mutual authentication
2. User name-password-based mutual authentication
In certificate-based mutual authentication, the following steps occur:
1. A client requests access to a protected resource.
2. The web server presents its certificate to the client.
3. The client verifies the server's certificate.
4. If successful, the client sends its certificate to the server.
5. The server verifies the client's credentials.
6. If successful, the server grants access to the protected resource requested by the client.
In user name-password-based mutual authentication, the following steps occur:
1. A client requests access to a protected resource.
2. The web server presents its certificate to the client.
3. The client verifies the server's certificate.
4. If successful, the client sends its user name and password to the server, which verifies the client's credentials.
5. If the verification is successful, the server grants access to the protected resource requested by the client.
Digest authentication:
HTTP digest authentication is like HTTP basic authentication. HTTP digest authentication authenticates a user based on a user name and a password. However, the authentication is performed by transmitting the password in an encrypted form which is much more secure than the simple base64 encoding used by basic authentication.
With digest-based authentication, the following steps occur:
1. A client will request to access a protected resource.
2. The web server returns a dialog box as a response to the client request that requests the user name and password.
3. The client submits the user name and password to the server.
4. The server validates the credentials in the specified realm and, if successful, returns the requested protected resource.
You can specify the following authentication mechanisms:
* HTTP basic authentication
* Form-based login authentication
* Client certificate authentication
* Mutual authentication
* Digest authentication
HTTP basic authentication:
As the name implies, it is the simplest method of authentication and for a long time was the most common authentication method used.
Hope this is useful! Enjoy!
With basic authentication, the following steps occur:
1. A client will request to access a protected resource.
2. The web server returns a dialog box as a response to the client request that requests the user name and password.
3. The client submits the user name and password to the server.
4. The server validates the credentials in the specified realm and, if successful, returns the requested protected resource.
HTTP basic authentication is not particularly secure. Basic authentication sends user names and passwords over the Internet as text that is uu-encoded (Unix-to-Unix encoded) but not encrypted.
Form-based login authentication:
Form-based authentication works like basic authentication, except that you specify a login page that is displayed instead of a dialog and an error page that's displayed if login fails. Also form-based authentication allows you to control the look and feel of the login page.
With form-based authentication, the following steps occur:
1. A client will request to access a protected resource.
2. If the client is unauthenticated, the server redirects the client to a login page.
3. The client submits the login form to the server.
4. The server attempts to authenticate the user.
1. If the authentication succeeds, the authenticated user’s principal is checked to ensure it is in a role that is authorized to access the resource. If the user is authorized, the server redirects the client to the resource using the stored URL path.
2. If authentication fails, the client is forwarded or redirected to an error page.
Like basic authentication, form-based authentication is not secure because passwords are transmitted as clear text.
Client certificate authentication:
HTTPS Client Authentication requires the client to possess a Public Key Certificate (PKC). If you specify client authentication, the web server will authenticate the client using the client’s public key certificate.
HTTPS Client Authentication is a more secure method of authentication than either basic or form-based authentication. It uses HTTP over SSL (HTTPS), in which the server authenticates the client using the client’s Public Key Certificate (PKC). Secure Sockets Layer (SSL) technology provides data encryption, server authentication, message integrity, and optional client authentication for a TCP/IP connection. You can think of a public key certificate as the digital equivalent of a passport. It is issued by a trusted organization, which is called a certificate authority (CA), and provides identification for the bearer.
Mutual authentication:
The server and the client authenticate each other in mutual authentication. There are two types of mutual authentication:
1. Certificate-based mutual authentication
2. User name-password-based mutual authentication
In certificate-based mutual authentication, the following steps occur:
1. A client requests access to a protected resource.
2. The web server presents its certificate to the client.
3. The client verifies the server's certificate.
4. If successful, the client sends its certificate to the server.
5. The server verifies the client's credentials.
6. If successful, the server grants access to the protected resource requested by the client.
In user name-password-based mutual authentication, the following steps occur:
1. A client requests access to a protected resource.
2. The web server presents its certificate to the client.
3. The client verifies the server's certificate.
4. If successful, the client sends its user name and password to the server, which verifies the client's credentials.
5. If the verification is successful, the server grants access to the protected resource requested by the client.
Digest authentication:
HTTP digest authentication is like HTTP basic authentication. HTTP digest authentication authenticates a user based on a user name and a password. However, the authentication is performed by transmitting the password in an encrypted form which is much more secure than the simple base64 encoding used by basic authentication.
With digest-based authentication, the following steps occur:
1. A client will request to access a protected resource.
2. The web server returns a dialog box as a response to the client request that requests the user name and password.
3. The client submits the user name and password to the server.
4. The server validates the credentials in the specified realm and, if successful, returns the requested protected resource.
Tuesday, August 10, 2010
javas...: Java One Liner...
javas...: Java One Liner...: "1. Static methods can not be overwritten. A call to a static method is dependent on the type of the identifier and not on the object's class..."
Thursday, August 5, 2010
Java One Liner...
1. Static methods can not be overwritten. A call to a static method is dependent on the type of the identifier and not on the object's class.
2. String fileContent = new Scanner(new File("test.txt" )).useDelimiter("\\z").next(); it reads in the entire file at once.
3. A Monostate object has static member variables only. So all instances of a Monostate class share the same state. This is a rare pattern and it is used less.
4. Antipatterns -- "a commonly occurring solution to a problem that generates decidedly negative consequences".
5. Use “==” operator while performing value comparison, with Value Type and use “Equals()” method while performing value comparison with Reference Type.
2. String fileContent = new Scanner(new File("test.txt" )).useDelimiter("\\z").next(); it reads in the entire file at once.
3. A Monostate object has static member variables only. So all instances of a Monostate class share the same state. This is a rare pattern and it is used less.
4. Antipatterns -- "a commonly occurring solution to a problem that generates decidedly negative consequences".
5. Use “==” operator while performing value comparison, with Value Type and use “Equals()” method while performing value comparison with Reference Type.
Subscribe to:
Posts (Atom)