Matthias Wessendorf's Weblog

A blog on JSF, Ajax, Web 2.0 and other (interesting) things

Disabling the ARC in Xcode 4.2

With Xcode 4.2 (iOS 5) Apple introduce ARC (Automatic Reference Counting) to help with memory management. Basically you no longer need to call retain or release. However current examples/books (and (open source) libraries) are still doing it. This leads to (annoying) errors like:

ARC forbids explicit message send of ‘retain’

To get rid of this error you need to disable ARC, but how? I found this link which show how to disable it for cetain source files, but I wanted this to be a global setting.

My Kaazing colleague Richard Clark told me how to turn off ARC at the project level. Here is what you need to do in Xcode:

  1. Select your project file.
  2. You should be in the “Build settings” tab. Select the “levels” option (default is “Combined”)
  3. There’s a search field to the right of “Combined”. Enter “Automatic”
  4. Second group should be “Apple LLVM Compiler 3.0 – Language”. Second line under that controls ARC.
  5. Click that line, then in the middle column (where it says “yes”), click and choose “no”.
Now the error is gone. Great!
Thanks Richard :-)

Getting started with Objective C

In order to do i{Phone|Pod|Pad} or Mac development you need to learn Objective-C, which is basically adding some object-orientation to the C language.

The last 2.5 days I spent some time in learning about Objective C. I used Xcode (an IDE for the Mac) and also a pretty straightforward (or minimalistic) enviroment:

  • text editor
  • compiler

All you really need for coding some Objective-C is a text-editor and a compiler. On my Mac I used TextMate and the gcc compiler. Sure, with Xcode iOS/Objective-C development is nicer, but a with a text editor and a compiler you get something in a short amount of time as well. (Note: Xcode is only available for Mac OS)

Using the gcc compiler I noticed a few issues, when actually compiling the bits, since I was never doing any C/C++ development before. The main reason for writing this blog is giving a quick introduction that also includes the required gcc commands…. – as there are already a lot of “Hello World”-ish blogs.
For professional iOS development I do recommend using Xcode, but let’s get started…

The canonical “Hello World” is simple and looks like:

#import <Foundation/Foundation.h>

int main(void) {
	NSLog(@"Hello Objective-C");

	return 0;
}

The NSLog() function requires a NSString object. The String starts with an @, this identifies the string as a NSString object… Save the above as hello.m and compile it:

gcc hello.m -o prog -framework Foundation

It is important to specify that you are using the Foundation classes (-framework Froundation)…
Now you can invoke your first program:

./prog

Now let’s take a look at a simple class. For that we need two files: a header file and it’s implementation (or method) file. Let’s take a look at the MyPerson.h file:

#import <Foundation/Foundation.h>

@interface MyPerson : NSObject {
}

// getter and setter
@property (nonatomic, copy) NSString* firstName;
@property (nonatomic, copy) NSString* secondName;

// should print the complete name
- (void) printDetails;

@end

The MyPerson class extends the NSObject class and it defines a few setter/getter, by using Objective-C’s property syntax. I also has another method to print out the name of an instance of this class. The MyPerson.m file looks like:

// usage of our header file
#import "MyPerson.h"

@implementation MyPerson

// getter/setter
@synthesize firstName = firstName_ ;
@synthesize secondName = secondName_ ;

// the actual method
- (void) printDetails {

    // write out the name, in a formated way:
    NSLog(@"%@, %@", self.secondName, self.firstName);
}

@end

In here we basically implement the defined methods, like the getter/setter or the printDetails.

Now we want to use the MyPerson class, which is done in the main.m file:

#import <Foundation/Foundation.h>
#import "MyPerson.h"

int main(void) {
	// memory mgmt class
	NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];

    // autorelease to avoid leaks
    MyPerson* matze = [[[MyPerson alloc] init]autorelease];

    matze.firstName =  @"Matthias";
    matze.secondName = @"Wessendorf";

    [matze printDetails];

    // free the memory
	[pool release];
	return 0;
}

