Tuesday, July 9, 2013

SQL Server 2012 Connection using Java Source code written in Jdk 1.4

I  tried many Jdbc drivers but all failed giving errors like "Unsupported Major Minor Version".  Later i found a cool driver which allows connection smoothly using jdk 1.4 source code and it compiles quite well, its also better in comparision to other drivers in terms of performance.

JSQLConnect JDBC_2.0_Driver connects fine using jdk 1.4, 1.5 source code.

If you need help/alternate, comment this post or email me.

Cheers,

Ujjwal Soni

Back-porting jtds driver to jdk 1.4

Recently, i had to connect to MS Sql server 2012 using source code compiled under jdk 1.4, so, i back-ported jtds driver to jdk 1.4, backporting process went fine but when i tried to connect it to MS Sql server 2012 using my java code, it entered into endless non-responsive loop. So, i gave up this back-porting process.

Java Secret: What is called before main.

Overview

The starting point for core java applications is the main(String[]) method. But is there any code which is called before this method and do we even need it?

The class has to be initialised

Before calling main, the static block for the class is called to initialise the class.

public class Main {
    static {
        System.out.println("Called first.");
    }
    public static void main(String... args) {
        System.out.println("Hello world.");
    }
}
prints
Called first.
Hello world.

Can we avoid having a main()

Normally, if you don't have a main() method, you will get an error. However if your program exits before calling main() no error is produced.
public class Main {
    static {
        System.out.println("Hello world.");
        System.exit(0);
    }
}
prints
Hello world.

The premain method

If you have Java agents, those agents can have a premain method which is called first. Instrument package

public static void premain(String agentArgs, Instrumentation inst);
The Instrumentation class gives the agent access to each class' byte code after it is read and before it is linked, giving the agent the option to change byte code.

One interesting feature of the Instrumentation class is the getObjectSize() which will give you the size of an object.

High performance libraries in Java



There is an increasing number of libraries which are described as high performance and have benchmarks to back that claim up. Here is a selection that I am aware of.

Disruptor library

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

LMAX aims to be the fastest trading platform in the world. Clearly, in order to achieve this we needed to do something special to achieve very low-latency and high-throughput with our Java platform. Performance testing showed that using queues to pass data between stages of the system was introducing latency, so we focused on optimising this area.
The Disruptor is the result of our research and testing. We found that cache misses at the CPU-level, and locks requiring kernel arbitration are both extremely costly, so we created a framework which has "mechanical sympathy" for the hardware it's running on, and that's lock-free.
The 6 million TPS benchmark was measured on a 3Ghz dual-socket quad-core Nehalem based Dell server with 32GB RAM.
http://martinfowler.com/articles/lmax.html

Java Chronicle

https://github.com/peter-lawrey/Java-Chronicle
This library is an ultra low latency, high throughput, persisted, messaging and event driven in memory database. The typical latency is as low as 16 nano-seconds and supports throughputs of 5-20 million messages/record updates per second.
It uses almost no heap, trivial GC impact, can be much larger than your physical memory size (only limited by the size of your disk). and can be shared between processes with better than 1/10th latency of using Sockets over loopback.

It can change the way you design your system because it allows you to have independent processes which can be running or not at the same time (as no messages are lost) This is useful for restarting services and testing your services from canned data. e.g. like sub-microsecond durable messaging.
You can attach any number of readers, including tools to see the exact state of the data externally. e.g. You can use; od -t cx1 {file} to see the current state.

Colt Matrix library

http://acs.lbl.gov/software/colt/
Scientific and technical computing, as, for example, carried out at CERN, is characterized by demanding problem sizes and a need for high performance at reasonably small memory footprint. There is a perception by many that the Java language is unsuited for such work. However, recent trends in its evolution suggest that it may soon be a major player in performance sensitive scientific and technical computing. For example, IBM Watson's Ninja project showed that Java can indeed perform BLAS matrix computations up to 90% as fast as optimized Fortran. The Java Grande Forum Numerics Working Group provides a focal point for information on numerical computing in Java. With the performance gap steadily closing, Java has recently found increased adoption in the field. The reasons include ease of use, cross-platform nature, built-in support for multi-threading, network friendly APIs and a healthy pool of available developers. Still, these efforts are to a significant degree hindered by the lack of foundation toolkits broadly available and conveniently accessible in C and Fortran.

