Wednesday, November 28, 2012

Collections emptyList()

Can you guess the output for the below program ?
import java.util.Collections;
import java.util.List;

public class CollectionsTest {

private List<String> pool = Collections.<String> emptyList();

public List<String> call1() {
pool.add("Hello");
return pool;
}

public static void main(String[] args) {
CollectionsTest collectionsTest = new CollectionsTest();
List<String> call1 = collectionsTest.call1();
System.out.println(call1);
call1.add("one more added..");
System.out.println(call1);
}
}


Output:

Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:131)
at java.util.AbstractList.add(AbstractList.java:91)
at CollectionsTest.call1(CollectionsTest.java:9)
at CollectionsTest.main(CollectionsTest.java:15)


In short:
Collections.emptyList() returns an immutable list, i.e., a list to which you cannot add or remove elements.

Then, why should we use at all ? What is the purpose of this ?


Best Regards,
Kondal Kolipaka


My JAXB Learnings - Part 2


As part of this post, you will be understanding on the following concepts in the JAXB through an example.

1. Defining the name space
2. Defining the wrapper elements in the XML
3. Setting the name for entities in the list.
4. Defining the order for elements

This example is based on the book store and book model objects.

Book.java


import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlRootElement(name = "myBook")
// If you want you can define the order in which the fields are written
// Optional
@XmlType(propOrder = { "author", "name", "publisher", "isbn" })
public class Book {

private String name;
private String author;
private String publisher;
private String isbn;

// If you like the variable name, e.g. "name", you can easily change this
// name for your XML-Output:
@XmlElement(name = "titleName")
public String getName() {
return name;
}

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

public String getAuthor() {
return author;
}

public void setAuthor(String author) {
this.author = author;
}

public String getPublisher() {
return publisher;
}

public void setPublisher(String publisher) {
this.publisher = publisher;
}

public String getIsbn() {
return isbn;
}

public void setIsbn(String isbn) {
this.isbn = isbn;
}

}



2. BookStore.java


import java.util.ArrayList;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;

//This statement means that class "Bookstore.java" is the root-element of our example
@XmlRootElement(namespace = "com.kondal.bookstore.model")
public class BookStore {

// XmLElementWrapper generates a wrapper element around XML representation
@XmlElementWrapper(name = "bookList")

// XmlElement sets the name of the entities
@XmlElement(name = "book")
private ArrayList<Book> bookList;
private String name;
private String location;

public void setBookList(ArrayList<Book> bookList) {
this.bookList = bookList;
}

public ArrayList<Book> getBooksList() {
return bookList;
}

public String getName() {
return name;
}

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

public String getLocation() {
return location;
}

public void setLocation(String location) {
this.location = location;
}
}


3. BookMain 


import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class BookMain {

private static final String BOOKSTORE_XML = "./BookStore-jaxb.xml";

public static void main(String[] args) throws JAXBException, IOException {

ArrayList<Book> bookList = new ArrayList<Book>();

// create books
Book book1 = new Book();
book1.setIsbn("978-0060554736");
book1.setName("The Game");
book1.setAuthor("Neil Strauss");
book1.setPublisher("Harpercollins");
bookList.add(book1);

Book book2 = new Book();
book2.setIsbn("978-3832180577");
book2.setName("Feuchtgebiete");
book2.setAuthor("Charlotte Roche");
book2.setPublisher("Dumont Buchverlag");
bookList.add(book2);

// create BookStore, assigning book
BookStore BookStore = new BookStore();
BookStore.setName("Fraport BookStore");
BookStore.setLocation("Frankfurt Airport");
BookStore.setBookList(bookList);

// create JAXB context and instantiate marshaller
JAXBContext context = JAXBContext.newInstance(BookStore.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

// Write to System.out
m.marshal(BookStore, System.out);

// Write to File
m.marshal(BookStore, new File(BOOKSTORE_XML));

// get variables from our xml file, created before
System.out.println();
System.out.println("Output from our XML File: ");
Unmarshaller um = context.createUnmarshaller();
BookStore bookstore2 = (BookStore) um.unmarshal(new FileReader(
BOOKSTORE_XML));
ArrayList<Book> list = bookstore2.getBooksList();
for (Book book : list) {
System.out.println("Book: " + book.getName() + " from "
+ book.getAuthor());
}
}
}


Output on console:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:bookStore xmlns:ns2="com.kondal.bookstore.model">
    <bookList>
        <book>
            <author>Neil Strauss</author>
            <titleName>The Game</titleName>
            <publisher>Harpercollins</publisher>
            <isbn>978-0060554736</isbn>
        </book>
        <book>
            <author>Charlotte Roche</author>
            <titleName>Feuchtgebiete</titleName>
            <publisher>Dumont Buchverlag</publisher>
            <isbn>978-3832180577</isbn>
        </book>
    </bookList>
    <location>Frankfurt Airport</location>
    <name>Fraport BookStore</name>
</ns2:bookStore>

Output from our XML File:
Book: The Game from Neil Strauss
Book: Feuchtgebiete from Charlotte Roche




Tuesday, November 27, 2012

Get started with JAXB

If you are a beginner for JAXB. Here is the simple example will help you to get started.

All you need to have is JDK environment. This comes along with JAXB implementation.

This particular example is based upon the customer data, which deals with marshaling and unmarshaling.

Work flow:
1. Define your customer class, and identify the elements and attributes as part of  it.

Customer.java


import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Customer {

String name;
int age;
int id;

public String getName() {
return name;
}

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

public int getAge() {
return age;
}

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

public int getId() {
return id;
}

@XmlAttribute
public void setId(int id) {
this.id = id;
}

}

2. Using JAXB Context do the marshaling.

CustomerJAXBMarshal.java

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

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

Customer customer = new Customer();
customer.setId(100);
customer.setName("Raj");
customer.setAge(20);

try {

File file = new File("C:\\Customer.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

jaxbMarshaller.marshal(customer, file);
jaxbMarshaller.marshal(customer, System.out);

} catch (JAXBException e) {
e.printStackTrace();
}

}
}


