Saturday, October 29, 2011

Fix for CSS opacity in Internet Explorer

How to set CSS opacity in Internet Explorer? It's easy for good browsers like Firefox, Google Chrome or new IE9:
opacity: 0.5;
For old Safary versions you probably also need
-khtml-opacity: 0.5;
For IE6, IE7 you can write
filter: alpha(opacity=50);
and for IE8
-ms-filter: "alpha(opacity=50)";
Saidly, but filter with opacity value in IE isn't enough. Element should be positioned, in order that opacity would work in IE. If the element doesn't have a position, there is a little trick in order to get it working. Add 'zoom: 1' to your CSS.
filter: alpha(opacity=50);        // IE6, IE7
-ms-filter: "alpha(opacity=50)"; // IE8
zoom: 1;
I have faced this problem with Schedule component in PrimeFaces. The button "today" is not disabled in IE7 for the current day although it has the jQuery UI style .ui-state-disabled. The fix would be
/* IE7 hack */
div.fc-button-today.ui-state-disabled {
    *zoom: 1;
}
* means the style is applied for IE7 only.

Friday, October 7, 2011

Draw masked images with Java 2D API and Jersey servlet

The task I had for one Struts web project was the dynamic image painting. You maybe know a small flag icon in MS Outlook which indicates message states. It can be red, green, etc. We needed the similar flag icon with configurable colors. The color is variable and thus unknown a priori - it can be set dynamically in backend and passed to front-end. I develop Struts web applications with JSF in mind. We can't use custom JSF resource handler in Struts, but we can use servlets. A HTTP servlet is able to catch GET requests causing by Struts or JSF image tags and render an image. All parameters should be passed in URL - they should be parts of URL. We need following parameters:
  • image format like "png" or "jpg"
  • file name of base image
  • file name of mask image
  • color (in HEX without leading "#" or "0x" signs)
An URL-example is
 
http://host:port/webappcontext/masked/png/flag/flag-mask/FF0000/mfile.imgdrawer
 
To save me pain for manually parsing of URL string and extraction of all parameters I have took Jersey - reference implementation for building RESTful Web services. Jersey's RESTful Web services are implemented as servlet which takes requests and does some actions according to URL structure. We just need to implement such actions. My action (and task) is image drawing / painting. That occurs by means of Java 2D API - a set of classes for advanced 2D graphics and imaging. Let me show the end result at first. Base image looks as follows


Mask image looks as follows

And now the magic is comming. I'm sending a GET request to draw a red flag (color FF0000) dynamically:


I'm sending a GET request to draw a green flag (color 00FF00):


Do you want to see a blue image? No problem, I can type as color 00ff.

You need four things to achieve that:

1. Dependencies to Jersey and Java 2D Graphics. Maven users can add these as follows:
<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-server</artifactId>
    <version>... last version ...</version>
</dependency>
<dependency>
    <groupId>com.sun.media</groupId>
    <artifactId>jai_codec</artifactId>
    <version>... last version ...</version>
</dependency>
<dependency>
    <groupId>com.sun.media</groupId>
    <artifactId>jai_imageio</artifactId>
    <version>... last version ...</version>
</dependency>
2. Two image files in the web application. I have placed them under webapp/resources/themes/app/images/ and they are called in my case flag.png and flag-mask.png.

3. Configuration for Jersey servlet in web.xml. My configuration is
<servlet>
    <servlet-name>imagedrawer</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>com.sun.jersey.config.property.packages</param-name>
        <param-value>ip.client.commons.web.servlet</param-value>
    </init-param>
</servlet>
<servlet-mapping>
    <servlet-name>imagedrawer</servlet-name>
    <url-pattern>*.imgdrawer</url-pattern>
</servlet-mapping>
Image-URL should be ended with imgdrawer to be able to handled by Jersey servlet. By the way, my FacesServlet is mapped to *.jsf and Struts ActionServlet to *.do. Init parameter com.sun.jersey.config.property.packages points to the Java package where the handler class is placed. Writing of handler class is the step 4.

