Functional Java

+++Google Guava+++

Google Guava is a collection of libraries provided by google under Apache licence to support a number of common problems in developing Java. It also provides a number of interfaces and implementations, which allow to develop in a more functional style. A good tutorial on these can be found here and here.

+++Lambdaj+++

I think it is a very interesting approach to use Java‘s flexibility to write Java code, which matches the style of other programming paradigms. In this context, the lambdaj project seems to be an interesting and already quite mature framework.

Advantages:
I stumbled across this project after checking out Hamcrest, which seems to be a quite popular tool for JUnit test. I was asking myself why, when it is easier to define test cases in this functional way, why not write code like this in the first place. And I believe for at least some instances writing code in lambdaj style can be much easier to read and understand.

Limitations seem to be:

  • Many operations take around three times longer than the traditional java solution
  • There seem to be some limitations in regards to generics
  • Although this might not be relevant for many, the heavy use of reflection in lambdaj prevents from using the library in GWT applications.

CLAP Protocol in Restlet and OSGi

Problem:

Accessing resources using the CLAP protocol in Restlet becomes troublesome in an OSGi environment. In particular, if the Restlet libraries are in a different bundle than the resources, which shall be accessed using the CLAP protocol.

Solution:

Although it might be more than a workaround than a solution, it works quite well to do some manual changes to the classloaders. First, the Directory class must be overriden:

import org.restlet.Context;
import org.restlet.Request;
import org.restlet.Response;
import org.restlet.data.Reference;
import org.restlet.resource.Directory;

public class ClassLoaderDirectory extends Directory {

        private ClassLoader _cl;

        public ClassLoaderDirectory(Context context, Reference rootLocalReference, ClassLoader cl) {

                super(context, rootLocalReference);
                this._cl = cl;
        }

