File Upload in Servlet 3.0

Nikolaus Gradwohl2010-09-01T19:35:00+02:00

I played around a bit with the new servlet-api 3.0 and tomcat7 and i really like it. it has some nice features like servlet declaration using annotations or the support for asynchornous requesthandling, but the feature that i really really love is the support for file upload.

To handle a file upload form like this

<html>
<body>
<form action="upload" enctype="multipart/form-data" method="post">
<input type="file" name="filename"/>
<input type="submit" value="submit"/>
</form>
</body>
</html>

is to mark the servlet with an annotation and access the uploaded file using 'request.getPart("filename")' like this

package at.hpc.servlettest;

import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;

@WebServlet(name="testUpload", urlPatterns={"/upload"})
@MultipartConfig
public class TestUpload extends HttpServlet {
    protected void doPost( HttpServletRequest req, HttpServletResponse res ) 
               throws ServletException, IOException {
        Part part = req.getPart("filename");

        res.setContentType( part.getContentType());
        res.setHeader( "disposition", "inline" );

        OutputStream out = res.getOutputStream();
        InputStream in = part.getInputStream();

        byte buffer[] = new byte[ 4048 ];
        int n = 0;
        while ((n = in.read( buffer )) > 0) {
            out.write( buffer, 0, n );
        }
        out.close();
    }
}

This is a really silly example that just copies the uploaded file back to the browser, but it shows how clean and simple handling fileuploads gets with this api - this is the feature i have been waiting for years!

read more ...

OutOfIdeasException

Nikolaus Gradwohl2010-06-22T20:46:00+02:00

hmmmmmm - todays project for 30daysofcreativity is...

guru.OutOfIdeasException()
    at guru.bodyparts.head.Brain.think()
    at.guru.bodyparts.head.Head()
    at.guru.body.Main().run()
read more ...

Deploying Processing apps using WebStart

Nikolaus Gradwohl2010-01-11T11:22:00+01:00

To deploy a processing sketch via java webstart export the sketch as an application (i used my randomlines sketch and exported it as a linux application).

then i wrote a simple jnlp file and copied the files to my webserver. The only thing thats left is providing a link to the jnlp file like this.

click here to dowload and launch the application

More info on jnlp and webstart can be found here

test.jnlp

<?xml version="1.0" encoding="UTF-8"?>
<jnlp spec="1.0+" codebase="" href="">
    <information>
        <title>Processing Test</title>
        <vendor>guru</vendor>
        <icon href="http://www.local-guru.net/jnlp/randomlines/randomlines.png"/>
        <desktop/>
        <offline-allowed/>
        <shortcut online="false">
              <desktop/>
        </shortcut>
    </information>
    <resources>
        <j2se version="1.5+" href="http://java.sun.com/products/autodl/j2se"/>
        <jar href="http://www.local-guru.net/jnlp/randomlines/lib/randomlines.jar" main="true" />
        <jar href="http://www.local-guru.net/jnlp/randomlines/lib/core.jar" main="true" />
    </resources>
    <application-desc
         name="ProcessinTestApp"
         main-class="randomlines"
         width="300"
         height="300">
     </application-desc>
     <update check="background"/>
</jnlp>
read more ...

Handassembled java bytecode

Nikolaus Gradwohl2009-03-03T04:25:00+01:00

motivated by my hand written x86 machinecode, i decided that i had to take it to the next level.

i worte some handassembled java bytecode. run the file below as

./dump.sh > HelloAsm 

and run the programm with

java HelloAsm
read more ...

switching java-versions in ubuntu

Nikolaus Gradwohl2009-01-23T15:19:00+01:00

to switch between 2 installed versions of the jdk in ubuntu 2 commands are needed:

sudo update-alternatives --config java

is used to choose the java version

sudo update-alternatives --config javac

is used to change the javac version

read more ...

Javadeus08

Nikolaus Gradwohl2008-06-20T05:44:00+02:00

Yesterday i attended to the javadeus08, the first java-conference by sun in austria.

Most of the sessions were really interesting, and i definitly have to give jmaki a try :-)

The only thing, that annoyed me, is that there was no free wlan and that even the speakers had a veeeeeeeeery slow connection for their demos

read more ...

simple Java Set/Map initialization

Nikolaus Gradwohl2008-04-20T07:55:00+02:00

When you need a array in java filled with some data, initializing it is easy

String[] bla = new String[] { "Foo", "Bar", "Bla" };

and done. but when you need a Map or a Set prefilled with some data it starts getting complicated. you can either use a static initializer block like

public class Bla {
    static Set<String> dings;
    static {
        dings = new HashSet<String>();
        dings.add("foo");
        dings.add("bla");
    }
}

or you fill your set or map in the contructor if it is still null (be carefull if you use this in a multithreaded application)

another way i have learnd at the last jax is using this code

public class Bla {
    static Set<String> dings = new HashSet<String>() {{ 
        add("Foo"); add("Bar"); add("Bla"); }};
}

neat isn't it?

this also works with a Map

