Thursday, December 27, 2007

java.lang.String replaceAll case insensitive

private String replaceAll(String string, String regex, String replaceWith){
Pattern myPattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
/*for space,new line, tab checks*/
//Pattern myPattern = Pattern.compile(regex+"[ /n/t/r]", Pattern.CASE_INSENSITIVE);
string = myPattern.matcher(string).replaceAll(replaceWith);
return string;
}

Thursday, December 20, 2007

Inversion of Control / Dependency Injection

Decoupling is much easier when beans do not look up their dependencies, but are provided with them, and additionally do not even know where the dependencies are located and of what actual type they are.

i)setter-based dependency injection is realized by calling setters on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean. Beans defined in the BeanFactory that use setter-based dependency injection are true JavaBeans. Spring generally advocates usage of setter-based dependency injection, since a large number of constructor arguments can get unwieldy, especially when some properties are optional.

ii)constructor-based dependency injection is realized by invoking a constructor with a number of arguments, each representing a collaborator or property. Additionally, calling a static factory method with specific arguments, to construct the bean, can be considered almost equivalent, and the rest of this text will consider arguments to a constructor and arguments to a static factory method similarly.

Wednesday, December 19, 2007

Libraries required for a Spring-Hibernate project

hibernate3.jar - ORM
ojdbc14.jar - driver
commons-beanutils-1.6.1.jar
commons-collections-2.1.1.jar
commons-digester-1.3.jar
commons-lang-2.1.jar
commons-logging-1.0.4.jar
asm.jar - Java byte code manipulation framework
cglib-2.1.3.jar - Code Generation Library
spring.jar
dom4j-1.6.1.jar - XML parsing
jta.jar - Transaction

Tuesday, December 18, 2007

Hibernate Life Cycle

The state of an object reflects the values contained in the attributes of an object at a given time. So whenever the values change, the state also changes to reflect the current values. The total number of states traversed by an object to reach its initial state is known as the life-cycle of the object. Following are the states that form the life-cycle of a persistent object, also known as life-cycle of persistence:

1. Transience
2. Persistence
3. Detachment


1. Transient State:

Transient is the state of an object when it is not associated with any database. Transient objects don’t come under the context of a transaction.

2. Persistent State:

An object is said to be in a persistent state when it has a database identity.To make any transient object persistent, the save method of the Persistence manager has to be called. The most important characteristic feature of an object in the persistent state is that it takes part in transactional activities.

3. Detached State:

In Hibernate, when the transaction completes by calling the close() method on the Session object, the instances of persistence class lose their association with the Persistence manager. Thus the detached state is attained. In this state the object is no longer in sync with the database. Also Hibernate doesn’t care about the modifications being done to the object, as the object is no longer under the management of Hibernate.


Tuesday, September 25, 2007

Hibernate one-to-one properties

5.1.11. one-to-one

A one-to-one association to another persistent class is declared using a one-to-one element.

(1)
class="ClassName" (2)
cascade="cascade_style" (3)
constrained="true|false" (4)
fetch="join|select" (5)
property-ref="propertyNameFromAssociatedClass" (6)
access="field|property|ClassName" (7)
formula="any SQL expression" (8)
lazy="proxy|no-proxy|false" (9)
entity-name="EntityName" (10)
node="element-name|@attribute-name|element/@attribute|."
embed-xml="true|false"
foreign-key="foreign_key_name"
/>
(1)

name: The name of the property.

(2)

class (optional - defaults to the property type determined by reflection): The name of the associated class.

(3)

cascade (optional) specifies which operations should be cascaded from the parent object to the associated object.

(4)

constrained (optional) specifies that a foreign key constraint on the primary key of the mapped table references the table of the associated class. This option affects the order in which save() and delete() are cascaded, and determines whether the association may be proxied (it is also used by the schema export tool).

(5)

fetch (optional - defaults to select): Chooses between outer-join fetching or sequential select fetching.

(6)

property-ref: (optional) The name of a property of the associated class that is joined to the primary key of this class. If not specified, the primary key of the associated class is used.

