Tuesday, April 21, 2009

Reload development changes without redeploy or restart

While I was browsing I arrived to a page, a commerical product called: JavaRebel. It offers to reflect development changes without a redeploy or restart. I strongly recommend you to see this demo.

This definetly increases development time but I heard that its not helpful with debugging. If it can be avoided, the product will be more useful.

However this is a commerical product and I hope that there will be such open-source tools, if there are any, please let me know.

Thursday, April 16, 2009

Difference between Static AOP and Dynamic AOP

If you have none knowledge on aspect oriented programming you should continue this article to have a basic knowledge on the topic.

AOP is a complement of object oriented programming, not a compete. In few words, with aop, you can execute a code (called advice in aop termology) in a defined point (called joinpoint) during the execution of your application.

An example to joinpoint can be execution of a method. You can group a collection of all method calls in a particular package (so this was an example to pointcut, so group of joinpoints are called pointcut). 

The combination of advice (the code which is going to be executed on a joinpoints) and pointcuts are called aspect.

There are other termologies involved too but you got the basic idea. For example now you know that with aop you can select the methods (pointcuts) and configure your logging class to be invoked (advice) before and after each method call in your application. So you do not need to go each method and change those methods just to measure the time spent, you can achieve this more simply with aop. Also your methods will not contain code which is not related with their business.

Term weaving refers to the process of inserting aspects into the application code at the appropriate point. The difference of Static and Dynamic AOP occurs here.

In static aop, weaving occurs in compilation time. Thus means, the advices are included to compiled bytecode.

In dynamic aop, weaving occurs on the fly while bytecode is instrumented. So there are no any bytecodes related with aop in the compiled code, but they are added at runtime.

Static aop should perform better since there is no need to special handling in runtime. In the other hand dynamic aop is more flexiable becouse you do not need to re-compile your code when your aspects changes.

You may choose these links to do a hello world with aop:

Hello world with AspectJ (static aop): http://javatouch.googlepages.com/aspectjtutorial
Hello world with Spring AOP (dynamic aop): http://javatouch.googlepages.com/springaop-helloworld

Sunday, April 12, 2009

Flex and BlazeDS

Although Flex is not new, it is for me. Unfortunetly none of us has enough time to learn and evaluate these (relativly) newly technologies.


It looks like Flex is going to be a standart for rich internet applications. The Flex source code (.mxml and .as files) is compiled to Flash bytecode (.swf) which is interrupted by ActionScriptVirtual Machine. As you already know, this will be independent on the client-side from the hardware, operating system or the browser. If you wonder how does Flex applications look like check here.


Do not worry, Flex in not built for animators like a Flash (where your artistic skills are more important), but for programmers whom I expect reading this blog :).


In order to develop RIAs with Flex you need to learn:
  • Action-Script ( which is based on ECMAScript 4, the language standard behind JavaScript)
  • MXML - an XML-based language (mostly used for developing user interfaces and this is based in Action-Script)
  • And you will need to be familiar with libraries of this technology (documentation is available)

You can use Flex Builder (commerical) in order to fasten your developments or you can just use the SDK which is free.

With Flex you can already make use of Web services or ajax like HTTP Services. However with BlazeDS you can also:

  • Call methods of Java objects in your web application directly
  • Make cross-domain service requests
  • Publish or Subscribe events to/with your application in server

If you want to learn more about how to get started you can check here.

Friday, April 10, 2009

What is Continuous Integration?

Continuous Integration is a software development practice which decreases integration time. In this practice, each member of a development team integrates his/her work so often in order to avoid an "integration hell". In each integration (usually at least once daily or even more frequent, which might be automated or activated manually), build is test to find integration errors as quickly as possible. If there are any errors , it will be easier to fix when all the members of the team have fresh knowledge and it will avoid an integration problem to grow if developers were unaware of it and continuing development.

In Continuous Integration, if possible, everyday commit is essential which means members need small cycles to complete and commit their code. Like a beer and chicken-wings, I think this is best achieved with another practice called scrum. Here is a link to a nice video which summarizes scrum technique.

Also, to make a good use of CI, you should have your unit tests with wide coverage.

Now, if you want to start your own Continuous Integration and Build Server continue with this link: http://continuum.apache.org/

Wednesday, April 8, 2009

Differences between DOM, SAX or StAX

Today we are using XML widely in order to exchange data. When you receive an xml resource you need to parse (read it) in order to get data you need.

However there are different approaches for parsing an xml source. You should select proper approach for your needs. You may choose one of these:
  • DOM - Document Object Model,
  • SAX - Simple API for XML,
  • StAX – Streaming API for XML