4. Handler class which treats GET requests and draws / paints a new masked image by means of Java 2D API. The new image is a composition of two predefined images from the step 2. The mask gets painted and overlapped with the base image. The code is more or less documented, so that I omit any comments :-)
/**
 * Jersey annotated class for image drawing. Drawed images don't need to be cached server side because they are cached
 * proper on the client side. Set "expires" and "max-age" ensure client side caching.
 */
@Path("/")
@Produces("image/*")
@Singleton
public class ImageDrawer {
    @Context ServletContext context;

    /** directory for image files (can be done configurable if needed) */
    private String imageDir = "/resources/themes/app/images/";

    /**
     * Gets composed image consist of base and mask image.
     *
     * @param  format   format, e.g. "png", "jpg".
     * @param  basefile file name of base image without file extension
     * @param  maskfile file name of mask image without file extension
     * @param  hexcolor color in HEX without leading "#" or "0x" signs
     * @return Response new composed image
     * @throws WebApplicationException thrown exception, 404 or 500 status code.
    */
    @GET
    @Path("/masked/{format}/{basefile}/{maskfile}/{hexcolor}/{img}")
    public Response getImage(@PathParam("format") String format,
                             @PathParam("basefile") String basefile,
                             @PathParam("maskfile") String maskfile,
                             @PathParam("hexcolor") String hexcolor) {
        // check parameters
        if (format == null || basefile == null || maskfile == null || hexcolor == null) {
            throw new WebApplicationException(404);
        }

        // try to get images from web application
        InputStream is1 = context.getResourceAsStream(imageDir + basefile + "." + format);
        if (is1 == null) {
            throw new WebApplicationException(404);
        }

        InputStream is2 = context.getResourceAsStream(imageDir + maskfile + "." + format);
        if (is2 == null) {
            throw new WebApplicationException(404);
        }

        RenderedImage img1 = renderImage(is1);
        RenderedImage img2 = renderImage(is2);

        // convert HEX to RGB
        Color color = Color.decode("0x" + hexcolor);

        // draw the new image
        BufferedImage resImage = drawMaskedImage(img1, img2, color);

        byte[] resImageBytes = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        try {
            // use Apache IO
            ImageIO.write(resImage, format, baos);
            baos.flush();
            resImageBytes = baos.toByteArray();
        } catch (IOException e) {
            throw new WebApplicationException(500);
        } finally {
            try {
                baos.close();
            } catch (IOException e) {
                ;
            }
        }

        // cache in browser forever
        CacheControl cacheControl = new CacheControl();
        cacheControl.setMaxAge(Integer.MAX_VALUE);

        return Response.ok(resImageBytes, "image/" + format).cacheControl(cacheControl)
                       .expires(new Date(Long.MAX_VALUE)).build();
    }
 
    // Utilities (written not by me, copyright ©)

    private RenderedImage renderImage(InputStream in) {
        SeekableStream stream = createSeekableStream(in);
        boolean isImageIOAvailable = false;
        if (Thread.currentThread().getContextClassLoader().
            getResource("META-INF/services/javax.imageio.spi.ImageReaderSpi") != null) {
            isImageIOAvailable = true;
        }
        return JAI.create(isImageIOAvailable ? "ImageRead" : "stream", stream);
    }

    private BufferedImage drawMaskedImage(RenderedImage orig, RenderedImage mask, Color color) {
        BufferedImage overlay = manipulateImage(mask, null);
        return manipulateImage(orig, new ImageManipulator() {
            public void manipulate(final Graphics2D g2d) {
                float[] scaleFactors = new float[] {
                2f * (color.getRed() / 255f), 2f * (color.getGreen() / 255f),
                2f * (color.getBlue() / 255f), color.getAlpha() / 255f};
                float[] offsets = new float[] {0, 0, 0, 0};
                g2d.drawImage(overlay, new RescaleOp(scaleFactors, offsets, null), 0, 0);
            }
        });
    }

