Sun Java Solaris Communities My SDN Account
 
Article

Graph Servlet: A Dynamic Graph Generator for Portal Channels

 
By Paul Lovvik and Beverly Sum, with contributions from Marina Sum, October 31, 2003  
With the Java Servlet API, you can build a variety of simple, practical utilities for portals. As an example, Graph Servlet dynamically graphs data in a custom channel of Sun ONE Portal Server 6.

This document describes the architecture of Graph Servlet, with emphasis on its components and implementation. Also discussed are installation and deployment procedures, pros and cons of the key aspects of the implementation, and troubleshooting tips.
Contents
 
Architecture
Key Components
Installation and Deployment
Dynamic Images
Caching
Pros and Cons of Architecture
Troubleshooting
References
About the Authors
 
Architecture

This program contains three key components:

  • A Singleton structure class that resides in the system class loader (java.awt.ClassLoader) and that shares data between Sun ONE Portal Server and Graph Servlet

  • Pages that are created with JavaServerPages (JSP) technology in both HTML and Java technology and that generate the channel content

  • A Java servlet that dynamically renders a pie graph or bar graph

Figure 1 illustrates the request flow in the architecture.

 
Figure 1: Request Flow
Figure 1: Request Flow

Figure 2 shows the hierarchy of the architecture structure.

 
Figure 2: Architectural Structure
Figure 2: Architectural Structure

Users communicate with the channel, which contains a controller. The views incorporate the dynamic images with the standard HTML <img> tag. This design circumvents two major hurdles, as follows:

  • Sun ONE Portal Server cannot aggregate Java servlets.

  • JSP pages cannot generate dynamic images, which are a key requirement for a graphing utility. (The alternative of using HTML is only viable to an extent.) Time-sheet data, for example, change constantly and require continual updates.
Key Components
This section describes the key components of Graph Servlet--a combination of JSP pages and Java classes.
 
controller.jsp
controller.jsp, the controller, collects information from the request, the channel's class (JSPProvider), and the user profile in which the task data are stored. Afterwards, controller.jsp processes, sorts, and dispatches the data for graphing. Specifically, controller.jsp performs the following tasks:

  1. Requests the channel name, the activities to be graphed, and the dimensions of the images. See Code Examples 1-3.
 
Code Example 1: Referencing JSPProvider
JSPProvider provider =
(JSPProvider)pageContext.getAttribute "JSPProvider");
ProviderContext providerContext = provider.getProviderContext();
 
Code Example 2: Retrieving the Collection Property from User Profile
newNamesAndTimes =
providerContext.getCollectionProperty(channelName, "activities");
 
Code Example 3: Retrieving a Parameter from HttpServletRequest
String activityName = (String)request.getParameter(channelName + "-activity");
 
Note -- Sun ONE Portal Server 6 sends the request parameters for a channel name to all the channels that are on display. Hence, be sure to adopt a naming convention of channel_name-parameter_name, for example, ActivityChannel-activity, so that each request applies to a single channel only, not to multiple channels.
 
  1. Places the data of the activities into HashMap for editing.

  2. Places the data into the ActivityElement array for sorting and color assignment.

  3. Puts the data in the session and in Singleton to make them available for access.

  4. Adds or deletes activities, as appropriate.
See Code Examples 4 and 5.
 
Code Example 4: Putting the Data in HttpSession
session = request.getSession(true);
session.putValue("timesheet",elements);
 
Code Example 5: Putting the Data in Singleton
DataFactory.setData(request, elements);
 
Finally, according to user input, controller.jsp determines whether to display the main view or the graph view and inserts the <img> tag into the resulting HTML content.
 
main.jsp

main.jsp displays data, that is, it outputs the data that were processed and sorted by controller.jsp, as follows:

  • Activity names and durations in table format
  • Checkboxes for selection and deletion of activities
  • A form for inputting or editing the data for the current activities
  • Thumbnails for the bar or pie graphs; see Code Example 6
