Friday, December 5, 2008

Refreshing my memory on ear vs war

Below is the excert from the link

http://safari.oreilly.com/0596007345/jboss-CHP-3-SECT-1

WARs Versus EARs

The WAR file is a convenient way to bundle up all pieces of a web application. All servlet containers know how to deploy a WAR file—they expand the bundle, look for the WEB-INF directory, and read the web.xml found there for further deployment instructions.

The EAR file provides the same type of functionality for a full-fledged J2EE application. JBoss expands the EAR, finds the required deployment descriptors, and proceeds from there.

An EAR is like a carton of eggs—it keeps everything organized. While the carton doesn't add any direct value to your omelet, it makes getting the eggs home from the store so easy that you wouldn't think about transporting eggs any other way.

Each egg in your EAR carton is a specific piece of the J2EE puzzle. These eggs (or JARs) come in three basic varieties called "modules":


Web module

A WAR file containing presentation tier components

EJB module

An EJB JAR file containing the middle-tier components (EJBs, MDBs, etc.)

Java module

A regular JAR file containing classes and libraries that are shared across the entire application. An application client JAR and a common JAR are two examples of Java modules.

Wednesday, November 19, 2008

How to get version number from Spring Jar.

Do this

System.out.println(SpringVersion.getVersion());

Or

Look at manifest file.

hibernate environment specific configuration where there is no JNDI access

http://java-aap.blogspot.com/2007/05/configuration-of-environment-settings.html

Here are the contents of the above link

MAD Code Monkeys

MAD Code Monkeys Blog. Marcel Panse and Daniel Rijkhof are software engineers from the netherlands specialized in techniques like Java, Ruby, Spring, Hibernate, DWR and Flex
Tuesday, May 15, 2007
Configuration of Environment Settings
written by Daniel Rijkhof

I get a lot of questions asking how I deal with configuring environment specific settings. I'll explain my solution here.

The following solution depends on the Spring framework.

1) have a separate package per environment (e.g. production, test, local)
2) put a properties file in this directory (e.g. webapp.properties)
3) configure the spring context
4) set a system environment variable to choose your environment


I'll use the following packages:


com.mad.project.env.junit
com.mad.project.env.local
com.mad.project.env.test
com.mad.project.env.acceptance
com.mad.project.env.production



The webapp.properties files i'm using are simular to my junit.properties file:


hibernate.schemaUpdate=true

hibernate.dialect=org.hibernate.dialect.HSQLDialect
hibernate.show_sql=false

dataSource.driverClassName=org.hsqldb.jdbcDriver
dataSource.url=jdbc:hsqldb:mem:test
dataSource.username=sa
dataSource.password=

webapp.logDir=../logs/junit

env.dir=junit
env.name=junit environment


Note: the env.dir line is only present in my junit env properties file.


The context:







classpath:com/venspro/payment/env/junit/junit.properties
classpath:com/venspro/payment/env/${env.dir}/webapp.properties










...




${hibernate.dialect}
${hibernate.show_sql}







Main DataSource






...



Take a close look at the propertyPlaceHolderConfigurer; there is a default configured, and one with an EL expression. If ${env.dir} is not specified, it will not find the properties file, and ignore this because of the ignoreResourceNotFound setting.

The properties in the junit.properties file, are overwritten by any settings in the next properties file.

The only thing left to do is specify the environment setting 'env.dir'. This can be done in several ways; in the servlet container configuration, or on the system environment, or as a parameter to the jvm (-Denv.dir=test).
Posted by Daniel Rijkhof at Tuesday, May 15, 2007
Labels: hibernate, java, spring

All about java and jar files.

Here is a good article on java and jars.

http://fraaargh.wordpress.com/2008/07/13/how-to-java-jars-and-manifestmf/




Snap Shots Options [Make this Shot larger] [Close]
Options
Disable
Get Free Shots


