<?xml version="1.0" encoding="utf-8"?>
<feed version="0.3" xmlns="http://purl.org/atom/ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="en">
<title>Elie Levy&apos;s Blog</title>
<link rel="alternate" type="text/html" href="http://weblogs.java.net/blog/elevy/" />
<modified>2008-05-30T18:31:13Z</modified>
<tagline></tagline>
<id>tag:weblogs.java.net,2008:/blog/elevy/391</id>
<generator url="http://www.movabletype.org/" version="3.01D">Movable Type</generator>
<copyright>Copyright (c) 2008, elevy</copyright>
<entry>
<title>JavaOne - Extending Swing: Creating your own components</title>
<link rel="alternate" type="text/html" href="http://weblogs.java.net/blog/elevy/archive/2008/05/javaone_extendi.html" />
<modified>2008-05-30T18:31:13Z</modified>
<issued>2008-05-30T18:31:05Z</issued>
<id>tag:weblogs.java.net,2008:/blog/elevy/391.9902</id>
<created>2008-05-30T18:31:05Z</created>
<summary type="text/plain">The slides of my JavaOne session are available for download.</summary>
<author>
<name>elevy</name>

<email>elie.levy@usa.net</email>
</author>
<dc:subject>Community: JavaDesktop</dc:subject>
<content type="text/html" mode="escaped" xml:lang="en" xml:base="http://weblogs.java.net/blog/elevy/">
<![CDATA[The JavaOne slides are available now for download. My session on how to extend the swing API creating your own components can be reached at:<br>
<A href="http://developers.sun.com/learning/javaoneonline/j1sessn.jsp?sessn=TS-4982&yr=2008&track=desktop">Extending Swing: Creating your own components</A><br><br>
Thank you all for the positive feedback you have gave me, it was a great experience!]]>

</content>
</entry>
<entry>
<title>Securing the integrity and authenticity of links</title>
<link rel="alternate" type="text/html" href="http://weblogs.java.net/blog/elevy/archive/2008/05/securing_the_in.html" />
<modified>2008-05-13T20:40:34Z</modified>
<issued>2008-05-13T20:40:27Z</issued>
<id>tag:weblogs.java.net,2008:/blog/elevy/391.9796</id>
<created>2008-05-13T20:40:27Z</created>
<summary type="text/plain">Form hidden fields, query string arguments, and cookie values are frequently used as parameters to keep session state on the client of web based application. In this blog, I explore an option for securing those values. The key to this approach is that even if the developer is unaware of the problem, they are safe, thanks to the underlining framework.
</summary>
<author>
<name>elevy</name>

<email>elie.levy@usa.net</email>
</author>
<dc:subject>Community: Java Enterprise</dc:subject>
<content type="text/html" mode="escaped" xml:lang="en" xml:base="http://weblogs.java.net/blog/elevy/">
<![CDATA[It has been a while since my last posting. As you can imagine, I have been really busy. Last week I was presenting at the JavaOne, and it was amazing. Thank you all for all the positive feedback on my session. I will most likely writing something about the demos I showed, and may be I will post them here with Java WebStart. That will have to wait for now...<br><br>

Now back to the blog that I have been thinking to write:<br><br>

Form hidden fields, query string arguments, and cookie values are frequently used as parameters to keep session state on the client of web based application. In this blog, I explore an option for securing those values. The key to this approach is that even if the developer is unaware of the problem, they are safe, thanks to the underlining framework.<br><br>

The problem is that it is extremely easy for an attacker to change the values of any of these parameters. Making the Web Application vulnerable if the developers are not careful.<br><br>

My first recommendation to address this problem is to avoid using those parameters in the first place. If that is not possible, then strong validation is necessary.<br><br>

However, there are some cases where that validation is not easy to do. How do you achieve security?<br><br>

In this blog, I am going to describe a solution for the parameters in the query string. It would be trivial to extrapolate it and apply it to the other cases.<br><br>

The idea is to use a keyed-Hash Message Authentication Code (HMAC).<br><br>

HMAC is just a hash value combined with a private key. In this case we are going to use it as a checksum.<br><br>

The idea is to get the URL with the parameters, pass it through the HMAC algorithm, and append this "checksum" to the query string. 

In this way when we receive a URL we can calculate the checksum again. If it matches, we know that the URL was generated from our application. If it doesn't, ALARM! someone modified the query string.<br><br>

A problem that we would still have, is that if someone was to be able to get to the computer of an authorized user, after looking at the browse history, the attacker can replicate the requests, and potentially violate the system security.<br><br>

A way to stop that from happening would be to include a timeout as part of the query string, and then obtain the HMAC. The validation phase would include validating that the timeout has not expired.<br><br>

There is no constraint that does not have side effects. In this case, a bookmark would only be good for the lifetime of the session (until the timeout of the query string is good). I personally don't think of this as a problem, on the contrary I see this as a benefit. The links that we would protect using this technique, are the type of links we would not want the user to bookmark in the first place.<br><br>

Now that we have gone through the theory, let's see some code of what would it take to implement something like this. In this case, I will extend the struts framework. Obviously, the same idea can be applied to almost any other framework as well.<br><br>

The first step will be to identify which Actions are going to have this security. For that we can extend the Action Mapping class to include a requireHMAC parameter:<br><br>

<pre>

public class SecureActionMapping extends RequestActionMapping {

   protected boolean requiresHMAC;

   public boolean getRequiresHMAC() {
      return requiresHMAC;
   }

   public void setRequiresHMAC(boolean requiresHMAC) {
      this.requiresHMAC = requiresHMAC;
   }

}

</pre>

Then in the struts-config.xml file we need to configure struts to use this as the ActionMapping class:

<pre>

&lt;action-mappings type="org.zilonis.hmaclinks.SecureActionMapping"&gt;
     .... all the action mappings
   &lt;action path="/editUser" type="EditUserAction"&gt;
      &lt;set-property property="requiresHMAC" value="true"/&gt;
   &lt;/action&gt;
&lt;/action-mappings&gt;

</pre>
<br><br>
In the Struts html tag library we have the custom tag html:link. To generate the links all we need to do is extend it to include the HMAC and the timeout as part of the link.<br><br>

To generate the HMAC:<br><br>

<pre>

   private final static JTIME="&time=";
   private final static HMAC="&jval=";
   public static String appendHMACSecurity(String url) {
      url+= JTIME + System.currentTimeMillis();
      url+= HMAC + HMACGenerator.genHMac(url);
      return url;
   }

   public class HMACGenerator {
      private final static SecretKey key = genKey();
      
      public static String getMac(String url) {         
         Mac mac = Mac.getInstance(key.getAlgorithm());
         mac.init(key);
         byte utf8[] = url.getBytes("UTF8");
         byte digest[] = mac.doFinal(utf8);
         String result = URLEncoder.encode(new Base64Encoder.encode(digest));
      }
      private final static SecretKey genKey() {         
         KeyGenerator keyGen = KeyGenerator.getInstance("HmacMD5");
         return keyGen.generateKey();
      }
   }

</pre>
<br><br>     
I have omited purposely Exception handling for readability.
<br><br>
An interesting trick here is that I am generating the key in a static final field. That means that the first time the application gets started, the private key is going to be generated. In this way, there is no need to have any key management procedures with the operations team. If you were on a situation that your application does not get restarted in a long time (more than 15 days) you might want to considering putting some code there to generate a new key every now and then...
<br><br>
To verify the HMAC we just need to extend the FrontProcessor servlet to check if the action requires an HMAC. Then a similar piece of code to generate the HMAC and compare it with the one we are receiving. Notice that we are not decrypting the HMAC. The HMAC never gets decrypted. All we do is generate again our "checksum" and verify that it is the same we are receiving.<br><br>
Finally we just need to check the timeout.
<br><br>
This technique might be overkill for some environments. But there are some situations where other options are not really feasible. This is easy enough to turn on/off on any use case you application might have.]]>

