Java @ Desk

Java @ Desk

Breaking

Wednesday, November 23, 2016

Jquery show hide by id in Javascript

8:31 AM 0
Jquery show hide in Javascript

show and hide the UI elements using the id attribute of the html element.
hide() - Jquery method to hide the field
show() - Jquery method to show the field

To use the inbuilt function in JS, following library must be included in the HTML file
1) jquery.min.js

Here is the sample html code to show hide the image

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery.min.js"></script>

<script type="text/javascript">

function showImage() {
 $("#processNewImage").show();
}
function hideImage() {
 $("#processNewImage").hide();
}
</script>

</head>
<body>
 <div style="height: 40px;"></div>

 <div>
  <button onclick="showImage();">Show Image</button>
  <button onclick="hideImage();">Hide Image</button>
 </div>

 <div style="height: 40px;"></div>

 <div>
  <img src="images/giphy.gif" id="processNewImage"
   name="processNewImage">
 </div>
</body>
</html>

Tuesday, November 25, 2014

How can we create a deep copy of an object in Java

10:15 AM 0
How can we create a deep copy of an object in Java?

Copying objects in Java

There are two ways of creating copies of objects (and arrays) in Java:
1. Shallow Copy
2. Deep Copy

What is "Deep Copy"?

A deep copy copies all fields, and makes copies of inner objects as well (unlike creating a copy of the memory address of the inner object). A deep copy occurs when an object, along with all the objects to which it refers, is copied as a whole. After a deep copy, if we change the property of the inner object in the copied object, it will not affect the respective property of the inner object in the original object.

How can we create a deep copy of an object?

We can achieve deep copy in 3 ways.
1. Serialize and de-serialize
2. Clone the Object correctly
3. Copy Constructor

If the object which we need to deep copy is simple, we can go for either the copy constructor approach or we can implement the clone correctly. But in most cases we will need to deep copy various objects of various complexities. The object graph may be much more complex which results in increased complexity of both the copy constructor and the clone methods. In this case we can go for the serialization approach. By using serialization, we can create deep copies of any object s that adhere to a set of rules by just one function.

Rules for deep copy using serialization to work correctly
1. All classes in the object graph should be serializable
2. Serialization should not be overridden such that new instances are not created, e.g. for singletons.

How to implement serialization?
We need to use a common utility class and provide a static method that will serialize and de-serialize the object, thus creating a deep copy of that object, and then return the copy. Serialization and deserialization of the object ensures that all the classes in the object graph are recreated in a new heap location.

Sample code illustrating deep copy through serialization/deserialization:

/**
 * Util Class
 *
 */
class CommonUtil{
 
 /**
  * Method to provide deep copy
  * @param obj - Object to be deep copied
  * @return Deep copied Object
  * @throws IOException
  * @throws ClassNotFoundException
  */
 public static <T extends Object> T getCopy(T obj) throws IOException, ClassNotFoundException{
  
  ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream();
  ObjectOutputStream objectOutStream = new ObjectOutputStream                                 (byteOutStream);
  objectOutStream.writeObject(obj);
  objectOutStream.flush();
  objectOutStream.close();
  byteOutStream.close();
  byte[] byteData = byteOutStream.toByteArray();

  ByteArrayInputStream bais = new ByteArrayInputStream(byteData);
  T copy = (T) new ObjectInputStream(bais).readObject();
  
  return copy;
 }
}




What is "Shallow Copy"?


When we clone an object, only the values of that object get copied. The newly created object has an exact copy of the values in the original object. If any of the fields of the original object store references to other objects, then, just the reference addresses are copied (i.e., only the memory address is copied). So, manipulating the property of the inner object in a copied object after a shallow copy will result in the modification of the respective property of the inner object in the original object as well, as both points to the same address in the heap.

Sample code (with output) illustrating shallow copy:

class School implements Serializable, Cloneable {
 
 private String name;
 private Address address;
 
 public void setAddress(Address address){
  this.address = address;
 }
 
 public Address getAddress(){
  return address;
 }
 
 public void setName(String name){
  this.name = name;
 }
 
 public String getName(){
  return name;
 }
 
