Wednesday, November 12, 2014

Make a List

Just to summarize all the ways of list creation in Java.
Taken from: http://stackoverflow.com/questions/858572/how-to-make-a-new-list-in-java


JDK

1. List listA = new ArrayList<string>();
2. List listB = Arrays.asList("A", "B", "C")

Guava

1. List names = Lists.newArrayList("Mike", "John", "Lesly");
2. List chars = Lists.asList("A","B", new String [] {"C", "D"});

Immutable List

1. Collections.unmodifiableList(new ArrayList<string>(Arrays.asList("A","B")));
2. ImmutableList.builder()                                      // Guava
            .add("A")
            .add("B").build();
3. ImmutableList.of("A", "B");                                  // Guava
4. ImmutableList.copyOf(Lists.newArrayList("A", "B", "C"));     // Guava

Empty immutable List

1. Collections.emptyList();
2. Collections.EMPTY_LIST;

List of Characters

1. Lists.charactersOf("String")                                 // Guava
2. Lists.newArrayList(Splitter.fixedLength(1).split("String"))  // Guava

List of Integers

Ints.asList(1,2,3);                                             // Guava

A little java collections memo:

Tuesday, October 28, 2014

Initialize object with Java reflection mechanism

Java 7 has an improved way of working with object's reflection in comparison with older versions.
For example, at version 6 in order to initialize object and its fields we need.
1) initialize class object instance using type name of the target object
2) if some object's methods (for example 'setXxx') should be invoked, need to find it and pass corresponding parameters - be aware of parameter type, it must me consistent with original method signature.


Object param = new SomeType(); // SomeType must be included in a signature of the target method 
String type = "com.vbashur.MyType"
Class<?> clazz = Class.forName(type);
Object paramObject = clazz.newInstance();
String setterName = "setMyValue"

for (Method m : clazz.getDeclaredMethods()) { // if parameters are known, use getDeclaredMethod
    if (m.getName().equals(setterName)) {
        m.invoke(paramObject, param);
        break;
    }
}

The piece of code above may throw a bunch of ugly exceptions (llegalAccessException,
IllegalArgumentException, InvocationTargetException, InstantiationException, ClassNotFoundException) and works quite slow. In order to access private method it requires Method.setAccessible() to be invoked.

MethodHandle is a Java-7-way

1) What we need to do is to declare MethodType object firstly. A MethodType is an immutable object that represents the type signature of a method.

Friday, October 3, 2014

Merge Sort in Java (+JavaScript)

Merge sort algorithm has a worst-case performance of O(n log n) - that's a good performance of comparison-based sorting algorithm, moreover this algorithm is easy to understand, remember and repeat after while.
For implementation I'm going to use mergeSort method with the following signature:
<T extends Comparable<T>> void mergeSort(T[] arrayToSort, T[]resArray)
arrayToSort - array to be sorted
resArray - empty array with the same length as arrayToSort which will have all arrayToSort's items in a sorted order

In step one of merge sort we need to copy the content of arrayToSort into resArray and specify array's start and end indicies.


int lo = 0;
int hi = arrayToSort.length - 1;
for (int iter = 0; iter < arrayToSort.length; ++iter) {
 resArray[iter] = arrayToSort[iter];
} 

Now it's time to split an array in a central element and get two subarrays
int mid = lo + (hi - lo) / 2; // this is a central element index of array
1-st subarray elements will be from lo to mid indicies
2-nd subarray elements will be from mid + 1 to hi indicies


The following function can break up into subarrays recursively:

<T extends Comparable<T>> void sortMerge(T[] arrayToSort, T[] resArray, int lo, int hi) {
    if (lo >= hi)
  return;
 int mid = lo + (hi - lo) / 2;
 sortMerge(arrayToSort, resArray, lo, mid);
 sortMerge(arrayToSort, resArray, mid + 1, hi);
 //merge(arrayToSort, resArray, lo, mid, hi);
}

Thursday, September 18, 2014

Java + Vaadin + Spring: creating a basis for application's user interface. From the very beginning.

This article shows the way of creating java application with Vaadin user interface and Spring framework features.

Create a Vaadin application is very easy if you have installed corresponding eclipse plugin. Read http://vaadin.com/eclipse to get to know how to install the plugin and create vaadin application in a few mouse clicks.

