Transformations

A transformation is a HATS resource that controls how a host screen is transformed. In a rich client application, transformations are Java™ classes that extend from the com.ibm.hats.rcp.ui.transformations.RcpTransformation class. This class extends from the Standard Widget Toolkit (SWT) Composite class, which is a UI control that contains other controls. A transformation can contain SWT widgets, host components (ComponentRendering composites), DefaultRendering composites, global variable controls, macro controls, and host and application keys. Because a transformation is an SWT composite, standard SWT widgets can also be added it.

Some common uses of transformations are:

Editing transformations

Transformations are found in the HATS Projects view under Rich Client Content > Transformations.

Assuming the Java client application editor (VE) feature, also known as the Visual Editor, is installed with Rational® SDP, you can use it to edit your transformations. In addition to the information in this section, see Editing transformations for rich client projects in the HATS User's and Administrator's Guide.

You can use the Palette view in the Visual Editor to add new controls to a transformation. Besides being able to add standard SWT controls, you can also add HATS-specific controls, such as a ComponentRendering composite. Adding a control from the palette generates Java code in the transformation. The generated code references a specific class, as shown in Table 7, based on the selected palette item. The palette items are available in the HATS drawer of the palette:

Table 7. HATS-specific controls and corresponding classes
HATS-specific Palette tools Class generated in code
Component com.ibm.hats.rcp.transform.ComponentRendering
Default Rendering com.ibm.hats.rcp.transform.DefaultRendering
Macro Key com.ibm.hats.rcp.transform.MacroKey
Global Variable com.ibm.hats.rcp.transform.GlobalVariableControl
Host Key com.ibm.hats.rcp.transform.HostKey
Application Key com.ibm.hats.rcp.transform.ApplicationKey

More information about the classes listed in this table is provided in the following section.

HATS-specific controls

In addition to adding standard SWT controls, you can add HATS-specific controls, such as a ComponentRendering composite, to a transformation. The following sections describe these HATS-specific controls.

The ComponentRendering class

A ComponentRendering composite is a specialized UI control that transforms a given host screen region using a specified component, widget, and settings. Based on the selected HATS widget, SWT widgets are generated and placed on the ComponentRendering composite. The following code example illustrates the concept:

ComponentRendering componentRendering = new ComponentRendering(this, SWT.NONE);
   componentRendering.setScreenCapture(<fully qualified transformation 
                                                    class name>.screenCapture);
   componentRendering.setComponent("<fully qualified component class name>");
   componentRendering.setComponentSettings
                            (new com.ibm.hats.common.StringableProperties(""));
   componentRendering.setWidget("<fully qualified widget class name>");
   componentRendering.setWidgetSettings
           (new com.ibm.hats.common.StringableProperties("<widget settings>"));
   componentRendering.setRegion(new com.ibm.hats.transform.regions.
                    BlockScreenRegion(start_row, start_col, end_row, end_col));
   componentRendering.setApplyTextReplacement(true);
   componentRendering.setApplyGlobalRules(true);
Note:
The setWidgetSettings and setComponentSettings methods take a standard java.util.Properties object as the parameter. You can construct a Properties object and populate using the setProperty(String,String) method, as opposed to using the HATS StringableProperties class.

The DefaultRendering class

A DefaultRendering composite is a specialized UI control that transforms a given host screen region using a rendering set. A rendering set is defined in the Rendering tab of the Project Settings editor. Refer to Default Rendering in the HATS User's and Administrator's Guide for more information on defining rendering sets. Based on the selected rendering set, SWT widgets are generated and placed on the DefaultRendering composite. The following code example illustrates the concept:

DefaultRendering defaultRendering = new DefaultRendering(this, SWT.NONE);
defaultRendering.setScreenCapture(this.screenCapture);
defaultRendering.setRenderingSetName("main");
defaultRendering.setApplyTextReplacement(true);
defaultRendering.setApplyGlobalRules(true);
defaultRendering.setRegion
         (new com.ibm.hats.transform.regions.BlockScreenRegion(1,1,24,80));

The MacroKey class