</content>
</entry>
<entry>
<title>Help? Yes, you can use JavaHelp!</title>
<link rel="alternate" type="text/html" href="http://weblogs.java.net/blog/elevy/archive/2008/01/help_yes_you_ca.html" />
<modified>2008-01-15T18:31:15Z</modified>
<issued>2008-01-15T18:22:47Z</issued>
<id>tag:weblogs.java.net,2008:/blog/elevy/391.8951</id>
<created>2008-01-15T18:22:47Z</created>
<summary type="text/plain">I don&apos;t know about you, I thought JavaHelp was not ready. To my surprise, it works really well. In this blog, I describe some details of how I am using it.</summary>
<author>
<name>elevy</name>

<email>elie.levy@usa.net</email>
</author>
<dc:subject>Community: JavaDesktop</dc:subject>
<content type="text/html" mode="escaped" xml:lang="en" xml:base="http://weblogs.java.net/blog/elevy/">
<![CDATA[Being a server side developer, never had to worry about "help". I mean, about how to provide help to the users of my applications. They were simply just another JSP with ... well that's not what I want to blog about this time.<br><br>

I have been working with client side Java for a while now, learning different interesting things that you can do with Swing. The time came to put together a "help".<br><br>

As I always do, before writing a line of code, I started to google around to find out how others have done it. Other people had to include their help in the rich Java client applications at some point right?.<br><br>

I found a project called JavaHelp. I started reading about it. All I could find was extremely old. All the documentation seemed to be outdated. I wondered, is this project still alive? is this the way to go?<br><br>

I continued doing more research, and I decided I had to give it a try. I downloaded a open source authoring tool, which did not end up being really good. That's why I will not bother mentioning it in here.<br><br>

Continuously reading any documentation I was able to find, encountered some Java code on how to call the JavaHelp system.<br><br>

Finally, got it to work.<br><br>

Then, discovered that you can generate indexes for including the search capabilities. And you know what? it works great!!!!<br><br>

As I mentioned before the documentation was not really good.<br><br>

To get started, just create your content in HTML. Use a page per section of your help.<br><br>

Then you need to create some configuration files to define how the table of contents is going to be structured, and what are the views that you want to include.<br><br>

Here is what I did:<br><br>

1) Created the helpset definition file: master.hs<br><br>


&lt;?xml version="1.0" encoding="ISO-8859-1"?&gt;<br>
&lt;helpset&gt;<br>
  &lt;title&gt;reis-help&lt;/title&gt;<br>
  &lt;maps&gt;<br>
    &lt;mapref location="map.jhm"/&gt;<br>
  &lt;maps&gt;<br>
  &lt;view&gt;<br>
    &lt;name&gt;Table of Contents&lt;/name&gt;<br>
    &lt;label&gt;Table of Contents&lt;/label&gt;<br>
    &lt;type&gt;javax.help.TOCView&lt;/type&gt;<br>
    &lt;data&gt;toc.xml&lt;/data&gt;<br>
  &lt;/view&gt;<br>
  &lt;view&gt;<br>
    &lt;name&gt;Search&lt;/name&gt;<br>
    &lt;label&gt;Search&lt;/label&gt;<br>
    &lt;type&gt;javax.help.SearchView&lt;/type&gt;<br>
    &lt;data engine="com.sun.java.help.search.DefaultSearchEngine"&gt;chapters/searchDb&lt;/data>
  &lt;/view&gt;<br>
&lt;/helpset&gt;
<br><br>
2) Create the table of contents in the toc.xml file<br><br>

&lt;?xml version="1.0" encoding="ISO-8859-1"?&gt;<br>
&lt;!DOCTYPE toc PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp TOC Version 1.0//EN" "http://java.sun.com/products/javahelp/toc_2_0.dtd">
&lt;toc version="2.0"&gt;<br>
  &lt;tocitem target="Module_1_help_id" text="Module 1 Label"/&gt;<br>
  &lt;tocitem target="Module_2_help_id" text="Module 2 Label"/&gt;<br>
&lt;/toc&gt;<br>

<br><br>
3) Create the mapping file. As you probably saw in the step 2, each of the entries in the table of contents references the documents with ids. Those ids are defined in the mapping file that references the real file. Here is a sample one:<br><br>

&lt;?xml version="1.0" encoding="ISO-8859-1" standalone="no"?&gt;<br>
&lt;!DOCTYPE map PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp Map Version 1.0//EN
" "http://java.sun.com/products/javahelp/map_1_0.dtd"&gt;<br>
&lt;map version="1.0"&gt;<br>
  &lt;mapID target="Module_1_help_id" url="chapters/3. module1Help1.html"/&gt;<br>
  &lt;mapID target="Module_2_help_id" url="chapters/4. module1Help2.html"/&gt;<br>
