Sunday, March 16, 2008

Java Reflection and bytecode ...

I found a series of very useful articles about Java. Here is the address:http://www.ibm.com/developerworks/java/library/j-dyn0429/.
In this series, the author introduces classloading, bytecode, reflection, Class-transformation on-the-fly...

Javassist --- manipulation of bytecode
Introduction from official site:
"Javassist (Java programming assistant) is a load-time reflective system for Java. It is a class library for editing bytecodes in Java; it enables Java programs to define a new class at runtime and to modify a class file before the JVM loads it. Unlike other similar systems, Javassist provides source-level abstraction; programmers can modify a class file without detailed knowledge of the Java bytecode. They do not have to even write an inserted bytecode sequence; Javassist instead can compile a fragment of source text on line (for example, just a single statement). This ease of use is a unique feature of Javassit against other tools."
http://labs.jboss.com/javassist/
http://www.csg.is.titech.ac.jp/~chiba/javassist/

Configuration Of Tomcat

(Part of this post is cited from Tomcat Offcial site)
    I have been using Tomcat as JSP/Servlet container in current project. However, I have not got full understanding about Tomcat configuration. Every time I need to modify configuration, I search on the web and learn those related elements. I don't have a big picture about it. To fully understand the configuration, I read through official document at this site http://tomcat.apache.org/tomcat-6.0-doc/config/. And as I expect, it helps me a lot.
The configuration file of Tomcat is $TOMCAT_HOME/conf/server.xml.
(1) Server

Root element is server.
(2) Service
    A Service element represents the combination of one or more Connector components that share a single Engine component for processing incoming requests. So it looks like a container to enclose related Connector and Engine.
(3) Connector
    Connector receives requests from clients. There are two kinds of connector:HTTP and AJP.
HTTP Connector enables Tomcat to function as a stand-alone web server. An instance of connector listens for connections on a specific port number. One service can contain more than one connector. Normally, every connector maintains its own thread pool. However, this can be altered by setting property executor. If so, the connector will use the executor and all thread related properties are ignored. One advantage of using executor is that it can shared between components.
    "Each incoming request requires a thread for the duration of that request. If more simultaneous requests are received than can be handled by the currently available request processing threads, additional threads will be created up to the configured maximum (the value of the maxThreads attribute). If still more simultaneous requests are received, they are stacked up inside the server socket created by the Connector, up to the configured maximum (the value of the acceptCount attribute. Any further simultaneous requests will receive "connection refused" errors, until resources are available to process them."
    If SSL on HTTP is needed, corresponding connector element should be modified. Property redirectPort can be used to redirect SSL request received by a plain connector to another connector which supports SSL.
(4) Engine
    Following all connector elements in a service component is engine element. Engine element represents processing machinery associated with a service. It gets and processes all requests from connectors and returns the response to Connector. Note: exactly one engine element should be defined inside a service element.
(5) Host
    Inside engine element, multiple host elements can be nested. Each host element represents a virtual host. At least one host is required, and one of the hosts MUST match value of property defaultHost of engine element. Element alias can be used to give alias. Property appBase is used to specify application base directory of the virtual host. Properties deployOnStartUp and autoDeploy can be configured to set functionality of auto-deployment.
(6) Context
Context element represents a web application which is run inside a certain virtual host. "Each web application is based on a Web Application Archive (WAR) file, or a corresponding directory containing the corresponding unpacked contents, as described in the Servlet Specification (version 2.2 or later)." However, in high version of Tomcat, Context elements do not need to written in server.xml. Detailed information is:
    "For Tomcat 6, unlike Tomcat 4.x, it is NOT recommended to place <Context> elements directly in the server.xml file. This is because it makes modifing the Context configuration more invasive since the main conf/server.xml file cannot be reloaded without restarting Tomcat.
Context elements may be explicitly defined:
  • in the $CATALINA_HOME/conf/context.xml file: the Context element information will be loaded by all webapps
  • in the $CATALINA_HOME/conf/[enginename]/[hostname]/context.xml.default file: the Context element information will be loaded by all webapps of that host
  • in individual files (with a ".xml" extension) in the $CATALINA_HOME/conf/[enginename]/[hostname]/ directory. The name of the file (less the .xml extension) will be used as the context path. Multi-level context paths may be defined using #, e.g. context#path.xml. The default web application may be defined by using a file called ROOT.xml.
  • if the previous file was not found for this application, in an individual file at /META-INF/context.xml inside the application files
  • inside a Host element in the main conf/server.xml

