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>