    private BufferedImage manipulateImage(RenderedImage orig, ImageManipulator manipulator) {
        BufferedImage image;
        boolean drawOriginal = false;
        ColorModel colorModel = orig.getColorModel();
        int colorSpaceType = colorModel.getColorSpace().getType();
        if (colorModel.getPixelSize() >= 4 && colorSpaceType != ColorSpace.TYPE_GRAY) {
            image = new RenderedImageAdapter(orig).getAsBufferedImage();
        } else if (colorSpaceType == ColorSpace.TYPE_GRAY) {
            image = new BufferedImage(orig.getWidth(), orig.getHeight(), BufferedImage.TYPE_INT_ARGB);
            drawOriginal = true;
        } else {
            image = new BufferedImage(orig.getWidth(), orig.getHeight(), BufferedImage.TYPE_BYTE_INDEXED);
            drawOriginal = true;
        }
   
        Graphics2D g2d = image.createGraphics();
        if (drawOriginal) {
            g2d.drawImage(new RenderedImageAdapter(orig).getAsBufferedImage(), 0, 0, null);
        }

        if (manipulator != null) {
            manipulator.manipulate(g2d);
        }
    
        return image;
    }

    private interface ImageManipulator {void manipulate(Graphics2D g2d);} 
}

Thursday, October 6, 2011

Facelets with HTML5

After reading this post on StackOverflow I have decided to use HTML5 DOCTYPE in JSF. Why to write long DOCTYPE with DTD, (X)HTML, Transitional, etc. like this one
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:h="http://java.sun.com/jsf/html"
      ... >
      
</html>
if we can write much simpler <!DOCTYPE html>?
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:h="http://java.sun.com/jsf/html"
      ... >
      
</html>
Using HTML5 DOCTYPE doesn't have side effects with Facelets parser and works fine in all browsers expect of IE6 which will render pages in quirks mode. IE6 usage is decreasing last years and it's not supported by many JSF libraries (like PrimeFaces) anymore. So, it doesn't hurt. If you are using HTML5 specific elements (e.g. file upload in PrimeFaces) and the browser doesn't support them, fallbacks will be applied. HTML5 specific elements will be gracefully degraded to HTML4.

One small issue I had during my changes of DOCTYPE was the entity &nbsp; which I sometimes use for non-breaking space. The Facelets parser says
 
The entity "nbsp" was referenced, but not declared.
 
The solution is to replace &nbsp; by the character reference &#160; Also other entities like &copy; should be replaced by character references. Apart from that JSF components which I use in my web apps are okey so far.

Summary: Using of <!DOCTYPE html> in Facelets is highly recommended. It's simple and future-proof.

Thursday, September 29, 2011

Atmosphere and JSF are good friends

Decision to write this long article was driven by PrimeFaces community. People have troubles to develop web applications with server push techniques. Even with Atmosphere - framework for building portable Comet and WebSocket based applications. Portable means it can run on Tomcat, JBoss, Jetty, GlassFish or any other application server which supports Servlet specification 2.5 or higher. If you want to be independent on underlying server and don't want to have headaches during implementation, use Atmosphere framework. It simplifies development and can be easy integrated into JSF or any other web frameworks (don't matter). I read Atmosphere doesn't play nice with JSF or similar. PrimeFaces had a special Athmosphere handler for JSF in 2.2.1. But that's all is not necessary. It doesn't matter what for a web framework you use - the intergration is the same. My intention is to show how to set up a bidirectional communication between client and server by using of Atmosphere. My open source project "Collaborative Online-Whiteboard" demonstrates that this approach works well for all three transport protocols - Long-Polling, Streaming and WebSocket. This is an academic web application built on top of the Raphaël / jQuery JavaScript libraries, Atmosphere framework and PrimeFaces. You can open two browser windows (browser should support WebSocket) and try to draw shapes, to input text, to paste image, icon, to remove, clone, move elements etc.


We need a little theory at first. For bidirectional communication we need to define a Topic at first (called sometimes "channel"). Users subscribe to the Topic and act as Subscribers to receive new data (called updates or messages as well). A subscriber acts at the same time as Publisher and can send data to all subscribers (broadcasting). Topic can be expressed by an unique URL - from the technical point of view. URL should be specified in such a manner that all bidirectional communication goes through AtmosphereServlet. JSF requests should go through FacesServlet. This is a very important decision and probably the reason why Atmosphere integration in various web frameworks like JSF and Struts sometimes fails. Bidirectional communication should be lightweight and doesn't run all JSF lifecycle phases! This can be achieved by proper servlet-mapping in web.xml. The picture below should demonstrate the architecture (example of my open source project).


