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.