(7)

access (optional - defaults to property): The strategy Hibernate should use for accessing the property value.

(8)

formula (optional): Almost all one to one associations map to the primary key of the owning entity. In the rare case that this is not the case, you may specify a some other column, columns or expression to join on using an SQL formula. (See org.hibernate.test.onetooneformula for an example.)

(9)

lazy (optional - defaults to proxy): By default, single point associations are proxied. lazy="no-proxy" specifies that the property should be fetched lazily when the instance variable is first accessed (requires build-time bytecode instrumentation). lazy="false" specifies that the association will always be eagerly fetched. Note that if constrained="false", proxying is impossible and Hibernate will eager fetch the association!

(10)

entity-name (optional): The entity name of the associated class.


Refer for more::::::

http://www.hibernate.org/hib_docs/reference/en/html/mapping.html

Hibernate many-to-one properties

5.1.10. many-to-one

An ordinary association to another persistent class is declared using a many-to-one element. The relational model is a many-to-one association: a foreign key in one table is referencing the primary key column(s) of the target table.

(1)
column="column_name" (2)
class="ClassName" (3)
cascade="cascade_style" (4)
fetch="join|select" (5)
update="true|false" (6)
insert="true|false" (6)
property-ref="propertyNameFromAssociatedClass" (7)
access="field|property|ClassName" (8)
unique="true|false" (9)
not-null="true|false" (10)
optimistic-lock="true|false" (11)
lazy="proxy|no-proxy|false" (12)
not-found="ignore|exception" (13)
entity-name="EntityName" (14)
formula="arbitrary SQL expression" (15)
node="element-name|@attribute-name|element/@attribute|."
embed-xml="true|false"
index="index_name"
unique_key="unique_key_id"
foreign-key="foreign_key_name"
/>
(1)

name: The name of the property.

(2)

column (optional): The name of the foreign key column. This may also be specified by nested element(s).

(3)

class (optional - defaults to the property type determined by reflection): The name of the associated class.

(4)

cascade (optional): Specifies which operations should be cascaded from the parent object to the associated object.

(5)

fetch (optional - defaults to select): Chooses between outer-join fetching or sequential select fetching.

(6)

update, insert (optional - defaults to true) specifies that the mapped columns should be included in SQL UPDATE and/or INSERT statements. Setting both to false allows a pure "derived" association whose value is initialized from some other property that maps to the same colum(s) or by a trigger or other application.

(7)

property-ref: (optional) The name of a property of the associated class that is joined to this foreign key. If not specified, the primary key of the associated class is used.

(8)

access (optional - defaults to property): The strategy Hibernate should use for accessing the property value.

(9)

unique (optional): Enable the DDL generation of a unique constraint for the foreign-key column. Also, allow this to be the target of a property-ref. This makes the association multiplicity effectively one to one.

(10)

not-null (optional): Enable the DDL generation of a nullability constraint for the foreign key columns.

(11)

optimistic-lock (optional - defaults to true): Specifies that updates to this property do or do not require acquisition of the optimistic lock. In other words, dertermines if a version increment should occur when this property is dirty.

(12)

lazy (optional - defaults to proxy): By default, single point associations are proxied. lazy="no-proxy" specifies that the property should be fetched lazily when the instance variable is first accessed (requires build-time bytecode instrumentation). lazy="false" specifies that the association will always be eagerly fetched.

(13)

not-found (optional - defaults to exception): Specifies how foreign keys that reference missing rows will be handled: ignore will treat a missing row as a null association.

(14)

entity-name (optional): The entity name of the associated class.

Tuesday, August 14, 2007

Java Optimisation

