Tuesday, October 02, 2007

JACC - Java Authorization Container Contract

The Java Authorization Container Contract (JACC) is a specification that was introduced in Java 2 Platform, Enterprise Edition (J2EE) 1.4 through the Java Specification Request (JSR) 115 process. This specification defines a contract between J2EE containers and authorization providers. This enables any third-party authorization providers to plug into any J2EE 1.4 Application Servers such as WebSphere to make authorization decisions when a J2EE resource is being accessed. The access decisions is made through the standard java.security.Policy object.

When an authenticated user makes a request to a web or a EJB resource, the security runtime makes the decision of whether to allow the access. This is called an access decision. Based on JACC, the appropriate permission object is created, the appropriate policy context handlers are registered, and the appropriate policy context identifier (contextID) is set. A call is made to the java.security.Policy object that is implemented by the provider to make the access decision.

In IBM WebSphere Application Server (WAS), when security is enabled, the default authorization is used unless a JACC provider is specified. The default authorization does not require special setup, and the default authorization engine makes all of the authorization decisions. However, if a JACC provider is configured and set up for WAS, all of the enterprise bean and web resource access decision will be delegated to the JACC provider.

Monday, October 01, 2007

WAS 6.1 Startup Error on SystemOut.log

My WAS 6.1 on RSA 7.0.0.3 has this error when starts up.
[10/1/07 9:48:28:785 EDT] 0000000a WrappingFileO E archiveCurrentFile TRAS0016E: An unexpected exception while trying to archive log file C:\Program Files\IBM\SDP70\runtimes\base_v61\profiles\AppSrv01\logs\server1\SystemOut.log Exception is java.io.IOException: Unable to rename file C:\Program Files\IBM\SDP70\runtimes\base_v61\profiles\AppSrv01\logs\server1\SystemOut.log to C:\Program Files\IBM\SDP70\runtimes\base_v61\profiles\AppSrv01\logs\server1\SystemOut_07.10.01_09.48.28.log. Logging continues.
It was said on IBM WID Forum that the fix for this issue will be available in 6.0.2.25 fixpack.

Friday, September 28, 2007

Log4JCategoryLog

Apache common logging 1.0 used Log4JCategoryLog. In version 1.1, replace it with Log4JLogger. The commons-logging.properties file will look like this,
org.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JLogger

web.xml version 2.4

In web.xml version 2.4, taglib shall be defined inside a jsp-config section.

Monday, September 17, 2007

升级FC6->FC7

折腾了好几个晚上,想把自己的一台老爷机从FC6升级到FC7,未果。
根本的原因是,FC7不认PATA的硬盘。就算用RESCUE碟都不行。
记住,自此一定不能升级内核。

Tuesday, September 11, 2007

Hibernate and Struts - Identifier Altered

In our application, we used Hibernate 3.1.2, Spring 1.2.6 and Struts 1.2.4. One of the page flows was to gather input from a form and insert a record into database then go back to the list page.

We saw messages like that,
org.hibernate.HibernateException: identifier of an instance of ... was altered ...
...
org.hibernate.event.def.DefaultFlushEventListener.onFlush...
...
In the beginning of investigation, we found the Hibernate related code did not flush after insert. We added the flush, but it didn't solve the problem.

Then we read Spring document and found HibernateTemplate recommended over Session. So we replaced Session with Template. But it didn't solve the problem.

Because because it had no problem going back to list after update, we tried to use saveOrUpdate and replace save. But it was the same.

Finally we noticed the Hibernate flush was scheduled after the page was forwarded, no matter what the setting of transaction.flush_before_completion was true or false. We also noticed the struts always recovered the form after forward. We tried to reset the data bean in the form right after insert. And this time, it solved the problem.

Thursday, September 06, 2007

Hibernate and MS SQL - Nullability Problem

The nullability problem happens when Hibernate 3 deletes an instance with any null value property defined not nullable.
org.springframework.orm.hibernate3.HibernateSystemException: not-null property references a null or transient value: com.ag.applications.forms.entity.qstnaire.QstnaireBean.qstnaireNam; nested exception is org.hibernate.PropertyValueException: not-null property references a null or transient value: com.ag.applications.forms.entity.qstnaire.QstnaireBean.qstnaireNam
org.hibernate.PropertyValueException: not-null property references a null or transient value: com.ag.applications.forms.entity.qstnaire.QstnaireBean.qstnaireNam
To get rid of the error, edit the hbm.xml file and change the not-null="true" to "false".

However, it is necessary to define some properties not nullable. In this case, modify the application and let the property has non-null value or get the instance from database by primary key, then delete it.

This problem was reported to Hibernate on August, 2007. No known release fixes it.

Wednesday, September 05, 2007

Hibernate and MS SQL - Delete Operation

When does delete operation, application prompts message,
Data Access Error: Write operations are not allowed in read-only mode (FlushMode.NEVER) - turn your Session into FlushMode.AUTO or remove 'readOnly' marker from transaction definition.
This is because Spring 1.2 is incompatible with Hibernate 3. I heard Spring 2.0 solved this problem, but I found a workaround solution with Spring 1.2.

Here is the solution, in applicationContext.xml, set the property "checkWriteOperations" of "org.springframework.orm.hibernate3.HibernateTemplate" to false.

Tuesday, September 04, 2007

Hibernate and MS SQL - Unsupported prepareStatement

Insert operation generated by Hibernate didn't work with MS SQL. I was using Hibernate 3.1.2, WAS 6.1, JVM 1.5. And I was testing two JDBC drivers.

For IBM ConnectJDBC for MS SQL,
java.sql.SQLException: [IBM][SQLServer JDBC Driver]Unsupported method: Connection.prepareStatement
at com.ibm.websphere.jdbc.base.BaseExceptions.createException(Unknown Source)
at com.ibm.websphere.jdbc.base.BaseExceptions.getException(Unknown Source)
at com.ibm.websphere.jdbc.base.BaseConnection.prepareStatement(Unknown Source)
at com.ibm.websphere.jdbcx.base.BasePooledConnection.prepareStatement(Unknown Source)
at com.ibm.websphere.jdbcx.base.BaseConnectionWrapper.prepareStatement(Unknown Source)
at com.ibm.ws.rsadapter.jdbc.WSJdbcConnection.pmiPrepareStatement(WSJdbcConnection.java:3980)
at com.ibm.ws.rsadapter.jdbc.WSJdbcConnection.prepareStatement(WSJdbcConnection.java:3854)
For DirectData ConnectJDBC for MS SQL,
java.sql.SQLException: [DataDirect][SQLServer JDBC Driver]Unsupported method: Connection.prepareStatement(String, String[])
at com.ddtek.jdbc.base.BaseExceptions.createException(Unknown Source)
at com.ddtek.jdbc.base.BaseExceptions.getException(Unknown Source)
at com.ddtek.jdbc.base.BaseConnection.prepareStatement(Unknown Source)
at com.ddtek.jdbcx.base.BasePooledConnection.prepareStatement(Unknown Source)
at com.ddtek.jdbcx.base.BaseConnectionWrapper.prepareStatement(Unknown Source)
at com.ibm.ws.rsadapter.jdbc.WSJdbcConnection.pmiPrepareStatement(WSJdbcConnection.java:3980)
at com.ibm.ws.rsadapter.jdbc.WSJdbcConnection.prepareStatement(WSJdbcConnection.java:3854)
There is a saying that the Connection.prepareStatement(String sql, String[] columnNames) is not supported. Workaround solution is to set the "hibernate.jdbc.use_get_generated_keys" to false in the hibernate settings, either in the properties or in the cfg.xml.

Here is the definition of the property.
Enable use of JDBC3 PreparedStatement.getGeneratedKeys() to retrieve natively generated keys after insert. Requires JDBC3+ driver and JRE1.4+, set to false if your driver has problems with the Hibernate identifier generators. By default, tries to determine the driver capabilites using connection metadata.

eg. true|false

Here is the quote from mdiamonte in DataDirect forum.
Against SQL Server 2000, the driver can not implement this method correctly in the general case because SQL Server 2000 does not allow you to return the value of an arbitrary column from an insert, update or delete statement. At least not with out making an extra round trip to the server, which negates the purpose of this method.

I have seen implementations of this method by other drivers where the value returned will be the value of the identity column regardless of which column was actually asked for. I believe that implementation is bad. I feel it is much worse for a driver to return incorrect information than it is to not be able to return the information. Assuming the id column in the statement is an identity column, then Hibernate may have just gotten lucky that it worked in the testing that they did.

Tuesday, August 28, 2007

Migrate WASD 5.1 Application to RSA 7.0/WAS 6.1

Get the application source from Harvest repository. Disconnect Harvest connection.

Create a new web project and ear project in RSA on a new folder. Import source code from the old folder. Compile passed.

Deploy to the embedded WAS 6.1. Run.

Find the tld path problem. Old web.xml sets tlds under WEB_INF/, now application looks tlds under WEB_INF/tlds. Edit web.xml and fix it. WAS 6.1 automatically republishes the app and restart the app.

Get this exception.
[8/28/07 10:49:14:485 EDT] 00000036 WebApp E Exception caught while initializing context
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator' defined in ServletContext resource [/WEB-INF/declarativeServices.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.FatalBeanException: Could not instantiate class [org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator]; constructor threw exception; nested exception is java.lang.NoSuchMethodError: org/objectweb/asm/ClassVisitor.visit(IILjava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)V
org.springframework.beans.FatalBeanException: Could not instantiate class [org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator]; constructor threw exception; nested exception is java.lang.NoSuchMethodError: org/objectweb/asm/ClassVisitor.visit(IILjava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)V
java.lang.NoSuchMethodError: org/objectweb/asm/ClassVisitor.visit(IILjava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)V
Search Google. Find talks on incompatibility of asm, cglib, spring and hibernate. We are using
  • spring-1.2.6
  • hibernate-3.1.2
  • asm-1.5.3
  • cglib-2.1_3