 @Override
 public String toString(){
  StringBuilder builder = new StringBuilder();
  builder.append("School Name: ");
  builder.append(name);
  builder.append(", ");
  builder.append("Address: ");
  builder.append(address.getAddress());
  return builder.toString();
 }
 
 @Override
 protected Object clone() throws CloneNotSupportedException {
  return super.clone();
 }
 
}


class Address implements Serializable, Cloneable{
 
 private String address;
 
 public Address(){
  
 }
 
 public Address(String name){
  this.address = name;
 }
 
 public String getAddress(){
  return address;
 }
 
 public void setAddress(String address){
  this.address = address;
 }
 
 @Override
 protected Object clone() throws CloneNotSupportedException {
  return super.clone();
 }
}

//Code to run application

School s1 = new School();
s1.setName("General School");
s1.setAddress(new Address("School 1 Address"));

School s2 = (School) s1.clone();// Deep copy by improper clone implementation
s2.getAddress().setAddress("School 2 Address");
  
System.out.println(s1);
System.out.println(s2);

Output:
School Name: General School, Address: School 2 Address
School Name: General School, Address: School 2 Address


Note here, that the change made to the value of "address" in the cloned object (s2) changed the value of "address" in the original object (s1) as well, as they both point to same object in the heap.



How Deep Copy can be implemented effectively in the above example:

1. Override clone Correctly
In the above case if we override the clone method in the School correctly we can create a deep copy.

@Override
protected Object clone() throws CloneNotSupportedException {
  
School clone = new School();
clone.setName(name);
clone.setAddress((Address)address.clone());
return clone;
}

2. Copy Constructor
We can provide a copy constructor in the School that will return a deep copy of the school. In school class provide the copy constructor

/**
 * Copy Constructor to get the copy
 * @return Copy of the school
 */
public static School getSchoolCopy(School school){
 School copy = new School();
 copy.setName(school.getName());
 copy.setAddress(new Address(school.getAddress().getAddress()));
 return copy;
}

And use copy constructor to provide the copy of the object

School s2 = School.getSchoolCopy(s1);

3. Serialize and de-serialize
Use the CommonUtil class (already explained above) to get the copy:

School s1 = CommonUtil.getCopy(s1); to get the clone of the object


The output of all three deep copy methods is:

School Name: General School, Address: School 1 Address
School Name: General School, Address: School 2 Address

Note here, that the change made to the value of "address" in the cloned object (s2) does not change the value of "address" in the original object (s1).

You can also use some third party libraries to create deep copies. Dozer and Kryo are two great libraries that serve this purpose. There is also Apache Commons that provides SerializationUtils.

NOTE:

1) Whenever we copy a Collection of objects we should always go for deep copy.
2) Copy method in the Collections class creates a shallow copy, and hence, modifying the objects in the copied collection will modify the object in the actual collection.

This post is written by Jerin Joseph. He is a freelance writer, loves to explore latest features in Java technology.

Friday, February 21, 2014

Producer Consumer in Java using BlockingQueue

9:38 PM 0
Producer Consumer in Java using BlockingQueue

What is Producer Consumer in Java?
Producer - A producer in Java is a thread that runs independently that produces something that is going to be consumed by a single Consumer or a group of Consumers.
Consumer - A Consumer in Java is a thread that runs independently and consumes something produced by a single producer or a group of Producers.

Producer/Consumer implmentation is required in java when instead of running a complete process in a single thread, the division takes place to run a process in order to speed up the process.

Consider a banking application scenario, where the requirement is to notify all the customers whose balance falls below 5000. Consider below tables :
1) <ACCOUNT> - It holds all the account numbers & balance
2) <ACCOUNT_INFO> - It holds all the account numbers in which withdrawal/deposit took place.

As soon as financial transaction takes place a job run which picks up the account number from 1st table and inserts into second table.
Now, there is a single thread which runs indefinetly in a while(true) loop which scans the table and as soon as an update is found follows the process :
1) Pick up the account
2) Check balance < 5000
3) If true notify the user either through email or SMS

Now all the three steps runs in a single thread. Why not seperate the above process using producer consumer model as shown below :
Producer Thread scans the table and loads the batch of 1000 accounts
Consumer pick up the account from Producer and checks for balance and notify the user
Both these threads can run independently. This can be achieved using the java.util.concurrent.BlockingQueue class.