&lt;/map&gt;<br>

4) Create the index (only if you want to use the search, which I recommend).<br><br>
run:<br><br>
<pre>
jhindexer chapters
</pre>
<br><br>
Where chapters is the directory where you have your content. It will go recursively through the directory structure and index all the files.<br><br>

Note that jhindexer has to be in the PATH env variable. It is installed at the bin directory of the JavaHelp distribution.<br><br>

That's it!<br><br>

Now all you have to do is call from your Java code the help component.<br><br>

All the documentation I found uses the broker to create the JavaHelp component. It is like a level of indirection between your code and the code that creates and opens the JavaHelp dialog. The problem is that you don't have control over the dialog it generates. You can not set the icons, you can not get to the GlassPane if you want to do something fancy there.<br><br>

I did a little bit of scanning in the source code (open source advantage!) and found that there is a class called JHelp. It is a Swing component that does everything you will need.<br><br>

Here is my Java code that opens the JavaHelp window:<br><br>

<pre>
                String pathToHS = "/master.hs";
		try {
			hsURL = MainFrame.class.getResource(pathToHS);
			hs = new HelpSet(null, hsURL);
		} catch (Exception e) {
			e.printStackTrace();
			return;
		}
		JHelp jHelp = new JHelp(hs);
		JDialog dialog = new JDialog(this, "Help", true);
		dialog.add("Center", jHelp);
		dialog.setSize(new Dimension(950, 700));
		dialog.setLocationRelativeTo(null);
		dialog.setVisible(true);
</pre>

That should do it for you too.<br><br>

There are others things I read about that I haven't tried. You can merge different help files dynamically. In this way the user can to install some modules at this time, then later when the other modules are downloaded/installed you can merge dynamically the help for those new modules.]]>

</content>
</entry>
<entry>
<title>Zilonis JavaOne Presentation Slides</title>
<link rel="alternate" type="text/html" href="http://weblogs.java.net/blog/elevy/archive/2007/10/zilonis_javaone.html" />
<modified>2007-10-25T15:59:49Z</modified>
<issued>2007-10-25T15:59:43Z</issued>
<id>tag:weblogs.java.net,2007:/blog/elevy/391.8492</id>
<created>2007-10-25T15:59:43Z</created>
<summary type="text/plain">Finally the slides from the &quot;Zilonis Rules Engine&quot; JavaOne presentation are available. In the slides I presented the internals of how Zilonis uses the Java Concurrency API&apos;s to manage concurrent access to the Working Memory.</summary>
<author>
<name>elevy</name>

<email>elie.levy@usa.net</email>
</author>
<dc:subject>Community: Java Enterprise</dc:subject>
<content type="text/html" mode="escaped" xml:lang="en" xml:base="http://weblogs.java.net/blog/elevy/">
<![CDATA[Finally the slides from the <a href="http://www.zilonis.org">Zilonis Rules Engine</a> JavaOne presentation are available. In the slides I presented the internals of how Zilonis uses the Java Concurrency API's to manage concurrent access to the Working Memory.<br><br>

<a href="http://www.zilonis.org/J1_2007_zilonis_pub.pdf">The Java Concurrency API and Deadlock Prevention in a RETE Rules Engine to Implement a Pricing Service</a><br><br>


]]>

</content>
</entry>
<entry>
<title>Power-N Architectures</title>
<link rel="alternate" type="text/html" href="http://weblogs.java.net/blog/elevy/archive/2007/09/powern_architec.html" />
<modified>2007-09-21T15:28:40Z</modified>
<issued>2007-09-21T15:28:35Z</issued>
<id>tag:weblogs.java.net,2007:/blog/elevy/391.8295</id>
<created>2007-09-21T15:28:35Z</created>
<summary type="text/plain">With the availability of WebServices across the Internet, and the semantic web technologies, a new architecture of applications is going to start to appear. In this blog, I explain how the n-tier architecture is exploding into the power of N.

</summary>
<author>
<name>elevy</name>

<email>elie.levy@usa.net</email>
</author>
<dc:subject>Community: Java Enterprise</dc:subject>
<content type="text/html" mode="escaped" xml:lang="en" xml:base="http://weblogs.java.net/blog/elevy/">
<![CDATA[Early in the dot com boom era, a lot of companies implemented the popular portals. Those portals allowed us to "integrate" multiple applications together into a single screen. I write "integrate" between quotes, because there was nothing really integrated, it was just that the set of applications were displayed in the same screen. The reason for the low level of integration was not because of lack of need, or lack of will. It was primarily because the applications at the time were written to produce data mixed with the rendering information, loosing all the semantics of the "data" that was being produced as a result of a request from the clients.<br><br>

With the services and technologies that are available today I see a completely different future.<br><br>

The ability to create a Rich Client user interface, with most of the benefits that a Thin Client offer, is an amazing technological resource. Think about it for a second. You can create a Rich Client application, that has zero maintenance cost. It is downloaded from the web, it runs on your client machine, and when there is a newer version, it downloads automatically an update (auto-update). For those of you that haven’t have the exposure to it, take a look at Java WebStart.<br><br>

Adding to that we have lots of "backend" services sitting on the web, that can be easily accessed (i.e. google base, etc) and integrated, and semantically integrated.<br><br>

These resources (technologies + services) give birth to what I am calling power-N architectures.<br><br>

We can write a Rich Client application that accesses M * N-Tier services on the Web, integrate the data that the services have, and provide a really powerful tool for the end user.<br><br>

<img alt="Power-N Architectures" align="center" src="http://weblogs.java.net/blog/elevy/archive/powern.JPG" width="285" height="280" /><br><br>


On many cases, as an application/service provider, writing the client application is not going to be enough. Most likely you will still have to provide your own services that provide an extra touch to make your application really unique, but I claim that most of the services that you would need are out there, just waiting to be integrated.<br><br>

There are 2 fundamental differences with the approach I am presenting here.<br><br>

<b>Distribution of Tasks</b><br><br>

The first one, is using a Rich Client interface that directly accesses the services that are distributed across the network. This is a very important difference. You are having all the advantages of a truly distributed application.<br><br>

Specially scalability and high availability.<br><br>

With the old model, all the services were tunneled through one server that acted as a proxy for you application. With JavaScript, AJAX, and all those technologies you really have no choice but do something like that. It would be extremely complicated to write an application in AJAX that goes to multiple services, and merges the data in an intelligent way. Not the case for full rich client java applications. In this scenario, having your server down, means your application is fully down.<br<br>

In the Power-N architecture, the clients are more independent of the backend availability. If one of the services is down, that only means that the areas of the application that depend on that service is down. But the user can continue using the rest of the services without a problem.<br><br>

I will not write about Scalability, I think it is obvious.<br><br>

<b>Integration</b><br><br>

The second fundamental difference is Integration. With XML, and the semantic web technologies, we can write application that truly integrate different services. Here I am not talking about just presenting different unrelated information in the same screen. I am talking about real integration.<br><br>

<b>Specialized Browers</b><br><br>

What will end up happening is that these Rich Client applications distributed across the web, are going to be sort of specialized browsers, that will access and integrate different web services, and provide rich and unique functionalities that are going to facilitate the life of the users.<br><br>

You can access the reviews of a book in amazon.com, and query wikipedia on that book, find the author and its place of birth, get the geo coordinates and map the location, then go to another service and find how much would be a flight ticket to get there, and on, and on, and on…<br><br>

I am not trying to present here a specific use case of a business that would work. I am just presenting an architecture that is here in front of us just waiting to be exploded into what will be the real new web.<br><br>
]]>