How to map incoming request to specific web app?
    "The web application used to process each HTTP request is selected by Catalina based on matching the longest possible prefix of the Request URI against the context path of each defined Context. Once selected, that Context will select an appropriate servlet to process the incoming request, according to the servlet mappings defined in the web application deployment descriptor file (which MUST be located at /WEB-INF/web.xml within the web app's directory hierarchy)."

Deployment
    If you want to develop and deploy your JSP/Servlet applications, consult this page: http://tomcat.apache.org/tomcat-6.0-doc/appdev/deployment.html. It contains information about: Standard directory layout, where to put shared libraries, web.xml and deployment. This link also contains some useful information: http://tomcat.apache.org/tomcat-6.0-doc/config/host.html#Automatic%20Application%20Deployment.

Configuration of virtual host:
http://hi.baidu.com/zouziting/blog/item/7e3ad7808f3491d79123d936.html

Saturday, March 15, 2008

Edit binary file in hex mode in vim

It will be nice if we can edit binary file directly in vim. VIM provides basic support which has a few restrictions.
(1) Open a binary file
    vim -b datafile
or
    :set binary
(2) Many characters are unprintable. You can see the Hex format by using:
    :set display=uhex
Or you can use ga command to see the value of current character.
(3) To see current position, use
    g CTRL-G
The output is verbose:
    Col 6 of 38; Line 31 of 31; Word 94 of 96; Byte 747 of 780
(4) Move to a specific byte offset:
    234go
(5) xxd can be used to convert the file into hex dump format
    %!xxd
Result should look like this:   
    0000000: 6262 630a 6465 660a 6768 696b 0aab de0a  bbc.def.ghik....
There are two parts: hex part and printable character part.
Go back:
    %!xxd -r
Note: only changes in hex part have effect. Changes in printable text part are ignored.

Of course, tool xxd can be used independently in command line.

Friday, March 14, 2008

Google Apps

I have heard of "Google Apps" for a long time, but I have not tried it. Recently, I am investigating some web2.0 applications including Google YouTube, CodeSearch... Gradually, I knew more about Google Apps. It is integration of various Google Applications including Gmail, doc&Spreadsheet, GTalk... The standard edition of Google Apps is free!! And premier edition is $50 which is much cheaper than Microsoft office. As a result, it may become first choice of small companies which don't want to spend lots of money to buy MS Office. By using Google Apps, users can build web site for their companies and make use of Google Doc, GTalk, Gmail and much more applications made by Google.
However, these two rivals are not counterparts. Google Apps aims to provide a way for businesses to build applications conveniently. The end users don't need to maintain any software and hardware to run the system. The infrastructure is provided and managed by Google. In addition, all applications in Google Apps are web-based which means collaboration and communication become light-weight. In other words, users don't need to install any client-side software. This is the largest advantage of Google Apps.
But, Google Apps is not as powerful as MS Office. For example, Google Doc&Spreadsheets provides just very basic editing functionality, which may not meet requirements of advanced users. If someday Google provide its own desktop tools like MS Office, future of Google Apps will be bright.
After all, it is a good thing because Google Apps is a new choice for users. And it may benefit small companies which own limited amount of money.

Thursday, February 21, 2008

Groovy

