Showing posts with label J2EE Technologies. Show all posts
Showing posts with label J2EE Technologies. Show all posts

Tuesday, January 24, 2012

Java Spring Framework Dependency Injection Variants

Variants in Java Spring Framework Dependency Injection:

Constructor dependency Injection: Dependencies are provided through the constructors of the component.
Setter dependency injection: Dependencies are provided through the JavaBeanstyle setter methods of the component and are more popular than Constructor dependency injection.

Constructor Dependency Injection Syntax:
public class ConstructorInjection
{
private Dependency dep;
public ConstructorInjection(Dependency dep)
{
this.dep = dep;
}
}

Setter Dependency Injection Syntax
public class SetterInjection
{
private Dependency dep;
public void setMyDependency(Dependency dep)
{
this.dep = dep;
}
}

Read more...

Tuesday, January 10, 2012

STRUTS 2 Interceptors

Interceptors in STRUTS 2

Many of the features provided in the Struts2 framework are implemented using interceptors; examples include exception handling, file uploading, lifecycle callbacks and validation. Interceptors are conceptually the same as servlet filters or the JDKs Proxy class. They provide a way to supply pre-processing and post-processing around the action. Similar to servlet filters,interceptors can be layered and ordered. They have access to the action being executed, as well as all environmental variables and execution 
properties. (Reference: Ian Roughley - Starting Struts 2 Book)

Below are the implementing interceptors mentioned:
  1. Spring Framework  the ActionAutowiringInterceptor interceptor.
  2. Request String and Form Values  the ParametersInterceptor interceptor.
  3. Servlet-based objects  the ServletConfigInterceptor interceptor.
The first two interceptors work independently, with no requirements from the action, but the last interceptor ServletConfigInterceptor is different.It works with the assistance of the following interfaces:
  • SessionAware to provide access to all the session attributes via a Map
  • ServletRequestAware to provide access to the HttpServletRequest object
  • RequestAware to provide access to all the request attributes via a Map
  • ApplicationAware to provide access to all the application attributes via a Map
  • ServletResponseAware to provide access to the HttpServletResponse object
  • ParameterAware to provide access to all the request string and form values attributes via a Map
  • PrincipalAware to provide access to the PrincipleProxy object; this object implements the principle and role methods of the HttpServletRequest object in implementation, but by providing a proxy,allows for implementation independence in the action
  • ServletContextAware to provide access to the ServletContext object

Read more...

Sunday, January 1, 2012

Java Mail API

Java Mail API is used to send and receive emails between applications. To send and receive the emails  SMPT, POP and IMAP protocols are used. The message sending and receiving is done by creating a framework using set of abstract classes in the API. This framework allows the application to create customized cross-platform mail application by having basic knowledge of e-mail. There are methods and classes that are used to access mail folders, message downloading and sending messages along with attachments feature.

Java Mail API is used to create personal mail filter, simple mailing lists and personal mail applications. Java mail also includes the capabilities to add the emailing process to an enterprise application or even to create a full-fledged e-mail client. Many companies in the industry have written new e-mail clients using Java Mail.
  • JavaMail is a set of abstract classes that create a framework for sending, receiving and handling e-mail. 
  • The package that Sun provides contains implementations of IMAP and SMTP, which allow sending and receiving mail. 
  • The framework eases the creation of cross-platform mail application without an in-depth knowledge of e-mail.
  • There are methods and classes that allow access to mail folders, download messages, send messages with attachments and filter mail.

Read more...

Sunday, December 18, 2011

Accessing the Java Spring Container

How to access the java Spring Container:

Java Spring is an open source, lightweight, application framework that is intended to help structure entire applications in a consistent manner, pulling together best of breed single-tier frameworks in
a coherent architecture.

From Stand-alone:
ApplicationContext context = new
ClassPathXmlApplicationContext(APP_CONTEXT_CLASSPATH);
(APP_CONTEXT_CLASSPATH is spring/pam-contact-loader-spring-context.xml)
From Web Application
ApplicationContext context =
WebApplicationContextUtils.getWebApplicationContext(
pRequest.getSession().getServletContext());
web.xml modification
<ltcontext-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/spring/pam-spring-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listenerclass>
</listener>