The latest stable Colt release breaks the 1.9 Gflop/s barrier on JDK ibm-1.4.1, RedHat 9.0, 2x IntelXeon@2.8 GHz.

Javolution

http://javolution.org/ Javolution real-time goals are simple: To make your application faster and more time predictable! That being accomplished through:
  • High performance and time-deterministic (real-time) util / lang / text / io / xml base classes. 
  • Context programming in order to achieve true separation of concerns (logging, performance, etc). 
  • A testing framework addressing not only unit tests but also performance and regression tests as well. 
  • Straightforward and low-level parallel computing capabilities with ConcurrentContext. Struct and Union base classes for direct interfacing with native applications (e.g. C/C++). 
  • World's fastest and first hard real-time XML marshalling/unmarshalling facility. Simple yet flexible configuration management of your application. 

Trove collections for primitives

http://trove.starlight-systems.com/
The Trove library provides high speed regular and primitive collections for Java.
The GNU Trove library has two objectives:
  • Provide "free" (as in "free speech" and "free beer"), fast, lightweight implementations of the java.util Collections API. These implementations are designed to be pluggable replacements for their JDK equivalents.
  • Provide primitive collections with similar APIs to the above. This gap in the JDK is often addressed by using the "wrapper" classes (java.lang.Integer, java.lang.Float, etc.) with Object-based collections. For most applications, however, collections which store primitives directly will require less space and yield significant performance gains.

MG4J: Managing Gigabytes for Java™

http://mg4j.dsi.unimi.it/
MG4J (Managing Gigabytes for Java) is a free full-text search engine for large document collections written in Java. MG4J is a highly customisable, high-performance, full-fledged search engine providing state-of-the-art features (such as BM25/BM25F scoring) and new research algorithms.

Other links

Overview of 8 performance libraries

http://www.dzone.com/links/r/8_best_open_source_high_performance_java_collecti.html
Sometimes collection classes in JDK may not sufficient. We may require some high performance hashtable, Bigarrays etc. Check out the list of open source high performance collection libraries.

Serialization benchmark

http://code.google.com/p/thrift-protobuf-compare/wiki/Benchmarking
This is a comparison of some serialization libraries.
Its still hard to beat hand coded serialization.

Art of Programming

I have been wondering whether my blog has more to do with art than practical purpose. I say this because I want to blog to simulate ideas rather than be a how to guide on things which most people will possibly never have a need for.
There are only two reasons we create art: for ourselves and for others
-- Brenda Behr
Art has no other purpose than to brush aside... the conventional and accepted generalities, in short everything that veils reality from us, in order to bring us face to face with reality itself.
-- Henri Bergson
Art is the perpetual motion of illusion. The highest purpose of art is to inspire. What else can you do? What else can you do for any one but inspire them?
-- Bob Dylan
Art for art's sake, with no purpose, for any purpose perverts art. But art achieves a purpose which is not its own.
― Benjamin Constant, 1804
My view is that art cannot be created purposely, and it has no direct function. However, it has an important role which is to stimulate creative thinking and stimulate a positive mind set.
Computer science and engineering is often seen as all about creating software with a purpose, so art may be forgotten. Computer science is a adolescent science and I would argue art plays its part in simulating innovation and improving productivity. How are we to find innovation and productivity which can make a dramatic different to performance, user experience or lower development times? I would say this is where art plays an important role.
Every child is an artist. The problem is how to remain an artist once we grow up
-- Pablo Picasso
In computer science, there is so much to learn all the time. There is constant change. Children acquire knowledge very easily compared with adults and I think its important to approach computer science like a child to keep up and to develop new ideas.
How do we do this?
  • Work on interesting things which will stimulate and challenge you for its own sake.
  • Take time out regularly to try new ideas
  • When you come back to your work, keep the momentum and excitement
  • Look for opportunities to improve things and improve them, don't wait to be asked.
    Do it for your own sake (and for the sake of the project)
  • If you have children, look at the way they learn. You could learn something from them.

