Wednesday, November 28, 2018

Thread Pooling In Java Using Executors Class

Most of the Important and most of the developer found one topic in java they perform a task and then they get destroyed. Purpose of multithreading is to perform multiple tasks simultaneously for effective utilization of our resources (time and CPU).


Imagine that there are 10 tasks to perform, so using traditional multithreading mechanism we will need 10 threads. Do you see a drawback in this approach? I see it; creation of a new thread per task will cause resource overhead.

Sunday, September 2, 2018

Remote Debugging of Java Application deployed on AWS Elastic Beanstalk

Most of the time we stuck in the situation where we need to do remote debugging of the application which is running on some server or somewhere other than localhost. We need to debug the code in eclipse. To do that we need to allow the running application to allow remote debugging. 


Generally, we know how to do remote debug in eclipse while the code is running on tomcat. In this post, we will see how to do remote debug when the application is deployed over AWS by elastic beanstalk.



Let's start.

To do Remote debug of AWS deployed the application, we need to follow below steps.

1)We need to Go to AWS Console -> Elastic Beanstalk -> Application -> Configuration

2) Under Configuration you need to go to Software ->Modify ->Container Options 
 Now in Container Options, search for JVM options    In this text box you need to write the below arguments.
-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005
Now, these arguments say that - The remote debug will be listening at 5005 port.

3) Now you need to Go to EC2 Instance running from AWS Console -> EC2

4) After that you need to check which security group is defined for that EC2 Instance, you need to allow this port to communicate outside AWS.

5)For that, you need to add the Port in Inbound and Outbound of the Security Group
   Select the Custom Protocol and define the Port as 5005 and then define Anywhere in Ip accessible.

After this, you will be able to communicate the port with the local debugger of the eclipse.

Now you need to configure the Local Eclipse environment for Remote debugging.


Configure Local Eclipse 


For this you need to go to  Run ->Debug Configuration -> Remote debugging 

Under that define the IP of the application ( you need to find the IP of the application at EC2 Instance Properties )

Define the port as 5005 ( as defined above).

Run the application and hurray, are now connected with the AWS application running.

Now you will be able to debug remotely.

Hope you like the post, If so please share it with your friends and family.

Thanks for reading
Noeik

Saturday, August 18, 2018

Upload File on AWS S3 Using Java

Most of us know nowadays that AWS  is used for almost everything because of its cheap price as well its availability.

AWS S3 is an online storage for storing file and images and zip, literally everything you want to put. 

Most of us have some use cases where we want to upload the image to aws s3 so that it can we used anywhere we want.

#Usercase we need to get the file or Image from UI and need to upload it to AWS S3 using java.

#Approach To Achieve it 
  • first, need to add the AWS SDK for Java 
  • Then we need to Get the client of AWS which is basically creating a connection with AWS 
  • After successfully getting the connection we will use s3 API to put the image as an object in AWS.

We first need to Add the dependency of AWS SDK in our project ( maven dependency as below )

  <dependency>
   <groupId>com.amazonaws</groupId>
   <artifactId>aws-java-sdk</artifactId>
   <version>1.11.388</version>
 </dependency>

After this, we need to have the AWS Account Access key and access_id
you can get it from https://console.aws.amazon.com/iam/home?#/security_credential

Access key file will look like below

[default]
aws_access_key_id=<Your-Access-key_id>
aws_secret_access_key=<Your Secret_access_key>
Note change <Your-Access-key_id> and <Your Secret_access_key> values with your access key.

Now you need to save the access key file at a location below.

~/.aws/credentials on Linux, macOS, or Unix
C:\Users\USERNAME \.aws\credentials on Windows

Now let see the Code for the Uploading of Image /File on AWS.  (Ref : here )
 we will create one jsp file where we create upload file and call the spring controller , under the controller, you can see the file and it will store to the aws s3.




Thyemleaf Html Code

<!DOCTYPE html>
<html xmlns:th="http://thymeleaf.org">
<head>
<title>File Upload Example</title>
<link href="webjars/bootstrap/3.3.7/css/bootstrap.min.css"
 rel="stylesheet" />
