wesleyhales.com

Pushing CDI Events to the Browser with WebSockets

20 January 2012

html5 websocket jboss jetty cdi

Disclaimer: Minimal load testing was performed with 10000 concurrent WebSocket connections. You can see some true performance numbers here.
Github Icon Download

Here is the demo in action. As you can see on the right, I have 2 chat windows open and on the left we have a member registration. Users are chatting across a raw WebSocket connection and when another user registers, the CDI event is fired all the way through to the browser as a JavaScript alert via the connected WebSocket clients.

With WebSockets, we have a new development model for server side applications; event based programming. There are 3 out-of-box events associated with WebSockets: onopen, onmessage, and onclose. For starters, we must wire up these three listeners to utilize the core functionality that the WebSocket specification gives us. The open event is fired when the WebSocket connection is opened successfully. The message event is fired when the server sends data. The close event is fired when the WebSocket connection is closed.

But sending messages in the form of strings over raw WebSockets isn't very appealing when we're wanting to develop advanced web applications. Obviously, we're going to be using JSON to transfer data to and from the server. But how do we propagate our CDI events which are fired on the server and have them bubble up on the client?

First, we'll start with the server. I'm using the JBoss AS7 application server and embedding Jetty within my web application. Thanks to this article, I was able to easily add the latest Jetty server to my maven project (dependencies below) to get everything up and running in a few minutes.

A few things worth noting:

  • Security: Since our WebSocket server is running on a different port (8081) than our AS7 server (8080), we must account for not having the ability to share cookies, etc...
  • Proxies: As if proxy servers weren't already a huge problem for running WebSockets and HTTP over the same port, we are now running the separately (but I have a semi-solution for this below)
  • Threading: Since we're observing/listening for CDI events, we must perform some thread same operations and connection sharing.

So, if you're still reading ;) let's get on with the code.

Download the latest JBoss AS7 (7.1.0.CR1b as of this writing)

Add the Jetty maven dependencies to your project. This demo is based off of the original html5-mobile quickstart for JBoss AS7.

Next we setup the WebSocket server using Jetty's WebSocketHandler and embedding it inside a ServletContextListener. Here we're sharing a synchronized set of WebSocket connections across threads. Using the synchronized keyword, we ensure that only a single thread can execute a method or block at one time. The ChatWebSocketHandler contains a global Set of webSocket connections and adds each new connection as it's made within the Jetty server View complete source here.

Now we'll create a method to observe CDI events and send the fired "Member" events to all active connections.

The above code will observe the following event when a new Member is registered through the web interface.

Finally, we setup our WebSocket JavaScript client and safely avoid using the eval() method to execute the received JavaScript.

Here is the JavaScript code which listens for our CDI event, and executes the necessary client side code. (This is the alert popup seen in the video above.)

One additional piece I added to this approach is the use of HAProxy. This gives us a reverse-proxy on the WebSocket port (8081), in the end allowing all traffic (HTTP and ws/wss) to be sent across a central port - 8080 in this case.

As you can see, this is a very prototyped approach to achieve $SUBJECT, but it's a step forward in adding a usable programming layer on top of the WebSocket protocol. There's probably a few framework out there which try to provide a programming model on top of WebSockets, so leave comments if you know of any.

2011 Year In Review

29 December 2011

life

This year has been a personal best form me. I’ll spare you the long winded summary and get straight to what I actually produced :)

Published my first DZone Refcard “Mastering Portals with a Portlet Bridge” http://refcardz.dzone.com/refcardz/mastering-portals-portlet

Learned that CSS3 is replacing Photoshop http://wesleyhales.com/blog/2011/02/05/Replacing-Photoshop-With-CSS3-Creating-Styles/

Watched the entire Battlestar Galactica series on Netflix.

Mourned the loss of Stargate Universe

Posted this blog entry and later joined the RichFaces team because of it http://wesleyhales.com/blog/2011/02/16/Going-Mobile-With-RichFaces-4-Part-1-Drag-and-Drop/