Read more...

Wednesday, March 3, 2010

Struts ActionForm & DynaActionForm

Difference between ActionForm and DynaActionForm


An ActionForm represents an HTML form that the user interacts with over one or more pages. You will provide properties to hold the state of the form with getters and setters to access them. Whereas, using DynaActionForm there is no need of providing properties to hold the state. Instead these properties and their type are declared in the struts-config.xml

The DynaActionForm bloats up the Struts config file with the xml based definition. This gets annoying as the Struts Config file grow larger.

The DynaActionForm is not strongly typed as the ActionForm. This means there is no compile time checking for the form fields. Detecting them at runtime is painful and makes you go through redeployment.

ActionForm can be cleanly organized in packages as against the flat organization in the Struts Config file.

ActionForm were designed to act as a Firewall between HTTP and the Action classes, i.e. isolate and encapsulate the HTTP request parameters from direct use in Actions. With DynaActionForm, the property access is no different than using request.getParameter( .. ).

DynaActionForm construction at runtime requires a lot of Java Reflection (Introspection) machinery that can be avoided.

Read more...

Sunday, February 21, 2010

Hibernate proxy

Hibernate proxy

Proxies are created dynamically by subclassing your object at runtime. The subclass has all the methods of the parent, and when any of the methods are accessed, the proxy loads up the real object from the DB and calls the method for you. Very nice in simple cases with no object hierarchy. Typecasting and instanceof work perfectly on the proxy in this case since it is a direct subclass. By default Hibernate creates a proxy for each of the class you map in mapping file. This class contain the code to invoke JDBC. This class is created by hibernate using CGLIB.


Proxies are the mechanism that allows Hibernate to break up the interconnected cloud of objects in the database into smaller chunks, that can easily fit in memory. Proxies are created dynamically by subclassing your object at runtime. The subclass has all the methods of the parent, and when any of the methods are accessed, the proxy loads up the real object from the DB and calls the method for you.


A class can be mapped to a proxy instead to a table. When you actually call load on session it returns you proxy. This proxy may contain actual method to load the data. Object proxies can be defined in one of two ways. First, you can add a proxy attribute to the class element. You can either specify a different class or use the persistent class as the proxy.


For example:

<class name="Loc"
proxy="com.ch01.Loc">

lt;/class>

The second method is to use the lazy attribute. Setting lazy="true"is a shorthand way of defining the persistent class as the proxy.

Read more...

Wednesday, January 27, 2010

Hibernate Meta Model

The meta model is the model used by Hibernate core to perform its object relational mapping. The model includes information about tables, columns, classes, properties, components, values, collections etc. The API is in org.hibernate.mapping and its main entry point is the Configuration class, the same class that is used to build a session factory.

The model represented by the Configuration class can be build in many ways. The following list the currently supported ones in Hibernate Tools.

  • A Core configuration uses Hibernate Core and supports reading hbm.xml files, requires a hibernate.cfg.xml. Named core in Eclipse and <configuration> in ant.
  • A Annotation configuration uses Hibernate Annotations and supports hbm.xml and annotated classes, requires a hibernate.cfg.xml. Named annotations in Eclipse and <annotationconfiguration> in ant.
  • A JPA configuration uses a Hibernate EntityManager and supports hbm.xml and annotated classes requires that the project has a META-INF/persistence.xml in its classpath. Named JPA in Eclipse and <jpaconfiguration> in ant.
  • A JDBC configuration uses Hibernate Tools reverse engineering and reads its mappings via JDBC metadata + additional reverse engineering files (reveng.xml). Automatically used in Eclipse when doing reverse engineering from JDBC and named <jdbcconfiguration> in ant.
In most projects you will normally use only one of the Core, Annotation or JPA configuration and possibly the JDBC configuration if you are using the reverse engineering facilities of Hibernate Tools. The important thing to note is that no matter which Hibnerate Configuration type you are using Hibernate Tools supports them.

The code generation is done based on the Configuration model no matter which type of configuration have been used to create the meta model, and thus the code generation is independent on the source of the meta model and represented via Exporters.

Read more...

Sunday, August 9, 2009

EJB Home Interface & Remote Interface