<script type="text/javascript" src="webjars/jquery/3.3.1/jquery.min.js"></script>
<script src="webjars/bootstrap/3.3.7/js/bootstrap.min.js"></script>

</head>
<script th:inline="javascript">
 /*<![CDATA[*/
 var _validFileExtensions = [ ".csv", ".zip" ,".png" ];
 function Validate(oForm) {
  var arrInputs = oForm.getElementsByTagName("input");
  for (var i = 0; i < arrInputs.length; i++) {
   var oInput = arrInputs[i];
   if (oInput.type == "file") {
    var sFileName = oInput.value;
    if (sFileName.length == 0) {

     alert("Please select a file to upload");
     return false;
    }
    if (sFileName.length > 0) {
     var blnValid = false;
     for (var j = 0; j < _validFileExtensions.length; j++) {
      var sCurExtension = _validFileExtensions[j];
      if (sFileName.substr(
        sFileName.length - sCurExtension.length,
        sCurExtension.length).toLowerCase() == sCurExtension
        .toLowerCase()) {
       blnValid = true;
       break;
      }
     }

     if (!blnValid) {
      alert("Invalid File Extension");
      return false;
     }
    }
   }
  }

  return true;
 }
  
 /*]]>*/
</script>

<body>

 <div class="container-fluid padding-0">
  <div class="row padding-0">
   
   <div class="col-md-4">
    <h2>File Upload Example</h2>
   </div>
   <div class="col-md-4" align="right"></div>
  </div>
 </div>
 <nav role="navigation" id="trainingset-container-id"
  class="navbar navbar-default">
  <div class="row" style="margin-top: 10px;">
   <div class="col-md-2">
    <B>Upload File</B>
   </div>
   <div class="col-md-6">
    <form method="POST" action="/upload"
     onsubmit="return Validate(this);" enctype="multipart/form-data">
     <div class="col-sm-6">

      <input type="file" name="file"  />
     </div>
     <div class="col-sm-6">
      <input type="submit" class="btn btn-success btn-sm" value="Upload data" />
     </div>
    </form>
   </div>
   
  </div>
 </nav>
  <div id="messageboxid">
   <div id="uploadstatus" th:if="${message}">
    <B>Status Of Uploaded File</B>
    <h6 th:text="${message}" />
   </div>
  </div>
  
</body>
</html>
This will see like this

Now we will see the Upload Controller Code.

Upload Controller.java

package com.programinjava.learn.controller;

import java.io.InputStream;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;

@Controller
public class UploadController {
 
 @PostMapping("/upload")
 public String singleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {


  if (file.isEmpty()) {
   redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
   return "redirect:uploadStatus";
  }
//  bucket name 
  String bucketName ="atserve-photos";
//  get it from user or change it 
  String nameOffile ="myPhoto";
//  getting aws access 
  AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
                .withRegion(Regions.AP_SOUTH_1)
                .withCredentials(new ProfileCredentialsProvider())
                .build();
  boolean isBucketExist =s3Client.doesBucketExist(bucketName);
  if(!isBucketExist) {
   s3Client.createBucket(bucketName);
  }
  try {
   InputStream is = file.getInputStream();
   s3Client.putObject(new PutObjectRequest(bucketName,nameOffile,is,new ObjectMetadata()).withCannedAcl(CannedAccessControlList.PublicRead));
   redirectAttributes.addFlashAttribute("message", "SuccessFully Uploaded On AWS S3");
  }catch(Exception e) {
   e.printStackTrace();
  }
  return "redirect:/uploadStatus";
 }
 
 @GetMapping("/uploadStatus")
 public String uploadStatus(ModelMap m) {
  return "Homepage";
 }
 
 @GetMapping("/upload")  
 public String displayHomePageForAlarm() {
  return "Homepage";
 }

}

Let see what we get on AWS S3

So this is how we can see the myPhoto is now uploaded on AWS S3.

DOWNOAD THE CODE :