BlockingQueue
Insert put(e)
Remove take()

The advantage of BlockingQueue implementations is it interally performs wait and notify operations. There is no need of synchronize block and wait/notify.
BlockingQueue may be capacity bounded as BlockingQueue blockingQueue = new ArrayBlockingQueue(10);

In above scenario as soon as, blockingQueue size reached 10 it wait for atleast one to be consumed. Also, if it becomes empty, it waits for the producer to produce atleast 1.
put(e) - It adds the object in the queue. As soon a queue becomes full, it waits for take() to consume atlease one object. As soon as take() is called on the blockingQueue, it notified the queue to add more.
take() - It waits for the put(e) to add atlease one object in the queue. As soon as an object is added put(e) notifies to start consuming.
So, as shown above there is no need to perform additional wait(), notify() checks in case of BlockingQueues.
BlockingQueue implementations are thread-safe. All queuing methods achieve their effects atomically using internal locks or other forms of concurrency control.

Sample Implementation:
This is the sample implementation for email marketing, where the producer will load the email id and put in the blocking quere whereas the consumer will consume the email id and send the email to the user.



EmailProducer.java
package com.blockingqueue;

import java.util.concurrent.BlockingQueue;

public class EmailProducer implements Runnable {

 private BlockingQueue<ProducerConsumerBean> blockingQueue;

 public EmailProducer(BlockingQueue<ProducerConsumerBean> blockingQueue) {
  super();
  this.blockingQueue = blockingQueue;
 }