Realized that my motivation on the portlet bridge project was exhausted http://wesleyhales.com/blog/2011/04/05/Does-Developing-Portlets-Make-You-a-Better-Developer/

However, I proudly took the project through passing the TCK http://community.jboss.org/people/wesleyhales/blog/2011/09/26/jboss-portlet-bridge-passes-jsr-329-tck

Had a lot of fun with @tech4j creating JBoss’ first mobile web demo http://wesleyhales.com/blog/2011/05/04/Runtime-Type-Detection-and-Usage-with-Weld/

Presented at JBoss World for the first time http://www.slideshare.net/wesleyhales/making-portals-cool-the-compelling-advantages-of-a-portlet-bridge

Read JavaScript The Good Parts (again)

Dressed up like a white bunny and had some fun with @burrsutter http://topsy.com/vimeo.com/27534958

Was in the right place at the right time at JBoss and took a new career path http://wesleyhales.com/blog/2011/07/04/My-New-Career-Choice-at-Red-Hat/

My wife gave birth to the sweetest, most beautiful baby girl in the whole world.

Formed Atlanta’s first HTML5 User Group http://www.meetup.com/AtlantaHTML5/

Presented at JavaOne for the first time http://community.jboss.org/people/wesleyhales/blog/2011/10/17/jboss-and-html5-at-javaone-2011

Proposed a new way to handle AJAX on mobile devices http://community.jboss.org/people/wesleyhales/blog/2011/08/28/fixing-ajax-on-mobile-devices

Wrote an article for HTML5Rocks.com http://www.html5rocks.com/en/mobile/optimization-and-performance.html

Watched all episodes of Breaking Bad on Netflix

Lead the development of the RichFaces mobile effort http://community.jboss.org/people/wesleyhales/blog/2011/11/28/converting-existing-web-apps-for-mobile http://vimeo.com/31616425

Helped form Atlanta’s first JBoss User Group with long time friends from @shadowsoftnews http://vimeo.com/33795907

Signed a contract with O’Reilly Media to write a book called “HTML5 Architecture” coming soon... I hope ;)

Joined the native web apps community group @W3C http://www.w3.org/community/native-web-apps/

Overall I want to thank the people who have supported me and helped me achieve these things. There are too many to list, but you know who you are. I’m starting to realize that technology and trends are irrelevant. The thing that matters most are the people and communities behind them.

2011 has been a mind blowing year and I’m looking forward to topping it in 2012.

Fixing Ajax on Mobile Devices (with HTML5)

29 August 2011

Java ajax html5 innerhtml

“Not only is innerHTML bad, it is the root cause of many problems… from browser memory leaks (it destroys/replaces existing elements that may have event handlers attached) to failing completely on iOS’s Mobile Safari. Yes, that‘s right, it just flakes out.”

Read on...

RichFaces Mobile Designs - Day 3

03 August 2011

Java java mobile richfaces

So I made it over the hump of this mobile design week of madness. Below you will find a dark theme with a component skin for the rich:accordion component.


Day 3: About The Design


Here we have another phone based design broke out into 3 pages.
The first page is a standard menu so not much to say there. The bottom menu bar is a little different from my first design – following the lead of the native twitter iPhone app.
RichFace Mobile Skin1



As you can see with the second page (below), this is not a standard accordion panel type of component. When you touch an option from page one, the accordion expands on a different page and only focuses on that specific panel. Not sure if it could work, but accordion collapse/expand style of components don‘t make a ton of sense to me on limited screen real estate.
RichFace Mobile Skin1



So after you go through the menu options and decide on a component, you are taken to the detail/demo screen(below) where you can play around with your component of choice.

Note the small orange page marker dots at the bottom. The user would have the ability to flip through each component in the given section by swiping horizontally.
RichFace Mobile Skin1




Going Mobile With RichFaces! Design Proposals - Day2

02 August 2011

Java java jsf mobile richfaces web

Day 2 of the RichFaces skinning and we have the first approach for tablet devices. Tablets are a little harder to design for because of a few reasons:

1) Your design sits on the fine line between desktop and mobile. You are designing your app for a max 1024 pixel resolution (in landscape mode) but you must also take advantage of mobile usability (which you will see in page2)

2) Similar to the iPad Mail.app, it‘s almost like you are designing 2 different UI‘s for landscape and portrait modes. For portrait you need more drop down menus, and for landscape you can try to fit everything on one page without the drop downs.


RichFace Mobile Skin1

Day 2: About The Design


Here we have the interaction broken out into 2 pages. The first page shows the primary menu and isn‘t all that exciting.

Notice how, unlike the iphone design from Day 1, I left the browser button overrides within the app itself. Tablet web apps are completely use case driven so this will vary. But since we have so much more real estate, we can play around with standard navigation options that keep the user's attention focused on the app itself.



RichFace Mobile Skin1





The second page is what you see after selecting a menu item from page 1 (click to enlarge). Here we have the title bar at the top left with a built in back button which takes the user back to the first screen.

To the right of the title you see the secondary menu represented by rounded rectangles. Next is the main content of the page broken out into content and actionable panels.

And finally you have the big arrows to the right and left. These arrows are “thumb reachable” which is a common usability pattern in portrait mode tablets. It provides an easy page flip access to all of the RichFaces components within the top level category.


The great thing about CSS3 transitions is that you can really make a UI like this scream and flow seamlessly. So you can imagine how tapping an arrow with your thumb will slide in a new component demo and gracefully highlight the secondary menu option at the top.


So this concludes our design for Day 2. As I said earlier, this is more of a use case driven design. WE could spawn a very minimalistic skin and component look and feel from this. However, It would be more to display the power behind RichFaces ajax and templating features as the user moves through the app.

Going Mobile With RichFaces! Design Proposals - Day1

01 August 2011

Java java jsf mobile richfaces web

Today marks an important day in the RichFaces project as we continue to head down the mobile web road. Since we have such a great community of users and followers, we want you to be involved with the design process.
So each day this week, I will come up with a new proposed design/theme for RichFaces Mobile and we want to hear your feedback.

I will announce each new design (both for tablet and phone) via twitter with a link back to this article. I will try my best to pick apart each design and describe why I did what I did, and hope you can give me some real world feedback. We want this project to actually make sense and be usable to what you guys are facing in the real world. Without further adieu....


RichFace Mobile Skin1Our first task is to tackle the RichFaces showcase of components. Classifying what is mobile ready and which components may need a little work.

Day 1: About The Design


Here we have what could be the RichFaces component showcase skin. This is what I will be posting a new version of each day this week.

In this design we have the standard browser “functionality take over” at the top header. The custom back button is essential to mobile web design and must be overridden here – following the pattern of previous designs.

Nothing too different about the standard menu options and detail options (center stage). Following convention here as well. One thing I am adhering too are the usability guidelines set forth by Jakob Nielsen‘s Usability of iPad Apps and Websites

To get the full tab bar at the bottom (and to replicate the native feel) the user must bookmark the application. I think it makes sense for this menu to be contextual to the app and provide other alternate routes.




My New Career Choice at Red Hat

04 July 2011

Life jboss

July 1st marked my first day on the JBoss RichFaces team. I've decided to push myself and get out of my comfort zone. It seems that a developer only has so many years that he or she can sustain the same position doing the same thing and dealing with the same technology.

I’ve been with Red Hat almost 4 years now and have enjoyed every second of it, and this is the first time in my career that I have chosen the position for myself while working within a company. It’s usually the other way around - as you are either picked for your skills and talent to work on a specific team or for whatever reason you are just told to move to another team.

As for my new position, I have been designated to serve on JBoss’ mobile working group (see Tiger Team). I will be part time on the actual RichFaces project (making the project work on mobile devices) and the other part heavily focused on HTML5 and the Mobile Web. This is a new frontier for developers as we try to create HTML5/CSS3 based web apps that not only match the native app feel but also answer the question “How can we make the mobile web faster using JBoss middleware?”.