For my use case I need messages in JSON format, but generally any data can be passed over bidirectional channel (XML, HTML). What is the Topic exactly? It depends on web application how you define the Topic. You can let user types it self (e.g. in chat applications) or make it predefined. In my application I equate Topic with Whiteboard-Id which is generated as UUID. Furthermore, I have introduced User-Id (= Publisher-Id) as well and called it Sender. Sender serves as identificator to filter Publisher out of all Subscribers. Publisher is normally not interested in self notification. I'm going to show using of Sender later. My Topic-URL follows this pattern
http://host:port/pubsub/{topic}/{sender}.topic
and looks like e.g. as
http://localhost:8080/pubsub/ea288b4c-f2d5-467f-8d6c-8d23d6ab5b11/e792f55e-2309-4770-9c48-de75354f395d.topic
I use Atmosphere with Jersey I think it's a better way than to write Atmosphere handlers or try to integrate MeteorServlet. Therefore, to start using of Atmosphere, you need a dependency to current Atmosphere and Jersey. Below is a dependency configuration for Maven users. Note: I cut logging off.
<dependency>
    <groupId>org.atmosphere</groupId>
    <artifactId>atmosphere-jersey</artifactId>
    <version>0.8-SNAPSHOT</version>
    <exclusions>
        <exclusion>
            <groupId>org.atmosphere</groupId>
            <artifactId>atmosphere-ping</artifactId>
        </exclusion>
        <exclusion>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.apache.geronimo.specs</groupId>
    <artifactId>geronimo-servlet_3.0_spec</artifactId>
    <version>1.0</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.6.2</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-nop</artifactId>
    <version>1.6.2</version>
</dependency>
The next step is to add Atmosphere-jQuery plugin to the client side. This plugin can be downloaded from the Atmosphere's homepage. After placing jquery.atmosphere.js under webapp/resources/js you can include it with
<h:outputScript library="js" name="jquery.atmosphere.js" target="head"/>
Yes, I know that Atmosphere can load jquery.atmosphere.js from JAR file in classpath, but a manual include is better in JSF environment. Now we are able to subscribe to the Topic and communicate with the server on the client side. There are two calls: jQuery.atmosphere.subscribe() and jQuery.atmosphere.response.push(). To establish a bidirectional communication, you need to call subscribe(). You have to call this method just once when page has been loaded. After that the method push() is responsible for data publushing to all subsribers. In the mentioned above web application I have an JavaScript object WhiteboardDesigner which encapsulates the Atmosphere's subscribe() call in the method subscribePubSub().
// Subscribes to bidirectional channel.
// This method should be called once the web-application is ready to use.
this.subscribePubSub = function() {
  jQuery.atmosphere.subscribe(
    this.pubSubUrl,
    this.pubSubCallback,
    jQuery.atmosphere.request = {
      transport: this.pubSubTransport,
      maxRequest: 100000000
    });
    
    this.connectedEndpoint = jQuery.atmosphere.response;
}
The first parameter this.pubSubUrl is the shown above Topic-URL. The second parameter this.pubSubCallback is the callback function. The third parameter is the request configuration which keeps among other things transport protocol defined in this.pubSubTransport: "long-polling", "streaming" or "websocket". The last line assigns jQuery.atmosphere.response the variable this.connectedEndpoint which allows us data publishing via push(). So now when new data being received, the callback function this.pubSubUrl gets called. Inside of the callback we can extract received data from response object. You can get the idea how to handle broadcasted data from my example:
// Callback method defined in the subscribePubSub() method.
// This method is always called when new data (updates) are available on server side.
this.pubSubCallback = function(response) {
  if (response.transport != 'polling' &&
      response.state != 'connected' &&
      response.state != 'closed' && response.status == 200) {
      var data = response.responseBody;
      if (data.length > 0) {
        // convert to JavaScript object
        var jsData = JSON.parse(data);

       // get broadcasted data
        var action = jsData.action;
        var sentProps = (jsData.element != null ? jsData.element.properties : null);
        switch (action) {
          case "create" :
            ...
            break;
          case "update" :
            ...
            break;
          case "remove" :
            ...
            break;
          ... 
          default :
        }
        ...
      }
  }
}
To publish data over the Topic-URL you need to call this.connectedEndpoint.push(). this.connectedEndpoint is a defined above shortcut for jQuery.atmosphere.response. I call it in my example for created whiteboard elements as follows (just an example):
// Send changes to server when a new image was created.
this.sendChanges({
  "action": "create",
  "element": {
    "type": "Image",
    "properties": {
      "uuid": ...,
      "x": ...,
      "y": ...,
      "url": ...,
      "width": ...,
      "height": ...
    }
  }
});

