Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Thursday, 27 October 2016

Tomcat Performance

Tomcat's basic status can be accessed via the url: http://localhost:8080/manager/status url. It shows the threads and the connections stats.

To see detailed tomcat statistics enable JMX beans for tomcat by adding following to setnev.sh - "-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.port=15555"

Then the MBeans for tomcat and your specific webapp/Servlet can be accessed via jconsole or JMXProxyServlet.
https://tomcat.apache.org/tomcat-7.0-doc/manager-howto.html#Using_the_JMX_Proxy_Servlet

You need to add following entries to conf/tomcat-users.xml to be able to access manager/status and manager/jmxproxy urls.
<role rolename="manager-gui"/>
<role rolename="manager-status"/>
<role rolename="manager-script"/>
<role rolename="manager-jmx"/>

 <role rolename="tomcat"/>
 <role rolename="role1"/>
 <user username="tomcat" password="tomcat" roles="tomcat,manager-gui,manager-status,manager-jmx"/>
 <user username="both" password="tomcat" roles="tomcat,role1"/>
 <user username="role1" password="tomcat" roles="role1"/>

Source: https://www.mulesoft.com/tcat/tomcat-performance

Tuning Tomcat Performance For Optimum Speed

Tomcat configuration is by default geared towards first time users looking for powerful, hassle-free, out-of-the-box functionality. However, when deployed in a real-world setting, where high server load can be expected and achieving the best possible peak load performance is vital, it is important to customize these default settings based on your site's needs.
This may seem like a daunting task, and it is certainly not a small one, but the good news is that Tomcat is a very configurable system, and by following a logical process of testing and implementation, you can vastly improve your site's performance.
Are you tuning Tomcat for performance? Tcat gives you deep visibility into the performance of your web applications, and allows you to save optimal configurations. Get new instances up and running with a single click. Try Tcat today!

Understanding Limits

While some of Tomcat's settings can be adjusted in a way that will increase any site's performance, the most beneficial techniques for increasing Tomcat's performance are need-specific - that is, they are geared towards making Tomcat perform in the best way for your site, based on factors such as the types of traffic you serve and the web applications your server runs.
Before getting down to business, let's take a look at the biggest limits on your site's performance. Three factors negatively impact Tomcat's performance more than any others - network delays, remote client latency, and application architecture.
Two of these factors - network delays and remote client latency - are for the most part unavoidable, although using a web server in front of Tomcat to serve static content will free up more power for dynamic content. Remote client latency can be mitigated by compressing content with Apache mod_zip or Tomcat's compression filter.
However, the largest increases in performance are directly related to the architecture of your web applications. Consequently, the first step towards streamlining Tomcat's performance is determining the needs of your site, and using benchmark tools to obtain a clear, comprehensive picture of your site's current performance.

Establishing a Benchmark

Before any improvements can be made, it is essential to establish an accurate benchmark of your site's current performance, so that any changes can be measured in a useful, quantifiable manner.
There are a wide variety of both commercial and free tools that you can use to measure Tomcat's performance. Two of the most effective, Apache Jakarta JMeter, and ab, an HTTP server benchmark tool provided by Apache, can be obtained for free on Apache's website, along with further documentation and more specialized benchmark tools.
To generate a high-quality benchmark, it is important to simulate the real world scenario in which your site operates as closely as possible. Your test system should be as close a match to your production system as possible. Use the same hardware, OS, and software, and populate databases with the expected real-world record load. Generate traffic that is characteristic of your real-world traffic - if you are expecting lots of human traffic, don't test your system with repetitive HTTP requests.
When running your benchmarks, make sure to include tests for any special situations such as short term traffic spikes or searches that return extremely large result sets. Your final tests should be run over a two to three day period, as factors such as variable JVM performance and Tomcat memory leaks may only expose themselves after a longer time period.

General Tuning Techniques

Now that you've established your benchmark, it's time to apply a few techniques that provide a general increase in performance for almost all Tomcat users. This will allow you to determine how much your application's architecture needs to be modified.

Tuning JVM

