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

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