As things grow, so will the project and the team. I find excitement in bringing grass roots projects from nothing into full blown enterprise supported products ;) Luckily I was in the right place at the right time and I must say that it was quite an honor to be allowed to make such a move. I’m looking forward to making good stuff happen.

Stay tuned…

Runtime Type Detection and Usage with Weld

04 May 2011

Java cdi hornetq infinispan jms jsf richfaces seam weld

About TweetStream


tweetstreamIn developing the TweetStream demo for the JBoss World keynote and JUDCon presentation, I wanted to use CDI in a way that would choose the implementation of a given type at runtime. With Qualifiers and Producers, CDI gives you the power to do this.
A little bit about the usecase: The TweetStream application is an app that Jay Balunas and I developed over the past few months for our presentation at JUDCon and JBoss World 2011. It was purposely developed with a myriad of JBoss community projects to showcase how you can build a mobile HTML5 web application (which runs on Android and iOS devices) with things like scalable data grid, JMS, JSF2, HTML5/CSS3 and other middleware technologies. This application (TweetStream) was also chosen to be part of the literally incredible JBoss World 2011 keynote.
So, we had 2 scenarios – 1) for our presentation we needed a mobile app that could run solely on it’s own so that users could pull the source code, see how we did things, and run it. 2) For the keynote, we had to make our app integrate with the Infinispan datagrid that was already setup as part of the keynote demo. The data stored on this grid utilized Drools and complex event processing as part of the keynote, so our app had to consume that data for that environment.
So we got our tweet data from the true source (twitter4j) during our JUDCon presentation, and then from the data grid during the keynote. We could have used CDI alternatives, but I wanted a true solution with no XML configuration and runtime detection.


The Code...


So we have 2 Qualifier Types:
@TwitterLocal for the JUDCon demo impl
@TwitterServer for the keynote impl

We used infinispan in both instances, but our @TwitterLocal is a single node caching a direct twitter stream from Twitter4J.

Now that we have our types defined as follows…

@Qualifier

@Retention(RetentionPolicy.RUNTIME)

@Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})

public @interface TwitterServer

{

}



@Qualifier

@Retention(RetentionPolicy.RUNTIME)

@Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})

public @interface TwitterLocal

{

}

We need not only an implementation of each, but also a deciding bean that tells us which type to use.

First, our implementation of each Type implements an interface:

public interface TwitterSource {

  public void init();

And our implementations have a different usage of the init method. TwitterLocal starts the stream coming from twitter and updates the infinispan cache. TwitterServer starts a method which allows us to start receiving data from the keynote which uses complex event processing and a datagrid with 6–8 nodes.

So now, how do we decide which Type to use? There are a few different ways to do it, but in the case of this being a demo and not a lot of time on my part. I used this approach:

public class TweetStream {



  @Inject

  @Any

  Instance<TwitterSource> twitterSource;



  class TwitterLocalQualifier extends AnnotationLiteral<TwitterLocal> implements TwitterLocal

  {

  }



  class TwitterServerQualifier extends AnnotationLiteral<TwitterServer> implements TwitterServer

  {

  }



  boolean initialCheck = true;

  boolean demoexists = false;



  @PostConstruct

  private void init()

  {

     getTwitterSource().init();

  }





  @Produces

  public TwitterSource getTwitterSource()