The main.m file imports our MyPerson class and its main() function creates an object of the class and sets values to the instance by using the two setter functions. Afterwards the printDetails is called to print the first and second name to the console. It also uses the NSAutoreleasePool class, for some memory management… The compilation is done with the following command:

gcc main.m MyPerson.m -o prog2 -framework Foundation

You can now invoke the prog2!

Thanks to Torsten Curdt! He was around when I had some newbie questions. Thanks!

WebSocket: Bringing TCP to the browser

The WebSocket standard is almost finalized. However, WebSocket itself is offering “just” a (data) pipe. WebSocket is well suited to bring event- or data-driven applications to the browser. A valid example would a Web UI for a JMS or AMQP application. With help of the Kaazing Gateway this is possible! As said before, you are basically able to bring any TCP- or UDP-based application to the web.

A simple TCP-based echo server

Since the WebSocket client API itself is not enough (to build a “real” application), we need some (existing) backend, or server. A very simple example would be to bring a (TCP) echo server to the browser, via WebSocket:

var net = require('net');

var server = net.createServer(function (socket) {
  socket.write("Echo server\r\n");
  socket.pipe(socket);
});

server.listen(1337, "127.0.0.1");

The above code is a VERY simple “EchoServer” that runs on port “1337″. It is in Node.js. The code is borrowed from their website.

Bring it to the Web

To be able to access this TCP server with a WebSocket application you need to add the following configuration to the Kaazing WebSocket Gateway:

<service>
  <accept>ws://localhost:8000/echo</accept>
  <connect>tcp://localhost:1337/</connect>
  <type>proxy</type>
  <cross-site-constraint>
    <allow-origin>*</allow-origin>
  </cross-site-constraint>
</service>

The entry point for the echo server is the ws://localhost:8000/echoURL. The Gateway connects the WebSocket connection to the backend (check the tcp port). The connection to the echo server is straightforward. The following shows a pretty simple JavaScript program, that opens a WebSocket connection in order to send and receive data from the underlying TCP server:

var websocketConnection = new WebSocket("ws://localhost:8000/echo");
websocketConnection.onopen = function(ev) {
	console.log('Connected to the echo service')
};
websocketConnection.onmessage = function(event) {
  var payload = event.data;
  displayEcho(payload);
};
...
websocketConnection.send("Hello Echo Server");
...

This is obviously a simple example, but it clearly shows the power of WebSocket! Give it a try!

If you are interested in HTML5 and WebSocket, check out the Kaazing Gateway! BTW. Kaazing is hiring

Bringing Stomp/JMS to the browser – via WebSocket

Last week I attended the Con-Fess conference in Vienna to speak about WebSocket (and its JSF integration). The first demo described how to bring UDP-based network traffic to the browser. Another demo from my presentation showed how to bring JMS to the browser, by using WebSocket.

You can try this out as well – The steps are quite simple:

  • Download the JMS Edition of the Kaazing gateway and extract it
  • Start the included Apache ActiveMQ server
  • Start the gateway itself
  • Start the demo stock ticker feed
The Java program behind the “stock.start” script is a simple class, which uses the standard JMS API to send messages (stock prices) to the running Apache ActiveMQ. We now need a browser-based JavaScript client, which talks to the Apache ActiveMQ over WebSocket.
The Kaazing Gateway (JMS edition) comes with a JMS API for various platforms, like JavaScript or Flash/ActionScript. If you have ever programmed something that used JMS, you are able to use it!
Let’s have a look how to setup a connection to the JMS server:
...
var stompConnectionFactory =
        new StompConnectionFactory( "ws://localhost:8000/jms");