Try to obtain the ear file from production system and deploy to WAS 6.1.

Encounter the same exception.

Several combinations tried. Finally this one worked.

Download spring-framework-1.2.9-with-dependencies.zip and extract the cglib-nodep-2.1_3.jar and replace the original cglib-2.1_3.jar. Redeploy the application in workspace to WAS 6.1 and restart server.

It is possibly both spring framework and hibernate depend on cglib, and further on asm, but they require different asm. cglib-nodep actually packages a revised asm, spring will have no need of a separate asm and let hiberate uses the asm exclusively. Hibernate may actually not need any cglib, but no time for this research yet.

Saturday, August 18, 2007

终于能在Red Hat中键入中文

关键是需要将默认的语言设置成简体中文,然后用Ctrl+Space在中英文之间切换。

默认的输入法是二笔,我不会,改成了智能拼音就好了。和用惯了的全拼有些区别,用用也就习惯了。

简体中文中好多系统菜单翻译得莫名其妙,试了试,不知道怎么切回英文。

Thursday, August 09, 2007

Compare Fuse Message Broker 4.1 to Apache Active MQ 4.1.1

  1. conf\activemq.xml: Fuse has one more block of comments.
  2. installsession_log.xml: only Fuse has.
  3. docs: Fuse has welcome.htm and more images.
  4. etc: only Fuse has etc folder, including license_agreement.txt and notices.txt. Apache puts these two files at the root directory.
  5. example is not compared.
  6. lib: Most differences are on the release number. Fuse is 4.1.2.4, Apache is 4.1.1. One noticable difference is Fuse has xbean-spring-fuse-2.7.0.0.jar, but Apache has xbean-spring-2.8.jar.

Monday, August 06, 2007

Unit Test - Piece of Logic Covered or Not?

Emma coverage report will show uncovered pieces of logic red. For example,
if (validField(fk.getName(), valueFK)) {
criteria.add(buildRestriction(propertyTypes[i], value, relationName));
criteriaCount.add(buildRestriction(propertyTypes[i], value, relationName));
}
In the unit test, you will need to make the validField returns true. And then the report will show them covered and mark them green.

JMS Implementation with RSA 7.0 and WAS 6.1

Environment:
IBM Rational Software Architect 7.0 with embedded WebSphere Application Server 6.1.

Purpose:
  • Create a JMS client application to send a simple message to a queue defined by WAS 6.1 default messaging provider.
  • Create a MDB to consume the message received by the queue.
Development:
  1. Open RSA, use the New wizard to create an Enterprise Application Project under J2EE group, if you cannot see this selection, check if you are using the J2EE perspective. I called the project minzy.
  2. Click "Show Runtimes" to make sure the v6.1 is selected.
  3. Click "New Modules" to create default modules, check off Web module and Connector module, which we don't need, and change the name of the EJB module to minzyEnt. It's only my preference, you can call it any name.
  4. Rename source folders to "src" in both minzyClient and minzyEnt.
  5. In minzyClient, create a package "tliu.minzy.client" and create a class "MessProducer" with main method.
  6. Delete default package.
  7. Edit MANIFEST.MF under META-INF and change Main-Class to tliu.minzy.client.MessProducer.
  8. From menu Project, select clean and select minzyClient, minzyEnt and minzy, error in minzy and minzyClient will be gone.
  9. In minzyEnt, create package tliu.minzy.ent, use New wizard to create a Enterprise Bean.
  10. Check "Message-driven bean", give name MessConsumer, select package tliu.minzy.ent and check on "Generate an annotated bean class".
  11. Make sure JMS type is javax.jms.MessageListener.
  12. Check off "Add bean to Class Diagram", diagrams are out of the scope.
  13. Now you see all error gone, we are ready to put real codes in.
Code in MessProducer:
    public static void main(String[] args) throws Exception {
InitialContext initCtx = new InitialContext();
javax.jms.ConnectionFactory qcf = (javax.jms.ConnectionFactory) initCtx.lookup("jms/minzyConnectionFactory");
Destination q = (Destination) initCtx.lookup("jms/minzyQueue");
Connection connection = qcf.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer queueSender = session.createProducer(q);
TextMessage outMessage = session.createTextMessage();
outMessage.setText("Hello, minzy.");
outMessage.setJMSType("minzy");
outMessage.setJMSDestination(q);
queueSender.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
queueSender.send(outMessage);
connection.close();
System.out.println("Minzy mess produced.");
}
Code in MessConsumerBean:
    public void onMessage(javax.jms.Message mess) {
TextMessage text = (TextMessage) mess;
try {
System.out.println("Message Received: " + text.getText());
} catch (JMSException e) {
System.out.println("Oops, exception.");
}
}
Packaging:
Export minzyClient to C:\development\applications\minzyClient.ear.
Export minzyEnt to C:\development\applications\minzyEnt.ear.

Deployment:
  1. In Servers view in RSA, select WebSphere Application Server v6.1 and start the server.
  2. After started, right click the server and select "Run administrative console".
  3. Navigate Service integration > Buses > New and create a bus "minzyBus".
  4. Navigate minzyBus > Bus members > Add and add server "cledt-123691Node02:server1".
  5. Open a command window, and change directory to "C:\Program Files\IBM\SDP70\runtimes\base_v61\bin", run "setupCmdLine.bat".
  6. Run "wsadmin -f installSdoRepository.jacl -createDb cledt-123691Node02 server1".
  7. Verify SDO Repository successfully started under Enterprise Applications. Note, install once per server.
  8. Run "wsadmin -f ../util/sibwsInstall.jacl INSTALL_RA -installRoot "C:/Program Files/IBM/SDP70/runtimes/base_v61" -nodeName cledt-123691Node02". Note, install once per node.
  9. Run "wsadmin -f ../util/sibwsInstall.jacl INSTALL -installRoot "C:/Program Files/IBM/SDP70/runtimes/base_v61" -serverName server1 -nodeName cledt-123691Node02".
  10. Run "wsadmin -f ../util/sibwsInstall.jacl INSTALL_HTTP -installRoot "C:/Program Files/IBM/SDP70/runtimes/base_v61" -serverName server1 -nodeName cledt-123691Node02".
  11. In the admin console, navigate to Servers > Application Servers > server1 > Endpoint Listeners and select New. Specify SOAPHTTPChannel1 as name, http://cledt-123691.agna.amgreetings.com:9081/SOAPHTTPChannel1 as URL root, http://cledt-123691.agna.amgreetings.com:9081/sibws as WSDL root.
  12. Select the "Connection Properties" of SOAPHTTPChannel1, client New and select minzyBus.
  13. Go to minzyBus > Destinations, there should be a new destination called cledt-123691Node02.server1.SOAPHTTPChannel1Reply.
  14. Navigate minzyBus > Destinations > New and create a Queue type destination "minzyDestination".
  15. Navigate Resources > JMS Providers > Default messaging. Select Node as the scope.
  16. Select Connection factories and click New. Enter minzyConnectionFactory as name, jms/minzyConnectionFactory as JNDI name, select minzyBus, enter localhost:7277 in the "Provider endpoints" box, leave other default and click OK.
  17. Go back to Default messaging provider and select Queues. Click New.
  18. Enter minzyQueue as name, jms/minzyQueue as JNDI name, select minzyBus and minzyDestination. Click OK.
  19. Go back to Default messaging provider and select Activation specifications. Click New.
  20. Enter minzyActivation as name, eis/minzyActivation as JNDI name, jms/minzyQueue as Destination JNDI name and select minzyBus. Click OK and save all your changes.
  21. Install minzyEnt.ear in admin console. Make sure Deploy enterprise beans are checked. Enter eis/minzyActivation as Activation Specification Target and jms/minzyQueue as Destination.
  22. Restart server.
Run:

In a command line window, change directory to C:\Program Files\IBM\SDP70\runtimes\base_v61\bin. Run,

setupCmdLine.bat
launchClient \development\applications\minzyClient.ear -CCBootstrapPort=2810

In the command line window, you shall see,
WSCL0014I: Invoking the Application Client class tliu.minzy.client.MessProducer
Minzy mess produced.

In the server console, you shall see,
[8/6/07 13:33:32:455 EDT] 0000002f SystemOut O Message Received: Hello, minzy.

The End.

Thursday, August 02, 2007

WAS 6.1 - JMS Default Provider Administrative Aspect

In WAS 6.1, there is a default messaging JMS provider. It comes with WAS 6.1.

To list messages in a queue, go through this path,

Service integration > Buses > [TheBus] > Messaging engines > [cledt-123691Node01.server1-TheBus] > Queue points > [MyQueueDestination@cledt-123691Node01.server1-TheBus] > Runtime

you see the "Current message depth".

Select "Messages", you see messages and their position, identifier, state and transaction id. You can select any of them and click "Delete" or just click "Delete all" to delete them from the queue.

The message's identifier is actually a link. Click it to get the detail of the message. It shows
identifier, state, transaction id, message type, approximate length, time stamp, message wait time, current messaging engine arrival time, redelivered count, security user id, producer type, message id, correlation id, user id, format, JMS delivery mode, JMS expiration, JMS destination, JMS reply to destination, JMS redelivered, JMS type, JMSX delivery count, JMSX application id, discriminator, priority, reliability, time to live, reply discriminator, reply priority, reply reliability, reply time to live and system message id. All attributes are read only.

Click "Message body", you will get "Approximate total message size" in bytes, message body. The message body is also read only.

You can define Performance Monitoring Infrastructure(PMI) to collect JMS runtime statistics. You will need a PMI client to view these statistics. So far, Tivoli Performance Viewer(TPV) is the only known PMI client to us. TPV has not been tested so far. According to IBM, TPV comes with WAS 6.1 and is free.