</content>
</entry>
<entry>
<title>Single Sign On</title>
<link rel="alternate" type="text/html" href="http://weblogs.java.net/blog/elevy/archive/2007/08/single_sign_on.html" />
<modified>2007-08-29T20:56:11Z</modified>
<issued>2007-08-29T20:56:03Z</issued>
<id>tag:weblogs.java.net,2007:/blog/elevy/391.8130</id>
<created>2007-08-29T20:56:03Z</created>
<summary type="text/plain">In the last few weeks I was asked to help to integrate a set of built-in-house web applications with a Single Sign On (SSO) solution. After working with people from different teams, I realized that it would be a good idea to write a brief description of how the SSO solutions work in general. Perhaps this might help you to get started if you have to do something like this at some point.
</summary>
<author>
<name>elevy</name>

<email>elie.levy@usa.net</email>
</author>
<dc:subject>Community: Java Enterprise</dc:subject>
<content type="text/html" mode="escaped" xml:lang="en" xml:base="http://weblogs.java.net/blog/elevy/">
<![CDATA[In the last few weeks I was asked to help to integrate a set of built-in-house web applications with a Single Sign On (SSO) solution. After working with people from different teams, I realized that it would be a good idea to write a brief description of how the SSO solutions work in general. Perhaps this might help you to get started if you have to do something like this at some point.<br><br>

SSO is by no means a new technology. It has been in use for a long time. Even before the Web Applications were available.<br><br>

The most primitive of SSO systems is a piece of paper per user with a small table listing systems with the user names and passwords. This list can be generally stamped on the user monitor. Later on it can evolve, instead any simple piece of paper, it can be a post-it.<br><br>
<img alt="passwords.jpg" src="http://weblogs.java.net/blog/elevy/archive/img/passwords.jpg/passwords.jpg" width="370" height="170" align="center"/><br>
(for those of you interested in how I created this picture, I did it using the napkin look and feel)
<br><br>
Yes, you might be thinking that I am kidding here. And to some extent I am. However, this has been a big concern in the corporate world. That's the way it used to be, not by design, and it still is in some companies. Lots of applications, managed by different teams in the famous "silos", not integrated, each requiring the user to authenticate with its own username/password... you know the picture.<br><br>

I think that that's how the need of SSO got started.<br><br>

Early SSO systems worked as the post-it that the users where sticking to their monitors.<br><br> 

They were repositories of users/passwords pairs protected by a password. In that way before the user would authenticate to the destination system, they would first access the SSO repository, fetch their passwords, and continue authenticating with the system they were intending to work on the first place.<br><br> 

Lately, In a web based environment, this can be extremely simplified with a well know device: cookies.<br><br>  

<h3>Example</h3>

We will go over an SSO implementation with an example. Let's have 3 major components: The SSO server, Application A, Application B.<br><br>

Here is how the system would work:<br><br>

1) The user tries to access the application A. <br><br>

2) Application A realizes that the user has not been authenticated. (See <A href="#authenticated">"user has been authenticated"</a> for details).<br><br>

3) Application A sends an HTTP redirect to the SSO server.<br><br>

4) The SSO server sees that the user is not authenticated (again, See "user has been authenticated" for details).<br><br>

5) The SSO server requires the user to authenticate.<br><br>

6) The user submits username/password<br><br>

7) SSO Server validates username/password. If they are valid, the user is <a href="#grantedPermission">"granted permission"</a>.<br><br>

8) The user is redirected to Application A.<br><br>

9) Application A sees that the user has been authenticated, and proceeds.<br><br>

<h3 id="grantedPermission">Granting permission:</h3>

When the username and password are validated by the SSO server, a unique large token is generated for the user. The token is going to have a unique identifier for the user's session. The SSO server keeps a list of the tokens associated with the credentials of the user that owns it. This token is set by the SSO server in the user's browser as a cookie.<br><br>

<h3 id="authenticated">User has been authenticated:</h3>

For an application to validate that a user has been authenticated it has to follow this steps:<br><br>

1) Check for the token in the cookies.<br><br>

2) Query the SSO server for the credentials associated with the token. If the token is valid, the SSO returns the credentials of the user for the application to continue. If the token is not present, or is invalid, the application knows that the user has not been authenticated, and is redirected to the SSO server.<br><br>

This makes it look like there is a lot of work to get this type of setup. Luckily, it is not complicated at all. Most SSO servers come with a plug-in that is installed in the application/web server that intercepts all the requests, and performs the logic just described. Any application deployed in such a server will automatically get the user credentials, populated by the plug-in, just as if the user was authenticated locally using the JAAS framework.<br><br>

<h3>A Note on Cookies</h3>
As most of you know the capabilities of setting and reading cookies are restricted by the domains. A web server that does not belong to the domain where the cookie was set will not be able to read the cookie.<br><br>

For that reason the applications and the SSO server have to belong to the same domain. Indeed, if they are not to be part of the same domain the cookies would not work. For that case the URL rewriting technique can be used.

<h3>Development TIP:</h3>

When you are developing your app, no need to authenticate with the SSO. Just have each developer to work with a simple JAAS authentication within a local flat file (most of the IDEs have this by default). Get them to complete the development, and when you are ready to test, deploy it in your testing environment using the SSO plugin.]]>