// create a connection, by using a JS callback
var connectionFuture =
   stompConnectionFactory.createConnection(user, passwd, function () {

    if (!connectionFuture.exception) {
        connection = connectionFuture.getValue();
        // register a JMS exception handler
        connection.setExceptionListener(handleException);

        // create session
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        // create a topic
        topic = session.createTopic("/topic/destination");

        // creating some consumers!
        var consumer1 = session.createConsumer(topic);

        // attach the callback that receives the stock prices:
        consumer1.setMessageListener(handleMessageCallback);

        // start!
        connection.start(someCallback);
    }
....
});

The code is straightforward: A (Stomp)ConnectionFactory is created and we use that factory object to create the actual connection. The createConnection() function takes three arguments: user, password and a callback, which is invoked once the connection has been established (or an exception is thrown). If no exception occurred, the code executes a few steps:
  • we receive the actual connection
  • we setup a JMS exception handler
  • we create a session, a JMS topic and a consumer
  • we register a handler for the incoming JMS messages (handleMessageCallback)
  • we finally start the connection’s delivery of incoming messages
The handleMessageCallback() is used to receive the stock prices and to “draw” the DTHML, so that the stock changes are nice to watch in a vanilla HTML table, like below:
The code for the message listener is also using our JavaScript JMS API, to receive JMS (Text)messages:
function handleMessageCallack(message) {

  // did Apache ActiveMQ send us a JMS TextMessage?

  if (message instanceof TextMessage) {
     var body = message.getText();

     // DHTML code to show stock values...

  }
}

The above JavaScript code is pretty much readable for every JMS coder. The big news is that the JMS communication from the ActiveMQ to the browser (and vice versa) happens over WebSocket. This dramatically reduces overhead and latency for your web application!

The WebSocket gateway is not limited to Stomp/JMS, it has support for other protocols like AMQP, or even XMPP as well!

If you want to try (or see) this stock ticker, you can! It is part of the Kaazing JMS demo bundle. Once you installed the gateway, you can see the stockticker on your machine

Have fun!

Extending TCP/UDP-based protocols to the browser by using WebSocket

WebSocket is a bi-directional AND full-duplex communication STANDARD to build next generations web applications. The WebSocket Protocol and its client APIs are getting more and more to their final state. You could say it is “TCP for the web”.

However WebSocket is NOT:

  • just a better Ajax or XHR, nor was it designed to be!
  • designed to be a one-size-fits-all replacement for HTTP!

When you build typical client-server applications you are using higher level protocols and APIs, such as XMPP, JMS or JDBC instead of raw TCP socket. You should think of WebSocket the same way! Instead of exchanging raw WebSocket data between the browser and the server (and introducing your own “protocol”), but you should use WebSocket to run these high level protocols on top of it! In fact the Kaazing WebSocket Gateway allows you to do this!

Here is an example that shows how to extend a (NodeJS-based) UDP program to the browser, by using the Kaazing WebSocket gateway.

Getting ready with NodeJS and the Kaazing gateway

  1. Download the Kaazing WebSocket Gateway (HTML5 Edition)
  2. Download and install NodeJS (only needed for this demo…)

The installation of the Kaazing WebSocket Gateway is quite esay: Unzip the archive and launch the gateway.start command in $KAAZING_HOME/bin. That’s it.

Now we can write pretty simple and straightforward UDP program, in Node:

var Buffer = require('buffer').Buffer;
var dgram = require('dgram');
// create the datagram socket
var sock = dgram.createSocket("udp4");
// some bogus news...
var news = [
   "Borussia Dortmund wins German championship",
   "Tornado warning for the Bay Area",
   "More rain for the weekend",
   "Android tablets take over the world",
   "iPad2 sold out",
   "Nation's rappers down to last two samples"
];
function broadcastNew() {
   var buf = new Buffer(news[Math.floor(Math.random()*news.length)]);
   sock.send(buf, 0, buf.length, 55555, "127.0.0.1");
   console.log("Sent " + buf + " to the wire...");
}
setInterval(broadcastNew, 3000);

The program is simple: Every three seconds it throws some data to its UDP connection (localhost:55555) and it logs the same message to the server console. You can run the broadcasting “server” with node yourFilename.js.

