Friday, May 11, 2018

First Unique Word in a Book


Problem : Find the first unique word in entire book .
Solution:

import java.util.LinkedHashMap;
import java.util.Map.Entry;
import java.util.Random;
import java.util.stream.Stream;

public class UniqueWordInBook {

static String [] words = {"find","the","first","unique","word","in","entire","book"};
public static void main(String[] args) {
LinkedHashMap wordsVisited = new LinkedHashMap<>();

Random rand = new Random();
Stream stringStream = rand.ints(1, 500).limit(8).mapToObj(i->words[i%(words.length-1)]);
stringStream.forEach(str -> {
System.out.println(str);
if(wordsVisited.containsKey(str)) {
wordsVisited.remove(str);
wordsVisited.put(str, true);
} else {
wordsVisited.put(str, false);
}
});
Entry uniqEntry = wordsVisited.entrySet().iterator().next();
if(!uniqEntry.getValue()) {
System.out.println("First unique word : " + uniqEntry.getKey());
} else {
System.out.println("Not present");
}
}

}

This solution can be used to find the first unique char present in a String.

Sunday, January 24, 2016

Running Java program as the service or daemon

Making Java program as service or a daemon

Since Java is one of the most used languages in both server and client programming. Still java doesn't have native support of running the program as service in windows or daemon in unix flavors. Apache Software Foundation provide a way running the Java program as the windows service or the daemon. The advantage of running service or the daemon is that the start of the program is always managed by the OS and program will get the additional privileges when it runs as the service.

Apache commons library provides a way for creating the Java program as the windows service or the Unix daemon . Apache comes up with commons daemon library also which provides the wrapper around the daemons creation .
Apache provide 2 binaries one for windows and another for Linux . prunsrv is the binary on the windows which as the 32 bit and 64 flavors . If we are using Java 32 binary to run the program we need to use prunsrv 32 bit and if we are using Java 64 bit we need use the other one. In Linux jsvc will part of the package or we can download the tomcat server , under bin folder will find the jsvc source which we can compile on the Linux by providing the Java binary location.


Here is the sample program which can be used for Windows as well Linux for creating daemons.

import org.apache.commons.daemon.Daemon;
import org.apache.commons.daemon.DaemonContext;
import org.apache.commons.daemon.DaemonInitException;

public class Javaservice implements Daemon
{
    private static String getArg(String[] args, int argnum){
        if (args.length > argnum) {
            return args[argnum];
        } else {
            return null;
        }
    }
     private static boolean stop = false;

    public static void main(String[] args) throws Exception  {
        String mode=getArg(args, 0);
        Javaservice javaservice = new Javaservice();
        if ( "start".equals(mode)) {
            javaservice.start();
        } else if ("stop".equals(mode)) {
            javaservice.stop();
        }
    }

    @Override
    public void init(DaemonContext context) throws DaemonInitException, Exception {
        System.out.println("init");
       
    }

    @Override
    public void start() throws Exception {
        System.out.println("start");
        while (stop) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
            System.out.println("running");
        }
       
    }

    @Override
    public void stop() throws Exception {
        System.out.println("stop");
        stop = true;
    }

    @Override
    public void destroy() {
        System.out.println("destroy");
       
    }
}



Required windows binaries can be found at the following location :

http://www.apache.org/dist/commons/daemon/binaries/windows/

Notice that i am use the commons-daemon package provided by Apache , you can also avoid using commons-daemon refer commons-daemon documentation.

After creating the executable jar , copy the jar and dependencies into a folder . When we compile the above program we end up in coping two binaries one which contains the program and another the commons-daemon.jar which is the dependency.


Linux 
 
On Linux you can run the following commands which will create a program in back ground :

Command for starting :

/usr/bin/jsvc -home $JAVA_HOME -cwd `pwd` -cp Service.jar -pidfile pidfile -outfile outfile.log -errfile logerror.log -debug tryitout.service.Javaservice

Command for stoping :

/usr/bin/jsvc -stop -home $JAVA_HOME -cwd `pwd` -cp Service.jar -pidfile pidfile -outfile outfile.log -errfile logerror.log -debug tryitout.service.Javaservice

 If you are not able to run/create the service you can  check outfile.log and logerror.log for more detailed error messages. I would recommend to used all absolute path in the commands.


Windows

On Windows we need create first the service and windows does provide the interface to start/stop the service.

"c:\testservice\prunsrv" //IS//TestService --DisplayName="Test Service" --Install="c:\testservice\prunsrv.exe" --LogPath="C:\testservice\Service\logs" --StdOutput=auto --StdError=auto --Jvm="C:\testservice\jre-32bit\bin\client\jvm.dll" --Classpath="c:\testservice\commons-daemon-1.0.15.jar":"c:\testservice\service-0.0.1-SNAPSHOT.jar" --StartMode=jvm --StartClass=tryitout.service.Javaservice --StartParams=start --StopMode =jvm --StopClass=tryitout.service.Javaservice --StopParams=stop

 Above command line will install the service name called "Test Service" . You can stop and start the service using windows services.msc.


For deleting the service we can use the following command :

"c:\testservice\prunsrv" //DS//TestService"

If you face any issues you can refer files created under directory "LogPath" .Thats it for now .