// Send any changes on client side to the server.
this.sendChanges = function(jsObject) {
  // set timestamp
  var curDate = new Date();
  jsObject.timestamp = curDate.getTime() + curDate.getTimezoneOffset() * 60000;

  // set user
  jsObject.user = this.user;

  // set whiteboard Id
  jsObject.whiteboardId = this.whiteboardId;

  var outgoingMessage = JSON.stringify(jsObject);

  // send changes to all subscribed clients
  this.connectedEndpoint.push(this.pubSubUrl, null, jQuery.atmosphere.request = {data: 'message=' + outgoingMessage});
}
Passed JavaScript object jsObject is converted to JSON via JSON.stringify(jsObject) befor it's sending to the server.

What is necessary on the server side? Calls jQuery.atmosphere.subscribe() and jQuery.atmosphere.response.push() have to be caught on the server side. I use Jersey and its annotations to catch GET- / POST-requests for the certain Topic-URL in a declarative way. For that are responsible annotations @GET, @POST und @PATH. I have developed the class WhiteboardPubSub to catch the Topic-URL by means of @Path("/pubsub/{topic}/{sender}"). With @GET annotated method subscribe() catches the call jQuery.atmosphere.subscribe(). This method tells Atmosphere to suspend the current request until an event occurs. Topic (= Broadcaster) is also created in this method. Topic-String is extracted by the annotation @PathParam from the Topic-URL. You can imagine a Broadcaster as a queue. As soon as a new message lands in the queue all subscribers get notified (browsers which are connected with Topic get this message). With @POST annotated method publish() catches the call jQuery.atmosphere.response.push(). Client's data will be processed there and broadcasted to all subscribed connections. This occurs independent from the underlying transport protocol.
@Path("/pubsub/{topic}/{sender}")
@Produces("text/html;charset=ISO-8859-1")
public class WhiteboardPubSub
{
  private @PathParam("topic") Broadcaster topic;

  @GET
  public SuspendResponse<String> subscribe() {
    return new SuspendResponse.SuspendResponseBuilder<String>().
               broadcaster(topic).outputComments(true).build();
  }

  @POST
  @Broadcast
  public String publish(@FormParam("message") String message,
                      @PathParam("sender") String sender,
                      @Context AtmosphereResource resource) {
    // find current sender in all suspended resources and
    // remove it from the notification
    Collection<AtmosphereResource<?, ?>> ars = topic.getAtmosphereResources();
    if (ars == null) {
      return "";
    }

    Set<AtmosphereResource<?, ?>> arsSubset = new HashSet<AtmosphereResource<?, ?>>();
    HttpServletRequest curReq = null;
    for (AtmosphereResource ar : ars) {
      Object req = ar.getRequest();
      if (req instanceof HttpServletRequest) {
        String pathInfo = ((HttpServletRequest)req).getPathInfo();
        String resSender = pathInfo.substring(pathInfo.lastIndexOf('/') + 1);
        if (!sender.equals(resSender)) {
          arsSubset.add(ar);
        } else {
          curReq = (HttpServletRequest) req;
        }
      }
    }

    if (curReq == null) {
      curReq = (HttpServletRequest) resource.getRequest();
    }

    // process current message (JSON) and create a new one (JSON) for subscribed clients
    String newMessage = WhiteboardUtils.updateWhiteboardFromJson(curReq, message);

    // broadcast subscribed clients except sender
    topic.broadcast(newMessage, arsSubset);

    return "";
  }
}
In my case the method publish() looks for sender (= publisher of this message) among all subscribers and removes it from the notification. It looks a little bit complicated. In simple case you can write
@POST
@Broadcast
public Broadcastable publish(@FormParam("message") String message) {
  return new Broadcastable(message, "", topic);
}
and that's all! The last step is the mentioned above configuration in web.xml. *.jsf requests should be mapped to FacesServlet and *.topic requests to AtmosphereServlet. AtmosphereServlet can be configured comprehensively. Important configuration parameter is com.sun.jersey.config.property.packages. With this parameter you can tell Jersey where the annotated class is located (in my case WhiteboardPubSub). In my example Jersey scans the directory com.googlecode.whiteboard.pubsub.
<!-- Faces Servlet -->
<servlet>
  <servlet-name>Faces Servlet</servlet-name>
  <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
  <servlet-name>Faces Servlet</servlet-name>
  <url-pattern>*.jsf</url-pattern>