EJB Home Interface
  • The EJBHome object must implement the home interface.
  • This interface contains the methods used by the clients to create and remove the instances of the EJB.
  • The home interface is the client’s initial point of contact with your EJB components.
  • For the client to access the EJB , an instance of the EJB is created from one or more create() methods of the Home interface.
  • The ejbCreate() methods defined in the EJB must also be declared with matching signatures in the Home interface.
  • Returns a reference to a EJB by creating or finding it.
EJB Remote Interface
  • The EJBObject class must implement the remote interface.
  • Once the client has used the home interface to gain access to EJB ,it uses this interface to invoke the business methods defined in the EJB class.
  • Clients can never get a reference to the EJBs class , only the EJBObject class.
  • The EJB container uses the remote interface for your bean to generate both the client-side stub and server-side proxy object that passes client calls to your EJB object.

Read more...

Wednesday, August 5, 2009

Java Deployment Descriptor

  • The deployment descriptor objects are used to establish the runtime service settings for an enterprise bean
  • This object defines the enviromental properties , along with the enterprise bean class name, the
  • JNDI namespace,the home and remote interface name
  • It has two types depending on the requirements,Session descriptor and entity descriptor
  • The deployment descriptor also contains detailed inforamtion about how the bean should execute regarding transaction and security
  • The deployment descriptor provides the full description of all files in the ejb jar
  • Deployment descriptor is defined in a XML based format having some standard tags and attributes

Read more...

Tuesday, July 28, 2009

Entity Bean's Ready State & Pooled State

The idea of the “Pooled State” is to allow a container to maintain a pool of entity beans that has been created, but has not been yet “synchronized” or assigned to an EJBObject. This mean that the instances do represent entity beans, but they can be used only for serving Home methods (create or findBy), since those methods do not relay on the specific values of the bean.

All these instances are, in fact, exactly the same, so, they do not have meaningful state. It can be looked at it this way

If no client is using an entity bean of a particular type there is no need for caching it (the data is persisted in the database). Therefore, in such cases, the container will, after some time, move the entity bean from the “Ready State” to the “Pooled state” to save memory. Then, to save additional memory, the container may begin moving entity beans from the “Pooled State” to the “Does Not Exist State", because even though the bean’s cache has been cleared, the bean still takes up some memory just being in the “Pooled State".

Read more...

Sunday, July 26, 2009

Struts 2

Programming the abstract classes instead of interfaces is one of design problem of struts1 framework that has been resolved in the struts 2 framework

Most of the Struts 2 classes are based on interfaces and most of its core interfaces are HTTP independent

Unlike ActionForwards, Struts 2 Results provide flexibility to create multiple type of
outputs

In Struts 2 any java class with execute() method can be used as an Action class

ActionForms feature is no more known to the Struts 2 framework. Simple JavaBean flavored actions are used to put properties directly

Struts 2 Actions are HTTP independent and framework neutral. This enables to test struts applications very easily without resorting to mock objects

Java 5 annotations can be used as an alternative to XML and Java properties configuration

Struts 2 lets to customize the request handling per action, if desired. Struts 1 lets to customize the request processor per module

Struts 2 Actions are Spring-aware.Just need to add Spring beans

AJAX client side validation

Read more...

Thursday, July 23, 2009

Hibernate 3 Features

Hibernate 3’s “Hibernate for the Enterprise” focus has built on the success of Hibernate 2 and extended it with enterprise class functionality includes following additional features

  • Support for EJB 3.0 Annotations, Entity Manager, and Java Persistence API
  • ORM improvements that support virtualized filtering for temporal, historical, regional, and permissioned data
  • Single object to multi-table mapping, bulk update and delete by query, and the ability to override generated SQL with hand-written SQL
  • JMX-enabled statistics reporting and monitoring through any JMX console
  • XML binding that enables data to be represented as XML and Java objects interchangeably
  • Event-driven design that enables custom event objects to be created and registered to handle auditing scenarios or cascaded behavior semantics

Read more...

Tuesday, July 7, 2009

Struts Framework Tag Libraries

The Struts framework includes custom JSP tag libraries that you can use to create JSP pages that work with the rest of the Struts framework objects in your web application

Struts HTML Tags