Another way of creating vaadin application quickly is using Vaadin "application" archetype. Type the following string in the command line once you're getting into workspace directory:

mvn archetype:generate -DarchetypeGroupId=com.vaadin -DarchetypeArtifactId=vaadin-archetype-application -DarchetypeVersion=7.1.8

NOTE: if you got an error : "The desired archetype does not exist (com.vaadin:vaadin-archetype-application:7.1.8)" execute this command: mvn archetype:update-local-catalog

I'd like to show old-school way of Vaadin integration into a simple web application. There are two solutions. Second solution I find more attractive, however it cannot be applied to Vaadin 6. Read more for details.

Thursday, July 31, 2014

Spring MVC, OSGI bundles and forwarding requests

I have a post in this blog with example of using OSGI servlet bridge and embedded OSGI framework. Now it's time to extend it.
Let's play with OSGI combining it with Spring MVC application.



With stackoverflow you can find some links to samples and explanations about Sprng MVC and OSGI
http://stackoverflow.com/questions/12832697/looking-for-an-osgi-with-spring-specifically-spring-mvc-tutorial
http://stackoverflow.com/questions/12331722/osgi-spring-mvc-bundle-nightmare-java-lang-classnotfoundexception-org-springf

In this article I'd like to show how does spring MVC application may use OSGI servlet-bundles.
1. My spring MVC application is going to be the main application with a fundamental business logic and it's going to be a bridge for bundles
2. I'd like to have a special bundle with a logic that is common for osgi bundles installed. Some kind of super bundle with general functionality.
3. Other bundles have it's logic implemented inside and also could interact with general bundle and main spring application forwarding its queries.

Step-by-step

Thursday, July 17, 2014

Simple jUnit which compares two files

I have a piece of code that generates some file an I need to cover this code with unit-tests. With a sample file I may check my code whether the file was generated correctly. Maven creates src/test/resources directory automatically, there is no better place to put the sample file.
If the file has a path /src/test/resources/tables/sample.xml we can read them in a following way

URL url = this.getClass().getResource("/tables/sample.xml");
File sampleFile = new File(url.getFile());

Don't need to compare files line-by-line, just use commons-io util

FileUtils.contentEquals(file1, file2);

Finally, three lines of code below can be applied for unit tests (and not only for tests) to check for files equality:

private boolean isFileDataEqual(File target) throws IOException {
 URL url = this.getClass().getResource("/tables/sample.xml");
 File sampleFile = new File(url.getFile());
 return FileUtils.contentEquals(target, sampleFile);
}

Monday, July 7, 2014

OSGI servlet bridge sample