Close
Snap Shares for charity
Some thoughts about things
No forward thinking leads to afterward sinking
« Blagounette graveleuse
Use ANT to auto-generate the list of jar files in a MANIFEST.MF »
How-to java jars and MANIFEST.MF

Here’s a brief “how-to” for remembering what is possible with a jar file, how to use it, launch its main class and define where the other jars (the libraries used) are stored. I could not find anywhere on the net a good explanation of all this, so decided to write my own.
So imagine you have your own jar file named myApp.jar which main class (the one with the “main” method) is marot.francois.MyMainClass which needs to receive 2 arguments: arg1 and arg2 (passed in String[] args).

1- Without using any MANIFEST.MF fil

If you don’t have a MANIFEST.MF file in your jar, or if you want to set some specific places where Java should look for the libraries used by myApp.jar, then you should use the following command. Beware, the use of the star is only available since Java 6 (or is it Java 5 ?)

on Windows:
java -cp tmmerge.jar;myCustomLibPath1\*;myCustomLibPath2\*;myCustomLibPath3\* marot.francois.MyMainClass arg1 arg2
on Linux:
java -cp tmmerge.jar:myCustomLibPath1\*:myCustomLibPath2\*:myCustomLibPath3\* marot.francois.MyMainClass arg1 arg2

Same as previous one but with all the libraries’ jars listed instead of using *:
on Windows:
java -cp ./myApp.jar;myCustomLibPath1\sctm.jar;myCustomLibPath2\ant.jar;myCustomLibPath2\ant-launcher.jar;myCustomLibPath3\scdata.jar marot.francois.MyMainClass arg1 arg2

on Linux:
java -cp ./myApp.jar:myCustomLibPath1\sctm.jar:myCustomLibPath2\ant.jar:myCustomLibPath2\ant-launcher.jar:myCustomLibPath3\scdata.jar marot.francois.MyMainClass arg1 arg2

At first, I thought such a command line was overriding the classpath in MANIFEST.MF, if any. But that is not the case, the MANIFEST.MF is just bypassed.


2- Using a MANIFEST.MF file in the jar
Launch myApp using the jar files listed in myApp.jar’s own manifest
java -jar myApp.jar arg1 arg2

The content of the META-INF\MANIFEST.MF file must be:

Manifest-Version: 1.0
Ant-Version: Apache Ant 1.7.0
Created-By: 1.6.0_02-b06 (Sun Microsystems Inc.)
Main-Class: marot.francois.MyMainClass
Product-Name: myApp
Package-Title: marot.francois
Package-Version: 1.00.00
Package-Vendor: Elsys Design Avisto
Class-Path: myCustomLibPath2/ant-launcher.jar myCustomLibPath2/ant.jar myCustomLibPath3/scdata.jar myCustomLibPath1/sctm.jar

In a next post, I’ll show you how to use ANT to automatically generate the content listed here. And more specifically the list of libraries which would be error prone to write by hand.
By the way, I think it’s good to point to something important: in the “Class-Path”line of the manifest, you CAN’T use a star as you could do when specifying the classpath on the command line.
Also be aware that the space is the jars path delimiters as opposed to the “;” (windows) or “:” (Linux) on the command line. This last remark is very very error prone…

3- What I would like to be able to do (but it seems like Java doesn’t handle this case)

Warning: the exemple given hereafter does not work. I spent a lot of time trying to find some explanation of the reasons why, but was not able to find.
So the problem seems to be that you can’t override the default classpath specified in the jar’s manifest if you use the -cp switch at the same time. So the basic rule of thumb is:
“in java, do not use both switches -jar and -cp at the same time”: it does not work (at least up to Java 6).
I thought it would be cool to be able to run a jar but defining another place where it can find its dependancies. In case you want the users of your app to be able to use a shared folder containing the lib jars but don’t want him to have to know the main class’ name.
Here’s the command line I desperatly tryed to run:
REM java -cp myCustomLibPath1\*;myCustomLibPath2\*;myCustomLibPath3\* -jar myApp.jar arg1 arg2