Output on console:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer id="100">
    <age>20</age>
    <name>Raj</name>
</customer>


3.  Unmarshal the Customer XML file to build the Customer run time object.

CustomerJAXBUnmarshal.java

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

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

try {

File file = new File("C:\\Customer.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);

Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Customer customer = (Customer) jaxbUnmarshaller.unmarshal(file);
System.out.println(customer);

} catch (JAXBException e) {
e.printStackTrace();
}

}
}

Output on console:
Customer@1feca64



Monday, November 26, 2012

Git squash all commits into a single commit


$ git rebase -i 
Remember again that this is a rebasing command. Don’t include any commit you’ve already pushed to a central server — doing so will confuse other developers by providing an alternate version of the same change.
Running this command gives you a list of commits in your text editor that looks something like this:
pick f7f3f6d changed my name a bit
pick 310154e updated README formatting and added blame
pick a5f4a0d added cat-file

# Rebase 710f0f8..a5f4a0d onto 710f0f8
#
# Commands:
#  p, pick = use commit
#  e, edit = use commit, but stop for amending
#  s, squash = use commit, but meld into previous commit
#
# If you remove a line here THAT COMMIT WILL BE LOST.
# However, if you remove everything, the rebase will be aborted.
#
It’s important to note that these commits are listed in the opposite order than you normally see them using the log command. If you run a log, you see something like this:
$ git log --pretty=format:"%h %s" HEAD~3..HEAD
a5f4a0d added cat-file
310154e updated README formatting and added blame
f7f3f6d changed my name a bit
Notice the reverse order. The interactive rebase gives you a script that it’s going to run. It will start at the commit you specify on the command line and replay the changes introduced in each of these commits from top to bottom. It lists the oldest at the top, rather than the newest, because that’s the first one it will replay.

It’s also possible to take a series of commits and squash them down into a single commit with the interactive rebasing tool. The script puts helpful instructions in the rebase message:
#
# Commands:
#  p, pick = use commit
#  e, edit = use commit, but stop for amending
#  s, squash = use commit, but meld into previous commit
#
# If you remove a line here THAT COMMIT WILL BE LOST.
# However, if you remove everything, the rebase will be aborted.
#
If, instead of "pick" or "edit", you specify "squash", Git applies both that change and the change directly before it and makes you merge the commit messages together. So, if you want to make a single commit from these three commits, you make the script look like this:
pick f7f3f6d changed my name a bit
squash 310154e updated README formatting and added blame
squash a5f4a0d added cat-file
When you save and exit the editor, Git applies all three changes and then puts you back into the editor to merge the three commit messages:
# This is a combination of 3 commits.
# The first commit's message is:
changed my name a bit

# This is the 2nd commit message:

updated README formatting and added blame

# This is the 3rd commit message:

added cat-file
When you save that, you have a single commit that introduces the changes of all three previous commits.
Ref: http://git-scm.com/book/en/Git-Tools-Rewriting-History


Cherry-Picking specific commits from one branch to another

Say, for example you are working with two different branches. Dev-4.0 and Dev-5.0.

