Why Load Balance not work in Hessian C# client calling to hessian service?

November 9, 2011 by · Comments Off on Why Load Balance not work in Hessian C# client calling to hessian service?
Filed under: design, java, troubleshooting 

When I was migrating our application from C# to Java, our Java service moved ahead of  the client application. The client application is in C#. And we export service through Hessian service. So we call java hessian service through C# hessian client.

But we met a big problem on load balance after the new application deployed. The load is never balanced on the C# hessian client’s request. The service is invoked through F5.

After digging into the code of C# hessian, I found the cause: C# Hessian Client uses HttpWebRequest with default properties to call java hessian service, while the default HttpWebRequest’s KeepAlive property is true. That means after the C# client connected to a load balance server, it will keep on calling the same back-end service and the request from this client will not routed to other back-end service.

So the solution is to change the default KeepAlive property in file CHessianMethodCaller.cs

HttpWebRequest req = webRequest as HttpWebRequest;

req.KeepAlive = false;  // newly added line to assure load balance work

 

Digg This
Reddit This
Stumble Now!
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

Json and flexjson on exchanging abstract object data

August 7, 2011 by · 1 Comment
Filed under: java 

JSON is a lightweight text-based open standard designed for human-readable data interchange.  It is widely used in java applications as a replacement of XML. Many times we need to convert java object to json text and vice versa.

You can use Gson to convert java object to JSON format, and convert JSON into java object. And you can export your interface by JSON RPC using jsonrpc4j or json-rpc.

public class Employee
{
    private String name;
    private int salary;
    private String dateOfBirth;

    public static void main(String[] args)
    {
        Employee emp = new Employee();
        emp.setName("david");
        emp.setDateOfBirth("20080801");

        Gson gson = new Gson();
        String jsonString = gson.toJson(emp, Employee.class);
        System.out.println(jsonString);
    }
}

The output would be:

{“name”:”david”,”salary”:0,”dateOfBirth”:”20080801″}

Now you can deserialize the jsonString to an Employee object.

   Employee employee = gson.fromJson(jsonString, Employee.class);
   System.out.println(employee.getName());

The problem with Gson is that it loses the type information on serialization, and you need to provide type information explicitly on deserialization like the above example.

How to serialize and deserialize with automatic type recognization?

Flex Json is the answer. FlexJson would add a “class” attribute in the serialized json string to represent the full qualified class name. Thus you can exchange interface/abstract object by json format. Here’s an example.

        JSONSerializer serializer = new JSONSerializer();
        String empString = serializer.serialize(emp);
        System.out.println(empString);

        JSONDeserializer<Object> deserializer = new JSONDeserializer<Object>();

        Employee eee = (Employee) deserializer.deserialize(empString);
        //System.out.println(eee);

The output would be like this:

{“class“:”com.beyondlinux.demo.bean.Employee”,”dateOfBirth”:”20080801″,”name”:”david”,”salary”:0}

Reference List:

http://en.wikipedia.org/wiki/JSON-RPC

http://code.google.com/p/jsonrpc4j/

http://code.google.com/p/json-rpc/

http://flexjson.sourceforge.net/

Digg This
Reddit This
Stumble Now!
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

3 steps to dynamically compile, instantiate and run a Java class

July 20, 2011 by · 2 Comments
Filed under: java 

The background:  sometimes we need to compile dynamic source code, and run the code.  Some common situation includes on a program contest evaluation system, on a dynamic business logic control,  on evaluation of dynamic math expression, or even on evaluation of dynamic expression on test case.

Here’s 3 steps to implement compilation, instantiation and running of dynamic java source code.  It is the hard way,  the most original and elastic way; cause you can add any logic in the generation of your dynamic source code.

1. Construct an in-memory java source file from your dynamic code.

You need to override SimpleJavaFileObject, and take a string content as and In memory java source file.

2.Compile your files by JavaCompiler

You need to compile by JavaCompiler which could be got by ToolProvider.getSystemJavaCompiler(). Then get a task of JavaCompiler.CompilationTask. And call the task to execute compilation.

3.Load your class by URLClassLoader

Load your class by URLClassLoader from classes output folder, then instantiate a instance from the class, and finally call method of the class from the instance by reflection.

Here’s a complete working code (tested on JDK 1.6):

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;
import java.util.Locale;

import javax.tools.Diagnostic;
import javax.tools.DiagnosticListener;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;

/**
 * Dynamic java class compiler and executer  <br>
 * Demonstrate how to compile dynamic java source code, <br>
 * instantiate instance of the class, and finally call method of the class <br>
 *
 * http://www.beyondlinux.com
 *
 * @author david 2011/07
 *
 */
public class DynamicCompiler
{
    /** where shall the compiled class be saved to (should exist already) */
    private static String classOutputFolder = "/classes/demo";

    public static class MyDiagnosticListener implements DiagnosticListener<JavaFileObject>
    {
        public void report(Diagnostic<? extends JavaFileObject> diagnostic)
        {

            System.out.println("Line Number->" + diagnostic.getLineNumber());
            System.out.println("code->" + diagnostic.getCode());
            System.out.println("Message->"
                               + diagnostic.getMessage(Locale.ENGLISH));
            System.out.println("Source->" + diagnostic.getSource());
            System.out.println(" ");
        }
    }

    /** java File Object represents an in-memory java source file <br>
     * so there is no need to put the source file on hard disk  **/
    public static class InMemoryJavaFileObject extends SimpleJavaFileObject
    {
        private String contents = null;

        public InMemoryJavaFileObject(String className, String contents) throws Exception
        {
            super(URI.create("string:///" + className.replace('.', '/')
                             + Kind.SOURCE.extension), Kind.SOURCE);
            this.contents = contents;
        }