Let’s discuss each one.

Parsing with DOM:

If you prefer this technique you should know that the whole XML will be loaded into memory. Advantage of this technique is you can navigate/read to any node. You can append, delete or update a child node because data is available in the memory. However if the XML contains a large data, then it will be very expensive to load it into memory. Also the whole XML is loaded to memory although you are looking for something particular.

You should consider using this technique, when you need to alter xml structure and you are sure that memory consumption is not going to be expensive. Also this is the only choice where you can navigate to parent and child elements. This makes it easier to use.

If you are creating a XML document (which is not big!) you should use this technique. However, if you are going to export a data from a database to xml (where you do not need navigation in the xml and/or data is huge) then you should consider other approaches.

DOM API is standardized by w3c.

Parsing with SAX:

SAX has totally a different approach. It starts to read the XML document from beginning to end, but it does not store anything to memory. Instead it fires events and you can add your event handler depending on your requirements.

Your event handler will be called for example when an element begins or ends, when processing of document begins or ends. For all events please follow this link.
So you register a handler (or more then one handler) and those handlers are called when an event occurs.
Here is a sample code from a site which calculates the total amount from this xml.


With SAX, first of all you do not need to worry on memory consumptions. If the performance is the criteria, (and if you are only reading the xml, not modifying it), SAX is a much better choice then DOM. However you are not going to have a tree structure where you can require parent or child elements. You should be aware where you are.

Parsing with StAX:
StAX is a newer technology then the others we discussed and it is the only one with a JSR (JSR-173).

Parsing with StAX look like parsing with SAX. Again StAX does not store anything to memory and the document is read from beginning to end once.

However in SAX, your event handler is called by SAX when an event occurs. In StAX, you ask StAX to continue to next event.

You can use StAX in two methods, the “cursor model” and the “iterator model”.

Here is a simple code fragment I found on google. “cursor model” looks like:

As you see above, next event is required by us (parser.next();). In “iterator model” the logic is same but you receive an object while iterating which contains information about the current event like:



They were technologies, we also have implementaions.

After choosing your technology you can choose an implementaiton. There are different DOM,SAX and StAX implementations.

Check these:

http://java.sun.com/j2se/1.5.0/docs/guide/xml/jaxp/index.html
http://xerces.apache.org/xerces2-j/
http://stax.codehaus.org/Home

Or better, here is a link which has archieved all: http://java-source.net/open-source/xml-parsers

Monday, April 6, 2009

Another Way To Call A Native Method: JNA

Three days ago there was an article titled "Calling a .NET Method from Java via JNI" in this blog. In that approach we had to do some native development in order to call a .NET method from Java side. We had...
  • ...created a java class with native declarations and we had compiled it
  • ...created header files with javah (so with JNI)
  • ...developed an implementation of header files, we used C++ and we called .NET methods (so our implementation was a wrapper for the target dll) and we compiled the DLL (which were going to be a bridege between Java and .NET) with Visual Studio
Then I heard that I could also achieve this with JNA (JNA stands for Java Native Access). JNA allows you to access native libaries and call methods in that library. You only need to define native methods in an interface. (You should already know the signatures of the methods you are going to use anyway.) Also there is a tool called jnaerator which generates those interfaces for you but it is so limited and not matured yet.