The com.ibm.hats.rcp.transform.MacroKey class represents an individual macro either as a button (org.eclipse.swt.widgets.Button class) or a link (org.eclipse.swt.widgets.Link class). The following code sample shows a MacroKey that is displayed as a button:

macroKey = new MacroKey(this, SwtTransformationConstants.BUTTON);
macroKey.setText("macro_1");
macroKey.setMacroName("macro_1");
macroKey.addSelectionListener(new org.eclipse.swt.events.SelectionListener() {
    public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) {
        com.ibm.hats.runtime.services.ISessionService 
                               sessionService = getSessionService();
        if (sessionService != null) {
            sessionService.playMacro(macroKey.getMacroName());
        }
    }
    public void widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent e) {
    }
});

The GlobalVariableControl class

The com.ibm.hats.rcp.transform.GlobalVariableControl class represents a global variable either as a static text (org.eclipse.swt.widgets.Label class) or an input field (org.eclipse.swt.widgets.Text class). The following code sample shows a GlobalVariableControl that displays a global variable as an input field:

gvControl = new GlobalVariableControl(this, SwtTransformationConstants.TEXT);
gvControl.setInitialValueFromGlobalVariable(true);
gvControl.setUseAllIndices(true);
gvControl.setGlobalVariableName("userName");
gvControl.setShared(false);
gvControl.setSeparator("");
gvControl.setPasswordField(false);
gvControl.setIndex(0);
gvControl.setGlobalVariableIndexed(false);
Note:
You can read and change global variables from a transformation without using the GlobalVariableControl class. Please see Setting and retrieving global variable values for more details.

The HostKey class

The com.ibm.hats.rcp.transform.HostKey class represents an individual host key either as a button (org.eclipse.swt.widgets.Button class) or a link (org.eclipse.swt.widgets.Link class). Multiple keys cannot be included in one HostKey instance. If you need to have two or more keys, define multiple HostKey instances. The following code sample shows a HostKey that is displayed as a button that sends [PF1] to the host when pressed:

hostKey = new HostKey(this, SwtTransformationConstants.BUTTON);
hostKey.setText("F1");
hostKey.setCommand("[pf1]");
hostKey.addSelectionListener(new org.eclipse.swt.events.SelectionListener() {
    public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) {
        com.ibm.hats.runtime.services.ISessionService 
                                    sessionService = getSessionService();
        if (sessionService != null) {
            sessionService.sendCommand(hostKey.getCommand());
        }
    }
    public void widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent e) {
    }
});

The ApplicationKey class

This is the class that represents an individual application key either as a Button or a Link. Multiple keys cannot be included in one ApplicationKey class. If you need to have two or more keys, define multiple ApplicationKey instances. The following code sample shows an ApplicationKey that is displayed as a link and sends a disconnect command to the HATS runtime when clicked:

applicationKey = new ApplicationKey(this, SwtTransformationConstants.LINK);
applicationKey.setText("<a>Disconnect</a>");
applicationKey.setCommand("disconnect");
applicationKey.addSelectionListener(new org.eclipse.swt.events.SelectionListener() {
    public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) {
        com.ibm.hats.runtime.services.ISessionService 
                                     sessionService = getSessionService();
        if (sessionService != null) {
            sessionService.sendCommand(applicationKey.getCommand());
        }
    }
    public void widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent e) {
    }
});

Transformation classes

Table 8 lists the methods that can be overridden in a transformation class.

