Saturday, January 03, 2009

Version matching of JSP, JSTL and Servlet

Working with JSP, JSTL, Servlet and Container is not an easy job if you download and configure every part by yourself. The most important problem is version matching. Also web.xml must be correctly configured to make use of the right version of Servlet/JSP.

Web app descriptor (web.xml)
To make use of correct version of JSP/JSTL/EL, you should read following posts which give detailed information you need to know to write web.xml:
http://faq.javaranch.com/java/ServletsWebXml

Some useful resources I found:
http://faq.javaranch.com/java/ElOrJstlNotWorkingAsExpected
http://forum.springframework.org/archive/index.php/t-19866.html
http://blog.csdn.net/eviliw/archive/2007/12/17/1944270.aspx
http://faq.javaranch.com/java/JstlTagLibDefinitions

On Sun's website, it is so hard to find a download link for JSTL 1.2. Usually you will be directed to the JSTL spec site.
You can download JSTL 1.2 from here: https://maven-repository.dev.java.net/repository/jstl/jars/.
Note for JSTL 1.2 there is just one jar file instead of two.
In JSTL 1.1/1.0, there are two jars : jstl.jar and standard.jar.
You can download JSTL 1.1 from here http://jakarta.apache.org/site/downloads/downloads_taglibs-standard.cgi and JSTL 1.0 from http://jakarta.apache.org/site/downloads/downloads_taglibs-standard.cgi.

Version match
JSTL 1.0 : Servlet 2.3 : JSP 1,2 (tomcat 4)
JSTL 1.1 : Servlet 2.4 : JSP 2.0 (tomcat 5)
JSTL 1.2 : Servlet 2.5 : JSP 2.1 (tomcat 6)
In old versions of JSP, EL is not enabled by default!! You can enable EL manually by using JSP page directory.
JSTL  jars are not included in tomcat distributions so far. You need to download and deploy JSTL by yourself.

JSTL 1.0 specifies a set of custom tag libraries based on the JSP 1.2 API. There are four separate tag libraries, each containing custom actions targeting a specific functional area. This table lists each library with its recommended tag prefix and default URI:

Description Prefix Default URI
Core c http://java.sun.com/jstl/core
XML Processing x http://java.sun.com/jstl/xml
I18N & Formatting fmt http://java.sun.com/jstl/fmt
Database Access sql http://java.sun.com/jstl/sql

JSTL 1.1 specifies a set of custom tag libraries based on the JSP 2.0 API. There are five separate tag libraries, each containing custom actions targeting a specific functional area. This table lists each library with its recommended tag prefix and default URI:
Description Prefix Default URI
Core c http://java.sun.com/jsp/jstl/core
XML Processing x http://java.sun.com/jsp/jstl/xml
I18N & Formatting fmt http://java.sun.com/jsp/jstl/fmt
Database Access sql http://java.sun.com/jsp/jstl/sql

One missed tag in the table is "functions".
It seems that you also can use tag URI like this: http://java.sum.com/jstl/core_rt. And it works in my application. However, I have not investigated what's going on behind the scene. So this may or may not work generally. Instead, you should always use the new tag URI.

Prefixes and URL of JSTL 1.2 Tag Libraries are the same as that of JSTL 1.1.

Troubleshooting
(1) If you get following error "According  to TLD or attribute directive in tag file, attribute test does not accept any expressions", it is possible that you don't specify tag prefix and URI correctly. You may be using JSTL 1.2 while you specify tag URI of JSTL 1.0 wrongly. Take Core as an example, tag URI in JSTL 1.1/1.2 is http://java.sun.com/jsp/jstl/core while tag URI in JSTL 1.0 is http://java.sun.com/jstl/core.
(2) If your EL/JSP is displayed directly without evaluation. it is highly possible that your web.xml file specifies wrong JSP version. See this post http://faq.javaranch.com/java/ServletsWebXml.

Monday, December 29, 2008

HTML table cell text wrap