I was told that I even do not need to touch Visual Studio nor use JNI directly becouse JNA was invoking native codes directly. However later on I explored that this was where they were wrong. Becouse, if you want to call a method in a class (which is written for example in C++ or C#) and which is compiled to dll, you still need to write a wrapper in C and procude a DLL (Here is the recommendation, it is actually what we had done with JNI too). So JNA does not help in this case.

However if it was method like printf in msvcrt library, we might make a use of JNA. I am saying maybe becouse using JNA is much slower then JNI!

This excerpt is from JNA project site: A simple test calling a function like int testfunc(int) with JNA might take an order of magnitude (~10X) greater time than equivalent custom JNI (whether it actually does in the context of your application is a different question).

This is still why I would choose to go with JNI. I feel more safe and have more control when I use JNI. Also JNA lacks loading initiating/classes. (Please correct me if I am wrong, but if I am wrong then this time I will start to complain about lack of documentation/example). JNI has more documentation, and it is more standarized. Of course they are not competing technologies but for now I keep distance with JNA.

However, assume if you have a native method in abcLib with a signature int compute(), then you could:

  1. Download jna.jar (download comes with .zip extension but it is a jar infact, so rename .zip to .jar)
  2. Then wrote your interface like:
    package mytrial;
    import com.sun.jna.Library;
    public interface MyInterface  extends Library  {
    public int compute();
    }
    
    
  3. Then we can call native method easyly. Here is the code for calling our native method:

    package mytrial;
    
    import com.sun.jna.Native;
    public class Main {
    public static void main(String[] args) {
    MyInterface lib = (MyInterface) Native.loadLibrary("abcLib", MyInterface.class);
    lib.compute();
    }
    }
    
    

So if we summary, I do no recommend JNA if performance is essential for you. Or if you are going to call a method in a class written with in .NET or unmannaged C++.

However maybe I am wrong, here are the projects that are using jna.

Difference between Portal, Portlet and Portlet Container

Although you may be a java expert, you may never worked with portlets. If this is the case, let me give you a short description.

According to JSR-168: Portlets are web components -like Servlets- specifically designed to be aggregated in the context of a composite page. Usually, many Portlets are invoked to in the single request of a Portal page. Each Portlet produces a fragment of markup that it s combined with the markup of other Portlets, all within the Portal page markup.

In other words, a portlet is an mini-application that provides some content that forms part of a portal page. These portlets are handled by portlet container.

A portal container:

  • executes portlets,
  • manages lifecylce of portles,
  • provides them a runtime enviroment to portlets.

In order to execute and test the portlet container, we need a driver: the portal.

Requests from users are recieved by portal then this is directed to portlet container and these requests are executed on portlets. And portal (not portlet container) is responsible for bringing together all the content produced by portlets and present them to clients. So a portal is a web application (which can be deployed a servlet container like tomcat) which brings together contents from different portles and the communication between portal and portlets are achieved by portlet containers.

Here is a popular image I found on the google which summarizes whole concept:
(Image may not be available since the image link refers to an external source)


A portal does not only built a portal page from portlets but also provides:

  • Personalization
  • Advanced security configuration
  • Single Sign On (SSO)
  • Customizable look and feel

Although a portal and a portlet container are different units, they can be built together as a single component.

Here is the list of some open source portals:

Now it is time learn details, chose one of the paths below, my favorite is JetSpeed v2 tutorial. You can follow the instructions to master portals or just read fastly to have deeper knowldge on the concepts discussed.

Friday, April 3, 2009

Clustering with Terracotta

When we talk about clustering, it is always known as a hard mission to accomplish. Configuring collections in entity relations, clustering databases, http sessions and such attempts always requires an experience that gained with failures. However according to Terracotta you achieve this without any experience in 30 minutes. Terracotta’s motto is if you know Java you know Terracotta. Terracotta is the name of both the JVM clustering technology product and the company name.

Terracotta is an open source technology (also there is a commercial version) that allows you to make clustering at JVM level. So you do not need to do anything actually except running your application in several JVM and connecting them together with Terracotta. You do not need to do any special change in your code because Terracotta uses ASM to instrument bytecode on the fly for you. Although you run a cluster with terracotta you can think that your application is working on one JVM.

Terracotta relies on their technology called Network-Attached Memory (NAM), so that they can even dare to recommend using memory for entities instead of using a database since NAM is durable to disk and runs at in-memory (according to Terracotta) speeds. Although this can be discussed, if you think that Terracotta is transactional (synchronized blocks form transactions of modified objects) this should make you eager to put this alternative in your designs.

Most suspicious developers may think the best approach would be keeping long term data in database but keeping all the value objects in memory. For example, in a web application, all the basket and basket items, any registration data, big query results and such items (so we can summarize as data in user session) can be kept in memory until user ends his conversation. When user completes his shopping, order can be committed to database and removed from memory.

But it is being discussed if you need a RDBMS unless you need to open your database to other non-java applications. While the market is demanding for simplicity (like Ruby on Rails, Grails), Terracotta seems to be a valuable design solution to be considered in suitable cases and I am sure there will be more JVM clustering frameworks will appear.

Go to Terracotta web page for more.

What is OSGi? – The Dynamic Module System for Java

You may encounter with term OSGi somewhere. If you do not know what the OSGi, perhaps you do now that your popular IDE Eclipse has been built on OSGi since release 3.

According to Carlos Perez, it was one of the top five technologies to learn in 2008. It is open to discussions but the fact is it is getting more and more popular. So I recommend you to read this article if you do not have a clue on what the OSGi is and then you can continue with a tutorial given at the end of this article.

OSGi technology allows adding functionalities/services that are independently developed and plugged into an application framework. So most notable items in OSGi technology we can talk about are OSGi container and bundles that can be deployed to this container.

There is a consortium including Ericsson, IBM, Sun Microsystems, Nokia, Intel, BMW, and Philips. This consortium is known as “OSGi Alliance” (OSGi stands for Open Service Gateway Initiative).

OSGi alliance maintains a specification (like EJB Specification or Servlet Specification) so that several vendors can build OSGi Containers and developers can use these containers to deploy their bundles. So with specification released by OSGi Alliance there are some popular OSGi Container implementations such:

Equinox
KnoplerFish
Felix

With these containers you can built your applications in a modular form. For example Eclipse is based on Equinox container and what we call plug-ins are actually OSGi bundles.

A bundle can search for other bundles, use them or it can use container’s services, it can export some of its packages. A bundle may have dependency on another bundle and this dependency can be optional, mandatory or it can require a specific version or version range. A bundle can also have its own classpath which can prevent many conflicts.

A bundle is actually a jar and a META-INF file which includes directives for the OSGi container.

For example you can build a bundle (lets call it time-bundle) which synchronizes a time attribute from a time server and export that time. And another bundle (lets call this one log-bundle) which logs some important happenings in the environment. Log-bunde can have an optional dependency on time-bundle. Log-bundle may use the synchronized time if time-bundle is available in the container, if it is not, it simple uses the system time without throwing an error.

Thus allows us reduced complexity, easy deployment (you can undeploy for example time-bundle and use a better one, a better version without restarting the whole application), reuse and many more.

Now download an OSGi container and start to develop some bundles.


When you have knowledge on the basic terms I recommend you to continue with: http://www.springsource.org/osgi.

Thursday, April 2, 2009

Calling a .NET Method from Java via JNI

One of my friends asked me for a fast and painless solution in order to call a .NET method from Java side. The best way (according to me) is web services to establish interoperability but however they especially asked for me not to use a web service. Although there are some frameworks we can use, for a fast and temporary development you do not need anything. Here’s how you can achieve it in 24 minutes :)