</servlet-mapping>

<!-- Atmosphere Servlet -->
<servlet>
  <description>AtmosphereServlet</description>
  <servlet-name>AtmosphereServlet</servlet-name>
  <servlet-class>org.atmosphere.cpr.AtmosphereServlet</servlet-class>
  <init-param>
    <param-name>com.sun.jersey.config.property.resourceConfigClass</param-name>
    <param-value>com.sun.jersey.api.core.PackagesResourceConfig</param-value>
  </init-param>
  <init-param>
    <param-name>com.sun.jersey.config.property.packages</param-name>
    <param-value>com.googlecode.whiteboard.pubsub</param-value>
  </init-param>
  <init-param>
    <param-name>org.atmosphere.useWebSocket</param-name>
    <param-value>true</param-value>
  </init-param>
  <init-param>
    <param-name>org.atmosphere.useNative</param-name>
    <param-value>true</param-value>
  </init-param>
  <init-param>
    <param-name>org.atmosphere.cpr.WebSocketProcessor</param-name>
    <param-value>org.atmosphere.cpr.HttpServletRequestWebSocketProcessor</param-value>
  </init-param>
  <init-param>
    <param-name>org.atmosphere.cpr.broadcastFilterClasses</param-name>
    <param-value>org.atmosphere.client.JavascriptClientFilter</param-value>
  </init-param>
  <load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
  <servlet-name>AtmosphereServlet</servlet-name>
  <url-pattern>*.topic</url-pattern>
</servlet-mapping>
Please check Atmosphere documentation and showcases for more information.

Summary: We have seen that few things are needed to establish the bidirectional comminication: Topic-URL, callback function for data receiving, subsribe() und push() methods on client side, an Jersey class on server side and configuration in web.xml to bind all parts together. JSF- und Atmosphere-requests should be treated separately. You maybe ask "but what is about the case if I need to access JSF stuff in Atmosphere-request?" For a simple case you can use this technique to access managed beans. If you want to have a fully access to all JSF stuff you should use this technique which allows accessing FacesContext somewhere from the outside.

P.S. Good news. Atmosphere's lead Jeanfrancois Arcand announced his intention to pursue the work on Atmosphere. He can invest more time now in his great framework.

Tuesday, September 27, 2011

Quick practical introduction to JSDoc (JsDoc Toolkit)