        @Override
        public void handle(Request request, Response response) {
                final ClassLoader saveCL = Thread.currentThread().getContextClassLoader();
                Thread.currentThread().setContextClassLoader(_cl);
                super.handle(request, response);
                Thread.currentThread().setContextClassLoader(saveCL);
        }

}
(http://gist.github.com/602448)

Then we need a little helper class to allow using more than one classloader:

private static class CompositeClassLoader extends ClassLoader {
                 private Vector<ClassLoader> classLoaders = new Vector<ClassLoader>();

                        @Override
                        public URL getResource(String name) {
                                for (ClassLoader cl : classLoaders) {

                                        URL resource = cl.getResource(name);
                                        if (resource != null)
                                                 return resource;

                                }

                                return null;
                        }

                        @Override
                        public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {

                                for (ClassLoader cl : classLoaders) {
                                 try {
                                         return cl.loadClass(name);
                                 } catch (ClassNotFoundException ex) {

                                 }
                                }

                                throw new ClassNotFoundException(name);
                        }

                 public void addClassLoader(ClassLoader cl) {
                         classLoaders.add(cl);
                 }

         }
(http://gist.github.com/602450)

Lastly, we create the Directory:

@Override
         public Restlet createRoot() {
                 final Router router = new Router(getContext());

         getConnectorService().getClientProtocols().add(Protocol.FILE);
                 getConnectorService().getClientProtocols().add(Protocol.CLAP);

                 LocalReference localReference = LocalReference.createClapReference(LocalReference.CLAP_THREAD, “/src/main/webapp/”);

                 CompositeClassLoader customCL = new CompositeClassLoader();
                 customCL.addClassLoader(Thread.currentThread().getContextClassLoader());
                 customCL.addClassLoader(Router.class.getClassLoader());

                 ClassLoaderDirectory directory = new ClassLoaderDirectory(getContext(),
                        localReference,
                        customCL);        

                 router.attach(“/www”, directory);
                 return router;
         }
(http://gist.github.com/602451)

Therewith, the Directory can load files stored in the bundle in which the server is started, even when the Restlet libraries are in a different bundle.

Caveat:

Due to the rudimentary nature of the composite classloader class, there might be issues if there are resources at identical paths in the two bundles. In the current implementation, the resources of the first classloader added will be given preference. In the example given above, resources will first be loaded from the bundle in which the server is started, and only if there is no resource at the specified path will the resource be looked up in the bundle in which the Restlet library is located.

Resources:

Issue 740: DirectoryResource, “clap://class/” scheme, and custom Classloaders issue

Mail list: DirectoryResource, the “clap://class/” scheme, and custom Classloaders – doesn’t work? (OSGi- related)

JavaDoc LocalReference class (can be a reference to a resource on the ClassLoader)

Install Maven on Windows 7

Steps

1. Download the latest Maven distribution zip from http://maven.apache.org/download.html

2. Extract the Zip

    bildschirmfoto2010-09-28um10-14-35.png

    3. Consult the README.txt. Here you will a description of the following steps.

      4. Add Maven to your path. The procedure is similar as described here for Windows Vista: http://www.java.com/en/download/help/path.xml

        5.You might also have to add the JAVA_HOME environment variable: http://stackoverflow.com/questions/2619584/how-to-set-java-home-on-windows-7

          6.Don‘t forget to restart your command line window (cmd.exe)

            7.You can test maven by starting the command line cmd.exe and type „mvn“

              SVN Ignore Eclipse Project Files

              Problem

              How to stop svn from synchronizing eclipse meta data in a project (eg .project files)

              Solution

              Add a number of project specific or global svn ignore directives. In the latter case, eclipse meta data will be ignored in all of your projects.

              You can add the following pattern for exclusion

              .eclipse
              .settings
              .project
              .classpath

              Below the eclipse settings to add global ignore pattern:

              bildschirmfoto2010-09-28um09-37-521.png

              GWT + OSGi + Maven

              Summary:

              Some steps and resources to set up a GWT project, which uses OSGi and Maven. However, these steps do not lead to a fully working GWT application. The main difficulty lies in the Server side, where the GWT servlets do not start up properly in the OSGi environment. I plan to implement the server using the Restlet framework, what should mitigate this problem.

              Steps:

              Create a new GWT project in eclipse

              Add a new XML file pom.xml to the project

              pom.xml in github

              Now you should be able to create eclipse metadata using the eclipse:eclipse goal as well as compile and start the GWT project using gwt:compile, gwt:…

              Alternative:

              Set up a new plugin project in eclipse for the gwt.user package.

              bildschirmfoto2010-09-26um15-25-03.png

              bildschirmfoto2010-09-26um15-25-24.png

              bildschirmfoto2010-09-26um15-26-40.png

              … and add the GWT user package to this package to keep it seperate from the bundle with your application.

              Now you can remove the dependency to the GWT user package from the pom above.

              Resources

              Run GWT hosted mode in OSGi: http://efreedom.com/Question/1-3060682/Debug-GWT-Application-Running-OSGi

              Google Web Toolkit and Equinox (from eclipse wiki): http://wiki.eclipse.org/Google_Web_Toolkit_and_Equinox
              (One project with an example GWT/OSGi project http://sourceforge.net/projects/sse-examples/develop)

              Example project attempting to route GWT RPC calls to OSGi services: http://code.google.com/p/gwt-in-osgi/source/checkout

              Tutorial using the Servlet Bridge: http://angelozerr.wordpress.com/2010/09/02/osgi-equinox-in-a-servlet-container-step2/

              Overview developing web applications with OSGi (German) http://www.wuetherich.com/public/ruhrjug-2009-05/mit-osgi-webanwendungen-entwickeln.pdf

              Tutorial HttpService by example: http://www.dynamicjava.org/articles/osgi-compendium/http-service

              OSGi and GWT integration report: http://www.morelab.deusto.es/morelab/media/OSGiGWT.pdf

              Issue discussing calling GWT servlets hosted in a OSGi environment: http://code.google.com/p/google-web-toolkit/issues/detail?id=1888

              Setting up and starting a web server in eclipse PDE (Quickstart)

              The following describes a number of simple steps to set up and start up a web server in the eclipse PDE environment.

              Steps

              1. Create a new OSGi run configuration
              1. Add the package org.eclipse.equinox.http.jetty

              bildschirmfoto2010-09-25um19-11-59.png

              1. Click on „Add Required Bundles“

              A number of bundles should have been added to your run configuration.

              bildschirmfoto2010-09-25um19-13-53.png

              1. Go to the tab arguments and add the VM argument: „ -Dorg.osgi.service.http.port=8080“

              bildschirmfoto2010-09-25um19-14-45.png

              Result

              Now you should be able to start up the server by starting the run configuration. You can check if the server is running by opening the URL http://localhost:8080/. It should show an error message as the following:

              bildschirmfoto2010-09-25um19-16-31.png

              Resources

              Building a server based Application with Equinox (on eclipse.org): http://www.eclipse.org/equinox-portal/tutorials/server-side/

              Building a web server in Felix by using wars: http://heapdump.wordpress.com/2010/03/25/osgi-enabled-war/

              Alternative way: starting Equinox as deployed application on a web server and let this bundle load osgi modules: http://angelozerr.wordpress.com/2010/09/01/osgi-equinox-in-a-servlet-container-step1/

              Scroll down to Server-Side
              http://wiki.eclipse.org/Equinox_Eclipse_to_RT_Migration

              The core bundle to start server
              http://www.eclipse.org/equinox/server/http_in_equinox.php
              org.eclipse.equinox.http.jetty

              Equinox Server Side info: http://www.eclipse.org/equinox/server/http_quickstart.php

              Slides giving a good overview:

              Deployment of GWT Applications (Part 2)

              Purpose

              Show using the example project created in part 1 different ways in which a GWT application can be deployed. In a nutshell, the html file of your application can be deployed to any place you desire – another server or even a local machine. However, the generated JavaScript needs to remain on the same server, which hosts the RPC services your application uses.

              Overview

              I think the GWT technology presents itself as less versatile as it actually is. This might be due to Google‘s desire to integrate GWT application with Google Apps Engine (GAE). However, although this might make your life easier in many cases, I think GAE binds you to Google‘s platform, which might not always be desirable. Google Web Toolkit, in contrast, however is highly vendor independent. It build on top of powerful technologies like Java and JavaScript and can be deployed to any server environment.

              In part 1, I have already illustrated that the application can run in hosted mode on your local development machine but can also be deployed to a servlet container such as tomcat. This makes the project available under the URL for the servlet package. In below picture, the name of the package is zzSampleGWT204Project-0.0.1-SNAPSHOT and the project can be accessed by opening this URL under the servlet container.

              bildschirmfoto2010-09-19um14-23-34.png

              However, the application can basically be deployed by using just two files from the generated WAR file. To illustrate this, we can create a new Dynamic Web Project in eclipse. Copy the html and css files from your GWET projects webapp folder into the „WebContent“ folder of this application.

              bildschirmfoto2010-09-19um17-48-23.png

              Now we only need to change the link to the generated JavaScript in the .html file. Add ../[Name of the deployed project to the server

              <script type=“text/javascript” language=“javascript” src=“../zzSampleGWT204Project-0.0.1-SNAPSHOT/zzsamplegwt204project/zzsamplegwt204project.nocache.js”></script>

              You can export (select export as WAR file) this dynamic web file and upload it to the same tomcat server.

              Under the URL of your newly deployed project you are able to access your GWT application.

              bildschirmfoto2010-09-19um14-23-14.png

              This is possible based on the Same Origin Policy (SOP) as both of our HTML pages access the same JavaScript file which interfaces with the GWT RPC.

              We can download this html file to our local desktop. We will find that the application does nothing when we open the locally downloaded HTML file. This is because GWT disables cross site access for your applications by default. You can enable cross site access by adding the following line to your module descriptor (.gwt.xml).

              <add-linker name=“xs” />        

              Recompile the GWT application and deploy it to tomcat again.

              Now open the html file you have downloaded and change the location of the script to the absolute location on your webserver.

              <script type=“text/javascript” language=“javascript” src=“http://[your server address]:8080/zzSampleGWT204Project-0.0.1-SNAPSHOT/zzsamplegwt204project/zzsamplegwt204project.nocache.js”></script>

              Now you can open the html file on your local desktop and the application should work from this html file as well.

              bildschirmfoto2010-09-19um14-22-14.png

              But remember that this application not just downloads the JavaScript from the server but also access the GWT RPC from the same server. You cannot download the JavaScript file to your local machine. Then you would not be able to call the GWT RPC service anymore as you would violate the Same Origin Policy (SOP).