Also, learn

Wednesday, August 8, 2018

Mocking of static method in unit testing


While we do unit testing, we mostly encounter the situation where we need to do the unit testing of a method which is calling a static method. if we are using mockito for doing mocking, We will have to suffer as mockito don't provide Static method mocking.


Let's see in a simple manner what is required and how we achieve it.

# Objective: We need to mock the static class which is being used in a method for which we are writing unit test.

# Solution: We have to use Powermockito for that 

What is PowerMockito?
PowerMockito is a PowerMock’s extension API to support Mockito. It provides capabilities to work with the Java Reflection API in a simple way to overcome the problems of Mockito, such as the lack of ability to mock final, static or private methods.

Getting Start with Powermockito

Also read: JUnit Tests Basics and how to do unit testing in java

First, you need to add the dependency in pom.xml

<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-module-junit4</artifactId>
    <version>1.6.4</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-api-mockito</artifactId>
    <version>1.6.4</version>
    <scope>test</scope>
</dependency>
Now as you are using powermockito , you need to change the JUNIT Runner class as
@RunWith(PowerMockRunner.class)
@PrepareForTest(<StaticClassName>.class)
<StaticClassName> will be replace with you static class Name.

Now let see the example.


Project Structure
Now let see the class for with we will write test case.

public class Rectangle {
 
 public int getAreaOfRectangle(int length , int breadth) {
  return AreaFinder.findArea("rectangle", length, breadth);
 }

}

The Static Class

public class AreaFinder {
 public static int findArea(String type , int length , int breadth) {
  if(type.equals("rectangle")) {
   return length*breadth;
  }else if(type.equals("square")) {
   return length*length;
  }else {
   return 0;
  }

 }

}

Test Class

@RunWith(PowerMockRunner.class)
@PrepareForTest(AreaFinder.class)      // need to add the static class for which you mock the method
public class RectangleTest {

 @Test
 public void getAreaOfRectangleTest() {
  Rectangle rec = new Rectangle();
  int length =10;
  int breadth =20;

  PowerMockito.mockStatic(AreaFinder.class);   // mocking of static class
  PowerMockito.when(AreaFinder.findArea("rectangle", length, breadth)).thenReturn(200); // defining behaviour
  Assert.assertEquals(200, rec.getAreaOfRectangle(length, breadth));
 }

}

When you run this you will be able to see the test will be run successfully and it will get passed.

If you have any issue regarding the above concept, please let us know.

I hope this will help you in understand how to do mocking of static method in  unit testing.

Thanks for reading
Noeik

Friday, July 20, 2018

producer consumer problem implementation using wait notify methods.

producer-consumer problem using wait notify

Most of you have heard about the Producer-Consumer problem where one is producing something and another is consuming it.


So basically what actually the producer-consumer problem says 

Producer-Consumer Problem says that if we have a shared resource among 2 threads, and producer's job is to generate the data and put it in the buffer and consumer's job is to take the data from the buffer but then where is the problem? So problem is there should not be a scenario where the producer has produced the data more than the buffer size, which results in overflow problem also consumer should not consume all the data in the buffer and again try, which result in underflow problem. 
So basically its a multi-thread synchronization problem.

Read about: Concurrency CountDownLatch in java

Now, what is the solution?
We can use wait-notify mechanism to solve this problem of synchronization.



Approach 
  1. We will have 2 thread one is to produce random data and second will get the random data from the shared LinkedList (or and queue).
  2. we will write on a class called processor where there will be 2 methods one is produce() and second will be consume () 
  3. In produce() method we will write random generator and also be checking whether the size of linked list is less than 10 or not if greater we will call wait method over the object called lock which we are using for the locking mechanism.
  4. when produce() put the data in linkedlist it will call lock.notify() which will notify the second thread that there are some data stored in the linked list.
  5. now in consume() we will have a check for the linked list size should not be 0 if so we will call lock.wait() else we will take the data from the list and notify the producer().
Now let see the implementation of the above approach.

learn more about wait notify ()

