Annotationen in Spring 2.0/2.5 für Autowire und neue Beans

Bis Spring 2.0 gab es im Wesentlichen nur eine Möglichkeit, Spring-Beans zu deklarieren und Bean-Referenzen zu injizieren. Ab Spring 2.0 und besonders in Spring 2.5 gibt es einen Richtungswechsel. Statt Bean-Definitionen und Injizierungsanweisungen ausschließlich über XML-Dokumente zu beschreiben, kommen Annotationen hinzu. Spring nutzt zum Einen Standard-Annotationen aus Java 6 (Common Annoations) aber auch eigene.

Nehmen wir zwei Beans an:

    <bean id="today" class="java.util.Date" /> 
<bean id="calendarPrinter"
class="com.tutego.spring.annotation.CalendarPrinter" />

Die Bean CalendarPrinter soll ein Datum injiziert bekommen.

    public class CalendarPrinter { 
public void setDate( Date date ) …

Über XML lässt sich das einfach beschreiben, doch seit Spring 2.5 veranlasst eine Annotation Spring dazu, die Verweise automatisch zu injizieren:
@Autowired

@Autowired ist eine Annotation für Methoden und Attribute, damit Spring selbständig den Verweis setzt:

    public class CalendarPrinter { 
@Autowired
public void setDate(@Qualifier("today") Date d) …
}

Die Annotation @Qualifier ist nur dann nötig, wenn es mehrere Beans dieses Typs gibt. (Nicht bei uns.)

Damit Spring überhaupt die Verknüpfung vornimmt, ist in der XML-Datei ein Hinweis zu setzen.

Die erste Möglichkeit ist:

    <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>

Eine im Allgemeinen bessere Alternative (die AutowiredAnnotationBeanPostProcessor und CommonAnnotationBeanPostProcessor zusammenfasst) ist

    <context:annotation-config/>

Die Annotation @Autowired ist genauso gültig bei Attributen:

    public class CalendarPrinter 
{
@Autowired Date date;

      public void doIt()
      {
        System.out.println( date );
      }
    }

<beans xmlns="http://www.springframework.org/schema/beans" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:annotation-config/>
<bean id="today" class="java.util.Date" />
<bean id="calendarPrinter" class="com.tutego.spring.annotation.CalendarPrinter" />
</beans>

Java 6 (für Java 5 ist ein Extra-Jar nötig) führt aus JSR-250 die Lebenszyklus-Annotationen @PostConstruct und @PreDestroy sowie @Resource ein.

    public class CalendarPrinter { 
@PostConstruct public void initialize() {
System.out.println( "init" );
}
/* @PreDestroy public void remove() {
System.out.println( "destroy" );
} */
}

Beans deklarieren

Die Verknüpfung ist durch Autowire automatisiert und minimiert die XML-Konfigurationsdatei.
Zum Deklarieren von neuen Beans bringt Spring ebenfalls Annotationen mit.
Statt in der XML-Datei zu schreiben

    <bean id="calendarPrinter" class="com.tutego.spring.annotation.CalendarPrinter" /> 

können wir annotieren:

    @Component class CalendarPrinter

Damit Spring nach annotierten Beans sucht, ist nötig:

    <context:component-scan base-package="com.tutego.spring" />

Die Annotation @Component ist an allen Typen erlaubt und natürlich zur Laufzeit sichtbar:

    @Target(value=TYPE) 
@Retention(value=RUNTIME)
@Documented
public @interface Component
{
String value();
}

API zur Eigenschaft: „The value may indicate a suggestion for a logical component name, to be turned into a Spring bean in case of an autodetected component.“

Geben wir dem CalendarPrinter den Bean-Namen „ cal-printer“:

    @Component("cal-printer") 
public class CalendarPrinter

Aus dem ApplicationContext genommen folgt:

    ApplicationContext context = 
new ClassPathXmlApplicationContext( … );
Object bean = context.getBean( "cal-printer" );
System.out.println( bean.getClass() );
// class com.tutego.spring.annotation.CalendarPrinter

@Component ist eine sehr allgemeine Annotation.

Besser ist es, semantische Annotationen zu nutzen, die @Component erweitern. Spring liefert drei mit:

  1. @Target(value=TYPE) … @Component
    public @interface Repository
  2. @Target(value=TYPE) … @Component
    public @interface Service
  3. @Target(value=TYPE) … @Component
    public @interface Controller

Thema der Woche: Datum und Zeit

An der Datum/Zeit-API wird schon ewig rumgemeckert, und jetzt soll es wirklich gut werden. Lies zunächst die API-Dokumentation der zentralen Standard-Klassen:

  • Date
  • DateFormat
  • SimpleDateFormat
  • Calendar
  • GregorianCalendar

Was sind die Argumente der Kritiker?

Eine hervorragende Open-Source-Biblitohek ist http://joda-time.sourceforge.net/. Was macht Joda-Time anders/besser?

Die https://jsr-310.dev.java.net/ möchte endlich eine tolle Datums/Zeit-API in das Standard-Java Version 7 bringen. Was unterscheidet Joda-Time von JSR 310?

Thema der Woche: Inversion Of Control/Dependency Injection

Komponenten müssen in irgendeiner Weise auf Dienste (Services) zurückgreifen. Diese Dienste könnte entweder in die Komponenten injiziert werden oder eine Komponente bezieht den Dienst über eine zentrale Service-Factory. Vergleiche die Ansätze Service-Locator und IoC (Spring-Beispiele).

Spring ist nicht der einzige IoC-Container. Verschaffe einen Überblick über

Ob nun IoC grundsätzlich die Beste Lösung ist, oder ob nicht eine einfache Zentrale reicht, ist Thema von http://lateralprogramming.wordpress.com/2008/04/07/why-use-spring-if-you-have-a-hashmap-at-hand/.

Aufgabe:

  • Welcher fundamentale Unterschied hat Google Guice gegenüber Spring?
  • Frage Google Trends, wie sich die beiden IoC-Framwork sich in letzter Zeit entwickelt haben.

Thema der Woche: Apache Commons

Die Apache-Group hat mit ihren vielen Projekten irgendwann bemerkt, dass sie einige Dinge immer wieder programmieren. So ist nach und nach http://commons.apache.org/ entstanden, ein Projekt, welches viele Hilfsklassen implementiert.

Vertiefe in http://commons.apache.org/io/ und http://commons.apache.org/lang/ und schaue in die Typbeschreibung jeder Klasse/Schnittstelle.

  • Programme eine Beispielprogramm, bei dem die toString()-Methode generisch über ToStringBuilder aufgebaut wird.
  • Schreibe ein paar Demos, die Funktionen aus StringUtils, WordUtils nutzen.
  • Kopiere eine Datei von einer Stelle zur anderen.
  • Nutze passende Klassen/Funktionen aus org.apache.commons.io.filefilter um in einem Vergleiche alle Dateien zu finden, die (älter ein als gewisses Datum sind UND über einer gewissen Größe liegen) ODER (auf eine bestimmte Dateiendungen, wie doc oder rtf, enden).

Thema der Woche: Bytecode und Obfuscator

Wie jeder weiß, produziert der Java-Compiler in der Regel Bytecode. Um eine Vorstellung davon zu bekommen, sollte man lesen

Dann je nach Wunsch weitere Kapitel aus der Java Virtual Machine Specification; da ist aber jede Waschmaschine spannender.

Java Bytecode lässt sich disassemblieren, etwa mit javap. Hier sollte man ein Beispiel ausprobieren.

Um den Bytecode unansehnlich zu machen, lässt sich ein Obfuscater einsetzten. Teste die Möglichkeiten von http://proguard.sourceforge.net/ an einem Beispiel.

JVM auf iPhone

Apple ist zwar bisher gegen eine Java VM (und auch gegen Flash — angeblich zu langsam, hahaha), aber Sun hat eine Implementierung für das iPhone angekündigt:

Da das iPhone auf OS X 10 basiert (http://www.roughlydrafted.com/2007/07/13/iphone-os-x-architecture-the-mach-kernel-and-ram/), ist es durchaus möglich, das Sun auch für „normale“ Apple-Computer ein JDK ausliefert. Wenn bei Sun schon Linux, Solaris und Windows dazugehört, passt OS X auch noch ganz gut rein.

Thema der Woche: PDF-Dokumente

PDF ist ein Standard-Dokumentenformat geworden, an dem man nicht vorbeikommt.

Java bietet eine Reihe von Bibliotheken an, die PDF-Dokumente verfassen und darstellen. Bekannter sind:

Was sind Bibliotheken zum Anzeigen und Erstellen? Welche Einschränkungen sind bekannt? Was kann man mit http://djproject.sourceforge.net/ns/ machen?

Erstelle mit iText aus den Kurzbeispielen http://itextdocs.lowagie.com/tutorial/ eine PDF mit Absätzen, einfachen Tabellen und Bildern. Zeige die PDF mit dem https://pdf-renderer.dev.java.net/ an.

Microsoft versucht mit dem XPS-Standard (http://en.wikipedia.org/wiki/XML_Paper_Specification) eine Alternative zu etablieren. Gibt es dazu irgendwelche Java-Bibliotheken?

Java Swing Framework hat sich wohl erledigt

Das AppFramework (RI von JSR 296) ist wohl tot. Von Pushing-Pixels:

Hans Muller confirms what many have already guessed. His e-mail on the users mailing list of AppFramework (reference implementation of JSR 296) confirms that the development of this project has been dead since last November and will continue to be so through this summer. The subsequent discussion on the mailing list indicates that it is quite unlikely that somebody will step up and be able to provide leadership that is much needed for JSR-level projects. The inclusion in JDK 7 looks like it’s in jeopardy as well.

Hans Muller schreibt dazu:

I’m the spec lead for JSR-296 and the only developer as well. I’ve been neglecting the project for the past several months to focus exclusively on Sun’s Java FX initiative. You can see the results of some of that work in the Scenario project (http:www.scenegraph.dev.java.net), and before too long in the revised („Reprise“) version of the graphics/UI library for the FX Script language. I’d originally expected to be heads-down on FX for a couple of weeks and then after that return to devoting part of my time to this project. Unfortunately that hasn’t happened and it’s unlikely to change through this summer.

I’m proud of how far along Application Framework is and it’s inspiring to see how the developer community has responded. It’s particularly gratifying to see questions asked and answered on this list and proposals floated and discussed. I’d like to restore the project’s ability to make some progress, by adding a few developers to the project who’ll be able to update the code and make decisions about how to evolve the design. If you’re interested and if you feel you have the time and the right kind of experience, please send me an email. I’m going to try and resolve this in the next week or so.

Tja. Hoffentlich bleibt dann das Bean-Binding stehen. Obwohl — da schreibt Pushing-Pixels weiter:

John O’Connor has an article on Beans Binding (reference implementation of JSR 295). Unfortunately, these two projects are twin victims of JavaFX for the better part of this year, and one could only hope that JavaFX will live up to its promise and to the investment in engineering resources that have been subverted to it.

So viel zum Thema: „Wir bringen Java zurück zum Desktop. In Java 7.“ Klar.

Thema der Woche: Unicode und Kodierungen

Java verarbeitet Zeichen (bisher) intern in 2-Byte Unicode. Gespeichert werden Daten aber in der Regel in UTF-8 oder, für uns in Europa, in Latin-1. Thema der Woche ist Unicode und die Umkodierungen. Am Anfang sollen The Ten Commandments of Unicode von Elliotte Rusty Harold stehen:

  1. I am Unicode, thy character set. Thou shalt have no other character sets before me.
  2. Thou shalt carefully specify the character encoding and the character set whenever reading a text file.
  3. Thou shalt not refer to any 8-bit character set as “ASCII”.
  4. Thou shalt ensure that all string handling functions fully support characters from beyond the Basic Multilingual Plane. Thou shalt not refer to Unicode as a two-byte character set.
  5. Thou shalt plan for additions of future characters to Unicode.
  6. Thou shalt count and index Unicode characters, not UTF-16 code points.
  7. Thou shalt use UTF-8 as the preferred encoding wherever possible.
  8. Thou shalt generate all text in Normalization Form C whenever possible.
  9. Thou shalt avoid deprecated characters.
  10. Thou shalt steer clear of the private use area.

Da schließen sich nun einige Fragen an, die es zu klären gilt:

  • Was ist der Unterschied zwischen ASCII, Unicode 2 und Unicode 4?
  • Was ist ein Code-Point? Welche Funktionen in Java 5 sind wegen Unicode 4 hinzugekommen? Welche beiden Funktionen zum Zugriff auf ein Zeichen gibt es? Resultieren daraus Performance-Unterschiede?
  • Was ist eine Kodierung? Wie wird sie in Java bestimmt? Durch einen String oder durch eine Klasse?
  • Welchen Funktionen/Konstruktoren der Java Klassenbibliothek nehmen eine Kodierungskennung entgegeben? Nenne mehrere Wege, wie man Strings/Byte-Felder umkodiert.
  • Gibt es XML-Parser in Java, die Unicode 4 unterstützten? Was sagen die Autoren von XML-Parsern zu Unicode 4?
  • Warum kann es beim Datenbankzugriff auf Textspalten Probleme geben? Gibt es dokumentierte Probleme/Lösungen?

Auch neu: tutego’s Clip-Art Seite. Links zu weiteren Clip-Art Sammlungen (ohne die lästigen Popup-Menüs) sind willkommen.

Neues aus EJB 3.1

Einige Änderungen aus dem Preview der EJB 3.1 Specification.

Es gibt neu auch Singleton Session Beans, die mit @Singleton annotiert sind:

The EJB specification defines stateful, stateless, and singleton session beans. There are differences in
the API between stateful session beans, stateless session beans, and singleton session beans.

4.7 Singleton Session Beans
A Singleton session bean is a session bean component that is instantiated once per application. In cases
where the container is distributed over many virtual machines, each application will have one bean
instance of the Singleton for each JVM.
Once instantiated, a Singleton session bean instance lives for the duration of the container in which it is
created. It maintains its state between client invocations but that state is not required to survive container
shutdown or crash.

Man kann für lokale Beans auf eine Business-Schnittstelle verzichten:

In EJB 3.x, a local client accesses a session bean through the bean’s local business interface or through
a no-interface client view representing all the public methods of the bean clas
s.

3.4.2 Obtaining a Reference to the No-interface Local View
A client can obtain a reference to a Session Bean’s No-interface Local View through dependency injection
or lookup in the JNDI namespace.
For example, the No-interface Local view of the CartBean session bean with bean class com.acme.Cart-
Bean may be obtained using dependency injection as follows :
@EJB CartBean cart;
The CartBean No-interface view could also be looked up via JNDI as shown in the following code segment
using the lookup method provided by the EJBContext interface. In this example, a reference to
the client bean’s SessionContext is obtained through dependency injection:
@Resource SessionContext ctx;

CartBean cart = (CartBean)ctx.lookup(“cart”);
Despite the fact that the client reference for the No-interface Local view has type <bean class> , the client
never directly uses the new operator to acquire the reference.

3.4.4 Session Bean’s No-Interface Local View
A Session Bean’s no-interface view is a variation of the Local view that exposes the public methods of
the bean class without the use of a separate business interface.
A reference to the no-interface view may be passed as a parameter or return value of any Local business
interface or no-interface view method.
The container provides an implementation of a reference to a no-interface view such that when the client
invokes a method on the reference, the business method on the session bean instance and any interceptor
methods are invoked as needed.
Only public methods of the bean class (and any super-classes) may be invoked through the no-interface
view. Attempted invocations of methods with any other access modifiers via the no-interface view reference
result in the javax.ejb.EJBException.
It is invalid to reference a session object that does not exist. If a stateful session bean has been removed,
attempted invocations on the no-interface view reference result in the javax.ejb.NoSuchEJBException.

Neu ist, das eine Session-Bean synchron oder asynchron aufgerufen werden kann:

3.4.8 Asynchronous Invocations
By default, session bean invocations through the Remote, Local, and no-interface views are synchronous,
meaning the client blocks for the duration of the invocation and is returned control only after all
invocation processing has completed. Clients can achieve asynchronous behavior by invoking session
bean methods that have been designed to support asynchrony.

When a client invokes an asynchronous method, the container returns control to the client and continues
processing the asynchronous invocation on a separate thread of execution.

3.4.8.1 Return Values
Asynchronous methods have a return type of void or Future<V>, where V represents the result value
of the asynchronous invocation.
In the case of a Future<V> return type, the object returned to the client is a container provided object.
This object allows the client to retrieve the invocation result value, discover any invocation exception,
or attempt to cancel the asynchronous invocation.

Thema der Woche: Reguläre Ausdrücke

Reguläre Ausdrücke vereinfachen die Abfragen an Strings radikal. Lese zunächst zur Einleitung

Anschließend sollte man die die API-Doku lesen:

In einer Code-Suchmaschine kann man nun einige Beispiele für Pattern-Nutzung ablesen:

Mehr Beispiele (allerdings auch mit Perl-RegEx, die Java nicht unterstützt) gibt die Seite

Hier sollte man sich ein paar Beispiele anschauen.

Zum Schluss eine Übung: Schreibe einen RegEx-Ersetzer, der aus einem Satz mit der „Basic text formatting“ Regel der Wiki-Syntax (http://wiki.splitbrain.org/wiki:syntax) HTML erzeugt. Also soll aus

**bold**

folgendes werden:

<b>bold</b>

Alternative Sprachen für die und auf der JVM

Java hat seine Monopolstellung eingebüßt – die hochoptimierte JVM und die umfangreichen Java-Bibliotheken lassen sich mittlerweile durch alternative Programmiersprachen nutzen. Auf der einen Seite existieren klassische Interpreter und Compiler für existierende Sprachen, wie Ruby, Prolog, LISP, BASIC, Python, die bestmöglich auf die Java-Umgebung portiert werden. Auf der anderen Seite sind es ganz neue Programmiersprachen (wie Groovy), die sich als echte Alternative zur Programmiersprache Java etablieren. Skriptsprachen werden oft über die JSR 223: Scripting for the Java Platform, einer standardisierten API, angesprochen.

JavaScript

Seit Java 6 ist über Rhino – ein Projekt der Mozilla Foundation – eine JavaScript-Laufzeitumgebung integriert. Die Script-Engine erlaubt die dynamische Übersetzung in Bytecode, was schnelle Ausführungszeiten der prozeduralen, funktionalen, objektorientierten Programmiersprache garantiert.

Groovy

[Logo]Groovy bietet eine starke Syntax mit Closures, Listen/Mengen, Reguläre Ausdrücke, eine dynamische und statische Typisierung und vielem mehr. Moderne IDEs wie Eclipse oder NetBeans unterstützen Groovy durch Plugins. Der Groovy-Compiler erzeugt für die Groovy-Klassen den typischen Bytecode, sodass normale Java-Klassen problemlos Groovy-Klassen nutzen können – oder umgekehrt. Zwei Vorträge zum Einlesen:

JRuby

[Logo]JRuby ist die Java-Version der dynamisch getypten Programmiersprache Ruby. Sun beschäftigt mit Charles Nutter und Thomas Enebo (die ›JRuby Guys‹) zwei Entwickler, und bringt auch mit der Integration in die NetBeans IDE (J)Ruby weit nach vorne. Ruby wird mit einem Atemzug mit dem Web-Framework Ruby on Rails genannt, ein Framework für Web-Applikationen, welches dank JRuby auch auf jedem Tomcat und Java Application-Server läuft.

Jython

[Logo]Die beliebte Programmiersprache Python bringt Jython auf die Java-Plattform. Auch Jython übersetzt Python-Programme in Java-Bytecode und erlaubt relativ schnelle Ausführungszeiten. Jython 2.2 implementiert Python auf 2.2, doch hat sich (C-)Python mit Version 2.6 und 3 schon weiter entwickelt. Auch sonst gibt es Unterschiede, etwa bei den eingebauten (nativen) Funktionen. Sun hat im März 2008 Ted Leung und Frank Wierzbicki (Hauptentwickler von Jython) eingestellt, um Python auf der JVM weiter zu fördern.

Scala

[Logo]Scala ist eine Funktionale, objektorientierte Programmiersprache, die in der Java-Community große Zustimmung findet, obwohl sie von Martin Odersky erst 2001 entwickelt und 2004 vorgestellt wurde. Ein Eclipse-Plugin steht ebenfalls bereit. Für die .NET-Plattform gibt es ebenfalls eine Implementierung. Besonders zeichnet Scala ein durchdachtes Typsystem aus.

Quercus

Quercus ist eine Implementierung von PHP, welches insbesondere dazu geeignet ist, bestehende und beliebte PHP-Projekte in einer Java-Umgebung ablaufen zu lassen. In der Java-Welt werden zwar nicht alle PHP-Funktionen unterstützt, aber es gibt in der Java-Welt keine Speicherüberläufe oder Sicherheitsprobleme.

Jatha

Jatha ist eine ›Common LISP library in Java‹, eine Implementierung von Common LISP. Mit einer API lassen sich LISP-Programme aus Java heraus aufrufen.

LuaJava

[Logo]LuaJava implementiert die Programmiersprache Lua für die JVM. Die aus Brasilien stammende dynamisch getypte Programmiersprache Lua zählt zu den performantesten, interpretierten Skriptsprachen. Sie ist in erster Linie als eingebettete Programmiersprache zur Applikationssteuerung entworfen worden; prominete Nutzer sind Sim City, World of Worcraft, Adobe Photoshop Lightroom, SciTE.

Pnuts

Pnuts gehört zu den schnellsten Skriptsprachen auf der JVM. Die Sprache hat eine einfache Syntax und übersetzt Programme ebenfalls in Bytecode.

JBasic

Mit JBasic gibt es für die Java-Plattform einen BASIC-Dialekt, der sich an GW-BASIC anlehnt.

JLog

JLog implementiert einen ISO-Standardisierten PROLOG-Interpreter. JLog läuft in einem eigenen Fenster mit Quellcode-Editor, Query-Panel, Hilfe, Debugger, oder es kann in einem eigenen Java-Programm eingebettet werden.

Jacl

Jacl implementiert einen TCL-Interpreter in Java. Die Entwicklung ist nicht mehr aktiv.

 

Die Webseite http://www.robert-tolksdorf.de/vmlanguages.html führt weitere Programmiersprachen für die JVM auf. Allerdings sind viele der gelisteten Sprachen für sehr spezielle Anwendungsfälle entworfen, experimentell oder werden nicht mehr gepflegt.

Thema der Woche: Java 5 und Java 6

Java 5 ist mittlerweile weit verbreitet, und Entwickler sollten auf der einen Seite die neuen Spracheigenschaften kennenlernen, auf der anderen Seite sich mit dem Update der Bibliotheken beschäftigen. Als Startlinks gelten:

Von jeder neue Klasse und Schnittstelle sollte man zumindest den API-Kopf gelesen haben. Besonderes Augenmerk sollten Entwickler auf Generics legen. Hier gilt hervorzuheben das Tutorial http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf. Die Begriffe

  • Generischer Typ
  • Typparameter
  • formalter Typparameter
  • parametrisierter Typ
  • Typargument
  • Wildcard-Typ
  • Bounded Wildcard
  • upper bound, lower bound
  • generische Methode
  • unchecked Warnung
  • erasure
  • Wildcard capture
  • multiple bound

solle man sofort einordnen und beschreiben können.

Jeder Entwickler sollte insbesondere alle Anwendungen von Generics bei der Utility-Klasse Collections verstehen:

PS: Beginne bei <T>/<E> bzw. <K,V>, dann <?> und dann den restlichen. max/min sind dann die Generics-„Bonbons“.

Wer danach die Nase von Generics immer noch nicht voll hat, beginnt http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html zu lesen. Das ist die umfangreichste Quelle zu dem Thema im Netz.

Neue Rubrik "Die wöchentliche Dosis Java"

Nach mehr als 10 Jahren in der Java-Weiterbildung wiederholen sich doch die Fragen. Die Klassiker: „Wie haben Sie Java gelernt?“, „Wie bilden Sie sich weiter?“, „Was für Java-Bibliotheken nutzen Sie?“, „Wie verbreitet ist eigentlich XZY?“ Aus diesen Anfragen heraus möchte ich eine neue Rubrik „Die wöchentliche Dosis Java“ vorstellen. Die Idee ist, die kontinuierliche Weiterbildung von Software-Entwicklern zu fördern. In der (hoffentlich) wöchentlichen Rubrik stelle ich Technologien, Bibliotheken, Tools, Sprachupdates, … vor, in der sich Programmierer in einer Woche beschäftigen können und somit ein neues Gebiet kennenlernen. Der Bereich umfasst dabei die gesamte Java-Landschaft. Mal werden es Sprach-Erweiterungen sein, mal XML-Technologien, dann wieder etwas von Swing und Gui-Frameworks, dann REST, Web-Toolkits oder Open-Source Bibliotheken.

Java-API für Google-Calendar/Google Documents

Mit der Google Java API (http://code.google.com/apis/gdata/javadoc/) lässt sich leicht auf die Dokumente oder Kalender zurückgreifen. Ein erstes Beispiel für eine Liste der Google-Calender ist schnell formuliert:

import java.net.URL;
import com.google.gdata.client.calendar.CalendarService;
import com.google.gdata.client.docs.DocsService;
import com.google.gdata.data.calendar.CalendarEntry;
import com.google.gdata.data.calendar.CalendarFeed;
import com.google.gdata.data.docs.DocumentListEntry;
import com.google.gdata.data.docs.DocumentListFeed;

public class GoogleExample
{
  public static void main( String[] args ) throws Exception
  {
    String user = „user@gmail.com“, pass = „pass“;

    CalendarService calService = new CalendarService( „Mein Kalender“ );
    calService.setUserCredentials( user, pass );

    CalendarFeed resultFeed = calService.getFeed(
                                new URL( „http://www.google.com/calendar/feeds/default/allcalendars/full“ ),
                                CalendarFeed.class );

    for ( CalendarEntry entry : resultFeed.getEntries() )
      System.out.println( entry.getTitle().getPlainText() );

    DocsService service = new DocsService( „Meine Dokumente“ );
    service.setUserCredentials( user, pass );

   DocumentListFeed feed = service.getFeed(
                              new URL( „http://docs.google.com/feeds/documents/private/full“ ),
                              DocumentListFeed.class );

    for ( DocumentListEntry doc : feed.getEntries() )
      System.out.println( doc.getId() + „/“ + doc.getTitle().getPlainText() );
  }
}

Die notwendigen Java-Archive nimmt man aus dem lib-Verzeichnis des Archivs http://gdata-java-client.googlecode.com/files/gdata.java-1.15.2.zip. Um auf die Dokumente zurückzugreifen (oder auch nur aufzulisten), ist mail.jar ebenfalls nötig.

Mikroformate mit JAXB in XML abbilden

Die Informationen von Mikroformaten lassen sich mit JAXB relativ leicht in XML konvertieren:

import java.util.*;
import javax.xml.bind.*;
import javax.xml.bind.annotation.*;

public class MicroformatViaJaxb
{
public static void main( String[] args ) throws JAXBException
{
Microformat mf = new Microformat();
mf.elements.add( new Element( "name", "Christian Ullenboom" ) );
mf.elements.add( new Element( "address", "tutego Allee" ) );
mf.elements.add( new Element( "phone", "2873568956928" ) );

JAXBContext context = JAXBContext.newInstance( Microformat.class );
Marshaller m = context.createMarshaller();
m.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE );
m.marshal( mf, System.out );
}
}
@XmlRootElement( name = "div" )
class Microformat
{
@XmlAttribute( name = "class" )
public String key = "person";
@XmlElement( name = "span" )
public List<Element> elements = new ArrayList<Element>();
}
class Element
{
@XmlAttribute( name = "class" )
public String key;
@XmlValue
public String value;
public Element() { }
public Element( String key, String value )
{
this.key = key;
this.value = value;
}
}

Got all this abbreviations?

XML HK2 WSIT ESB JMS SSO SAO JSR JAX-RS JCP DOJO AJAX WSDP jBMP RIFE RAILS MC4J CAPS SAML WS-* WSRP SAW JXTA HTTP URL IIOP ORB JMX TCP/IP WSDL MEX XWSS MTOM XSD SMTP WSA SOAP JBI JCA CMT LDAP BMT CMPI VJM CDDL GPL BSD API JAX-B StAX JSP JSTL EJB JPA TCK JDBC JDK JRE JAXP XOP REST POJO SQL GUI URI XMLDSig JAAS GSSAPI META-INF NIO ACL JNL CORBA CDC CLDC MIDP ACID SSL DRDA UML SAX DOM XOM XML-RPC MVC XSLT DAO SVG COM FTP PDF JNA ANTLR SLF4J

Alles klar?

Unterlagen von Sun Tech Days Dezember 2007 online

Die PDFs sind zwar schon länger online, aber für Interessierte noch der Link: http://de.sun.com/sunnews/events/2007/20071203/agenda_frankfurt.jsp#agenda-2:

Sun Microsystems Country Manager Introduction:Donatus Schmid, Marketing Director Germany
Download PDF

Demo. Showcase: Tomorrow’s Technologies in action Today
Sang Shin, Simon Ritter, Sridhar Reddy, Carol McDonald, Philip Torchinsky, Joey Shen, Inyoung Cho
Sun Spot

Java EE, GlassFish and their Future
Daniel Adelhardt
Download PDF

Java SE 6 Top 10 Features, Java SE 7 and OpenJDK
Inyoung Cho
Download PDF

What Makes Solaris Interesting?
Frank Curran
Download PDF

Oracle Sponsor Session: Discover Oracle
Wolfgang Ehrenthaler
Download PDF

Easy Deployment: Leaner and Meaner Runtime
Simon Ritter
Download PDF

New Security Features in Solaris and OpenSolaris
Scott Rotondo
Download PDF

Sun Keynote – James Gosling
Download PDF

Java DB: The Multi-tier Database
Dag H. Wanvik
Download PDF

A Rich Application Platform: JavaFX
Sridhar Reddy
Download PDF

Building High Performance Applications on Multicore Systems Using Sun Studio Compilers and Tools
Vijay Tatkar
Download PDF

Solaris Virtualization for Systems Administrators
Philip Torchinsky
Download PDF

Rapid Development with Ruby, JRuby and Rails
Joey Shen
Download PDF

Real-time Java
Simon Ritter
Download PDF

Performance Tuning With Sun Studio Analyzer, Race Detection Tools, Dtrace (D-Light)
Boris Ivanovsky
Download PDF

Efficient System Administration Using Sun’s System Management Technologies
Juergen Fleischer
Download PDF

Developing Applications Using Spring and JPA
Eberhard Wolff
Download PDF

Effective Concurrency for the Java Platform
Sang Shin
Download PDF

Let SMF Deal With That
Detlef Drewanz
Download PDF

Java Persistence API: Further Simplifying Persistence
Simon Ritter
Download PDF

Isolating Performance Bottlenecks and Memory Leaks
Jaroslav Bachorik
Download PDF

Enterprise Database Inside: The PostgreSQL In Your Solaris
Paul van den Bogaard
Download PDF

Sun Community Keynote: Developing in a Polyglot World by Craig McClanahan
Download PDF

Ajax and Web 2.0 Related Frameworks and Toolkits
Carol McDonald
Download PDF

Programming for Cool Devices using the Open Source Java ME PhoneME Stack
Terrence Barr
Download PDF

ZFS – Using Its Full Potential
Uli Graef
Download PDF

Building Rich Web Applications using jMaki
Joey Shen
Download PDF

More Concurrency: The Ten Unofficial Laws
Heinz Kabutz and Kirk Pepperdine
Download PDF

NFS and pNFS: High Performance Shared Data Stores for HPC Applications
Guenter Herbert
Download PDF

AMS GmbH Sponsor Session: jBEAM – A Framework for Desktop and Web Based Analysis and Reporting Systems
Dr. Bernhard Sünder
Download PDF

OpenSolaris Testing
Joaquim Rosell &
Sean McGrath

Download PDF

AMD Sponsor Session: Optimizing for Quad-core Solaris Systems based on AMD platforms
Raj Kharran
Download PDF

Metro and REST: Everyday Web Services
Harold Carr and Carol McDonald
Download PDF

Web Services Security, OpenSSO and Access Management for SOA
Abdi Mohammadi
Download PDF

Intel Technical Session: What are we doing to optimize Solaris on Intel Architecture?
Download PDF

Java ME GUI Makeover with Ajax Mashup
Terrence Barr
Download PDF

Performance Tuning Applications: GC Friendly Java Programming
Simon Ritter
Download PDF

How to Develop Solaris Parallel Applications
Leonid Lenyashin
Download PDF

DTrace Web 2.0 Applications, JavaScript, PHP, Java and the SAMP Stack
Peter Karlsson and Philip Torchinsky
Download PDF

SOA Using OpenESB, BPEL and NetBeans
Armin Wallrab
Download PDF

Get Your Parallel Applications Onto The Grid With Sun Grid Engine
Guenter Herbert
Download PDF