Nevertheless, the same goal can be reached (successfuly) by using method 1. Only that the user needs to know the main class.

Tags: java jar manifest

This entry was posted on 2008-07-13 at 22:34 and is filed under Java, dev. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
6 Responses to “How-to java jars and MANIFEST.MF”

1. Use ANT to auto-generate the list of jar files in a MANIFEST.MF « Some thoughts about things Says:
2008-07-13 at 23:04

[...] Some thoughts about things Computing, IT, society… « How-to java jars and MANIFEST.MF [...]
2. Swathi Says:
2008-08-06 at 06:53

Thank you very much for the valuable inputs…
I am facing an issue.. I am using a junit library and built a test library testXXX.jar now this has a number of dependent jars say XXX.jar etc but how do i ask the testXXX.jar to use XXX.jar and execute the test library?
3. fraaargh Says:
2008-08-08 at 13:57

Swathi, I don’t really understand your problem there… Why can’t you use for testXXX.jar the same process used for your application’s main jar ?
4. Swathi Says:
2008-08-20 at 07:08

Actually i have one jar xxxlib.jar . Now from command line i ll be executing the jar yyylib.jar(inside that i have one property file prop.properties) which inturn use the xxxlib.jar. Now my problem is when i try to access the prop.properties while executing the yyylib.jar from cmd prompt i am not able to read the property file inside the yyylib.jar. I want to know how i can read this property file which is actually inside the jar?
5. fraaargh Says:
2008-08-20 at 21:45

If I understand, you try to access the *.properties file in xxxlib.jar from yyylib.jar… I never faced such a problem. Perhaps you could add a utility class in xxxlib.jar that would provide such an access through public methos ? Otherwise, try to find information on how to read files in jar files.
6. Swathi Says:
2008-09-10 at 13:18

Actually thats my doubt i am unable to read the property file inside the xxxlib.jar.

Leave a Reply

Name (required)

Mail (will not be published) (required)

Website

Blog at WordPress.com.
Entries (RSS) and Comments (RSS).

Thursday, November 13, 2008

Spring: Basic Application and Environment Set up.

To get started on spring.

http://static.springframework.org/docs/Spring-MVC-step-by-step/part1.html

How to create spring-hibernate project structure with maven archetype.

http://sezera.blogspot.com/2008/01/how-to-create-project-directory.html

Nowadays i am working on a new dynamic web project which uses spring-hibernate-richfaces trio.My first task to set up development environment of project.It involves many steps.I will write sth about it occasionally.

Here I will use Maven Archetype plugin to create directory structure of my project.Assume that dynamic webproject has 3 directory initially.

core
web
security

Because we will created an internal artifactory repository and configured it we dont care about jars anymore.Project will be simply involves java classes,resources like gifs,jpegs for web side,and our pom.xmls.Jars will reside in M2_REPO which is = Your home\.m2\repository as default.

1.Create an empty directory e.g myproject
2.Go inside it
3.write in command prompt

mvn archetype:create -DgroupId=com.mycompany.myproject.core
-DartifactId=myproject-core -DarchetypeArtifactId=maven-archetype-quickstart

It will create myproject-core directory.

4.write in command prompt

mvn archetype:create -DgroupId=com.mycompany.myproject.web
-DartifactId=myproject-web -DarchetypeArtifactId=maven-archetype-webapp

It will create myproject-web directory.

5..write in command prompt

mvn archetype:create-DgroupId=com.mycompany.myproject.security
-DartifactId=myproject-security-DarchetypeArtifactId=maven-archetype-quickstart

It will create myproject-security directory.

You will see that every directory has a pattern.Thanks to this plugin you dont need to think about directory structure of your project.

For more information
http://maven.apache.org/plugins/maven-archetype-plugin/

Tuesday, October 14, 2008

Prepared Statement Vs. Regular Statement.

Trying to refresh my memory on some fundamentals, I bumped into this article.

http://sharat.wordpress.com/2006/09/09/49-what-is-the-difference-between-statement-and-prepared-statment/