Table 8. RcpTransformation methods
Method Description
getApplicationKeypadDisplayInfo() Returns an IApplicationKeypadDisplayInfo object that controls how, and if, the application keypad is displayed. This method enables the application keypad to be customized for this transformation. Returning null from this method indicates that the default application keypad, based on the application's default settings, should be displayed.
getAutoAdvanceOrderer() Returns an IAutoAdvanceOrderer object that controls how, and if, auto advance is performed. The default implementation is to return null, indicating that the system should decide the auto advance handler to use from the project settings.
getDefaultMonospacedFont() Allows you to override the default monospaced font at the transformation level. See Overriding the default monospaced font for an example that uses this method.
getHostKeypadDisplayInfo() Returns an IHostKeypadDisplayInfo object that controls how, and if, the host keypad is displayed. This method enables the host keypad to be customized for this transformation. Returning null from this method indicates that the default host keypad should be displayed based on the application's default settings. Refer to Customizing the host keypad for examples that use this method.
getOiaDisplayInfo() Returns an IOiaDisplayInfo object that controls how, and if, the OIA is displayed. This method enables the OIA to be customized for this transformation. Returning null from this method indicates that the default OIA should be displayed based on the application's default settings.
getToolbarDisplayInfo() Returns an IToolbarDisplayInfo object that controls how, and if, the toolbar is displayed. This method enables the toolbar to be customized for this transformation. Returning null from this method indicates that the default toolbar should be displayed based on the application's default settings.
handlePreSubmit() This method is called just prior to a command being submitted. Refer to Validating input on a transformation for examples that use this method.
handlePostSubmit() This method is called just after a command has been submitted.
isInitialFocusAtCursorPosition() Identifies whether the initial focus is placed at cursor position. For more information, refer to the description of the Initial cursor position client setting in the HATS User's and Administrator's Guide.
needsAutoAdvanceSupport() Identifies whether the auto advance function for this transformation is enabled. For more information, refer to the description of the Enable automatic field advance client setting in the HATS User's and Administrator's Guide.
preRender() This method is called prior to the render() method being called.
postRender() This method is called after the render() method is called and the rendering of the transformation is complete.
setScreenCapture() Sets the screen capture for use while editing ComponentRendering and DefaultRendering in the HATS Toolkit. componentRendering.setScreenCapture( <fully qualified transformation name>.screenCapture);
needsArrowKeyNavigationSupport() Identifies whether the arrow key navigation support function for this transformation is enabled. For more information refer to the Arrow key navigation support client setting in the HATS User's and Administrator's Guide

Samples

Sending a key from a button

Using the palette, add a SWT Button widget to your transformation. Override the postRender() method of the RcpTransformation class.

Note:
To override the postRender() method, follow these steps:
  1. Right-click in the Source editor pane.
  2. Select Source > Override/Implement Methods.
  3. Under RcpTransformation, check postRender().
  4. Click OK.

Add the following code to the postRender() method:

final RcpContextAttributes attrs = (RcpContextAttributes) getContextAttributes();
		button.addSelectionListener(new SelectionListener()
		{
			public void widgetDefaultSelected(SelectionEvent event) {				
			}
			
			public void widgetSelected(SelectionEvent event) {
				attrs.getSessionService().sendCommand("[enter]");
			}
		});

Updating an input field after the user selects a SWT List widget item

Using the palette, add a SWT List widget to your transformation. Override the postRender() method of the RcpTransformation class. Add the following code to the postRender() method:

//retrieve a model adapter that is bound to a host field at position 1527.
//assuming that the list widget will update the field at this position on the host.
final IModelAdapter modelAdapter = factory.getFieldAdapter(1527);

		list.addSelectionListener(new SelectionListener()
		{
			public void widgetDefaultSelected(SelectionEvent event) {				
			}
			
      //when an item in the list is selected, update the field at position 1527 
      //with the value of selected item.
			public void widgetSelected(SelectionEvent event) {
				modelAdapter.setValue(list.getData(list.
                  getItem(list.getSelectionIndex())).toString());
			}
		});

Setting the value of a global variable from a transformation

The following code sample shows how to prompt a user for a value, in the case the prompt is asking for a customer number, and then set the customerNumber global variable with this value.

Button button = new Button(this, SWT.NONE);
button.setText("Prompt for command");
button.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() {

public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) {
    InputDialog dialog = new InputDialog(getShell(), "Prompt", 
                                         "Enter a customer number:", "", null);
    if (dialog.open() == InputDialog.OK) {
        String value = dialog.getValue();
        getSessionService().getParameterDataAccessService().
                setParameterValue("hatsgv_customerNumber",value);
    }
}
 });
Note:
The HATS runtime is unaware of the new global variable value, set by the setParameterValue() method call, until the form is submitted.

Setting and retrieving global variable values

