XStream mit JSON-Serialisierung
XStream (http://xstream.codehaus.org/) ist neben
XmlBeans einer der bekanntesten XML-Serialisierer. Nun haben die Entwickler die Bibliothek erweitert, dass XStream auch als XML-JSON-Serialisierer (http://xstream.codehaus.org/json-tutorial.html) arbeitet. Die Methodenamen sind mit toXML() und fromXML() zwar nicht so passend, aber der Aufruf dennoch einfach:
Product product = new Product("Banana", "123", 23.00);
XStream xstream = new XStream(new JettisonMappedXmlDriver());
xstream.setMode(XStream.NO_REFERENCES);
xstream.alias("product", Product.class);
System.out.println(xstream.toXML(product));
Der andere Weg:
String json = "{\"product\":{\"name\":\"Banana\",\"id\":\"123\"" +
",\"price\":\"23.0\"}}";
XStream xstream = new XStream(new JettisonMappedXmlDriver());
xstream.alias("product", Product.class);
Product product = (Product)xstream.fromXML(json);
System.out.println(product.getName());
Grammatikalische Struktur vom Java-Programm visualisieren
Unter http://www.antlr.org/wiki/display/ANTLR3/Tool+showing+grammatical+structure+of+Java+code gibt es ein hübsches Gui-Tool, welches nach der Java Grammatik vom Openjdk javac compiler project with ANTLR-based Java grammar die Struktur aufzeigt:
JavaFX 1.0 offiziell veröffentlicht
Sun hat Anfang Dezember 2008 JavaFX veröffentlicht. Es ist als Alternative zu MS Silverlight und Flash + Flex für Rich Internet Applications gedacht. Einige Links dazu:
- http://en.wikipedia.org/wiki/JavaFX
- http://en.wikipedia.org/wiki/JavaFX_Script
- http://en.wikipedia.org/wiki/JavaFX_Mobile
- http://www.theregister.co.uk/2008/01/24/javafx_tools_adobe/
- http://www.oreillynet.com/onjava/blog/2007/05/javafx_im_still_not_impressed.html
Zentrale Punkte von JavaFX 1.0 sind: (Zitiert von http://blogs.sun.com/javafx/entry/javafx_1_0_is_live)
- Fast and easy to use 2D graphics
- PerspectiveTransform for 3D effects
- KeyFrame animation
- Video and Audio support using both native and cross-platform codecs
- Swing Integration
- XML & JSON web services
- Pixel-filters and visual effects with GPU hardware acceleration
- CSS styling (more on that later)
- Windows XP+ and Mac 10.4+ support with Linux & Solaris in the works (more on that later too)
- The new JavaFX Script language with binding and animation built in, running 10->20x faster than Javascript
- Visually rich applets that you can drag to your desktop and save for later
- Integration with Photoshop and Illustrator
- Access to the world’s huge library of Java code and APIs
- A new website with docs, tutorials, and tons of BSD licensed sample code and as a nice bonus:
- A sneak-peek beta of JavaFX on mobile devices
Der Punkt Support with Linux & Solaris in the works macht sicherlich nicht jeden in der Community glücklich, aber gut…
Sun hat die schöne Seite http://javafx.com/ aufgebaut, um mehr über JavaFX zu lernen. Die NetBeans IDE 6.5 bringt volle Unterstützung für JavaFX (http://www.netbeans.org/features/javafx/index.html) mit. Für Eclipse gibt es bisher keine große Unterstützung.
http://www.reportmill.com/jfx/ bringt passend ein Tool auf Markt. Zentrale Elemente sind (Zitiert von der Webseite):
- Powerful Visual Designer
- Animation, Illustration and Page Layout
- Video, Sound and Image Effects
- Drag & Drop Application Components
- JDBC and POJO Data Binding
- HTTP Form Generation and Binding
- Navbar Generation, Page Transitions
- Graphs, Charts, Tables and Reports
- Full Featured Player/Document Reader
- Extension Plugins with Internet Directory
JBoss 5 ist fertig + Application Servers 2008 Rankings
Nach 3 Jahren gibt es nun (endlich) den JBoss 5 AS. Einige Meldungen und Meinungen dazu:
- http://www.heise.de/newsticker/JBoss-5-ist-nach-drei-Jahren-Entwicklungszeit-fertig–/meldung/120010
- http://www.jboss.org/feeds/post/as_5_0_0_we_are_done_next
- http://sourceforge.net/project/shownotes.php?release_id=645033&group_id=22866
JBoss 5 taucht aber (noch) nicht als zertifizierter Java EE 5 Container unter http://java.sun.com/javaee/overview/compatibility.jsp auf, obwohl http://sacha.labourey.com/2008/09/15/jboss-as-is-now-ee5-certified/ davon berichtet.
Unter http://www.theserverside.com/news/thread.tss?thread_id=51008 wird der EDC report – "Application Servers 2008 Rankings" (http://www.evansdata.com/reports/viewRelease_download.php?reportID=20) diskutiert. Die Kommentare sind lesenswert. Der Download des Papers verlangt ein Login, ist aber ansonsten frei.
Inselraus: getContextClassLoader() vom Thread
Entwickler von Java-Enterprise-Applikationen haben oft damit zu kämpfen, dass immer der falsche Klassenlader eine Klasse bezieht und die Typen dann nicht zusammenpassen. In unserem Beispiel mit dem statischen Initialisierungsblock ist gut zu erkennen, dass durch das zweimalige Laden die Laufzeitumgebung auch zweimal die Anweisungen ausführt. Hätten wir Singletons definiert, würden ihre statische Anfragemethoden unterschiedliche, nicht kompatible Objekte liefern, obwohl es laut Defini-tion eines Singletons der Fall sein müsste. Allgemein gesprochen: Besonders Fabrikfunktionen liefern bei mehreren Versionen der Klasse unterschiedliche Objekte, die nicht zusammenpassen. Zwei Lösungen gibt es hier: Zum einen bekommen die Fabrikfunktionen einen Klassenlader, in dessen Kontext sie die Klassen erzeugen können, oder sie nutzen den Klassenlader, der mit einem Thread ver-bunden ist.
Jeder Thread ist mit einem Klassenlader assoziiert, der standardmäßig mit dem Standardklassenlader identisch ist. getContextClassLoader() auf dem Thread-Objekt bezieht diesen Klassenlader:
Listing 8.13 com/tutego/insel/lang/ThreadClassLoader.java, main()
ClassLoader loader = Thread.currentThread().getContextClassLoader();
System.out.println( loader ); // sun.misc.Launcher$AppClassLoader@a12a00
loader = ThreadClassloader.class.getClassLoader();
System.out.println( loader ); // sun.misc.Launcher$AppClassLoader@a12a00
Soll der assoziierte Klassenlader geändert werden, bewerkstelligt dies setContextClassLoader().
Inselraus: Ein flexibles Tabellenlayout mit JGrid
Eine JTable ist zwar eine einfache Komponente, doch schon in der HTML-Tabelle gibt es Eigenschaften, die die JTable nicht abbilden kann: Zellen, die über mehrere Zeilen und Spalten gehen. Hier ist einiges an Programmieraufwand nötig, der jedoch für diejenigen unnötig ist, die auf die freie Komponente JGrid zurückgreifen. Die Swing-Komponente gehört zu Pepper (http://jeppers.sourceforge.net/), einer Komponente für Tabellenkalkulationen, die sogar eine Formelauswertung ähnlich Excel versteht. Pepper selbst untersteht zwar der GPL, doch JGrid ist LGPL und lässt sich somit in eigene kommerzielle Anwendungen einbinden.
PS: tutego bietet nun auch ein GWT-Seminar an:
Thema der Woche: SwingX
Die Anzahl Swing-Komponenten ist nicht besonders groß und seit dem Swing in Java 1.2 fest eingeführt wurde, hat sich wenig an Swing verändert. Im Laufe der Zeit sind diverse Projekte mit Zusatzkomponenten und Swing-Erweiterungen entstanden, wobei SwingX (http://swinglabs.org/) zu den bekannteren gehört.
- Lies über das Angebot der Webseite http://swinglabs.org/, http://swinglabs.org/projects.jsp
- Verfolge die Präsentationen unter http://swinglabs.org/docs.jsp
- Lade das SwingX-Jar und binde es ein. Hole http://swinglabs.org/hudson/job/SwingX%20Continuous%20Build/javadoc/index.html?org/jdesktop/swingx/package-summary.html vor.
- Nutze in einem Beispiel JXDatePicker, JXMonthView, JXHyperlink, JXImagePanel, JXMultiSplitPane, JXStatusBar, JXTreeTable
- Was unterschiedet JXTable, JXTree, JXList von den Standard Swing-Komponenten?
- Entwickle ein Beispiel mit Klassen aus org.jdesktop.swingx.autocomplete
- Was ist die Aufgabe von org.jdesktop.swingx.action?
SwingX wurde in den letzten Tagen mit mehr Aufmerksamkeit bedacht, seit dem Sun angekündigt hat, dass SwingX-Projekt nicht mehr zu unterstützten. Zusammen mit diversen Blog-Einträgen ergibt sich der Eindruck, dass Swing für Sun keine besondere Rolle spielt, sondern Sun stattdessen Geld und Entwicklerkapazität in JavaFX steckt. Lese dazu
Neuer Java Decompiler
Jad (http://www.kpdus.com/jad.html) gehört immer noch zu den Klassikern der Java-Decompiler. Nun gibt es etwas neues, den “Java Decompiler” (http://java.decompiler.free.fr/). Mit dem Screenshot der Gui sieht das schon mal vielversprechend aus.
Joda Time 1.6/JSR 310
Von Joda Time (http://joda-time.sourceforge.net/) gibt es ein neues Update in der Version 1.6 (vom 2008-10-27). Interessant bleibt zu sehen, wie sich Joda Time im Laufe der Zeit gegenüber der JSR 310: A New Java Date/Time API abhebt.
Zur JSR 310, die in Java 7 erwartet wird:
- https://jsr-310.dev.java.net/
- http://jcp.org/en/jsr/detail?id=310
- http://today.java.net/pub/a/today/2008/09/18/jsr-310-new-java-date-time-api.html
- https://jsr-310.dev.java.net/nonav/doc-2008-08-04/index.html
Stephen Colebourne ist einer der treibenden Personen von Joda Time und auch Specification Lead der JSR 310.
Java EE 6 in der Endphase der Spezifikation
Die JSR-316 (http://jcp.org/aboutJava/communityprocess/edr/jsr316/index.html) ist eine Umbrella-API für Java EE 6. Am 22. November 2008 war der Close of Early Draft Review, sodass Java EE 6 nun in die heiße Endphase geht. Interessante neue APIs in Java EE 6 sind:
- JSR-311 JAX-RS: Java API for RESTful Web Services
- JSR-299 Web Beans
- JSR-236 Timer for Application Servers
- JSR-237 Work Manager for Application Servers
Erwartet Updates gibt es bei
- Enterprise JavaBeans
- Java Persistence API
- Servlets
- JavaServer Faces
- JAX-WS
- Java EE Connector API
NetBeans IDE 6.5
Von der Webseite (http://www.netbeans.org/servlets/NewsItemView?newsItemID=1313):
NetBeans.org is proud to announce the availability of NetBeans IDE 6.5!
NetBeans IDE 6.5 offers simplified and rapid development of web, enterprise, desktop, and mobile applications with PHP, JavaScript, Java, C/C++, Ruby, and Groovy.
New features include a robust IDE for PHP, JavaScript debugging for Firefox and IE, and support for Groovy and Grails. The release also delivers a number of enhancements for Java, Ruby on Rails, and C/C++ development. Java highlights include: built-in support for Hibernate, Eclipse project import, and compile on save. Combining excellent out of the box experience, compelling features, and a great plugin ecosystem, NetBeans IDE 6.5 is a must-download for all developers.
NetBeans IDE 6.5 is currently available in English, Japanese, Simplified Chinese and Brazilian Portuguese. There are several community contributed localization efforts underway to support additional languages. Join the efforts today.
More information about NetBeans IDE 6.5:
- NetBeans IDE 6.5 Features
- NetBeans IDE 6.5 Tutorials and Documentation
- Guided Video Tour of NetBeans IDE 6.5
As always, we welcome and encourage feedback about your experience using the NetBeans IDE. Share your thoughts on our mailing lists and forums; if you blog about NetBeans add your blog to Planet NetBeans. NetBeans is now on Twitter! Follow us at twitter.com/netbeans to get the latest news and information, ask questions and engage with the NetBeans team.
Diskussion und Anwendung von Ribbon-Komponenten
Kirill Grouchnikov hat unter http://www.pushing-pixels.org/?p=622 einen langen Blog verfasst, in dem er sich mit der Entwicklung und Einsatz der Ribbon-Komponente befasst. Der Blog mit seinen vielen Links ist auf jeden Fall lesenswert. Für Java hat Kirill eine Ribbon Komponente implementiert, die Teil vom Flamingo Framework (https://flamingo.dev.java.net/) ist. Die Dokumentation https://flamingo.dev.java.net/docs/ribbon/ribbon-overview.html zeigt Screenshots und die API dahinter.
Thema der Woche: Das XML-Modell XOM
XOM (http://www.xom.nu/tutorial.xhtml) ist ein XML-Modell von Elliotte Rusty Harold, welches eine Alternative zu DOM, aber auch zu moderneren XML-Modellen JDOM und dom4j ist.
- Lies die Einführung unter http://www.xom.nu/tutorial.xhtml und implementiere Beispiele
Um die Philosophie hinter dem Design zu verstehen, hat Elliotte Rusty Harold mit Bill Venners auf artima ein Interview geführt.
- In Part I: What’s Wrong with XML APIs, Harold discusses the five styles of XML APIs and the problems with data-binding XML APIs.
- In Part II. The Good, the Bad, and the DOM, Harold discusses the problems with the DOM API, and the design lessons he learned from DOM.
- In Part III. A Design Review of JDOM, Harold discusses the problems with the JDOM API.
- In Part IV. Lessons Learned from JDOM, Harold discusses the design lessons he learned from the JDOM API.
- In Part V. Design Principles and XOM, Harold discusses the API design principles that guided the design of XOM.
Aufgabe: Gehe mit XOM und XPath an das XML-Ergebnis einer REST-Abfrage http://www.flickr.com/services/api/flickr.places.findByLatLon.html und gib nur die place_url aus.
http://acs.lbl.gov/nux/ lässt sich als Erweiterung von XOM verstehen. Was macht NUX genau?
Jersey 1.0 (JAX-RS) ist fertig
Im Sun-Blog ist http://blogs.sun.com/theaquarium/entry/jersey_1_0_just_shipped ist zu lesen:
JAX-RS co-spec lead and Jersey lead Paul Sandoz just announced Jersey 1.0 availability. v1.0 moments are always special and this one is certainly no exception given how progress was made on a regular basis from engineering hard work and lots of community feedback. Congrats to Paul and the entire community for a well run open source project !
Jersey 1.0 is obviously a JAX-RS 1.0 implementation, but it also adds Spring integration, a REST client, and obviously is production quality…
One of the signs of a community-involved project is the many ways the bits can be accessed: GlassFish v2 and v3, NetBeans 6.5, Maven 2, zip, etc…With Jersey 1.0 out the door, you can now freely choose your Web Services style and stick to standards. Java EE 6, scheduled sometime mid-2009, will make this even clearer though a maintenance release.
See Jerseyfor more stories.
Thema der Woche: Sun Certified Java Programmer (SCJP)
The Sun Certified Java Programmer (SCJP) exam is the entry level Java exam and is a prerequisite to a number of the other Java-related certifications. SCJP 6, designated CX-310-065 by Sun, was released in December 2007. It is designed to have a fairly detailed test of basic knowledge of the essentials of the Java programming language. It tests looping constructs and variables, and does not cover specific technologies such as GUI creation, Web or network programming. It is assessed through an automatically administered multiple-choice test system and consists of 72 questions which the candidate has 210 minutes to answer. At least 47 questions are needed to be correct to pass (around 65%). The SCJP 5 exam tests a candidate on knowledge of declarations, access control, object orientation, assignments, operators, flow control, assertions, string handling, I/O, parsing, formatting, generics, collections, inner classes, threads and the JDK toos (Quelle: http://en.wikipedia.org/wiki/Sun_Certified_Professional).
Zur Vorbereitung auf den SCJP gibt es im Netz viele Fragen, die denen aus dem SCJP sehr ähnlich sind. Auch wer kein SCJP machen möchte, sollte sich mit dem Thema beschäftigen, da es doch das tiefe Verständnis der Sprache Java schärft (weniger den Bibliotheken oder dem Design von großen Anwendungen!)
- http://faq.javaranch.com/view?ScjpMockTests
- http://www.javadeveloper.co.in/scjp/scjp-mock-exams.html
- http://www.javadeveloper.co.in/scjp/scjp-simulator.html
- http://certificationking.net/sun.html
- http://www.javaprogrammingworld.com/
- http://www.jchq.net/mockexams/exam1.htm
- http://www.examulator.com/phezam/question.php
- http://www.wickedlysmart.com/SCJPStudyGuide/Java_5_SCJPquestions.html
Aufgabe: Trage 30 der spannendsten Fragen zusammen.
TWAIN-Scannen mit Java
http://www.mms-computing.co.uk/uk/co/mmscomputing/device/twain/ ist eine Java-API für die TWAIN-Schnittstelle, um etwa einen Scanner anzusteuern. Ein Beispiel ist schnell aufgebaut:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import org.jdesktop.swingx.JXFrame;
import org.jdesktop.swingx.JXImagePanel;
import org.jdesktop.swingx.JXImagePanel.Style;
import uk.co.mmscomputing.device.scanner.Scanner;
import uk.co.mmscomputing.device.scanner.ScannerIOException;
import uk.co.mmscomputing.device.scanner.ScannerIOMetadata;
import uk.co.mmscomputing.device.scanner.ScannerListener;
public class TwainExample
{
@SuppressWarnings("serial")
public static void main( String[] args )
{
final JXImagePanel imagePanel = new JXImagePanel();
imagePanel.setStyle( Style.SCALED_KEEP_ASPECT_RATIO );
final Scanner scanner = Scanner.getDevice();
JXFrame f = new JXFrame( "SSP", true );
Action action = new AbstractAction("Scan") {
@Override public void actionPerformed( ActionEvent e ) {
try { scanner.acquire(); } catch ( ScannerIOException ex ) { }
}
};
f.add( new JButton(action), BorderLayout.PAGE_START );
f.add( imagePanel );
f.setSize( 1000, 700 );
f.setVisible( true );
scanner.addListener( new ScannerListener()
{
public void update( ScannerIOMetadata.Type type, ScannerIOMetadata metadata )
{
if ( ScannerIOMetadata.ACQUIRED.equals( type ) )
imagePanel.setImage( metadata.getImage() );
}
} );
}
}
Globale Tastendrücke und Mausoperationen abfangen (Windows)
Globale Mausbewegungen von Java zu überwachen ist mit dem MouseInfo.getPointerInfo().getLocation() kein Problem. Aber mitzubekommen, ob in einer anderen Java-Applikation eine Maustaste oder eine andere Keyboard-Taste gedrückt ist, schon. Wer vor dem Problem steht, dies unter Java und Windows abzufangen, kann SWT zusammen mit den SWT Win32 Extensions (http://www.swtui.cn/index.php) nutzen — auch wenn man selbst nicht mit SWT, sondern mit Swing arbeitet. Soll etwa global die <Pause> Taste abgefangen werden, kann man schreiben:
Hook.KEYBOARD.addListener(new HookEventListener() {
public void acceptHookData( HookData hookData ) {
if ( ((KeyboardHookData) hookData).getVirtualKeyCode() == KeyEvent.VK_PAUSE &&
! ((KeyboardHookData) hookData).getTransitionState() ) {
// TU WAS DICH GLÜCKLICH MACHT
}
} } );
Hook.KEYBOARD.install();
Neben Hook.KEYBOARD gibt es auch Hook.MOUSE.
Möchte man nun beides zusammen haben, also wissen, ob etwa STRG und eine Maustaste gedrückt wurde, meldet man einen HookEventListener für die Maus an und fragt die Taste wie folgt ab:
Extension.GetKeyState(Extension.VK_CONTROL) < 0
HOWTO: Change Title, Autor, Subject of a PDF
package com.tutego.traida.util;
import java.io.FileOutputStream;
import java.util.HashMap;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;
public class PdfUtils
{
public static void setMetaData( String sourceFilename, String targetFilename )
{
try
{
PdfReader pdfReader = new PdfReader( sourceFilename );
PdfStamper stamp = new PdfStamper( pdfReader, new FileOutputStream( targetFilename ) );
@SuppressWarnings("unchecked")
HashMap<String, String> info = pdfReader.getInfo();
info.put( "Title", "Rechnung für Beratung" );
info.put( "Author", "tutego" );
info.put( "Subject", "Rechnung" );
info.put( "Keywords", "Rechnung, tutego" );
info.put( "Creator", "http://www.tutego.com/" );
info.put( "Producer", "tutego Training Software 1.2" );
stamp.setMoreInfo( info );
stamp.close();
pdfReader.close();
}
catch ( Exception e )
{
e.printStackTrace();
}
}
public static void main( String[] args )
{
setMetaData( "c:/a.pdf", "c:/new.pdf" );
}
}
With iText of course: http://www.lowagie.com/iText/
Alpha-Version vom JAva COm Bridge (JACOB) Plug-In
Das Eclipse-Plugin http://jacob-project.wiki.sourceforge.net/Jacob+Gen+Plugin erlaubt über einen Menüeintrag einfach das Erzeugen von Stub-Code für den Zugriff auf Windows-DLLs.
Der Generator geht einen interessanten Weg über Eclipse JET, wie es die Webseite erklärt:
The plug-in uses the old, JacobGen 0.7, c++ program (dll) which reads a Microsoft’s proprietary TLB file and writes out what it finds on stdout. From the information gathered the plug-in produces an ecore model based of what is found inside the TLB. At this point the plug-in has created a model of what’s inside the DLL file. I.E. what classes and enums exist. The plug-in uses Java Emitter Templates (JET) to generate java code based on the above ecore model. It also produces the java method bodies to automatically call JACOB methods with the correct parameters. This will create a strongly typed java proxy, via JACOB, into the windows DLL.
So to wrap up. The plug-in reads the TLB file (using the existing JacobGEN DLL), creates a model based on the TLB / DLL file, and then produces a java proxy. The JET generated classes are really a proxy into the DLL via JACOB. So the end result is a set of java classes hiding all JACOB internal knowledge.