They only sent a dll to me without any information so I used a .NET Reflector to see what methods are in the dll and what the signature of the methods are there. In order to keep things simple, let me say I only determined following method:

int compute();

So I created a Java class, if we skip error handling and fa├žade patterns, the most two important lines were:

System.load("C:\\netBridge.dll");
private static native int callNativeCompute();
netBridge.dll is the dll that we are going to create it’s header with JNI and implement/compile with .NET.
callNativeCompute is the method that any third java party will call to invoke that .NET method.

After compiling your java class, generate the C++ header for implementing your native method (callNativeCompute)with javah. I will write an article about using JNI but believe me it is easy; just use javah as javac after compiling. But now I am so lazy to describe using JNI but at least let me share a JNI tutorial: http://java.sun.com/developer/onlineTraining/Programming/JDCBook/jniexamp.html#gen

Corresponding lines of the header file for our native method are:

JNIEXPORT jint JNICALL Java_com_yamanyar_j2n_FormalisTech_callNativeCompute
(JNIEnv *, jclass);

Now go to your Visiual Studio an create a DLL project from scratch and add the generated header file. Do not forget to include JNI include libraries to your project. (For example in my case: C:\Program Files\Java\jdk1.6.0_11\include).

Okay here is the .NET implementation:

JNIEXPORT jint JNICALL Java_com_yamanyar_j2n_FormalisTech_callNativeCompute
(JNIEnv *env, jclass myclass) {

try {
System::Reflection::Assembly ^ assembly = System::Reflection::Assembly::LoadFrom("c:\\Friterm.FrtCoils.dll");
System::Type ^ theType =  assembly->GetType("Friterm.FrtCoils.Calculator");
System::Console::WriteLine(theType->ToString());
System::Reflection::MethodInfo ^ mi =     theType->GetMethod("Compute");
System::Object ^ instance = System::Activator::CreateInstance(theType);
cli::array<System::Object ^,1> ^ arr = {};
return (int) mi->Invoke(instance,arr);
} catch (System::Exception ^ e){
System::Console::WriteLine(e->Message);
System::Console::WriteLine(e->StackTrace);
throw(e);
}

}


As you see in the above unmanaged C++ code, we are loading the dll and calling the Compute method. All the namespaces, location of dll, method name are hard-coded. You can make it configurable via text file too. And if an error occurs, it will be displayed in the terminal where your java application is running.

As you see we used reflection of .NET (do .NET developers call it reflection? I do not know). I am not a .NET expert, so if you recommend better solutions at the .NET side I will be glad to learn. Compile this dll and rename it to netBridge.dll so that our java class can load it.