Here are a few general guidelines for using object memory efficiently:

  • Avoid creating objects in frequently used routines. Because these routines are called frequently, you will likely be creating objects frequently, and consequently adding heavily to the overall burden of object cycling. By rewriting such routines to avoid creating objects, possibly by passing in reusable objects as parameters, you can decrease object cycling.
  • Try to presize any collection object to be as big as it will need to be. It is better for the object to be slightly bigger than necessary than to be smaller than it needs to be. This recommendation really applies to collections that implement size increases in such a way that objects are discarded. For example, Vector grows by creating a new larger internal array object, copying all the elements from and discarding the old array. Most collection implementations have similar implementations for growing the collection beyond its current capacity, so presizing a collection to its largest potential size reduces the number of objects discarded.
  • When multiple instances of a class need access to a particular object in a variable local to those instances, it is better to make that variable a static variable rather than have each instance hold a separate reference. This reduces the space taken by each object (one less instance variable) and can also reduce the number of objects created if each instance creates a separate object to populate that instance variable.
  • Reuse exception instances when you do not specifically require a stack trace (see ).

Thursday, July 26, 2007

java.lang.UnsupportedClassVersionError

I got an error like this trying to run a stand alone java class
Got fed up searching in the net.

Finally I found that I had more than 3 JREs installed in my machine, i tried removing all but one.

Even then it didnt work, due to bloody Oracle resetting the class path to its JRE version, which was an older one compared to what we were using.

So finally solved the problem by setting the class path to just one java library.

Wednesday, May 23, 2007

Application Context Class File

package com.client.project.context;

import org.springframework.beans.BeansException;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ApplicationContextOne extends ClassPathXmlApplicationContext {

private static ApplicationContextOne applicationContext = null;

public ApplicationContextOne(String arg0) throws BeansException {
super(arg0);
}

public ApplicationContextOne() throws BeansException {
super("ApplicationContext.xml");//argument is the name of the context xml file
}

static{
Thread.currentThread().setContextClassLoader(ApplicationContextOne.class.getClassLoader());
applicationContext = new ApplicationContextOne();
}
}

Sunday, April 01, 2007

Application context loading info

INFO XmlBeanDefinitionReader:158 - Loading XML bean definitions from class path resource[SpringApplicationContext.xml]
INFO XmlBeanFactory:222 - Creating shared instance of singleton bean 'user_dao'
INFO CollectionFactory:61 - JDK 1.4+ collections available
INFO XmlBeanFactory:222 - Creating shared instance of singleton bean 'sessionFactory'
INFO XmlBeanFactory:222 - Creating shared instance of singleton bean 'appDataSource'
INFO DriverManagerDataSource:154 - Loaded JDBC driver: org.postgresql.Driver
INFO Environment:499 - Hibernate 3.2 cr2
INFO Environment:532 - hibernate.properties not found
INFO Environment:666 - Bytecode provider name : cglib
INFO Environment:583 - using JDK 1.4 java.sql.Timestamp handling
INFO HbmBinder:298 - Mapping class: com.tvarita.ehr.model.hibernate.AccessUser -> access_user

