Clipping Programmer Guide

Embed Size (px)

Citation preview

  • 8/12/2019 Clipping Programmer Guide

    1/54

    Kap

    owMashupSe

    rver6.4

    ClippingProgrammers Guide

  • 8/12/2019 Clipping Programmer Guide

    2/54

  • 8/12/2019 Clipping Programmer Guide

    3/54

    ClippingProgrammers Guide

  • 8/12/2019 Clipping Programmer Guide

    4/54

    Copyright 1999-2008 Kapow Technologies

    http://www.kapowtech.com

    All rights reserved.

  • 8/12/2019 Clipping Programmer Guide

    5/54

  • 8/12/2019 Clipping Programmer Guide

    6/54

    iv CLIPPING

    Example .......................................................................................22User Message Localization Provider ..................................................... 22

    Purpose and Use............................................................................ 22Clip Configuration File Specification ..................................................23Implementation ............................................................................. 25Example .......................................................................................26

    Distribution Policy Provider.................................................................26Purpose and Use............................................................................ 26Clip Configuration File Specification ..................................................28Implementation ............................................................................. 28

    Example .......................................................................................29

    HANDLERS ............................................................................................ 34Additional Output Objects Handler.......................................................34

    Purpose and Use............................................................................ 34Clip Configuration File Specification ..................................................35Implementation ............................................................................. 35Example .......................................................................................36

    Error Handler ...................................................................................37Purpose and Use............................................................................ 37Clip Configuration File Specification ..................................................37Implementation ............................................................................. 37Example .......................................................................................38

    FILTERS ............................................................................................... 40Header Filter....................................................................................40

    Purpose and Use............................................................................ 40Clip Configuration File Specification ..................................................41Implementation ............................................................................. 41Example .......................................................................................42

    CONTROLLERS........................................................................................ 43Restart Session Controller..................................................................43

    Purpose and Use............................................................................ 43Clip Configuration File Specification ..................................................43Implementation ............................................................................. 44

    Example .......................................................................................44

    TIPS AND TRICKS ................................................................................... 45Extending the Standard Portlet ........................................................... 45

    Example .......................................................................................45Communication between Portlet and Servlet ......................................... 46

    Example .......................................................................................46INDEX.................................................................................................. 51

  • 8/12/2019 Clipping Programmer Guide

    7/54

    PREFACE 5

    PrefaceThis guide describes the RoboSuite Clipping API. The API defines a number ofextension points and allows advanced users of the Kapow Clipping technologyto configure and control the use and execution of clipping robots.

  • 8/12/2019 Clipping Programmer Guide

    8/54

    6 CLIPPING

    IntroductionA Clipping robot is a special robot type that will be called from a web clip. Webclips will be deployed to either a web server (servlet engine) or a portalapplication.

    The RoboSuite Clipping API provides Java programmers with a means ofmodifying and extending the standard functionality of clipping robots. Theextension points allow you to:

    Provide, modify or filter input or output to your robot, e.g. by accessingdata from an external source. This includes modifying the robots input andoutput objects, adding properties, and filtering cookies and headerinformation.

    Provide user credentials, e.g. by retrieving them from an externalcredential vault.

    Program your own scheduling algorithm for balancing the load on multipleRoboServers.

    Controlling session restart.The guide is intended for Servlet programmers integrating Kapow Clips intotheir portal or web application. We assume that the programmer is familiarwith the following:

    Kapow Mashup Server Portal Content Edition. Java. Java Portlet standard (JSR-168).This guide complements the JavaDoc reference documentation, and the

    examples that are included in the release zip-file. While it does cover manybasic issues, it does not go into detail on subjects that are covered in otherKapow Mashup Server guides, such as the RoboMaker, ModelMaker and JavaProgrammers Guides. The reader is advised to consult these other guides asneeded.

    VersionsThis guide is written for the Clipping Java API version 1.0, and Kapow Mashup

    Server 6.4.

    OrganizationThe guide consists of six parts:

    Introduction:The part you are reading now, containing a shortintroduction to this guide and the product.

  • 8/12/2019 Clipping Programmer Guide

    9/54

    INTRODUCTION 7

    Using the API:Gives a brief overview of the clipping architecture and howextension points are called. Furthermore, gives an introduction to

    how the extension points are defined.

    Providers: Providers are a number of extension points that allow APIprogrammers to provide extra information to the clipping robot.

    Handlers: Handlers are a number of extension points that allow APIprogrammers to modify the output from the clipping robot.

    Filters: Filters can modify information transferred to and from the clippingrobot.

    Controllers: Used to control to the behavior of the RoboServer.The guide can be read in one stretch. However, it is not necessary to readthrough the entire guide to be able to get started with the API. Werecommend that you read the Using the API chapter first. After that youshould be able to jump to the section describing the extension point that youneed for your purpose.

    Notation

    The notation used in the guide will probably be familiar, if you have read anyof the other guides. Here is a listing of the important types of notation:

    Code examples:Being a programming guide, this document containsseveral small code examples. We use mostly code fragments forbrevity. This means that the code fragments cannot simple be copy-pasted into a Java source file and compiled. Furthermore, in theexamples brevity has been preferred to good coding style.

    Inline code:Written in fixed-width font. Inline code is used to refer to

    Java classes, keywords, or file names. For example, this is how wewould refer to the java.lang.Stringclass.

    New terms or important features:Are emphasizedso as to stand out.

    ResourcesThe Kapow Developer Connectionprovides access to many resources fordevelopers. It contains the latest downloads, as well as a problem tracking

    system, and a discussion forum. It is located at this URL:http://kdc.kapowtech.com/.

    Support

    We are always interested in feedback from our users. At the Kapow DeveloperConnection it is possible to make feature requests, bug reports, or give otherforms of feedback.

    http://kdc.kapowtech.com/http://kdc.kapowtech.com/
  • 8/12/2019 Clipping Programmer Guide

    10/54

    8 CLIPPING

    More support can be found at:

    http://support.kapowtech.com

    RequirementsThe API is written for Java 2 Standard Edition (J2SE) 1.3 through 6. Earlierversions of Java are not supported. As the API is intended to be used withinthe context of a web container, the necessary Java 2 Enterprise Edition (J2EE)APIs (in particular the Servlet API) will automatically be available.

    Another requirement is that you have a license that allows clipping, i.e. a

    Portal Content Edition or an Oracle Edition.

    ReferencesThe API uses XML as a message format, and for configuration files. It may beuseful to consult the following document:

    RoboSuite Clipping Deployment Descriptor 1.2 DTD:http://www.kapowtech.com/robosuite/rql/dtd/clip-deployment-

    descriptor_1_2.dtd.

    http://support.kapowtech.com/http://support.kapowtech.com/
  • 8/12/2019 Clipping Programmer Guide

    11/54

    USING THE API 9

    Using the APIThis chapter provides an overview of how the clipping API works and how touse it.

    The Clip Configuration FileA clip is deployed as a clip configuration file. This is an XML file with fileextension .clip. The clip configuration file contains all information needed toconfigure the clip.

    The Clipping API consists of a number of interfaces that defines extensionpoints to the clipping logic. Developers may provide implementations of theseinterfaces and register them in the clip configuration file by specifying theclass name of the implementation. In some cases default implementations areprovided, and these can be chosen in the clip configuration file withoutspecifying a class name.

    Note, that deploying a robot from RoboMaker will overwrite the clipconfiguration file, so in this case modifications to the clip configuration file will

    have to be redone. To avoid doing this often, you should choose to use a robotlibrary at a URL. Furthermore, you could use a Property Provider (see below)to retrieve configuration which might change often from another source thanthe clip configuration file.

    The Clipping LogicWhen a request is made for a clip e.g. in a portlet, the HTML of the clip willnot be returned directly, but instead a document with an IFRAME will bereturned (see Figure 1). This IFRAME will make a new request targeting theclip configuration file; that is its source (src) URL is pointing at thecorresponding clip configuration file. The request for the clip configuration fileis then handled by a servlet. In other words all requests for clip configurationfiles are mapped to a servlet which means that there must be a servletmapping in the web applications web.xml file for this (this is automaticallyplaced there when you run a clipping wizard). The specific class name of theservlet may depend on where the clip is deployed e.g. on a standard servlet

    engine, in a BEA WebLogic Portal, etc. The servlet contains code (in thefollowing called clipping logic) that will be deployed to a web server or portaland this code will be responsible for contacting a RoboServer to run theclipping robot and for presenting the clip on the web page. The clipping logicwill send request to a RoboServer and will receive responses back from this.Requests may take various forms, e.g. a request to restart a robot, a requesttelling the RoboServer that the user has clicked on a link in the clip, etc.Request may also contain extra information to the robot e.g. extra inputobject. The responses can also take many forms, e.g. content to present in

    the clip, an error message, etc.

  • 8/12/2019 Clipping Programmer Guide

    12/54

    10 CLIPPING

    Figure 1illustrates how this is done, if the clip is deployed to a portalapplication, but clips deployed to a web server will work in the same way.

    Figure 1: The Clipping Logic

    Calling RoboServerThe servlet sends a set of objects to a RoboServer. These objects can be seen(and must be defined) in the Input Objects tab in RoboMaker. One object the ClipRequest is predefined. You can define and declare additional inputobjects by defining a model in ModelMaker and adding an object inRoboMakers Input Object tab.

    The ClipRequest consists of a command specification and some data. Thecommand typically reflects an action performed by the user, e.g. clicking on a

    link, changing focus, retrieving an attachment or navigating in the history. Inaddition, a command might contain instructions to the RoboServer, e.g. tostart and stop the session.

    The data sent part of the ClipRequest includes

    SessionId:an identifier uniquely identifying the current session. Cookies:an abstract representation of the cookies in the servlet request. Header:an abstract representation of the HTTP header sent in the servlet

    request.

    Portal Application

    RoboServer

    ClipResponse

    Additional outputobjects

    Request

    ClipRequest

    Additional inputobjects

    Portlet

    Servlet

    Browser

    IFRAME

    RoboServer

  • 8/12/2019 Clipping Programmer Guide

    13/54

    USING THE API 11

    User credentials:user name and password used by the RoboServer to login.

    Properties:input values, which can be retrieved within the robot using theGet Properties converter.

    Response from RoboServer

    When RoboServer finishes processing the clipping robot, it will send back aresponse to the Servlet. Like the call to the RoboServer, this response consistsof a number of objects, where one ClipResponse is predefined. You candefine and declare additional output objects.

    A ClipResponse contains

    Changes:a specification of the changes to the servlet resulting fromexecuting the robot.

    SessionId:an identifier uniquely identifying the current session. Cookies:an abstract representation of the cookies set by the clipped site. Header:an abstract representation of the HTTP header returned from the

    clipped site.

    Alert message:if the clipping robot execution resulted in a JavaScriptalert box being shown, the message of this alert will be present in thisattribute.

    Extension PointsWe are now able to describe the extension points in more detail. If you wantto insert code at an extension point, you must provide a Java class

    implementing the Java interface for the extension point. This class must bespecified in the clip configuration file.

    All providers, handlers and controller have access to the servlet request(HttpServletRequest) and response(HttpServletResponse) and can thereforeaccess various resources, e.g. portlet preferences to get access to data fromwhich to create the values it provides.

    Providers

    A provider is an extension point, which is called before the servlet calls theRoboServer. The provider will then provide, modify or add information that willdetermine how the RoboServer is called. You can implement the followingproviders:

    Additional input objects provider:adds additional input objects to thecall to RoboServer.

    User credentials provider:Modify user name and password in theClipRequest sent to RoboServer.

  • 8/12/2019 Clipping Programmer Guide

    14/54

    12 CLIPPING

    Properties provider:Modify or add properties in the ClipRequest sent toRoboServer.

    User message localization provider:Provide localization of Kapowmessages presented by the servlet.

    Distribution policy provider:Modify the scheduling algorithm for loadbalancing multiple RoboServers

    Handlers

    A handler is an extension point, which is called after RoboServer has executed

    the clipping robot. Hence, handlers have access to the response from therobot. There are two handler interfaces, which you might implement:

    Additional output objects handler:Have the ability to read additionaloutput objects in the response from RoboServer. These extra values cane.g. be stored in the session or a database.

    Error handler:Allows you to write your own error handling strategy; e.g.forwarding to a portlet specific error page.

    FiltersA filter corresponds to two extension points: the filter is called both beforeRoboServer is called and after RoboServer has responded. The filter is capableof modifying properties, which are common to the ClipRequest and theClipResponse:

    Header filter:Modifies the list of headers by filtering, rewriting or addingheaders.

    ControllersA controller makes it possible to control the command sent to RoboServer aspart of the ClipRequest. Only one controller is available:

    Restart session controller:This extension point is before a call toRoboServer and allows you to discard the command that would normally besent and instead send a restart session command. This can be useful if theuser has changed his credentials and the clipping robot therefore shouldlog out and log in again.

    Technical IssuesA couple of technical issues relating to all extension points are mentionedhere.

    Correlation between Portlet and Servlet

    In a portal there might be several instances of the same portlet (also called

    portlet windows). For a clipping portlet this means that several clipping

  • 8/12/2019 Clipping Programmer Guide

    15/54

    USING THE API 13

    portlets in a portal may use the same clip configuration file. This also meansthat the servlet needs a way to distinguish between calls from these. If a user

    requests that a given clipping portlet should restart its session then it is thisportlet that should restart and not some other instance. In order for theservlet to know which portlet it is delivering content to, the request contains aportlet id and this can be accessed in the following way:

    request.getParameter(ClipServlet.PORTLET_PARAMETER_NAME);

    If one extends the clipping portlet class ClipJavaPortletto provide ones ownfunctionality, e.g. an edit mode, then the same portlet id may be obtained bycalling the method:

    String getPortletID(RenderResponse response)See section Communication between Portlet and Servlet, where this exampleis explored in depth. Note, that the getPortletIDmethod can only be calledduring rendering, e.g. from doEDit, doViewor doHelpand not when handlingan action from processAction.

    Thread Safety

    All classes implementing providers, handles, controllers and filters are

    required to be thread-safe.

  • 8/12/2019 Clipping Programmer Guide

    16/54

    14 CLIPPING

    ProvidersThis chapter describes the provider extension points in the clipping servlet.Providers are called by the servlet before RoboServer is called, and they areable to intervene in this calling mechanism: either by choosing a RoboServerin an environment with several RoboServers (the distribution policy provider)or by modifying the data sent as part of the request.

    Additional Input Objects Provider

    Additional input objects providers make it possible to pass data from theservlets environment to the clipping robot running on RoboServer.

    Purpose and Use

    Additional input objects providers are particularly well suited for passingstructured data or data with complex data types to the server. This can beuseful for e.g. transmitting binary data or for passing data base records to theserver. To use an additional input object provider you need to define the

    object types in ModelMaker, which makes this option a bit cumbersome.

    Hence, if the data is less structured and of string type, using a propertiesprovider is encouraged: a common example of this is passing portal userpreferences to the robot.

    The additional input objects provider functionality has a natural counterpart inthe additional output objects provider, which makes it possible for the clippingrobot to return a modified version of the input object as output. Note,however, that you can not use that same object definition since they need to

    be defined as input object and output objects respectively.

  • 8/12/2019 Clipping Programmer Guide

    17/54

    PROVIDERS 15

    Clip Configuration File Specification

    In order for the clipping logic code to know that it should use the givenadditional input objects provider this must be declared in the clip configurationfile (.clip-file). Figure 2shows an example of such a clip configuration file. Thiswill tell the clip to use a given additional input objects provider calledMyAdditionalInputObjectsProvider .

    library:/my.robot

    com.mycompany.myproject.MyAdditionalInputObjectsProvider

    Figure 2: An Example of a Clip Configuration File

    The additional-input-objectstag can contain either a specification ofobject values to use or a class specification (see the dtd for details).

    Implementation

    Additional input objects are passed from the clip to RoboServer using anAdditional Input Objects Provider. This is a class that you write yourself thatmust implement the interface:

    com.kapowtech.robosuite.client.clip.version1.api.AdditionalInputObjectsProvider

    This interface has one method called provide:

    RQLObjects provide(HttpServletRequest request,HttpServletResponse response,RQLObjects defaultObjects);

    The providemethod returns an RQLObjectsobject that contains theadditional input objects (RQLObject). Each RQLObjectcontains a number ofAttributes.

    The types RQLObject, RQLObjects and Attributeare all from the RoboSuiteJava API and documentation on these can be found in RoboSuite JavaProgrammer's Guidewhich is part of the RoboSuite documentation. TheRQLObjectscreated by the method must correspond to an input object in theclipping robot. Object and attribute names are case-sensitive.

  • 8/12/2019 Clipping Programmer Guide

    18/54

    16 CLIPPING

    The provider has access to the HttpServletRequest which makes it possible toretrieve important information about the context, such as the current URL or

    user preferences.

    The provide method also takes an HttpServletResponse as parameter thismakes the clipping API consistent with servlet and portlet APIs (such as theservlet filter) and is therefore useful if you need to call methods in these APIs(e.g. forwarding to a request dispatcher).

    The third parameter defaultObjectsof the provider is included for futureuse, and its value is left unspecified.

    ExampleFigure 3show what the code of such a provider could look like. This exampleprovider will add an object called SearchInputwhich have two attributes(textand matchCase) to the input objects that are being sent to the robot.

    package com.mycompany.myproject;

    import com.kapowtech.robosuite.api.java.rql.construct.Attribute;import com.kapowtech.robosuite.api.java.rql.construct.RQLObject;

    import com.kapowtech.robosuite.api.java.rql.construct.RQLObjects;import com.kapowtech.robosuite.client.clip.version1.

    api.AdditionalInputObjectsProvider;

    import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.util.ArrayList;import java.util.List;

    public class MyAdditionalInputObjectsProviderimplements AdditionalInputObjectsProvider {

    public RQLObjects provide(HttpServletRequest request,HttpServletResponse response,RQLObjects defaultObjects) {

    List rqlObjectsList = new ArrayList();List attributes = new ArrayList();attributes.add(new Attribute("text", "Kapow"));attributes.add(new Attribute("matchCase", "true"));RQLObject rqlObject = new RQLObject("SearchInput", attributes)rqlObjectsList.add(rqlObject);return new RQLObjects(rqlObjectsList);

    }

    }

    Figure 3: Code Example of an Additional Input Objects Provider

    The provider will create an RQLObject object representing the SearchInputobject and add this to an RQLObjects object. This RQLObjects object will bereturned from the provide method of the provider. The value that is assignedto the attributes will of course not normally be fixed as in the example, butmay be obtained from some external source, e.g. from the portal preferences

    of the user.

  • 8/12/2019 Clipping Programmer Guide

    19/54

    PROVIDERS 17

    Properties Provider

    Property providers provide an alternative way of passing data from theservlets environment to the clipping robot. The data is passed via the stringattribute properties on the ClipRequest object. Special classes andmethods are available to the properties provider for creating such values, andthe properties are parsed by the robot and made available via a converter.

    Purpose and Use

    The property provider gives you a simple way of providing extra input to the

    clipping robot. They are convenient if the data to pass to the robot is simplestrings, since properties are defined as simple name-value pairs, where boththe name and the value are represented as a string.

    The most obvious use case is to retrieve business domain values from thesession and pass these to the robot, for instance to pass a customer numberthat the robot should enter into a field. A less obvious but very useful use ofproperty providers is to make your robot more general: if a value of yourrobot is likely to change, you can replace this value by a property and haveyour property provider look up the value in a configuration file or database.This way it is not necessary to change the robot (and redeploy or create arobot library) and you can just change your configuration instead. An exampleof this would be retrieving the start URL as a property.

    Within the clipping robot, the data of a property is retrieved using the GetProperty converter.1

    1The list of properties is also available as a text attribute on the ClipRequest object andcan in principle be retrieved from there. This, however, requires parsing the string, and

    hence it is not a very useful option.

  • 8/12/2019 Clipping Programmer Guide

    20/54

  • 8/12/2019 Clipping Programmer Guide

    21/54

    PROVIDERS 19

    Map propertyMap = new HashMap();propertyMap.put("property1", "value1");propertyMap.put("property2", "value2");Properties properties = new Properties(propertyMap);

    Create a list of Propertyobjects and call the Propertiesconstructor withthis list as argument. A Propertyis created by calling its constructor with aname and a value. You should not add more than one Propertyobject withthe same property name, as this will cause an error when the clippingrobot is executed.E.g.

    List propertiesList = new ArrayList();

    propertiesList.add(new Property("property1", "value1"));propertiesList.add(new Property("property2", "value2"));Properties properties = new Properties(propertiesList);

    Example

    Figure 5shows an example where a URL is chosen randomly between Googleand Kapow and passed as a property

    package com.mycompany.myproject;import java.util.ArrayList;import java.util.List;import java.util.Random;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.kapowtech.robosuite.client.clip.version1.api.Properties;import com.kapowtech.robosuite.client.clip.version1.api.

    PropertiesProvider;import com.kapowtech.robosuite.client.clip.version1.api.Property;

    public class MyPropertiesProvider implements PropertiesProvider {public Properties provide(HttpServletRequest request,HttpServletResponse response,Properties defaultProperties) {

    Random generator = new Random();int i = generator.nextInt(2);Property property =new Property("startUrl",

    "http://" + (i==0 ?"www.google.com":

    "www.kapowtech.com"));List properties = new ArrayList();

    properties.add(property);return new Properties(properties);}

    }

    Figure 5: Code Example of a Properties Provider

  • 8/12/2019 Clipping Programmer Guide

    22/54

    20 CLIPPING

    User Credentials Provider

    User credentials providers are used to supply user credentials to the clippingrobot, which in turn will use this for login on the clipped web site. Usercredentials are passed as attributes on the ClipRequestobject, and can beretrieved by the robot from this object.

    If the clipping robot is set up to use http-based login, the robot willautomatically retrieve the user name and password from these attributes. Ifform based login is used, the robot developer must ensure that the attributesare entered into the correct field on the login form.

    Purpose and Use

    The User Credentials Provider is used for supporting automatic login in clippedweb sites and is hence instrumental in using clipped web sites in a singlesign onportal solution.

    Typically, an SSO solution will be based on some sort of credentials vault. Inthis case, the user credentials provider should access this vault to retrieveuser name and password. In another use cases, the user might login in a

    special portlet, which would store the username and password (encrypted) inthe session. This could then be retrieved by the user credentials provider.

    Clip Configuration File Specification

    The User Credentials Provider must be declared in the clip configuration file(.clip-file). Figure 6shows such a clip configuration file. This will tell the clip touse a given user credentials provider called MyUserCredentialsProvider.

    library:/my.robot

    com.mycompany.myproject.MyCredentialsProvider

    Figure 6: An Example of a Clip Configuration File

  • 8/12/2019 Clipping Programmer Guide

    23/54

    PROVIDERS 21

    The user-credentials tag contains either a class-name tag (as in the example)or a pair of username and password. E.g.

    Joe Smithabcdefgh

    Implementation

    To create a user credentials provide, you must implement the interface

    com.kapowtech.robosuite.client.clip.version1.api.

    UserCredentialsProvider

    This interface has one method

    UserCredentials provide(HttpServletRequest request,HttpServletResponse response,UserCredentials defaultCredentials);

    This provider follows the well known pattern from previous sections onproviders by taking an HttpServletRequestand HttpServletResponseasinput. In addition as in previous sections it takes default credentials, whichwill always be empty in practice (i.e. user credentials with empty user nameand empty password), as default credentials cannot be specified in the clipconfiguration file together with a class name specifying a user credentialsprovider.

    The provider returns an object of type UserCredentials. Such an object iscreated by calling the constructor with user name and password (see theexample below).

  • 8/12/2019 Clipping Programmer Guide

    24/54

    22 CLIPPING

    Example

    Figure 7presents a trivial example of a user credentials provider. Here theusername demo and password demo is passed to the roboserver inpractice you would retrieve the username and password from some externalsource such as a credentials vault or the session.

    package com.mycompany.myproject;

    import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.kapowtech.robosuite.client.clip.version1.api.

    UserCredentials;import com.kapowtech.robosuite.client.clip.version1.api.UserCredentialsProvider;

    public class MyUserCredentialsProviderimplements UserCredentialsProvider {

    public UserCredentials provide(HttpServletRequest request,HttpServletResponse response,UserCredentials defaultCredentials)

    {// place your code to fetch username and password here:

    final String username = "demo";final String password = "demo";

    return new UserCredentials(username, password);}

    }

    Figure 7: Code Example of a User Credentials Provider

    User Message Localization ProviderKapow clipping technology pipes HTML from the clipped page to the consumer(portal or web server). This means that correct localization andinternationalization of the actual content is the responsibility of the clippedpages, and that your main task is to ensure that the correct user settings aretransferred to the clipped page.

    However, a few user messages exists which originate solely from Kapow.Hence, to make your portal truly international, these user messages need to

    be localized.

    Purpose and Use

    The user message localization is useful in multi-language environments, wherethe messages should depend on the user or the browsers locale. If you justneed to use clipping in a non-English speaking environment, it is easier tospecify the localized texts in RoboMaker.

    A user message localization provider should provide a localized version of the

    static Kapow user messages, which will then be shown in the end-users

  • 8/12/2019 Clipping Programmer Guide

    25/54

  • 8/12/2019 Clipping Programmer Guide

    26/54

    24 CLIPPING

    Figure 9gives an example of a clip configuration file specifying a resourcebundle. In the example com.mycompany.myproject.MyResourceBundleis a

    class extending java.util.ResourceBundle.

    library:/my.robot

    com.mycompany.myproject.MyResourceBundle

    Figure 9: Clip Configuration File with a Resource Bundle

    The resource bundle should specify a translation of the texts named

    UserMessageLocalizationProvider.WAIT_PAGE_TEXT_KEY UserMessageLocalizationProvider.POPUPS_BLOCKED_KEYAn example of a root resource bundle is given in Figure 10. Specific locales arespecified in the same way.

    import java.util.*;

    import com.kapowtech.robosuite.client.clip.version1.api.UserMessageLocalizationProvider;

    public class MyResourceBundle extends ListResourceBundle {

    private static final Object[][] localization =new Object[][] {{UserMessageLocalizationProvider.WAIT_PAGE_TEXT_KEY,"Please wait."},

    {UserMessageLocalizationProvider.POPUPS_BLOCKED_KEY,"Popups blocked. Please unblock."}

    };

    protected Object[][] getContents() {return localization;

    }}

    Figure 10: Resource Bundle Root

    P 25

  • 8/12/2019 Clipping Programmer Guide

    27/54

    PROVIDERS 25

    The name of the resource bundle can be specified in RoboMaker and will thenbe written to the clip configuration file. Note, that the user-messagestag can

    be used together with the wait-page-textand/or popups-blocked-texttags, which then provide default values.

    The third way of specifying the localization is to provide a class which

    performs the localization. The class name is specified in the standard fashionas illustrated in Figure 11.

    library:/my.robot

    com.mycompany.myproject.MyMessageLocalizationProvider

    Figure 11: Clip Configuration File with a User Message LocalizationProvider

    Implementation

    We will not describe how to implement resource bundles here instead you

    should consult Suns document on localization.

    A user message provider must implement the interface

    com.kapowtech.robosuite.client.clip.version1.api.UserMessageLocalizationProvider

    This interface has one method

    void modifyMessageMap(HttpServletRequest request,HttpServletResponse response,Map messageMap);

    This provider follows the well known pattern from previous sections onproviders by taking an HttpServletRequest and HttpServletResponse asparameters.

    The last parameter is a map mapping user message keys (Strings) to localizedmessages. This provider works by modifying this map. The keys in the mapare the same as we saw with resource bundles:

    UserMessageLocalizationProvider.WAIT_PAGE_TEXT_KEY

    26 CLIPPING

  • 8/12/2019 Clipping Programmer Guide

    28/54

    26 CLIPPING

    UserMessageLocalizationProvider.POPUPS_BLOCKED_KEYExampleA simple example of a user message localization provider is given in Figure12:

    package com.mycompany.myproject;

    import java.util.Enumeration;import java.util.Locale;import java.util.Map;

    import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.kapowtech.robosuite.client.clip.version1.api.

    UserMessageLocalizationProvider;

    public class MyUserMessageLocalizationProviderimplements UserMessageLocalizationProvider {

    public void modifyMessageMap(HttpServletRequest request,HttpServletResponse response,Map messageMap) {

    Enumeration locales = request.getLocales();

    if (locales.hasMoreElements()) {final Locale locale = (Locale) locales.nextElement();if (locale.equals(Locale.FRENCH))messageMap.put(WAIT_PAGE_TEXT_KEY,"Attendez sil vous plait");

    }}

    }

    Figure 12: An Example of a User Message Localization Provider

    In this example the wait text will be in French if the locale is French and thedefault wait text (as given in the robot configuration) will be used otherwise.

    Distribution Policy ProviderA distribution policy provider makes it possible to write your own policy forcontacting RoboServers in an environment with multiple RoboServers.

    Purpose and UseA distribution policy determines how clipping sessions should be distributed tothe available RoboServers. This is, in effect, a coarse-grained client-side loadbalancing policy. The distribution policy for a particular clip is used for allinstances of the clip portlet. The policy is normally not shared among differentclips in a portal.

    The DistributionPolicyProvider interface allows you to specify whichDistributionPolicy instance should be used for the clip.

    PROVIDERS 27

  • 8/12/2019 Clipping Programmer Guide

    29/54

    PROVIDERS 27

    Two different distribution policies are provided by Kapow and can be usedwithout having to use the API: Round Robin and Random. In both cases, you

    specify a list of RoboServers in the clip configuration file. For each session, theservlet will then choose a RoboServer from the list according to the policyspecified. In addition, it will make sure, that the RoboServer is available andotherwise choose another one.

    The Round Robin distribution policy will choose RoboServers successively fromthe list of servers, i.e. the instance of the portlet will contact a randomRoboServer, the next portlet instance will contact the next in the list etc.When the last RoboServer in the list has been contacted, the next instance willcontact the first in the list.

    The Random distribution policy will contact a random RoboServer each time asession starts. You should consult standard text books on the subject for anintroduction to scheduling algorithms and their pros and cons.

    In many cases, choosing one of these will be sufficient (Round Robin is thedefault if you do not modify the clip configuration file).

    Defining your own distribution policy can, however, be useful in a number ofsituations. E.g.:

    It is often convenient to separate the list of available servers from the clipconfiguration file. This makes it possible to change the list of serverswithout having to redeploy. The available servers might be retrieved from adirectory service such as LDAP.

    It can be useful to cache the responses from RoboServer to improveperformance. This can be done using a Caching RQLEngine as described inthe Java Programmers Guide.

    Round Robin and Random distribution policies are not always optimal: Theybehave best if the processes allocated to the different RoboServers resultin a similar load. In addition, the implementation of Round Robin has onestate (the next RoboServer to use) for each clip, which means thatdifferent clips might accidentally favor the same RoboServers.An introduction to other scheduling policies is beyond the scope of thismanual.

    You might want to implement more advanced fail-over than provided in thedefault distribution policies. The default implementation is, however, fairlyadvanced: If a RoboServer fails, it is marked as unavailable. Every time anew RoboServer is requested, it is picked from the list of available servers.If a certain time has elapsed since the last check, the unavailable server ispinged and potentially marked as available. The time interval is increasedevery time pinging the server fails. This solution is often sufficient, but canbe tuned to the actual situation (e.g. pinging more often might be efficientin a low latency-low bandwidth network, and just trying to send therequest might be useful in a high latency-high bandwidth network).

  • 8/12/2019 Clipping Programmer Guide

    30/54

    PROVIDERS 29

  • 8/12/2019 Clipping Programmer Guide

    31/54

    This interface has one method:

    DistributionPolicy provide(HttpServletRequest request,

    HttpServletResponse response);

    The arguments are the usual request and response, and are available toaccess the context and call servlet API methods.

    The providemethod returns a

    com.kapowtech.robosuite.api.java.rql.engine.dist.DistributionPolicy

    The DistributionPolicy interface is only briefly mentioned in the Java

    Programmers guide, so we will go a bit more into details here. The interfacehas two methods:

    RQLEngine nextRQLEngine();

    List selectAvailableRQLEngines();

    The first method is at the core of the distribution policy: Whenever a session isstarted it must return a new RQLEngine (see the Java programmers Guide formore information on RQLEngines).

    The second method returns a list of all available RQLEngines. This will often bea natural part of the implementation of the DistributionPolicy, but has beenmade public: It can be used to allow RQLEngines to multicast special requeststo all RoboServers.

    All relevant state is kept in the DistributionPolicy instance. For example, theRoundRobinDistributionPolicy keeps track of which server instance wasreturned last, and also which servers are known to be unavailable. TheDistributionPolicy implementation is accessed from multiple threads, so it must

    be thread-safe. In practice, this means that all state must be protected by amutual exclusion lock.

    Example

    It is important to understand, that implementing your own distribution policyis a difficult task. To give a complete and useful example, which goes beyondthe pre-implemented distribution algorithms is therefore beyond the scope ofthis manual. The example given below is therefore not a useful one, and while

    it is fully functional, it is less efficient than the build-in Random distributionpolicy. It is, however, sufficiently complex to illustrate the central concerns,you must address when you implement your own distribution policy.

    Figure 15gives an example of a Distribution Policy Provider. It defines aDistributionPolicy as a final field (_distributionPolicy) which is returnedevery time the providemethod is called note, that there are no guaranteesconcerning how often the providemethod is called. The distribution policy is aMyRandomDistributionPolicy , which is described in details below. TheMyRandomDistributionPolicy is initialized with a static list of RQLEngines

    30 CLIPPING

  • 8/12/2019 Clipping Programmer Guide

    32/54

    each of these are created in addRoboServeras a RemoteRQLEnginecommunicating via SocketBasedObjectRQLProtocol (for further details on

    RQLEngines consult the Java Programmers Guide). The methodgetRoboServers is meant to illustrate that the list of servers is retrieved froman external source.

    Figure 16presents the implementation of MyRandomDistributionPolicy . Thepolicy works by choosing a random RQLEngine among the available engines.

    The distribution policy tries to ensure, that only available engines are returnedin the nextRQLEngineand selectAvailableRQLEnginesmethods (whichimplement the DistributionPolicyinterface). It does so in a nave (some

    would say stupid) way, by always pinging all potentially available servers tosee if they are available. This is implemented in updateAvailableEngines whichpings each server using a special handler (presented in Figure 17) which willthrow an exception if pinging errs hence adding the engine will be skippedand the exception caught and ignored.

    Pinging all servers every time is of course clearly highly inefficient, but isincluded to illustrate the importance of availability

    PROVIDERS 31

  • 8/12/2019 Clipping Programmer Guide

    33/54

    package com.mycompany.myproject;

    import java.util.ArrayList;import java.util.Iterator;import java.util.LinkedList;import java.util.List;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.kapowtech.robosuite.api.java.rql.engine.RQLEngine;import com.kapowtech.robosuite.api.java.rql.engine.dist.

    DistributionPolicy;import com.kapowtech.robosuite.api.java.rql.engine.remote.

    RQLProtocol;import com.kapowtech.robosuite.api.java.rql.engine.remote.

    RemoteRQLEngine;import com.kapowtech.robosuite.api.java.rql.engine.remote.socket.

    SocketBasedObjectRQLProtocol;import com.kapowtech.robosuite.client.clip.version1.api.

    DistributionPolicyProvider;

    public class MyDistributionPolicyProviderimplements DistributionPolicyProvider {private interface RoboServerSpec {String getHost();int getPort();

    }

    private final DistributionPolicy _distributionPolicy= new MyRandomDistributionPolicy(getEngineList());

    public DistributionPolicy provide(HttpServletRequest request,HttpServletResponse response) {

    return _distributionPolicy;}

    private List getEngineList() {List engineList = new LinkedList();

    List servers = getRoboServers();for (Iterator r = servers.iterator();r.hasNext();) {

    addRoboServer(engineList, r.next());}return engineList;

    }

    private void addRoboServer(List engineList,RoboServerSpec host) {

    RQLProtocol protocol= new SocketBasedObjectRQLProtocol(host.getHost(),

    host.getPort());RQLEngine engine = new RemoteRQLEngine(protocol);engineList.add(engine);

    }

    private List getRoboServers() {// implementation left to the reader

    }}

    Figure 15: An Example of a Distribution Policy Provider

  • 8/12/2019 Clipping Programmer Guide

    34/54

    PROVIDERS 33

  • 8/12/2019 Clipping Programmer Guide

    35/54

    package com.mycompany.myproject;

    import com.kapowtech.robosuite.api.java.rql.RQLException;import com.kapowtech.robosuite.api.java.rql.construct.RQLResponse;import com.kapowtech.robosuite.api.java.rql.engine.RQLHandler;

    public class myPingRQLHandler implements RQLHandler {public void handleError(RQLException e) throws RQLException {

    throw e;}

    public void handleFatal(RQLException e) throws RQLException {throw e;

    }

    public void handleResponse(RQLResponse response)throws RQLException {

    // do nothing}

    }

    Figure 17: A Simple RQLHandler for Handling the Result of Ping

    In the implementations of RoundRobinDistributionPolicy and

    RandomDistributionPolicy , the knowledge of availability is put in the handsof the RQLEngine itself (an engine wrapping another engine as described inthe Java Programmers Guide). This means that you do not have to ping theserver to know whether it is available, but can do it at each request to theRQLEngine. It is then the responsibility of the distribution policy to return theengines to service. This is done by pinging each unavailable engine after acertain interval if the engine is still not available this is repeated afterincreasingly longer intervals. While the implementation in Figure 16issignificantly simpler than this, it is the hope, that it illustrates the principles,

    so you will be able to write your own distribution policy.

    34 CLIPPING

  • 8/12/2019 Clipping Programmer Guide

    36/54

    HandlersThis chapter describes the handler extension points in the clipping servlet.Handlers are called when execution of the clipping robot has terminated onthe RoboServer either successfully or by returning an error. Handlers canintercept the returned values (an additional output objects handler) or theexception thrown in case of error (an error handler).

    Additional Output Objects Handler

    Additional Output Objects handlers are called by the clipping logic if the robotreturns additional output objects.

    Purpose and Use

    An additional output objects handler gives access to objects returned from theRobot. These objects must be declared as output objects in the clipping robotand explicitly returned in a return step. The returned values can be used for avariety of purposes like being written to log-files or database, but most often

    they will be put in a session attribute to be read by other servlets or portlets.The data could be a key such that other portlets can retrieve the informationand show relevant information. E.g. if you are clipping a list of invoices due fora given customer, you might want to return the customer number, so otherportlets can show other information perhaps clipped from other systems concerning the same customer. Or it could be information that you navigatedpast in the clipping robot in the invoices due example, you might havenavigated past a page with the customers address, which could be shown inanother portlet.

    One thing that one has to be aware of with respect to clipping portletsreturning additional output objects is that there is no way for the portlet toalert other portlet (clipping or non clipping) that the portlet has returned anobject and that these other portlets might want to update their view to reflectthe change. The reason for this is that a clip in a clipping portlet is actually an

    IFrame that communicates directly with a servlet without the portletknowing about this. So the clipping portlet cannot decide to refresh theportal to let other portlets refresh their views. So if one wants to write a

    portlet that adjusts its view based on objects returned by a clip portlet thenone has to put in some kind of regular updating mechanism into the portlet,such that this will update itself regularly, e.g. by using JavaScript and possiblyAJAX.

    HANDLERS 35

  • 8/12/2019 Clipping Programmer Guide

    37/54

    Clip Configuration File Specification

    To add an additional output object provider, you need to specify a class name

    within an additional-output-objects tag. Figure 18gives an example ofhow this can be done.

    library:/my.robot

    com.mycompany.MyAdditionalOutputObjectHandler

    Figure 18: Example of a Clip Configuration File with an AdditionalOutput Objects Handler

    Implementation

    An Additional Output Objects handler is a Java class that must implement thefollowing interface:

    com.kapowtech.robosuite.client.clip.version1.api.AdditionalOutputObjectsHandler

    This interface has one method:

    void handle(HttpServletRequest request,HttpServletResponse response,RQLObjects outputObjects);

    RQLObjectshas been mentioned in section Additional Input Objects Providerand further described in the Java Programmers Guide. It holds a list of allobjects returned explicitly in the clipping robot. In each object you can then

    access the attribute values.

    36 CLIPPING

  • 8/12/2019 Clipping Programmer Guide

    38/54

    Example

    The example in Figure 19shows an Additional Output Objects Handler that

    takes an attribute value from an output object and places this in a sessionattribute. The output object is called MyAdditionalOutputObject and this hasone attribute url.

    package com.mycompany.myproject;

    import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.kapowtech.robosuite.api.java.rql.construct.RQLObject;import com.kapowtech.robosuite.api.java.rql.construct.RQLObjects;

    import com.kapowtech.robosuite.client.clip.version1.api.AdditionalOutputObjectsHandler;

    public class MyAdditionalOutputObjectsHandlerimplements AdditionalOutputObjectsHandler {

    public void handle(HttpServletRequest request,HttpServletResponse response,RQLObjects objects) {

    RQLObject rqlObject= (RQLObject)

    objects.getByName("MyAdditionalOutputObject").get(0);String url = (String) rqlObject.getAttribute("url").getValue();request.getSession().setAttribute("com.mycompany.url", url);

    }}

    Figure 19: Code Example of an Additional Output Objects Handler

    The robot is a simple clipping robot that besides returning the normalClipResponse object also returns a MyAdditionalOutputObject object that

    contains the URL of the clipped document (see Figure 20).

    Figure 20: Clipping Robot Returning an Additional Output Object

    The session attribute written by the additional output objects handler may beread by other portlets using the following code:

    request.getPortletSession().getAttribute("com.mycompany.url",

    PortletSession.APPLICATION_SCOPE)

    or in a JSP page by using the following code:

    HANDLERS 37

  • 8/12/2019 Clipping Programmer Guide

    39/54

    Error HandlerError handlers make it possible to intercept errors and deal with them in asuitable manner.

    Purpose and Use

    An error handler defines a strategy for handling errors in a clip. The customerror handler is only invoked after all other handlers have failed, and theclipping logic is about to throw a ServletExceptioncausing the currentrequest to fail. The custom error handler can forward to a portlet-specific errorpage or provide localized error messages, but should not otherwise attempt to

    recover from the error.

    Note that most portal systems (among them BEA WebLogic Portal 8.1 to 10.0)allow the user to specify a portlet specific error page to handle exceptions, soimplementing this class might not be necessary.

    Clip Configuration File Specification

    Figure 21show how to add a reference to an Error Handler in a clipconfiguration file.

    library:/my.robot

    com.mycompany.MyErrorHandler

    Figure 21: An Example of a Clip Configuration File with an Error

    Handler

    ImplementationA custom error handler must implement the following interface:

    com.kapowtech.robosuite.client.clip.version1.api.ErrorHandler

    This interface has one method:

    void handleError(HttpServletRequest request,HttpServletResponse response,Exception e) throws Exception;

    38 CLIPPING

  • 8/12/2019 Clipping Programmer Guide

    40/54

    The exception (e) in this method signature may be used to find the cause ofthe error to be able to produce an appropriate error message.

    Example

    Figure 22shows an example of an Error Handler class. This will forward therequest to a JSP page that will present an error message. The handler willplace the message in a request attribute such that the JSP page can getaccess to this. Figure 23show a simple example of how such a JSP page canbe constructed. One might decide not to handle the exception in an errorhandler and re-throw the exception such that the portal or web applications

    default method for handling error may be invoked.

    package com.mycompany.myproject;

    import javax.servlet.RequestDispatcher;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.kapowtech.robosuite.client.clip.version1.ClipException;importcom.kapowtech.robosuite.client.clip.version1.api.ErrorHandler;

    public class MyErrorHandler implements ErrorHandler {private static final String _ERROR_JSP = "error.jsp";

    public void handleError(HttpServletRequest request,HttpServletResponse response,Exception clipException)

    throws Exception {request.setAttribute("com.mycompany.error",

    clipException.getMessage());RequestDispatcher dispatcher= request.getRequestDispatcher(_ERROR_JSP);

    try {dispatcher.forward(request, response);} catch (Exception e1) {throw new ClipException(

    "ErrorHandler failed to redirect to jsp: " +_ERROR_JSP, e1);

    }}

    }

    Figure 22: Code Example of an Error Handler

    HANDLERS 39

  • 8/12/2019 Clipping Programmer Guide

    41/54

    The JSP error page error.jspcould then look something like shown in Figure23. The page error.jspmust be located in the same folder as the clip

    configuration file for the example to work.

    Error

    An error has occurred:

    Figure 23: JSP Error Page Example

    40 CLIPPING

  • 8/12/2019 Clipping Programmer Guide

    42/54

    FiltersFilters intercept the communication between the client and RoboServer. Theyare able to modify the content of the communication: Both requests sent toRoboServer and responses from RoboServer can be modified.

    Header FilterWith a header filter, you can exclude, rewrite or even add to the list of httpheaders sent to RoboServer and returned from RoboServer.

    Purpose and Use

    Some single sign on solutions (SSO) work by adding a token to the HTPPheader of all calls. Suppose that you are clipping from one internal site usingthis SSO solution and want to insert the clip into a portal using the same SSOsolution. Now, the SSO will append the special header to the request from theusers browser to the servlet and you need to make sure, that the header isforwarded to RoboServer and on to the site from which you are clipping. Onthe other hand the header should not be forwarded to other sites which are

    not under the SSO solution.

    The SSO problem is one of the key examples of using a header filter, and thehope is that it serves to illustrate the purpose of the filter. On the other hand,a word of caution is needed: altering or adding headers or even just allowingheaders from the users browser to be forwarded to RoboServer might resultin unexpected behavior. E.g. consider the situation where the user-agent isallowed to filter through: Then the clipped site will begin to function accordingto the end-users browser and not according to the browser emulated by

    RoboServer (where most of the site is processed).For this reason the default filter will exclude all headers.

    FILTERS 41

  • 8/12/2019 Clipping Programmer Guide

    43/54

    Clip Configuration File Specification

    If nothing is specified in the clip configuration file, no headers will be passed

    on. If you instead want to allow all unrecognized extension headers to pass,you should specify the preconfigured extension-headersfilter. Figure 24shows how to do this.

    library:/my.robot

    Figure 24: Header Filter ElementThe extension-headersfilter passes on all unrecognized extension headers.A header is an unrecognized extension header if it is not a general, request,response, or entity header as defined in RFC 2616 (HTTP/1.1), and is not acookie-related header (as defined in RFC 2109 and RFC 2965). This filter willbe useful in the SSO example presented above.

    If you wish to write your own header filter, you specify the class name of yourimplementation as follows:

    com.mycompany.MyHeaderFilter

    Implementation

    If you wish to write your own header filter, your must implement the interface

    com.kapowtech.robosuite.client.clip.version1.api.HeaderFilterThis interface has one method:

    public List filterHeaders(List headers)

    Both the argument and the result of this method is a list of headers:

    com.kapowtech.robosuite.client.clip.version1.api.Header

    A header cannot be modified, but new headers are easily constructed.

    42 CLIPPING

  • 8/12/2019 Clipping Programmer Guide

    44/54

    Example

    Figure 25gives the implementation of a header filter, which corresponds to

    the default blocking filter which excludes all headers.

    package com.mycompany.myproject;

    import java.util.Collections;import java.util.List;import com.kapowtech.robosuite.client.clip.version1.api.

    HeaderFilter;

    public class MyHeaderFilter implements HeaderFilter {public List filterHeaders(List headers) {return Collections.EMPTY_LIST;

    }}

    Figure 25: Code Example of a Header Filter

    CONTROLLERS 43

  • 8/12/2019 Clipping Programmer Guide

    45/54

    ControllersA controller is an extension point, which allows the programmer direct controlover the execution of the robot on the server. Only one controller is available,namely the restart session controller, which allows the programmer to restartthe robot session.

    Restart Session ControllerA restart session controller determines whether to restart the clipping session

    for a robot on a RoboServer.

    Purpose and Use

    It is often useful to restart the session if some of the input values to a robothave changed. An example could be a clip that uses credential to login to theremote site. If a user changes the credential the robot should logout and loginagain. This would happen if the robot is told to restart its clipping session,because this would make the robot run its logout branch (if it has one) andthen run its login branch again with the new credentials.

    Clip Configuration File Specification

    Figure 26show how to add a reference to an Error Handler in a clipconfiguration file.

    library:/my.robotcom.mycompany.MyRestartSessionController

    Figure 26: Example of a Clip Configuration File with a Restart SessionController

    44 CLIPPING

  • 8/12/2019 Clipping Programmer Guide

    46/54

    Implementation

    A restart session controller must implement the interface:

    com.kapowtech.robosuite.client.clip.version1.api.RestartSessionController

    This interface has one method:

    public boolean shouldRestartSession(HttpServletRequest request,HttpServletResponse response)

    The method should return true when the robot session should be restarted.

    ExampleIn this chapter, we just give a fragment of an example of the use: We leave itunspecified how to decide when to restart. In the next chapter, we will seehow we can communicate this information from the surrounding portlet to theservlet and hence on to the controller. The next chapter will also illustrate howto extend the portlet, and these two techniques in combination will allow us toextend the portlet with and edit page where the end-user can control therestart.

    Figure 27shows a prototype of a restart session controller.

    import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;importcom.kapowtech.robosuite.client.clip.version1.api.RestartSessionController;

    public class MyRestartSessionControllerimplements RestartSessionController {

    public boolean shouldRestartSession(HttpServletRequest request,

    HttpServletResponse response){final Boolean shouldRestart = ...return shouldRestart;

    }}

    Figure 27: Example of a Restart Session Controller

    TIPS AND TRICKS 45

  • 8/12/2019 Clipping Programmer Guide

    47/54

    Tips and TricksThis chapter discusses some common use cases and present ideas of how tosolve them.

    Extending the Standard PortletYou can extend the functionality of your clipping portlet by extending theClipJavaPortletclass, which by default is used for all clipping portlets.Remember to change the in portlet.xml to point to yourimplementation. E.g.:

    clippingapi.ClipJavaPortletWithHelp

    Example

    A very simple example of extending the clipping portlet is to add a help page.First, you must enable the help-mode of your portlet (again in portlet.xml):

    text/htmlhelp

    You then extend the ClipJavaPortletclass and implement the doHelpmethod. An example of this is shown in Figure 28.

    package com.mycompany.myproject;

    import javax.portlet.PortletException;import javax.portlet.PortletRequestDispatcher;import javax.portlet.RenderRequest;import javax.portlet.RenderResponse;import com.kapowtech.robosuite.client.clip.version1.adapter.

    platform.portlet10.ClipJavaPortlet;

    public class ClipJavaPortletWithHelp extends ClipJavaPortlet {

    protected void doHelp(RenderRequest request,RenderResponse response)

    throws PortletException, java.io.IOException {

    PortletRequestDispatcher portletRequestDispatcher= getPortletContext().getRequestDispatcher("/help.html");portletRequestDispatcher.include(request, response);response.flushBuffer();

    }}

    Figure 28: Extending the Clipping Portlet with a Help Page

    In this example, the doHelpmethod redirects to a simple html page displaying

    the help.

    46 CLIPPING

    A th i t dd dit W ill t t thi

  • 8/12/2019 Clipping Programmer Guide

    48/54

    Another common use case is to add an edit page. We will return to thisexample in the next section.

    Communication between Portlet and ServletIf clipping is used in a Portal, the portlet shown will contain an IFRAME with aservlet (see chapter The Clipping Logic). Often information from the portletneeds to be communicated from the portlet to the servlet. Assume forinstance that you have created an edit page for your portlet, and that thispage allows the user to restart the clipping session. Now you need tocommunicate the users action from the portlet to the clipping servlet, such

    that a RestartSessionController can retrieve the information and return true.

    Example

    As an example let us assume that we want to extend our clipping portlet withan edit page on which there is a button to restart the portlet. That is if at agiven point a user goes to the edit page and presses this button the clip willrestart its session and the clip will display its start URL instead of whatever itwas displaying before.

    This example is meant to capture the essence of a common situation wherethe clip portlet has an edit page allowing the user to change the configurationof the robot. After modifying the configuration and pressing save, the cliphas to be restarted for the configuration changes to take effect.

    For this to work we need to find a way to get the information that the portletwants to restart its session to the servlet.

    Figure 30shows a portlet class that extends the clipping portlet classClipJavaPortlet. First, it adds an edit page to the portlet: This is done in the

    doEditmethod, which redirects to a JSP page called edit.jsp (this is shown inFigure 29).

    Press here to restart the clip:

    Figure 29: The Edit JSP Page

    TIPS AND TRICKS 47

  • 8/12/2019 Clipping Programmer Guide

    49/54

    package com.mycompany.myproject;

    import ...

    public class ClipJavaPortletWithEdit extends ClipJavaPortlet {public static final String SHOULD_RESTART = "ShouldRestart";private static final String LAST_RESTART_ATTRIBUTE_NAME= "lastRestart";

    private static final Random random = new Random();

    public void processAction(ActionRequest request,ActionResponse response)

    throws PortletException, IOException {final boolean isEditMode

    = PortletMode.EDIT.equals(request.getPortletMode());if (isEditMode) {final String restart = request.getParameter("restart");if (restart != null) {response.setRenderParameter("restart",

    "" + random.nextInt());response.setPortletMode(PortletMode.VIEW);

    }}

    }

    protected void doEdit(RenderRequest request,

    RenderResponse response)throws PortletException, java.io.IOException {PortletRequestDispatcher portletRequestDispatcher =getPortletContext().getRequestDispatcher("/edit.jsp");

    portletRequestDispatcher.include(request, response);response.flushBuffer();

    }

    public void doView(RenderRequest request,RenderResponse response)

    throws PortletException, IOException {final String restartParameter = request.getParameter("restart");

    final String lastRestartParameter= (String) getSessionAttribute(request, response,

    LAST_RESTART_ATTRIBUTE_NAME);final boolean shouldRestart= restartParameter != null &&!restartParameter.equals(lastRestartParameter);

    if (shouldRestart) {setSessionAttribute(request, response,

    LAST_RESTART_ATTRIBUTE_NAME,restartParameter);

    }setSessionAttribute(request, response,

    SHOULD_RESTART, shouldRestart);super.doView(request, response);

    }}

    Figure 30: Portlet Extending ClipJavaPortlet

    The edit page has a button restart. When the user presses this, the methodprocessAction(see Figure 30) will be called. If the user has pressed restart,

    the processActionmethod will set a RenderParameter restartto a random

    48 CLIPPING

    value The doView method can read this parameter and check whether it is

  • 8/12/2019 Clipping Programmer Guide

    50/54

    value. The doViewmethod can read this parameter and check whether it isequal to the last value of the restartparameter (which is saved as a sessionattribute). Hence processActionensures that a new value is generatedwhenever it is responsible for calling doView, but when doViewis called forother reasons, the value will be unchanged. Thus the random value makes itpossible for doViewto distinguish calls due to the user pressing restart, andcalls due to portal refreshes (this method works well in practice, but is not100% bulletproof in principle, as random might return the same value twice).

    If doViewis called due to a restart, we should make this fact available to theRestart Session Controller: The key to transferring data from the portlet to theservlet (where the Restart Session Controller is called) is to let the portlet

    write a session attribute and let the servlet read it.The Restart Session Controller then reads the same attribute and reset it.

    So to summarize:

    1. The JSP edit page communicates that a restart is required by adding aparameter.

    2. The processActionmethod reads this parameter, sets a render parameterto a random value and changes the portlet mode to VIEW.

    3. The doViewmethod reads the render parameter, and if it is set anddifferent from the saved value, it sets a session attribute.

    4. The Restart session controller reads the session attribute and restarts thesession if necessary.

    In Figure 30setting and reading session attributes is done using method calls.The implementation of these is in the ClipJavaPortletWithEdit class and ispresented in Figure 31. There are two setter methods and two gettermethods, making it possible to call them from doViewand the Restart Session

    Controller (i.e. the servlet), using a RenderRequest/RenderResponsepairresp. a HttpServletRequest.

    It is important to note, that session attributes are shared among all portlets,so if you just write a session attribute ShouldRestart, you might risk thatanother portlet restarts its session.

    To avoid this, we augment the attribute name with an identifier uniquelyidentifying the portlet instance: The clipJavaPortletclass offers a methodgetPortletIDfor exactly this purpose so we can use this method in thesession attribute methods taking a RenderRequest/RenderResponsepair.

    Unfortunately, the getPortletIDmethod requires a RenderRequest (becauseit uses getNameSpace) so we cannot call this from the Restart SessionController, but only from doView. This problem has been solved in the clippingframework in the following way: When the ClipJavaPortletclass embeds theservlet in an IFrame it calls the getPortletIDmethod to retrieve an id, andpasses this id as a parameter to the servlet. This means that we are able to

    TIPS AND TRICKS 49

    retrieve the id in the methods, which take an HttpServletRequest by getting

  • 8/12/2019 Clipping Programmer Guide

    51/54

    retrieve the id in the methods, which take an HttpServletRequestby gettingthis parameter.

    public static Object getSessionAttr(HttpServletRequest request,String name) {

    final HttpSession session = request.getSession();final String portletId= request.getParameter(ClipServlet.PORTLET_PARAMETER_NAME);

    return session.getAttribute(name + portletId);}

    public static void setSessionAttr(HttpServletRequest request,String name,Object value) {

    final HttpSession session = request.getSession();final String portletId= request.getParameter(ClipServlet.PORTLET_PARAMETER_NAME);

    session.setAttribute(name + portletId, value);}

    protected Object getSessionAttribute(RenderRequest request,RenderResponse response,String name) {

    final PortletSession session = request.getPortletSession();final String portletId = getPortletID(response);return session.getAttribute(name + portletId,

    PortletSession.APPLICATION_SCOPE);}

    protected void setSessionAttribute(RenderRequest request,RenderResponse response,String name,Object value) {

    final PortletSession session = request.getPortletSession();final String portletId = getPortletID(response);session.setAttribute(name + portletId, value,

    PortletSession.APPLICATION_SCOPE);}

    Figure 31: Session Attribute Methods

    50 CLIPPING

    The restart session controller is presented in Figure 32. It gets the attribute

  • 8/12/2019 Clipping Programmer Guide

    52/54

    p g gfrom the session by calling the getSessionAttribute, which we saw in Figure31. If this returns true, it will reset the attributes value to false and returntrue, which will tell the servlet to restart the clip.

    package clippingapi;

    import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;importcom.kapowtech.robosuite.client.clip.version1.api.RestartSessionController;

    public class MyRestartSessionControllerimplements RestartSessionController {public boolean shouldRestartSession(HttpServletRequest request,

    HttpServletResponse response){final Boolean shouldRestart= (Boolean) ClipJavaPortletWithEdit.getSessionAttribute(

    request,ClipJavaPortletWithEdit.SHOULD_RESTART);

    if (shouldRestart) {ClipJavaPortletWithEdit.setSessionAttribute(

    request,ClipJavaPortletWithEdit.SHOULD_RESTART,

    Boolean.FALSE);}return shouldRestart;

    }}

    Figure 32: The Restart Session Controller

    INDEX 51

    Index

  • 8/12/2019 Clipping Programmer Guide

    53/54

    Index

    Aadditional input objects, 15

    additional input objects provider,11, 14

    additional ouput objects handler,12, 34

    AJAX, 34

    BBEA WebLogic Portal, 9, 37

    Cchanges, 11class

    ClipJavaPortlet, 13

    clip configuration file, 9

    clipping logic, 9

    clipping robot, 6

    ClipRequest, 10, 17, 20

    ClipResponse, 11

    command, 10

    controller, 12, 43

    restart session, 12, 43

    controllers

    restart session, 43

    cookies, 10, 11

    Ddistribution policy provider, 12, 26,

    28

    DistributionPolicy, 29

    DistributionPolicyProvider, 28

    doEdit, 13

    doHelp, 13, 45

    doView, 13, 48

    Eerror handler, 12, 37

    error handling, 37

    extension point, 11

    Ffilter, 12, 40

    header, 12, 40

    Hhandler, 12, 34

    additional input objects, 12, 34

    error, 12, 37

    handlers

    error, 37

    header, 10, 11

    header filter, 12, 40http header, 10

    HttpServletRequest, 16

    HttpServletResponse, 16

    Iinternationalization, 22

    JJavaScript, 34

    JSP, 38, 46

    JSP error page, 38

    JSP page, 36

  • 8/12/2019 Clipping Programmer Guide

    54/54