Monday 14 May 2018

Producer-Consumer Problem solved using Blocking Queue

The problem can be approached using various techniques
  • Using wait() and notifyAll()
  • Using BlockingQueue
  • Using sempahores

How to use BlockingQueue in code
public class ProducerConsumerBlockingQueue {

  static int MAX_SIZE = 5;
  static BlockingQueue queue = new LinkedBlockingQueue(MAX_SIZE);

  public static void main(String[] args) {

    Producer producer = new Producer();
    Consumer consumer = new Consumer();
    producer.start();
    consumer.start();
  }

  static class Producer extends Thread {
    Random random = new Random();

    public void run() {
      while (true) {
        int element = random.nextInt(MAX_SIZE);
        try {
          queue.put(element);
        } catch (InterruptedException e) {
        }
      }
    }
  }

  static class Consumer extends Thread {
    public void run() {
      while (true) {
        try {
          System.out.println("Consumed " + queue.take());
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }
  }
}

//Output
Producer 2
Producer 3
Consumed 2
Consumed 3
Producer 0
Producer 4
Consumed 0



Tuesday 17 April 2018

How to use Google Translate API in Java application ?

You can do the language translation using Google Translate API. Below is the Java code for integration.

import java.util.Arrays;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.translate.Translate;
import com.google.api.services.translate.model.TranslationsListResponse;
import com.google.api.services.translate.model.TranslationsResource;

public class GoogleTranslationAPISample {
public static void main(String[] arguments) throws GeneralSecurityException, IOException 
    {
        Translate t = new Translate.Builder(
                GoogleNetHttpTransport.newTrustedTransport()
                , GsonFactory.getDefaultInstance(), null)
// Set your application name
                .setApplicationName("sample-Example")
                .build();
        Translate.Translations.List list = t.new Translations().list(
                Arrays.asList(
// Pass in list of strings to be translated
                "Hello World",
                "How to use Google Translate from Java"),
// Target language
                "es"); // es for spanish

// TODO: Set your API-Key from https://console.developers.google.com/
// list.setKey("your-api-key");
        
//list.setKey("AIdwaSyCAKK7htoeT8i8ArmITELoDMyuiorooe5wk-cKs5g"); // my test credentials

        TranslationsListResponse response = list.execute();
        for (TranslationsResource translationsResource : response.getTranslations())
        {
            System.out.println(translationsResource.getTranslatedText());
        }
    }
}

Maven Dependencies :

<dependency>
  <groupId>com.google.cloud</groupId>
  <artifactId>google-cloud-translate</artifactId>
  <version>1.24.1</version>
</dependency>
<dependency>

  <groupId>com.google.api-client</groupId>
  <artifactId>google-api-client-gson</artifactId>
  <version>1.23.0</version>
</dependency>

References :
https://cloud.google.com/vision/docs/libraries
https://github.com/GoogleCloudPlatform/java-docs-samples

Tuesday 27 February 2018

How to Create a Cron Job or Scheduling Function in Tomcat

Scheduling Function or Repeating Job in Tomcat 

Repeating jobs in tomcat can be created by creating a listener which will get started when tomcat is started or new war is deployed and destroyed when tomcat is shutdown.
We can take advantage of thread and infinite loop in which we can do our repetitive work and then wait for specified time and loop again.
This example have been tested in tomcat 8.5.23 and will be applicable for other application server as well.

web.xml 
<listener>
<listener-class>com.test.api.util.NotificationListener</listener-class>
</listener> 

Java class
package com.test.api.util;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class NotificationListener implements ServletContextListener {
    private Thread t = null;
    private ServletContext context;
    public void contextInitialized(ServletContextEvent contextEvent) {
        t =  new Thread(){
            //repeating task
            public void run(){               
                try {
                    while(true){
                        // do all you repeating jobs here.
                       // Example 1. sending reports every 5 mins. 2. sending notifications 3. db cleanup etc.
                       
                        Thread.sleep(1000*60*5); // thread waits for 5 mins.
                    }
                } catch (InterruptedException e) {}
            }           
        };
        t.start(); // starting the thread
        context = contextEvent.getServletContext();
        // context values can be set as well as shown below
        context.setAttribute("TEST_VARIABLE", "VALUE");
    }
    public void contextDestroyed(ServletContextEvent contextEvent) {
        // context is destroyed interrupts the thread
        t.interrupt();
    }           
}

NOTE
1. you can use producer and consume problem approach as well and start them in constructor.



Tuesday 9 January 2018

Configuration and Command to Directoy Deploy to Remote Server through maven

configuration and command to directoy deploy to remote server through maven :
-----------------------------------------------------------------------------
pom.xml configuration :

<build>
<finalName>MYWAR</finalName>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<url>http://XX.XX.XX.XX:8080/manager/text</url>
<username>admin</username>
<password>admin</password>
<path>/MYWAR </path>
</configuration>
</plugin>
</plugins>
</build>

------------------------------------------------------------------------------
maven command :

mvn compile tomcat7:redeploy

------------------------------------------------------------------------------

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
    }
}