INFO ConnectionProviderFactory:72 - Initializing connection provider: org.springframework.orm.hibernate3.LocalDataSourceConnectionProvider
INFO SettingsFactory:78 - RDBMS: PostgreSQL, version: 7.4.7
INFO SettingsFactory:79 - JDBC driver: PostgreSQL Native Driver, version: PostgreSQL 7.4.1 JDBC3 with SSL (build 210)
INFO Dialect:128 - Using dialect: org.hibernate.dialect.PostgreSQLDialect
INFO TransactionFactoryFactory:31 - Using default transaction strategy (direct JDBC transactions)
INFO TransactionManagerLookupFactory:33 - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
INFO SettingsFactory:126 - Automatic flush during beforeCompletion(): disabled
INFO SettingsFactory:130 - Automatic session close at end of transaction: disabled
INFO SettingsFactory:137 - JDBC batch size: 15
INFO SettingsFactory:140 - JDBC batch updates for versioned data: disabled
INFO SettingsFactory:145 - Scrollable result sets: enabled
INFO SettingsFactory:153 - JDBC3 getGeneratedKeys(): disabled
INFO SettingsFactory:161 - Connection release mode: auto
INFO SettingsFactory:188 - Default batch fetch size: 1
INFO SettingsFactory:192 - Generate SQL with comments: disabled
INFO SettingsFactory:196 - Order SQL updates by primary key: disabled
INFO SettingsFactory:357 - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
INFO ASTQueryTranslatorFactory:24 - Using ASTQueryTranslatorFactory
INFO SettingsFactory:204 - Query language substitutions: {}
INFO SettingsFactory:210 - Second-level cache: enabled
INFO SettingsFactory:214 - Query cache: enabled
INFO SettingsFactory:344 - Cache provider: org.hibernate.cache.HashtableCacheProvider
INFO SettingsFactory:229 - Optimize cache for minimal puts: disabled
INFO SettingsFactory:238 - Structured second-level cache entries: disabled
INFO SettingsFactory:331 - Query cache factory: org.hibernate.cache.StandardQueryCacheFactory
INFO SettingsFactory:265 - Statistics: disabled
INFO SettingsFactory:269 - Deleted entity synthetic identifier rollback: disabled
INFO SettingsFactory:284 - Default entity-mode: pojo
INFO SessionFactoryImpl:159 - building session factory
INFO SessionFactoryObjectFactory:82 - Not binding factory to JNDI, no JNDI name configured
INFO UpdateTimestampsCache:43 - starting update timestamps cache at region: org.hibernate.cache.UpdateTimestampsCache
INFO StandardQueryCache:51 - starting query cache at region: org.hibernate.cache.StandardQueryCache
INFO XmlBeanDefinitionReader:158 - Loading XML bean definitions from class path resource [org/springframework/jdbc/support/sql-error-codes.xml]
INFO DefaultListableBeanFactory:222 - Creating shared instance of singleton bean 'DB2'
INFO DefaultListableBeanFactory:222 - Creating shared instance of singleton bean 'HSQL'
INFO DefaultListableBeanFactory:222 - Creating shared instance of singleton bean 'MS-SQL'
INFO DefaultListableBeanFactory:222 - Creating shared instance of singleton bean 'MySQL'
INFO DefaultListableBeanFactory:222 - Creating shared instance of singleton bean 'Oracle'
INFO DefaultListableBeanFactory:222 - Creating shared instance of singleton bean 'Informix'
INFO DefaultListableBeanFactory:222 - Creating shared instance of singleton bean 'PostgreSQL'
INFO DefaultListableBeanFactory:222 - Creating shared instance of singleton bean 'Sybase'
INFO SQLErrorCodesFactory:120 - SQLErrorCodes loaded: [DB2, HSQL, MS-SQL, MySQL, Oracle, Informix, PostgreSQL, Sybase]

Monday, March 05, 2007

doGet and doPost

What is the difference between the doGet and doPost methods?

Ans 1)
When you invoke a Servlet, the servlet engine passes the information on to the Servlets service() method. This method determines the type of request made (GET, POST, HEAD, ...) and calls the function doTYPE, like doGet, doPost. GET and POST just differ in the way form data is sent from the browser to the server. The method doGet handles data that has been attached to the url in the form url questionmark (name=value ampersand)+. Typically in a CGI you would have to read the environment variable QUERY_STRING to get this string of concatenated parameternames and values. With the doPost method, form data comes in through standard input stream, a cgi would just need to open the input stream and read until EOF to get the form data.

With Servlets, you don't need to read in the concatenated string of parameternames and values. The parsing is all done behind the scenes. You just need to call getParameter regardless of how the form data is actually sent in.

Ans2)
doGet is called in response to an HTTP GET request. This happens when users click on a link, or enter a URL into the browser's address bar. It also happens with some HTML FORMs (those with METHOD="GET" specified in the FORM tag).

doPost is called in response to an HTTP POST request. This happens with some HTML FORMs (those with METHOD="POST" specified in the FORM tag).

Both methods are called by the default (superclass) implementation of service in the HttpServlet base class. You should override one or both to perform your servlet's actions.

Saturday, February 24, 2007

IoC Minimal

Dependency Injection

i)Constructor Injection (type3 IoC)
ii)Setter Injection (type2 IoC)
iii)Interface Injection (type1 IoC)