By default, if you set width of table cell, words would be wrapped automatically.  A single word would not be split into pieces. Usually, an English word is not so long. But, some "words" may be very long. For example, URLs without word delimiter would be considered as a single word.
CSS property word-break can be used to force split a long word into more than one line.
usage: work-break:break-all
Unfortunately, that does not work on FireFox :-( I searched the internet and found that FireFox does not support that property. Besides, there is no equivalent in FireFox.

Friday, December 26, 2008

How to use Maven2

Download and install maven: http://maven.apache.org/download.html.

Running Maven
http://maven.apache.org/guides/getting-started/maven-in-five-minutes.html
http://maven.apache.org/guides/getting-started/index.html
Generally the local repository is provided in USER_HOME/.m2/repository.

Configuration
http://maven.apache.org/guides/mini/guide-configuring-maven.html
Three levels:

Build your own private/internal repository:
This article introduces how to create a repository using Artifactory: http://www.theserverside.com/tt/articles/article.tss?l=SettingUpMavenRepository. In addition, the author also compares some mainstream maven remote repository managers including Standard maven proxy, Dead simple Maven Proxy, Proximity and Artifactory.
In my case, I also use Artifactory and deploy it to tomcat. It has a nice web-based interface. Artifactory uses database(derby I think) to store various repository data so a user can not know the repository content by directly looking at the directory.

Deploy your artifacts to remote repository by using maven-deploy plugin:
http://maven.apache.org/plugins/maven-deploy-plugin/usage.html
(1) If the artifacts are built by using Maven, you should use deploy:deploy Mojo.
In your pom.xml, element <distributionManagement/> should be inserted to tell Maven how to deploy current package. If your repository is secured, you may also want to configure your settings.xml file to define corresponding <server/> entries which provides authentication information.
Command: mvn deploy.
(2) If the artifacts are NOT built by using Maven, you should use deploy:deploy-file Mojo.
Sample command:
mvn deploy:deploy-file -Dpackaging=jar -Durl=file:/grids/c2/www/htdocs/maven2 
-Dfile=./junit.jar -DgroupId=gridshib -DartifactId=junit -Dversion=GTLAB

FAQ:
(1) What does maven standard directory layout look like?
http://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html
(1) How to specify parent artifact in pom.xml?
Read http://maven.apache.org/guides/introduction/introduction-to-the-pom.html.
(2) If a dependent package can not be download from central Maven repository, three methods can be used to deal with it:

"
  1. Install the dependency locally using the install plugin. The method is the simplest recommended method. For example:
    mvn install:install-file -Dfile=non-maven-proj.jar -DgroupId=some.group -DartifactId=non-maven-proj -Dversion=1

    Notice that an address is still required, only this time you use the command line and the install plugin will create a POM for you with the given address.

  2. Create your own repository and deploy it there. This is a favorite method for companies with an intranet and need to be able to keep everyone in synch. There is a Maven goal called deploy:deploy-file which is similar to the install:install-file goal (read the plugin's goal page for more information).
  3. Set the dependency scope to system and define a systemPath. This is not recommended, however, but leads us to explaining the following elements:
"
(2) How to add new repository?
Put following code snippet into pom.xml or settings.xml.
<repository>
  <id>your-new-repository-id</id>
  <name>New Maven Repository </name>
  <layout>default</layout>
  <url>Address of the new repository</url>
  <snapshots>
    <enabled>enable-it?</enabled>
  </snapshots>
  <releases>
    <enabled>enable-it?</enabled>
  </releases>
</repository>
(3) How to disable default central maven repository?
Put following snippet into your pom.xml.
<repository>
  <id>central</id>
  <name>Maven Repository Switchboard</name>
  <layout>default</layout>
  <url>http://repo1.maven.org/maven2</url>
  <snapshots>
    <enabled>false</enabled>
  </snapshots>
  <releases>
    <enabled>false</enabled>
  </releases>
</repository>

(4) How can I package source code without run test?
Feed parameter -Dmaven.test.skip=true into the command line.
Note this property is defined by maven plugin surefire.
(5) Why does "mvn clean" delete my source code?
In your pom.xml, if content of element <directory> nested in element <build> is "./", "mvn clean" will delete all content in current directory including the src directory.
There are two more elements which can be used to specify locations of compiled classes.
outputDirectory:  The directory where compiled application classes are placed.
testOutputDirectory:  The directory where compiled test classes are placed.
(6) How to add resources into built package?
http://maven.apache.org/guides/getting-started/index.html#How_do_I_add_resources_to_my_JAR.
http://maven.apache.org/guides/getting-started/index.html#How_do_I_filter_resource_files
(7) Sometime, you want to use some libraries at compilation time and you don't want Maven to add them into your package(jar or war). How to do that?
Use dependency scope "provided" instead of default "compile". Read this post for details:
http://maven.apache.org/general.html#scope-provided. And this post elaborates Maven's dependency mechanism: http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html#Dependency_Scope
(8) How to build a war instead of jar?
Use Maven WAR Plugin: http://maven.apache.org/plugins/maven-war-plugin/usage.html.
First you should set entry packaging in pom.xml to war.
<packaging>war</packaging>
Then you can use one of the following commands to build your war:
mvn package
mvn compile war:war
mvn compile war:exploded
mvn compile war:inplace

Also you can filter resources of your web app. See this post http://maven.apache.org/plugins/maven-war-plugin/examples/adding-filtering-webresources.html.
(9) How to make war and jar at the same time?
By default your source code is compiled into class files and placed into directory WEB-INF/classes. Sometimes you may want to build a jar and then put it into directory WEB-INF/lib.
http://communitygrids.blogspot.com/2007/11/maven-making-war-and-jar-at-same-time.html
http://maven.apache.org/plugins/maven-war-plugin/war-mojo.html
http://maven.apache.org/plugins/maven-war-plugin/faq.html#attached
(10) help plugin can be used get information about a project, plugin or the system.
http://maven.apache.org/plugins/maven-help-plugin/
mvn help:describe -DgroupId=org.apache.maven.plugins -DartifactId=maven-compiler-plugin -Dfull=true
mvn help:describe -DgroupId=org.apache.maven.plugins -DartifactId=maven-compiler-plugin
mvn help:system
mvn help:all-profiles
mvn help:active-profiles


Properties reference:
http://docs.codehaus.org/display/MAVENUSER/MavenPropertiesGuide

During my using of Maven2, I encountered several bugs:
(1) targetPath support on the webResources war plugin parameter:
http://jira.codehaus.org/browse/MWAR-54
(2) maven-war-plugin webResources -- relative path:
http://www.mail-archive.com/users@maven.apache.org/msg77274.html
http://jira.codehaus.org/browse/MNG-2382
http://jira.codehaus.org/browse/MWAR-79
http://jira.codehaus.org/browse/MWAR-77

Install and Configure Ubuntu 8.10

Recently, I got a used desktop which would be used as linux server. I installed Ubuntu 8.10. The installation was easy. I downloaded the Ubuntu .iso file and burned it to a CD. Then just installed Ubuntu using the CD.

Vim upgrade
By default, Ubuntu just installed vim-tiny whose functionalities may not satisfy end user's requirements. For example, opening a directory using vim-tiny would fail rather than list all files in the directory in vim. So I installed vim-full which includes all vim features using this command:
sudo apt-get install vim-full
Then usually vim is configured to meet user's specicial requirements. In my case, the configuration file $HOME/.vimrc looks like:

set tabstop=4
set shiftwidth=4
set wrapmargin=8
set smartindent	"smart indentation
set expandtab  	"expand tabs to spaces
set ruler 		"display ruler on bottom right corner
set nu			"display line number
set incsearch	"turn on incremental search
set hlsearch		"highlight search result

:colorscheme ron 
:filetype indent on		"enable special indentation rules according to file type.

"highlight the 81-th character in each line
au BufEnter * ":/\%81c"
"in default configuration, textwidth option is set
"so I want to override the default value.
au BufRead * set tw=0

"when you open a file, cursor is moved to previous position when you edited the file last time.
au BufReadPost * if line("'\"") > 0|if line("'\"") <= line("$")|exe("norm '\"")|else|exe "norm $"|endif|endif

:syntax on		"turn on syntax detection and highlight
"stop cursor blinking. Only available when compiled with GUI enabled,
"and for MS-DOS and Win32 consol
set guicursor=a:blinkon0

All available options of vim can be read here: http://www.vim.org/htmldoc/index.html

Browser
Firefox is installed by default which is the default web browser. Several addons were installed manually.

Tab Mix Plus Tab browsing with added boost.
All-in-One gestures Support mouse gestures.
 
Firebug Web development Evolved
RestTest

Allow users to send HTTP requests with customized heads and data.

Poster

A developer tool for interacting with web services and other web resources that lets you make HTTP requests, set the entity body, and content type.
Similar to RestTest. But Poster works on FF3 while RestTest does not.

HttpFox An HTTP analyzer
Web Developer Adds a menu and a toolbar with various web developer tools
 
FireShot Take a screenshot and edit it
Google Notebook Firefox addon for google notebook application
QuickRestart Add a "Restart Firefox" item to the "File" menu.
MenuEditor Customize application menus
FlashGot Enables single and massive downloads using external download managers. This addon itself is not a download program.

Terminal configuration
I like "green on black" color theme.

Keyboard shortcuts
Click System -> Keyboard Shortcuts to display the shortcut setting dialog. Shortcuts I use very often include:
Super + s     #start a terminal
Super + m    #toggle maximization state
Super + n     #minimize window
Ctrl+Alt+L    #lock screen
Alt + F2       #Show run application dialog
Alt + Tab     #switch between different windows
Ctrl + Alt + Left/Right/Up/Down    #switch to different workspaces

Following serveral shortcuts are available only after you install compiz and enable corresponding components.
Super + E      #Expo key
Super + Tab  #another window switcher
Super + leftclick    #move the window

Wireless network configuration
Wired network connection is established successfully. However, after I moved my desktop, it is not close to the router and I don't want to connect them using a cable.
I have a D-Link System AirPlus G DWL-G122 Wireless USB Adapter. After I plugged it in, I used command lsusb to see whether the device was detected.  It was detected but it did not work. Obviously, a driver is needed to make it work. I read this post: https://help.ubuntu.com/community/WifiDocs/Driver/Ndiswrapper. It states

D-Link DWL-G122 USB Wireless device: As of December 2008, Ubuntu 8.10 provides full 'out of the box' support for this device, using the rt73usb driver. In this case, there is no need to use ndiswrapper at all and there is no need to make any changes to the default /etc/modprobe.d/blacklist file."

But on my machine, the wireless adapter still did not work even after the module rt73usb was loaded. I guess the reason is that the device mentioned in the manual and my device are different although they seem the same.
Then I followed the instructions on post https://help.ubuntu.com/community/WifiDocs/Driver/Ndiswrapper and it worked well.
Network manager is a convenient tool to configure your network.
http://projects.gnome.org/NetworkManager/
https://help.ubuntu.com/community/NetworkManager

Network Management
Some packages and their useful commands to manage network devices

Supported commands by package "net-tools":
ifconfig: configure the kernel-resident network interfaces.

Supported commands by package "wireless-tools":
iwconfig: it is dedicated to the wireless interfaces. It can be used to set the parameters of NIC which are specific to wireless connection.
iwlist: display additional information from a wireless NIC. "iwlist scan" returns a list of available wireless networks.

Supported commands by package "network-manager":
NetworkManager: network management daemon.
nm-tool: utility to report state of network manager in text mode.
nm-system-settings:

Supported commands by package "network-manager-gnome":
nm-applet: a graphical networkmanager applet. It displays an icon in notification area(usually at top right corner) for managing network devices and connections. Usually, it is started up automatically when the system boots up.
nm-connection-editor: display a graphcial connection configuration tool.

Supported commands by package "gnome-nettool":
gnome-nettool : GNOME network tools. This tool can be used to display detailed network information.

gnome-network-preference : Set network proxy preferences

Compiz window manager
A good reference: https://help.ubuntu.com/community/CompositeManager/CompizFusion
Compiz provides some very cool features I like.
Use command ccsm to display CompizConfig Settings manager.
More shortcuts:
Super + E             #Expo key. supported by "Expo" component.
Super + Tab          #another window switcher. supported by "Shift Switcher" component and "Ring Switcher" component.
Alt + left-button    #move the window. supported by "Move Window" component.
Alt + mid-button   #resize the window. supported by "Resize Window" component.

Input Method
To input Chinese, I added Chinese language support. Executing command "gnome-language-selector" would display "language support" dialog and you can select any language in the list you want to use. Releated packages are installed automatically.
SCIM (smart comman input method) is installed by default. Try command "scim-setup" to configure scim. Use command "im-switch -z en_US -s scim" to switch input method to scim. Then restart X. scim would be started automatically.
Also you can manually start scim using command "scim -d".
To make the lookup table follow the cursor, in scim setup dialog uncheck
FrontEnd -> Global Setup -> Embed Preedit String into client window
and
Panel -> GTK -> Embedded lookup table

Misc. Useful packages I installed:
(*) sudo apt-get install gnome-device-manager
As its name implies, it is a device manager with GUI. Then it can be accessed by clicking Applications->System Tools -> Device Manager.
(*) Totem is installed by default which is a video player.
(*) sudo apt-get install vlc  #vlc player
Also, I tried to find a video player in Ubuntu repositories which can play .rm and .rmvb files. None of vlc, Kmplayer and mplayer can do that job. It seems that the main problem is license which means including real codec is illegal. Finally I downloaded linux version of realplayer from official real web site and installed it successfully.
(*) sudo apt-get install sun-java6-jdk  #jdk 6
Then use update-alternatives --config java to set default java executable.
(*) Package "Transmission" is installed by default which is a BitTorrent client program.
(*) sudo apt-get install deluge-torrent (a bittorrent client)
(*) sudo apt-get install d4x (a download manager)
(*) sudo apt-get install gwget (another download manager)

More tips
How to take screenshots: http://tips.webdesign10.com/how-to-take-a-screenshot-on-ubuntu-linux
How to view btchina in Linux?
http://mozilla.sociz.com/viewthread.php?tid=2367
First install greasemonkey addon and then install the script at http://userscripts.org/scripts/show/33286 (click the button "Install" at top right corner). After successful installation, you can set the options of the script by clicking Tools->GreaseMonkey->User Script Commands -> option-here.
If you use FireFox on Windows, addon IETab can be used.
Flashget on Linux?
Candidates: gwget and WebDownloader for X (d4x) (can be installed from Ubuntu repositories). wxDownload Fast and trueDownloader(maybe must be installed from source).
Pick the ones you like from this list http://en.wikipedia.org/wiki/List_of_download_managers.
How to configure multiple versions of a program?
use utility update-alternatives.

Saturday, December 20, 2008

Latex resources

[How to insert figures to Latex document]
ftp://ftp.tex.ac.uk/tex-archive/info/epslatex.pdf
http://www.miwie.org/tex-refs/html/index.html
FAQ: http://www.physics.ohio-state.edu/~faqomatic/fom-serve/cache/103.html

[Screen presentation]
http://www.math.uakron.edu/~dpstory/pdf_present.html
http://www.miwie.org/presentations/html/index.html

References
http://www-h.eng.cam.ac.uk/help/tpl/textprocessing/teTeX/latex/latex2e-html/index.html
http://www-h.eng.cam.ac.uk/help/tpl/textprocessing/

Document Structuring Conventions and EPS

Document Structuring Conventions (DSC)

PS standard does not specify the overall structure of a PS language program. DSC includes information about the document structure and printing requirements in a way that does NOT affect the PS interpreter in any manner.
DSC comments are specified by two percent characters (%%) as the first characters on a line without leading white space. These two percent characters are immediately followed by a unique keyword - not white space. The keyword starts with a capital letter, e.g. BoundingBox. Some keywords end with a colon (part of the keyword) which indicates that the keyword should be provided arguments. One space character should be inserted between ending colon and its arguments.
Example:
%%BoundingBox: 10 10 200 200

Resources
http://partners.adobe.com/public/developer/en/ps/5001.DSC_Spec.pdf
http://hepunx.rl.ac.uk/~adye/psdocs/DSC.html
http://en.wikipedia.org/wiki/Document_Structuring_Conventions

EPS

"An EPS file is a PS language program describing the appearance of a single page. The purpose of the EPS file is to be included in another PS language page description. The EPS file can contain any combination of text, graphics, and images."
EPS should be DSC-conformant.
EPS file format allows for an optional screen preview image.
Two required DSC header comments are:
%!PS-Adobe-3.0 EPSF-3.0
%%BoundingBox: llx lly urx ury

The first line is the version comment. The second required DSC header comment provides information about size of the EPS file. They are expressed in the default PS coordinate system. For an EPS file, the bounding box is the smallest rectangle that encloses all the marks painted on the single page of the EPS file.
Also, header comments %%Creator:, %%Title:, and %%CreationDate: are recommended.

Coordinate System Transformation
Transform PS coordinate system according to the final placement of the EPS file.
Steps:
(a) Translate the origin of PS coordinate system to the user-chosen origin
(b) Rotate, if the user has rotated the EPS file
(c) Scale
After previous three steps, the lower-left corner of EPS file's bounding box is translated to the user-chosen origin.

Spec: http://partners.adobe.com/public/developer/en/ps/5002.EPSF_Spec.pdf

Bounding box

This piece of information is critical especially when  the .ps figures would be inserted into latex document. Bounding box specifies which region the text and figures in ps file occupy. Latex needs this piece of information because it would reserve corresponding space for the content in ps file. It is specified in a single comment line:
%%BoundingBox: llx lly urx ury
It appears in the one of the first lines of the .ps file.
Parameters:

llx
x coordinate of lower left corner
lly
y coordinate of lower left corner
urx
x coordinate of upper right corner
ury
y coordinate of upper right corner
Example:
%%BoundingBox: 50 50 410 302
Note:
(1) Origin of the coordinate system is lower left corner.
(2) Unit of coordinates is Postscript point which is 1/72 of an inch. 
A PostScript point is slightly larger than a TEX point, which is 1/72.27 of an inch. In TEX and LATEX, PostScript points are called "big points" and abbreviated bp while TEX points are called "points" and abbreviated pt."(from http://www.physics.ohio-state.edu/~faqomatic/fom-serve/cache/105.html)
(3) 0 0 612 792 is the coordinates of a US Letter–sized page

Resources
http://www.physionet.org/physiotools/plt/plt/html/node47.html
http://amath.colorado.edu/documentation/LaTeX/reference/bbox.html

Additional Resources

Postscript:
http://www.tailrecursive.org/postscript/postscript.html
http://hepunx.rl.ac.uk/~adye/psdocs/

Friday, October 10, 2008

JAXP + Java Endorsed Packages

In this post I summarized XML related stuff. After all JAXP was constructed with the hope to unify interface.
Here is a very good FAQ about JAXP.

Pluggability
Pluggability is necessary so that programmers can choose the desired implementations of JAXP.
From the JAXP specification, I found the lookup procedure. For XSLT, the procedure is:

• Use the javax.xml.transform.TransformerFactory system property
• Use the properties file "lib/jaxp.properties" in the JRE directory. This configuration file is in standard java.util.Properties format and contains the fully qualified name of the implementation class with the key being the system property defined above. The jaxp.properties file is read only once by the JSR-000206 Java™API for XML Processing (“Specification”) implementation and its values are then cached for future use. If the file does not exist when the first attempt is made to read from it, no further attempts are made to check for its existence. It is not possible to change the value of any property in jaxp.properties after it has been read for the first time.
• Use the Services API (as detailed in the JAR specification), if available, to determine the classname.
The Services API will look for the classname in the file META-INF/services/javax.xml.transform.TransformerFactory
in jars available to the runtime.
• Platform default TransformerFactory instance.

It seems that the #3 option is used mostly. If you download an implementation jar (xalan.jar or xerces-api.jar...), you should be able to find the corresponding file META-INF/services/javax.xml.xxx.xxx.

Problem with Java SE 1.4
However, there is a problem for Java 1.4. It bundled in an implementation of JAXP 1.1 from Apache. Unfortunately, the developers did not change the package names. Even if you downloads and uses a newer version of package from Apache, none of the plug-in options described above works because the class loader always uses the built-in implementation.

Solution
Then two solutions are provided:
(1) Change the package names to other internal package names (e.g. com.sun.org.apache.*)
This is what Sun does in later Java SE releases.
(2) For old Java SE, Endorsed override mechanism can be used.
Java 5 Endorsed Standard: http://java.sun.com/j2se/1.5.0/docs/guide/standards/index.html.
Users can specify the endorsed package path by setting system property - java.endorsed.dirs.
The default path is: <jre-home>/lib/endorsed
On my machine, the path is /usr/java/jdk1.5.0_09/jre/lib/endorsed.
Information about system properties can be accessed here http://java.sun.com/docs/books/tutorial/essential/environment/sysprop.html.
Also I found a very simple program on the web to list all system properties:

public class DisplaySystemProps {
    public static void main(String[] args) {
         System.getProperties().list(System.out);
    }
}
Then you can check the properties you are interested in, such as user home directory, java home, vm version, java class version, path separator, file separator...

Tomcat
For old tomcat releases which rely on old versions of Java, users can put XML parser  into CATALINA_HOME/common/lib.
But for latest versions, it does not work. Read http://tomcat.apache.org/tomcat-6.0-doc/class-loader-howto.html for more information.

"Classes which are part of the JRE base classes cannot be overriden. For some classes (such as the XML parser components in J2SE 1.4+), the J2SE 1.4 endorsed feature can be used.
In previous versions of Tomcat, you could simply replace the XML parser in the $CATALINA_HOME/common/lib directory to change the parser used by all web applications. However, this technique will not be effective when you are running on JSE 5, because the usual class loader delegation process will always choose the implementation inside the JDK in preference to this one.
Tomcat utilizes this mechanism by including the system property setting -Djava.endorsed.dirs=$JAVA_ENDORSED_DIRS in the command line that starts the container."
In other words, users MUST use Endorsed override mechanism to use another XML parser/XSLT in Tomcat. See this post for more information.

Thursday, August 28, 2008

Ruby notes(2) - OO

Function

Definition
def method([arg1, ..., argn,..., *arg, &arg])
    statements
end
Singleton Method
def obj.method([arg1, ..., argn,..., *arg, &arg])
    statements [rescue [exception [, exception...]] [=>var] [then] code ]... [else code ] [ensure code] end

undef method    #make the method undefined.yield(expr...)    #execute the block passed in to current method.
super(expr...)    #execute the method in super class.
super                #execute the method in super class with current method's arguments are passed in.
yield
alias newmethodname oldmethodname
Method Invocation
(*) General
method ([param1 ...[, *param [, &param]]])
method [param1 ...[, *param [, &param]]]
obj.method([param1 ...[, *param [, &param]]])
obj.method [param1 ...[, *param [, &param]]])
obj::method([param1 ...[, *param [, &param]]])
obj::method [param1 ...[, *param [, &param]]]
(*) With blocks
methdo { |[var1 [, var2 ...]]|
    code
}
method do |[var1 [, var2 ...]]|
    code goes here
end
A block has its own local scope and code within a block can access local variables of outer scope.

Class

Definition
class classname [ < superclass]
    code
end

classname MUST be a constant instead of a global or local variable. Class definition introduces a new scope. In order for different definitions of the same class to be merged, one of the two conditions must be met:
(1) A class does not include superclass
(2) if a class definition includes superclass, superclass MUST match super class of previous declaration.

class << object
    code
end

Creation
Instances of a class are created by using method new.
str = String.new or str = String::new

Modules

Definition
module modulename
    code
end
modulename MUST be a constant instead of a global or local variable. Module definition introduces a new scope. Different definitions of the same module are merged.

Sunday, August 24, 2008

Locale in linux/unix

(1) Get locale information
Use command locale.

locale    //get current locale environment for each locale category defined by the LC_* environment variables.
locale -a //output names of all available locales
locale -m //Write names of available charmaps.
locale -k LC_CTYPE //Write names and values of selected keywords (In this case, it is "LC_CTYPE").

command: localedef
"The  localedef  program  reads  the  indicated  charmap  and input files, compiles them to a form usable by the locale(7) functions in the C library, and places the six output files in the outputpath directory."

When a program looks up locale dependent values, it does this according to the following environment variables, in priority order:

  1. LANGUAGE
  2. LC_ALL
  3. LC_xxx, according to selected locale category: LC_CTYPE, LC_NUMERIC, LC_TIME, LC_COLLATE, LC_MONETARY, LC_MESSAGES, ...
  4. LANG

Variables whose value is set but is empty are ignored in this lookup.
Set locale environment variable (E.g. LC_ALL, LANG...):
ll_cc.encoding  E.g. de_DE.UTF-8, zh_CN.UTF-8
ll_cc@variant  E.g. de_DE@euro, sr_RS@latin
"There is also a special locale, called ‘C’. When it is used, it disables all localization: in this locale, all programs standardized by POSIX use English messages and an unspecified character encoding (often US-ASCII, but sometimes also ISO-8859-1 or UTF-8, depending on the operating system)."
http://www.gnu.org/software/gettext/manual/gettext.html#Setting-the-POSIX-Locale

C lib:
char *setlocale(int category, const char *locale): set the current locale.

Ruby notes-basic(1)

Semicolons and newline characters are interpreted as ending of a statement. +, = or \ can be use as line continuation characters.
Comments
Single-line comments: Comments extend from # to the end of a line.
Multi-line comments:

=begin
comments go here
=end
Note: '=begin' and '=end' must appear at the beginning of a line.
Integer literals: 123, 0123(octal), 0xf34(hex), 0b1123(binary), ?d(char code for 'd')
Float-point literals: 23.45, 3e4, 4E10, 5e+39
String literals:
double quotations: allow substitution and escape character sequences.
single quotations: don't allow substitution and escape character sequences except \\ and \'.
Adjacent strings are concatenated automatically. "abc""def" => "abcdef"
Command execution: `command`. The syntax is similar to the counterpart of bash. It allows substituion and escape character sequences. The output generated by execution of the command is converted to a string.
here documents:

<<EOF
content goes here
EOF
The string is in double quotations.
<<"EOF"
content goes here
EOF
<<'EOF'
content goes here
EOF
The string is in single quotations.
<<`EOF`
command goes here
EOF
The string is in back quotes.
<<-EOF
command goes here
EOF
The delimiter ('EOF' in this example) needs not be at the beginning of a line.

Symbols:
"A symbol is an object corresponding to an identifier or variable"
:name    #symbol for 'name'
:$name   #symbol for variable 'name'
Array
[], [1,2,3], [1,[2,3]]
%w(str1 str2 str3) => ["str1", "str2", "str3"]
Dictionary(Map, or Hash):
{key => value}
Regular expression:
/pattern/
/pattern/options

Alternatives:
%!string! and %Q!string! are equivalent to "string".
%q!string! is equivalent to 'string'
%x!command! is equivalent to `command`.
%r!pattern!

Variable

Type Description Example Note
global variables can be accessed globally by and program. $var Uninitialized global variables are set to nil.
instance variables that belong to an object. @var
class variables that belong to a class. @@var Class variables must be initialized before they are accessed in methods.
contants Constants as you know in other languages Var must begin with an upper case letter.May not be defined in methods.
local Local variables. var must begin with a lowercase letter or _

Variable substitutions: #{varname}. E.g. #{filename}, #{@conf}, #{$stdin} 
Variable assignments
var = value
var1, var2, ..., *varn = expr1, expr2, ..., *exprn
Operators:

expr?expr1:expr2
    The same as the tertiary operator in C/C++.
defined? varname
    #return a description about the variable/method or nil.

Control statements

Name Syntax Alternatives
if if cond [then]
    code
[elsif cond [then]
    code]
[else
    code]
end
code if cond
unless unless cond [then]
    code
[else
    code]
end
code unless cond
case case expr
[when expr [,expr ...] [then]
    code ]...
[else
    code]
end
 
while while cond [do]
    code
end
(1)code while cond
(2)begin code end while cond.
Note: code is executed once before cond is evaluated.
until until cond [do]
    code
end
(1) code until cond
(2) begin code end until cond
Note: code is executed once before cond is evaluated.
for for var[, var2 ...] in expr [do]
    code
end
expr do |var [,var...]|
    code
end
break Break from look  
next like continue in C++  
redo re-execute the loop body once without evaluation of conditional expression.  
retry re-execute a call to a method  
begin begin
    code
[rescue [exception_class [, excep_cls...]] [=>var] [then]
    code ]...
[else
    code ]
[ensure
    code ]
end
Code in ensure clause is always executed.
Code in else clause is executed only when no exceptions are raised.
Code in rescue clause is executed when exception is caught.
rescue code rescue expr Evaluate the expr only if an exception is caught.
raise raise exception_class, message
raise exception_object
raise message
raise
Raise an exception.
To call raise in a rescue clause will re-raise the exception.
BEGIN BEGIN{
    code
}
Code to be executed before the program is run.
END END{
    code
}
Code to be executed when the interpreter quits.