* Prepared Statement is Pre-compiled class , but Statement is not.
* So in PreparedStatement the execution will be faster.

Actually when u submit a simple statement to the databse, at first the DBMS parses it and sends it back with the result, so again when u send the same statement again the DBMS server parses it and sends back the result so here a lot of time is wasted and because the statement is again parsed though it has been sent twice or thrice it consumes a lot of time and response will be slow.Prepared Statement is used when u want to execute a statement object many times. when u submit a PreparedStatement the DBMS server parses it and creates a execution plan. This e-plan can be used when u again send the same statement to the database.That is the DBMS server zest executes the compiled statement rather that executing it from first, hence we get an precompiled statement.And also the advanatge of using this PreparedStatement is it is used to send dynamic sql statements, which u can give values later than giving the values at the time of creation.

Friday, October 3, 2008

Web Log Analyzer

There seems to be a open source tool available that can be very easily used to analyze logs and give us statistics on number of unique visitors, access paths, and other cool stuff.

http://www.hping.org/visitors/

Linux Performance Tools.

The following tools seems to be popular.

1. Zabbix
2. Naggios

Thursday, September 11, 2008

Cut and Pasting from a web page and issues with the data.

I recently encountered an issue where I was sent an user id/password in an email claiming that it doesn't work. When I cut and paste that in the web page, it in-fact doesn't work, but when I type it, it works. When i pasted the user id and password in microsoft word and turned on to show formatting characters, I noticed some formatting characters. If I paste them into notepad and pasted them back to the web page, it works fine. A little more reasearch got me the following info from wikipedia.

Notepad is a common text-only (also referred to as plain text) editor. The resulting files – typically saved with the .txt extension – have no format tags or styles, making the program suitable for editing system files that are to be used in a DOS environment.

One notable feature of Notepad is that it does not support formatting of any kind - if text is copied from a web page and pasted into a word processor, the formatting and embedded metadata comes along with the text, and can be difficult to remove. However, if text is copied from a formatted web site, pasted into Notepad, then copied again from Notepad before being pasted into a destination program, Notepad will have stripped all of the formatting. As an interesting aside, Notepad does support both left-to-right and right-to-left based languages, and one can alternate between these viewing formats by pressing and releasing the arrow key followed by Ctrl+Shift, using the right or left arrow and shift keys to go to right-to-left format or left-to-right format, respectively.

http://en.wikipedia.org/wiki/Notepad

otepad is a common text-only (also referred to as plain text) editor. The resulting files – typically saved with the .txt extension – have no format tags or styles, making the program suitable for editing system files that are to be used in a DOS environment.

One notable feature of Notepad is that it does not support formatting of any kind - if text is copied from a web page and pasted into a word processor, the formatting and embedded metadata comes along with the text, and can be difficult to remove. However, if text is copied from a formatted web site, pasted into Notepad, then copied again from Notepad before being pasted into a destination program, Notepad will have stripped all of the formatting. As an interesting aside, Notepad does support both left-to-right and right-to-left based languages, and one can alternate between these viewing formats by pressing and releasing the arrow key followed by Ctrl+Shift, using the right or left arrow and shift keys to go to right-to-left format or left-to-right format, respectively.

Notepad can edit files of almost any format; however, it does not treat Unix- or Mac-style text files correctly (see newline). (Wordpad however does.)

Thursday, August 21, 2008

JUnit and multi threading test cases.

http://www.javaworld.com/jw-12-2000/jw-1221-junit.html?page=5

Wednesday, August 20, 2008

Difference between a pool and a cache.

Here is a great article on differences between a pool and a cache.

http://www.informit.com/guides/content.aspx?g=java&seqNum=104

In case, this link should ever be removed, here are the contents of the link.


Java
Caches and Pools
Last updated Jul 23, 2004.


It invariably comes up in discussions of design patterns and performance tuning: do I use a cache or do I use a pool? The answer flows naturally when you understand the differences between the two and what you are trying to accomplish. As with everything in programming, there are functional and performance tradeoffs.