Documentation of JavaScript code is a very important part of software development and helps front-end developers to understand code of third-party libraries. There are really well documented libraries. One of them is Mojarra JavaScript documentation. Other libraries (and that's a common case) don't have JavaScript documentation at all or don't cover all their features, so that features stay undocumented (I hope PrimeFaces guys read this blog post :-)).

JSDoc is documentation generated for JavaScript code by means of JsDoc Toolkit. Documentation is not restricted to multi-page HTML, other formats are possible too. Look-&-feel can be fully customized by templates. In this quick introduction I use built-in templates and would like to show generated JSDoc on example of my open source project "Collaborative Online-Whiteboard". I use following tags in my example:

@fileOverview
This tag allows you to provide documentation for an entire file. It's often used with other tags @author and @version.
@class
This tag also allows you to add a description of the JavaScript class (if you write your code in OOP style).
@param
This tag allows you to document information about the parameters to a function, method or class (constructor)
@public
This tag allows you to document public methods or variables.
@private
This tag allows you to document private methods or variables.
@type
This tag allows you to document the type of value a variable refers to, or the type of value returned by a function.
@returns
This tag documents the value returned by a function or method. You can specify a type of the returned value in curly braces {...}.
@link
This tag allows you to create a HTML link to some other documented symbol (similar link in JavaDoc).

Let's document the JavaScript code! I have a class called WhiteboardDesigner which expects 5 parameters (to be passed to constructor) and has many public / private methods. The documented class looks like
/**
* @fileOverview
* @author <a href="mailto:ovaraksin@googlemail.com">Oleg Varaksin</a>
* @version 0.2
*/

/**
* Whiteboard designer class for element drawing.
* @class
* @param witeboardConfig whiteboard's configuration {@link WhiteboardConfig}
* @param whiteboardId whiteboard's id
* @param user user (user name) working with this whiteboard
* @param pubSubUrl URL for bidirectional communication
* @param pubSubTransport transport protocol "long-polling" | "streaming" | "websocket"
*/
WhiteboardDesigner = function(witeboardConfig, whiteboardId, user, pubSubUrl, pubSubTransport) {
    /**
     * Whiteboard's configuration {@link WhiteboardConfig}.
     * @public
     * @type WhiteboardConfig
     */
    this.config = witeboardConfig;
    /**
     * Whiteboard's id.
     * @public
     * @type uuid
     */    
    this.whiteboardId = whiteboardId;
    /**
     * User which works with this whiteboard.
     * @public
     * @type string
     */    
    this.user = user;
    /**
     * URL for bidirectional communication.
     * @public
     * @type string
     */    
    this.pubSubUrl = pubSubUrl;
    /**
     * Transport protocol "long-polling" | "streaming" | "websocket".
     * @public
     * @type string
     */    
    this.pubSubTransport = pubSubTransport;
    /**
     * Logging flag, true - logging is visible, false - otherwise.
     * @public
     * @type boolean
     */    
    this.logging = false;
    /**
     * Raphael's canvas.
     * @private
     * @type Raphael's paper
     */    
    var paper = Raphael(this.config.ids.whiteboard, whiteboard.width(), whiteboard.height());
    
    ...
    
    /** Draws image with default properties.
    * @public
    * @param inputUrl image URL.
    * @param width image width.
    * @param height image height.
    */    
    this.drawImage = function(inputUrl, width, height) {
        ...
    }
    
    /** Gets currently selected whiteboard element.
    * @public
    * @returns {Raphael's element} currently selected element
    */
    this.getSelectedObject = function() {
        ...
    }

    ...

    /** Outputs debug messages.
    * @private
    * @param msg message
    */
    var logDebug = function(msg) {
        ...
    }
}
How to generate a documentation now? I would like to show a quick and simple way. Download JsDoc Toolkit zip file at first. Extract it and go to the directory jsdoc-toolkit. Create there a new folder with any name which will contain your documented JavaScript files. I have created a folder called "whiteboard". Copy all JavaScript files into this folder. Open a DOS console or Linux terminal or whatever at jsdoc-toolkit and type
 
java -jar jsrun.jar app/run.js -a -p -t=templates/jsdoc ./<yours folder name>/*.*
 
In my case it's
 
java -jar jsrun.jar app/run.js -a -p -t=templates/jsdoc ./whiteboard/*.*
 
JsDoc Toolkit runs via the Mozilla JavaScript Engine "Rhino." Rhino is wrapped in a runner application called jsrun. Option -a says: include all functions, even undocumented ones. Option -p says: include symbols tagged as private, underscored and inner symbols (such symbols are not included per default). Option -t is required und used to point to templates for output formatting. Using of default build-in templates which are located under templates/jsdoc is satisfying in most cases.

After script running you will find generated files in the out folder. Entry file is index.html. Its location is .../jsdoc-toolkit/out/index.html You can see online here how does it look for my project. Have much fun!