Next you need to add the following section to the gateway-config.xml file:

<service>
  <accept>ws://localhost:8000/nodejs</accept>
  <type>broadcast</type>
  <properties>
    <accept>udp://localhost:55555</accept>
  </properties>
  <cross-site-constraint>
    <allow-origin>*</allow-origin>
  </cross-site-constraint>
</service>

This maps any incoming WebSocket request for ws://localhost:8000/nodejs to the UDP tool we started on localhost:55555. The used cross-site-constraint ensures that you can invoke the Gateway from a different origin (e.g. different port). If you check the other configured Gateway services you see they do contain URIs for the cross-site-constraint parameter…

The missing piece here is a VERY simple WebSocket script, like:

<!DOCTYPE html>
<html>
  <head>
    <title> My first WebSocket app!</title>

<script src="./WebSocket.js"></script>

<script type="text/javascript">
function connectMeToNodeByUsingKaazing() {
  var ws = new WebSocket("ws://localhost:8000/nodejs");
  ws.onopen = function(ev) {
     console.log("connection is up");
};
ws.onmessage = function(ev) {
     console.log("The news: \"" + ev.data + "\"");
};
}
</script>
<body onLoad="connectMeToNodeByUsingKaazing()">
<h2>Open your JavaScript console to see the messages!</h2>
</body>
</html>

Now go to the $KAAZING_HOME directory and cd to “web/extras”:

  1. create a new folder in there (e.g. mkdir firstApp)
  2. copy the WebSocket.js file (from $KAAZING_HOME/lib/client/javascript/WebSocket.js) to the new ‘firstApp‘ folder.
  3. make sure the above HTML page is in that directory as well (e.g. simpleUDP.html)

That’s it!