  {

     if (initialCheck)

     {

        try

        {

                   Class.forName("org.jboss.jbw2011.keynote.demo.model.TweetAggregate");

           log.info("Running in JBW2011 Demo Mode.");

           demoexists = true;

        }

        catch (ClassNotFoundException ex)

        {

           log.info("Running in local JUDCon2011 Demo Mode.");

        }

        initialCheck = false;

     }



     Annotation qualifier = demoexists ?

        new TwitterServerQualifier() : new TwitterLocalQualifier();

     return twitterSource.select(qualifier).get();

  }

This is all in the source code. Feel free to pull it and make improvements or run it to see it in action. There are many more blog posts to come from this demo, so stay tuned…

Does Developing Portlets Make You a Better Developer?

05 April 2011

Java java jsf portal portlets

Working with portlet technology is often discredited for it’s seemingly complex API and development hoops one must jump through. But if you have worked on a portlet project for a considerable amount of time, and then jump back to a servlet based project, you have a feeling that life just got easier.
This is all within the context of which servlet-based framework you might be working with, but overall things are a bit easier when dealing with one request and response.

What if you didn’t have to worry about portlet development gotchas anymore? What if you could develop portlets with the ease and hassle free life that you have with good ol’ servlets? Well, I’m here to tell you that this can be partly achieved with JSR-301 portlet bridge technology.

I encourage (actually I dare you) to those who have never even touched a portal to take the JBoss Portlet Bridge for a test drive. It takes 1 download (GateIn bundled with JBoss) and one maven archetype to get started. You can choose from any combination of plain JSF, Richfaces, and Seam with
mvn archetype:generate -DarchetypeCatalog=http://bit.ly/jbossportletbridge from the command line.

If you run into any questions or special usecases, we have 7 videos which demo and walk you through just about anything you could think up.

And for those that like to have a refcard by their side, you can get all the information you need about the story of portal technology and configuration drill downs here:


From “Mastering Portals with a Portlet Bridge” DZone Refcard:
“A portlet bridge allows you to run application frameworks like JSF in a portal environment without needing to know anything about the underlying portlet API or portlet concepts.”






And if all that wasn’t enough, I will be giving a 50 minute talk at JBoss World titled "Making Portals Cool: The Compelling Advantages of a Portlet Bridge" where you can come and personally track me down and specifically tell me about your problems, pains, or happiness with the project or the world in general ;) JBoss World will be located in Boston from May 3–6.
I think early bird pricing ends this Friday (April 8th), so you better hurry if you want to save a little cash.

Going Mobile With RichFaces 4 - Part 1: Drag and Drop

16 February 2011

Java jquery jsf richfaces

Richfaces 4 just reached Milestone 6 and now would be a great time for the community to step up and check how the components run on mobile platforms.
First off, Richfaces 4 currently does not offer mobile support but it is definitely the direction they are heading. And the RF team has taken all the necessary steps to allow the client side code to be extended and improved by way of jQuery.

Today I am going to add touch support to the RF drag and drop component. We all know that touch events and gestures are not the same as a mouse click. So one must consider a couple of different approaches before implementing a final solution:

1) Override the default touch events with their mouse counterparts.
This is easy since you are basically overriding the default functionality of touch and gesture events. There are 3 mouse events to replace to get this component working:
touchstart,touchmove,touchend

2) Extend jQuery core components and add the “drag” functionality alongside “touch”
A little more difficult and fortunately the jQuery team is working on the mobile upgrade to ui.draggable – so this should be available in the next few weeks/months.

(tested on live iPhone4 and iOS simulator iPad)

I originally started out using the touch and gesture events to do the drag and drop. This allowed for a smoother UX but unfortunately, the internal plumbing of Richfaces required a complex extension/wrap of rf.ui.draggable (to add the new touch functions) and some custom bindings like rf.Event.bind(this.dragElement, ‘touchstart‘+this.namespace….) in dnd-draggable.js.
In the end, it was just easier for me to use this script and re-map the 3 main touch events.

I looked at many different approaches starting with SenchaTouch which btw is pointless if you are going to leverage existing jQuery, then moving to a few different jQuery utilities.
The basic question here, which can be applied to any component framework, is “What’s the best mobile approach for supporting product xyz?” Every product out there that touches the UI has to cross this gap. Touch interfaces today… tangible UI’s tomorrow… and the vicious cycle continues. And majority of the time, the best way to get started is to build an emulator so that your product can work today. This will buy you the time to build the native functionality that takes full advantage of the target platform.
Unfortunately the script I used here doesn’t always work and there are still a few more components in Richfaces that do not work with this duck punch approach. So I will try to make this a series and blog about & fix the other components on mobile platforms.

The old days of drag and drop are not as simple as they used to be. With multi touch surfaces you have the ability to accelerate your drag and throw it across the page, rotate it, and auto scrolling when you drag the object off the page, etc... Just something to think about when designing a similar component.