The proper Tomcat JVM configuration is essential for getting the most out of your server.
Before you start changing any settings, you should make sure that you have chosen the most logical JVM for your site's needs. There are a growing number of JVM vendors, and if you do not require any JDK-specific functionality, it is a good idea to run some benchmarks and see which solution gives you the best performance. Also, make sure to upgrade to the latest stable release of your JVM, as this may give you a sizable performance boost right away.
Next, consider experimenting with your JVM threading configuration. If your JVM supports both green and native threads, you should try both models to determine the best choice for your site. If you are running I/O bound applications, the native thread model should offer you improved performance. However, green threads will decrease the load placed on your machine. If you are unsure which option to choose, native threads are usually a good choice.
Certain JVM processes, such as garbage collection and memory reallocation, can be a drain on your server. You can reduce the frequency with which these processes occur by using the -Xmx and -Xms switches to control how JVM handles its heap memory.
JVM garbage collection can use up valuable CPU power that you want being used to serve web requests. To reduce the frequency with which JVM invokes garbage collection, Use the -Xmx switch to start the JVM with a higher maximum heap memory. This will free up CPU time for the processes you really care about.
To maximize the effectiveness of this technique, use the -Xms switch to ensure that the JVM's initial heap memory size is equal to the maximum allocated memory. This will keep the Tomcat JVM from having to reallocate and resize its heap memory, which will free up additional CPU cycles for Tomcat to serve requests. If your web applications can handle the possibility of lower total garbage collection throughput, you should try enabling incremental collection with -Xincgc.
If you need more information on the way your current configuration is handling your collection load, use -verbose:gc to capture performance data.

Configuring Connectors

Basing your maxThreads Connecter thread pool settings on an accurate estimation of your web request load is essential for getting the most out of Tomcat.
Values that are too small can leave you without enough threads to handle all your requests, and prevent Tomcat from effectively utilizing your server hardware to increase performance. Values that are too high significantly increase Tomcat's startup time, which is a critical issue at at peak traffic intervals. Experiment with different values to determine the best middle ground, and you should see an increase in performance.

Compression

By default, the compression attribute is set to off, but some applications perform better when it is switched to on. Try changing your settings and see what works best for your site. If you find that turning compression on increases your performance, make sure you use the compressableMimeTypes setting to specify what types of data you want compressed.

HTTP, HTTPS, and HTTPD

In general, using HTTP instead of HTTPS will result in much better Tomcat performance. However, HTTP may not be right for your site. If you require the security of HTTPS, despite its slow speed compared to HTTP, you may have to consider adding additional servers closer to your users to increase speed. The problem lies in the verbose traffic HTTPS generates during requests, which increases the overall serve time for users with higher pings.
Whatever you do, using Apache HTTPD to proxy your requests should be avoided at all costs, as it will decrease your performance by nearly 50%.

Web Servers For Static Content

Tomcat's major strength is dynamic content generation, and it will balance loads better if it is not responsible for anything else. Dedicating a web server in front of Tomcat to serve any static content your site requires is a quick way to free up more power to serve requests.

Stay Current

Every major Tomcat release is optimized for higher performance across the board. Taking the time to keep your version updated will save you big performance headaches in the future.

Tuning Your Applications For Performance

Now that you've done everything you can to customize Tomcat's configuration to match your needs, it's time to look at improvements to your application's architecture. This process is more complex, but the performance gains you will see are exponentially greater.
The best time to think about optimizing your application for better performance with Tomcat is during the development phase. Using tools such as JProbe or OptimizeIt to search for any bottlenecks due to thread synchronization will save you a lot of hassle when you deploy your application.
Additionally, read up on optimization techniques specific to each of your application's elements. If your database performance is slower than you'd like, consider using middleware to persist and cache objects. You'll see less thrashing of the JVM for creation, which means less garbage collection, and less db query latency. Consider factors such as the suitability of your protocol for the project. For example, if you are loading large amounts of data, and you need high performance, XML is the wrong choice.
Design your application to distribute work across the tools that do that work most efficiently. If you are serving dynamic pages that are in reality more static than dynamic, consider changing them to static pages and serving them with your web server to take some unnecessary load off of Tomcat.
If the page changes too frequently to make this option logical, try temporarily caching the dynamic content, so that it doesn't need to be regenerated over and over again. Any techniques you can use to cache work that's already been done instead of doing it again should be used - this is the key to achieving the best Tomcat performance. The most significant limits to performance are the demands of your web application, so consider all your design choices carefully.
Implement these techniques, and you're well on your way to great Tomcat performance.

Thursday, 6 November 2014

Using Memory Mapped files in Java

