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).

              Restlet Server: OSGi and Maven

              Here a collection of links regarding the Restlet Framework (restlet.org) and how to use it with Maven and OSGi

              OSGi + Restlet

              Three blog posts on building restlet based web services using Equinox

              Mail discussion: Adding OSGi as another protocol to Restlet

              OSGi

              Equinox Server-side Quickstart

              Equinox Server Project on eclipse.org

              Restlet + Maven

              Official Restlet Maven repository

              Restlet

              Using Restlet as a WebServer rerouting requests to a number of other servers (from restlet.org documentation)

              Simple Restlet Demo Application inside Servlet container (showing how to use Application and Resources)

              Host a Restlet server inside a Servlet container (eg tomcat) (from restlet.org documentation)

              Applications using Restlet: Hackystack, restlet.org

              Tutorial Set up a servlet based Restlet service

              Serving Restlet Files from within the current jar/project/webarchive

              Mail Discussion about how to serve files from within a war
              Mail Discussion about how to server files using the clap protocol Restlet documentation CLAP protocol

              Maven, GWT and Eclipse Quick start (Part 1)

              Purpose

              Getting started with a GWT project, which utilizes Maven build management and is still compatible with the eclipse Google Plugin, can be quite complex. Especially if one is not familiar with Java web applications and/or Maven. This post starts with the simplest possible GWT project, created by the Google Plugin for eclipse. Then we manually add a pom to the project and compile the project with Maven.

              Instructions

              As of now only works for 2.0.4 (see problems with 2.1 below)

              1. Download and Install the Google Plugin for Eclipse
              2. Create a new Web application project

              You can name the project „zzSampleGWT204Project“ and use the package „de.mxro.zz.zzsamplegwt204project“ to make following the succeeding steps easier.

              bildschirmfoto2010-09-18um17-35-471.png

              1. You should be able to Compile this project (using GWT compile) and run it (will require you to open the provided URL in Safari)
              1. Create a new XML file „pom.xml“ on the root of the project

              bildschirmfoto2010-09-18um17-38-331.png

              bildschirmfoto2010-09-18um17-40-331.png

              1. Use the following pom.xml as starting point (you might want to change artifact id etc).

              View and download pom.xml

              1. You will need to change the project structure a little bit to conform with the maven convention.

              - Right click the folder src and select „remove from build path“
              - Create a new source folder at src/main/java

              bildschirmfoto2010-09-18um18-16-351.png

              bildschirmfoto2010-09-18um18-16-471.png

              - right click the source folder inside the src folder and select „move“ – move the source folder the the src/main/java

              bildschirmfoto2010-09-18um18-18-041.png

              - Move the war folder into the folder scr/
              bildschirmfoto2010-09-18um19-49-431.png

              - rename the war folder to „webapp“

              bildschirmfoto2010-09-18um19-50-591.png

              - change the WAR directory path in the project settings (right click the project and select properties)

              bildschirmfoto2010-09-18um19-51-461.png

              1. Go the project folder on the command line and type „mvn verfiy“
              1. Maven should download the necessary libraries (what might take a while), compile Java and GWT classes and create a war package in the folder target

              bildschirmfoto2010-09-18um20-06-111.png

              1. You can deploy this war file to a servlet container (eg tomcat) – the sample application should run there as in the hosted mode

              bildschirmfoto2010-09-18um19-55-061.png
              bildschirmfoto2010-09-18um19-55-311.png

              Closing Remarks

              - You can also test your server right from the command line by typing „mvn gwt:run“

              bildschirmfoto2010-09-18um20-23-481.png

              - It should still be possible to run the project from eclipse. This is only a simple introductory example: Maven and eclipse work beside each other rather than being integrated. It would be better to be able to use the Maven eclipse plugin to handle the dependencies in eclipse.

              You can create the eclipse project files using the command „mvn gwt:eclipse“. However, you might have to change the export order of the associated libraries to make eclipse recognize the gwt skds.

              === Does not work ===

              … because there are no „Mac“ artefacts for 2.1.0.M3 or 2.1-SNAPSHOT …

              1. Create a new project using the GWT archetype

              mvn archetype:create -DarchetypeGroupId=com.totsp.gwt -DarchetypeArtifactId=maven-googlewebtoolkit2-archetype -DarchetypeVersion=1.0.4 -DremoteRepositories=http://gwt-maven.googlecode.com/svn/trunk/mavenrepo -DgroupId=myGroupId -DartifactId=myArtifactId

              1. Add the codehaus maven repository and the Google Web Toolkit Repository

              <repository>
              <id>codehaus-maven-repo</id>
              <name>Codehaus repo</name>
              <url>http://repository.codehaus.org/org/codehaus/mojo/</url>
              </repository>
              <repository>
              <id>gwt-repo</id>
              <url>http://google-web-toolkit.googlecode.com/svn/2.1.0.M3/gwt/maven</url>
              <name>Google Web Toolkit Repository</name>
              </repository>

              1. Update GWT Version

              <properties>
                              <gwtVersion>2.1-SNAPSHOT</gwtVersion>
                      </properties>

              1. Download the libraries using „mvn verify“

              Resources:

              There is a post on the Google Web Toolkit Blog discussing how to use GWT with Maven and the eclipse plugins

              Step by step of creating a GWT project with Maven

              Work Pattern: Explore, Tag, Collect (ETC)

              A work pattern for explorative investigations, which should result in a structured collection, for instance a Literature Review.

              Step 1: Explore

              Browse through potential sources for your collection. Possible tools for this are databases, search engines or feed aggregators (eg Google Reader).

              Step 2: Tag

              Tag articles or places you think might be of relevance. Do not think of a complex and sophisticated typology for tags but rather use a generic „might be interesting tag“. In Google Reader, for instance, this can be achieved by ‚starring‘ relevant articles. In other contexts, you could email yourself a copy of the respective article. For academic research you can try to collect the full references if it can be achieved effortlessly (for instance from databases interfacing with online bookmark managers like cituelike.org).

              The main objective for the steps 1 and 2 is speed and openness. Try to explore as many sources as possible an be open to novel roads.

              Step 3: Collect

              With a little time difference, go back to the tagged resources. Flip through them and reflect whether you still find them relevant. If you think so, you can add these articles to a collector. A collector is a vehicle which helps you to organize and classify the pieces of information you have found. This can for instance be a long essay with many essays, where you can add the pieces of information as references to relevant sections. It can also be a classification typology of tags or other forms to structure your information.