Wednesday, July 25, 2007

WAS 6.1 in RSA 7.0

Try to run WAS 6.1 in RAS 7.0. Find conflict on port 2810.

In WAS 6.1, RMI ORB bootstrap port is defined 2810. Modify it to 7810.

Start WAS 6.1, still complain on port 2810. Restart RAS 7.0.

Profile name "AppSrv01", server name "server1".

From its log, it started. but in the RSA console, it still says starting. Also the publish failed and complained not started.

Even after 30 minutes, it still says starting. So I stopped it.

Restarted the workstation. Found port 2810 gone. Modify WAS 6.1 port back to 2810. Restart RSA.

Start WAS 6.1 and started.

Sunday, June 10, 2007

Fodero Core 5 Package Updater

I was having trouble with FC 5 Package Updater. This is out of the topic, but it is a good experience anyway.

I then opened a terminal window and run "yum update". It reported the error at Macromedia update. After some research, I was suggested replacing the /etc/yum.repos.d/macromedia-mplug.repo with the following content.

[macromedia]
name=Macromedia for i386 Linux
#baseurl=http://macromedia.rediris.es/rpm/
baseurl=http://sluglug.ucsc.edu/macromedia/rpm/
enabled=1
gpgcheck=1
#gpgkey=http://macromedia.mplug.org/FEDORA-GPG-KEY
gpgkey=http://sluglug.ucsc.edu/macromedia/FEDORA-GPG-KEY

After that, the Package Update came back to normal.

Thursday, May 31, 2007

Unique ID Generation

Generating globally unique IDs in a clustered, distributed environment is a common application requirement. A simple way is to combine the following four parts together.
  1. Unique to the System.currentTimeMillis()
  2. Unique to the IP address
  3. Unique to the object instance System.identityHashCode(this)
  4. Unique within a millisecond, SecureRandom
All ints and longs will be converted to a hex string of length 8.

A open source named Java UUID Generator is available at http://jug.safehaus.org/.

Business Delegate and Session Facade

What would the cardinality generally be between the Business Delegate objects and the Session Facade?

ONE to ONE. Often, the business delegate will have the same API as the session facade.

There is a close relationship between the BD and the SF. The client layer interacts with a BD. The BD would in turn, employ the Service Locator pattern to locate the SF. It is common to see a one-to-one mapping between the BD and the SF.

Monday, May 28, 2007

Testing Glossary

  • Black-box testing - testing that verifies that given input A the component or system being tested gives you expected results B.
  • Boundary-value testing - testing of unusual or extreme situations that your code should be able to handle.
  • Function testing - a part of system testing in which development staff confirm that their application meets the specified user requirements.
  • Integration testing - testing that verifies that several portions of software work together.
  • Regression testing - testing that ensures previously tested behaviors still work as expected after changes have been made to an application.
  • Stress testing - testing that ensures the system performs as expected under a high volume of transactions, high number of users, and so on. Also referred to as load testing.
  • White-box testing - testing that verifies specific line of code work as defined. Also referred to as clear-box testing.
  • Alpha testing - a testing period in which pre-release versions of software products are released to users who need access to the product before it it officially deployed. In return, these users will report any defects to the software developers. Alpha testing is typically followed by beta testing.
  • Beta testing - a similar process to alpha testing, except the software product should be less buggy.
  • Code inspection - a form of technical review in which the deliverable being reviewed is source code.
  • Peer view - a style of technical review in which a project artifact, or portion thereof, is inspected by a small group of experts.
  • Use-case scenario testing - a testing process in which users work through use cases with the aid of a facilitator to verify that a user interface prototype fulfills the needs of its users and that the identified classes for a system fulfill the requirements described in the use cases.
  • User testing - testing processes in which the user community, as opposed to developers, performs the tests.
  • User-interface testing - the testing of the user interface to ensure that it follows accepted standards and meets its requirements. User-interface testing is often referred to as graphical user interface (GUI) testing.

Friday, May 25, 2007

Session Data in Multiframed JSPs

Update or create a session in only one frame or before accessing any frame sets. For example, assuming there is no session already associated with the browser and a user accesses a multiframed JSP files, the browser issues concurrent requests for the JSP files. Because the requests are not part of any session, the JSP files end up creating multiple sessions and all the cookies are sent back to the browser. The browser honors only the last cookie that arrives. Therefore, the client can only retrieve the session associated with the last cookie. Creating a session before accessing multiframed pages that utilize JSP files is recommended.

JSPs will, be default, create an HttpSession if it does not already exist. A developer can use <% @page session="false" %> to turn off the automatic session creation from the JSP files that will not access the session. Then if the page needs access to the session information, the developer can use <% HttpSession session = HttpServletRequest.getSession(false); %> to get the already existing session that was created by the original session creating JSP file. This action helps prevent breaking session affinity on the initial loading of the frame pages.

Web Application Session Data

  • When developing new objects to be stored in the HTTP session, they should implement Serializable to ensure that they can be persisted into a database or send via the message server if clustered sessions are enabled by the system administrator.
  • Maximize use of session affinity and avoid breaking affinity. Session affinity is enabled by default in WebSphere Application Server. It ensures that, except for hardware or software fail-over, requests are handled by the container which initialized that session. Session clustering may be used in addition to affinity to handle fail-over.
  • Release HttpSessions when done, call HttpSession.invalidate(). Otherwise the session objects remain in memory until the session timeout expires.
  • It does not make sense to protect access to session state only part of the time.
  • Distributed HttpSession support does not guarantee transactional integrity of an attribute in a failover scenario or when session affinity is broken.

Tuesday, May 22, 2007

Syntactic and Semantic

Validation comes in two types:
  • Syntactic -- this involves checking for the format of a field, e.g. number of characters, alpha or numeric, membership in a list, and so forth. This needs to be repeated on the server because of the issues with JavaScript being turned off, loss of synchronization between the two languages in a project.
  • Semantic -- this requires domain (business) logic to perform, e.g. comparing postal code with city, and so forth.

Monday, April 30, 2007

Combine Intercepting Filter and Template Method

You can use a base filter which serves as a common superclass for all filters. Common features can be encapsulated in the base filter and shared among all filters. For example, a base filter is a good place to include default behavior for the container callback methods.

At the mean time, template method can be also integrated into the base filter. As shown in this diagram.

Intercepting Filter Pattern

This pattern creates pluggable filters to process common services in a standard manner without requiring changes to core request processing code. The filters intercept incoming requests and outgoing responses, allowing preprocessing and post-processing. We are able to add and remove these filters unobtrusively, without requiring changes to our existing code.

We are able, in effect, to decorate our main processing with a variety of common services, such as security, logging, debugging, and so forth. These filters are components that are independent of the main application code, and they may be added or removed declaratively. For example, a deployment configuration file may be modified to set up a chain of filters. The same configuration file might include a mapping of specific URLs to this filter chain. When a client requests a resource that matches this configured URL mapping, the filters in the chain are each processed in order before the requested target resource is invoked.

Possible types of filters include:

  • Authentication filters
  • Logging and auditing filters
  • Image conversion filters
  • Data compression filters
  • Encryption filters
  • Tokenizing filters
  • Filters that trigger resource-access events
  • XSL/T filters that transform XML content
  • MIME-type chain filters
  • Filters that cache URLs and other information

Note: As for J2EE, filters are a new feature of the version 2.3 Java Servlet specification.

Tuesday, April 03, 2007

1998/99: A year after taking talented high school star Tracy McGrady in the draft the Raptors select his cousin Vince Carter who was a star at UNC. However, Toronto fans would have to wait to see the talented cousins in action as a 4-month lockout delayed the start of the season. When the season started the Raptors new arena was almost ready, as they beat the Vancouver Grizzlies 102-87 in their first game at the Air Canada Centre on February 21st. After years of playing in the spacious SkyDome the Raptors finally had an arena built for basketball and they clearly benefited as they finally escaped last place by posting a record of 23-27. Leading the promising Raptors was Vince Carter who became the 2nd Raptor in 4 years to win Rookie of the Year with 18.3 ppg. At season's end Carter took the microphone and addressed the ACC crowd after the final game and guaranteed a trip to the post-season next year.

1999/00: With the off-season acquisition of Antonio Davis for a high draft pick, the Raptors not only got older, they got a whole lot better. As Davis along with Charles Oakley who was acquired a year earlier provided veteran stability to a young talented team. The veteran presence helped make Vince Carter into an All-Star as he received the second most amount of all star votes ever while stealing the show in the Slam Dunk Contest which he won easily. Carter would go on to average a team high 25.7 ppg while his cousin Tracy McGrady finished second with 15.4 ppg, as the Raptors fulfilled Vince Carter's guarantee with a 45-37 record. However, in the playoffs the inexperienced Raptors would be schooled by the playoff tested New York Knicks losing in 3 straight games. Following the season, the Raptors would be jilted by Tracy McGrady, who decided to seek his own fame, out of his cousin's shadow by signing with the Orlando Magic.

2000/01: After their first playoff appearance the Raptors decided to go after a Hall of Fame coach, to lead the team to the next step as the hired al-time winingest Coach Lenny Wilkins. Vince Carter continued to establish himself as the next big star in the NBA by leading the Raptors with an impressive 27.6 pp, after exhibiting show-stopping dunks in the Olympics with Team USA. With the continued improvement of Vince Carter the Raptors would finish in 2nd place with a solid record of 47-35. In the playoffs the Raptors were matched up against the New York Knicks for the second year in a row. After splitting the first 2 games in New York the Raptors appeared to be heading for a disappointing exit again after they lost Game 3 at the ACC 97-89. However, the Raptors would send the series back to New York by winning Game 4 100-93. In the decisive 5th game in New York the Raptors would stun the Knicks 93-89 to advance to the 2nd round. In the 2nd round the Raptors were matched up against the top seed Philadelphia 76ers. However the Raptors would give the 7ers all they could handle as the battled tooth and nailed all the way to a 7th game where Vince Carter missed a buzzer beater with the Raptors down 88-87, which would have sent the Raptors on the Eastern Conference Finals.