 @Override
 public void run() {
  while(true) {
   try {
    ProducerConsumerBean producerConsumerBean = new ProducerConsumerBean();
    producerConsumerBean.setEmailId("EmailId");
    this.blockingQueue.put(producerConsumerBean);
    System.out.println("Producer Produced Email Id");
    Thread.sleep(100);
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }
}

EmailConsumer.java
package com.blockingqueue;

import java.util.concurrent.BlockingQueue;

public class EmailConsumer implements Runnable {
 private BlockingQueue<ProducerConsumerBean> blockingQueue;

 public EmailConsumer(BlockingQueue<ProducerConsumerBean> blockingQueue) {
  super();
  this.blockingQueue = blockingQueue;
 }

 @Override
 public void run() {
  while(true) {
   try {
    System.out.println("Consumer Started Sending Email to - " + this.blockingQueue.take().getEmailId());
    Thread.sleep(100);
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }  
 }

}

ProducerConsumerBean.java
package com.blockingqueue;

public class ProducerConsumerBean {

 private String emailId;

 public String getEmailId() {
  return emailId;
 }

 public void setEmailId(String emailId) {
  this.emailId = emailId;
 }
}

BulkEmailMarketing.java
package com.blockingqueue;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class BulkEmailMarketing {

 public static void main(String args[]) {
  BlockingQueue<ProducerConsumerBean> blockingQueue = new ArrayBlockingQueue<ProducerConsumerBean>(10);
  
  EmailProducer producer = new EmailProducer(blockingQueue);
  EmailConsumer consumer = new EmailConsumer(blockingQueue);
  
  new Thread(producer).start();
  new Thread(consumer).start();
 }
}

Output
Producer Produced Email Id
Consumer Started Sending Email to - EmailId
Producer Produced Email Id
Consumer Started Sending Email to - EmailId
Producer Produced Email Id
Consumer Started Sending Email to - EmailId
Producer Produced Email Id
Consumer Started Sending Email to - EmailId
Producer Produced Email Id
Consumer Started Sending Email to - EmailId
Producer Produced Email Id
Consumer Started Sending Email to - EmailId
....and so on

To download source, click here

Thursday, January 9, 2014

Java List ArrayList override equals method

1:49 AM 2
Java List/ArrayList override contains method using equals
java.util.List() - A List is an ordered collection i.e. it maintains the insertion order. List is allowed to contain duplicate elements in it.
java.util.ArrayList() - This class implemented the list interface methods.

When we add String, Integer or any Wrapper class objects into an ArrayList, using the contains() method we can check is the ArrayList object contains the value or not.

In case, it is required that the list not to contains duplicates {you anyways can use java.util.Set interface} then in above case before adding any value, a contains() method can be called for that value.

Consider a scenario where you have custom java object and there is an ArrayList object of that object type i.e. generic type. In this case, contains method will not work, since it checks for object references. In order to achieve contains implementation for custom java object for List/ArrayList than in the custom java object equals() method need to be overridden.

Consider below class
Person
{ 
 String name;
 String address;
}

Create Person object with name = "Kumar", address = "Mumbai";
Add this in the List. Before adding in the list, perform a check if it contains or not. To achieve the correct implementation, Person class must override equals() method as shown below

@Override
    public boolean equals(Object o) {
        if (o instanceof Person) {
            System.out.println("List already contains this object");
            return name.equals(((Person) o).name) && age == ((Person) o).age && address.equals(((Person) o).address);
        }
        return false;
    }
Check below the complete implementation:

Person.java
package com.pojo;

public class Person {

    private int age;

    public String name;

    protected String address;

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

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public boolean equals(Object o) {
        if (o instanceof Person) {
            if (name.equals(((Person) o).name) && age == ((Person) o).age && address.equals(((Person) o).address)) {
                System.out.println("List already contains this object with Name - " + name + ", Address - " + address
                        + " & Age - " + age);
                return true;
            }
        }
        return false;
    }
}



Main Class For Testing
import java.util.ArrayList;
import java.util.List;

import com.pojo.Person;

public class ListContainsOverride {

    public static void main(String args[]) {
        Person person = new Person();
        person.setName("Kumar");
        person.setAddress("Mumbai");
        person.setAge(25);

        Person person1 = new Person();
        person1.setName("Kumar");
        person1.setAddress("Mumbai");
        person1.setAge(25);

        List<Person> persons = new ArrayList<Person>();
        
        // Before adding an object, check if it not contains
        // Adding Person Object
        if (!persons.contains(person)) {
            persons.add(person);
        }
        
        // Before adding an object, check if it not contains
        // Adding Person1 Object with same values
        if (!persons.contains(person1)) {
            persons.add(person1);
        }

        System.out.println("\nFinal List \n");
        for (Person person2 : persons) {
            System.out.println("Name - " + person2.getName());
            System.out.println("Address - " + person2.getAge());
            System.out.println("Age - " + person2.getAddress());
        }
    }
}

Output
List already contains this object with Name - Kumar, Address - Mumbai & Age - 25

Final List 

Name - Kumar
Address - 25
Age - Mumbai

Sunday, January 5, 2014

Marquee in HTML

12:30 AM 0
Marquee allows a scrolling text in an HTML file.

Attributes :
1) behavior - This attribute defines the way the text will scroll withing the marquee. Values can ve scroll, slide or alternate.

2) bgcolor - To set the background color for marquee.

3) direction - Sets the direction for the text to scroll, slide. Values can be left, right, up down. If no direction is specified than default is left

4) height - To set the height of marquess

5) scrollamount - Sets the amount of scrolling at each interval in pixels. The default value is 6.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title> New Document </title>
  <meta name="Generator" content="EditPlus">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
  <style type='text/css'>