Servlet bridge is a mechanism for extending your servlet functionality adding other servlets. In this case your main servlet is not affected within some changes however the number of processed request is increased by newly added servlets (modules).
We don't want to have some sophisticated way to register/unregister new modules, don't want to be forced to rebuild the whole application when the new servlet is registered. OSGI is a keyword which helps us to avoid of this issues. In the scope of Servlet Bridge feature OSGI is a powerful mechanism which can help you to extend the functionality of your java servlet application. It can be achieved by using HttpService implementation provided by OSGI standards. Image source: http://www.jayway.com/2007/05/01/osgi-not-just-a-four-letter-word/
(image from: http://www.jayway.com/2007/05/01/osgi-not-just-a-four-letter-word/)
This post is a good way to start with theoretical basics of OSGI, let's try to implement the OSGI servlet bridge.

Tuesday, July 1, 2014

Get data table metadata using MyBatis

Don't try to use myBatis type handlers to get the metadata of some database tables.
If the datatable doesn't contain any data the type handler won't work and you will not get any result.
There is a link about how to do it with TypeHandlers but don't forget that your datatable shoudn't be empty:
http://www.coderanch.com/t/415314/ORM/databases/retrieve-metadata-ibatis
http://www.thespringriver.com/simple-example-of-mybatis-java-maven-implementation-8-customized-type-handler/ (This is about how to use TypeHandler for the latest MyBatis version [3.2.7])

The better solution is using the data from INFORMATION_SCHEMA, for example you can use some query like:

<select id="selectMeta" parameterType="String" resultType="DataColumnForm">
 SELECT TABLE_CATALOG, TABLE_NAME, COLUMN_NAME, TYPE_NAME, DATA_TYPE, COLUMN_DEFAULT
  FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=#{tbl_name}  
</select>

Sunday, June 15, 2014

Disjoint-set data structure

Disjoint-set data structure is the one of the best way to have separated sets of unique items.
Union-find is a simple algorithm which allows us to identify whether two (or more) points are in the same set. For example we have the following disjoint-sets:

It's not a hard task to examine if points 6 and 10 are in the same disjoin-set, but for a sufficient number of points we need to have correct algorithm (correct means fast, reliable and valid). The best practice is using union-find algorithm.
To implement the algorithm we need:
1. Create disjoint-data set adding items one-by-one, it could be performed on initializating of our data.
2. Create a special 'root' nodes array
3. Get a result using 'root' nodes


Lets use this class to store our items:

static class UnionItem {  

  private int itemValue;

  private int neighborItemValue;

  public UnionItem(int itemValue, int neighborItemValue) {
   super();
   this.itemValue = itemValue;
   this.neighborItemValue = neighborItemValue;
  }
  
  public int getItemValue() {
   return itemValue;
  }

  public int getNeighborItemValue() {
   return neighborItemValue;
  }

 }

For our example we have the following array (ROOT_ID can be replaced by repeating the actual item value)


private final static int ROOT_ID = -1;

private static UnionItem[] items = new UnionItem[] {
   new UnionItem(1, ROOT_ID),   
   new UnionItem(5, ROOT_ID),
   new UnionItem(8, ROOT_ID),
   new UnionItem(2, 1),
   new UnionItem(11, 2),
   new UnionItem(4, 11),
   new UnionItem(7, 5),
   new UnionItem(6, 7),
   new UnionItem(9, 8),
   new UnionItem(3, 9),
   new UnionItem(10, 9)
 };

For a 'root' nodes we need to have an array


private static int[] unions = new int[items.length + 1];

Array may be filled out in a cycle:


for (int iter = 0; iter < items.length; ++iter) {
 int currentValue = items[iter].getItemValue();
 if (items[iter].getNeighborItemValue() != ROOT_ID) {
     unions[currentValue] = getParentValue(items[iter]
      .getNeighborItemValue());
 } else {
      unions[currentValue] = currentValue;
 }
}

public static int getParentValue(int val) {
 if (val != unions[val]) {
  val = getParentValue(unions[val]);
 }
 return val;
}
'root' nodes array will look like: 1 1 8 1 5 5 5 8 8 8 1. We can say for sure that element 3 is included in the same disjoint-set as elements 8,9,10. Why? Because of our algorithm that uses indicies as element's values and values available by those indicies as identificators of the set.

Then we just need the method to examine two value in one union

public static boolean isInUnion(int val1, int val2) {
 return unions[val1] == unions[val2];
}

Thursday, June 12, 2014

Java Stack Implementation

This is a the simplest example of stack implementation in Java. 'Must-do' exercise for a junior software guys

public class Stack<T> {

 T[] items;

 int index = 0;

 @SuppressWarnings("unchecked")
 public Stack(int size) {
  items = (T[]) new Object[size];
 }

 public void push(T item) {
  if (index < items.length) {
   items[index] = item;
   ++index;
  } else {
   throw new StackOverflowError(
     "Element couldn't be added: stack is full. ");
  }
 }

 public T pop() {
  if (index > 0) {
   --index;
   T value = items[index];
   items[index] = null;
   return value;
  } else {
   return null;
  }
 }
 
 public boolean isFull() {
  return index == items.length;
 }
 
 public boolean isEmpty() {
  return index == 0;
 }
 
 
 public String toString() { /* Optional */
  StringBuilder sb = new StringBuilder();
  for (int iter = 0; iter < items.length; ++iter) {
   sb.append(items[iter] + " ");
  }
  return sb.toString();
 }

}

Wednesday, March 19, 2014

Override toString() method with ToStringBuilder

One fancy way of toString method implementation is in using of ToStringBuilder class.
With this class you don't need to specify all the objects for output and you get a flexible mechanism of building and formatting your object's string representaion.
Just a couple of strings:

<dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.5</version>
</dependency>

import org.apache.commons.lang.builder.ToStringBuilder;

@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}

Got it!

See more information on official reference documntation: http://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/builder/ToStringBuilder.html

Another very good article about ToStringBuilder by Lokesh Gupta (with nice samples)
http://howtodoinjava.com/2013/06/03/how-to-override-tostring-effectively-with-tostringbuilder/