Recently, I found that something called Groovy is getting popular. Then, I decided to have a look at it. Following are some notes I made during learning of Groovy.
In terms of underlying foundation, Groovy is identical to Java. They all rely on JVM. The advantage of Groovy is that it enhances Java so that programs can be written more compactly and more intuitively. First, Groovy looks like a dynamic script language which is quite different from traditional languages like Java. Users don't need to compile groovy files into .class files manually. Groovy compiler does this automatically for us when a program is executed. Besides, Groovy provides extensive support to make programming an easy job. For example, you can write code like this: mylist = [1, 3, 5]; mylist.each({it -> println it});
Collections:
(1) Range (http://groovy.codehaus.org/api/groovy/lang/Range.html)
Declaration: dot operator (..)
    (leftBound..rightBound)  inclusive(leftBound<= value <=rightBound)
    (leftBound..<rightBound) half-exclusive(leftBound<=value<rightBound)
Note: It is not necessary to let leftBound smaller than rightBound. Range can have a lower left bound and a higher right bound. It is called reverse range.
Declaration Samples:
    ('a'..'c') ('ab'..'az')
    new IntRange(0,10)
    (0..10).each({element -> println element})
Illegal samples:
    ('a'..'bc') ('ab'..'bc')
Data objects can be used in ranges. Unit of increase or decrease is one day.
Implementation:
    IntRange, EmptyRange, ObjectRange
Useful Functions:
    each
    contains
    isCase (used in switch statement. This has the same meaning as contains)
Usage:
(1)money = 10000
    switch(money){
        case 0..1000: taxRate = 0.1; break
        case 1001..5000: taxRate = 0.2; break
        default: taxRate = 0.3; break
    }
(2)payroll = [1000, 2000, 1004, 4000];
    filter = 2000..3000
    pryroll.grep(filter)
Customized Range:
Users can create their own types which can be used with ranges, provided following requirements are satisfied:
(1) The type implements functions previous and next.
(2) The type implements compareTo function by overriding the <=> spaceship operator.
(2) List
Declaration:bracket operator([item1, item2, item3])
Declaration Samples:
    list = [1, 2, 3]
    list2 = ['abc', 2, 'def']
Usage:
    println list[0]    //print 1
    println list[0..2] //print 1 2 3
    println list[0,1]  //print 1 2
    list2[3] = 10    //extend the list automatically, list2 becoms ['abc',2,'def',10]
    list2[0..2] = 100 //list2 becomes [100,10]
    list2[0..2] = [1 100] //list2 becoms [1, 100, 10]
Note: access indices can be negative numbers which count from the end of the list. For example: list[-1].
image
(3) Map
Closure
Closures are objects essentially.
Closures are mainly used to represent a specific behavior. In Java, an object has behavior as well as data.
If the closure needs only a single parameter, Groovy provides a default name --it. Print a file: new File('input.txt').eachLine{ println it }
Declaration:
    (1..10).each{ele -> println ele} or (1..10).each({ele -> println ele})
    def clo = {ele -> println ele}
    def Closure getClosure(){
        return { ele -> println ele }
    }
You can use methods as closures.
Call closures:
    closure(parameters)    or    closure.call(parameters)

Audio Record

Recently, I am looking for a good audio recording software.
In my English class, we use Sanako to do this job. It is easy to use, but I think it is too simple in terms of functionality. As a result, I wanted to find a free and great audio recording software. At last, I found one which I think satisfies my requirements. It is Audacity -- a open source software. It is powerful. It supports multi-tracks.
Chinese software:
(1) wavecn
    It looks like a great product. However, I have not tried it.

Some commercial software:
(1) Cooledit

Monday, February 18, 2008

Javascript snippet

In my application, I need to modify a select dynamically. I found out inconsistency between IE and Firefox. In Firefox, property innerHTML can be used to set the content of a select object while it does not work in IE.

Following snippet works in Firefox:

var ele = document.getElementById('select1');
var htm = '<option value="coke">cokecola</option><option value="pepsi">Pepsi</option>';
ele.innerHTML = htm;

But it does not work in IE. You should use following snippet in IE:

var ele = document.getElementById('select1');
ele.options[0] = new Option('cokecola', 'coke');
ele.options[1] = new Option('Pepsi', 'pepsi');

Thursday, January 31, 2008

Matlab (2) - Drawing

Basic functions:
plot mesh

How to query handles of a graph?
findall
findobj
When a handle is obtained, then following function can be used to set properties of the object corresponding to the handle.
set() 

Other functions related to manipulation of handles: 
gcf: get current graph. If no figure exists, MATLAB creates one and returns its handle
gca: get current axes handle.
gco: Return handle of current object
gcbo: Return handle of object whose callback is executing
root object: Root object properties
figure: creates a new figure object using default property values. Figure objects are the individual windows on the screen in which MATLAB displays graphical output.
delete: Delete files or graphics objects
close: deletes the current figure or the specified figure(s).
cla: deletes from the current axes all graphics objects.
clf: deletes from the current figure all graphics objects including axes.
clc: Clear Command Window.
clear:Remove items from workspace, freeing up system memory
home: moves the cursor to the upper-left corner of the Command Window. You can use the scroll bar to see the history of previous functions.
reset: resets all properties having factory defaults on the object identified by h.
hold: determines whether new graphics objects are added to the graph or replace objects in the graph.
ishold: Returns current hold state
newplot: prepares a figure and axes for subsequent graphics commands

load: Load workspace variables from disk
save: Save workspace variables on disk
who, whos: List variables in workspace
workspace:
what: List MATLAB files in current directory
which: Locate functions and files
type: Display contents of file
path: View or change MATLAB directory search path
savepath: Save current MATLAB search path to pathdef.m file
rmpath: Remove directories from MATLAB search path
restoredefaultpath: Restore default MATLAB search path
pathdef: List of directories in MATLAB search path
partialpath:Partial pathname description.A partial pathname is a pathname relative to the MATLAB path, matlabpath. It is used to locate private and method files, which are usually hidden, or to restrict the search for files when more than one file with the given name exists.
fileparts: Return filename parts
fullfile:Build full filename from parts
genpath: Generate path string
pathsep: Return path separator for current platform
filesep: Return directory separator for current platform
addpath: Add directories to MATLAB search path

File operations:
fprintf: Write formatted data to file
fscanf: Read formatted data from file
fclose: Close one or more open files
fopen: Open file, or obtain information about open files
ferror: Query MATLAB about errors in file input or output
fread: Read binary data from file
fwrite: Write binary data to file
fseek: Set file position indicator
ftell: Get file position indicator
feof: Test for end-of-file
fgetl: Read line from file, discarding newline character
fgets: Read line from file, keeping newline character


sprintf
sscanf
int2str
num2str
str2num
hex2num
hex2dec
dec2bin
bin2dec
dec2hex
num2hex
mat2str

format
textread
disp
text

Tools:
pathtool: Open Set Path dialog box to view and change MATLAB path
imtool:

To see the list of factory defaults, use the statement
get(0,'factory')

 

more: Control paged output for Command Window
diary: Save session to file. The diary function creates a log of keyboard input and the resulting text output.
evalc: Evaluate MATLAB expression with capture
eval: Execute string containing MATLAB expression
evalin: Execute MATLAB expression in specified workspace
feval: Evaluate function

function_handle(@):Handle used in calling functions indirectly. E.g. handle = @functionname
functions: Return information about function handle
func2str: Construct function name string from function handle
str2func" Construct function handle from function name string
builtin: Execute built-in function from overloaded method. E.g. builtin('pi'). This function is useful if some of your functions/variables have the same names as built-in functions/variables.
class: Create object or return class of object. E.g.
isa: Determine if input is object of given class. E.g. isa(rand(3,4),'double')

assignin: Assign value to variable in specified workspace

try: Attempt to execute block of code, and catch errors
catch: Specify how to respond to error in try statement.
rethrow:Reissue error
lasterror: Return last error message and related information
lasterr: Return last error message
lastwarn: Return last warning message
warning: Display warning message
error: Display error message
warndlg: Display warning dialog box
dialog: Create and display dialog box
errordlg: Create and display an error dialog box
helpdlg: Create and display help dialog box
questdlg: Create and display question dialog box
inputdlg: Create and display input dialog box
msgbox: Create and display message box
pagesetupdlg: Display page setup dialog box
end: Terminate block of code, or indicate last index of array

dbstop: Set breakpoints
printdlg: Display print dialog box
print, printopt: Create hardcopy output
printpreview:Preview figure to be printed
textwrap: Return wrapped string matrix for given uicontrol

break, for, if, return, switch, while

display: Overloaded method to display text or array
disp: Display text or arrayrat
rats:Rational fraction approximation

isnumeric:Determine if input is numeric array
isfloat isinteger

floor
round
ceil

spy: Visualize sparsity pattern
gplot: Plot set of nodes using an adjacency matrix
sparse: Create sparse matrix
diag: Diagonal matrices and diagonals of a matrix
tril: Lower triangular part of a matrix
triu: Upper triangular part of a matrix
spdiags: Extract and create sparse band and diagonal matrices
full: Convert sparse matrix to full matrix
issparse: Determine if input is sparse
nnz: Number of nonzero matrix elements
nonzeros: Nonzero matrix elements
nzmax: Amount of storage allocated for nonzero matrix elements
size: Array dimensions
isempty:Determine if array is empty
numel: Number of elements in array or subscripted array expression
prod: Product of array elements
cumprod: Cumulative product
cumsum: Cumulative sum
sum
diff: Differences and approximate derivatives
length: Length of vector
ndims: Number of array dimensions
find: Find indices and values of nonzero elements

subsasgn:Overloaded method for A(I)=B, A{I}=B, and A.field=B
subsref:Overloaded method for A(I), A{I} and A.field
substruct:Create structure argument for subsasgn or subsref

exist: Check if variables or functions are defined
computer: Return information about computer on which MATLAB is running
getenv ispc isunix isstudent ver version license

lookfor: Search for keyword in all help entries
doc docopt
help helpwin helpbrowser web

regexp, regexpi: Match regular expression
regexprep: Replace string using regular expression

nargin, nargout: Return number of function arguments

strfind: Find one string within another
findstr: Find string within another, longer string
strmatch: Find possible matches for string
strcmp, strcmpi, strncmp, strncmpi, strvcat

DB family
dbtype: List M-file with line numbers

Monday, January 28, 2008

<pre class="languageName:nocontrols" name="code"> code </pre>
indent paragraph: <div class="indentparagraph"> content goes here </div>

A Groovy sample

Sometimes, I use MS visual studio to write programs. MS VS automatically generates additional files and directories which are not necessary when I release my code. For example, debug directory and .ncb file. When I finish my program, I want to delete these unnecessary files/directories. To delete them manually is not a good choice considering number of programs I have. So I decide to write a Groovy script to do this task and following is my code.

/**
 * This Groovy script is used to delete directories named 'debug'.
 * Usually, this directory is generated by MS Visual Studio when
 * you compile your code in debug mode. After you release your 
 * code, debug information can be discarded. Or else, it occupies
 * non-trivial amount of hard disk space.
 * Moreover, MS VS generates .ncb files. 
 * Besides debug directory and .ncb file, you can easily change 
 * the pattern of files/directories you want to delete.
 */
 
def baseDir = 'E:\\my_program'
dirPattern = /[d|D][e|E][b|B][u|U][g|G]/
fileNamePattern = /.*\.ncb$/

/** This closure delete a specified directory or file 
 * Note: here File means a regular file or a directory.
 */
deleteFile= {
 currentObj ->
 if( currentObj.isDirectory() ){
  currentDir.eachFile{
   currentFile ->
   if( currentFile.isFile() ){
    //first file
    if( currentFile.delete() == false )
     println "file " + currentFile + " failed to be deleted"
   }else if( currentFile.isDirectory() ){
    //then recursively delete dirs
    deleteDir( currentFile )
   }
  }
 }
 //delete this dir
 if( currentObj.delete() == false )
  println "dir " + currentDir + " failed to be deleted"
}

/** delele directories corresponding to pattern specified by variable
 *  dirPattern.
 */
deleteDirs ={
 _baseDir ->
 _baseDir.eachDir{
  currentDir ->
  def dirName = currentDir.getName()
  if( dirName ==~ dirPattern){
   //find it, just delete it
   deleteFile(currentDir)
  }else//recursivly look for it
   deleteDirs(currentDir)
 }
}

/** delele files corresponding to pattern specified by variable
 *  fileNamePattern.
 */
deleteFiles ={
 _baseDir ->
 _baseDir.eachFile{
  currentFile ->
  if( currentFile.isFile() ){
   def fileName = currentFile.getName()
   println fileName
   if( fileName ==~ fileNamePattern ){
    //find it, just delete it
    deleteFile(currentFile)
   }
  }else//recursivly look for it
   deleteFiles(currentFile)
 }
}

/** Sample usage */
deleteDirs(new File(baseDir))
deleteFiles(new File(baseDir));