2001/02: After experience success in the playoffs the Raptors were able to sign Vince Carter to a long-term multimillion-dollar deal to ensure their marquee stars for years to come. In addition the Raptors would add even more star power by acquiring future Hall of Famer Hakeem Olajuwon from the Houston Rockets. The Raptors appeared to be heading for another strong season as they held a record of 29-21 entering the all-star break. However, in the final game before the break Vince Carter suffered a knee injury that would hamper their star for the rest of the season. In the second half the Raptors lost 18 of 19 games including, 13 straight games following the break. With all hopes of the playoff seemingly lost Vince Carter decided to undergo knee surgery. However, the Raptors would suddenly turn thing around as they won 8 straight without Vince Carter to get back into the playoff picture. The Raptors would do on to slip into the playoff as the 7th seed with a record of 42-40. In the playoffs the Raptors would get off to a shaky start as they dropped the first 2 games on the road to the Detroit Pistons. However, coming home the Raptors would rebound nicely winning 2 games at ACC to force a decisive 5th game. In Game 5 at Detroit the Raptors gave the Pistons all they could handle before losing 85-82.

2002/03: Things looked bleak for the Raptors early in the season as Hakeem Olajuwon announced his retirement following a disappointing first season in Toronto. In addition Vince Carter continued to feel the lingering effect of his knee injury as he missed most of the first half. However, some former teammates and NBA observes began to question Carter's heart and desire and he didn't seem to be a hurry to get back in the lineup. This view was even given further ammo when Carter was dancing on stage with Nelly as the Raptors, were getting blown out by the Hawks in Atlanta. The Raptors would have all hopes for the playoff buried in January as they held a record of 8-28, which included a 12-game losing streak. Vince Carter would return and play most of the second half, averaging 20.6 ppg, but the Raptors struggles continues as Coach Lenny Wilkins who already held the record for most career wins set the record for most career losses as a coach, while the Raptors finished in 7th place with a disappointing record of 24-58. Following the final game GM Glenn Grunwald apologized to the fans at ACC announcing changes would be made. He would get started right away by firing Coach Lenny Wilkins.

2003/04: With new Coach Kevin O'Neill the Raptors started the season on a high note beating the 2-time Eastern Conference Champion New Jersey Nets 90-87. However a few days later they would set an embarrassing post shot clock record by scoring just 56 points in a loss to the Minnesota Timberwolves. That kind of inconsistency would become the hallmark of the Raptors all season, at times they looked like genuine playoff contenders, while others they looked like a last place team. At 8-8 the Raptors pulled off a blockbuster deal with the Chicago Bulls on December 1st acquiring Jalen Rose, Donyell Marshall, and Lonny Baxter in exchange for Antonio Davis, Jerome Williams, and Chris Jefferies. The Raptors would win their first 3 games after the deal but won just 1 of 7 following the initially strong start as the Raptors continued through out the entire first half as they sat at 25-25 at the All Star Break. However after the all star break injuries would become a problem as the Raptors won just 8 games the rest of the way finishing with a 33-49 record. Following the season the Raptors would fire Coach O'Neill choosing to go with Sam Mitchell.

2004/05: The Sam Mitchell era got off to a good start as the Raptors won 4 of their first 5 games. However the joy was short lived as the Raptors came back to earth fast, as a disgruntled Vince Carter continued to sulk, which hit rock bottom in a November 12th loss in Seattle as he told the Supersonics what play the team was going to run in the waning moments of an 88-87 loss. Through December the Raptors struggled badly winning just 3 of 15 games, as they finally gave up on Vince Carter as he was traded to the New Jersey Nets for Eric Williams, Aaron Williams, Alonzo Mourning, and two first-round draft picks. Mourning a future Hall of Famer refused to play for the Raptors and forced a buyout as he returned to the Miami Heat where he had his best years. Meanwhile the Raptors would go to finish tied for last place in the Atlantic Division with a 33-49 record, while Chris Bosh started to emerge as the new star of the Toronto with a solid 16.8 ppg and 8.9 rpg in just his second year.

2005/06: Under new Coach Sam Mitchell not much was expected from the Raptors who were clearly in a rebuilding mindset as they were still feeling the effects of the Vince Carter deal, in which they got nothing substantial in return, while many questioned their decision to draft Charlie Villanueva. When the season start the Raptors were struggling to match even their low expectations as they lost 15 of their first 16 games. In December the Raptors would show some improvement as they split 14 games as Chris Bosh put together an All-Star season leading the Raptors with 22.5 ppg. The Raptors would continue to play .500 ball in an up and down January that saw them set a franchise record for points in a game while a week later they were torched by Kobe Bryant for 81 points. January would also see changes in Management as GM Mike Babcock was fired and eventually replaced by Bryan Colangelo. The Raptors would close the season much as they begun losing 12 of their last 13, with Chris Bosh injured as they finished in 4th Place with a 27-55 record. The Raptors poor record would have one beneficial side effect as they won the top pick in the draft lottery which they used on Italian prodigy Andrea Bargnani, making him the first European drafted number one overall. While they would trade Charlie Villanueva, who would prove critics wrong by finishing second in Rookie of the Year Voting to the Milwaukee Bucks for play making Point Guard T.J. Ford.

猛龙队史 - 97/98

满满两年的阳光,挡不住那一夕的阴雨。

坎比等等五员大将相继倒下,被伤病浸透的猛龙无奈迎来十七连败。以色亚辞职,达蒙声言必不留营。

猛龙无奈,只好交换达蒙,虽然也换来了昌西-比卢普斯,但当时的昌西尚是菜鸟,远非今日的BIG SHOOT。

猛龙一蹶不振,16-66,全联盟垫底。

猛龙队史 - 96/97

猛龙步入第二年,以色亚-托马斯慧眼识英豪,继上一季选中最佳新秀达蒙-司徒麦尔之后,再度选中马库斯-坎比。达蒙该季的得分已经上升到了20.2分,而坎比也以场均14.7分和6.3个篮板入选了新秀挑战赛。

依然是小鬼当家,猛龙虽然战胜了诸如公牛、爵士和火箭这样的决赛圈队伍,却也输给波士顿三场。公牛是当年的总冠军,爵士和火箭则是西区的冠亚军,而波士顿一季不过才胜了15场。

第二年,30-52猛龙依然中区殿底。

猛龙队史 - 95/96

1946年11月1日,NBA的前身BAA开始了联盟的第一场球赛。

为了纪念那位加拿大人--篮球之父奈施密斯教授,第一场比赛被特意安排在多伦多开球。可惜天公不做美,多伦多HUSKIES队以66比68败给了来访的纽约尼克斯队。此后,BAA脱胎成了NBA,尼克斯也成了NBA的基石,而HUSKIES却以15-45的惨淡战绩仅生存了一个赛季便黯然收场。

光阴似箭,时光荏苒,这一去就是五十年。

九五年,正是朱罗纪公园大红大紫的那一年,顺着这股狂热,
猛龙从天而降。11月3日,也是多伦多的主场,猛龙迎战蓝网,94比78猛龙破网而出。

好彩头却依然是烂成绩,赛季结束的时候,猛龙仅仅胜了21场而排在中区最末。

虽然如此,那一季的猛龙却也是可歌可泣。一是3月24日,猛龙主场以109-108击败公牛,而那正是公牛以72-10的战绩横扫联盟的那个赛季。二是达蒙-司徒麦尔以
场均19.0分和9.3助攻当选年度最佳新秀。

Monday, March 05, 2007

ThreadLocal – A Wrapper Class for Thread Safe

In his article “Thread-safe webapps using Spring”, Steven Devijver talked about the idea behind the thread-safe template classes through which Spring achieves the Data Access Abstraction.

Basically the template thread-safe is fulfilled by using a wrapper class "ThreadLocal". The following code provides a simple example that shows how the ThreadLocal class work.

private static ThreadLocal pi = new ThreadLocal();

public Double pi() {
if (pi.get() == null) {
pi.set(new Double(22 / 7));
}
return (Double)pi.get();
}

ThreadLocal class wraps any object and binds it to the current thread thus making objects local to the thread. When a thread executes the pi() method for the first time there will be no object bound to the thread by ThreadLocal instance pi so the get() method will return null.The set() method will bind an object to the thread that is not shared by other threads. If the method pi() is called often per thread this approach may still offer a considerable performance gain while guaranteeing thread-safety.

Thursday, February 22, 2007

Is RMI Thread Safe?

When the thread safety question extends to the remote calls, e.g. RMI, it becomes even more interesting.

According to the specification defined with Java 1.4.2, RMI section 3.2,
A method dispatched by the RMI runtime to a remote object implementation may or may not execute in a separate thread. The RMI runtime makes no guarantees with respect to mapping remote object invocations to threads. Since remote method invocation on the same remote object may execute concurrently, a remote object implementation needs to make sure its implementation is thread-safe.
No matter how confusing this specification is, it at least tells us two things,
  1. RMI does not take care of the thread safety, it leaves the thread safety as it is.
  2. RMI does not give you one server thread for one client thread, actually, it guarantees nothing on the thread scheduling.
It sounds a little bit discouraging, but it is good enough already since it does not break the thread safety either.

As long as both the client objects and the server objects are thread-safe, the application is thread-safe.

Wednesday, February 21, 2007

Please! Don't Thread Safe Everything!