And you have made few changes/fixes in Dev-4.0 branch and now you want to bring those changes in to the Dev-5.0 branch.

GIT provides cherry-pick command to do that.

1. Go to Dev-4.0 branch and identify the commit id's which need to be cherry-picked.
ex: Below the commit id's for my changes in Dev-4.0 branch.
 8ae534e23d82070cdaaea4913415678affdab44b

892aec46126320b8a2e030b0017611509a57a7b

2. Go to Dev-5.0 branch and fire the following command.

> git cherry-pick  8ae534e23d82070cdaaea4913415678affdab44b

this will bring all your commit changes from Dev-4.0 to  Dev-5.0

If you have any conflicts during this time.
- Resolve the conflicting files
- Once you have resolved the issues, add them to git if it's not added.
- Commit the modified files.

Otherwise git automatically commit your changes with cherry-pick command itself, if there are no conflicts occurred.

Ref: http://gitref.org/inspect/

Now..hope you are good to go!!.


Sunday, November 25, 2012

Checking user specific commits in GIT


> To filter your commit history to only the ones done by a specific author.

           git log --author=kondal.kolipaka@kony.com

 > -[number] option, which will limit the results to the last [number] commits.

         git log --author=kondal.kolipaka@kony.com  -4

> git log --since --before filter commits by date committed

If you want to specify a date range that you're interested in filtering your commits down to, you can use a number of options - I use --since and --before, but you can also use --until and --after. For example, if I wanted to see all the commits in the Git project before 3 weeks ago but after April 18th, I could run this (I'm also going to use --no-merges to remove merge commits):

     git log --oneline --before={3.weeks.ago} --after={2012-11-18} --no-merges

> git log --grep filter commits by commit message
You may also want to look for commits with a certain phrase in the commit message. You can use --grep for that. Let's say I knew there was a commit that dealt with using the P4EDITOR environment variable and I wanted to remember what that change looked like - I could find the commit with --grep.

    git log --grep=P4EDITOR --no-merges

Friday, November 23, 2012

Tooltip on tree viewer items

This describes about how to add a tooltip on tree viewer items based on the context of object. 

ExplorerViewer.getTree().addMouseTrackListener(new ExplorerMouseListener());


private class ExplorerMouseListener implements MouseTrackListener {

@Override
public void mouseEnter(MouseEvent e) {
}

@Override
public void mouseExit(MouseEvent e) {
}

@Override
public void mouseHover(MouseEvent event) {

TreeItem item = explorerViewer.getTree().getItem(new Point(event.x, event.y));
if (item != null && item.getData() instanceof MyResource) {
MyResource selectedElement = (MyResource) item.getData();
if (selectedElement.getResourceType() == MyResourceType.APP_GROUP
|| selectedElement.getResourceType() == MyResourceType.DATA) {
if (selectedElement.getData() instanceof INameDescription)
explorerViewer.getTree().setToolTipText(
((INameDescription) selectedElement.getData())
.getDescription());
} else {
explorerViewer.getTree().setToolTipText(null);
}
}
}

}

Template for git commit messages


Good commit messages always makes a difference!!!

Following is the template I generally refer to.



FEATURE/BUGFIX/ENHANCEMENT: KonyOne Studio - <Module name> - <short problem/module description>

<Detailed description of feature/solution description/enhancement comments>

<Fix: #JSP1234>

Reviewed By :  <reviewer name>


Example for Feature:

FEATURE: KonyOne Studio - Sky Data Explorer - Implemented model classes for sky explorer

Provided the offline support capabilities to work offline.

Reviewed by: Rakesh 


Example for BugFix:

BUGFIX: KonyOne Studio - Java Script Module - Heap memory issues with huge number of files.

Java script listener is modified..etc,..

Fix: #JSP12345


Example for Enhancement:

ENHANCEMENT: KonyOne Studio - Java Script Module - code clean for java script model

Unnecessary code has been removed in java script module.

Reviewed by: Rakesh 


Points to be considered:

  • Topic description (first line)
  •  72 characters max for each line.
  •  Give space for title and body
  •  Use present tense.(Generally git uses the same for merge/rebase)


Why 72 characters ??
git log doesn’t do any special special wrapping of the commit messages. 

On an 80 column terminal, if we subtract 4 columns for the indent on the left and 4 more for symmetry on the right, we’re left with 72 columns.


Good commit messages serve at least three important purposes:

  • To speed up the reviewing process.
  • To help us write a good release note.
  • To help the future maintainers (it could be you!), say five years into the future, to find out why a particular change was made to the code or why a specific feature was added.