Tuesday, 13 December 2011

Write JUnit test for XSLT

Firstly, you just create a Util Class for xslt transformer:
import javax.xml.transform.*;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.InputStream;
import java.io.StringWriter;

public class XsltTransformer {
    public static String transformer(InputStream xml, InputStream xslt) throws TransformerException {
        Source xmlSource = new StreamSource(xml);
        StringWriter stringWriter = new StringWriter();
        Result result = new StreamResult(stringWriter);

        TransformerFactory transFact = TransformerFactory.newInstance();
        Source xsltSource = new StreamSource(xslt);
        Transformer trans = transFact.newTransformer(xsltSource);
        trans.setOutputProperty(OutputKeys.INDENT, "yes");
        trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3");

        trans.transform(xmlSource, result);
        return stringWriter.getBuffer().toString();

Secondly, combined with XMLUnit, Junit to verify
    public void testXSLT() {
        InputStream expectedOutput = ODSEventXsltTest.class.getResourceAsStream("ods-output.xml");
        InputStream xml = ODSEventXsltTest.class.getResourceAsStream("ods.xml");
        InputStream xslt = ODSEventXsltTest.class.getResourceAsStream("SSNOdsExportToCannonical.xsl");

        try {
            String actual = XsltTransformer.transformer(xml, xslt);
            String expected = IOUtils.toString(expectedOutput);
            Diff diff = XMLUnit.compareXML(expected, actual);
            String errorMessage = "\nexpected:\n" + expected + "\n-------------------------------------\nbut actual: \n" + actual + "\n>>>>" + diff.toString();
            assertTrue(errorMessage, diff.similar());
        } catch (TransformerException e) {
        } catch (SAXException e) {
        } catch (IOException e) {

How to write unit test for private method in java

  * Method: parseDateTime(String text)
 public void testParseDateTime() throws Exception {
     try {
        CsvToXml csvToXml = new CsvToXml();
        Method method = CsvToXml.class.getDeclaredMethod("parseDateTime", String.class);
        String actual = (String) method.invoke(csvToXml, "2011-11-08T13:04:31.000+11:00");
        String expect = "2011-11-08T12:04:31Z";
        assertEquals(expect, actual);
     } catch (NoSuchMethodException e) {
     } catch (IllegalAccessException e) {
     } catch (InvocationTargetException e) {

BTW. Another choice is PowerMock Framework

Wednesday, 7 December 2011

fibonacci number in javascript under cached way

function fibonacci(n) {
    if (!(n in fibonacci)) {
        if (n == 0) {

           fibonacci[n] = 0;
           return 0;

         if (n == 1) {

            fibonacci[0] = 0;
            fibonacci[1] = 1;
            return 1;

          fibonacci[n] = fibonacci(n -1) + fibonacci(n-2);
     return fibonacci[n];
fibonacci.counter = 0; // for debug
var val1 = fibonacci(10);
var val1 = fibonacci(9);
console.log('counter: ' + fibonacci.counter); // >> counter: 10
var val1 = fibonacci(11);
console.log('counter: ' + fibonacci.counter); // >> counter: 11

Monday, 5 December 2011

static variable in javascript

Functions are not primitive values in JavaScript, but a specialized kind of object, which means that functions can have properties. When a function needs a “static” variable whose value persists across invocations, it is often convenient to use a property of the function, instead of cluttering up the namespace by defining a global variable. You could store this information in a global variable, but that is unnecessary, because the information is used only by the function itself. It is better to store the information in a property of the Function object. So there're two solutions to solve this.
1) using global variable
2) function properties
function uniqueSuffix() {
    uniqueSuffix.counter = uniqueSuffix.counter || 0;
    return uniqueSuffix.counter++;

console.log(uniqueSuffix.counter); // >>2

Tuesday, 29 November 2011

add remove() function to array of javascript

Array.prototype.indexOf = function(e){
    for (var i = 0; i < this.length; i++) {
        if (e==this[i]) {
            return i;

  return -1;

Array.prototype.remove = function(elem) {
    var match = -1;
    while ((match = this.indexOf(elem)) > -1) {
        this.splice(match, 1);

How to create an unique array using javascript

Array.prototype.indexOf = function(e){
    for (var i = 0; i < this.length; i++) {
        if (e==this[i]) {
            return i;

  return -1;

Array.prototype.unique = function () {
    var values = this;
    var uniqueValues = [];
    for (var i = values.length; i--;) {
        var val = values[i];
        if (uniqueValues.indexOf(val) === -1) {
    return uniqueValues;

How to reset the start value of Oracle Sequence?

Alter Sequence SEQ_TX_ID Increment By 1000;
Select SEQ_TX_ID.NextVal From Dual;
Alter Sequence SEQ_TX_ID Increment By 1;

Spring MVC error page

It’s always recommended to display a custom friendly error page instead of the default long java plain exception code in tomcat.So what do you do in Spring MVC Web application? 1) Declare SimpleMappingExceptionResolver in Spring’s bean configuration file.
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <property name="exceptionMappings">
            <prop key="java.lang.Exception">error</prop>
2) Define "error.jsp"
    <link rel="stylesheet" href="<%=request.getContextPath()%>/styles/smoothness/jquery-ui-1.8.12.custom.css" type="text/css"/>
    <script type="text/javascript" src="<%=request.getContextPath()%>/scripts/jquery-1.5.1.min.js"></script>
    <script type="text/javascript" src="<%=request.getContextPath()%>/scripts/jquery-ui-1.8.12.custom.min.js"></script>
        <div class="ui-widget">
            <div class="ui-state-error ui-corner-all" style="padding: 0 .7em;">
                <p><span class="ui-icon ui-icon-alert" style="float: left; margin-right: .3em;"></span>
                    <strong>Alert:</strong> An error has occurred. Please contact our administrator for details.</p>
                <p><strong>Cause:</strong></p> ${exception.message}
3) Exmaple

How to validate Date format in Javascript?

Validate the input Date text is very common in web application. My solution is combine Regular Express and Date object. Using regular express to validate the text under the special pattern(yyyy-MM-dd etc.). Using Date object to validate the year,month, day is reasonable.

function dateValidator(text) {
    var pattern = /^([1-9]\d{3})-(0[1-9]|1[0-2])-([0-2][1-9]|3[0-1])$/;
    if (pattern.test($.trim(text))) {
        var datePart = text.split('-');
        var year = parseInt(datePart[0], 10);
        var month = parseInt(datePart[1], 10) - 1;
        var day = parseInt(datePart[2], 10);
        var date = new Date(year, month, day, 0, 0, 0);

        var y = date.getFullYear();
        var m = date.getMonth();
        var d = date.getDate();

        if ( year == y && month== m && day == d) {
           return true;
    return false;

Friday, 25 November 2011

how to customize icon for JQuery-UI buttons

Step1: define css


Sunday, 13 November 2011

How to avoid web page duplicated submit?

Solution 1) PRG (Post/Redirect/Get) Pattern

Solution 2) Synchronizer Token Pattern (From book "java/j2ee interview")

The basic idea of this pattern is to set a use once only token in a “session”, when a form is requested and the
token is stored in the form as a hidden field. When you submit the form the token in the request (i.e. due to hidden field) is compared with the token in the session. If tokens match, then reset the token in the session to null or increment it to a different value and proceed with the model & database update. If you inadvertently resubmit the form by clicking the refresh button, the request processing servlet (i.e. PurchaseServlet) first tests for the presence of a valid token in the request parameter by comparing it with the one stored in the session. Since the token was reset in the first submit, the token in the request (i.e 123) would not match with the token in the session (i.e. null or 124). Since the tokens do not match, an alternate course of action is taken like forwarding to an error.jsp page.

HTTP Sessions-From book java/j2ee interview

A session identifies the requests that originate from the same browser during the period of conversation. All the servlets can share the same session. The JSESSIONID is generated by the server and can be passed to client through cookies, URL re-writing (if cookies are turned off) or built-in SSL mechanism. Care should be taken to minimize size of objects stored in session and objects stored in session should be serializable.

Session tracking uses cookies by default. What would you do if the cookies are turned off?
If cookies are turned off, you can still enable session tracking using URL rewriting. This involves including the session ID within the link as the name/value pair as shown below.

Adding session ID to each and every link is cumbersome and hence is simplified by the following methods: response.encodeURL(givenURL) to associate a session ID with a given URL and if you are using redirection then response.encodeRedirectURL(givenURL).
public class CRMServlet extends HttpServlet {
   protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     req.getSession().setAttribute("key", "ItemNo-1245");
     String url = resp.encodeURL("/myWebCtxt/purchase.do");
     PrintWriter pw = resp.getWriter();
     pw.println("Sample encoded URL -->purchase");
When you invoke the method encodeURL(givenURL) with the cookies turned on, then session ID is not appended to the URL. Now turn the cookies off and restart the browser. If you invoke the encodeURL(givenURL) with the cookies turned off, the session ID is automatically added to the URL as follows:

How do you upload a file to your web application? -From book java/j2ee interview

Upload file via web application then the default encoding and GET methods are not suitable for file upload and a form containing file input fields must specify the encoding type “multipart/formdata”and the POST method in the <form>tag as shown below:
When the user clicks the “Upload” button, the client browser locates the local file and sends it to the server using HTTP POST. When it reaches your server, your implementing servlet should process the POST data in order to extract the encoded file. Unfortunately, application servers implementing the Servlet and JSP specifications are not required to handle the multipart/form-data encoding. Fortunately there are number of libraries available such
as Apache Commons File Upload, which is a small Java package that lets you obtain the content of the uploaded file from the encoded form data. The API of this package is flexible enough to keep small files in memory while large files are stored on disk in a “temp” directory. You can specify a size threshold to determine when to keep in memory and when to write to disk.

how do you download a file from your web application? - From book java/j2ee interview

Files can be downloaded from a web application by using the right combination of
//set the header to a non-standard value for attachments to be saved by the browser with the
//Save-As dialog so that it is unrecognized by the browsers because often browsers try to do
//something special when they recognize the content-type.
//use Content-Disposition “attachment” to invoke “Save As” dialog and “inline” for displaying
//the file content on the browser without invoking the “Save As” dialog.
response.setHeader(“Content-disposition”, “attachment;filename=” + fileName);

@RequestMapping(value = "get_zip_archive")
public ResponseEntity<byte[]> getZippedLogFilesArchive(@RequestParam("tempFileName") String tempFileName) throws IOException {
    final File zipFile = new File(TEMP_DIR, tempFileName);
    try {
        final HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Disposition", "attachment; filename=" + tempFileName);
        return new ResponseEntity<byte[]>(Files.toByteArray(zipFile), headers, HttpStatus.OK);
    } finally {

--jsp page--
function downloadReport(id) {
 window.location = "downloadReportData?id=" + id;

Friday, 30 September 2011

Interesting part of Java equality

public class JavaEqualty {
    public static void main(String[] args) {
        // java language specification 3.0 $5.1.7 Boxing Conversion
        // If the value p being boxed is true, false, a byte, a char
        // in the range \u0000 to \u007f, or an int or short number
        // between -128 and 127, then let r1 and r2 be the results
        // of any two boxing conversions of p. It is always the
        // case that r1 == r2.
        /* auto-boxing */
        Integer int1 = 2;
        Integer int2 = 2;
        // print 'true'
        System.out.println(int1 == int2);

        Integer int3 = 200;
        Integer int4 = 200;
        // print 'false'
        System.out.println(int3 == int4);
        Integer int5 = new Integer(0);
        Integer int6 = new Integer(0);
        // The two objects are both equal to 0
        System.out.println(int5 == 0 && int6 == 0);
        // But they are not equal to each other
        System.out.println(int5 == int6);
        //print 'true', relational ops unboxing both sides
        System.out.println(int5 <= int6 && int5 >= int6);

        // java language specification 3.0 $15.21.2 Boolean Equality
        // Operators == and !=
        // If the operands of an equality operator are both of type
        // boolean, or if one operand is of type boolean and the
        // other is of type Boolean, then the operation is boolean
        // equality. The boolean equality
        // operators are associative.
        // If one of the operands is of type Boolean it is subjected
        // to unboxing conversion
        Boolean b1 = new Boolean(true);
        boolean b2 = true;
        // print 'true'
        System.out.println(b1 == b2);

        Boolean b3 = new Boolean(true);
        Boolean b4 = new Boolean(true);
        // print 'false', they are not equal to each other
        System.out.println(b3 == b4);