The following example sets a value to the non-shared global variable named "myGlobalVariable":

getSessionService().getParameterDataAccessService().setParameterValue
                              ("hatsgv_myGlobalVariable", "some new value");

The following example retrieves a value from the non-shared global variable with the same name.

// This will return some string or null
String str = getSessionService().getParameterDataAccessService().
                                getParameterValue("hatsgv_myGlobalVariable"); 
Note:
If the global variable is shared, replace hatsgv_myGlobalVariable with hatssharedgv_myGlobalVariable in the preceding examples.

Validating input on a transformation

All HATS rich client transformations implement the com.ibm.hats.rcp.transform.IPrePostSubmitHandler interface which provides the ability to control what happens immediately before and after a request is made to the HATS runtime when a specific transformation is displayed. The primary function of this interface is to give you the opportunity to validate values supplied on a transformation by a user before a request is made to the HATS runtime. If a problem is found with one or more of the user's responses, you have the ability to cancel the request, alter the parameters, alter the command, and display a message to the user.

Note:
Validation should be performed in the handlePreSubmit method of your transformation class, since this method is called just before a request is made to the HATS runtime. Once the request has been made, you cannot alter or cancel it.

The following sample shows how to perform validation on input provided by the user. If an invalid value is specified, the submission is cancelled and a message is displayed to the user.

If the handlePreSubmit method has not been overridden in your transformation class, following these steps:

  1. Right-click on the source of the transformation (in the Java Editor) and select Source > Override/Implement Methods
  2. Expand the RcpTransformation node and place a check next to handlePreSubmit(CommandEvent) and click OK.
  3. A stub method is inserted into the transformation source (based on your Java code style preferences, your sample code may not look like the following):
        public void handlePreSubmit(CommandEvent event) {
            // TODO Auto-generated method stub
            super.handlePreSubmit(event);
        }

The following code sample shows how to perform a range check on a hypothetical part quantity field. If the quantity supplied by the user is not greater than 500, a message is displayed and the submission is cancelled. It is assumed that this field resides at row 4, column 20 of the host screen that is being transformed by this transformation. Replace your existing handlePreSubmit(CommandEvent) method with the following:

    public void handlePreSubmit(CommandEvent event) {
        // Avoid validation if the user is attempting to disconnect the session
        if (event.getCommand().equals(RuntimeConstants.CMD_DISCONNECT)) {
            return;
        }

        // Retrieve the value of the "quantity" field using the 
        // IHostScreenDataAccessService interface
        // (which is accessed by calling the getHostScreenDataAccessService() 
        // method on the session service)
        // The getFieldValue() method takes a linear screen position and a 
        // length. The 
        // Component.convertRowColToPos() method converts a row, column value 
        // into a linear screen position. 
        // "5" indicates the length of the field.
        String quantityString = getSessionService().
                            getHostScreenDataAccessService().
                            getFieldValue(Component.convertRowColToPos(4, 20, 
                            getHostScreen().getSizeCols()), 5);

        // Convert the numeric string into an int
        int quantity = 0;
        try {
            quantity = Integer.parseInt(quantityString);
        } catch (Exception ex) {
        }

        // Check to ensure the quantity entered is greater than 500
        if (quantity < 500) {
            // Display a message to the user indicating what the problem is
            MessageDialog.openError(getShell(), 
                            getSessionService().getApplication().getName(),
                    "You must order at least 500 units.");

            // Cancel the event (this prevents the request from being made)
            event.setCanceled(true);
        }
    }

Customizing the host keypad

Customizing the application keypad

The application keypad can be customized at the transformation-level by overriding the getApplicationKeypadDisplayInfo() method of the transformation and returning an object of type IApplicationKeypadDisplayInfo.

The following code sample shows how the getApplicationKeypadDisplayInfo() method can be overwritten to expose "Page down" and "Page up" to the application keypad when this transformation is applied:

public IApplicationKeypadDisplayInfo getApplicationKeypadDisplayInfo() {
 // Define the extra keys
 	KeypadKey[] extraKeys = new KeypadKey[] { 
                          new KeypadKey(ECLConstants.PAGEDWN_STR, "Page Down"), 
                          new KeypadKey(ECLConstants.PAGEUP_STR, "Page Up") };

// Construct a new ApplicationKeypadDisplayInfo object using the project-level 
// settings and the new keys
   Application app = getSessionService().getApplication();
   Properties appKeypadSettings = app.getDefaultSettings
      (ApplicationKeypadConstants.SETTINGS_ID);
   ApplicationKeypadDisplayInfo info = new ApplicationKeypadDisplayInfo
      (appKeypadSettings, extraKeys);

  return info;
}

To customize the application keypad at the application-level, the getApplicationKeypadDisplayInfo() method of your transformation view class "MainView" can be overwritten. See Transformation view for more information.

Overriding the default monospaced font

This code example causes a smaller font size to be used if the host screen has 132 columns, instead of the standard 80:

public Font getDefaultMonospacedFont() {
    if (getHostScreen() != null) {
        if (getHostScreen().getSizeCols() == 132) {
            return FontManager.getInstance(getDisplay()).getFont("Courier New", 8, 0);
        }
    }

    return null;
}

Integrating other user interface widgets

The samples in this section require that you add the org.eclipse.emf.common plug-in to your rich client project's dependency list. To do this:

  1. Open the plug-in manifest file for your project.
  2. On the Dependencies tab, click Add and select org.eclipse.emf.common.
  3. Save the file.

Binding a SWT Slider widget to a host input field

A slider is a control that enables a user to select a numeric value from a range of values. For example, on the OS/400® main menu, you can use the slider to make a selection.

Using the palette, add a SWT Slider widget to your transformation. Override the postRender() method of the RcpTransformation class. Add the following code to the postRender() method:

// The following code creates 2 adapters :  a FieldAdapter that adapts to a 
// Host Screen field located at a specific position, an IControlAdapter that 
// adapts to a Slider widget, and bind these 2 adapters so that when slider 
// selection is changed, its selection value is updated in the model, and 
// when the data in the model is changed, the slider selection is updated.
// In this example, we bind to the a host screen field located at 
// position (20,007).
    final RcpContextAttributes attrs = (RcpContextAttributes) 
                                                    getContextAttributes();
		HostScreenDataModelManager dataModelManager = attrs.
                                           getHostScreenDataModelManager();
		HostScreenModelAdapterFactory factory = (HostScreenModelAdapterFactory) 
                                  dataModelManager.getModelAdapterFactory();
		final IModelAdapter modelAdapter = factory.getFieldAdapter(1527);
		IControlAdapter sliderAdapter = new SliderWidgetAdapter(slider,dataModelManager);
		dataModelManager.bindControlToModel(sliderAdapter, modelAdapter);

Example of the SliderWidgetAdapter class

//This class allows the slider widget to update a host field with its values and
//also update its value from a host field.
public class SliderWidgetAdapter implements IControlAdapter {

	private Slider slider;  //the target slider widget.
	private IDataModelManager dataModelManager; //handles updating values in the model
     	 
	public SliderWidgetAdapter(Slider slider,IDataModelManager dataModelManager) {
		this.slider = slider;
		this.dataModelManager = dataModelManager;

		//create a SelectionListener such that when the value of the slider
		//is changed, it updates the host field.
		this.slider.addSelectionListener(new SelectionListener()
		{
			public void widgetDefaultSelected(SelectionEvent event) {
			}

			public void widgetSelected(SelectionEvent event) {
				updateModel();
			}		 		 		 
		});
	}
     	 
	//this method calls the updateModel from the IDataModelManager to
	//update the host field.
	private void updateModel() {
		if ( dataModelManager != null )
			dataModelManager.updateModel(this);
	}
     	 
	//return the value of slider selection.
	public String getValue() {
		return slider.getSelection() + "";
	}

	//this method updates the slider selection from a value. This method
	// is called when the value of a host field is changed.
	public void setValue(String value) {	
		try {		 		 		 		 		 
			slider.setSelection(Integer.parseInt(value));
		}
		catch ( NumberFormatException e ) {
			slider.setSelection(0);
		}
	}
}