Code Sample 6: Adding a Thumbnail for the Pie Graph
<a href="<dtpc:getDesktopURL/>?<%=channelName%>-
view=graph.jsp&<%=channelName%>-style=Pie"><img
src="/graph/graphController?width=100&height=100&style=Pie"></a>
 
  • Two buttons, labeled Add and Delete
  • An HTML link labeled Refresh for reloading the main view
 
graph.jsp

graph.jsp performs the following tasks:

  1. Determines whether to display the bar or pie graph according to user input.

  2. Converts color objects to Red-Green-Blue (RGB) hex strings for HTML presentation.

  3. Displays the following:

    • A larger view of the graph according to user input (a click on either of the two graph thumbnails on main.jsp)

    • A color-coded table of the activities

    • An HTML link labeled Back to Main Page

GraphServlet

GraphServlet, a Java servlet, extends the HttpServlet class and performs the following tasks:

  1. Obtains from the URL, which is generated by controller.jsp, the parameters for drawing the graphs: height, width, and style

  2. Creates a frame for the graph.

  3. Obtains the pertinent data (ActivityElement array) from DataFactory and sends them to either the Pie or Bar object.

  4. Encodes the graph image as a GIF file.

  5. Deletes the Graphics and Frame objects.
Code Example 7: Collecting the Data for the Appearance of the Graph from HttpServletRequest
public void doGet(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException{
    ServletOutputStream out = res.getOutputStream();
    String width = req.getParameter("width");
    String height = req.getParameter("height");
    String style = req.getParameter("style");
...}
 
Note -- On UNIX systems, you can start the Web container from any shell of your choice, so be sure to grant display access to users. See also the section, Troubleshooting. Alternatively, if the server on which your portal is running is executing in headless mode, you can start the Web container with the Xvfb server software.
 
Pie Object

The Pie object passes the information from controller.jsp to DataFactory and then to GraphServlet to render a pie graph that represents the durations of the activities. The Pie object performs two major tasks:

  1. Calculates the durations of the activities.

  2. By means of float conversions and divisions, scales the durations to add up to 360 degrees. Specifically, the Pie object does the following:

    1. Converts the durations to integers.

    2. Fixes integer rounding errors, if any, with a method.

    3. Fills the arcs with fixed degrees and different colors, the latter with the Graphics method in the Abstract Windowing Toolkit (java.awt.*).

    4. Scales and centers the pie graph.

Bar Object

Similarly, the Bar object passes information from controller.jsp to DataFactory and then to GraphServlet to render a bar graph that represents the durations of the activities. It performs two major tasks:

  1. Determines the activity with the longest duration.

  2. Scales the bars to fit within the height and width of the graph.

  3. Fills the rectangles to render the bars of different colors with the Graphics method in java.awt.* and then creates the bar graph.
DataFactory Object
The DataFactory object, which resides in the system class loader, serves as a liaison for data that are passed between Sun ONE Portal Server and GraphServlet. True to the Singleton design, DataFactory uses a method (setData) to enable data storage in HashMap, to which Sun ONE Identity Server's SSOToken can later refer in the getData method. That way, users have exclusive access to and unique ID matches with their data.

To match multiple pieces of data with a user, associate a container that holds all the data with the user in DataFactory.

Each time DataFactory receives new data, it checks whether the data ID already exists in the map; if not, it adds an entry. Since each user of Sun ONE Identity Server has a unique ID, users are exclusively matched with their data.

See Code Example 8.
 
Code Example 8: Setting Data in the System Class Loader
public static void setData(HttpServletRequest r, Object obj){
        String uniqueID = getUniqueID(r);
		
        if(h.get(uniqueID) == null){
            try{
                SSOTokenManager tokenManager =
SSOTokenManager.getInstance();
                SSOToken s = tokenManager.createSSOToken(r);
/*
 * If the user is logging in for the first time,
 * DataFactory adds a token listener to watch for session
 * logouts and timeouts.
 */
               s.addSSOTokenListener(factory);
           }catch(SSOException e){
               d.error("setData method could not get
SSOTokenManager", e);
            }
        }
        h.put(uniqueID, obj);
    }
 
If a large number of users log in simultaneously, the performance of Sun ONE Portal Server may decline. To head off this issue, practice clean housekeeping by adding an event listener to SSOToken to watch for session changes (user logouts and session timeouts) and then delete the associated data from HashMap. See Code Example 9.
 
Code Example 9: Deleting Data from HashMap to Optimize Performance
public void ssoTokenChanged(SSOTokenEvent evt) {
    SSOToken token = evt.getToken();
    h.remove(token.getTokenID().toString());
}
 

The process flow is as follows:

  1. The content returned from controller.jsp includes the image tags.

  2. controller.jsp calls the data in the user profile and sends them to the DataFactory object.

  3. The browser parses the tag data and requests the image from GraphServlet, that is, Sun ONE Portal Server calls controller.jsp and then the browser requests the image from GraphServlet.
Sorter Object
The Sorter object sorts object arrays in alphabetical order with the mergesort method.
 
ActivityElementStringComparator Object
The ActivityElementStringComparator object compares strings within an object array of ActivityElements.
 
NamedColors Object
The NamedColors object is created from the /usr/openwin/lib/rgb.txt file. NamedColors stores numerous colors by name to enhance the readability of the graphing code and the graph display. Those colors far outnumber the ones in java.awt.Color, according many color choices for the graph.

NamedColors provides two schemes for acquiring colors: static final class variables and a static lookup method.
 
ActivityElement Object

The ActivityElement object serves as a storage location for the data and a color for a single activity. Each instance of ActivityElement contains mainly the set and get methods. ActivityElement performs only minimal data processing, as follows:

  • The setDuration method takes either an integer or a string.

  • controller.jsp passes an array of the ActivityElement instance to DataFactory, to GraphServlet, and finally to either Pie or Bar for graphing and output.
Installation and Deployment
First, download the zipped archive and place it in a temporary directory, for example, /tmp.
 
Installation

To install, do the following:

  1. Unzip the zipped archive.

  2. Change directory to graphing.

  3. Import the portal archive (PAR) file by typing this command:
    % par import -p password -r uid -- TimeTracker.par dn channel

    where:

    • password is the password for logging in to your portal.
    • uid is the distinguished name of the administrator.
    • dn is the distinguished name of the target for the channel.
Table 1 explains how to derive the values for uid and dn and provides examples.

Table 1: Distinguished Names
  
Name Type
    
Value
    
Example
 
  
uid
    
The
com.sun.identity.authentication
.super.user
setting in the
install_dir/SUNWam/lib/
AMConfig.properties file
    
Sun ONE Portal Server 6.0:
uid=amadmin,ou=people,o=sun.com,o=isp

Sun ONE Portal Server 6.1:
uid=amadmin,ou=people,dc=sun,dc=com
 
  
dn
    
The com.iplanet.am.defaultOrg
setting in the install_dir/SUNWam/lib/
AMConfig.properties file
    
Sun ONE Portal Server 6.0:
o=sun.com,o=isp

Sun ONE Portal Server 6.1:
dc=sun,dc=com
 
 
Note -- The user interface described in the following steps applies to Sun ONE Portal Server 6.0. The UI varies slightly in Sun ONE Portal Server 6.1 and 6.2.
  1. Add the new channel to the portal desktop by following these steps:

    1. Log in to the Administration Console.

    2. Select the organization on the left panel, followed by Show: Services, and then click the arrow to the left of Desktop under Portal Server Configuration.

    3. Click Channel and Container Management under Display Profile on the right panel.

    4. In the scrolling list under Container Channels, click the container you would like to designate for the new channel.

      To place the new channel on the first tab of the sample desktop, select MyFrontPageTabPanelContainer.

    5. In the scrolling list for Existing Channels, select TimeTrackerChannel.

    6. Click Add to the left of the Available and Visible scrolling list.

    7. Click Save under Channel Management.

    8. Log out of the Administration Console.

  2. Add the DataFactory classes to the system class loader. Do the following:

    1. Create a directory for the DataFactory classes:

      % mkdir /opt/DataFactory

    2. Copy the JAR file to that directory:

      % cp DataFactory.jar /opt/DataFactory

    3. Add the JAR file to the CLASSPATH attribute of the system class loader.

      If your portal is running on Sun ONE Web Server, append the jvm.classpath setting in the jvm12.conf file at install_dir/SUNWam/servers/https-hostname/config with this string:

      :/opt/DataFactory/DataFactory.jar
 
Deployment
Graph Servlet resides in the graph.war file. Deploy the Web application for Graph Servlet as for any other Web archive (WAR) file. Depending on your Web container, the procedure varies. If you are using Sun ONE Web Server and Sun ONE Portal Server 6.0, run the wdeploy command, all in one line, like this:

% wdeploy deploy -u /graph -i instance_name -v virtual_server_name
-d /opt/GraphServlet graph.war


For example:

% /opt/SUNWam/servers/bin/https/httpadmin/bin/wdeploy deploy
-u /graph -i gravitywell.sun.com -v https-gravitywell.sun.com
-d /opt/GraphServlet graph.war


Finally, restart Sun ONE Portal Server. Ensure that the $DISPLAY environment setting is correct and that proper access permissions are available in the shell from which the portal is started.
 
Dynamic Images
Graph Servlet demonstrates the use of dynamic images within Sun ONE Portal Server. Upon receiving a user request, such as one for a new graph or with revised data, Sun ONE Portal Server sends the request to controller.jsp. If the request is to change the style of the graph, controller.jsp creates a style parameter in the URL for main.jsp and graph.jsp. See Code Example 10.
 
Code Example 10: Creating a Style Parameter
<a href="<dtpc:getDesktopURL/>?<%=channelName%>-
view=graph.jsp&<%=channelName%>-style=Pie">
 

Next comes this process:

  1. main.jsp and graph.jsp determine which graph style the user has requested, for example, an enlargement or a new activity.

  2. main.jsp and graph.jsp call the setData method in DataFactory and dispatch the request and the data to the system class loader, to be accessed later by DataFactory.

  3. DataFactory pairs the request's SSOToken ID with the data and processes the data as a comprehensible object.

  4. GraphServlet calls either Pie or Bar to render the graph.
The data passed to Graph Servlet are visible in the URL and include the key parameters, such as the width, height, and style of the graph.  
Note -- Parameters with null values cause errors. Be sure to set default values for the parameters.
 
Caching
As a scheme for improving performance, caching stores the most recently generated data and uses them on subsequent requests.

Graph Servlet supports caching to ensure that the channel's view stays constant even after a refresh or after a user's return from browsing other content by clicking a tab.
 
Pros and Cons of Architecture
Software solutions abound for a variety of tasks. A major rule of thumb for determining which solution to adopt is the "cleanness" of the code--the cleaner and more concise the program, the more robust the solution. For example, Graph Servlet uses only one servlet to generate the pie and bar graphs. Using two servlets would complicate the deployment process and incur a higher implementation cost.

Here is an analysis of the pros and cons of the design aspects of Graph Servlet:
  • JSPProvider versus other content providers

    JSPProvider creates the content for desktop channels with JSP pages. It boasts a more efficient development cycle because of two major advantages it commands over other content providers, such as ProfileProviderAdapter:

    • JSPProvider offers a standard scheme that separates logic from presentation: The JSP page file contains the presentation; most of the logic resides in Java code in separate classes.

    • JSPProvider can update a JSP page without necessitating a restart of the Web server.

  • Data in system class loader versus data in session

    You cannot access the portal's session object, and separate Web applications cannot share the same session. Recall that to share data across Web applications, you can store them in a Singleton class loaded from the system class loader.

  • Deep integration versus shallow integration

    In an architecture that adopts shallow integration, clicking a link inside a channel opens a new browser window for the target location.

    Graph Servlet adopts deep integration, whereby the program rests in its own channel. Consequently, when you click a link in the channel for Graph Servlet, the view changes within that channel, resulting in a saving of screen real estate.

    Deep integration requires a more complicated implementation. However, its many advantages, including the reduction of the number of popup windows and a more stable integration into the Secure Remote Access add-on product, all accessible on the same desktop, more than justify the extra effort. For most Sun ONE Portal Server channels, deep integration offers a more robust user interface.

  • Data sharing through URLs versus other schemes

    Because it cannot access the session data, GraphServlet picks up that information by using parameters in the HttpServletRequest object. Besides being a simple solution for data sharing, this scheme also reveals whether the data are being correctly passed from one component to another--a most useful clue for debugging.

    A disadvantage with this scheme is that users can tamper with the parameters in the URL, which are plainly visible on the browser.
 
Troubleshooting

You can find clues for troubleshooting in the system console or the Web server log. Alternatively, initiate the debug process by doing the following:

  • Become root, and then edit the /opt/SUNWam/lib/AMConfig.properties file.

  • Enable debugging by setting it to the level of your choice: error, warning, message, or all.

  • Insert debug statements from the Debug class in the com.iplanet.am.util.* package. Save your changes.
Table 2 describes the common error conditions and the suggestions for resolving them.

Table 2: Error Conditions and Troubleshooting Tips
  
Error
    
Troubleshooting Tips
 
  
The images are not displayed.
    
  • See the Web server log for awt errors. If they are present, the DISPLAY environment variable setting is likely incorrect. Find out whether DISPLAY is set in the same shell or terminal in which you restarted the Web server. If not, at the prompt of a shell or terminal in which you launched the Web server, type:
    % setenv DISPLAY hostname:0.0

  • The X server default grants permissions for displaying images to the login user only. Ensure that root has that permission by typing at the prompt of a shell or terminal of your host:
    % xhost +hostname

    To test, type:
    % xterm

    If an external terminal is displayed, the permissions are correct.

  • Verify that the URL and the images are correct. To test the images, open a new browser window and click the images there, not through Sun ONE Portal Server.
     
      
    The graph view corrupts the other portal channels.
        
    You may have specified no channel names in the URL, in which case Sun ONE Portal Server 6 sends the request to all the channels. When defining the variables for the URL (for example, the view of your choice), ensure that the channel name is fully qualified. Here's an example of a correct URL:

    <a href="<dtpc:getDesktopURL/>?<%=channelName%>-
    view=graph.jsp">exampleLink</a>

     
      
    No data are displayed.
        
    Verify that the code in the JSP pages sets the data into the DataFactory object.
     
      
    graph.jsp cannot access the required data.
        
    Ensure that the class files are being deployed in the correct locations and that the Web application is pointing to the correct targets.
     
     
    References
     
    About the Authors
    Paul Lovvik, who has been with Sun for six years, is lead engineer in the ISV adoption group for Sun ONE Portal Server in Market Development Engineering. Over the past two years, Paul and his team have engineered approximately 40 integrations of ISV solutions into Sun ONE Portal Server.

    Beverly Sum, a high school student keenly interested in software programming, contracted for Sun in the summer of 2003. She developed Graph Servlet under Paul's leadership and guidance.

    Marina Sum is a staff writer for Sun Developer Network. She has been writing for Sun for 14 years, mostly in the technical arena.

    Oracle is reviewing the Sun product roadmap and will provide guidance to customers in accordance with Oracle's standard product communication policies. Any resulting features and timing of release of such features as determined by Oracle's review of roadmaps, are at the sole discretion of Oracle. All product roadmap information, whether communicated by Sun Microsystems or by Oracle, does not represent a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions. It is intended for information purposes only, and may not be incorporated into any contract.