When two processes map the same file in memory, the memory that one process writes is seen by another process, so memory mapped files can be used as an interprocess communication mechanism. We can say that memory-mapped files offer the same interprocess communication services as shared memory with the addition of filesystem persistence. However, as the operating system has to synchronize the file contents with the memory contents, memory-mapped files are not as fast as shared memory.


/*--------------------------------------------------------------
Class MemoryMapWriter - creates mmap file
---------------------------------------------------------------*/

import java.io.File;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

public class MemoryMapWriter {

public static void main(String[] args) throws Exception {
File f = new File("/tmp/mapped.txt");
f.delete();

FileChannel fc = new RandomAccessFile(f, "rw").getChannel();

int start = 0;
long counter = 1;
long HUNDREDK = 100000;
long startT = System.currentTimeMillis();
long noOfMessage = HUNDREDK * 100 * 10;

long bufferSize = 8 * noOfMessage;
MappedByteBuffer mem = fc.map(FileChannel.MapMode.READ_WRITE, 0,
bufferSize);

for (;;) {
if (!mem.hasRemaining()) {
start += mem.position();
mem = fc.map(FileChannel.MapMode.READ_WRITE, start, bufferSize);
}
mem.putLong(counter);
counter++;
if (counter > noOfMessage)
break;
}
long endT = System.currentTimeMillis();
long tot = endT - startT;
System.out.println(String.format("No Of Message %s , Time(ms) %s ",
noOfMessage, tot));

fc.close();
unmap(fc, mem);
}

private static void unmap(FileChannel fc, MappedByteBuffer bb)
throws Exception {
Class<?> fcClass = fc.getClass();
java.lang.reflect.Method unmapMethod = fcClass.getDeclaredMethod(
"unmap", new Class[] { java.nio.MappedByteBuffer.class });
unmapMethod.setAccessible(true);
unmapMethod.invoke(null, new Object[] { bb });
}

}

/*--------------------------------------------------------------
Class MemoryMapReader - reads mmap file
---------------------------------------------------------------*/
package org.g;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

public class MemoryMapReader {

public static void main(String[] args) throws FileNotFoundException,
IOException, InterruptedException {

FileChannel fc = new RandomAccessFile(new File("/tmp/mapped.txt"), "rw")
.getChannel();

// long bufferSize=8*10000;
MappedByteBuffer mem = fc.map(FileChannel.MapMode.READ_ONLY, 0,
fc.size());
long oldSize = fc.size();

long currentPos = 0;
long xx = currentPos;

long startTime = System.currentTimeMillis();
long lastValue = -1;

int exporterId = 8;

mem.position(exporterId * 8);
long res = mem.getLong() - 1;
if (res != exporterId) {
System.out.println("this should not happen !! ");
}

System.out.println("Resetting pos ...");
// reset position again
mem.position(0);

for (;;) {

while (mem.hasRemaining()) {
lastValue = mem.getLong();
currentPos += 8;
}
if (currentPos < oldSize) {

xx = xx + mem.position();
System.out.println("this shuold never occur !!! ");
// mem = fc.map(FileChannel.MapMode.READ_ONLY,xx, bufferSize);
continue;
} else {
long end = System.currentTimeMillis();
long tot = end - startTime;
System.out.println(String.format(
"Last Value Read %s , Time(ms) %s ", lastValue, tot));
break;
}

}

}

}

More Reading:
--------------------

To unmap the memory mapped byte buffer - http://lotusandjava.blogspot.in/2012/02/how-to-unmap-mappedbytebuffer.html
http://stackoverflow.com/questions/8462200/examples-of-forcing-freeing-of-native-memory-direct-bytebuffer-has-allocated-us


JNI - Calling native functions in Java

This example has been taken from this link -  http://www.science.uva.nl/ict/ossdocs/java/tutorial/native1.1/stepbystep/index.html

Hello world example for native functions :

1.) Compile your Java code using javac.
/*-------------------------------------
Class HelloWorld
--------------------------------------*/
class HelloWorld {
    public native void displayHelloWorld();

    // Declare a native method average() that receives two ints and return a double containing the average
    public native double average(int n1, int n2);

    static {
        //System.loadLibrary("hello");
        // You can specify the full path to the lib file
    System.load("/Users/xyz/Documents/workspace/JNITest/src/libhello.so");
    }
}


