Monday, October 29, 2007

A Linked List Sorter


About sorting LinkedList, I just implemented a sotrer class two weeks ago because I was asked how to sort a linked list. I tried to write a Java class to sort LinkedList.
Here is my implementation, just for everyone reference, and please advise if any mistake.

Suppose we have a data structure just as below, upper part display origional position, we have to sort out a sequence as lower part.
(Element has null parent ID means it is the first/top one)


First of all, I define an Interface as below:

public interface SortingElement {

Long getId();
Long getParentId();
void setParentId(Long parentId);

}

A sorting element is composed of two value, one is my id, the other is the id which I am linking to (that means parentId). So we have getId() and a pair of setter and getter for parentId.

Following is the LinkedListSorter class:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public final class Sorter {

public static List sort(List elements) {

List rs = new ArrayList();
Map temp = new HashMap();
SortingElement currentElement = null;
for (SortingElement element : elements) {
Long parentId = element.getParentId();
if (parentId != null)
temp.put(element.getParentId(), element);
else
currentElement = element;
}

for (int i=0; i<elements.size(); i++) {
Long childParentId = currentElement.getId();
SortingElement child = temp.get(childParentId);
rs.add(currentElement);
currentElement = child;
}
return rs;
}
}


Before passing List of SortingElement into sorter, we have a pre-condition has to be satisfied, that is only one element can return a null parent id, it means it sits at the top of these elements, others elements must contain its parent id.

Gets into the method, first of all these parent Id value of each elements are extracted out, they are put into a Map which using parent Id as key and element itsself as value.

Then a List is used to sequentially retrieve element from Map according each elements parent Id.

I didn't test its efficiency, but at least it seems works up to now by my test case. Attached is the test Java class, just for you are interested in it.

Tuesday, October 02, 2007

Study note: how the limitless nonvolatile memory will affect the future of world

I am studying the MSc of IT programme in Liverpool University. This week we discussed how the limitless nonvolatile memory will affect the future of world.


Below is the discussion summary of what I wrote to forum wtoday:


Hi All,

Super large but cheap storage device is not a dream in the coming future, but to keep the stored data organized is also the necessary thing we have to bear in mind. I think the problem is not how large of the storage capacity, it is because we misuse the large storage device, and the lack of softwares to help organize the large amount of documents, photos or binary files.

Vee mentioned a key point of these large amount of documents or images - metadata. Everyone knows the concept of web 2.0. It is a popular marketing phrase we can see in the Internet. If we can't organize data well, even 10MB data we could mess it up. Web 2.0 emphasize the interaction among Internet users, people contribute everything into many kinds of web 2.0 model web site, e.g. Del.icio.us, Flicker. Everytime you bookmark or upload something, you have to give metadata to your documents or photos, thus the sofrware, might be a search engine or something like that, behind the user interface can start to analyze the new uploaded document, and associate these data by many kinds of algorism. I would say that the 20th century is the era of data collecting century; and the 21th century is the era of data manipulating. So many ERP systems were built in the last century, these data are collected large enough to start predicting trends, analyzing behavior or something else. Thus who owns the most powerful search engine or analyzing algorism, who will lead the business of 21th century. So a stong back bone hardware to support these large raw data or results is the same important.

A reliable, fast, large, and reasonable price sotrage device is the foundation to support the everything above make make true in the future.

Thursday, May 10, 2007

An easy way to remove blank page generated by JasperReports

If your JasperReports report has one more sub-reports and it was generated as PDF file. In some circumstances, a blank page might be found within PDF file. Here is my solution to easily remove it.

private void removeBlankPage(List<JRPrintPage> pages) {

for (Iterator<JRPrintPage> i=pages.iterator(); i.hasNext();) {
JRPrintPage page = i.next();
if (page.getElements().size() == 0)
i.remove();
}
}

This method should be called before you flush your JasperPrint instance to PDF.

Followed with the sample code, it would be better to know the object hierarchy of JasperPrint.

  1. 1. A JasperPrint has one or more JRPrintPage, you can get it via getPages() method of JasperPrint. It returns a List of JRPrintPage. If you have three elements, then your printer will print 3 pages.
  2. 2. A JRPrintPage has one ore more JRPrintElement, each element might be a string of text, or a picture, or a rectangle, etc. You can change its position or content dynamically, or even add new JRPrintElement into JRPrintPage.

Sunday, November 12, 2006

use ListDataSource to easily pass object to JasperReports

Nowadays OR mapping framework and web framework are widely used in application, most of them use value objects go through entire transaction life cycle. But most of the applications also have report requirements, one of the most popular report engine framework is JasperReports.
If the same value objects can pass into report engine without having to transfer them or query database again to make another java type object, it will make the transaction more neater and easier to maintain.

Here is my implementation of JRDataSource, it is called ListDataSource, you just have to pass into java.util.List of value object(java.lang.Object) or implementation of java.util.Map.

Below are the code:

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRField;

import org.apache.commons.beanutils.MethodUtils;

/**
 * @author Matt Jiang (matt.jiang@gmail.com)
 * @version 1.0
 */
public class ListDataSource implements JRDataSource {

  private List records = null;
  private Iterator iterator = null;
  private Object currentRow = null;
  private boolean disableReflection = false;
  
  public ListDataSource(List records, boolean disableReflection) {
    
    this.disableReflection = disableReflection;
    this.records = records;
    if (records != null)
      this.iterator = records.iterator();
  }
  
  public ListDataSource(List records) {
    
    this(records, false);
  }
  
  /**
   * cursor switch to next record
   */
  public boolean next() throws JRException {

    boolean hasNext = false;
    
    if (iterator != null) {
      hasNext = iterator.hasNext();
      if (hasNext)
        currentRow = iterator.next();
    }
    
    return hasNext;
  }

  /**
   * fieldName is defined in JasperReports, it will used as a key of Map or be transfered to getter method 
   * to retrieve value by java reflection. 
   */
  public Object getFieldValue(JRField jrField) throws JRException {

    String fieldName = jrField.getName();
    String methodName = makeGetter(fieldName);
    Object fieldValue;
    
    if (currentRow instanceof Map)
      fieldValue = retrieveValueFromMap((Map)currentRow, fieldName);
    else {
      if (disableReflection)
        fieldValue = currentRow;
      else
        fieldValue = retrieveValueFromReflection(currentRow, fieldName);
    }
    
    return fieldValue;
  }
  
  private Object retrieveValueFromMap(Map currentRow, String fieldName) {
    
    return currentRow.get(fieldName);
  }
  
  private Object retrieveValueFromReflection(Object currentRow, String fieldName) {
    
    Object fieldValue = null;
    try {
      fieldValue = MethodUtils.invokeMethod(currentRow, makeGetter(fieldName), null);
    } catch (Exception e) {
      e.printStackTrace();
      ; // ignore this exception on purpose
    }
    return fieldValue;
  }
  
  private String makeGetter(String fieldName) {
    
    StringBuffer getter = new StringBuffer();
    getter.append("get").append(fieldName.substring(0, 1).toUpperCase()).append(fieldName.substring(1));
    return getter.toString();
  }

  public String size() {
    
    String size = "0";
    if (records != null) {
      size = String.valueOf(records.size());
    }
    
    return size;
  }
}

Tuesday, November 07, 2006

Hello World

Haha... You see the title, if your career is the same as mine, then you have known what my job is.
Sometimes I write some tiny utility or a framework, I am pleasure to share my idea and source code to everyone, and hope you can give me some advice as well.

Nice to meet you here.