</content>
</entry>
<entry>
<title>Java Dock with a better bouncing effect</title>
<link rel="alternate" type="text/html" href="http://weblogs.java.net/blog/elevy/archive/2007/07/java_dock_with.html" />
<modified>2007-08-20T16:21:13Z</modified>
<issued>2007-07-27T15:26:34Z</issued>
<id>tag:weblogs.java.net,2007:/blog/elevy/391.7930</id>
<created>2007-07-27T15:26:34Z</created>
<summary type="text/plain">In my last blog I explained how I built a Dock bar using the Timing Framework and the Glass pane. This one is a continuation, where I explain briefly a slight improvement on the bouncing effect. </summary>
<author>
<name>elevy</name>

<email>elie.levy@usa.net</email>
</author>
<dc:subject>Community: JavaDesktop</dc:subject>
<content type="text/html" mode="escaped" xml:lang="en" xml:base="http://weblogs.java.net/blog/elevy/">
<![CDATA[In my last blog I explained how I built a Dock bar using the Timing Framework and the Glass pane. This one is a continuation, where I explain briefly a slight improvement on the bouncing effect.<br><br>

You can try the new version with Java Web Start: <a href="http://www.zilonis.org/samples/dock/v0.9/dock-0.9.jnlp" alt="Java Web Start"><img src="http://www.zilonis.org/samples/demobutton.png"/></a> (again jdk 1.6+).<br><br>
Here is the <a href="http://www.zilonis.org/samples/dock/v0.9/dock-0.9-src.tar.gz">source code</a> under GPL.<br><br>

The improvement is to get the icons to bounce lower and lower after each cycle. I am pretty sure that I could have gone overboard and use some physics equations here. However, I followed the keep-it-simple principle.<br><br>

Instead of having one Animator object that repeats itself 6 times - 3 bounces - I created 3 different animator object. Each one goes from 0 to a different height. Then I used the Triggers available in the Timing Framework for starting the next animator after the current one is finished. I was surprised of the simplicity of the API.<br><br>

<pre class="java-code">

     TimingTrigger.addTrigger(animator[0], animator[1],
	                      TimingTriggerEvent.STOP);
     TimingTrigger.addTrigger(animator[1], animator[2],
			      TimingTriggerEvent.STOP);
     TimingTrigger.addTrigger(animator[2], animator[3],
                              TimingTriggerEvent.STOP);

</pre>

The other improvement I added was that after the bouncing animation is completed, I get the bar to animated into the standby state, instead of what I was doing before, which was to make the glass pane not visible. In this way it has a more smooth transition.<br><br>
<pre class="java-code">

    animator[3].addTarget(new TimingTarget() {
       public void begin() {}
       public void end() {
          glass.disolve();
       }
       public void repeat() {}
       public void timingEvent(float arg0) {}
    });
</pre>
<br><br>
Here you can see the disolve method:

<pre class="java-code">
   public void disolve() {
      if ((disolver == null) || (!disolver.isRunning())) {
	for (int i = 0; i < iconsOnBar.size(); ++i) {
	   IconOnBar iconOnBar = iconsOnBar.get(i);
	   iconOnBar.setMouseLocation(MOUSE_OUT);
	}
	disolver = PropertySetter.createAnimator(500, glass,
						"progress", 0f, 1f);
	disolver.setAcceleration(0.3f);
	disolver.setDeceleration(0.2f);
	disolver.addTarget(new TimingTarget() {
           public void begin() {}
           public void end() {
              glass.setVisible(false);
	   }
           public void repeat() {}
           public void timingEvent(float t) {}
	});
	disolver.start();
     }
   }
</pre>
<br><br>
We just make sure that there is no other disolver animation in the works, we update the state of all the icons to be "mouse out" and start the animation.<br><br>
]]>

</content>
</entry>
<entry>
<title>Java Dock (Launch Bar)</title>
<link rel="alternate" type="text/html" href="http://weblogs.java.net/blog/elevy/archive/2007/07/java_dock_launc.html" />
<modified>2007-07-25T20:02:13Z</modified>
<issued>2007-07-25T19:14:47Z</issued>
<id>tag:weblogs.java.net,2007:/blog/elevy/391.7870</id>
<created>2007-07-25T19:14:47Z</created>
<summary type="text/plain">With the timing framework and the glass panel, you can create almost any UI component. Offering cool and complex behaviors.
In this blog I present a version of a launch bar (Dock).</summary>
<author>
<name>elevy</name>