public class Bla {
    static Map<String,String> dings = new HashMap<String,String>() {{ 
        put("k1", "Foo"); put("k2", "Bar"); put("k2", "Bla"); }};
}
read more ...

Using "functional"-Programming to map Resultsets to POJOs

Nikolaus Gradwohl2007-09-26T20:40:00+02:00

When I use jdbc to develop a small tool, where using a OR-Mapper like Hibernate is overkill, I always dislike that i have to dublicate all the "getStatement" "execQuery" "while (resultSet.next())" stuff.

i dont like to repeat stuff in my code. It would be very easy if java had closures, but i dont want to wait until java7 to simplify my code so I needet another idea.

java has no closures but it has something that can be used in a similar manner - Anonymous inner classes.

so to simplify the following class

Connection con = getConnection()
Statement st = con.createStatement();
ResultSet rs = st.executeQuery( "sqlstring");
List<Foo> result = new ArrayList<Foo>();
while (rs.next()) {
    Foo f = new Foo();
    f.setProperty1( rs.getString( "property1" ));
    f.setProperty2( rs.getString( "property2" ));
    result.add( f );
}
// imagine catch/finaly block here
st.close();
con.close();

i define a interface called Function

interface Function<T> {
    public T valueOf( ResultSet rs ) throws SQLException;
}

Then i define a QueryMapper like this

public class QueryMapper<T> {
    private Database db;
    public QueryMapper( Database db ) {
        this.db = db;
    }

    List<T> listOf( Function<T> f, String query ) {
        List<T> res = new ArrayList<T>();
        Resultset rs = ... get resultset for query ..
        while ( rs.next() ) {
            res.add( f.valueOf( rs ));
        }
        // catch/finaly block here
        return res;
    }
}

So all i have to do in my code now is calling

Function<Foo> fn = new Function<Foo>() {
    public Foo valueOf( ResultSet rs) throws SQLException {
        Foo res = new Foo();
        res.setPropery1( rs.getString( "property1" ));
        res.setPropery2( rs.getString( "property2" ));
        return res;
    }
}

QueryMapper<Foo> qm = QueryMapper<Foo>( db );
List<Foo> res = qm.listOf( fn, "select * from foo");

I can even recycle the Function objects ( if i query different object of the same type but with different ids for example ) thats more how i like it

read more ...

Jax2007

Nikolaus Gradwohl2007-04-26T11:25:00+02:00

Im currently sitting in Wiesbaden at the Jax2007 (missing a keynote from SAP :-) ) i've seen a lot of new interessting tools and techniques which will keep me busy some times.

webtest from canoo, for example has evolved in a very interesting way since i gave it the last try,

one thing that many of the speakers are showing ist the tendency to use more languages on the JVM and choose the right tool for the problem. and not let the language shape the solution.

there were some nice sessions showning how to generate textual DSL with ruby or open architecture ware.

this time there were some netbeans sessions where new features from the upcoming netbeans 6 release where shown - realy nice

and i heard abount ApacheDS a ldap server which is completely written in java and can be embedded into other applications.

ok the sap keynote is comming to an end - i will go to the next session now ...

read more ...

the Future and Java 1.5

Nikolaus Gradwohl2007-01-21T11:09:00+01:00

Java 1.5 introduced a bunch of new classes for handling multithreaded programming. The one I realy like the most is Future.

With future its possible to start the calculation of something you know you will need at a later point in yout programm. When you reach that point you can call Future.get() to fetch the result of the calculation. If it is already avaliable the result is returned immediately, if the calculation is still running or has not started yet Future.get() blocks until the results are here.

one gets a future by submitting an object implementing Runnable or Callable to an ExecutorService. This is an interface that is implemented by ThreadPoolExecutor.

ExecutorService e = Executors.newSingleThreadExecutor();
Future<String> future = e.submit(callable);
...
String result = future.get();

This Class implements a queue and a threadpool. using ExecutorService.submit() you can put some Workload in an queue, from where the threads of the pool will fetch and execute them. the submit method returns an Future which can be used to fetch the results of the workload.

There are various preconfigured Threadpools available from Executors Class. For example

ExecutorService e = Executors.newSingleThreadExecutor(); 

creates a degenerated Threadpool using just one thread. This is very usefull if one has to garantee that no two instances of the submitted callable are executed at the same time. If you have to use an external service that is implemented by offering an api via webservice thats not threadsave beacause of a missing transaction handling, this SingleThreadExecutor can be used to serialize the requests comming from a webapplication. All the clientrequests can be spooled in the executor service but all the calls to the service api are strictly searialized.

Another very usefull class is

ExecutorService e = Executors.newCachedThreadPool()

this is what most people think of when they refere to a threadpool. The class generatets new threads if needed but reuses existing ones if they do idle. Threads that are not used for 60 seconds are removed from the pool.

ExecutorService e = Executors.newFixedThreadPool(n)

creates a Threadpool containing n threads. No new threads are generated an there also is no timeout. SingleThreadExecutor is an fixedThreadPool with n = 1.

I think the java.util.concurrent package is the one of the best things that got introduced with java 1.5.

read more ...