Thread safe is good, but please, don't do it everywhere. Do it only when instances will be used concurrently by multiple threads. We have three reasons to say that.
  • Unnecessary synchronized method invocations (and synchronized blocks) can cause unnecessary blocking and unblocking of threads, which can hurt performance.

  • Immutable objects tend to be instantiated more often, leading to greater numbers of often short-lived objects that can increase the work of the garbage collector.

  • Synchronization gives rise to the possibility of deadlock, a severe performance problem in which your program appears to hang.
None of these performance setbacks are good excuses for neglecting to make classes that need to thread-safe so, but they do constitute good reasons not to make classes thread-safe unnecessarily.

Way to Thread Safety - Wrapper

Wrapper is to embed an object in a thread-safe wrapper object. In this approach you leave the original class (which isn't thread-safe) unchanged and create a separate class that is thread-safe. Instances of the new class serve as thread-safe "front ends" to instances of the original class.

This approach makes the most sense when you want to give clients a choice between a version of a class that is thread-safe and one that isn't. It also makes sense when you're a client of someone else's class that isn't thread-safe, but you need to use the class in a multithreaded environment. Once you define your own thread-safe wrapper for the class, you can safely use the class in a multithreaded environment by going through your wrapper.

A good example of this approach from the Java API comes from the 1.2 collections library. The 1.2 collections library defines a hierarchy that includes classes that represent many kinds of collections -- none of which are thread-safe. But class Collection includes several class methods that will enclose a regular collection object in a thread-safe wrapper, so you can safely use the object in a multithreaded context. This design gives users of the collections library a choice of using a collections object that is thread-safe and one that isn't.

Note that a common attribute of wrapper classes like those you would use to add thread safety to the enclosed object is that the wrapper accepts the same messages as the enclosed object. In other words, often a wrapper class will descend from a common superclass or superinterface with the enclosed class. (For those of you familiar with the Design Patterns book by Gamma, et. al., this is the "decorator" pattern.) This decorator design approach to wrappers, which is exhibited by the thread-safe wrappers of the 1.2 collections library, allows the thread safety to be dynamically added or removed from an object.

Way to Thread Safety - Immutable

An immutable object is one whose state can't be changed once the object is created. Immutable objects are, by their very nature, thread-safe simply because threads have to be able to write to an object's instance variables to experience a read/write or write/write conflict. Because no methods (only the constructor) of an immutable object actually write to the object's instance variables, the object is by definition thread-safe.

In this approach to making an object thread-safe, you don't mark critical sections as synchronized. Instead, you separate out the critical sections that read instance variables from those that write to instance variables. The critical sections that read are left as-is. The critical sections that write must be changed so that, instead of altering the current object's instance variables, they create a new object that embodies the new state and returns a reference to that object.

It works well when objects are small and represent values of a simple abstract data type. The Java API includes several examples of immutable objects, including String and the primitive type wrappers such as Integer, Long, Float, Boolean, Character, and so on.

It also lets you pass references to them to methods without worrying that the method will change the object's state. In addition, if the overhead of immutability (excessive creation of short-lived objects) may at times be too inefficient, you can also define a mutable companion class that can be used when the immutable version isn't appropriate. An example of this design approach in the Java API is the StringBuffer class, which serves as a mutable companion to the immutable String class. Note that the StringBuffer class is also thread-safe, but it uses the "normal" approach: its instance variables are private and its critical sections are synchronized.

Way to Thread Safety - Synchronization

The most straightforward way to correct the unruly behavior exhibited by non thread safe objects when placed in a multithreaded context is to synchronize the object's critical sections.

An object's critical sections are those methods or blocks of code within methods that must be executed by only one thread at a time. Put another way, a critical section is a method or block of code that must be executed atomically, as a single, indivisible operation. By using Java's synchronized keyword, you can guarantee that only one thread at a time will ever execute the object's critical sections.

This approach takes two steps, to make all relevant fields private, and to identify and synchronize all the critical sections.

Any field that you need to coordinate multithreaded access to must be private, otherwise it may be possible for other classes and objects to ignore your critical sections and access the fields directly. Not every field must be private - only those that will be involved in any temporarily invalid states created by the object's or class's critical sections. For example, constants (static final variables) can't be corrupted by multiple threads, so they needn't be private.

A critical section is a bit of code that must be executed atomically, that is, as a single, indivisible operation.

Note that reads and writes of primitive types and object references are atomic by definition, except for longs and doubles. This means that if you have an int, for example, that is independent of any other fields in an object, you needn't synchronize code that accesses that field. If two threads were to attempt to write two different values to the int concurrently, the resulting value would be one or the other. The int would never end up with a corrupted value made up of some bits written by one thread and other bits written by the other thread.

The same is not necessarily true, however, for longs and doubles. If two different threads were to attempt to write two different values to a long concurrently, you might just end up with a corrupted value consisting of some bits written by one thread and other bits written by the other thread. Multithreaded access to longs and doubles, therefore, should always be synchronized.

For example, a Price class has two instances variables, double priceValue and Date effectiveDate. And the class has a updatePrice method,

public void updatePrice(doubel priceValue, effectiveDate) {
this.priceValue = priceValue;
this.effectiveDate = effectiveDate;
}

The way to make Price thread safe is to make the priceValue and the effectiveDate private first,
then synchronize the updatePrice method.

public synchronized void updatePrice(double priceValue, effectiveDate) {
...
}

or

public void ... {
synchronized (this) {
this.priceValue = priceValue;
this.effectiveDate = effectiveDate;
}
}

Thread Safety - How to Tell

In a multithreaded environment, instances of non thread safe classes are susceptible to two kinds of misbehavior: write/write conflicts and read/write conflicts. From any of these two conflicts, you can tell that the class is not thread safe.

Write/write conflicts

Imagine two threads are trying to write to the same object's instance variables concurrently. If the thread scheduler interleaves these two threads in just the right way, the two threads will inadvertently interfere with each other, yielding a write/write conflict. In the process, the two threads will corrupt the object's state.

Read/write conflicts

This kind of conflict arises when an object's state is read and used while in a temporarily invalid state due to the unfinished work of another thread.

This is like the ACID characteristics of transactions. As long as it takes two or more steps to move an instance from one state to another state, the class is very unlikely thread safe.

Tuesday, February 20, 2007

Thread Safety - Where to Worry About

Given the architecture of the JVM, you need only be concerned with instance and class variables when you worry about thread safety. Because all threads share the same heap, and the heap is where all instance variables are stored, multiple threads can attempt to use the same object's instance variables concurrently. Likewise, because all threads share the same method area, and the method area is where all class variables are stored, multiple threads can attempt to use the same class variables concurrently. When you do choose to make a class thread-safe, your goal is to guarantee the integrity -- in a multithreaded environment -- of instance and class variables declared in that class.

You needn't worry about multithreaded access to local variables, method parameters, and return values, because these variables reside on the Java stack. In the JVM, each thread is awarded its own Java stack. No thread can see or use any local variables, return values, or parameters belonging to another thread.

Five Categories of Thread Safety

In his Effective Java, Joshua Bloch described five categories of thread safety: immutable, thread-safe, conditionally thread-safe, thread-compatible, and thread-hostile.
  • Immutable objects are guaranteed to be thread-safe, and never require additional synchronization. Because an immutable object's externally visible state never changes, as long as it is constructed correctly, it can never be observed to be in an inconsistent state. Most of the basic value classes in the Java class libraries, such as Integer, String, and BigInteger, are immutable.
  • Thread-safe classes are safe not only for single call, but also for multiple calls combined. They will need no additional synchronzation from their callers. This thread-safety guarantee is a strong one -- many classes, like Hashtable or Vector, will fail to meet this stringent definition.
  • Conditionally thread-safe classes are those for which each individual operation may be thread-safe, but certain sequences of operations may require external synchronization. The most common example of conditional thread safety is traversing an iterator returned from Hashtable or Vector -- the fail-fast iterators returned by these classes assume that the underlying collection will not be mutated while the iterator traversal is in progress. To ensure that other threads will not mutate the collection during traversal, the iterating thread should be sure that it has exclusive access to the collection for the entirety of the traversal. Typically, exclusive access is ensured by synchronizing on a lock -- and the class's documentation should specify which lock that is (typically the object's intrinsic monitor).
  • Thread-compatible classes are not thread-safe, but can be used safely in concurrent environments by using synchronization appropriately. This might mean surrounding every method call with a synchronized block or creating a wrapper object where every method is synchronized (like Collections.synchronizedList()). Or it might mean surrounding certain sequences of operations with a synchronized block. To maximize the usefulness of thread-compatible classes, they should not require that callers synchronize on a specific lock, just that the same lock is used in all invocations. Doing so will enable thread-compatible objects held as instance variables in other thread-safe objects to piggyback on the synchronization of the owning object. Many common classes are thread-compatible, such as the collection classes ArrayList and HashMap, java.text.SimpleDateFormat, or the JDBC classes Connection and ResultSet.
  • Thread-hostile classes are those that cannot be rendered safe to use concurrently, regardless of what external synchronization is invoked. Thread hostility is rare, and typically arises when a class modifies static data that can affect the behavior of other classes that may execute in other threads. An example of a thread-hostile class would be one that calls System.setOut().

Monday, February 19, 2007

Generic Five Steps to Create JAX-RPC Web Service

The first stage is to write the interface to declare the remote methods to expose and to write the implementation class for those methods.

For the second stage, you typically run some kind of mapping tool to generate the WSDL description for the web service which maps the interface.

The third step is to run a mapping tool on the WSDL file to create the stub and tie classes which are required to allow remote client access.

The next step is to compile all the generated files and package them into an archive file, typically a WAR (Web Application Archive) file.

Finally, you deploy the web service onto a web server with a built-in SOAP engine.

Decompile .class in Eclipse

Don't you hate the "Source Not Found" while you are debugging in Eclipse?

