Thursday, February 26, 2015

Java get system environment variable details

Get System environment variable details.

import java.util.Map;

 * @author Uttesh Kumar T.H.
public class FindJdk {

    public static void main(String[] args) {
        Map<String, String> env = System.getenv();
        for (String envName : env.keySet()) {

Command execution by Java Processor

sample code to execute any command on operating system by using java processor.

for example :
To find jdk installed in system, We can run the command "where javac" for window and "where is javac" for linux
the above command will return path javac.exe/javac.bin, by using that path we have to go to root folder to find system is having jdk.

code :

 * @author Uttesh Kumar T.H.
public class CommandExecutor {

    public static void main(String[] args) {
        String JAVA_WINDOWS = "where javac";
        String JAVA_LINUX = "whereis javac";
        if (System.getProperty("").contains("win") || System.getProperty("").contains("Win")) {
            System.out.println("result : " + executeCommand(JAVA_WINDOWS));
            System.out.println("result : " + executeCommand(JAVA_LINUX));

    private static String executeCommand(String command) {
            String result = getCommandOutput(command);
            if (result == null || result.isEmpty()) {
                System.out.println("NOT FOUND");
                return result;
            } else {
                return result;

    private static String getCommandOutput(String command) {
        String output = null;
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(command);
            output = ConvertStreamToString(process.getInputStream());
        } catch (IOException e) {
            System.err.println("Cannot retrieve output of command");
            output = null;
        return output;

    private static String ConvertStreamToString(InputStream stream) {
        BufferedReader reader = null;
        InputStreamReader streamReader = null;
        try {
            streamReader = new InputStreamReader(stream);
            reader = new BufferedReader(streamReader);

            String currentLine = null;  //store current line of output from the cmd
            StringBuilder commandOutput = new StringBuilder();  //build up the output from cmd
            while ((currentLine = reader.readLine()) != null) {
            return commandOutput.toString();
        } catch (IOException e) {
        } finally {
            if (stream != null) {
                try {
                } catch (IOException e) {
            if (streamReader != null) {
                try {
                } catch (IOException e) {
            if (reader != null) {
                try {
                } catch (IOException e) {
        return null;

Wednesday, February 25, 2015

6 Steps for contribute your jar/project to open source maven repository


1. Sign Up at Sonatype.
2. Create your project in JIRA.
3. Create a Key Pair.
4. Create and Sign your Artifacts.
5. Deploy your Artifacts to your Staging Repository.
6. Promote your Repository

Step #1: Sign Up at Sonatype

Sonatype is a company that provide the access point to making a project available in the Maven Central Repository. You have to create an account at the following sites (for free ;) ): This is Sonatypes JIRA issue management system. This is Sonatypes Nexus installation. Nexus is a software that basically acts as a collection of Maven repositories.

Step #2: Create your project in JIRA

Before submitting the project we need create the jiira artifact. create an issue of type “New Project”.

Project: select “Community Support – Open Source”
Issue Type: select “New Project”
Summary: name of your project
Description: line about what your project is about
Attachment: don’t add an attachment
Group Id: your desired Maven group id (your namespace).
Project URL: URL to your project homepage. You should have a homepage for your project, even if it is just the frontpage of your github or google code repository.
SCM URL: URL to your source code management system like github or google code
Username: your JIRA user name
Already Synced to Central: choose “No”
Epic Link: leave empty

Once the jiira artifact for new project is created successfully,Sonatype developement team will usually respond within a couple hours, but it may take longer – be patient.

you will receive email with subject "[JIRA] (OSSRH-ID) you project description".

Step #3: Create a Key Pair

This step is very important proper key should be created and all file should be signed.

It is required for any artifacts you release to be signed. The easiest way to do this is by using GNU Privacy Guard.

Windows :

You will have to choose a passphrase when generating a key pair.

After installing the gpg run the following command to create the key.
1. create key
c:\gpg --gen-key
It'll ask you a few questions.
Algorithm - choose RSA and RSA
 Key size - choose 2048 bit
 Time of validity for the key, just use the default value if you don’t have any special requirements.
 Name and email 
 Comment - may be empty
 Passphrase (enter and remember)

2. List your key

gpg --list-keys

D:\git\pdfngreport>gpg --list-keys
pub   2048R/D6E12C4E 2015-02-24
uid       [ultimate] uttesh (pdf ngreport opensource project) <>

3.Now you can upload your key to keyserver.

gpg --keyserver hkp:// --send-keys D6E12C4E 

Step#4: Create and Sign your Artifacts:

Now you can sign you artifact manually or with maven plugin.


run for signing:

$gpg -ab artifact.jar

run for verifying:
$gpg --verify artifact.jar.asc

Maven plugin: add plugin to build section:


sign all the file
mvn clean javadoc:jar source:jar gpg:sign -Dgpg.passphrase=your_passphrase install

file in target folder :


Step #5:Deploy your Artifacts to your Staging Repository

If your request for a new Project in the Sonatype JIRA was successful, you will get an mail with content something like the following:

Configuration has been prepared, now you can:

Deploy snapshot artifacts into repository
Deploy release artifacts into the staging repository
Promote staged artifacts into repository ‘Releases’
Download snapshot and release artifacts from group
Download snapshot, release and staged artifacts from staging group
please comment on this ticket when you promoted your first release, thanks

This basically means that they have provided a staging repository for you where you can upload your artifacts (automatically or manually). From this staging repository you can then manually trigger a release to Maven Central.

After the Maven build has finished successfully, log in to and click the link “Staging Repositories” in the left-side navigation. In the opening tab, select your repository. This triggers some validation checks on the files you uploaded. You can see if those validations were successful by clicking on the “Activity”-tab in the bottom part of the screen and selecting the “close” node. If there were any errors, fix the errors and deploy again. A documentation of the validations that will be performed when closing a repository can be found here.
Go to, login (right top angle) with your sonatype jira account.

home page :

click "Staging Upload" from left side menu.

After the upload make sure no error in after the upload in the active tab.Once all validations were successful, you can now promote the repository by clicking the “release” button. This means that you want the contents you uploaded into this repository to be released to Maven Central. After this has been done you should receive an email with the subject “Nexus: Promotion completed” and you should add a comment to the JIRA issue you created and wait for them to activate the sync to Maven Central. This may again take one or two working days. After this, your project has been successfully released to Maven Central and you can upload and then release repositories at any time without having to wait so long (repositories that have been successfully promoted once before will automatically be synced to Maven Central about every two hours from now on).

Monday, February 23, 2015

Whois domain detail by java

Apache commmon class provides the domain details.

Following details:

Domain Name: UTTESH.COM
Sponsoring Registrar IANA ID: 146
Whois Server:
Referral URL:
Status: clientDeleteProhibited
Status: clientRenewProhibited
Status: clientTransferProhibited
Status: clientUpdateProhibited
Updated Date: 11-jan-2015
Creation Date: 24-jan-2012
Expiration Date: 24-jan-2017

But it will provide only the registry database contains ONLY .COM, .NET, .EDU domains and Registrars.

Sample Code :

 * @author Uttesh Kumar T.H.

public class WhoIsSample {

    public static void main(String[] args) {

        WhoIsSample obj = new WhoIsSample();


    public String getWhois(String domainName) {

        StringBuilder result = new StringBuilder("");

        WhoisClient whois = new WhoisClient();
        try {
            String whoisData1 = whois.query("=" + domainName);

        } catch (Exception e) {
        return result.toString();



Jar details :

maven dependency


Direct download click here

JAVA8 Lambda part1

Lambda expressions are a new and important feature included in Java SE 8. Lambda expressions also improve the Collection libraries making it easier to iterate through, filter, and extract data from a Collection. In addition, new concurrency features improve performance.

Lambda Expression Syntax
(Arguments)      (Arrow Token)  (Body)
(int x,int y)        ->    x+y

argument list is like normal method level parameters list, it can be no argument also. i.e.

() -> 121

it will return 121 value and no argument list.

body can be statement block or logical block with return statement.

more samples :

(String s) -> { System.out.println(s); }

block form just print the string.

a lambda could be represented as a comma-separated list of parameters, the –> symbol and the body. For example:

Arrays.asList( "Item1", "Item2", "Item3" ).forEach( e -> System.out.println( e ) );

Please notice the type of argument e is being inferred by the compiler. Alternatively, you may explicitly provide the type of the parameter.

Arrays.asList("Item1", "Item2", "Item3").forEach((String e) -> System.out.println(e));

If expression/processing in complex then add the brackets i.e.

Arrays.asList("Item1", "Item2", "Item3").forEach(e -> {

String separator = ",";
Arrays.asList( "Item1", "Item2", "Item3" ).forEach( {
    ( String e ) -> System.out.print( e + separator ) });

lambda expression will return the value as well. i.e.

Arrays.asList( "Item1", "Item2", "Item3" ).sort( ( e1, e2 ) -> e1.compareTo( e2 ) );

 Arrays.asList( "Item1", "Item2", "Item3" ).sort( ( e1, e2 ) -> {
    int result = e1.compareTo( e2 );
    return result;
} );

Functional Interfaces:

a Functional Interface is an interface with just one abstract method declared in it.

java.lang.Runnable is an example of a Functional Interface. There is only one method void run() declared in Runnable interface. We use Anonymous inner classes to instantiate objects of functional interface. With Lambda expressions.

// Anonymous Runnable
     Runnable r = new Runnable(){
       public void run(){
         System.out.println("Hello world old!");


// Lambda Runnable
     Runnable r = () -> System.out.println("Hello world new!");

Comparator Lambda expression

traditional compator sort
Collections.sort(list, new Comparator<Person>() {
            public int compare(Person p1, Person p2) {
                return p1.getName().compareTo(p2.getName());

Lambda sort 
Collections.sort(list, (Person p1, Person p2) -> p1.getName().compareTo(p2.getName()));
full sample


Thursday, February 19, 2015

Exciting Features In Java 8 That Will Change How We Code?

5 features that we feel an absolute must for you to know about.

1.Lambda expressions.
2.Parallel operations.
3.Java + JavaScript :)
4.New date / time APIs.
5.Concurrent accumulators

1.Lambda expressions

Lambda expressions have taken the programming world by storm in the last few years. Most modern languages have adopted them as a fundamental part of functional programming. JVM based languages such as Scala, Groovy and Clojure have integrated them as key part of the language. And now, Java 8 is joining in on the fun.

2.Parallel operations.

Java introduced a key concept into the language of internal iteration. Essentially as developers we’re used to use loop operations as one of the most basic programming idioms, right up there with if and else.
This enable operations carried out on long arrays such as sorting, filtering and mapping to be carried out in parallel by the framework.

ConcurrentMap> byGender = roster.parallelStream().collect(Collectors.groupingByConcurrent(Person::getGender))

here roster this a collection and by using the parallelStream() we are getting the person object by the gender and populating the map with gender as key and resulted collection as value.

3.Java + JavaScript :)

Java 8 is introducing a completely new JVM JavaScript engine – Nashorn. This means that the next time you’re looking to integrate JS into your backend, instead of setting up a node.js instance, you can simply use the JVM to execute the code. The added bonus here is the ability to have seamless interoperability between your Java and JavaScript code in-process, without having to use various IPC/RPC methods to bridge the gap.

4.New date / time APIs.

Java 8 implemented its own new date / time API from scratch. The good news is that unlike Calendar.getInstance(), the new APIs were designed with simplicity in mind, and clear operations to operate on manipulated values in both human readable and machine time formats.

5.Concurrent accumulators

One of the most common scenarios in concurrent programming is updating of numeric counters accessed by multiple threads. There have been many idioms to do this over the years, starting from synchronized blocks,read/write locks to AtomicInteger(s).

With Java 8 this problem is solved at the framework level with new concurrent accumulator classes that enable you to very efficiently increase / decrease the value of a counter in a thread safe manner.

Tuesday, February 17, 2015

Is in Daylight Saving Time (DST)? for given date and timezone

Daylight Saving Time (DST) is the practice of turning the clock ahead as warmer weather approaches and back as it becomes colder again so that people will have one more hour of daylight in the afternoon and evening during the warmer season of the year. i.e In the spring when DST starts (= lose one hour), and back one hour when DST ends in the fall (= regain one hour) In java we can find the given date and timezone is in DST. sample code

Monday, February 16, 2015

JAXB sample

JAXB, stands for Java Architecture for XML Binding, using JAXB annotation to convert Java object to / from XML file.

No need of external jar library files. JAXB is bundled in from JDK 1.6.

Basic features :
Marshalling – Convert a Java object into a XML file.
Unmarshalling – Convert XML content into a Java Object.

Model class
create a model class by using jaxb annotation to convert model class into xml file.

Generate/Convert Model object to xml
JAXB marshalling convert customer object into a XML file i.e. jaxbMarshaller.marshal().

Convert XML to Object
JAXB unmarshalling convert a XML file content into a customer object i.e. jaxbMarshaller.unmarshal()

Full source code:

Wednesday, February 11, 2015