Saturday, July 12, 2014

Setup virtualbox on Ubuntu Server 64 Bit

Setup virtual box on ubuntu server 64bit and use phpvirtualbox to access webui of VirtualBox to manage the instances on virtualbox.

Ubuntu Server 64bit 
VirtualBox 4.3.*
phpvirtualbox 

Running VirtualBox and phpvirtualbox on the same machine.

I mostly followed followed this blog http://santi-bassett.blogspot.in/2013/01/installing-virtualbox-on-ubuntu-server.html. 

Except few changes. When I installed virtual box it installed latest version 4.3.* and location of phpvirtualbox has been changed to sourceforge.net http://sourceforge.net/projects/phpvirtualbox/files/ and used phpvirtualbox 4.3.1 version.

However even after following all the steps right I got following error


I click on details and get the following:

Exception Object
(
    [message:protected] => Could not connect to host (http://127.0.0.1:18083/

I started vboxwebsrv server in foreground and tried to telnet 18083, everything was fine. Then I tried to do wget with url http://127.0.0.1:18083 and responded connection refused. Then I tried to wget with url http://localhost:18083 and it responded with 403 error. So url was the problem. Update config.php with http://localhost:18083 in place of http://127.0.0.1:18083. That solved my problem.




Tuesday, May 20, 2014

GWT browser specific css

Yea it is possible to write browser specific css with GWT application which uses CSS through CssResource.
    @if user.agent gecko1_8 {
    	.startup p {
    		color: #000000;
    		text-shadow: 0 0 3px #000000;
    	}
    } @else {
    	.startup p {
    		color: #000000;
    	}
    } 
 
Note: You can use this logical if else and many more other expression inside css which are used inside GWT code. Only through CssResource interface. If you are directly using the respective css inside html main source file then this will not work.




For more details refer






GWT Jquery integration

It is very easy to have GWT Jquery integration using gwtquery. Follow below steps

Add maven dependency for gwtquery, at the time of writing this article it was 1.4.2 and tested it with GWT 2.5.0 version. 
        <dependency>
            <groupId>com.googlecode.gwtquery</groupId>
            <artifactId>gwtquery</artifactId>
            <version>1.4.2</version>
            <scope>provided</scope>
        </dependency>

Then inherit your module from required gwtquery module.
<inherits name='com.google.gwt.query.Query'/>

User jquery api wrappers as follows.
import static com.google.gwt.query.client.GQuery.$;
..
...
public class GwtJquery implements EntryPoint {

	@Override
	public void onModuleLoad() {
		$("#startup").fadeIn(1000);
		$("#product").delay(2000).fadeIn(1000);
	}
...
...
}

For More details refer getting started







Tuesday, April 29, 2014

Eclipse getting crashed randomly on ubuntu

If your eclipse is getting crashed randomly and that too frequently look at the crash reported. This crash report will be placed in the directory from where you start the eclipse and search for " /usr/lib/x86_64-linux-gnu/gtk-2.0/modules/liboverlay-scrollbar.so". If find this string then this issues of overlay scrollbar library. This will be solved once you remove that library. Sometimes, you will not find crash report generated, even in that case it is most probably the issue of overlay scrollbar.

sudo apt-get remove overlay-scrollbar

for more details refer this bug . If you don't find above mentioned string, search google with few strings from that crash report.

Redirect process output to std output when you fork one process from another process.

In the situation where you want to redirect input / output of one process to the std input output of parent process (from which you are starting first process). You can make use of inheritIO() method of a ProcessBuilder.
ProcessBuilder pb = new ProcessBuilder("command", "argument);
pb.directory(new File(<directory from where you want to run the command>));
pb.inheritIO();
Process p = pb.start();
p.waitFor();

It may not be necessary to call waitFor() method in above code. This will just help to wait current process to wait for this child process to get complete.

There exist few other options as well, through which you can redirect required stream to standard output and input.


pb.redirectInput(Redirect.INHERIT);
pb.redirectOutput(Redirect.INHERIT);
pb.redirectError(Redirect.INHERIT);











Sunday, April 27, 2014

Quartz Scheduler with Google Guice

To integrate Quartz with Guice. One can follow below steps. The most important part is, we should be able to inject dependencies inside Job.

To provide injectable Scheduler Instance we need to write Scheduler provider as follows:
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.StdSchedulerFactory;

import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;

/**
 * @author Pandurang Patil 27-Apr-2014
 * 
 */
@Singleton
public class SchedulerProvider implements Provider<Scheduler> {
 private Scheduler scheduler;

 @Inject
 public SchedulerProvider(SchedulerJobFactory jobFactory) throws SchedulerException {
  scheduler = new StdSchedulerFactory().getScheduler();
  scheduler.setJobFactory(jobFactory);
 }

 @Override
 public Scheduler get() {
  return scheduler;
 }

}


Now that we have defined provider for Scheduler we need to map the same inside Guice Module

import org.quartz.Scheduler;

import com.google.inject.AbstractModule;

/**
 * @author Pandurang Patil 27-Apr-2014
 *
 */
public class SchedulerModule extends AbstractModule {

 @Override
 protected void configure() {
  bind(Scheduler.class).toProvider(SchedulerProvider.class);
 }

}


With the above code, we should be able to inject Scheduler instance where we want. Lets look at how we would be able to get dependencies injected inside Job. As instantiation of the Job object is done by Scheduler itself, we just pass on the class name through JobDetails. We need intercept this instantiation process to do that we will write our own Job Factory as follows:

import org.quartz.Job;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.spi.JobFactory;
import org.quartz.spi.TriggerFiredBundle;

import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Singleton;

/**
 * @author Pandurang Patil 27-Apr-2014
 * 
 */
@Singleton
public class SchedulerJobFactory implements JobFactory {

 @Inject
 private Injector injector;

 @Override
 public Job newJob(TriggerFiredBundle bundle, Scheduler scheduler) throws SchedulerException {
  return (Job) injector.getInstance(bundle.getJobDetail()
    .getJobClass());
 }

}

We need ask scheduler to use this JobFactory while instantiating Job object. We have already connected scheduler with JobFactory inside SchedulerProvider, look at line number 20 for SchedulerProvider code above
As we are returning same instance from Providers get method. Where ever you will inject Schedular, you will get the same object. Schedule your jobs the way it is done normally there is no change in it. 


import org.quartz.Scheduler;
import org.quartz.SchedulerException;

import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;

/**
 * @author Pandurang Patil 27-Apr-2014
 * 
 */
public class SchedulerSample {

 @Inject
 private Scheduler scheduler;

 void start() throws SchedulerException {

  scheduler.start();
 }

 public static void main(String[] args) {
  Injector injector = Guice.createInjector(new SchedulerModule());
  SchedulerSample sample = injector.getInstance(SchedulerSample.class);
  try {
   sample.start();
  } catch (SchedulerException e) {
   System.out.println("Error while starting the scheduler...");
  }
  ...
  ...
 }
}


Friday, April 25, 2014

Java: Retreive ByteArray from Direct ByteBuffer and convert it to String

I assume you understand what is Direct ByteBuffer. I was trying to retrieve byte[] from Direct ByteBuffer 


ByteBuffer buffer = ByteBuffer.allocateDirect(10000);
.....
.....
buffer.flip();
byte[] data = buffer.array();

and I was getting this error 


Exception in thread "main" java.lang.UnsupportedOperationException
 at java.nio.ByteBuffer.array(ByteBuffer.java:959)

I was able to solve this as follows 


ByteBuffer buffer = ByteBuffer.allocateDirect(10000);
.....
.....
buffer.flip();
byte[] data = new byte[buffer.remaining()];
buffer.get(data);
// Here you hava data populated inside data[] array
String token = new String(data);


Thursday, April 17, 2014

ZeroMQ ipc not working

If you are using Zero MQ IPC endpoint url like "ipc://someendpoint". Then communication between two threads of same process will work perfectly fine. But it will fail if you are trying to communicate across the processes. If you look at ZeroMQ document properly end point should correspond to path. Thats where above end point url works fine for intra process communication as this file "someendpoint" will correspond to file in current directory from where you are running this app. Both the threads will connect to same file. But in case of communication between two process, if you are running these application from different locations then "someendpoint" will correspond to two different paths.

So perfect endpoint for inter process communication is to have fully qualified file path e.g. (considering "tmp" folder is present inside root folder) "/tmp/someendpoint" complete url will be "ipc:///tmp/someendpoint". 

Wednesday, April 16, 2014

Java: Add shutdown hook invoked even with CTRL + C

Add Shutdown hook with JVM, which will be invoked even when application is killed by pressing CTRL + C

Create a separate class which extends java.lang.Thread class or implements java.lang.Runnable interface


public class AppShutDownHook extends Thread {
 @Override

 public void run() {
              // TODO: Complete your shutdown activity here.
 }
}


Register this thread with Java Runtime in your code where your application is getting initialised. Most probably inside main.


 public static void main(String[] args) {
  AppShutDownHook shutDownHook = new AppShutDownHook();
  Runtime.getRuntime().addShutdownHook(shutDownHook);
                .
                . 
                .
                . 
        }


Sunday, April 13, 2014

.profile is ignored when terminal is started in MAC-OSX

One fine day suddenly all environment variables that I have set inside .profile file of my machine stopped getting declared when machine is restarted. 

It turns out that if you have .bash_profile or .bash_login file then .profile file will be ignored by bash. 

So you need to make use of either .profile or .bash_profile not both of them, if you are using bash.

bind MySql to multiple ipaddress

If you are looking to bind MySql Service with multiple ip address on given machine. Then you cannot do it selectively. When I say selectively, if there are 5 network cards (IP Addresses) to given machine and you want to allow connections to be made only from 3 network cards (IP Addresses). Then you cannot configure MySql service to bind selective IP addresses. What you can do is either you can bind it with single ip address or all the IP addresses available on the machine. So here if you want to selectively allow connections you have to make use of firewall to restrict the connections. For more details refer 

To bind MySql service to all ip addresses change "bind-address" value to "0.0.0.0" and comment "#skip-networking". If you don't find it then don't worry don't have to do any thing, just set "bind-address" property to "0.0.0.0".

Mysql 5.5 is not accessible remotely.

I recently installed MySql 5.5 and tried to access it from remote machine. But it was not accessible. I had added remote user for the remote machine from which I was trying to access the DB. But it was failing to connect, I even tried to connect it through telnet. Then I found that by default mysql is only bound to serve localhost requests only. If you need to access it remotely you need to make changes in my.cnf file to bind mysql service to actual network ip address through which you will access it remotely.

Follow below steps to make those changes

1. First locate your my.cnf file. For me it was located at "/etc/mysql/my.cnf" on ubuntu server machine.
2. look for the [mysqld] section, and in there look for the bind-address keyword. This usually is set to 127.0.0.1 -- change that to match your "normal" IP-address.
3. Save file, close it and restart mysql service 

Now when try with telnet, you should be able to connect to the service. If you still facing this issue then probably you need to also check if you are running any firewall, which is blocking this connection. In that case you need to allow user to connect to mysql port through firewall.

Note: You need to add remote user to access mysql from remote machine.

Saturday, April 12, 2014

MySql Datafiles are getting corrupted on Mac-OSX abrupt shutdown

I have consistently faced this issue of MySql data files getting corrupted when my machine is rebooted abruptly. This has resulted into repetitive work that I have to do to rebuild the data. I tried to google for the solution and see if somebody else has seen this issue. But it seems this the way it will work, as MySql data files are not closed properly which results into corrupt database in case your machine gets abruptly restarted. I got this reference on stackexchange   

To recover corrupted data some times following commands worked well but not always. 

$ sudo mysqladmin refresh
$ sudo mysqladmin flush-tables 
Finally restart your myql server.

So to over come this issue, I stop my MySql service when I am not using it. This is not the perfect solution, as there is a still possibility your machine gets hanged or restarted abruptly while you are working with MySql. But at least it will lower down the possibility of corruption when you are not using it.    

Location of MySQL data files on MAC - OSX

Default location of MySql data files on MAC - OSX is 

/usr/local/mysql/data/


Friday, April 11, 2014

Open link in new Tab / Window (Html Anchor tag)

To Open respective page pointed by hyperlink in new tab or window one need to make use of target attribute for more details refer. As per below description following configuration will help you to control where a respective link will be displayed.


ValueDescription
_blankOpens the linked document in a new window or tab
_selfOpens the linked document in the same frame as it was clicked (this is default)
_parentOpens the linked document in the parent frame
_topOpens the linked document in the full body of the window
framenameOpens the linked document in a named frame


Sometimes you have to open a link inside new tab e.g. deep linked help pages on different pages of your application. But while doing that you don't want to annoy user by opening each link inside new tab. Instead you can open the link in new tab for very first time link, further links will be opened / displayed into same new tab created when user clicked on very first link. To achieve this you need to specify target as some unique string other than above mentioned values which starts with "_". 

<a target="help-tab" href="http://pandurangpatil.com/sample/help/firstchapter.html">First Help</a>


<a target="help-tab" href="http://pandurangpatil.com/sample/help/secchapter.html">Second Help</a>




Saturday, March 29, 2014

Run eclipse on remote ubuntu 13.10 server using x11

To run eclipse from on remote ubuntu 13.10 server using x11 on local machine. 

Requirement.
I am assuming Jdk and eclipse is already installed. 

In addition to that you need to install few libraries on remote server. Run following command to install those libraries on remote server.


  $ sudo apt-get install libgtk2.0-0:i386 libxxf86vm1:i386 libsm6:i386 lib32stdc++6 libxtst6

Once above libraries are install open another terminal and connect remote server through ssh with -X option


#From local machine
$ ssh <username>@<remote machine ip> -X

Now you can start the eclipse from this ssh session


#From local machine
$ cd <to location where eclipse is installed>
$ ./eclipse


Friday, March 28, 2014

UBUNTU 13.4 LD_LIBRARY_PATH is not set from /etc/environment

For some reason LD_LIBRARY_PATH value is not getting set through /etc/environment. All other variables are getting initialized properly when it is been set through /etc/environment. After searching for the solution I came to know after UBUNTU 9.04 release you are not able to set LD_LIBRARY_PATH from "$HOME/.profile, /etc/profile, nor /etc/environment" refer documentation https://help.ubuntu.com/community/EnvironmentVariables#List_of_common_environment_variables

Run following command and restart the machine to workaround the issue.

echo STARTUP=\"/usr/bin/env LD_LIBRARY_PATH=\${LD_LIBRARY_PATH} \${STARTUP}\" | sudo tee /etc/X11/Xsession.d/90preserve_ld_library_path

For more details refer comment #17 at this bug report https://bugs.launchpad.net/ubuntu/+source/xorg/+bug/366728. as well as refer https://bugs.launchpad.net/ubuntu/+source/xorg/+bug/380360




Thursday, March 27, 2014

Install ZeroMQ on ubuntu with Java Binding

First install all required tools to build zeromq library
sudo apt-get install libtool autoconf automake uuid-dev build-essential pkg-config

Once you have required tools install download zeromq source code and make a build


 #Download latest zermoq source code http://zeromq.org/area:download   
 #I tried it with zeromq-3.2.4.tar.gz (http://download.zeromq.org/zeromq-3.2.4.tar.gz)   
 $ zeromq-3.2.4.tar.gz  
 $ tar -zxvf zeromq-3.2.4.tar.gz  
 $ cd zeromq-3.2.4  
 $ ./configure  
 $ make  
 $ sudo make install  
 $ cd ../  

This will install zeromq libraries at location "/usr/local/lib" you may like to set this path with "LD_LIBRARY_PATH" so that the libraries will be used at the time of execution. If you are setting LD_LIBRARY_PATH from .profile, or /etc/environment then you will it is not getting set refer.

Generate Java binding refer official documentation for more details
http://zeromq.org/bindings:java
 $ git clone https://github.com/zeromq/jzmq.git  
 $ cd jzmq  
 $ ./autogen.sh  
 $ ./configure  
 $ make  
 $ sudo make install

At the end you will find zmq.jar generated at location /usr/local/share/java/zmq.jar


Updated Note : 

With latest version of available you may get following error

checking for sodium... no
configure: error: Package requirements (libsodium) were not met:
No package 'libsodium' found

You may not require this package, so install it with it to do that run configuration with following option


./configure --without-libsodium




Install Eclipse Maven plugin and import maven project

With new versions of Eclipse old m2e plugins have become absolute now you need to install eclipse plugins from eclipse market place. Follow below steps to install m2e plugins along with required GWT plugins. I have tried below steps with Eclipse (Kepler)


  • Install GWT eclipse plugin Help -> "Eclipse Marketplace". Search with string "GWT" install "Google Plugin for eclipse 4.3".
  • Install maven plugin open "Eclipse Marketplace" and search for "m2e-wtp" look for "Maven Integration for Eclipse WTP Juno (1.0.1)" and install it
  • Other maven integration plugins open "Eclipse marketplace" and search for "m2e" look for "APT M2E Connector" and "GWT M2E Connector" install both the plugins.


With above plugins installed before importing  your maven project. I tend to make sure I use same maven installation and configuration that I use for command line maven build. When you install m2e eclipse plugin for maven it comes with default maven installation. To change your maven installation to same as that of command line maven. Follow below steps.


  • Open Window - > Preferences "Preferences" window will be open.
  • Expand "Maven" label on left side panel.
  • Select "Installations" on right hand side panel you will see "embedded" maven installation selected.
  • Click on "Add" button directory window will be prompted.  Select home folder of your maven installation and click "Ok".
  • With addition of your installed maven installation. Make sure check mark is marked on your installed maven installation and then click on "OK" 
To import your maven project inside eclipse follow below steps.
Note: Before importing your eclipse projects make sure you make a complete build from command prompt.

  • Select "File - > Import" 
  • Expand "Maven" and select "Existing Maven Projects" and click on "Next".
  • Click on "Browse" button on next screen folder explorer will appear.
  • Select your project's parent folder which contains the pom.xml. 
  • Next follow next screens as next screens varies based on maven plugins used in your project. Sometimes it may take some time, but be patient and allow eclipse to complete it (in some cases where you are using maven plugin in your pom.xml m2e will try to locate respective eclipse plugin to achieve same task from eclipse. If it fails to find one it will try to locate in eclipse market place and if it is there user will be prompted to install the same). 

Sunday, March 23, 2014

gwt youtube player

Created GWT wrapper over YouTube Iframe player api refer

Usage

Inherit GWT module <inherits name="open.pandurang.gwt.youtube.YouTube" />
Before you start using YouTube iframe library one need to load them first, so as to load the library first you need make call to YouTubePlayer.loadYouTubeIframeApi();. This will ensure library is loaded, you can register to recieve event when library is loaded completely by using ApiReadyEventHandler for more details on the same refer YouTube documentation's geting started section. This ApiReadyEvent is equivalent to onYouTubeIframeAPIReady javascript callback.

// 3. This function creates an <iframe> (and YouTube player)
//    after the API code downloads.
   var player;
   function onYouTubeIframeAPIReady(){}


      YouTubePlayer.addApiReadyHandler(new ApiReadyEventHandler() {

            public void onApiReady(ApiReadyEvent event) {
              // Action you want take after api is loaded.
            }
      }

Note: Please make sure you load iframe library well in advance before using YouTube Player.
    public void onModuleLoad() {
        YouTubePlayer.loadYouTubeIframeApi();
        YouTubePlayer.addApiReadyHandler(new ApiReadyEventHandler() {

            public void onApiReady(ApiReadyEvent event) {
                PlayerConfiguration config = (PlayerConfiguration) PlayerConfiguration.createObject();
                config.setVideoId("M7lc1UVf-VE");
                config.setHeight("562.5");
                config.setWidth("1000");
                final YouTubePlayer player = new YouTubePlayer(config);
                player.addPlayerReadyHandler(new PlayerReadyEventHandler() {

                    public void onPlayerReady(PlayerReadyEvent event) {
                        GWT.log("First player is ready.");
                        GWT.log("First player state -> " + player.getPlayer().getPlayerState());
                    }
                });
                player.addStateChangedHandler(new StateChangeEventHandler() {

                    public void onStateChange(StateChangeEvent event) {
                        GWT.log("First player state changed => " + event.getPlayerEvent().getData());
                    }
                });
                RootPanel.get().add(player);
                Button btn = new Button("Stop");
                btn.addClickHandler(new ClickHandler() {

                    public void onClick(ClickEvent event) {
                        player.getPlayer().stopVideo();
                        GWT.log("First player state -> " + player.getPlayer().getPlayerState());
                    }
                });
                RootPanel.get().add(btn);
                config = (PlayerConfiguration) PlayerConfiguration.createObject();
                config.setVideoId("4biVZcgCn9A");
                PlayerVariables playerVars = (PlayerVariables) PlayerVariables.createObject();

                playerVars.setControls(0);
                playerVars.setRel(0);
                playerVars.setShowInfo(0);
                playerVars.setShowInfo(0);
                config.setPlayerVars(playerVars);
                final YouTubePlayer player1 = new YouTubePlayer(config);
                RootPanel.get().add(player1);

                Button btnCue = new Button("Cue");
                btnCue.addClickHandler(new ClickHandler() {

                    public void onClick(ClickEvent event) {
                        JsArrayString list = (JsArrayString) JsArrayString.createArray();
                        list.push("tQIBhsDlTxU");
                        list.push("4jGFreAGRI4");
                        player1.getPlayer().cuePlaylist(list);
                    }
                });
                RootPanel.get().add(btnCue);

            }
        });
    }

Fore more details refer test sample project

Maven Dependency
        <dependency>
            <groupId>open.pandurang.gwt</groupId>
            <artifactId>gwt-youtube-player</artifactId>
            <version>0.1</version>
            <scope>provided</scope>
        </dependency>

Maven Repository
   <repositories>
      <repository>
         <id>Pandurang repo</id>
         <url>https://github.com/pandurangpatil/pandurang-mvn-repo/raw/master/releases</url>
      </repository>
   </repositories>






Friday, March 21, 2014

GIMP Add border and shadow to a layer

To Add border to layer follow below steps


  1. Select the layer then use menu "Layer -> Transparency -> Alpha to Selection.
  2. "Select -> Border" Border Selection window will appear. Enter the size of border you want to show.
  3. "Layer -> Transparency -> Intersect with selection"
  4. "Edit -> Fill with FG/BG Color" You need to select required color from FG / BG color panel.
  5. "Select -> None"
With above steps you will be added border to your layer.

To add shadow to layer

  1. Select the layer 
  2. "Select -> All"
  3. "Filters -> Light And Shadows -> Drop Shadows"
  4. Window will appear select / add required values and click on "OK"



Tuesday, March 18, 2014

Call GWT Java Code from JavaScript

It is very easy to call javascript from GWT java code by making use of JSNI. But calling GWT java code from external java script of JSNI is little tricky and it becomes more complicate when you have to call instance method of a GWT java class. For more detail refer GWT official document (refer)

Call static class method from JavaScript

GWTCode.java


package open.pandurang.client.view;

/**
 * @author Pandurang Patil 18-Mar-2014
 * 
 */
public class GWTCode {

 public static String hello(String name) {
  return "Hello " + name + "!";
 }

 public static native void exportMethod() /*-{
  $wnd.gwtcode_hello = function(name) {
   return @open.pandurang.client.view.GWTCode::hello(Ljava/lang/String;)(name);
  };
 }-*/;
}

At line 15 we are exposing this GWTCode.hello method and assign it to window.gwtcode_hello. Please note there are two "( )" brackets, first one will declare parameter types and second will take actual parameters. Don't worry if you are using eclipse when you press CTRL + SPACE after method name it will populate corresponding type. Now from java script code you can call window.gwtcode_hello("<name>") method. 

NOTE: If method don't take any argument then line no 15 will look like "return @open.pandurang.client.view.GWTCode::hello()();"

Entry Point class 
Sample.java



package open.pandurang.client.view;

import com.google.gwt.core.client.EntryPoint;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class samples implements EntryPoint {

 public void onModuleLoad() {

  GWTCode.exportMethod();
 }

}

at line no 12 you will see we are calling exportMethod to export the GWTCode Hello method.

html code
sample.html


<!doctype html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Samples and trials</title>
<script type="text/javascript" language="javascript" src="sample/sample.nocache.js"></script>
</head>
<script type="text/javascript" language="javascript">
 function jsGwtCallTest() {
  var msg = window.gwtcode_hello("Pandurang");
  alert(msg);
 }
</script>
</head>
<body>
    <!-- OPTIONAL: include this if you want history support -->
    <iframe src="javascript:''" id="__gwt_historyFrame" tabIndex='-1' style="position: absolute; width: 0; height: 0; border: 0"></iframe>
    <!-- RECOMMENDED if your web app will not function without JavaScript enabled -->
    <noscript>
        <div
            style="width: 22em; position: absolute; left: 50%; margin-left: -11em; color: red; background-color: white; border: 1px solid red; padding: 4px; font-family: sans-serif">
            Your web browser must have JavaScript enabled in order for this application to display correctly.</div>
    </noscript>
    <button onclick="jsGwtCallTest();">test</button>
</body>
</html>


we are calling this method on event of button click. You will not see any issues here but if you are calling this method from other .js file on some events like on page load or something. You need to make sure gwt entry point has been executed and exported the method.

Saturday, March 15, 2014

Monday, March 10, 2014

Check Cron executed or not.

Many a times it happens we schedule some cron job to get executed, we do check as well whether command gets executed properly or not. And even though we tried the command some times your cron fail to execute.  There are two possibilities either cron is not configured properly or some how command is failed. Now in this case how do we check if cron is getting executed or not. Does it gets logged some where when is last cron executed? Yes it does get logged in syslog you can run following command to check cron entries
$ grep CRON /var/log/syslog
Mar 10 08:00:01 staging01 CRON[23609]: (root) CMD (my-command)
Mar 10 08:00:01 staging01 CRON[23608]: (CRON) info (No MTA installed, discarding output)
Mar 10 08:10:01 staging01 CRON[23611]: (root) CMD (my-command)
Mar 10 08:10:01 staging01 CRON[23610]: (CRON) info (No MTA installed, discarding output)
Mar 10 08:17:01 staging01 CRON[23613]: (root) CMD (   cd / && run-parts --report /etc/cron.hourly)
Mar 10 08:20:01 staging01 CRON[23616]: (root) CMD (my-command)
Mar 10 08:20:01 staging01 CRON[23615]: (CRON) info (No MTA installed, discarding output)
Mar 10 08:30:01 staging01 CRON[23618]: (root) CMD (my-command)
Mar 10 08:30:01 staging01 CRON[23617]: (CRON) info (No MTA installed, discarding output)
Mar 10 08:40:01 staging01 CRON[23620]: (root) CMD (my-command)
Mar 10 08:40:01 staging01 CRON[23619]: (CRON) info (No MTA installed, discarding output)
Mar 10 08:50:01 staging01 CRON[23698]: (root) CMD (my-command)


Sunday, March 9, 2014

Setup firewall with UFW on ubuntu

It is very easy to setup firewall using UFW on ubuntu server 

First you need to check if you have UFW installed on your machine. If it is installed you can check the status of the same using 
$ sudo ufw status
Status: inactive

In case it is installed but not enabled. If it is not installed then it will throw command not found error. If it is active then it will show out put similar like below output.
Status: active

To                         Action      From
--                         ------      ----
22                         ALLOW       Anywhere

If it is not installed then you can install it 
$ sudo apt-get install ufw

This will install ufw. Now when you will check the status it will be inactive. Before you activate the same you need to set the rules.  Depending on your requirement, you can set default policy for incoming as well as outgoing connections. If default policy for incoming is "deny" then all incoming connections are by default denied the access. Except on those ports which are made open. If you set default policy to be "allow" then all incoming connections will be allowed except on those ports for which rule has been added to deny the connections. Same is true for outgoing connections. Ideally we should set default policy to be "deny" for all incoming connections and default policy to be "allow" for all out going connections.

Set default policy for incoming connections
$ sudo ufw default deny incoming
Default incoming policy changed to 'deny'
(be sure to update your rules accordingly)

Set default policy for outgoing connections
$ sudo ufw default allow outgoing
Default incoming policy changed to 'deny'
(be sure to update your rules accordingly)

Now you before you enable the UFW you have to add rules to allow connections on specific port. Most importantly allow connections on SSH port, if you are doing all this on remote machine, over SSH. Don't enable it before you make sure you have added rule to allow connections over SSH port.

add rules to allow connections
$ sudo ufw allow ssh
or 
$ sudo ufw allow 22/tcp

Similarly you can allow other connections over port 80 and if required 443 as well
$ sudo ufw allow www
$ sudo ufw allow 443/tcp

you can add deny rule like 
$ sudo ufw deny 80/tcp

Delete any rule like
$ sudo ufw delete allow www

Once you have all rule set (Make sure you have added rule to allow ssh connection). Now you can enable ufw to act as firewall
$ sudo ufw enable
Command may disrupt existing ssh connections. Proceed with operation (y|n)? y
Firewall is active and enabled on system startup
$ sudo ufw status
Status: active

To                         Action      From
--                         ------      ----
22                         ALLOW       Anywhere
443/tcp                    ALLOW       Anywhere
80/tcp                     ALLOW       Anywhere

You can disable it like
$ sudo ufw disable




Saturday, March 8, 2014

download Oracle JDK / JRE from console / command prompt

Many a times we have to download JDK / JRE on remote machine through console. In most of the cases we tend to download it on our desktop and then upload it to the remote machine through SCP as the download link from Oracle website are not directly accessible. You need to first accept the agreement so that you get the download link. The link is not usable to download it using wget. It seems oracle site look at a cookie value which marks given download request as user's acceptance of agreement.  And that cookie is 

Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F

Now you can download it using wget by passing this cookie with required download link as follows

wget --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F" http://download.oracle.com/otn-pub/java/jdk/7u51-b13/jdk-7u51-linux-x64.tar.gz

Thursday, March 6, 2014

GWT access style defined inside .ui.xml within corresponding .java file

Some times you may want to access styles defined inside your Sample.ui.xml file which you want to access / use from within Sample.java widget class. You can do that by defining an interface which extends from com.google.gwt.resources.client.CssResource and declaring method with name matching exactly that of required style class name that you have declared inside ui.xml. Refer below code.


Sample.ui.xml contents


<src path>/com/pandurang/client/ui/Sample.ui.xml

<ui:UiBinder xmlns:ui='urn:ui:com.google.gwt.uibinder' xmlns:g='urn:import:com.google.gwt.user.client.ui'>
   .
   .
   .
   <ui:style type="com.pandurang.client.ui.Sample.MyStyle">
 .domain {
  margin: 0 auto;
  width: 730px;
 }
  
 .editImg {
  cursor: pointer;
  float: left;
  margin-left: 181px;
 }
   </ui:style>
    <g:HTMLPanel>
        <div>
            <div class="{style.domain}">
                   <!-- Contents.... -->
            </div>
        </div>
    </g:HTMLPanel>
</ui:UiBinder>

You need to connect <ui:style> tag with corresponding CssResource interface by using "type" attribute of <ui.style> tag as shown above.

Sample.java contents


<src path>/com/pandurang/client/ui/Sample.java

package com.agnie.useradmin.main.client.ui;

import com.google.gwt.resources.client.CssResource;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.core.client.GWT;

public class Sample extends Composite {

        interface MyUiBinder extends UiBinder<Widget, Sample> {
 }

 private static MyUiBinder uiBinder = GWT.create(MyUiBinder.class);

 interface MyStyle extends CssResource {
  String domain();
                String editImg();
 }

 @UiField
 MyStyle      style;

        public Sample(){
             initWidget(uiBinder.createAndBindUi(this));
        }
}

If you look at above code, we have defined MyStyle interface and declared methods with name matching to that of css class names. And instance of MyStyle will be injected by using @UiField annotation. In your java code you can make use of style variable to access the styles defined inside ui.xml.

configure nginx to redirect user from HTTP to HTTPS

When you are going to sever all requests over SSL then in some cases you need to only serve requests over SSL. While doing that you may have to disable port 80 so that all the requests will be only served through SSL. But in that case if user hits your url with http, user will see page not found error. Instead you can enable your port 80 and redirect all requests to https url with following configuration.



     server {
        listen      80;
        server_name www.yourdomain.com;
        return 301 https://www.yourdomain.com$request_uri;
    }


Adding "$request_uri" will make sure it will keep requested url as is as per requested. Other wise even if you hit the url like http://www.yourdomain.com/company/about.html still it will be redirected to https://www.yourdomain.com

Configure Nginx for SSL

You need to have private key and CA signed certificate (to test you may generate your own Self signed certificate) to configure your nginx to serve request over SSL. Add following lines into your nginx.conf file and make required changes to point ssl_certificate to location of your certificate in this configuration it is "server.crt" (if you copy your .crt and .key file into "<nginx home>/conf" folder . In that case you can specify only file name other wise you need to specify absolute path of a file). Change ssl_certificate_key to point your key file.

Restart nginx server and hit https url https://yourdomain.com. ( If you have installed self signed certificate you will see Untrusted Exception. You can safely continue with it.) 


    # HTTPS server
    #
    server {
        listen       443;
        server_name  yourdomain.com;

        ssl                  on;
        ssl_certificate      server.crt;
        ssl_certificate_key  server.key;

        ssl_session_timeout  5m;

        ssl_protocols  SSLv2 SSLv3 TLSv1;
        ssl_ciphers  HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers   on;

        location / {
            root   html;
            index  index.html index.htm;
        }
    }


Generate self signed SSL certificate

Follow below steps to generate self signed certificate:

1. You need to first generate your own private key.
$ openssl genrsa -des3 -out server.key 1024

Generating RSA private key, 1024 bit long modulus
.......................++++++
.......++++++
e is 65537 (0x10001)
Enter pass phrase for server.key:
Verifying - Enter pass phrase for server.key:

With above command it will generate private key, while doing that it will ask you to enter pass phrase which will make this private key useful who knows this pass phrase. This will generate the private server key "server.key".

2. Then you need to generate Certificate Signing Request.


$ openssl req -new -key server.key -out server.csr

Enter pass phrase for server.key:
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:IN
State or Province Name (full name) [Some-State]:Maharashtra
Locality Name (eg, city) []:Pune
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Pandurang Patil Pvt. Ltd.
Organizational Unit Name (eg, section) []:Pune
Common Name (e.g. server FQDN or YOUR name) []:www.pandurangpatil.com    
Email Address []:[email protected]

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:

Here you need to enter required details, you can refer above request output. You may chose to skip last to questions. This step will generate the certificate signing request server.csr. 

3. To self sign the certificate we need to create signing certificate as well (that is your own CA certificate). For that you need to first create private key for CA.


$ openssl genrsa -des3 -out ca.key 1024
Generating RSA private key, 1024 bit long modulus
.......................++++++
.......++++++
e is 65537 (0x10001)
Enter pass phrase for ca.key:
Verifying - Enter pass phrase for ca.key:

This private key pass phrase will be required to be used while signing the Certificate Signing Request.

4. Now we have to generate CA certificate


$ openssl req -new -x509 -days 365 -key ca.key -out ca.crt

Enter pass phrase for ca.key:
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:IN
State or Province Name (full name) [Some-State]:Maharashtra
Locality Name (eg, city) []:Pune
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Pandurang Patil CA
Organizational Unit Name (eg, section) []:Pune
Common Name (e.g. server FQDN or YOUR name) []:www.pandurangpatil.com
Email Address []:[email protected]

5. Now we have to sign .csr request that we have generated in step 2. For that we need to provide .conf file through which utility will take required inputs. Somebody has created this nice script which will automate next steps to sign .csr request. You can download this .sh file on your machine, I am assuming it will be saved on sign.sh at the same location from where you are executing above commands. Make this sign.sh executable.


$ ./sign.sh server.csr

CA signing: server.csr -> server.crt:
Using configuration from ca.config
Enter pass phrase for ./ca.key:
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
countryName           :PRINTABLE:'IN'
stateOrProvinceName   :PRINTABLE:'Maharashtra'
localityName          :PRINTABLE:'Pune'
organizationName      :PRINTABLE:'Pandurang Patil Pvt.Ltd.'
organizationalUnitName:PRINTABLE:'Pune'
commonName            :PRINTABLE:'www.pandurangpatil.com'
emailAddress          :IA5STRING:'[email protected]'
Certificate is to be certified until Mar  6 09:52:59 2015 GMT (365 days)
Sign the certificate? [y/n]:y


1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated
CA verifying: server.crt <-> CA cert
server.crt: OK

While signing you need to enter pass phrase for ca.key and confirm the details. This step will generate "server.crt". This way you have your private key "server.key" and self signed certificate "sever.crt" generated.

Wednesday, March 5, 2014

Configure nginx to server multiple domains / subdomains

With nginx it is quite easy to configure multiple domains or subdomains to be served from single server. Refer following configuration for the same.

    server {
        server_name first.pandurangpatil.com;
        root /var/www/first;
    }

    server {
        server_name second.pandurangpatil.com;
        root /var/www/second;
    }

    server {
        server_name someother.com;
        root /var/www/other;
    }



Monday, March 3, 2014

compare more than two war files and repackage them excluding common jars

Some times you need to deploy more than one war files under same servlet container. In those war files there might have some common jars across them, which you want to deploy directly to servlet containers class path. So that container won't load those jars separately in the context of each war application. Which in turn will reduce the utilisation of permgen memory space. Following code snippet will help you to compare more than two war files, extract common shared libraries inside separate folder and repackage those wars excluding common jar files. This will generate two folders "shared" and "repackaged" inside given path where you have kept war files. "shared" folder will contain all extracted shared jar files and "repackaged" folder contains all war repackaged excluding shared jar files. 


import java.io.File;
import java.io.FileFilter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;

/**
 * @author Pandurang Patil 02-Mar-2014
 * 
 */
public class RepackProcessor {

 private String    source;

 private Boolean    verbose    = false;

 private static final String sharedLocateion  = "shared";
 private static final String outPutLocation  = "repackaged";
 private Set<String>   commonLibs   = new HashSet<String>();
 private Set<String>   allLibs    = new HashSet<String>();
 private Set<String>   commonCopiedLibs = new HashSet<String>();

 public void process() throws Exception {
  File f = new File(source);
  if (f.isDirectory()) {
   File[] files = f.listFiles(new FileFilter() {

    public boolean accept(File pathname) {
     if (pathname.isFile() && pathname.getName().endsWith(".war")) {
      return true;
     }
     return false;
    }
   });
   if (files == null || files.length < 2) {
    System.out.println("You need to have at least have two war files in your source directory");
    return;
   }
   System.out.println("Scanning existing war files...");
   for (File file : files) {
    scan(file);
   }
   System.out.println("Scan complete...");

   if (commonLibs.size() == 0) {
    System.out.println("There are no common libraries found, so there is no need to repackage the wars, you can use them as is");
   } else {
    java.io.File mainDir = new java.io.File(source + java.io.File.separator + sharedLocateion);
    mainDir.mkdir();
    mainDir = new java.io.File(source + java.io.File.separator + outPutLocation);
    mainDir.mkdir();
    System.out.println("Repackaging...");
    for (File file : files) {
     repackage(file);
    }
   }
  } else {
   System.out.println("You need to specify directory which contains all war files that needs to be repackaged.");
  }
 }

 /**
  * Repackage war files by excluding common jar files.
  * 
  * @param warFile
  * @throws IOException
  */
 public void repackage(File warFile) throws IOException {
  FileOutputStream fos = new FileOutputStream(new File(source + java.io.File.separator + outPutLocation + java.io.File.separator + warFile.getName()));
  System.out.print("\nRepackaging war =>" + warFile.getName());
  JarOutputStream target = new JarOutputStream(fos);
  JarFile war = new JarFile(warFile);
  Enumeration<JarEntry> files = war.entries();
  while (files.hasMoreElements()) {
   java.util.jar.JarEntry file = files.nextElement();
   extractAndAdd(war, file, target);
  }
  System.out.println();
  target.close();
  war.close();
 }

 /**
  * Scan war file contents to identify shared libraries.
  * 
  * @param warFile
  * @throws Exception
  */
 public void scan(File warFile) throws Exception {
  JarFile war = new JarFile(warFile);
  Enumeration<JarEntry> files = war.entries();
  while (files.hasMoreElements()) {
   JarEntry file = files.nextElement();
   String fileName = file.getName();
   if (!file.isDirectory() && fileName.startsWith("WEB-INF/lib/") && fileName.endsWith(".jar")) {
    // file is jar file.
    if (!commonLibs.contains(fileName)) {
     if (allLibs.contains(fileName)) {
      // If given file is there in all libs that means it been added while scanning previous war file.
      // That means its common file between two wars.
      commonLibs.add(fileName);
     } else {
      // other wise add it in all libs list.
      allLibs.add(fileName);
     }
    }
   }
  }
  war.close();
 }

 /**
  * Extract given file from source war file and add it to destination war file. While doing that it will exclude
  * common jar files and copy to shared folder.
  * 
  * @param sourceWarFile
  *            Source war file.
  * @param source
  *            source file from source war file.
  * @param target
  *            Target war file output stream.
  * @throws IOException
  */
 private void extractAndAdd(JarFile sourceWarFile, JarEntry source, JarOutputStream target) throws IOException {
  String fileName = source.getName();
  if (!source.isDirectory() && commonLibs.contains(fileName)) {
   if (commonCopiedLibs.contains(fileName)) {
    return;
   } else {
    if (verbose)
     System.out.println("copying to shared Lib => " + fileName);
    else
     System.out.print(" .");
    java.io.File newFile = new java.io.File(this.source + java.io.File.separator + sharedLocateion + java.io.File.separator
      + fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length()));
    java.io.InputStream is = sourceWarFile.getInputStream(source); // get the input stream
    java.io.FileOutputStream fos = new java.io.FileOutputStream(newFile);
    while (is.available() > 0) { // write contents of 'is' to 'fos'
     fos.write(is.read());
    }
    fos.close();
    is.close();
    commonCopiedLibs.add(fileName);
   }
  } else {
   if (verbose)
    System.out.println("adding to war =>" + fileName);
   else
    System.out.print(" .");
   target.putNextEntry(source);
   if (!source.isDirectory()) {

    java.io.InputStream is = sourceWarFile.getInputStream(source); // get the input stream
    while (is.available() > 0) { // write contents of 'is' to 'target war'
     target.write(is.read());
    }
   }
   target.closeEntry();
  }
 }

 public static void main(String[] args) throws Exception {
  RepackProcessor rp = new RepackProcessor();
  // Copy all war files at one location and provide absolute path to the location which contains all those war
  // files.
  rp.source = "<location of folder where all war files are placed.";
  rp.process();
 }
}



Friday, February 28, 2014

nginx proxypass configuration with X-Forwarded-Host header

I have used and configured apache for proxy pass and proxy pass reverse multiple times with X-Forwarded-Host. I tried configuring same with nginx and it works out to be more customisable and easy one.

    server {
        listen       80;
        server_name  pandurangpatil.com;
        location /myapp {
            proxy_set_header X-Forwarded-Host $host;
            proxy_pass http://localhost:8080/myapp;
        }
        .
        .
        .
    }

MySql JPA toplink Auto increment id generation.

To configure JPA entity to make use of auto increment feature of MySql for primary key generation you can make use of IDENTITY strategy ref below code. 


@Entity 
public class Customer { 

        @Id 
        @GeneratedValue(strategy=GenerationType.IDENTITY) 
        private long id;
        .
        .
        .
        public long getId() {
  return id;
 }
}

But problem with this way of generating ids with MySql and JPA combination is when you persist new entity and try to retrieve id assigned to newly persisted entity using getId() method. You get 0 value, because newly generated id for the record is not set with managed entity for that you need to flush after persisting the entity. 

If you don't specify strategy with GeneratedValue annotation, default value will be GenerationType.AUTO. AUTO strategy means your are asking JPA to select appropriate strategy. In most of the cases it is TABLE strategy. 


@Entity 
public class Customer { 

        @Id 
        @GeneratedValue
        private long id;
        .
        .
        .
        public long getId() {
  return id;
 }
}

One can make use of TABLE strategy directly, this way you have more control over configurations.


@Entity 
public class Customer { 

 @Id
 @GeneratedValue(generator = "idgen")
 @TableGenerator(name = "idgen", table = "ID_GEN", pkColumnName = "ID_NAME", valueColumnName = "ID_VAL", pkColumnValue = "CUST_SEQ", allocationSize = 1, initialValue = 0)
        private long id;
        .
        .
        .
        public long getId() {
  return id;
 }
}


Wednesday, February 26, 2014

Java java.lang.OutOfMemoryError: PermGen space


java.lang.OutOfMemoryError: PermGen space

You get this error that means your JVM is running out of allocated memory for storing class metadata information (class properties, methods annotations etc). This space is not cleaned by Garbage Collected by Garbage collector. When JVM run out of memory for this, it could happen because of multiple reasons, 
  1. One you are dynamically generating classes and those are getting loaded in JVM. 
  2. Second your application is so big and it has more number of dependencies on other third party libraries.  Which in turn deploys huge number of jars.
  3. Third you are deploying multiple modules in the form separate wars (multiple war files) inside your application server. Which results in loading big number of classes in JVM's memory space.
In either of the case to resolve this issue, you have to first try to reduce the number of classes / jars that you are deploying with your application. In some cases I have seen we tend to use multiple frameworks in the same application when single framework can do the job. Generally that happens if we don't keep a tap on what all frameworks getting used in your application and every team member go ahead and add new framework in application. Because he / she has already used it and not willing to explore frame work being used currently in project. If we try, avoid and exclude absolute dependency we can reduce the memory foot print of the application. Which in turn reduces the possibility of getting this errors. I also also see one more reason for this error that is "Maven" which includes dependencies of dependencies some times dependencies which are not needed. This happens without the knowledge to the developer.  And it may become tedious to remove / exclude unwanted dependencies with maven. I don't say it is not possible but it takes some time.

In some cases if you are deploying multiple applications (.war this in context of deploying application on single servlet container). Every application's dependencies will be isolated from each other, and thus it ends up loading some common jars (across the deployed wars) multiple times and in turn ends up consuming more memory. In such cases, one can sort out all common jars across application and deploy them in containers class path directly e.g. inside jetty you can copy those common jar in <jetty home>/lib/ext. As well as remove such common jar from individual war file and then deploy them. Now here there are some challenges as well as some extra efforts and time you need to put in to sort those dependencies. When I talk about challenges, I am talking about situation where there is conflict of versions of dependencies i.e. one app is used lower version of some library and other one is using latest version of the same. In such cases you should keep those dependencies packaged with war only. On extra efforts and time, it depends on you whether you are ready invest your time or money on spending more on hardware. (ok I prepared one utility that will scan all war files, extract common shared jars in one folder and repackage those war files once again excluding common jar files refer)

If you are developing your front end with GWT, then I have seen all GWT libraries remain packaged with WAR file. Here I would like to point out that when you compile your GWT project for deployment, all your GWT client code has been converted to JavaScript. So you no more require those classes to be deployed with your application unless those are being used in backend code as well. And some times it becomes quite tedious to isolate these classes. So I would suggest you to break down you application in three modules, one for pure client side GWT code, one for common code which will be shared across both GWT client side code as well as backend code and third module will be for pure backend side code. In this situation you could exclude the dependency or code from pure GWT module while deployment.

After you try all possibilities and you cannot reduce the memory foot print you can try increasing the allocated permgen memory with following options
  • -XX:PermSize=64M -XX:MaxPermSize=128M Increase memory used for perm gen. Value for these options you need to do trial and error. 
  • You can also try with following options if you are using AOP or dynamically generating the classes.
    • -XX:+CMSClassUnloadingEnabled : Enables garbage collection in permgen 
    • -XX:+CMSClassUnloadingEnabled  Allows garbage collector to remove the classes.