<email>elie.levy@usa.net</email>
</author>
<dc:subject>Community: JavaDesktop</dc:subject>
<content type="text/html" mode="escaped" xml:lang="en" xml:base="http://weblogs.java.net/blog/elevy/">
<![CDATA[With the timing framework and the glass panel, you can create almost any UI component. Offering cool and complex behaviors.<br><br>
In this blog I present a version of a launch bar (Dock).<br><br>

Here is a screen shot of it in action:<br><br>
<img src="http://www.zilonis.org/samples/dock/dock.jpg"/>
<br><br>

To give it justice, you should try running the demo with Java Web Start: <a href="http://www.zilonis.org/samples/dock/dock.jnlp" alt="Java Web Start"><img src="http://www.zilonis.org/samples/demobutton.png"/></a> (again jdk 1.6+).<br><br>

Here is the <a href="http://www.zilonis.org/samples/dock/dock-src.tar.gz">source code</a> under GPL.<br><br>

The component extends JPanel. That provides the foundation to paint the background and the icons. It has an inner class that is the responsible of the animations as the glass pane on the parent frame. Here is where all the magic happens.<br><br>

In the default conditions, when the user is not interacting with the component, the glass pane is not visible.<br><br>

The Dock component paints the background, which is a shape with rounded corners and using anti-aliasing creating a smooth effect on the edges. It was tricky to get the anti-aliasing working.<br><br>

You probably noticed that it uses a nice gradient.<br><br>

The gradient is cached in a buffered image with the width of the image and just a couple of pixels in the height. In this way we can recreate the entire gradient using less memory, and the painting is a lot faster.<br><br>

An important principle that I try to follow is to keep the code as simple as possible. Not introducing optimizations before I know that it is necessary. In this particular case, I followed the same philosophy, until I saw that the animation was not performing, when I started optimizing the code as I continue describing later in this blog.<br><br>

On top of the background, the component just paints the icons in the order they were added one next to each other.<br><br>

There is a mouse listener, that is waiting for the user to move the mouse over the component. At this time, we make the glass pane visible. And start animating!<br><br>

The glass panel is the one that paints the animations.<br><br>

The trick is to record for each icon it's current state, and the state  after the animation. In this way we can calculate its size and location based on how long the animation has progressed.<br><br>

Each icon has an Id which maps to its location in the Dock. When the mouse moves over the Dock, we determine the icon id that the mouse is over. We are going to call it mouseOverId.<br><br>

In the glass paint method we iterate over all the icons. To determine the size of each icon after the transition is completed, we use the Math.abs of the differece between the mouseOverId and the iconId. That gives us the distance between the mouse location and the icon being painted.<br><br>

One tricky thing was to determine the horizontal position of each icon. The solution was to make sure that the entire dock is always centered on the screen, and that the icons are centered in the dock. With that in mind, every time a icon expands or retracts the location of the dock is recalculated, and the icons location in the dock too. It actually works really well.<br><br>

Then we use the timing framework to animate the transition from the previous size to the next size. Using acceleration and deceleration allows the animation to look very smooth.<br><br>

There is another event that we listen. It is the mouse click. In that case we start another animation with the timing framework. This time to simulate a bouncing effect. For that we use a deceleration of 9.8 ~ 10 (gravity!) It looks very real. I just need to make the height of the bouncing lower and lower after each cycle<br><br>

Every icon is appended with the mirror image, using the swingx ReflectionRenderer.appendReflection(...)<br><br>

In the case of the bouncing, we create the reflection, and then append it at a distance proportional to the bouncing effect, to make it look more real.<br><br> 

When I finished codding it, it was working great in the demo app (similar to the one that you are seeing in the web start). However, as soon as I tried to integrate it with a more elaborate user interface with lots of windows and components in the background the animation started to be really slow.<br><br>

I discovered a couple of things that I was doing wrong. Hopefully my learning experience will help you not to make the same mistakes:<br><br>

1) Everytime you create a Graphics object, you need to call the dispose method as soon as you are done with it.<br><br>
2) When you don't need a BufferedImage anymore, call the flush method<br><br>
Those are 2 things that were sort of surprising to me, comming from the background of server side development, I did not expect that I had to free resources explicitly. I understand that working with graphics is resource intensive and it is extremely difficult, if not impossible to actually leave the gc to do it efficiently for you.<br><br>
3) Probably the most important thing, when you call repaint from the animation trigger, call it with the clip. Specially when you are working on a transparent glass pane, and there are a lot of components underneath it. The repaint with the clipping area is going to make sure that only the components that are in that area get repainted, not the entire application. Even if your paint method does not take advantage of the clip, you should still pass it by.]]>

</content>
</entry>
<entry>
<title>Fancy JTable Animations, or should I say &quot;Extreme&quot;</title>
<link rel="alternate" type="text/html" href="http://weblogs.java.net/blog/elevy/archive/2007/06/fancy_jtable_an.html" />
<modified>2007-06-18T20:03:16Z</modified>
<issued>2007-06-15T14:43:05Z</issued>
<id>tag:weblogs.java.net,2007:/blog/elevy/391.7653</id>
<created>2007-06-15T14:43:05Z</created>
<summary type="text/plain">If you went to the Extreme Makeovers JavaOne presentation, you probably enjoyed as much as I did the fancy table sorting animations that were presented. I got impatient waiting for them to release their code, and went to write my own.</summary>
<author>
<name>elevy</name>

