Tuesday, 18 April 2017

JAVA ---> Generating unique IDs

To generate UUID in Java we can use the java.util.UUID class. This class was introduced in JDK 1.5. The UUID.randomUUID() method return a UUID object.

A Sample Java Program for Generating Unique IDs :
import java.util.UUID;
public class GeneratingUniqId {
public static void main(String[] args) {
            UUID testId1 = UUID.randomUUID();
   UUID testId2 = UUID.randomUUID();
   System.out.println("UUID One: " + testId1);
   System.out.println("UUID Two: " + testId2);

}
}

Sunday, 26 February 2017

java - How to make an executable jar using maven with all dependencies added ?


Creating an executable jar file through maven with all dependecies added :
Requirement :
To pack a little app with all dependencies [external jars ] through maven and run it from the console.

maven-assembly-plugin can be used to assemble all the dependent jar into the same executable jar so that we do not need to pass the classpath of dependent jars while running the executable jar.

To do it just add the following to pom.xml and make sure we write the correct path to our main class.

 <build>
     <plugins>
       <plugin>
         <artifactId>maven-assembly-plugin</artifactId>
         <configuration>
           <archive>
             <manifest>
               <mainClass>com.test.MavenBuildTest</mainClass>
             </manifest>
           </archive>
           <descriptorRefs>
             <descriptorRef>jar-with-dependencies</descriptorRef>
           </descriptorRefs>
         </configuration>
         <executions>
           <execution>
             <id>make-assembly</id>
             <phase>package</phase>
             <goals>
               <goal>single</goal>
             </goals>
           </execution>
         </executions>
       </plugin>
       <plugin>
         <groupId>org.apache.maven.plugins</groupId>
         <artifactId>maven-compiler-plugin</artifactId>
         <version>2.5.1</version>
         <inherited>true</inherited>
         <configuration>
           <source>1.7</source>
           <target>1.7</target>
         </configuration>
       </plugin>
     </plugins>
   </build>
 

When the maven package gets executed, two .jar files will be created.
The one with the text jar-with-dependencies on its name,
will contain is the one we should run. To do it, just go to the terminal,
navigate to it(inside the target folder) and type the command:
 java -jar myapp-jar-with-dependencies.jar

Here is complete pom Example:

 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>MavenBuildTest</groupId>
  <artifactId>MavenBuildTest</artifactId>
  <version>1.0-SNAPSHOT</version>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
     <plugin>
       <artifactId>maven-compiler-plugin</artifactId>
       <version>3.1</version>
       <configuration>
         <source>1.7</source>
         <target>1.7</target>
       </configuration>
     </plugin>
    <plugin>
         <artifactId>maven-assembly-plugin</artifactId>
         <configuration>
           <archive>
             <manifest>
               <mainClass>MavenBuildTest</mainClass>
             </manifest>
           </archive>
           <descriptorRefs>
             <descriptorRef>jar-with-dependencies</descriptorRef>
           </descriptorRefs>
         </configuration>
         <executions>
           <execution>
             <id>make-assembly</id>
             <phase>package</phase>
             <goals>
               <goal>single</goal>
             </goals>
           </execution>
         </executions>
       </plugin>
        </plugins>
<finalName>MavenBuildTest</finalName>
  </build>
  <dependencies>
       <dependency>
          <groupId>org.postgresql</groupId>
           <artifactId>postgresql</artifactId>
           <version>9.4-1201-jdbc4</version>
            </dependency>
     <dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.4.1.3</version>
  <!-- <scope>system</scope>
  <systemPath>${basedir}\src\lib\jackson-databind-2.4.1.3.jar</systemPath> -->
 </dependency>
 <dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-annotations</artifactId>
  <version>2.4.1</version>
  <!-- <scope>system</scope>
  <systemPath>${basedir}\src\lib\jackson-annotations-2.4.1.jar</systemPath> -->
 </dependency>
 <dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-core</artifactId>
  <version>2.4.1.1</version>
  <!-- <scope>system</scope>
  <systemPath>${basedir}\src\lib\jackson-core-2.4.1.1.jar</systemPath> -->
 </dependency>
 <!-- https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple -->
<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <version>1.1.1</version>
   <!--  <scope>system</scope>
    <systemPath>${basedir}\src\lib\json-simple-1.1.1.jar</systemPath> -->
</dependency>

    </dependencies>
<packaging>jar</packaging>
</project>

Tuesday, 31 January 2017

Calling Https url from Java Code

Java code snipet for hitting Https url from Java code ::

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class TestHitSSL {

    public static void main(String[] args) throws Exception {
        // Need to create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } };
        // Installing the all-trusting trust manager
        final SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        // Create all-trusting host name verifier
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };

        // Installing the all-trusting host verifier
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

        URL url = new URL("https://www.google.com"); // test https url
        URLConnection con = url.openConnection();  //opening the url connection to test url
     
        final Reader reader = new InputStreamReader(con.getInputStream());
        final BufferedReader br = new BufferedReader(reader);      
        String message = "";
        while ((message = br.readLine()) != null) // reading the line from InputStream
    {
            System.out.println(message );
        }      
        br.close(); //closing the BufferedReader
    }
}

Monday, 30 January 2017

Yesterday's Date using Java code

Java code snipet for Yesterday's Date :

We can use Calendar class to do this job.

                                Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");
Date date = cal.getTime();
System.out.println(df2.format(date));
String dateForConsultation = df2.format(date);

Sunday, 29 January 2017

MD5 Hash Code Encription

Java Code Snipet for MD5 Encription :

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public  String md5(final String s) {
        final String MD5 = "MD5";
        try {
            // Create MD5 Hash
            MessageDigest digest = java.security.MessageDigest
                    .getInstance(MD5);
            digest.update(s.getBytes());
            byte messageDigest[] = digest.digest();

           // Create Hex String
            StringBuilder hexString = new StringBuilder();
            for (byte aMessageDigest : messageDigest) {
                String h = Integer.toHexString(0xFF & aMessageDigest);
                while (h.length() < 2)
                    h = "0" + h;
                hexString.append(h);
            }
            return hexString.toString();

       } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

Base64 Decode and Encode

Java Code snipet for Base64 Encode and Decode

import org.apache.commons.codec.binary.Base64;

// Encode data on your side using BASE64
byte[]   bytesEncoded = Base64.encodeBase64(str .getBytes());
System.out.println("ecncoded value is " + new String(bytesEncoded ));

// Decode data on other side, by processing encoded data
byte[] valueDecoded= Base64.decodeBase64(bytesEncoded );
System.out.println("Decoded value is " + new String(valueDecoded));


Maven Dependencies :
<!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.9</version>
</dependency>