/*-------------------------------------
Class JNITest - with main()
--------------------------------------*/
public class JNITest {
public static void main(String[] args) throws InterruptedException {
HelloWorld hw = new HelloWorld();
hw.displayHelloWorld();

Thread.sleep(1000);
System.out.println("Exiting ... "+hw.average(2, 100));
}

}

2.) Generate the c++ header file using the javah command

> javah HelloWorld

3.) Write the c++ native function implementation

#include <jni.h>
#include "HelloWorld.h"
#include <stdio.h>

JNIEXPORT jdouble JNICALL Java_HelloWorld_average(JNIEnv * jenv, jobject jo, jint n1 , jint n2){

return ((jdouble)n1 + n2) / 2.0;
}

JNIEXPORT void JNICALL
Java_HelloWorld_displayHelloWorld(JNIEnv *env, jobject obj)
{
  printf("Hello world!\n");
  return;
}

4.) Compile your c++ code and create a shared library

Note: If you have problems importing <jni.h> on linux box ensure that the include path contains your java's include directories. For example:
> g++ -O3 -shared -fPIC mibc.cpp -I /usr/java/default/include/ -I /usr/java/default/include/linux/ -o libhello.so -lrt

5.) Run your java program
Place your shared library in the correct path as specified in the java System.load() call. And run the java program using "java JNITest"

More Reading:
To use different data types for native calls -  https://www3.ntu.edu.sg/home/ehchua/programming/java/JavaNativeInterface.html
JNI performance and overheads -
http://thinkingandcomputing.com/2014/03/30/eliminating-jni-overhead/
http://a-hackers-craic.blogspot.in/2012/03/jni-overheads.html
http://stackoverflow.com/questions/6175209/low-latency-ipc-between-c-and-java
http://stackoverflow.com/questions/7699020/what-makes-jni-calls-slow
http://www.ibm.com/developerworks/java/library/j-jni/
http://normanmaurer.me/blog/2014/01/07/JNI-Performance-Welcome-to-the-dark-side/
http://www.javaworld.com/article/2077554/learn-java/java-tip-54--returning-data-in-reference-arguments-via-jni.html
http://stackoverflow.com/questions/1632367/passing-pointers-between-c-and-java-through-jni

Tuesday, 4 March 2014

Learning Scala

Reading : http://twitter.github.io/scala_school/

def f1(x : Int) : Int = x+1

def fact( z: Int) : Int = z* fact(z-1)

Anonymous functions
-------------------
scala> val addOne = (x: Int) => x + 1
addOne: (Int) => Int = <function1>

scala> addOne(1)
res4: Int = 2

def timesTwo(i: Int): Int = {
  println("hello world")
  i * 2
}

Partial application
-------------------

scala> def adder(m: Int, n: Int) = m + n
adder: (m: Int,n: Int)Int

scala> val add2 = adder(2, _:Int)
add2: (Int) => Int = <function1>

scala> add2(3)
res50: Int = 5

Curried functions
-----------------

scala> def multiply(m: Int)(n: Int): Int = m * n
multiply: (m: Int)(n: Int)Int


You can take any function of multiple arguments and curry it.

scala> val curriedAdd = (adder _).curried
curriedAdd: Int => (Int => Int) = <function1>

scala> val addTwo = curriedAdd(2)
addTwo: Int => Int = <function1>

scala> addTwo(4)
res22: Int = 6


Variable length arguments
-------------------------

def capitalizeAll(args: String*) = {
  args.map { arg =>
    arg.capitalize
  }
}

scala> capitalizeAll("rarity", "applejack")
res2: Seq[String] = ArrayBuffer(Rarity, Applejack)


Classes
-------

scala> class Calculator {
     |   val brand: String = "HP"
     |   def add(m: Int, n: Int): Int = m + n
     | }
defined class Calculator

scala> val calc = new Calculator
calc: Calculator = Calculator@e75a11



http://jim-mcbeath.blogspot.in/2009/05/scala-functions-vs-methods.html

Wednesday, 6 March 2013

Using memcache with Java



Memcache Overview