Used to create Struts input forms, as well as other tags generally useful in the creation of HTML-based user interfaces.

Struts Bean Tags

Useful in accessing beans and their properties, as well as defining new beans (based on these accesses) that are accessible to the remainder of the page via scripting variables and page scope attributes. Convenient mechanisms to create new beans based on the value of request cookies, headers, and parameters are also provided.

Struts Logic tag

Useful in managing conditional generation of output text, looping over object collections for repetitive generation of output text, and application flow management.

Struts Nested

Brings a nested context to the functionality of the Struts custom tag library. The purpose of this tag library is to enable the tags to be aware of the tags which surround them so they can correctly provide the nesting property reference to the Struts system.

Struts Tiles Tags

Provides tiles tags. Tiles were previously called Components.

Struts Templates

Three tags: put, get, and insert. A put tag moves content into request scope, which is retrieved by a get tag in a different JSP page. That template is included with the insert tag. Tags from the various Struts custom JSP tag libraries appear in JDeveloper on the Component Palette.

Read more...

Monday, July 6, 2009

Entity Bean Method Types

Entity bean is used to represent data in the database. It provides an object-oriented interface to data that would normally be accessed by the JDBC or some other back-end API. More than that, entity beans provide a component model that allows bean developers to focus their attention on the business logic of the bean, while the container takes care of managing persistence, transactions, and access control.

An entity bean consists of 4 types of methods

create() methods

To create a new instance of a CMP entity bean, and therefore insert data into the database, the create() method on the bean's home interface must be invoked. They look like this: EntityBeanClass ejbCreateXXX(parameters), where EntityBeanClass is an Entity Bean you are trying to instantiate, ejbCreateXXX(parameters) methods are used for creating Entity Bean instances according to the parameters specified and to some programmer-defined conditions.

A bean's home interface may declare zero or more create() methods, each of which must have corresponding ejbCreate() and ejbPostCreate() methods in the bean class. These creation methods are linked at run time, so that when a create() method is invoked on the home interface, the container delegates the invocation to the corresponding ejbCreate() and ejbPostCreate() methods on the bean class.

finder() methods

The methods in the home interface that begin with "find" are called the find methods. These are used to query the EJB server for specific entity beans, based on the name of the method and arguments passed. Unfortunately, there is no standard query language defined for find methods, so each vendor will implement the find method differently. In CMP entity beans, the find methods are not implemented with matching methods in the bean class containers implement them when the bean is deployed in a vendor specific manner.

The deployer will use vendor specific tools to tell the container how a particular find method should behave. Some vendors will use object-relational mapping tools to define the behavior of a find method while others will simply require the deployer to enter the appropriate SQL command.

There are two basic kinds of find methods: single-entity and multi-entity. Single-entity find methods return a remote reference to the one specific entity bean that matches the find request. If no entity beans are found, the method throws an ObjectNotFoundException . Every entity bean must define the single-entity find method with the method name findByPrimaryKey(), which takes the bean's primary key type as an argument. The multi-entity find methods return a collection ( Enumeration or Collection type) of entities that match the find request. If no entities are found, the multi-entity find returns an empty collection.

remove() methods