#Implemenation

Processor.java (this class will have the produce() and consume() method in it )

class Processor {
 
 LinkedList<Integer> list = new LinkedList<>();
 Object lock = new Object();
 int value =0;
 
 public void produce() throws InterruptedException{
  
  while(true)
  {
   synchronized (lock) {
    
    while(list.size() == 10)
     lock.wait();
    
    list.add(value++);
    lock.notify();
    
   }
  }
  
 }
 
 public void consume() throws InterruptedException {
  
  Random random = new Random();
  while(true){
  synchronized (lock) {
  
   while(list.size() == 0)
    lock.wait();
   int i =list.removeFirst();
   lock.notify();
   System.out.println("Got the value "+i + "now the list size is "+list.size());
   
   
   
  }
  Thread.sleep(random.nextInt(1000));
  
  }
  
  
 }
}

Now we will see the 2 thread class and how we are calling them.

ProducerConsumerWithWaitNotify.Java

public class ProducerConsumerWithWaitNotify {
 
 public static void main(String[] args) {
  Processor pro = new Processor();
  Thread t1 = new Thread(new Runnable() {
   
   @Override
   public void run() {

    try {
     pro.produce();
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
  });
  Thread t2 = new Thread(new Runnable() {
   
   @Override
   public void run() {

    try {
     pro.consume();
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
  });
  
  
  t1.start();
  t2.start();
 }
 

}

After executing the code what will be the result, It will be like below

Got the value 0now the list size is 9
Got the value 1now the list size is 9
Got the value 2now the list size is 9
Got the value 3now the list size is 9
Got the value 4now the list size is 9
Got the value 5now the list size is 9
Got the value 6now the list size is 9
Got the value 7now the list size is 9
Got the value 8now the list size is 9
Got the value 9now the list size is 9
Got the value 10now the list size is 9
Got the value 11now the list size is 9
Got the value 12now the list size is 9
Got the value 13now the list size is 9
Got the value 14now the list size is 9

I hope this will help you in understanding the producer-consumer problem implementation using wait notify method in java

If you have any issue or concern, please leave us a comment, will be happy to help

Thanks for reading
noeik

Thursday, July 19, 2018

Comparator interface and its example in java


In our previous post we have learn about what is comparable , In this article we will see basics about Comparator.


#What is Comparator ?
Comparator is a interface which is used to order the different user defined objects. When we have 2 object of different classes we want to order them we will use comparator.

Learn about What is Comparable?

#UserCase :
We have an array of person , we want to sort them on different basis , like on the basis of age of the person , or on the basis of name of the person. there are 2 questions comes in our mind , can we use comparable , - No ( as we can only compare on one of the 2 basis not both) , can we use comparator - Yes .




Approach 

  1. We will first create one person class .
  2. Now we will create 2 different Custom Comparator classes which will implements Comparator<person>
    1. One will be AgeComparator.
    2. Second will be NameComparator.
  3. Now we will create one Main class where we will create list of person. and then we will use Collections.sort and pass the list along with the comparator , we want to use for sorting.
Implementation

Person.java

class Person{
 
 int age;
 String name;
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 @Override
 public String toString() {
  return "Person [age=" + age + ", name=" + name + "]";
 }
 
 
 
}
AgeComparator.java

class AgeComparator implements Comparator<Person>{

 @Override
 public int compare(Person arg0, Person arg1) {
  // TODO Auto-generated method stub
  return arg0.getAge() - arg1.getAge();
 }
 
}
NameComparator.java

class NameComparator implements Comparator<Person>{

 @Override
 public int compare(Person o1, Person o2) {
  // TODO Auto-generated method stub
  return o1.getName().compareTo(o2.getName());
 }
 
}

Main Class

public class ComparatorDemo {
 public static void main(String[] args) {
  List<Person> list = new ArrayList<>();
  Person p1 = new Person();
  p1.setAge(35);
  p1.setName("vishal");
  
  Person p2 = new Person();
  p2.setAge(45);
  p2.setName("rohan");
  
  
  list.add(p2);
  list.add(p1);
  
  
//  Collections.sort(list,new AgeComparator());
  Collections.sort(list,new NameComparator());
  list.forEach(s-> System.out.println(s));
 }
 
}

Result 

Person [age=45, name=rohan]
Person [age=35, name=vishal]

Here we can see that the Objects are sorted on the basis of name , we can also do it by using age comparator as well.

If you have any issue , Please let us know , if you want any other topic to be covered in our next article please leave us a comment.

If you like this article please share it with your friends as well.

Thanks for reading
noeik

Saturday, July 14, 2018

Comparable and its example in java

comparable interface and its example

Most of us have heard about comparable and most of you also know what is comparable,
What is a comparable interface?
Comparable interface is used to sort the objects on the basis of any one variable, It is found in java.lang package and contain only one method compareTo(Object o).

In java When we have a scenario where we need to sort the array of objects on the basis of there member variable, or to eligible the objects to compare we use Comparable.

There are some good interview questions are there related to the comparable interface.

In this article, we will see one example of the implementation of the comparable interface and its explanation.



#Objective - We have a list of student and we need to sort the list on the bases of student ages in ascending order.

#Approach
  • We will implement the Comparable interface in the student class.
  • we will override the compareTo() method and write the logic for that 
  • As compareTo() method return 
    • 1 when own variable is greater than compared object variable.
    • 0 when both are equal
    • -1 when the own variable is less than compared object variable.
Now let see the implementation.
Below is the Student class

package com.programinjava.learning.comparable;


//implementing the comparable interface
public class Student implements Comparable<Student>{
 
 
 private int age;
 private String name;
 
 
 

 public int getAge() {
  return age;
 }




 public void setAge(int age) {
  this.age = age;
 }




 public String getName() {
  return name;
 }




 public void setName(String name) {
  this.name = name;
 }

 @Override
 public int compareTo(Student o) {
  return this.getAge() - o.getAge();
 }




 @Override
 public String toString() {
  return "Student [age=" + age + ", name=" + name + "]";
 }
 
 

}
Now we will see the Main Demo class

ComparableDemo.java
package com.programinjava.learning.comparable;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ComparableDemo {
 
 public static void main(String[] args) {
  
  
  
//  creating list of student with different name and age
  List<Student> list = new ArrayList<>();
  Student s1 = new Student();
  s1.setAge(10);
  s1.setName("student 1");
  
//  second
  Student s2 = new Student();
  s2.setAge(20);
  s2.setName("student 2");
//  third
  
  Student s3 = new Student();
  s3.setAge(30);
  s3.setName("student 3");
  
//  fourth
  Student s4 = new Student();
  s4.setAge(40);
  s4.setName("student 4");
  
//  fifth
  Student s5 = new Student();
  s5.setAge(50);
  s5.setName("student 5");
  
  list.add(s2);
  list.add(s1);
  list.add(s4);
  list.add(s3);
  list.add(s5);
  
  System.out.println("Printing before sorting the list");
  list.forEach(s->System.out.println(s));
  
//  sorting the list 
  Collections.sort(list);
  System.out.println();
  
  System.out.println("Printing after sorting the list");
  list.forEach(s->System.out.println(s));
  
  
 }

}
Result Looks like below
Printing before sorting the list
Student [age=20, name=student 2]
Student [age=10, name=student 1]
Student [age=40, name=student 4]
Student [age=30, name=student 3]
Student [age=50, name=student 5]

Printing after sorting the list
Student [age=10, name=student 1]
Student [age=20, name=student 2]
Student [age=30, name=student 3]
Student [age=40, name=student 4]
Student [age=50, name=student 5]

I hope this will help you in understand how to implement comparable and when to implement it.

There are some other topics if you want to explore


Conditional Logic in java
Loops in java
Arrays in java
Wrapper classes in java
Methods in java
Object Oriented Practices
Inheritance in java

If you have any issue, please leave us a comment, if you like it, please share it with your friends

Thanks for reading 
noeik