Skip to main content

23 posts tagged with "Java"

View All Tags

Install Oracle JDK on Ubuntu

· 2 min read
  1. Download the jdk-8u60-linux-x64.tar.gz from the Oracle site (Download 64bit or 32bit based on your linux environment).

  2. If you have root access then install java system-wide inside /usr/local directory.

First create a directory named java inside /usr/local

sandeep@vivan:~$ sudo mkdir /usr/local/java/

after that change directory

sandeep@vivan:~$ cd /usr/local/java/

Note: If you do not have access to root then install java inside your home directory.

  1. Unpack the tarball and install Java
sandeep@vivan:/usr/local/java$ sudo tar zxvf ~download/jdk-8u60-linux-x64.tar.gz

The Java files are installed in a directory /usr/local/java/jdk1.8.0_60/

  1. Install the new Java source in system:
sudo update-alternatives --install /usr/bin/javac javac /usr/local/java/jdk1.8.0_60/bin/javac 1
sudo update-alternatives --install /usr/bin/java java /usr/local/java/jdk1.8.0_60/bin/java 1
sudo update-alternatives --install /usr/bin/javaws javaws /usr/local/java/jdk1.8.0_60/bin/javaws 1
  1. Choose default Java:
sudo update-alternatives --config javac
sudo update-alternatives --config java
sudo update-alternatives --config javaws
  1. Check the Java version:
java -version
Output
java version "1.8.0_60"
Java(TM) SE Runtime Environment (build 1.8.0_60-b27)
Java HotSpot(TM) 64-Bit Server VM (build 25.60-b23, mixed mode)
  1. Verify the symlinks all point to the new Java location:
ls -la /etc/alternatives/java*
Output
lrwxrwxrwx 1 root root 36 Sep 24 19:27 /etc/alternatives/java -> /usr/local/java/jdk1.8.0_60/bin/java
lrwxrwxrwx 1 root root 37 Sep 24 15:00 /etc/alternatives/javac -> /usr/local/java/jdk1.8.0_60/bin/javac
lrwxrwxrwx 1 root root 38 Sep 24 15:06 /etc/alternatives/javaws -> /usr/local/java/jdk1.8.0_60/bin/javaws

Note: For Setting Java HOME on Ubuntu follow the

Execute N number of threads one after another in cyclic way

· 2 min read

This is a famous interview question how to execute 3 or n threads one after another and performing a job like :-

Thread T1 prints then Threads T2 print and then .... Thread Tn
then again Thread T1 prints then Threads T2 print and then .... Thread Tn and so on....

T1 -> T2 -> ... -> Tn; and then again T1 -> T2 -> ... -> Tn


CyclicExecutionOfThreads.java

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CyclicExecutionOfThreads
{

public static void main(String args[])
{

int totalNumOfThreads = 10;
PrintJob printJob = new PrintJob(totalNumOfThreads);

/*
* MyRunnable runnable = new MyRunnable(printJob, 1); Thread t1 = new
* Thread(runnable);
*
* MyRunnable runnable2 = new MyRunnable(printJob, 2); Thread t2 = new
* Thread(runnable2);
*
* MyRunnable runnable3 = new MyRunnable(printJob, 3); Thread t3 = new
* Thread(runnable3);
*
* t1.start(); t2.start(); t3.start();
*/

// OR
ExecutorService executorService = Executors.newFixedThreadPool(totalNumOfThreads);
Set<Runnable> runnables = new HashSet<Runnable>();

for (int i = 1; i <= totalNumOfThreads; i++)
{
MyRunnable command = new MyRunnable(printJob, i);
runnables.add(command);
executorService.execute(command);
}

executorService.shutdown();
}
}