These methods (you may have up to 2 remove methods, or don't have them at all) allow the client to physically remove Entity beans by specifying either Handle or a Primary Key for the Entity Bean.

home() methods

These methods are designed and implemented by a developer, and EJB specification doesn't have any requirements for them except the need to throw a RemoteException is each home method.

Read more...

Sunday, July 5, 2009

Struts and JSP

Struts makes it possible for JSP pages to externalize flow control, rather than specify physical links to various JSP pages within the JSP file, the JSP file contains a Struts-defined logical URI. The Struts URI defines a logical page request mapped to actions that may return different physical JSP pages depending on the context of the HTTP request.

Struts simplifies the development of the actual JSP file content by limiting it to user interface generation only. Java that would otherwise appear inside the JSP files appears in separate servlet action classes that the JSP page invokes at runtime.

Struts helps to separate the development roles into user interface designer (HTML or tag library user) and JSP action-handler developer. For example, one person can write JSP page using only HTML or suitable tag libraries, while another person works independently to create the page action handling classes in Java.

Struts externalizes JSP actions that would otherwise appear inside all the JSP pages of your project into a single configuration file. This greatly simplifies debugging and promotes reuse. Struts consolidates String resources that would otherwise appear inside all the JSP pages of your project into a single file. This simplifies the task of localizing JSP applications.

Read more...

Tuesday, June 30, 2009

Struts Action Classes

An Action Class performs a role of an adapter between the contents of an incoming HTTP request and the corresponding business logic that should be executed to process this request. Different kinds of actions in Struts are:

  • ForwardAction
  • IncludeAction
  • DispatchAction
  • LookupDispatchAction
  • SwitchAction
DispatchAction in Struts

The DispatchAction class is used to group related actions into one class. Using this class, We can have a method for each logical action compared than a single execute method. The DispatchAction dispatches to one of the logical actions represented by the methods. It picks a method to invoke based on an incoming request parameter. The value of the incoming parameter is the name of the method that the DispatchAction will invoke.

Struts ForwardAction

The ForwardAction class is useful when you’re trying to integrate Struts into an existing application that uses Servlets to perform business logic functions. You can use this class to take advantage of the Struts controller and its functionality, without having to rewrite the existing Servlets. Use ForwardAction to forward a request to another resource in your application, such as a Servlet that already does business logic processing or even another JSP page. By using this predefined action, you don’t have to write your own Action class. You just have to set up the struts-configfile properly to use ForwardAction.

IncludeAction in Struts

The IncludeAction class is useful when you want to integrate Struts into an application that uses Servlets. Use the IncludeAction class to include another resource in the response to the request being processed.

Struts LookupDispatchAction

The LookupDispatchAction is a subclass of DispatchAction. It does a reverse lookup on the resource bundle to get the key and then gets the method whose name is associated with the key into the Resource Bundle. LookupDispatchAction is useful if the method name in the Action is not driven by its name in the front end, but by the Locale independent key into the resource bundle. Since the key is always the same, the LookupDispatchAction shields your application from the side effects of I18N.

SwitchAction in Struts

The SwitchAction class provides a means to switch from a resource in one module to another resource in a different module. SwitchAction is useful only if you have multiple modules in your Struts application. The SwitchAction class can be used as is, without extending.

Read more...

Thursday, June 25, 2009

(EJB) Entity Beans in brief

What is an Entity Bean?

An Entity bean represents a business object in a persistent storage mechanism. An entity bean typically represents a table in a relational database and each instance represents a row in the table. Entity bean differs from session bean by persistence, shared access, relationship and primary key. There are two types of entity beans available.

  • Container Managed Persistence (CMP)
  • Bean Managed Persistence (BMP)
CMP / Container Managed Persistence

A The term container-managed persistence means that the EJB container handles all database access required by the entity bean. The bean's code contains no database access (SQL) calls. As a result, the bean's code is not tied to a specific persistent storage mechanism (database). Because of this flexibility, even if you redeploy the same entity bean on different J2EE servers that use different databases, you won't need to modify or recompile the bean's code. So, your entity beans are more portable.

BMP / Bean Managed Persistence

A Bean managed persistence (BMP) occurs when the bean manages its persistence. Here the bean will handle all the database access. So the bean's code contains the necessary SQLs calls. So it is not much portable compared to CMP. Because when we are changing the database we need to rewrite the SQL for supporting the new database.

Read more...

Tuesday, June 23, 2009

Stateless Session Beans

A Stateless session beans are of equal value for all instances of the bean. Session bean will execute a client request and return a result without saving any client specific state. This means the container can assign any bean to any client, making it very scalable. Stateless session beans does not retain client specific state from one method invocation to the next.

Bean instance can be reassigned to serve a method invocation from another client once current method invocation is done. Value of instance variables of a bean instance is not preserved between calls. Container transparently reuses bean instances to serve different clients. Load-balancing & Failover is easier since no state needs to be preserved. High scalability since a client call can be Served by any EJB server in a clustered architecture.

A stateless session bean is an enterprise bean that provides a stateless service to the client. Conceptually, the business methods on a stateless session bean are similar to procedural applications or static methods; there is no instance state, so all the data needed to execute the method is provided by the method arguments. The stateless session bean is an EJB component that implements the javax.ejb.SessionBean interface and is deployed with the declarative attribute "stateless".

Stateless session beans
are called "stateless" because they do not maintain conversational state specific to a client session. In other words, the instance fields in a stateless session bean do not maintain data relative to a client session. This makes stateless session beans very lightweight and fast, but also limits their behavior. Typically an application requires less number of stateless beans compared to stateful beans.

Read more...

Monday, June 22, 2009

Stateful Session Beans

A Stateful session bean maintain the state of the conversation between the client and itself. When the client invokes a method on the bean the instance variables of the bean may contain a state but only for the duration of the invocation.

Stateful session bean will retain client specific state (session state) from one method invocation to the next, her bean instances are to be maintained for each client. A stateful session bean is an enterprise bean (EJB component) that acts as a server-side extension of the client that uses it. The stateful session bean is created by a client and will work for only that client until the client connection is dropped or the bean is explicitly removed.

A stateful session bean is an enterprise bean (EJB component) that acts as a server-side extension of the client that uses it. The stateful session bean is created by a client and will work for only that client until the client connection is dropped or the bean is explicitly removed. Stateful session beans are usually developed to act as agents for the client, managing the interaction of other beans and performing work on behalf of the client application.

The stateful session bean is EJB component that implements the javax.ejb.SessionBean interface and is deployed with the declarative attribute "stateful". Stateful session beans are called "stateful" because they maintain a conversational state with the client. In other words, they have state or instance fields that can be initialized and changed by the client with each method invocation. The bean can use the conversational state as it process business methods invoked by the client.

Read more...

Friday, June 19, 2009

Java Internationalization (II8N)

Internationalization (I18N) in Java

Java Internationalization (I18N) is the process of designing an application so that it can be adapted to different languages and regions, without requiring engineering changes. This model is to support many languages but only two of them, English (ASCII) and another one, at the same time. One have to specify the 'another' language,usually by LANG environmental variable. The above I18N-L10N model can be regarded as a part of this I18N model. gettextization is categorized into I18N model.

I18N is needed in the following places.

  • Displaying characters for the end users' native languages.
  • Inputing characters for the end users' native languages.
  • Handling files written in popular encodings [1] that are used for the end users' native languages.
  • Using characters from the end users' native languages for file names and other items.
  • Printing out characters from the end users' native languages.
  • Displaying messages by the program in the end users' native languages.
  • Formatting input and output of numbers, dates, money, etc., in a way that obeys customs of the end users' native cultures.
  • Classifying and sorting characters, in a way that obey customs of the end users' native cultures.
  • Using typesetting and hyphenation rules appropriate for the end users' native languages.

Java Internationalization (I18N) can be done with some handy modifications in our existing application. We have to know the two Internationalization (I18N) components that are packaged with the Struts Framework. The first of these components, which is managed by the application Controller, is a Message class that references a resource bundle containing Locale-dependent strings.

The second Internationalization (I18N) component is a JSP custom tag, <bean:message /> , Which is used in the View layer to present the actual strings managed by the Controller.


Java Internationalization (I18N) is a set of simple Java properties files. Each file contains a key/value pair for each message that you expect your application to present, in the language appropriate for the requesting client.

Locale objects are only identifiers. After defining a Locale, you pass it to other objects that perform useful tasks, such as formatting dates and numbers. These objects are called locale-sensitive, because their behavior varies according to Locale. A ResourceBundle is an example of a locale-sensitive object.

Internationalization Sample Program

import java.util.*

public class I18NCode
{
public static void main(String args{})
{

String language;
String country;

if (args.length != 2)
{

language = new String("en");
country = new String("US");

}else{

language = new String(args[0]);
country = new String(ars[1]);
}

Locale currentLocale;
ResourseBundle messages;

currentLocale = new Locale(language, country);
messages = ResourseBundle.getBundle("MessagesBundle", currentLocale);

System.out.println(messages.getString("Hai");
System.out.println(messages.getString("How are");
System.out.println(messages.getString("You");

}
run this program in the following way:

java I18NCode en US
(or)

java I18NCode fr FR

Read more...
Blog Widget by LinkWithin

JS-Kit Comments

  © Blogger template Newspaper III by Ourblogtemplates.com 2008

Back to TOP