.CSSTableGenerator {
 margin:0px;padding:0px;
 width:50%;
 box-shadow: 10px 10px 5px #888888;
 border:1px solid #000000;
 
 -moz-border-radius-bottomleft:0px;
 -webkit-border-bottom-left-radius:0px;
 border-bottom-left-radius:0px;
 
 -moz-border-radius-bottomright:0px;
 -webkit-border-bottom-right-radius:0px;
 border-bottom-right-radius:0px;
 
 -moz-border-radius-topright:0px;
 -webkit-border-top-right-radius:0px;
 border-top-right-radius:0px;
 
 -moz-border-radius-topleft:0px;
 -webkit-border-top-left-radius:0px;
 border-top-left-radius:0px;
}.CSSTableGenerator table{
    border-collapse: collapse;
        border-spacing: 0;
 width:100%;
 height:100%;

 margin:0px;padding:0px;
}.CSSTableGenerator tr:last-child td:last-child {
 -moz-border-radius-bottomright:0px;
 -webkit-border-bottom-right-radius:0px;
 border-bottom-right-radius:0px;
}
.CSSTableGenerator table tr:first-child td:first-child {
 -moz-border-radius-topleft:0px;
 -webkit-border-top-left-radius:0px;
 border-top-left-radius:0px;
}
.CSSTableGenerator table tr:first-child td:last-child {
 -moz-border-radius-topright:0px;
 -webkit-border-top-right-radius:0px;
 border-top-right-radius:0px;
}.CSSTableGenerator tr:last-child td:first-child{
 -moz-border-radius-bottomleft:0px;
 -webkit-border-bottom-left-radius:0px;
 border-bottom-left-radius:0px;
}.CSSTableGenerator tr:hover td{
 
}
.CSSTableGenerator tr:nth-child(odd){ background-color:#e5e5e5; }
.CSSTableGenerator tr:nth-child(even)    { background-color:#ffffff; }.CSSTableGenerator td{
 vertical-align:middle;
 
 
 border:1px solid #000000;
 border-width:0px 1px 1px 0px;
 text-align:left;
 padding:7px;
 font-size:14px;
 font-family:Times New Roman;
 font-weight:normal;
 color:#000000;
}.CSSTableGenerator tr:last-child td{
 border-width:0px 1px 0px 0px;
}.CSSTableGenerator tr td:last-child{
 border-width:0px 0px 1px 0px;
}.CSSTableGenerator tr:last-child td:last-child{
 border-width:0px 0px 0px 0px;
}
.CSSTableGenerator tr:first-child td{
  background:-o-linear-gradient(bottom, #cccccc 5%, #b2b2b2 100%); background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #cccccc), color-stop(1, #b2b2b2) );
 background:-moz-linear-gradient( center top, #cccccc 5%, #b2b2b2 100% );
 filter:progid:DXImageTransform.Microsoft.gradient(startColorstr="#cccccc", endColorstr="#b2b2b2"); background: -o-linear-gradient(top,#cccccc,b2b2b2);

 background-color:#cccccc;
 border:0px solid #000000;
 text-align:center;
 border-width:0px 0px 1px 1px;
 font-size:20px;
 font-family:Times New Roman;
 font-weight:bold;
 color:#000000;
}
.CSSTableGenerator tr:first-child:hover td{
 background:-o-linear-gradient(bottom, #cccccc 5%, #b2b2b2 100%); background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #cccccc), color-stop(1, #b2b2b2) );
 background:-moz-linear-gradient( center top, #cccccc 5%, #b2b2b2 100% );
 filter:progid:DXImageTransform.Microsoft.gradient(startColorstr="#cccccc", endColorstr="#b2b2b2"); background: -o-linear-gradient(top,#cccccc,b2b2b2);

 background-color:#cccccc;
}
.CSSTableGenerator tr:first-child td:first-child{
 border-width:0px 0px 1px 0px;
}
.CSSTableGenerator tr:first-child td:last-child{
 border-width:0px 0px 1px 1px;
}

</style>
</head>

<body>





<div class="CSSTableGenerator" >
<table>
<tr><td>Marquee Behaviour - Scroll</td></tr>
<tr><td> <marquee behavior="scroll" direction="left" scrollamount="2">Slower From Left</marquee></td></tr>
<tr><td><marquee behavior="scroll" direction="left" scrollamount="6">Faster From Left</marquee></td></tr>
<tr><td><marquee behavior="scroll" direction="right" >Faster From Right</marquee></td></tr>
<tr><td><marquee behavior="scroll" direction="up">Goes Up</marquee></td></tr>
<tr><td><marquee behavior="scroll" direction="down">Goes Down</marquee></td></tr>
</table>
</div>
<br/>
<br/>

<div class="CSSTableGenerator" >
<table>
<tr><td>Marquee Behaviour - Slide</td></tr>
<tr><td><marquee behavior="slide" direction="right">Slide from right. Stop at left</marquee></td></tr>
<tr><td><marquee behavior="slide" direction="left">Slide from left. Stop at right</marquee></td></tr>
</table>
</div>
<br/>
<br/>

<div class="CSSTableGenerator" >
<table>
<tr><td>Marquee Behaviour - Alternate</td></tr>
<tr><td><marquee behavior="alternate" direction="left">Alternate from Left</marquee></td></tr>
<tr><td><marquee behavior="alternate" direction="right">Alternate from Right</marquee></td></tr>
</table>
</div>
<br/>
<br/>

</body>
</html>