OK yes, you can do this.
  1. download JAD at http://www.kpdus.com/jad.html and then install it on your workstation.
  2. download JAD Eclipse plugin at http://sourceforge.net/projects/jadclipse/ and then install it with your Eclipse.
  3. restart your Eclipse and click Window->Preferences->Java->JadClipse and finish the configuration.
Congratulations! .class is no longer a black box.

Wednesday, January 03, 2007

Property Editor Not Visible in Weblogic Workshop 8.1

Sometimes the Property Editor will be not visible in Workshop.

Search for the .workshop.pref and .workshop.zpref. Move them to another folder, e.g. the desktop.

Restart Workshop, the Property Editor will be visible. You will also notice that these two files will be recreated.

Monday, December 11, 2006

netui drop-down list

You can specify the options to a LinkedHashMap so the list will be presented as the same order as creation.

You need to set attributes of the Form Bean if the value of the drop-down list is associated with the Form Bean. Or the default value such as 0 for int will be inserted into the list.

Thursday, December 07, 2006

JAXP Introduction

JAXP is very adaptable. It essentially functions as an abstraction layer between your code and different vendors' XML processor implementations.

It allows you to plug in different DOM and SAX parsers, and XSLT (Extensible Stylesheet Language Transformation) transformers, as you require without needing to change your code. This is known as a pluggablility layer. The processor can be set by changing the appropriate environment variable. Attention, it doesn't mean you can swap between DOM and SAX.

JAXP also comes with its own default parsers that implement SAX and DOM functionality.

Simple API for XML (SAX) is an API for event-based parsing of XML documents. This means a SAX parser reads the XML document from beginning to end using a data stream. Any time it encounters a new element, it throws an event to notify the application running it. The application can then handle these events as required.

SAX comes with a number of methods that you can use to recognize an event. You then respond to these events by either implementing a specific interface or extending the default handler and overriding the appropriate method. SAX does not allow you to modify the XML document, it can only read it.

The Document Object Model (DOM) API is a World Wide Web Consortium (W3C) specification for parsing XML. It builds a representation of an XML document in memory in a tree structure. You can navigate this tree to search for elements, which correspond to branches. You can also insert new elements into the tree and remove elements.

When deciding which type of parser to use you should bear in mind your needs. The SAX API is fast, as it examines the XML serially. The DOM API is much more memory-intensive and CPU-intensive, as it must load the whole document. However, the DOM API allows you to modify the XML structure and has greater flexibility. You should choose the API that provides the best tradeoff between your requirements and the limitations of your system.

JAXP also supports XSLT, a language used for transforming XML documents into other documents using stylesheets. For example, using XSLT, you could transform an XML document into HTML, or you could make an XML document based on one schema conform to another schema.

Tuesday, December 05, 2006

Servlet and Web Service

When creating a servlet to act as an RPC-router for a web service, you must ensure that it performs all the necessary tasks. These include
  • parsing the SOAP envelope
  • validating the message format and the XML
  • converting any necessary data to Java specific data types
  • extracting all the necessary method call information from the SOAP message and calling the other components for the J2EE system correctly using this information.

Java API for XML

  • JAXP is the Java API for XML processing. It allows you to process and transform XML documents using DOM(Document Object Mode), SAX(Simple API for XML), and XSLT(eXtensible Stylesheet Language Transformations). It also allows you to switch between implementations of these standards - for example, from one DOM parser to another - without needing to alter the code.
  • JAXB stands for the Java Architecture for XML Binding. It provides a mechanism for mapping between XML elements and Java objects. It compiles your XML schema into Java classes. These generated classes can then handle and parse any XML data as well as checking that al the XML you use is compliant with your requirements. It is an alternative way of processing XML to that provided by the JAXP API.
  • SAAJ is the SOAP with Attachments API for Java. It is the basic package for SOAP messaging and allows you to create and populate a SOAP message.
  • JAX-RPC is the Java API for XML-based remote procedure calls. It enables you to build SOAP-based applications with RPC functionality in which the method calls are encapsulated in the SOAP messages.
  • JAXM is the Java API for XML Messaging. It enables applications to send and receive document-based XML messages. It implements the SOAP 1.1 standard to allow you to focus on sending the SOAP messages rather than creating low-level XML routines. It also facilitates asynchronous communications between web services.
  • JAXR is the Java API for XML Registries. It allows you to access different XML registries. Among the registries it allows you to access are those based on the UDDI and ebXML(Electronic Business XML) specifications.

Monday, December 04, 2006

Entity Bean and Exception

The exception thrown by entity beans are divided into two categories. The first is a system exception, such as SQLException, which alerts the container that there is problem with services that suport an application, therefore requiring the services of a system administrator to fix the problem. The other type of exception is an application exception, which alerts the container to an error in the business processes of a bean. Application exceptions are further divided into customized and predefined exceptions. A customized exception is an exception you have created specifically for your application.

A predefined exception is alreay part of a Java package and is provided to deal with common problems that arise within EJBs, for example, the CreateException.

Friday, December 01, 2006

Life Cycle of Entity Bean

There are three states in the life cycle of the entity bean, Does Not Exist, Pooled, and Ready.

When the bean is in the Does Not Exist state, no instance of the bean has been instantiated yet.

In the pooled state, several instances of the bean's implementation class are instantiated but are not associated with any EJBObject. All the bean instances in the pool are the same and are not associated with any database data or actively dealing with any client request.

Once the bean is instantiated, a reference to its javax.ejb.EntityContext is passed to it by the container using the bean's setEntityContext method.

Once the EntityContext is associated witht the bean, it can be placed in the pool. When the EJB server starts up, it will maintain a separate instance pool for each type of bean deployed by placing a number of bean instances in this pooled state.

Beans in the pooled state can be used to service ejbFindxxx requests, as these methods don't rely on the bean instance's state.

When a client requests a bean, the container creates an EJBObject for that bean, and it assigns a bean instance from any of the instances in the relevant instance pool to the EJBObject, using the appropriate data to initialize the bean.

This is done using the ejbCreate or ejbActivate method.

When a bean instance is assigned to an EJBObject, it moves to the ready state. In this state, the bean instance is associated with data and actively deals with client requests.

The bean instance can also use its EntityContext to receive information about the client that is using the instance and to receive callback methods from the container.

Initialized entity bean instances correspond to actual entries in a database, so, in the ready state, a bean instance can access a row of data from a database.

The ejbLoad and ejbStore callback methods, which the container uses to synchronize the bean's state with the database, can be called only when the bean is in the ready state.

Entity beans can move from the pooled state to the ready state in these circumstances,
  • when a new entity bean instance is created using the ejbCreate method
  • when the container activates a bean in response to a query using the ejbActivate method
  • when the container uses ejbActivate to activate a bean that has previously been passivated.
When the bean instance is in the ready state, there may be lulls in activity when the bean instance is consumig resources but not actually dealing with a client request.

To deal with this, the EJB container can passivate the bean - that is, return the bean to the pooled state - when it's not in use. It does this by invoking the ejbPassivate method.

And if a bean instance is required again, any one of the equivalent bean instances in the pooled state can be reassigned to the EJB object.

After the client request is completed with a bean instance, the bean instance can be removed and returned to the pooled state.

When the client signals that it wants to remove a bean, the container calls the ejbRemove method on the bean instance.

The life cycle of an entity bean ends when the bean instance is removed from the pool by the container to be destroyed.

If a bean is to be released, the unsetEntityContext method is called by the container to warn the bean instance that is about to be destroyed. This allows the bean instance to discharge any data it maintains before being destroyed.

Entity Bean and Transaction

Enterprise bean transactions can be bean managed or container managed, but entity beans can only use container-managed transactions.

In this case, the container manages the bean's transactions and is informed by the bean provider how the bean participates in a transaction. When a bean is transactional. it can be shared between multiple clients.

Session beans can be uniquely identified by an ID generated by the container. But such IDs are not enough for entity beans, since they are associated with data in a database.

Therefore, entity beans make use of the primary key class that uniquely identify the data in the database that the entity bean is associated with. So the primary key uniquely identifies both the entity bean and the underlying data in the database.

Wednesday, November 22, 2006

EJB Object and EJB Home

In order to add a bean to a container, files associated with the bean are packaged in a .jar file. Files include the bean class, home, remote, local home and local interfaces and the deployment descriptor. Beans need to be deployed into containers before be accessed by clients through containers as distributed components.

During deployment, EJB object and EJB home are automatically created (by J2EE servers) for entity and session beans.

The EJB object, which acts as a request interceptor, implements the bean's component interface and provides a reference to an invoked bean. The EJB home, which is an EJB object factory, implements the bean's home interface and is responsible for creating, removing, and locating enterprise beans.

As message-driven beans respond only to asynchronous messages, they do not have component or home interfaces and so have no corresponding EJB object or EJB home.

Tuesday, November 21, 2006

EJB 1-2-3

There are three types of Enterprise JavaBeans – entity, session, and message-driven. Entity beans model real-world business or data elements and can be accessed by multiple clients. Session beans represent processes and tasks. Entity beans are persistent, but session beans do not have a persistent state. A message-driven bean is a stateless bean that responds to requests placed by clients using the Java Message Service (JMS). Both message-driven and session beans can be used to perform tasks and manage interaction between enterprise beans. However, unlike session beans, message-driven beans don't have a component interface that defines what methods can be invoked.

To develop an EJB, you need to define a bean implementation class and, if using an entity bean, a primary key class. The component interface defines the bean's business methods, whereas the home interface includes the methods required to create, find, and remove a bean. A client accesses a session or entity bean indirectly through the EJB object, which is generated by the EJB home, an EJB object factory. In addition to referencing your bean, the EJB object takes care of system-level management tasks. The EJB object class – which implements the bean's component interface – and the EJB home – which implements the bean's home interface – are both automatically generated by the container during deployment.

Enterprise Components

Within the object-oriented process, objects are reusable at the class level. However, this level of encapsulation - problem solving with classes - is often two low for enterprise systems.