Let's start with some "formal" definitions:

*

A pool is a collection of stateless objects
*

A cache is a collection of stateful objects

The main distinction between a cache and a pool is what is contained in them. In other words: when you retrieve an object from a cache or a pool, do you need a specific object, or will any object do? If you need a specific object, then each object maintains state; hence, you need to use a cache. If, on the other hand, you can use any object, then the objects do not maintain state and you can use a pool.

Now let's climb down from theoretical-land and apply these concepts to their common implementations. That may make the differences clearer.
Pools

Pools contain a collection of objects that do not maintain state. Consider a database connection pool: the purpose of a database connection pool is for processes in your application to share database connections. The overhead of creating a connection is performed only once for a connection; then the various processes use and reuse the connection. A process "checks out" a connection from the connection pool, uses it, and then checks it back in. Later in its lifecycle, if the process needs another connection, it goes back to the pool to ask for another. It does not care whether it received the same connection that it did previously or a different one; it only cares that it receives a connection to a specific database.

Pools are very efficient and are meant to hold stateless objects that an application wants to share (or reuse). Common implementations of pools are the previously mentioned database connection pools, thread pools, and Servlet pools.

Thread pools are usually associated with a queue of requests for an application to process. An application receives a request from a user, builds the request object, and places it in the request queue. A thread pool is associated with each request queue where a request dispatcher removes an object from the queue and passes it to a thread in the thread pool for processing. The thread processes the request and then returns itself to the thread pool. Note again in this scenario that an individual request does not need to be executed by a specific thread instance, but rather by any thread in the pool.

Serlvets can run in one of two states: multithreaded or pooled. If a Servlet is multithreaded then it means that it is thread safe, and the Servlet Container can create a single instance of the Servlet and call its service() method from multiple threads.

The concept of thread safety is really a simple concept. You can make your objects thread safe by only modifying local variables in its methods; in other words, do not modify class variables on which your method depends. If you do, then one thread of execution may modify something that will unwantingly change the processing of another thread. So only modify local or method variables in your Servlet's service() method. This is a huge gain in performance over pooling Servlets.

If your Servlets are not thread safe, they must be pooled: a pool will be created that contains a specific number of Servlets. As a request is received for your Servlet, a thread will attempt to check out an instance of your Servlet from the Servlet pool, call its service() method, and then check the Servlet back in. If all of the instances are currently checked out, then the thread must wait for a Servlet instance to be checked back in before it can process the request.

With respect to Servlets, using a pool incurs memory overhead and potentially can cause your application to slow down. That can be avoided by making your Servlets thread safe. Aside from this performance tip, with respect to pools you should be able to see how Servlets can be pooled and how an individual request does not need to be processed by a specific Servlet instance, but rather by any Servlet instance of a specific class.
Pooled Object Requirements

There is one distinct requirement for an object to be pooled: it cannot maintain stateful information between uses. A pooled object cannot rely on the information from any prior invocation or expect to be used by the same consumer during any future invocation. Pooled objects do not necessarily have to be thread safe; they just need to clean up their class variables before being returned to the pool.
Caches

A cache is a collection of stateful objects; each object in a cache represents a unique entity. The two most common caches we see, in J2EE terms, are Entity Bean caches and Stateful Session Bean caches.

Entity Beans represent specific data. If you have control over the entire design of your application, chances are that your Entity Beans map pretty closely to a table (or a small collection of tables) in your database.

Consider an Entity Bean representing a person. The Steve Entity Bean is different from the Michael Entity Bean (the Michael bean (my 3-year-old son) is far cuter than the Steve bean). To access the Michael Entity Bean, the Steve Entity will not work: you need a specific stateful instance of the bean, not just a "like" bean. Because Entity Beans represent stateful information, we maintain them in a cache.