Hibern8 a few

Hibernate features

*)automatic dirty checking - updates the object if not the database when the state of the object is changed 'inside a transaction'

*) cascading save - making a new object persistent by automatically if its referenced by an already persistent object

*)



Hibernate Interfaces
====================

*)Session, Transaction, Query - to perform basic CRUD and querying
*)Configuration - to configure hibernate
*)Interceptor, Lifecycle and Validatable - Callback interfaces , to react to events
*)UserType, CompositeUserType, IdentifierGenerator - extension to hibernate's mapping functionality


Session Interface
-are not thread safe, should be used by only one thread at a time (singleton)
SessionFactory Interface
- the application obtains session instances from SessionFactory
will require one sessionFactory for each database connection

terminology
===========
*)container managed transaction(CMT) - used to control transactions in a managed environment with J2EE

Spring minimal info

Spring is an Application Container

The main Spring beans

i)Data source bean - org.springframework.jdbc.datasource.DriverManagerDataSource
ii)Session factory bean - org.springframework.orm.hibernate3.LocalSessionFactoryBean
iii)business beans

Vector Vs Arraylist

1. Use ArrayList and synchronize (but only as needed).

There is a big advantage to using Collections objects everywhere--
you can often have functions return Collection and not need to know
that your implementation is ArrayList--so that later you can substitute
some other kind of Collection as the implementation and not affect the calling code.

Also, you probably won't need synchronization in most cases.
Any Collection that is request-scoped will be accessed single-threaded
(unless you are creating Threads as part of the request).
You might only need to synchronize session-scoped collections, of which there should be few, if any.

Java Web application

WEB APPLICATION

* A web application is a collection of servlets , html pages, classes and other resources that can be bundled and run on multiple (web) containers.

* Each web application has one and only one ServletContext.

The contents of a web application
i)Servlets
ii)JS pages
iii)Utility Classes
iv)Static documents (HTML)
v)Client Classes
vi)Meta info about web application


The Web Application Deployment Descriptor (web.xml)

The elements in web.xml incude the following in order

i)ServletContext init parameters
ii)Localized Content
iii)Session Configuration
iv)Servlet / JSP Definitions
v)Sevlet / JSP mappings
vi)Mime Type Mappings
vii)Welcome File List
viii)Error pages
ix)Security

Webwork Details

WEBWORK
----------
WebWork is a Java web-application development framework. It is built specifically with developer productivity and code simplicity in mind, providing robust support for building reusable UI templates, such as form controls, UI themes, internationalization, dynamic form parameter mapping to JavaBeans, robust client and server side validation, and much more

WebWork is a powerful web-based MVC framework built on top of a command pattern framework API called XWork. The true power of Webwork is its underlying concept of simplicity and interoperability. Using WebWork will help minimize code and allow developers to concentrate more on business logic and modeling, rather than the plumbing oftern required when building web-based applications.


XWORK
--------
XWork is a command-pattern framework that is used to power WebWork as well as other applications. XWork provides an Inversion of Control container, a powerful expression language, data type conversion, validation, and pluggable configuration.


ServletDispatcher
-------------------

public class ServletDispatcher
extends HttpServlet
implements WebWorkStatics

Main dispatcher servlet in WebWork2 which acts as the controller in the MVC paradigm.

When a request enters the servlet the following things will happen:

1. The action name is parsed from the servlet path (i.e., /foo/bar/MyAction.action -> MyAction).
2. A context consisting of the request, response, parameters, session and application properties is created.
3. An XWork ActionProxy object is instantiated (wraps an Action) using the action name, path, and context then executed.
4. Action output will channel back through the response to the user.

Any errors occurring during the action execution will result in a HttpServletResponse.SC_INTERNAL_SERVER_ERROR error and any resource errors (i.e., invalid action name or missing JSP page) will result in a HttpServletResponse.SC_NOT_FOUND error.





****************OGNL is the Object Graph Navigation Language*************

Functions
---------
Handle page flow, validation, MVC structure, HTML form to java object mapping, JSP taglibs etc.