To meet the challenges of enterprise systems, components - which represent logical collections of finer-grained classes - have been developed to offer a higher or more coarse-grained level of encapsulation for partitioned problems.

Sun Microsystems's enterprise component model for component transaction monitors(CTMs) is based on CORBA and is called Enterprise JavaBean(EJB).

Friday, November 17, 2006

Coupling and Cohesion

Coupling refers to how tightly connected classes are. If a class is very dependent on other classes to carry out its functions, then it is strongly coupled.
Strongly coupled classes can lead to problems in program design. Because such classes are interdependent, they are difficult to extend, and bugs in one can affect others.

This interdependency can also make it difficult for other programmers to understand programs that contain such classes.
To perform adequately, classes must be connected to other classes. But you should choose a level of connection that doesn't make one class too dependent on another.

This is particularly important when you design for inheritance.
Though inheritance is a form of coupling, it can make programs easier to design and extend.

So when choosing classes, you need to balance the requirements of inheritance against the need for weak coupling.

Cohesion is a measure of how closely related the elements in a class are. These elements are the states, behaviors, and functionalities of the class.
A class whose members are simply grouped together and have little in common is only coincidentally cohesive. Such a class might have two unlinked functions, or it may group object states with unrelated object behavior.

Because its elements do not cohere to realize a single purpose, such a class is confusing, difficult to use, and often too complex to implement.
Let's say you used a class named BankEmployee to model how bank staff are paid and how they interact with customers.

Since the elements of these separate functionalities are unrelated, this class would be a bad abstraction.
Classes with good cohesion are well defined and contain elements that properly belong together.

Such classes are easy to understand and use because they serve a definite purpose – they have functional cohesion.

Monday, October 23, 2006

Create Qualified Association in Rational Software Modeler

To create a qualified association in Rational Software Modeler, e.g. the 1 on 1 relationship between a team and a player by the qualifier of shirtNumber, follow the following steps,
  1. create the Team class
  2. create the Player class
  3. create the shirtNumber attribute in the Player class, make it "unique"
  4. create an association between Team and Player
  5. expand Team
  6. right-click on the player attribute of the Team, select Add UML > Qualifier
  7. completed
Don't be confused by the 1 on 1 multiplicity. Given the qualifier, it is 1 on 1 instead of 1 to many. Of course at the same time, a team can still contains many player.

Thursday, October 19, 2006

Insurance on Property - 2.7

a) What is the major difference between how coverage under a named perils policy and an all risks policy is determined?
b) State the types of exclusions found in all risks policies and give an example of each.

Answer:

a) A named perils form responds only to loss caused by perils identified specifically in the policy. To recover under such policy, an insured must show both that property damaged or destroyed was insured property and that the cause of the loss was a listed peril.

An all risks form insures any fortuitous loss unless the proximate peril is exclued specifically in the policy. To recover under such policy, the insured must show that the property damaged or destroyed was insured and that the loss arose from a fortuitous and not inevitable risk. The insured need not prove the loss is covered, the onus is on the insurer's side.

b) All risks policies have the following types of exlusions,
  1. Types of property; for example, money, securities, aircraft, watercraft.
  2. Types of loss; for example, loss arising from delay, loss of market, or loss of use or occupancy.
  3. Types of risk; for example, loss by misappropriation, conversion, infidelity or dishonesty of any person to whom property is entrusted.

Insurance on Property - 2.6

In a policy covering a commercial or mercantile risk:
a) In the event of a fire, what other types of damage are regarded as fire losses?
b) How is actual cash value determined when a loss occurs? What qualifer governs the calculation of the actual cash value of a loss? Why is this qualifier essential?
c) What is the effect of the automatic reinstatement clause?
d) What would be the special provisions of a Replacement Cost endorsement if used in such a policy?

Answer:

a) In the event of a fire, other types of damage are considered as fire losses in that they occurred because of the fire, that is, they are consequences of a hostile fire. Such types of damage may be,
  • caused by explosure to heat
  • caused by smoke from fire
  • caused by water or chemical foam used by firefighters or released by fire sprinklers
  • caused by the action of firefighters in action to gain access to a fire, to release heat and smoke, to find the seat of a fire
  • caused by the action to prevent spread of fire
b) Actual cash value is the value of the damaged property under insurance at the time of the loss. Generally, it is the cost of replacing the property, less any depreciation to it. Depreciation is determined by serveral factors, including the physical condition of the property, its resale value and its normal life expectancy, just before the loss. The qualifier is essential because values fluctuate. The cost of replacing damaged or destroyed property may be different after loss than at the ime of the loss.

c) The Automatic Reinstatement rules the insurer to remain the amount of insurance unchanged throughout the policy period, even if losses are paid, it also rules the insurer to return the insured premium calculated on a short-term rate basis for the unexpired part of the policy period if the insured cancels the policy, even after a loss, even amount of recovery has already reached the full amount of insurance.

d) If a policy uses the Replacement Cost endorsement, the special provisions include these conditions,
  1. replacement must be made promptly.
  2. replacement must be on the same site or an adjacent site.
  3. payment will be limited to the cost of replacing, repairing, constructing or reconstructing (whichever is least) on the same site with new property of like kind and quality and for like occupancy.
  4. settlement will be made only when the work is completed and then for no more than the actual cost of the work.
  5. all other insurance covering the same perils (and the same interest) must have the same replacement cost provisions.

Insurance on Property - 2.5

Summarize the explosion coverage under the Basic Fire Policy and explain the effect of adding explosion as an additional peril.

Answer:

Under the Basic Fire Policy, in common law provinces, the explosion coverage covers the damage by the explosion of natural, coal or manufactured gas, in Quebec, it covers the damage by the explosion of fuel with the exclusion of gasoline vapour.

The coverage is boardened when the explosion is added as an additional peril. It covers most kind of explosion damage with the following exclusions,
  1. explosion of or in various types of boilers, pressure vessels and gas turbines;
  2. explosion during pressure testing or resulting from centrifugal force or mechanical breakdown;
  3. explosion by electric arcing, by bursting or rupture due to hydrostatic pressure or freezing or bursting or rupture of safety devices.

Thursday, October 12, 2006

Insurance on Property - 2.4

Under the (IBC) Standard Mortgage Clause:
a) Some provisions benefit the mortgagee. Briefly, describe three such benefits.
b) Which provision might be valuable to the insurer?

Answer:

a) The main benifit of a mortgage clause for the mortgagee is that the policy covers the mortgagee even if the named insured is unable to recover because a condition of the policy has been breached.

The mortgage clause permits the mortgagee to give notice of loss immediately on becoming aware of it, and proof of loss as soon as practicable.

The clause also includes the mortgagee and its assigns among those whom the insurer, acquiring title to the insured property, must continue to insure until the policy is cancelled or expires.

b) Under the mortgage clause, the insurer, having indemnified the mortgagee for a loss, becomes subrogated to the rights of the mortgagee against the insured, but only to the amount of the loss paid to the mortgagee.

Insurance on Property - 2.3

Explain how a stated amount coinsurance clause differs from a 90% coinsurance clause.

Answer:

A stated amount coinsurance clause works on the same purpse as a 90% coinsurance clause. They both encourage insureds to maintain a adequate amount of insurance. However they work differently.
  1. The Stated Amount specifies the minimum amount of insurance in dollars rather than as a percentage of the actual cash value of the property insured.
  2. The Stated Amount simplifies the determination of the adequacy of the amount of insurance, since it is easy to compare the amount of insurace to the Stated Amount coinsurance and the comparason result is valid through out the whole life cycle of the policy. But in the case of a 90% coinsurance clause, the actual cash value must be determined at the time of loss and the adequacy can only be determined at that time.
  3. The Stated Amount needs no Waiver of Coinsurance because no calculation of actual cash value is needed to detemine if the coinsurance clause applies to a loss settlement.
  4. The Stated Amount expires independently of the policy, usually after a certain number of monthes, but the 90% clause is valid throught out the policy life.
  5. The Stated Amount requires an annual Statements of Values so that the amount can be adjusted to reflect the actual value of the property at the time of renewal. The Statements of Values costs both side time and resources and due to this reason, the Stated Amount is more likely to be used when insuring large, high-value complexes under a single item.

Insurance on Property - 2.2

State the amount the insured will be entitle to recover in each of the following cases. Give reasons for each answer and show your calculations.

In all cases, the full value of the property insured is $500,000. The fire policy is subject to an 80% coinsurance clause and a 2% waiver of coinsurance clause.

Amount of Insurance Amount of Loss
A. $300,000 $2,000
B. $450,000 $100,000
C. $350,000 $ 80,000
D. $300,000 $20,000

Answer:

The recovery for any loss under a policy with coinsurance before considering the waiver is calculated by this formula,

Amount of Recovery = Amount of Loss * Amount Carried / Amount Required

where the Amount Carried is the specified amount of insurance and Amount Required is the coinsurance of the total value of the property insured. In this case, the Amount Required is $400,000, which is the 80%, the coinsurance, of $500,000, the full value of the property.

The waiver of the coinsurance clause in the policy is 2%, which nullifies the coinsurance clause for losses less than 2% of the amount of insurance. Only when the loss exceeds 2%, the coinsurance clause will apply.

A. The waiver is 2%*$300,000 and results $6,000. The amount of loss is $2,000 and it doesn't exceed the waiver. Thus the coinsurance clause will not apply and the amount of recovery will be the full amount of loss, which is $2,000.

B. The waiver is 2%*$450,000 and results $9,000. The amount of loss is $100,000 and it exceed the waiver. The coinsurance clause will click. However, since the amount of insurance also exceeds the $400,000 minimum required by the coinsurance clause, the amount of recovery will the full amount of loss, $100,000.