        public CharSequence getCharContent(boolean ignoreEncodingErrors)
                throws IOException
        {
            return contents;
        }
    }

    /** Get a simple Java File Object ,<br>
     * It is just for demo, content of the source code is dynamic in real use case */
    private static JavaFileObject getJavaFileObject()
    {
        StringBuilder contents = new StringBuilder(
                                                   "package math;"+
                                                            "public class Calculator { "
                                                           + "  public void testAdd() { "
                                                           + "    System.out.println(200+300); "
                                                           + "  } "
                                                           + "  public static void main(String[] args) { "
                                                           + "    Calculator cal = new Calculator(); "
                                                           + "    cal.testAdd(); "
                                                           + "  } " + "} ");
        JavaFileObject so = null;
        try
        {
            so = new InMemoryJavaFileObject("math.Calculator", contents.toString());
        }
        catch (Exception exception)
        {
            exception.printStackTrace();
        }
        return so;
    }

    /** compile your files by JavaCompiler */
    public static void compile(Iterable<? extends JavaFileObject> files)
    {
        //get system compiler:
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

        // for compilation diagnostic message processing on compilation WARNING/ERROR
        MyDiagnosticListener c = new MyDiagnosticListener();
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(c,
                                                                              Locale.ENGLISH,
                                                                              null);
        //specify classes output folder
        Iterable options = Arrays.asList("-d", classOutputFolder);
        JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager,
                                                             c, options, null,
                                                             files);
        Boolean result = task.call();
        if (result == true)
        {
            System.out.println("Succeeded");
        }
    }

    /** run class from the compiled byte code file by URLClassloader */
    public static void runIt()
    {
        // Create a File object on the root of the directory
        // containing the class file
        File file = new File(classOutputFolder);

        try
        {
            // Convert File to a URL
            URL url = file.toURL(); // file:/classes/demo
            URL[] urls = new URL[] { url };

            // Create a new class loader with the directory
            ClassLoader loader = new URLClassLoader(urls);

            // Load in the class; Class.childclass should be located in
            // the directory file:/class/demo/
            Class thisClass = loader.loadClass("math.Calculator");

            Class params[] = {};
            Object paramsObj[] = {};
            Object instance = thisClass.newInstance();
            Method thisMethod = thisClass.getDeclaredMethod("testAdd", params);

            // run the testAdd() method on the instance:
            thisMethod.invoke(instance, paramsObj);
        }
        catch (MalformedURLException e)
        {
        }
        catch (ClassNotFoundException e)
        {
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception
    {
        //1.Construct an in-memory java source file from your dynamic code
        JavaFileObject file = getJavaFileObject();
        Iterable<? extends JavaFileObject> files = Arrays.asList(file);

        //2.Compile your files by JavaCompiler
        compile(files);

        //3.Load your class by URLClassLoader, then instantiate the instance, and call method by reflection
        runIt();
      }
}
Digg This
Reddit This
Stumble Now!
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

Speed up your eclipse as a super fast IDE

June 25, 2011 by · 57 Comments
Filed under: java 

Follow these steps to speed up your eclipse as a super fast IDE , it works for 32 & 64 bit version eclipse/jdk on my windows 7 x64.

1.Disable antivirus software, or add your jdk & eclipse & workspace & other related folder to white list in your antivirus software.

2.Disable unecessary validations and startup action in eclipse reference.

For validations: on eclipse menu Windows -> Preferences -> Validation, click “Disable All”, and then select the validator which you need. I selected “Classpath Dependency Validator” only.

For startup action: on eclipse menu Windows -> Preferences, type “startup”, select “Startup and Shutdown”, untick the options you don’t need. (Thanks for David’s suggest,  I’ve added the above 2 detail steps for readers)

3.Modify eclipse.ini to set the Xmn(new generation size), Xms and Xmx, enable parallel GC
-vm
C:/jdk1.6.0_25/bin
-startup
plugins/org.eclipse.equinox.launcher_1.2.0.v20110502.jar
–launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.100.v20110502
-product
org.eclipse.epp.package.jee.product
–launcher.defaultAction
openFile
–launcher.XXMaxPermSize
256M
-showsplash
org.eclipse.platform
–launcher.XXMaxPermSize
256m
–launcher.defaultAction
openFile
-vmargs
-server
-Dosgi.requiredJavaVersion=1.5
-Xmn128m
-Xms1024m
-Xmx1024m
-Xss2m
-XX:PermSize=128m
-XX:MaxPermSize=128m
-XX:+UseParallelGC

4.Create a ram disk(virtual disk) on memory, and put your jdk on the ram disk.
You can use imdisk to create ram disk. Firstly download it from: http://www.ltr-data.se/opencode.html/#ImDisk,  and install it.

Then set the ImDisk driver to auto-load at Command Prompt with administrative privileges (for example right-click, start as Administrator), type:

sc config imdisk start= auto
net start imdisk

create a 200m ram disk as driver n by:
imdisk -a -t vm -s 300m -m n:

then you should format the ram disk manually.

later ,if you would like to remove the ram disk, just run the command:
imdisk -D -m n:

5.Make sure you are using sun jdk, not open jdk/gcj nor other jdk on linux.
If you are not satified with the after the above steps, install jrockit instead of sun jdk, and change some of the vm options by jrocket specification,
jrockit is faster than sun jdk.

Some note:

On my laptop(Aspire 4745G 4G mem ), windows 7 x64, by default, it takes more than 30 seconds to start eclipse.  After the vm options tuned,  takes only 15 seconds.

And after jdk moved to ram disk, it takes 10 seconds to startup.

Digg This
Reddit This
Stumble Now!
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)