But you might ask: why bother with a cache? Consider data that you might access on a regular basis, such as the top 100 books on Amazon.com. If each book stored in the database were accessed every 5 seconds, it would be foolish to query the database every 5 seconds for the same information! So we make the query to the database and store the results in a cache maintained in memory; subsequent requests are served out of memory and the trip to the database can be avoided.

TIP

Marc Fluery, of JBoss fame, wrote a "Blue Paper" called "Why I Love EJBs, an Introduction to Modern Java Middleware" that makes the assertion that the Entity Bean cache delivers a level of magnitude better performance by serving data requests out of memory rather than accessing a database. It is a fabulous read that I draw from in my performance tuning presentations all the time.

Stateful Session Beans are similar to Entity Beans, with the underlying storage medium determined by the application server and the lifespan of a Stateful Session Bean being restricted to a sesson timeout value.

The most common use of a Stateful Session Bean is a "shopping cart." We want to avoid the overhead of writing a user's shopping cart contents to disk or to a database every time things change, so we'll store the information in a cache and hold it in memory. The shopping cart example follows the same logical reasoning that you need a specific instance (your shopping cart) and not a generic shopping cart (someone else's).

Aside from Entity Beans and Stateful Session Beans, caches are useful to hold any data that you want to look up once and reference it multiple times, things like JNDI entries, RMI services, configuration file contents, etc. Caches save time!

Because a cache maintains specific object instances, when a cache is full and a new instance needs to be loaded into the cache, an existing object must be removed from the cache to make room for the new object. In EJB terms, removing and persisting an object from the cache into the database is referred to as passivation and loading an object from the database and inserting it into the cache is referred to as activation. If an excess of activation and passivation occur, the cache is said the thrash, meaning that it is spending more time loading and storing objects than servicing user requests.

The effectiveness of the cache can be measured by watching the activation and passivation rates along side the hit and miss counts; the hit count quantifies the percentage of requests that are serviced by the cache and the miss count quantifies the percentage of requests that are not serviced by the cache and hence require a passivation and activation. If your hit count is low and your activation and passivation rates are high then you need to increase the size of your cache!
Performance Considerations

Now that you have a commanding knowledge of the difference between pools and caches, let's compare their performance considerations:

*

A request for a pooled object can be serviced by any object in the pool.
*

A request for a cached object can only be serviced by a specific object in the cache.
*

If all objects in a pool are in use when a request is made, then the request must wait for any object to be returned to the pool before the request can be satisfied.
*

If the requested object in a cache is in use when it is requested, then the request must wait. It doesn't matter if the rest of objects in the cache are available, as a specific one is needed.
*

The size of a pool can be fixed or can grow. If a new object is requested from an empty pool, a new object can be created and added to the pool.
*

The size of a cache is usually fixed (because it holds specific objects and creating a new one is not always an option). However, if the cache is full and a new object needs to be loaded into the cache, an existing object has to be removed from the cache (activation and passivation).

Summary

Pools contain collections of stateless objects that your application processes want to share whereas caches contain collections of stateful information that your application does not want to incur the overhead of loading every time it is needed. The nature of the operations you are trying to perform determines whether you use a cache or a pool; the performance benefits strongly favor pools, but they simply cannot satisfy the requirements that a cache can. The determining characteristic to decide between a cache and pool is not performance, but rather functionality.
Online Resources

"Why I Love EJBs, an Introduction to Modern Java Middleware" by Marc Fleury

Jakarta Commons Database Connection Pool Library

Jakarta Commons Pool Library

Jakarta Commons Cache Library (still under development)

JBoss Cache: a clusterable cache implementation that JBoss uses to cache Entity Bean and Stateful Session Beans; made open to you as a standalone project

© 2008 Pearson Education, Inc. Informit. All rights reserved.

800 East 96th Street Indianapolis, Indiana 46240

Tuesday, August 12, 2008

Good article on groovy

http://www.ibm.com/developerworks/java/library/j-pg05245/index.html

Tuesday, August 5, 2008

How to get a web. app. server say jboss ready for remote debugging.

In order to remote debugging say jboss, in the run.sh or run.bat, we need to set the following.

add –xdebug and transport parameters to enable remote debug.

HTML Ignores white spaces in the data.

We had an issue where we had some of our user names that have mutliple spaces in them.
For e.g me & myself. However, this data saves correctly in our database, but the display on the web page ignore second space after me. So it's like me & myself. But when you view source, the data is there correctly. Upon further research, it's learnt that most browsers ignore extra white space and hence HTML spec introduced &nbsp. So in order to correct this issue any field that will have extra white spaces need to be encode by replacing spaces with &nbsp. Here is some reading on it to refresh my memory.

Source is from

http://www.theserverside.com/discussions/thread.tss?thread_id=28944

I know this is an annoying problem. Internet is a global thing, involving all languages, charsets, encodings and locales etc., but in my view the matter is underrepresented and there are no clear well known strategies. Most books, articles etc. silently assume that the world consists of English-speaking people... at most including a few French, Germans etc...

Anyway back to your problem:

I am trying to recollect from my memory, but if these advices don't work, please let me know and I will check the details of my own solution:

There are a few "intersections" where data is exchanged and where "implicit" encoding conversion might happen:


1- your mySQL DB: what version is it? Starting with 4.0.18 (I think) it can store UNICODE.
Prior to that you have to use binary columns to hold the data and prevent automatic conversion by MySQL.

2- I assume you fetch your data from JSP using JDBC. What driver (version) do you use?

3- the JDBC driver usually converts the data from the database automatically, depending on the default encoding of the machine it is running on.

To force JDBC to retrieve the data as unicode please use the parameter charset=utf8 (I don't have the exact synthax now... but you can check it yourself).

4- in the JSP page itself:

you have 2 levels of charset processing to deal with:

a- the java processing in the jsp-servlet itself, before data is sent back to the browser.

Here you have to take care that teh jsp-java code is not "silently converting" your data to the default charset, which might be "iso-8859-1" or anything that is not utf-8.

b- the 2nd level of data encoding is what is sent to the browser and how to force or help the browser to understand what "Character ENcoding" to use.

Well here you have of course to use ""


This is what has worked for me:





<%@ page
language="java"
contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"
%>


MY Page Title.....


Bla bla bla ....


....



PS:
I found in my case that

contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"

is not creating the a HTML meta element ()

the only secure way to have that meta element in your resulting HTML code is to put in the source code of your JSP page (in the HTML source code)

So include always this:


to force the browser to handle & display it as UTF-8.

Most of code is tested on Tomcat 4, Websphere 5, 5.1 and JBoss 3.2.x & 4.
-----------------------------------------------------------------------------


So bottom line is:

1- Judging from your description your code is correct since you are seeing your correct content in the source page.
So the pint is whether you have this in your resulted HTML code:

""

Or check whether your HTML code is valid.


2- if that all is not solving your problem, the other strategy is to check in all those data-intersections whether your content is not tempered with (implicit coversions by your system...).


One of my colleagues resolved this using a specific style.



or alternatively..












Sunday, August 3, 2008

Learning all about thread programming

I find these articles very useful in learning all about programming threads.

http://www.javaworld.com/javaworld/jw-05-2002/jw-0503-java101.html

Spring beans and thread safety

Here is a good thread on how to write thread safe code should there be a need to use instance variables.

http://weblogs.java.net/blog/tomwhite/archive/2006/09/index.html

J2EE and custom multi-threading code.

Since the inception of J2EE, it was strongly discouraged to write custom multi-threaded application running in a J2EE container that might interfere with the container's thread management. In my current project, which is a spring and hibernate application running in JBOSS we have a library that's multi-thread and we believe that's causing some of the site failures today. I was assigned the task of researching alternate solutions for it. We have a long running transaction that get's account information from mainframe. The queueing mechanism for these requests is synchronous block of code. So under high load and poor performance from mainframe, all the request threads waiting to get account information are blocked trying to get into this synchronous block of code. Two solutions were proposed by my colleages. One was to use JMS. Other was to use web services and use alternate queuing mechanism instead. Thinking about JMS, I don't think this solution will work here as we need upto date account information real-time to get lot of features on the site working and also JMS is meant to be reliable solution, but heavy which suits more for order placement etc. Here is an article I was reading on the topic.

http://www.geocities.com/sundar_rajan_in/java/jms/intro.html

Ruby on Rails introduction for newbies

For newbies like me, here is a good introduction article on ruby on rails. At my work place, we had a training class from Spring Source in which the trainer mentioned that using Ruby on rails, we can build a simple website in a day. However for high volume applications, this is not a solution.

http://www-128.ibm.com/developerworks/java/library/wa-rubyonrails/

Struts and multi-threading

Was reading this artcile on struts and multi-threading.

The Action classes are singleton classes that are instantiated once per class type per JVM, and all requests for a specific action are routed through the same Action class instance. This IBM article states this well:

"Struts will create a single instance of the Action and allow multiple threads to invoke execute(). This allows for faster request processing, as the framework is not continually creating new Action instances to handle each request. But because a single object is shared between multiple threads, you must observe proper threading considerations, as other threads are likely to pummel instance variables that hold state in the action. "

The thread safety thing always seems to comes into play. Now to the Struts Action Class Guidelines:

" Write code for a multi-threaded environment - Our controller servlet creates only one instance of your Action class, and uses this one instance to service all requests. Thus, you need to write thread-safe Action classes. Follow the same guidelines you would use to write thread-safe Servlets. Here are two general guidelines that will help you write scalable, thread-safe Action classes:

Only Use Local Variables - The most important principle that aids in thread-safe coding is to use only local variables, not instance variables, in your Action class. Local variables are created on a stack that is assigned (by your JVM) to each request thread, so there is no need to worry about sharing them. An Action can be factored into several local methods, so long as all variables needed are passed as method parameters. This assures thread safety, as the JVM handles such variables internally using the call stack which is associated with a single Thread.

Conserve Resources - As a general rule, allocating scarce resources and keeping them across requests from the same user (in the user’s session) can cause scalability problems. For example, if your application uses JDBC and you allocate a separate JDBC connection for every user, you are probably going to run in some scalability issues when your site suddenly shows up on Slashdot. You should strive to use pools and release resources (such as database connections) prior to forwarding control to the appropriate View component — even if a bean method you have called throws an exception.

Don’t throw it, catch it! - Ever used a commercial website only to have a stack trace or exception thrown in your face after you’ve already typed in your credit card number and clicked the purchase button? Let’s just say it doesn’t inspire confidence. Now is your chance to deal with these application errors - in the Action class. If your application specific code throws expections you should catch these exceptions in your Action class, log them in your application’s log (servlet.log("Error message", exception)) and return the appropriate ActionForward.

It is wise to avoid creating lengthy and complex Action classes. If you start to embed too much logic in the Action class itself, you will begin to find the Action class hard to understand, maintain, and impossible to reuse. Rather than creating overly complex Action classes, it is generally a good practice to move most of the persistence, and "business logic" to a separate application layer. When an Action class becomes lengthy and procedural, it may be a good time to refactor your application architecture and move some of this logic to another conceptual layer; otherwise, you may be left with an inflexible application which can only be accessed in a web-application environment. The framework should be viewed as simply the foundation for implementing MVC in your applications. Struts Action Framework provides a useful control layer, but it is not a fully featured platform for building MVC applications, soup to nuts. "

Lastly, note that :

"actions are cached, they must be thread-safe. That does’t mean that you can’t use instance variables. If those instance variables are thread safe, and the objects they reference are thread-safe, then everything is good. Servlets suffer the same problem because Servlets are pooled by the container. By default Spring delivers singletons. As long as the services are thread-safe (as all singletons should be), there is no danger."



http://technobuzz.wordpress.com/2005/11/29/struts-singletonand-the-merger/