If you now open that HTML page in a browser (e.g. http://localhost:8001/firstApp/simpleUDP.html) (and open the JavaScript console), you will see that the connection to the Kaazing gateway has been opened and that news items are coming across the wire!

The sweet part is that you have now been able to bring a UDP based communication to the browser, by using the Gateway server! Of course the demo is pretty simple and trivial, but it opens up for what’s possible when running the Kaazing gateway.

In fact the Kaazing WebSocket Gateway does already have support for JMS, XMPP, STOMP or even AMQP. You can now easily bring these backends to the web (including browsers like IE6)!!!

Have fun!

Java Client for WebSocket

When folks hear WebSocket, they most-likely imaging using the (native) JavaScript APIs, from modern browsers, to access a WebSocket server. However there is a need for other platforms, like a regular Java client. Several Http Client projects, like Async Http Client or Apache’s HttpClient , have already plans to add WebSocket support.

The Kaazing WebSocket Gateway is an advanced WebSocket server, which contains several Client SDKs, including a Java-based WebSocket client!

After downloading and extracting the Kaazing WebSocket Gateway, you find the Java API inside the lib/client/java folder. Add the JAR to a (blank) Java Project in your IDE (e.g. Eclipse).

A pretty quick (and simple) test is using the API against the public Echo-Server, hosted at websocket.org,like:


package net.wessendorf.kaazing.gateway;

import java.net.URI;
import com.kaazing.gateway.client.html5.WebSocket;
import com.kaazing.gateway.client.html5.WebSocketAdapter;
import com.kaazing.gateway.client.html5.WebSocketEvent;

public class WebSocketTest {

  public static void main(String[] args) throws Exception {
    final WebSocket ws = new WebSocket();
    ws.addWebSocketListener(
          new WebSocketAdapter() {
     @Override
     public void onMessage(WebSocketEvent messageEvent) {
         System.out.println("Received Event Data: " + messageEvent.getData());
         // let's close the open connection...
         try {
             ws.close();
         }
         catch (Exception e) {
             e.printStackTrace();
         }
     }
     @Override
     public void onOpen(WebSocketEvent openEvent) {
         System.out.println("Connection to Server is up!");
          // we are able to talk to the WebSocket gateway
         try {
             ws.send("Hey, server!");
         }
         catch (Exception e) {
             e.printStackTrace();
         }
            }
          }
        );
        ws.connect(new URI("ws://echo.websocket.org:80"));
    }
}

The Java code is pretty straightforward: It creates a WebSocket object, overrides a convenience class to react on some WebSocket events and finally connects to the actual Echo-Server.

Once the connection is up (inside the onOpen() callback), we are sending a simple text to the server. The server returns exactly the same string back to the sending client. This issues our onMessage() callback. After printing the received data to the console, we close the open connection.

Instead of using the remote server, you could try the demos on your machine, by installing the Kaazing WebSocket Gateway on your box!

Have fun!

Joining Kaazing

Tomorrow is my last workday it Oracle.

In March I am joining Kaazing! I will be working on WebSocket, HTML5 and other related technologies to build the next generation web!
I am really excited about it and I am looking forward to start my new adventure there!

Thanks!
Matthias

JPA2 and CloudBees

Besides its “Tomcat-as-a-Service”, the CloudBees service is also offering a hosted MySQL (5.0.51) database. This “database-as-a-service” can be used in various ways. Once you’ve created your database, you can get detailed informations about it in the management console. This console includes a few code samples on how-to configure the hosted database, e.g to be used in JSP or ColdFusion.

Of course, you can also use JPA inside of the CloudBees offer. I’ve tested it with EclipseLink and OpenJPA.

In order to use JPA with the hosted database, you need to include something like below, in your persistence.xml file:

<persistence-unit
  name="myUnit"
  transaction-type="RESOURCE_LOCAL">

<class>my.PersistentObject</class>
...

 <properties>
<!-- JPA standard properties -->
<property
   name="javax.persistence.jdbc.driver"
   value="com.cloudbees.jdbc.Driver"/>
<property
   name="javax.persistence.jdbc.url"
   value="jdbc:cloudbees://YOURSCHEMA"/>
<property
   name="javax.persistence.jdbc.user"
   value="USER"/>
<property
   name="javax.persistence.jdbc.password"
   value="PASSWORD"/>
....

That’s all you need! Now you are able to use the database!

Note: For your local development you can also access the DB via a real URL and the regular MySQL driver. The management console does show the remote connection details as well.

Leaving Oracle

After almost five years I am leaving Oracle at the end of February. In 2006 I joined the company to work on JavaServer Faces related projects like Apache MyFaces/Trinidad or ADF Faces. I had a great time at Oracle and I do have a lot of friends there! I had the opportunity to work on pretty interesting projects with great engineers. I’ve learned a lot!

As I am leaving Oracle, I won’t participate actively in JSF related projects anymore. Therefore I am also step back from being the Apache MyFaces PMC Chair.

I will be moving on to work on some really exciting stuff! I am looking forward to my new adventure!

NotSerializableException for UIComponents

Sometimes I am getting ‘bugs’ that claim there is something wrong with the (Trinidad) framework, as its UIComponents are NOT serializable… An example:

java.io.NotSerializableException:
org.apache.myfaces.trinidad.component.UIXSwitcher

No, this is not a bug at all!

First:
Your (session/application/pageFlow scoped) backing beans should not have an UI component as its property… (if you really really need the “cool” binding attribute).

Second:
UIComponents are not serializable – for a good reason!
In JSF there is StateSaving (see the restore/saveState() hooks)….

Apache MyFaces Trinidad does have a tool that helps to store an reference to an UIComponent (instead of the component itself).

Here are a few blogs on that, that may give more information on the API and why the tool is there:

http://matthiaswessendorf.wordpress.com/2010/03/31/uicomponent-references-in-session-scoped-jsf-beans/

http://leadingyouastray.blogspot.com/2010/02/references-to-uicomponents-in-session.html

Have fun!

Follow

Get every new post delivered to your Inbox.