<email>elie.levy@usa.net</email>
</author>
<dc:subject>Community: JavaDesktop</dc:subject>
<content type="text/html" mode="escaped" xml:lang="en" xml:base="http://weblogs.java.net/blog/elevy/">
<![CDATA[If you went to the Extreme Makeovers JavaOne 2007 presentation, you probably enjoyed as much as I did the fancy table sorting animations that were presented. I got impatient waiting for them to release their code, and went to write my own.<br><br>

I did not write it exactly as it is presented there, but I followed the same principles. The layout of the cells was done with the GroupLayout instead of the GridBagLayout. I didn't finished the "spanning" effect yet.

Here you can download the <a href="http://www.zilonis.org/samples/fancyTable/fancyTable-src.tar.gz">src</a> under GPL<br><br>
And for those of you that want to see it in action, you can try it now:
<a href="http://www.zilonis.org/samples/fancyTable/fancyTable.jnlp">
<img src="http://www.zilonis.org/samples/demobutton.png"/>
</a> (yes, sorry, you need jdk1.6)
<br><br>Try clicking the column headers to see how the table gets sorted. It is very fancy. After using it for a while, when I click on a table that does not have this effect I feel like it did not sorted the rows!.<br><br>
I can't wait to use this effect in one of my projects.]]>

</content>
</entry>
<entry>
<title>Zilonis Rules Engine at JavaOne</title>
<link rel="alternate" type="text/html" href="http://weblogs.java.net/blog/elevy/archive/2007/05/zilonis_rules_e.html" />
<modified>2007-05-25T21:19:31Z</modified>
<issued>2007-05-11T06:13:23Z</issued>
<id>tag:weblogs.java.net,2007:/blog/elevy/391.7361</id>
<created>2007-05-11T06:13:23Z</created>
<summary type="text/plain">The Zilonis Rules Engine is a Java Rules Engine that is Thread-Safe. It was presented yesterday at the JavaOne. The presentation discussed the challenges of implementing a Pricing Service in Retail, why using a Rules Engine would be a challenge, and the way Zilonis solves those scalability issues. We finished the session with the details of how it uses Read-Write Locks to achieve the multithreading capabilities with a high degree of concurrency. Also the Zilonis Analysis Tool (100% written with Swing) did its debut, and was used as a way to explain how the RETE algorithm works.</summary>
<author>
<name>elevy</name>

<email>elie.levy@usa.net</email>
</author>
<dc:subject>Community: Java Enterprise</dc:subject>
<content type="text/html" mode="escaped" xml:lang="en" xml:base="http://weblogs.java.net/blog/elevy/">
<![CDATA[The Zilonis Rules Engine is a Java Rules Engine that is Thread-Safe. It was presented yesterday at the JavaOne. The presentation discussed the challenges of implementing a Pricing Service in Retail, why using a Rules Engine would be a challenge, and the way Zilonis solves those scalability issues.<BR>

We finished the session with the details of how it uses Read-Write Locks to achieve the multithreading capabilities with a high degree of concurrency. Also the Zilonis Analysis Tool (100% written with Swing) did its debut, and was used as a way to explain how the RETE algorithm works.<BR><BR>

After cleaning up a little bit the Analysis Tool, I will be updating the <a href="http://www.zilonis.org">Zilonis Rules Engine</a> web site, and its repository releasing all the updates that I have been working on for quite a while.<BR><BR>

Some attendees approached me afterwards the presentation to tell me that they enjoyed the session. Thank you guys for your feedback. <BR><BR>

I am planning to write some blogs explaining some of the optimizations that I have included in the engine.<BR><BR>

Also, I will be describing in detail all the different parts of the implementation for those of you that were not able to make it to the presentation. Most likely this part will make it in the documentation at the Zilonis web site.]]>

</content>
</entry>
<entry>
<title>JavaOne: Using the Java Concurrency API and Deadlock Prevention in a RETE Rules Engine to Implement a Pricing Engine</title>
<link rel="alternate" type="text/html" href="http://weblogs.java.net/blog/elevy/archive/2007/05/javaone_using_t.html" />
<modified>2007-05-04T19:56:05Z</modified>
<issued>2007-05-04T19:56:00Z</issued>
<id>tag:weblogs.java.net,2007:/blog/elevy/391.7227</id>
<created>2007-05-04T19:56:00Z</created>
<summary type="text/plain">The JavaOne is comming next week. I will be presenting: Using the Java Concurrency API and Deadlock Prevention in a RETE Rules Engine to Implement a Pricing Engine.</summary>
<author>
<name>elevy</name>

<email>elie.levy@usa.net</email>
</author>
<dc:subject>JavaOne</dc:subject>
<content type="text/html" mode="escaped" xml:lang="en" xml:base="http://weblogs.java.net/blog/elevy/">
<![CDATA[The JavaOne conference is coming up next week. I am very excited specially because I will be presenting the BOF session: <b>Using the Java Concurrency API and Deadlock Prevention in a RETE Rules Engine to Implement a Pricing Engine.</b><BR>
<BR>

In the presentation I will be covering how the <a href="http://www.zilonis.org">Zilonis Rules Engine</a> manages concurrency, and how it can be used in an E-Commerce application for determining prices.<BR><BR>

I will demo the Zilonis Rules Analysis Tool. That tool is implemented using some of the Swing hacks available in the Aerith application, and the UI looks really cool!<BR><BR>

After the JavaOne I will posting some blogs about the engine, the tools, and the algorithm in general.<BR><BR>

Also I will update the <a href="http://www.zilonis.org">Zilonis</a> web site, with the latest version, more documentation, and some surprises that I have to keep for after the JavaOne.<BR><BR>

See you guys over there!]]>

</content>
</entry>
<entry>
<title>Multithreaded Hash Table</title>
<link rel="alternate" type="text/html" href="http://weblogs.java.net/blog/elevy/archive/2007/04/multithreaded_h_1.html" />
<modified>2007-04-17T16:50:03Z</modified>
<issued>2007-04-17T16:49:56Z</issued>
<id>tag:weblogs.java.net,2007:/blog/elevy/391.7072</id>
<created>2007-04-17T16:49:56Z</created>
<summary type="text/plain">If your application needs a &quot;Hash Table&quot; type of structure you have several options.

This blog present some of them, and discusses the pros and cons of each.</summary>
<author>
<name>elevy</name>

<email>elie.levy@usa.net</email>
</author>
<dc:subject>Community: Java Enterprise</dc:subject>
<content type="text/html" mode="escaped" xml:lang="en" xml:base="http://weblogs.java.net/blog/elevy/">
<![CDATA[<p>If your application needs a "Hash Table" type of structure you have several options.

<p>One is to use the java.util.Hashtable. In a multithreaded environment it would be safe, but not very efficient. If you have a couple of threads that want to read from the hash table, they will have to wait for each other. This wait is not necessary. There is no problem having multiple threads reading a structure.

<p>Another solution is to use the java.util.HashMap. Again in a multithreaded environment, you have to ensure that it is not modified concurrently or you can reach a critical memory problem, because it is not synchronized in any way.

<p>I thought that the solution was to use the static Collections.synchronizedMap method. I was expecting it to return a better implementation. But if you look at the source code you will realize that all they do in there is just a wrapper with a synchronized call on a mutex, which happens to be the same map, not allowing reads to occur concurrently.

<p>In the Jakarta commons project, there is an implementation that is called FastHashMap. This implementation has a property called fast. If fast is true, then the reads are non-synchronized, and the writes will perform the following steps:
<blockquote>
  <li> Clone the current structure
  <li> Perform the modification on the clone
  <li> Replace the existing structure with the modified clone
</blockquote>
<p>This implementation will work fine for the applications that write everything that they need into the structure at startup, and then only perform reads. You can see that writing into this structure is expensive. For the case where you need to do some writes every now and then, it can introduce a significant memory/performance issue.

<p>I wrote a very simple implementation. It starts creating a ReentrantReadWriteLock. Then every time we do a read operation we lock for reading. When we want to do an operation that modifies the structure, we call a write lock.

<p>Here an excerpt from the code:

<pre class="java-code">
public class FastSynchronizedMap implements Map,   
    Serializable {

    private final Map m;
    private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    .
    .
    .

    public V get(Object key) {
	lock.readLock().lock();
	V value = null;
	try {
	    value = m.get(key);
	} finally {
	    lock.readLock().unlock();
	}
	return value;
    }

    public V put(K key, V value) {
	lock.writeLock().lock();
	V v = null;
	try {
	    v = m.put(key, value);
	} finally {
	    lock.writeLock().lock();
	}
	return v;
    }

    .
    .
    .
}
</pre>

<p>Note that we do a try finally block, we want to guarantee that the lock is released no matter what problem is encountered in the block.

<p>This implementation works well when you have almost no write operations, and mostly read operations.

<p>When we want to insert into a hash table, we can see that depending on the hash code of the key that we are trying to insert, we will modify only one section of the structure. We could create a lock for each of the sections. In that way we can even have concurrent writes happening at the same time.

<p>An approach like that one is the one followed by the ConcurrentHashMap in the concurrency API. Looking at the implementation is interesting. 

<p>There is an inner class called Segment. The Segment is a "specialized version of hash tables". When you want to do an insert or read operation in the ConcurrentHashMap, it first finds the Segment where the key belongs too. After that it proceeds to do the operation on the respective Segment. 

<p>Interestingly enough, the Segment uses a ReentrantLock (actually it extends the ReentrantLock, I guess to save an instance). The lock is only used when writing to the table. When a read occurs no lock is performed. 

<p>If you are aware of the Java Memory Model you can be asking yourself what about the visibility? Can you get a partially built object when you are accessing it?

<p>Actually, the HashEntry that holds the value, and the value itself are defined as volatile. In that way you are guaranteed to read the value only when it has been fully initialized.

<p>And there is a check after performing the get to make sure a null reference is not being returned (this can happen if the compiler happens to reorder the operations). In the case of a null reference, it performs the lock to ensure that we have the proper visibility and then read the value.

<p>The choice of the structure to use, will depend on the scenario where you want to use it. Understanding how each of the structures work would be the first step into getting the right decision.

<p>If you are working on a web application, and you are loading some data into a hash table when the Servlet is initialized and then just reading the data from concurrent requests a HashMap should suffice. If you are just updating the table from time to time on a very controlled way, an implementation like the one I proposed above would do the job. If you are going to be updating the data often, a ConcurrentHashMap will actually give you better performance. However, if you want to iterate the data, and have guarantees that the data is correct, then may be a Hashtable is the answer.

<p>For those of you who are interested in concurrency, I would encourage you to look at the implementation of the ConcurrentHashMap. I would say that it is a nice source to learn from.]]>

</content>
</entry>
<entry>
<title>Why Java is going to succeed in the client side</title>
<link rel="alternate" type="text/html" href="http://weblogs.java.net/blog/elevy/archive/2007/02/why_java_is_goi.html" />
<modified>2007-02-21T14:15:15Z</modified>
<issued>2007-02-21T14:15:11Z</issued>
<id>tag:weblogs.java.net,2007:/blog/elevy/391.6641</id>
<created>2007-02-21T14:15:11Z</created>
<summary type="text/plain">When Sun Microsystems released Java back in 1995, the big promise was that it was going to bring profound changes in the way we interact with Web applications. The amazing Applets were going to allow us to write multiplatform rich client applications deployed over the web, that would lead to a reduction of total cost of ownership.</summary>
<author>
<name>elevy</name>

<email>elie.levy@usa.net</email>
</author>
<dc:subject>Community: JavaDesktop</dc:subject>
<content type="text/html" mode="escaped" xml:lang="en" xml:base="http://weblogs.java.net/blog/elevy/">
<![CDATA[<p>When Sun Microsystems released Java back in 1995, the big promise was that it was going to bring profound changes in the way we interact with Web applications. The amazing Applets were going to allow us to write multiplatform rich client applications deployed over the web, that would lead to a reduction of total cost of ownership.<br />
 <br />
There were several reasons why the Applets did not meet the expectations. I would have to say that it was in big part because of Microsoft’s strategy of not following the Java standards, and the creation of a proprietary JVM. However, I think that this is only part of the story. We should not forget the technology limitations of the time (CPU, Memory, and Bandwidth), and the lack of capabilities in the Abstract Windowing Toolkit (AWT) APIs.</p>

<p>Recently, I came to the realization that this is not over yet. <br />
The availability of bandwidth, CPU power, and cheap Memory, remove some of the limitations that we use to have. </p>

<p>It seems like the trend is on AJAX technologies. We are developing rich client applications using HTML, Java Script, and communicating to the server using XML. Those applications are running inside a browser... it sounds way too much like what the Applets of 1995-96 where promising back then. It feels like a Dejavu.</p>

<p>How these AJAX applications are being developed?</p>

<p>There are different AJAX frameworks or APIs. IMHO, they are all extremely difficult to program with, to debug, and to test.<br />
Some initiatives have realized those difficulties (i.e. Google Web Toolkit, and Echo), and to address those limitations they are producing a Java to AJAX compiler. You code with Java, and use a Swing-like API to create windows, components, and layouts. Then this gets compiled into JavaScript that ultimately is going to run in a browser..</p>

<p>If you take a deeper look into what those projects are doing, you are going to realize that they are reinventing the wheel. I believe that we already have that infrastructure in place, they are just trying to recreate it, and to make things worse, they are using the wrong technologies. I am a firm believer in simplicity. And for sure, compiling into JavaScript is not simple.</p>

<p>Java is here today, and it’s making that dream a reality. It is not applets anymore, but Java Web Start. It is not AWT but Swing. <br />
Java Web Start allows you to run/deploy any application from the Web. It literally installs the application in your client machine. This way, the next time you access the application it will run locally with almost no delay (it will just check for a newer version). </p>

<p>I used to think that the Java Client Applications had to have an odd looking UI. If you looked at the early days of Swing, or any of the Swing tutorials,  you will find the Metal Look and Feel. I thought as a developer that I was stuck with it, or the best option was to use the platform specific look and feels. BTW those never looked or behaved like the platform in place. </p>

<p>Later on, I found the Substance project. It seems like a huge amount of work, but still just out of the box the UIs would look with a very odd color combination selection. Well, I guess that you can customize the colors and make it look better, but I am referring to first impressions here.</p>

<p>I am pretty sure, that there is a lot of people who are still as wrong as I used to be. A deeper look into the APIs and the available Look and Feels allowed me to realize that the Java Rich Client Applications can have amazing UIs. </p>

<p>You just have to take a look at the the Aerith Java One demo to realize the things that can be accomplished with the Swing APIs, the Java 3D, and the Animation frameworks. It would be nice if someone would go ahead, and package that application into a more reusable framework. Perhaps, I will work on that some day.</p>

<p>There is the SwingX project which has a lot of interesting components. There is very little documentation out there, but the code is generally self explanatory. </p>

<p>I will write later on some of the components I have used (how I improved the Login framework to allow me to plug the “Waiting with Style in Swing” hack, but that's for another blog...).</p>

<p>I hope that the industry realizes everything I am presenting in this blog at some point in the near future, then AJAX will just be a transitory step in the evolution of the Web Applications and Java is going to rule in the client side.</p>]]>

</content>
</entry>

</feed>