- A distributed cache
- Store the key/value pairs in the cache. The value needs to be serializable since the cache is distributed.
- You can use this to cache Database objects as well as the generated HTML page markups from the servlets.
- The nodes of the cache cluster, don't know about each other and don't interact with each other
- The client however, knows about all the nodes in the memcache cluster
- The client hashes the string key and maps the hash value to one of the servers. The get() or set() requests for that key goes to the selected node of the server.
- The client sends the set() request asynchronously to the server using a daemon thread. -- ???
- This is good for web applications which need to scale massively.
- You can use the TELNET mode to connect and issue commands to the memcache cluster for debugging purpose.
- The spymemcached client lib for Java easily integrates with the hibernate.


http://www.javaworld.com/javaworld/jw-05-2012/120515-memcached-for-java-enterprise-performance-2.html?page=4


Sunday, 3 February 2013

Difference between ClassNotFoundException and NoClassDefFoundError

http://stackoverflow.com/questions/1457863/what-is-the-difference-between-noclassdeffounderror-and-classnotfoundexception


The difference from the Java API Specifications is as follows.
Thrown when an application tries to load in a class through its string name using:
  • The forName method in class Class.
  • The findSystemClass method in class ClassLoader.
  • The loadClass method in class ClassLoader.
but no definition for the class with the specified name could be found.
Thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found.
The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found.
So, it appears that the NoClassDefFoundError occurs when the source was successfully compiled, but at runtime, the required class files were not found. This may be something that can happen in the distribution or production of JAR files, where not all the required class files were included.
As for ClassNotFoundException, it appears that it may stem from trying to make reflective calls to classes at runtime, but the classes the program is trying to call is does not exist.
The difference between the two is that one is an Error and the other is an Exception. WithNoClassDefFoundError is an Error and it arises from the Java Virtual Machine having problems finding a class it expected to find. A program that was expected to work at compile-time can't run because of class files not being found, or is not the same as was produced or encountered at compile-time. This is a pretty critical error, as the program cannot be initiated by the JVM.
On the other hand, the ClassNotFoundException is an Exception, so it is somewhat expected, and is something that is recoverable. Using reflection is can be error-prone (as there is some expectations that things may not go as expected. There is no compile-time check to see that all the required classes exist, so any problems with finding the desired classes will appear at runtime.



Monday, 31 December 2012

Adding GC logs to hadoop child processes and analyzing the GC logs

Add the following to the mapred-site.xml file:

mapred.child.java.opts : Java opts for the task tracker child processes. The following symbol, if present, will be interpolated: @taskid@ is replaced by current TaskID. Any other occurrences of '@' will go unchanged. For example, to enable verbose gc logging to a file named for the taskid in /tmp and to set the heap maximum to be a gigabyte, pass a 'value' of: -Xmx1024m -verbose:gc -Xloggc:/tmp/@taskid@.gc.

Additional options: -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -XX:+PrintHeapAtGC

Reference: http://hadoop.apache.org/docs/r1.0.0/mapred-default.html


Analyzing GC logs:
-------------------------

Meaning of the [GC [PSYoungGen: 230400K->19135K(268800K)] line is:

  • Around 256MB (268800K) is the Young Generation Size, 
  • Before Garbage Collection in young generation the heap utilization in Young Generation area was around 255MB (230400K) and 
  • After garbage collection it reduced up to 18MB (19135K).


Reference: http://middlewaremagic.com/weblogic/?p=5131
https://www.ibm.com/developerworks/community/groups/service/html/communityview?communityUuid=22d56091-3a7b-4497-b36e-634b51838e11

Sunday, 7 October 2012

Chat server based on Apache Mina

Initially thought of making a chat server based on tomcat, but came across apache mina and apache async-web products which seem to be exciting and more scalable as well.

http://mina.apache.org/

Sunday, 8 July 2012

How to make the session in a Web Application secure


  • Using HTTPS to transfer session id and cookies as well. (If cookie is transferred over HTTP it can be easily stolen and used for impersonation)
  • Sending an entropic unique token in the hidden field in the page. The server authenticates the user based on this token, otherwise rejects the user request.
  • Session id/token should be unpredictable. Could be generated using java.security.SecureRandom class in Java or as explained in the post: http://technocratme.blogspot.in/2012/04/universally-unique-identifier-uuid.html
  • To confirm the authenticity of the sender of request, one can compare the sender's IP address with the IP of the user who created the session.

Saturday, 7 July 2012

Daemon vs Non Daemon thread in Java

 A Thread can be made a daemon, which makes it run in the background. The latter also affects VM termination behavior: the VM does not terminate automatically as long as there are non-daemon threads running.
A daemon Thread only runs as long as there are non-daemon Threads running. When the last non-daemon Thread ends, the whole program ends no matter if it had daemon Threads still running or not; i.e. A running daemon thread can be terminated by the VM, however a running non-daemon thread can not be terminated by the VM.

An example:
Imagine a Java application. It starts off with just one thread, the "main" thread which runs the main method. This is a regular (non-daemon) thread. Now imagine again that the program starts another thread which sits in a loop doing something. If the new thread is a regular (non-daemon) thread, it will prevent the program from finishing when "main" ends, and keep going forever!

Now, this isn't always what is required. Sometimes you want to end this "background" processing when the program finishes. To do this, you can mark threads as daemon threads. Daemon threads don't prevent the program from ending, but stop when the main thread, stops:

  1. Thread hello = new HelloThread();  
  2. hello.setDaemon(true);  



A classic example of a daemon thread is the garbage collector thread found in many Java Virtual Machines. It needs to run continuously while any other threads are running, but should not prevent the program from exiting. When the program exits, there is no more need for a garbage collector.


Making a jar runnable

This is based on using the MANIFEST.MF file inside the jar, which points to the 'Main class' of the jar and setting the class path too.

http://www.crazysquirrel.com/computing/java/basics/runnable-jar.jspx

Java Shutdown Hooks

 A shut down hook is simply a Thread that is registered with the JVM and run just before the JVM shuts down.


Example code taken from the below mentioned link:




package example;public class ShutdownHook {

  
/**
   * 
@param args
   */
  
public static void main(String[] args) {
    
Hook hook = new Hook();
    System.out.println
( "Running Main Application..." );
    Runtime.getRuntime
().addShutdownHook( hook );
    System.out.println
( "Exiting." );
  
}

  
  
private static class Hook extends Thread {
    
public void run() {
      
System.out.println( "Running Clean Up..." );
    
}
  }
}



http://www.crazysquirrel.com/computing/java/basics/java-shutdown-hooks.jspx

http://stackoverflow.com/questions/2921945/useful-example-of-a-shutdown-hook-in-java

Java Heap dumps and Thread dumps

THREAD DUMP
To take the thread dump of the running java process with process id = PID, use: "kill -3 PID".


The thread dump is written to the system out of the VM on which you executed the kill -3. If you are redirecting the console output of the JVM to a file, the thread dump will be in that file. If the JVM is running in an open console, then the thread dump will be displayed in its console.


You could alternatively use jstack (Included with JDK) to take a thread dump and write the output wherever you want

jstack PID > outfile



HEAP DUMP


You can use jdk utility 'jmap' to take the heap dump.


And use the jdk tool 'jhat' to analyse java heaps.


http://www.startux.de/java/45-java-heap-dump

Thursday, 10 May 2012

Regex - regular expressions

http://community.topcoder.com/tc?module=Static&d1=tutorials&d2=regularExpressions

A regular expression is a special string that describes a search pattern.

A regular expression(regex) is one or more non-empty branches, separated by '|'.
'|' - It matches one of the branches

A branch is one or more atoms, concatenated.

An atom is possibly followed by a '*', '+', '?', or bound.
* - 0 or more atom
+ - 1 or more atom
? - 0 or 1 atom
a{1,3} - atom a occurs between 1 to 3 times

An atom is a regular expression enclosed in '()' (matching a match for the regular expression), a bracket expression (see below),
'.' (matching any single character)
'^' (matching the null string at the beginning of a line)
'$' (matching the null string at the end of a line)
a `\' followed by one of the characters `^.[$()|*+?{\' (matching that character taken as an ordinary character) or a single character with no other significance (matching that character).
There is one more type of atom, the back reference: `\' followed by a non-zero decimal digit d matches the same sequence of characters matched by the d-th parenthesized subexpression (numbering subexpressions by the positions of their opening parentheses, left to right), so that (e.g.) `([bc])\1' matches `bb' or `cc' but not `bc'.

[0-9] or [a-z] for specify the character range
A bracket expression is a list of characters enclosed in '[]'. It normally matches any single character from the list.
If the list begins with '^', it matches any single character not from the rest of the list.
If two characters in the list are separated by `-', this is shorthand for the full range of characters between those two inclusive (e.g. '[0-9]' matches any decimal digit).
With the exception of ']','^','-' all other special characters, including `\', lose their special significance within a bracket expression.

Saturday, 21 April 2012

Java Data Objects (JDO)

Reading: http://java.sun.com/developer/technicalArticles/J2SE/jdo/
The JDO Programming Model
The Development Life Cycle: Using JDO in Your Applications


JDO as part of Google App Engine (GAE):
https://developers.google.com/appengine/docs/java/datastore/jdo/overview

Lifecycle of GAE datastore writes:
https://developers.google.com/appengine/articles/life_of_write



Spring Web MVC step by step tutorial


Steps to setup a Spring Web MVC project on eclipse Helios:

1. Create a new Dynamic Web Project name "SpringWebMVC".

2. Create a JSP, 'SpringWebMVC/WebContent/index.jsp' with contents:
<html>
  <head><title>Example :: Spring Application</title></head>
  <body>
    <h1>Example - Spring Application</h1>
    <p>This is my test.</p>
  </body>
</html>

3. Create 'SpringWebMVC/WebContent/WEB-INF/web.xml', with contents:

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.4"
         xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
         http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" >

  <welcome-file-list>
    <welcome-file>
      index.jsp
    </welcome-file>
  </welcome-file-list>

</web-app>

4. Run the web app on any server and access it through URL: "http://localhost:8080/SpringWebMVC/"

5. Modify 'web.xml' to add the spring's servlet  DispatcherServlet (also known as a 'Front Controller').
 It is going to control where all our requests are routed.

  <servlet>
    <servlet-name>springapp</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>springapp</servlet-name>
    <url-pattern>*.htm</url-pattern>
  </servlet-mapping>

We have decided to let any URL with an '.htm' extension be routed to the 'springapp' servlet (the DispatcherServlet).

6. Create a file called 'springapp-servlet.xml' in the 'SpringWebMVC/WebContent/WEB-INF' directory. This file contains the bean definitions (plain old Java objects) used by the DispatcherServlet. It is the WebApplicationContext where all web-related components go. The name of this file is determined by the value of the <servlet-name/> element from the 'web.xml', with '-servlet' appended to it (hence 'springapp-servlet.xml'). This is the standard naming convention used with Spring's Web MVC framework.

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

  <!-- the application context definition for the springapp DispatcherServlet -->

  <bean name="/hello.htm" class="springapp.web.HelloController"/>

</beans>

Added a bean entry named '/hello.htm' and specify the class as springapp.web.HelloController. This defines the controller that our application will be using to service a request with the corresponding URL mapping of '/hello.htm'. The Spring Web MVC framework uses an implementation class of the interface called HandlerMapping to define the mapping between a request URL and the object that is going to handle that request (the handler). Unlike the DispatcherServlet, the HelloController is responsible for handling a request for a particular page of the website and is also known as a 'Page Controller' (Fowler). The default HandlerMapping that the DispatcherServlet uses is the BeanNameUrlHandlerMapping; this class will use the bean name to map to the URL in the request so that the DispatcherServlet knows which controller must be invoked for handling different URLs.

7. Copy Spring libraries to the 'WEB-INF/lib' folder:
commons-logging.jar
org.springframework.asm-3.1.1.RELEASE.jar
org.springframework.beans-3.1.1.RELEASE.jar
org.springframework.context-3.1.1.RELEASE.jar
org.springframework.core-3.1.1.RELEASE.jar
org.springframework.expression-3.1.1.RELEASE.jar
org.springframework.web-3.1.1.RELEASE.jar
org.springframework.web.servlet-3.1.1.RELEASE.jar

8. Create the controller, 'src/springapp.web.HelloController'.

public class HelloController implements Controller {

    protected final Log logger = LogFactory.getLog(getClass());

    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        logger.info("Returning hello view");

        return new ModelAndView("hello.jsp");
    }

}

 In Spring Web MVC, the Controller handles the request and returns a ModelAndView - in this case, one named 'hello.jsp'/
 The model that this class returns is actually resolved via a ViewResolver. Since we have not explicitly defined a ViewResolver, we are going to be given a default one by Spring that simply forwards to a URL matching the name of the view specified.

Reading:
About using a view resolver and annotation based configuration.
http://blogs.sourceallies.com/2010/02/taking-advantage-of-spring-mvcs-default-behavior/