Life is Art
--Ujjwal


 

UI Controls for Java

go for
  1. Qt Jambi
  2. jgoodies
  3. SwingX
  4. SWT
  5. NetBeans Platform
  6. Eclipse Rich Client Platform
You can also use New Kendo Framework introduced by Telerik.

I think it depends in the IDE you are using. WebLogic has custom controls (http://download.oracle.com/docs/cd/E13196_01/platform/docs81/isv/controls.html) as well as instructions on how to create your own custom controls.

Cheers,

Ujjwal Soni

Friday, July 5, 2013

Building a Tomcat Bundle from Liferay Source

Few steps for creating your own tomcat bundle from Liferay Source.
  • Extract plain  tomcat .
  • Rename apache- tomcat-7.0.23  to tomcat-7.0.23(tomcat-[version]).
  • Download/checkout liferay source from https://lportal.svn.sourceforge.net/svnroot/lportal/portal/.
  • Import this in eclipse
  • Create app.server[userName].properties in portal-trunk(userName-User Name of your PC)
  • Override three properties in above file
  1. app.server.parent.dir =Parent directory path of tomcat
  2. app.server.tomcat.portal.dir=Absolute path of portal-trunk/portal-web/docroot
  3. app.server.tomcat.version=tomcat version
Eg. Suppose your source code in C:/WorkSpace folder & tomcat in C:/deployment folder with name tomcat-7.0.23.
  1. app.server.parent.dir =C:/deployment (don’t consider tomcat-7.0.23 in this path)
  2. app.server.tomcat.portal.dir = C:/WorkSpace/portal-trunk/portal-web/docroot
  3. app.server.tomcat.version =7.0.23
  • Then build ant all.
  • If it will throw out of memory then set VM arguments to -Xms512m or more
Right click of build.xml -> Run As -> 2 Ant Build -> JRE here you will find VM arguments.
  • Copy & replace catalina.properties from liferay bundle/conf  to tomcat/conf
  • Create portal-ext.properties in \tomcat-[version]\webapps\ROOT\WEB-INF\classes
Copy following configurations in portal-ext.properties
  1. jdbc.default.driverClassName=com.mysql.jdbc.Driver
  2. jdbc.default.url=jdbc:mysql://localhost/[ DN_NAME]?useUnicode=true&characterEncoding=UTF-8&useFastDateParsing=false
  3. jdbc.default.username=root
  4. jdbc.default.password=root
change properties as per your database.

Integrate Jersey RESTful with portlet project

Hello All Friends...



Recently I have succssfully integrate Jersey Framework with my existing portlet project.

It is very easy and very useful..



For this, you have to follow following steps..



1) Add following dependency if you are using maven, otherwise add this jars to your classpat.

<!-- Jersey -->



<dependency>
       <groupId>com.sun.jersey</groupId>
       <artifactId>jersey-server</artifactId>
       <version>1.8</version>
</dependency>

<dependency>
       <groupId>com.sun.jersey</groupId>
       <artifactId>jersey-json</artifactId>
       <version>1.8</version>
</dependency>

2) Edit in web.xml

<servlet>
         <servlet-name>jersey-serlvet</servlet-name>
         <servlet-class>com.sun.jersey.config.property.packages</servlet-class>
         <init-param>
                   <param-name>com.sun.jersey.config.property.packages</param-name>
                  <!-- Here, you have to mention package name where toy are implementd service(web service)-->
                   <param-value>com.hrms.admin.jersey.service</param-value>
         </init-param>
         <init-param>
         <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
                   <param-value>true</param-value>
         </init-param>
         <load-on-startup>1</load-on-startup>
  </servlet>