C. The waiver is 2%*$350,000 and gets $7,000. The amount of loss is $80,000 and exceeds the waiver. The coinsurance clause will work. At the same time, the amount of insurance is less than $400,000 which is minimum required. We use the formula

$350,000/$400,000 * $80,000 = $70,000

Therefore, the amount of recovery is $70,000.

D. The waiver is 2%*$300,000, $6,000. The amount of loss $20,000 is greater than the waiver. The coinsurance clause will apply. The amount of insurance is less than the minimum required. We use the formula

$300,000/$400,000 * $20,000 = $12,000

The $12,000 is the amount of recovery which the insured entitles.

Insurance on Property - 2.1

A fire policy is to be issued for the following property, located in Alberta:
- a building occupied as an office
- contents of the office
- merchandise stored in a warehouse several blocks from the office.

Separate amounts of insurance are to apply to each item and the policy is to contain a deductible provision.
a) What should the insured consider in deciding whether to select a deductible on a per item or per occurrence basis?
b) What steps must the insurer take to be sure the deductible is enforceable?

Answer:

a) Deductible on a per item basis means the deductible applies separately to the amount recoverable under each item. Deductible on a per occurrence basis means the deductible is substracted from the total amount of loss or damage arising from a single event. For the insured to get the same coverage with lower premium or to get a better coverage with same premium, it should consider that its first and second item are at the same location, but the third item is at another location. The probability that a single event happens on both locations is low, so that the per item basis normally works better for its situation.

b) The insurer will need to comply with the Statutory Conditions and stamp or print "This policy contains a clause that may limit the amount payable," on the face of the policy, in red ink and/or in a specified size and/or in bold font.

Wednesday, October 11, 2006

Thread Priority and Scheduling

If there is more than one thread in a Ready state at a given time, the thread scheduler must decide which thread should run first, and it does so based on the fixed priority scheduling algorithm.

In fixed priority scheduling, the scheduler chooses the highest-priority thread to run first. Lower-priority threads will run only when the highest-priority thread dies, yields, or enters one of the Not Runnable states. If an even higher-priority thread becomes Ready, it should usually pre-empt the original thread and gain control of the CPU.

If all Ready threads have the same priority, the thread scheduler chooses a thread at random. It won't necessarily be the one that has waited longest. If a high priority thread has a run method with no pauses in the code – sleep or wait method calls, for example – it will keep control of the CPU until its run method finishes. This is known as a selfish thread.

In pre-emptive implementation, such threads will either give the CPU up by themselves or be pre-empted by a thread of higher priority.

In time-slicing implementation, a thread runs for a specific time and then enters the runnable state, at which point the scheduler decides wether to return to the thread or schedule a different thread. This means that if more than one thread has equal, highest priority, the threads take turns at the CPU for finite slots of time until one finishes or a higher-priority thread becomes ready. (Win 95/NT)

Not all platforms implement scheduling in the same way, you need to be careful when writing programs that depend on manipulating thread priorities, because they may not run in the same way on all Java Virtual Machines (VMs).

Runnable vs Thread

It is usually better programming practice to use the Runnable interface rather than overriding the Thread class's run method.

Java does not support multiple inheritance, so classes that are subclasses of Thread cannot be subclasses of any other class. If you use the Runnable interface, however, you can create threads using classes that already have subclasses.

This approach is helpful when constructing your class hierarchy. Rather than saying that an object of your class "is a" thread, your class is associated with a thread that executes its code.

A further advantage of using the Runnable interface's run method is that this can make it easier for the run method to access protected methods and variables of its superclasses.

That is, because the run method belongs to a subclass, it gains access to methods and variables denied to non-subclassed classes.

Tuesday, October 10, 2006

Isolation Level

To understand isolation level, you need to understand three problems related to concurrency control, dirty reads, unrepeatable reads and phantoms.

Dirty Reads

A dirty read occurs when your application reads data from a database that has not been committed to permanent storage yet. Consider two instances of the same component performing the following:
  1. You read account balance X from the database. The database now contains X = 0.
  2. You add 10 to X and save it to the database. Now X = 10, but not committed, this is so-called dirty.
  3. Another instance reads X from database, it will get X = 10, which is dirty.
  4. You abort the transaction, which restores the X to 0.
  5. The other instance adds 10 to X and saves. The database now contains X = 20.
The problem here is the second instance commit its transaction based on a dirty data. The problem of reading uncommitted data is a dirty read.

Unrepeatable Read

Unrepeatable read occur when a component reads data from database, but upon re-reading the same data, the data has been changed. This can arise when another concurrently executing transaction modifies the data. For example,
  1. You read a data set X from database.
  2. Another component overwrites all or part of the set X.
  3. You re-read the set X and values have changed.
To prevent such changes, you need to lock out other components from modifying the data.

Phantom

Phantom is a new set of data that inserted in a database between two read operations. For example:
  1. You read the database and find 5 computers ordered by A.
  2. A order another computer.
  3. You re-read the database and find 6 computers by A.
  4. If one of your transaction depends on the number of computers ordered, you will have problem to believe when the number will not change during your transaction.
Now it becomes very easy to understand these isolation levels. READ UNCOMMITTED prevents none of these problems. READ COMMITTED prevents only the dirty read. REPEATABLE READ prevents dirty read and unrepeatable read. SERIALIZABLE prevents all the above mentioned problems.

Thursday, October 05, 2006

Insurance on Property - 1.9

In general terms, describe how the policy conditions address TWO(2) of the following. Indicate whether you are discussing the Statutory Conditions or the General Conditions.
a) Material change in risk.
b) Limitation of action.
c) Requirements after a loss.
d) Disagreements over amount of loss.

Answer:

In the Statutory Conditions,

b) the Action addresses the limitation of action. An insured who intends to pursue a grievance against an insurer in court must begin within a specified time. This period varies somewhat across Canada. In most common law provinces, the limit is one year after loss or damage occurs. In Manitoba and in in Yukon Territory, it is two years.

d) the Appraisal addresses the disagreements over amount of loss. Disagreements over amount of loss shall be determined by appraisal as provided under the Insurance Act before there can be any recovery under this contract. There shall be no right to an appraisal until a specific demand therefor is made in writting and until after proof of loss has been delivered.

Insurance on Property - 1.8

While investigating a claim under a fire insurance policy, the insurer discovers that the insured misrepresented a material circumstance of the risk when applying for the policy. As a result, the premium is only 50% of what is should have been.

Assume that the insurer is located in a common law province and that only the matter of the misrepresentation remains to determine the insurer's response to the claim.

Must the insurer pay the claim? Discuss the insurer's options. What policy conditions determine these options?

How does your answer change if the insurer is located in Quebec?

Answer:

The insurer may avoid the policy so that the insurer will not pay the claim. Since the insured misrepresented a material circumstance of the risk, and an inadequate permium of 50% has been charged for the risk.

However, the policy can be voided only if the insurer can prove the misrepresentation was metarial to the acceptance of or the 50% permium charged for the risk. If the insurer does not prove it, the insurer will still need to pay the claim and actually in 100% of the amount, but at the same time, correct the representation of the risk and amend the premium to 2 times of the current value.

The policy condition which determines these options is the Misrepresentation, Statutory Condition 1.

If the insurer is located in Quebec, these options will be determined by Misrepresentations or Concealment in Statements of the General Conditions.

Under this General Condition, the insurer may nullify the policy even if the loss is not connected to the misrepresentation, so that it will not pay the claim. Similar to other common law provinces, the insurer need to prove the bad faith on the insured. Or it need to establish the fact that it would not accept the risk if it had discovered the misrepresentation.

If the insurer cannot prove the bad faith nor the non-acceptance of risk, it must pay the portion of the loss that the premium collected bears to the premium it should have collected, in this case, it must pay 50% of the claim.

Unlike the Statutory Conditions, the General Condition does not govern how the insurer should alter the policy or charge the insured on additional premium.

Wednesday, October 04, 2006

Insurance on Property - 1.7

Summarize the requirements of the fire insurance policy conditions regarding length and manner of notice and premium computation if the policy is terminated prior to the expiry date in the policy declarations. (Relate your answer to either the common law provinces or Quebec. State which one.)

Answer:

According to Civil Code of Quebec, fire insurance policy can be concelled at any time before it expires.

By mere written notice from each of the Named Insureds, the termination takes effect upon receipt of the notice. By the insurer giving written notice to each Named Insured, the termination takes effect fifteen days following receipt of such notice by the Insured at his last known address.

If the insurer cancels, it shall refund the insureds the excess of premium actually paid over the pro rata premium for the expired time. The pro rata premium is the same proportion of the total that the effective period of the policy before cancellation was of the original policy term.

If the insureds request cancellation, the insurer should refund the insureds the excess of the premium actually paid over the short-term rate for the expired time. This allows the insurer retains its pro rata premium and a surcharge.

Insurance on Property - 1.6

A company operates two retail stores: one in Winnipeg, the other in Quebec City. The owner asks the broker to obtain a single fire insurance policy to insure merchandise at each store. (Separate amounts of insurance are given.)
a) What main article in the Civil Code of Quebec will the broker consider in selecting the insurer to issue the policy? Why?
b) What legal requirements must the insurer bear in mind in issuing such a policy?

Answer:
a) The broker need to consider the Article 3119 of the Civil Code of Quebec. This article allows properties located in Quebec and in other provinces can be insured under one policy, as long as the insured property locates in Quebec, or the interest of the insured or other interested party situates in Quebec, or the insured applies the insurance in Quebec or the insurer issues the policy in Quebec.
b) When the insurer issues such a policy which covers property in Quebec City and in Winnipeg, the insurer must include both Statutory and General Conditions in the policy. The Statutory Conditions may include a statement that they do not apply to the merchandise at the retail store in Quebec City. And the General Conditions may include a statement that they apply only to the merchandise at the retail store in Quebec City.