class MyRunnable implements Runnable
{

PrintJob printJob;
int threadNum;

public MyRunnable(PrintJob job, int threadNum)
{
this.printJob = job;
this.threadNum = threadNum;
}

@Override
public void run()
{
while (true)
{
synchronized (printJob)
{
if (threadNum == printJob.counter)
{
printJob.printStuff();

if (printJob.counter != printJob.totalNumOfThreads)
{
printJob.counter++;
} else
{

System.out.println();
// reset the counter
printJob.resetCounter();
}

printJob.notifyAll();

} else
{
try
{
printJob.wait();
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}

}
}
}

class PrintJob
{
int counter = 1;
int totalNumOfThreads;

PrintJob(int totalNumOfThreads)
{
this.totalNumOfThreads = totalNumOfThreads;
}

public void printStuff()
{
System.out.println("Thread " + Thread.currentThread().getName() + " is printing");

try
{
Thread.sleep(1000);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}

public void resetCounter()
{
this.counter = 1;
}
}
Output
Thread pool-1-thread-1 is printing
Thread pool-1-thread-2 is printing
Thread pool-1-thread-3 is printing

Thread pool-1-thread-1 is printing
Thread pool-1-thread-2 is printing
Thread pool-1-thread-3 is printing

Thread pool-1-thread-1 is printing
Thread pool-1-thread-2 is printing
Thread pool-1-thread-3 is printing

Thread pool-1-thread-1 is printing
Thread pool-1-thread-2 is printing
Thread pool-1-thread-3 is printing

DelayQueueExample Example

· 2 min read
DelayQueueExample.java
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class DelayQueueExample
{

public static void main(String[] args)
{

BlockingQueue<DelayedElement> blockingQueue = new DelayQueue<DelayedElement>();

try
{
blockingQueue.put(new DelayedElement(4000, "Message with delay 4s"));
blockingQueue.put(new DelayedElement(2000, "Message with delay 2s"));
blockingQueue.put(new DelayedElement(9000, "Message with delay 9s"));
} catch (InterruptedException ie)
{
}

while (!blockingQueue.isEmpty())
{
try
{
System.out.println(">>" + blockingQueue.take());
} catch (InterruptedException ie)
{
}
}
}
}

class DelayedElement implements Delayed
{

private long duration = 0;
private String message;

public DelayedElement(long duration, String name)
{
this.duration = System.currentTimeMillis() + duration;
this.message = name;
}

@Override
public int compareTo(Delayed o)
{

return (int) (this.duration - ((DelayedElement) o).getDuration());
}

/*
* Expiration occurs when an element's getDelay(TimeUnit unit) method
* returns a value less than or equal to zero.
*/
@Override
public long getDelay(TimeUnit unit)
{
long diff = duration - System.currentTimeMillis();
return unit.convert(diff, TimeUnit.MILLISECONDS);
}

public long getDuration()
{
return duration;
}

public void setDuration(long duration)
{
this.duration = duration;
}

public String getMessage()
{
return message;
}

public void setMessage(String message)
{
this.message = message;
}

@Override
public String toString()
{
return "DelayedElement [duration=" + duration + ", message=" + message + "]";
}
}
Output
>>DelayedElement [duration=1436431881725, message=Message with delay 2s]
>>DelayedElement [duration=1436431883725, message=Message with delay 4s]
>>DelayedElement [duration=1436431888725, message=Message with delay 9s]

ExecutorService InvokeAll Example

· One min read
ExecutorInvokeAllExample.java
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ExecutorInvokeAllExample
{

public static void main(String[] args) throws InterruptedException, ExecutionException
{
ExecutorService executorService = Executors.newSingleThreadExecutor();

Set<Callable<String>> callables = new HashSet<Callable<String>>();

callables.add(new CallableTask("Hello 1"));
callables.add(new CallableTask("Hello 2"));
callables.add(new CallableTask("Hello 3"));

List<Future<String>> futures = executorService.invokeAll(callables);

for (Future<String> future : futures)
{
System.out.println("future.get = " + future.get());
}
executorService.shutdown();
}
}

class CallableTask implements Callable<String>
{

String message;

public CallableTask(String message)
{
this.message = message;
}

@Override
public String call() throws Exception
{
return message;
}
}

Convert java.util.Collection to java.util.List

· One min read
Sandeep Bhardwaj
List list;  
if (collection instanceof List)
{
list = (List)collection;
}
else
{
list = new ArrayList(collection);
}

Generic way (java 1.5<=)

public <E> List<E> collectionToList(Collection<E> collection)  
{
List<E> list;
if (collection instanceof List)
{
list = (List<E>) collection;
}
else
{
list = new ArrayList<E>(collection);
}
return list;
}

Without Generics (java 1.4>=)

public List collectionToList(Collection collection)  
{
List list;
if (collection instanceof List)
{
list = (List) collection;
}
else
{
list = new ArrayList(collection);
}
return list;
}

How to convert java.util.List to java.util.Set

· One min read
Sandeep Bhardwaj

Removing duplicate items from a list is pretty simple in java just convert the list to java.util.Set it will automatically remove the duplicate items and create a set for you.

Syntax

Set<E> alphaSet  = new HashSet<E>(<your List>);  

Example

import java.util.ArrayList;  
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class ListToSet
{
public static void main(String[] args)
{
List<String> alphaList = new ArrayList<String>();
alphaList.add("A");
alphaList.add("B");
alphaList.add("C");
alphaList.add("A");
alphaList.add("B");
System.out.println("List values .....");
for (String alpha : alphaList)
{
System.out.println(alpha);
}
Set<String> alphaSet = new HashSet<String>(alphaList);
System.out.println("\nSet values .....");
for (String alpha : alphaSet)
{
System.out.println(alpha);
}
}
}

Comparing two list and removing duplicate elements

· One min read

Comparing two list and removing duplicate elements.

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

public class CheckList
{

public static void main(String[] args)
{

List<string> a = new ArrayList<string>();
a.add("a");
a.add("b");

List<string> b = new ArrayList<string>();
b.add("c");
b.add("a");
b.add("d");
b.add("f");

b.removeAll(a);

for (String str : b)
{
System.out.println(str);
}
}
}

Common BeanUtils to set html form values in Java Bean

· 4 min read
Sandeep Bhardwaj

Hi All,
Today I am going to discuss about a important jar commons-beanutils used by struts framework and demonstrating how to use this important jar in our servlet and jsp project.

If you worked with struts1 or struts2 then you noticed that the ActionForm or Action (in Struts2) linked with your Jsp page or html page when you clicked on submit button the values of html form with same property name is set by calling the setter method of your POJO or FormBean automatically.

But when we worked with only servlet and Jsp without using any MVC framework then we need to set the values using below line :-

String userName=request.getParameter(“userName”);

If we had 10 field on a form then we need to create 10 variables and we have to write the above line 10 times by passing the form filed name as argument.

Also another problem then we have to cast the filed values according to our need like

int age=Integer.parseInt(request.getParameter(“age”));  

About application


This application contains a simple form a Java Bean and a Servlet to display the form values submitted by user using Common BeanUtils jar.

  1. Simple Jsp with two input boxes and a submit button.
  2. LoginForm simple Java bean containing setter and getters of form fields.
  3. FormUtil class used to set the Jsp form values in Java Bean.
  4. LoginActionServlet to process from values.

Package Structure

jar needed

index.jsp


index.jsp containing a form with username and password textboxes and a submit button. When user clicked on submit button LoginActionServlet called.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<form action="loginActionServlet" method="post">
<table>
<tbody>
<tr>
<td>Username</td>
<td>
<input name="userName" type="text">
</td>
</tr>
<tr>
<td>Password</td>
<td>
<input name="password" type="password">
</td>
</tr>
<tr>
<td>
<input type="submit">
</td>
</tr>
</tbody>
</table>
</form>

LoginForm.java


LoginForm class with setters and getters of userName and password these fields names are same as form fields in jsp.

package form;

public class LoginForm {

private String userName;
private String password;

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}
}

FormUtil.java


FormUtil class used BeanUtils class populate method for setting the form values in Java beans. I made this class a generic class so that we do not need to write same lines again and again in each servlet, just we need to pass the class of java bean and request in populate method of FormUtil.
LoginForm loginForm = FormUtil.populate(LoginForm.class, request);

package util;

import java.lang.reflect.InvocationTargetException;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.beanutils.BeanUtils;

public class FormUtil {

public static <T> T populate(Class<T> clazz, HttpServletRequest request) {
T object = null;
try {

object = (T) clazz.newInstance();
BeanUtils.populate(object, request.getParameterMap());

} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return object;
}
}

LoginActionServlet.java


LoginActionServlet used to process the values of LoginForm and display the values.

package action;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import util.FormUtil;
import form.LoginForm;

public class LoginActionServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {

PrintWriter out = response.getWriter();

LoginForm loginForm = FormUtil.populate(LoginForm.class, request);

out.println("User name is :" + loginForm.getUserName());
out.println("Password is :" + loginForm.getPassword());

}
}

web.xml


web.xml with LoginActionServlet servlet mapping.

<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemalocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>DemoApp</display-name>
<servlet>
<display-name>LoginActionServlet</display-name>
<servlet-name>LoginActionServlet</servlet-name>
<servlet-class>action.LoginActionServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginActionServlet</servlet-name>
<url-pattern>/loginActionServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

Now paste these files according to package structure and run it by typing http://localhost:8080/DemoApp.

Enum in java

· One min read
Sandeep Bhardwaj

Enum: Get value using enum

enum Day {  
SUNDAY(1), MONDAY(2), TUESDAY(3), WEDNESDAY(4), THURSDAY(5), FRIDAY(6), SATURDAY(7);
private final int dayCode;
private Day(int dayCode)
{
this.dayCode = dayCode;
}
public int getCode() { return dayCode; }
}

public class EnumValueOfDay {
public static void main(String[] args) {

Day day = Day.SUNDAY;
System.out.println("Day = " + day.getCode());
}
}

also you can use enum in this way to get the value of enum . Here is one more example to print the names by using toString method.

enum Name {  
S("Sandeep"),
A("Aditya") ,
R("Rambrij"),
M("Meenakshi");

private final String name;

private Name(String name) {
this.name = name;
}

public String toString() {
return name;
}
}

public class NameDisplay {
public static void main(String[] args) {

Name name = Name.A;
System.out.println("Name = " + name);
}
}

Varargs:- Variable argument method in Java 5

· One min read

Varargs enables to write methods which can takes variable length of arguments.Varargs was added in Java 5 and the syntax includes three dots … provides the functionality to pass any number of arguments to a method.

Syntax

public void showDepartmentEmp(int deptCode, String... deptEmp){}
Example
public class Department {

public static void main(String args[]) {
showDepartmentEmp(100, "Sandeep", "Gaurav");
showDepartmentEmp(111, "Meenakshi", "Aditya", "Saurabh");
}

public static void showDepartmentEmp(int deptCode, String... deptEmp) {
System.out.print("\n"+deptCode);
for(String emp: deptEmp) {
System.out.print(", " + emp);
}
}
}