<servlet-mapping>
            <servlet-name>jersey-serlvet</servlet-name>
            <url-pattern>/rest/*</url-pattern>
</servlet-mapping>


3) Look out Web service class.
Example..

@Path("/mymessage")
public class MyWebServiceClass
{
      @GET
      @Path("hello")
      @Produces(MediaType.APPLICATION_JSON)
      public Message myMethod()
     {
             MyMessage msg = new MyMessage();
             msg.setName("Good Day!!!");
             msg.setTitle("Welcome");

            return msg;
     }
}

-> here, we can define @Path at two level. 1) class level 2) path level.
-> so Here, i provide both ultimately url become... <...>/mymessage/hello
-> @Produces(MediaType.APPLICATION_JSON) defines that this method returns data in JSON format.

This is web service class where we implelent service.


4) Now we have to create client which call this service.

<dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-client</artifactId>
        <version>1.8</version>
</dependency>

I am using GSON. So..

<!-- GSON -->
<dependency>
       <groupId>com.google.code.gson</groupId>
       <artifactId>gson</artifactId>
       <version>1.7.1</version>
</dependency>

5) Client program

public class MyClient {

      Logger log = Logger.getLogger(MyClient.class);

      public String createClient(String url) {
      try {
                    Client client = Client.create();
                    String baseURL = "http://localhost:8080/admin-0.0.1/rest";
                    WebResource webResource = client.resource(baseURL + url);
                    ClientResponse clientResponse = webResource.accept("application/json").get(ClientResponse.class);

                    if (clientResponse.getStatus() != 200) {
                                       throw new RuntimeException("Failed...... HTTP Error Code :"
                                                        + clientResponse.getStatus());
                                          }
                            }

                   String output = clientResponse.getEntity(String.class);

                    System.out.println("Output from Server :");

                    System.out.println(output);

                    return output;
                   } catch (Exception e) {
                         e.getMessage();
                       return "ERROR";
              }
       }
}

--> Here... http://localhost:8080/admin-0.0.1/rest define as a Base URL. and at the time of calling any service we have to pass remaining parameter in it.

like..

       MyClient client = new MyClient();
      String result = client.createClient("/mymessage/hello");


So... It will return MyMessage object in JSON format.


Thanksssssssssssssssssssss

Static Navigation for Liferay Portal

create a ServicePreAction, which will create a new
custom NavItem object and a change in navigation.vm of the theme, which
will show the custom navigation.

Here are the steps to create the custom navigation

1) Create a new ServicePreAction hook
2) In the run() method of ServicePreAction, retrieve the your community
group object

ThemeDisplay themeDisplay = (ThemeDisplay)
req.getAttribute(WebKeys.THEME_DISPLAY);
Group baseCommunity = GroupLocalServiceUtil.getGroup(themeDisplay.getCompanyId(), "yourcommunitName");
long defaultLayoutId = LayoutLocalServiceUtil.getDefaultPlid(baseCommunity.getGroupId());
Layout defaultLayout = LayoutLocalServiceUtil.getLayout(defaultLayoutId);
List layoutSet = LayoutLocalServiceUtil.getLayouts(baseCommunity.getGroupId(), false);
List publicNonHiddenLayouts = newArrayList(layoutSet.size());
for(Layout layout:layoutSet) {
    if(!layout.isHidden() && layout.getParentLayoutId()==0)
    {
         publicNonHiddenLayouts.add(layout);
    }
}
RequestVars requestVars = new RequestVars(req,themeDisplay,
defaultLayout.getAncestorPlid(), defaultLayout.getAncestorLayoutId());
List navItems = NavItem.fromLayouts(requestVars,publicNonHiddenLayouts);
Map vmVariables = new HashMap();
vmVariables.put("baseNavItems", navItems);
req.setAttribute(WebKeys.VM_VARIABLES, vmVariables);
---------------------------------------------------------------------------------------
Now, in the navigation.vm of the Theme,
replace  #foreach ($nav_item in $nav_items)  with  #foreach ($nav_item in $baseNavItems)

Unique Way to Save Portlet Preferences in Liferay 6.1

With Liferay 6.1 if you are using configuration mode and if you want to store form elements values in preferences then this post will definitely help you.

You can store form elements value in preferences with less efforts (as compare to version below Liferay 6.1).
You just need to follow few syntax to achieve this functionality. Lets go step by step.
Define your AUI element with below syntax
It should follow pattern like preferences--paramName-- .
And make sure you use below Configuration class in your liferay-portlet.xml
com.liferay.portal.kernel.portlet.DefaultConfigurationAction
By using this way we dont need to write any code to store form element value into preferences . DefaultConfigurationAction class will detect form element with specified syntax and store the same in preference for you.

In case if you want to retrieve value from preference then directly use.

preferences.getValue("showFeedTitle", StringPool.BLANK);
 
 

How to enable Tomcat Manager in an Alfresco installation

In order to address some maintenance tasks in Tomcat, may be useful to get access to the Tomcat Manager (http) interface, things like stop or start an application if you are doing some changes in Alfresco or Share, even a different way to access to its JMX interface using jmxproxy if you are working remotely.
This is a easy step by step guide about how you can enable the Tomcat Manager that comes with an Alfresco default (bundle) installation. Tested with Alfresco Enterprise 4.1.4, but should work with any other Alfresco 4 version.

  • Edit tomcat/conf/tomcat-users.xml and adapt it like below:

<tomcat-users>

<role rolename="manager-gui"/>

<role rolename="manager-status"/>

<role rolename="manager-jmx"/>

<role rolename="manager-script"/>

<user username="CN=Alfresco Repository Client, OU=Unknown, O=Alfresco Software Ltd., L=Maidenhead, ST=UK, C=GB" roles="repoclient" password="null"/>

<user username="CN=Alfresco Repository, OU=Unknown, O=Alfresco Software Ltd., L=Maidenhead, ST=UK, C=GB" roles="repository" password="null"/>

<user username="manager" roles="manager,manager-gui,manager-status" password="manager"/>

<user username="manager2" roles="manager-jmx,manager-script" password="manager"/>

</tomcat-users>


  • Then edit tomcat/conf/Catalina/localhost/manager.xml and change like this:
<Context antiResourceLocking="false" privileged="true" useHttpOnly="true" override="true">

<Valve className="org.apache.catalina.authenticator.BasicAuthenticator" securePagesWithPragma="false" />

</Context>

  • Restart your Tomcat and thats all.
Once Alfresco is up agan, lets try to access to the manager with user “manager” and password “manager”, please avoid using this credentials in production environments.
To access html interface:
http://localhost:8080/manager/html



To list all applications:
http://localhost:8080/manager/list
To list server information:
http://localhost:8080/manager/serverinfo
To see default session info (use / or /context):
http://localhost:8080/manager/sessions?path=/
To start, stop, and undeploy alfresco or share
http://localhost:8080/manager/start?path=/alfresco
http://localhost:8080/manager/stop?path=/alfresco
http://localhost:8080/manager/undeploy?path=/alfresco
http://localhost:8080/manager/start?path=/share
http://localhost:8080/manager/stop?path=/share
http://localhost:8080/manager/undeploy?path=/share
To see all MBeans (jmxproxy):
http://localhost:8080/manager/jmxproxy.



Cheers,

Ujjwal Soni

    Tuesday, July 2, 2013

    JSelect: switch between different JDK versions

    Do you often switch between different JDK version? Do you build JavaFX projects with early preview builds? Then JSelect is for you!
    On many platforms it’s a bad habbit to install every JDK (even preview builds) at a global place such as C:\Program Files. Users add global JAVA_HOME environment variables to the system. On windows it is quite common to use the system preferences to change the PATH variable andJAVA_HOME to match the Java version that shall be used. The UI for adding or changing environment variables on Windows is horrible!
    If you often switch between different versions then this is very time consuming. What if you’d like to use different JDK versions at once? What if the JDK you’d like to use is not installed to a global place such as C:\Program Files?
    To solve the issues I had with Java and environment variables, I wrote a small tool that allows to easily switch between different JDK versions. After choosing the JDK it opens a command-line window (cmd.exe on Windows and xterm on Linux/OS X). Just specify a JDK and click Open CMDto open a command-line window that uses local JAVA_HOME and PATH variables that match the selected JDK. JSelect can also save/load configurations.
    This is how it looks like (JDK 6 and JDK 8 in different cmd windows):

    That’s great if you want to trigger Gradle builds from the command-line.
    Download JSelect-0.3. You can also find it on GitHub


    Arrow symbols in Java

    Unicode is a major feature which Java supports perfectly. This means you can use ANY unicode symbols in your code. Arrow symbols are quite useful. Here is so-called “The Unicode Arrows Block” with characters codes. To use arrow symbols in a Java application just write something like this:
    String msg = "Press \u2191 button to go up";
    or, if your favorite editor supports unicode, copy and paste any symbol from here
    String msg = "Press ↑ button to go up";
    
    
     0123456789ABCDEF
    \u219x
    \u21Ax
    \u21Bx
    \u21Cx
    \u21Dx
    \u21Ex
    \u21Fx

    Monday, July 1, 2013

    Protect your java codes from decompilers

    Protect your java codes from decompilers.
    This method cannot save the java codes from getting decompiled but yes the cracker will find it really difficult to understand much part of your codes after decompilation.
    Proguard :
    This is an opensource software which makes programs and libraries harder to reverse-engineer.The best thing is it comes up with a GUI which makes it easy to work with.
    You can download the Proguard from http://sourceforge.net/projects/proguard/files/
    Extract the zip after download.
    Open it and goto bin folder and then double click on proguardgui.bat
    A GUI will open up. Goto tab Input/Output
    Click on Add Input and select the input jar file to protect.
    Click on Add Output to create a new protected version of the input file. Later you will use this copy for distribution
    If you have any jars on which your main jar is dependent then add them up in Library jar section by clicking on Add button
    Finally click on Process button on left side. If you want then you may tweak on remaining buttons according to your requirements
    Now click on Process! and your output protected file will be created which is really hard to crack fully.
    Just give it a try...
    Cheers,

    Ujjwal Soni

    Control your mouse with Java

    Perform all mouse operation with help of java program
    You may control your mouse using this simple program.
    import java.awt.Robot; 
    import java.awt.event.InputEvent; 

    /* 
     * To change this template, choose Tools | Templates 
     * and open the template in the editor. 
     */ 
    /** 
     * 
     * @author Anurag 
     */ 
    public class ControlMouse { 

        public static void main(String args[]) { 
            ControlMouse.control_mouse(); 
        } 

        public static void control_mouse() { 
            try { 
                Robot robot = new Robot(); 
                 
                //Move mouse to cordinates x,y 
                robot.mouseMove(300, 550); 
                 
                // Perform mouse LEFT CLICK 
                robot.mousePress(InputEvent.BUTTON1_MASK); 
                robot.mouseRelease(InputEvent.BUTTON1_MASK); 
                 
                // Perform mouse RIGHT CLICK 
                robot.mousePress(InputEvent.BUTTON3_MASK); 
                robot.mouseRelease(InputEvent.BUTTON3_MASK); 
                 

                // SCROLL THE MOUSE WHEEL 
                robot.mouseWheel(-150); 
                 
            } catch (Exception e) { 
                e.printStackTrace(); 
            } 
        } 

    Explaination :
    First we make an object of Robot class.
    To move the mouse to particular position like x,y use robot.mouseMove(x,y)
    To perform left click just perform mouse press and then release operation. For this we use mousePress and mouseRelease methods.BUTTON1_MASK resembles the left button
    To perform right click just perform mouse press and then release operation. For this we use mousePress and mouseRelease methods.BUTTON3_MASK resembles the right button
    To move mouse wheel use robot.mouseWheel(-150). Here -ve value give upward mouse wheel movement and +ve show downward.
    Hope you liked it.. :) 
    Cheers,

    Ujjwal Soni