Remote API

Package com.yworks.remote provides classes and interfaces that facilitate communication with HTTP services.

Class RoundtripHandler

The central class that offers easy-to-use server round-tripping support is the RoundtripHandler. The round-trip handler can be used both for stateless and stateful web applications and provides server response handling as well as various properties and methods that influence the data that is transferred to the server.

Class RoundtripHandler can be used for complete server round-trips and one-way data transfers (e.g. loading a graph from the server or saving a graph on the server). The RoundtripHandler has two properties that configure transfer directions:

send:Boolean
Description Whether to transfer the serialized graph instance to the server
update:Boolean
Description Whether to update the current graph instance by deserializing the GraphML data received from the server.

Customizing Graph Serialization

If the send property is true, the graph instance currently displayed in the GraphCanvasComponent that was passed to the RoundtripHandler will be serialized to a GraphML string and transferred to the server. The data send to the server and the graph serialization process can be easily configured using the following methods and properties:

Specifying the transferred data
API
sendOptions:uint
Description The options specifying the graph item data that will be transferred to the server. The options are given as a bitwise combination of OPTION_COPY constants defined in GraphCanvasComponent.
Additional POST or GET parameters
API
additionalParameters:Object
Description An object containing additional GET or POST parameters that will be transferred to the server.
Custom serializer implementations
API
addSerializer(serializer:ISerializer):void
Description Add a serializer that will be used by the input GraphMLIOHandler. Note that ISerializer implementations also can be retrieved using the lookup mechanism of model items. See the section called “General Serializer and Deserializer Concepts” for details on customizing GraphML serialization.
Accessing the GraphMLIOHandler
API
outputIOHandler:GraphMLIOHandler
Description The GraphMLIOHandler that will be used for graph serialization. A custom set of GraphML output handlers can be used for serialization by either setting a configured GraphMLIOHandler or by adding/removing output handlers to/from the GraphMLIOHandler instance used by the RoundtripHandler.

Additional GET or POST parameters to be sent to the server can be added using the additionalParameter property like shown in Example 5.1, “Using additional POST/GET parameters”. The exampe code will add the parameters "name1" and "name2" with the values "value1" and "value2", respectively.

Note that the following parameter names are reserved for internal use: graph, graphEncoding, and encodeURIComponent.

Example 5.1. Using additional POST/GET parameters

// adding POST or GET parameters
// results in a request like
// http://foo.bar.com/serviceName?name1=value1&name2=value2
var params:Object = new Object();
params.name1 = "value1";
params.name2 = "value2";
roundtripHandler.additionalParameters = params;

The sendOptions define which data will be sent in the GraphML in addition to the structure and layout information. The options are defined in the OPTION_COPY constants of GraphCanvasComponent and can be combined by bitwise OR. The OPTION_COPY constants are listed in Table 5.1, “Constants to be used with updateOptions and sendOptions”.

Table 5.1. Constants to be used with updateOptions and sendOptions

Option Affected Data
OPTION_COPY_NONE No additional data will be (de)serialized
OPTION_COPY_NODE_DATA Data which is added as mapper attribute to a node
OPTION_COPY_NODE_STYLE Node styles
OPTION_COPY_EDGE_DATA Data which is added as mapper attribute to an edge
OPTION_COPY_EDGE_STYLE Edge styles
OPTION_COPY_NODE_AND_EDGE_DATA Data which is added as mapper attribute to a node or edge
OPTION_COPY_LABELS Labels without style information
OPTION_COPY_LABEL_STYLE Labels together with their style information
OPTION_COPY_PORT_DATA Data which is added as mapper attribute to a port
OPTION_COPY_PORT_STYLE Port styles
OPTION_COPY_PORT_MODEL Port location models
OPTION_COPY_GRAPH_DATA Data which is added as mapper attribute to the graph
OPTION_COPY_NODE_USER_TAGS User tags which are associated with a node
OPTION_COPY_EDGE_USER_TAGS User tags which are associated with an edge
OPTION_COPY_NODE_LABEL_USER_TAGS User tags which are associated with a node label
OPTION_COPY_EDGE_LABEL_USER_TAGS User tags which are associated with an edge label
OPTION_COPY_PORT_USER_TAGS User tags which are associated with a port
OPTION_COPY_USER_TAGS All user tags
OPTION_COPY_TABLE_LAYOUT The layout of ITables
OPTION_COPY_TABLE_STYLE The style of ITables
OPTION_COPY_TABLES The layout and style of ITables
OPTION_COPY_ALL All data will be (de)serialized

Customizing Graph Deserialization and Update

If the update property is true, the current graph instance will be updated using the deserialized GraphML data contained in the server response. Deserialization and the update process can be configured using the following properties and methods:

Specifying the transferred data
API
updateOptions:uint
Description The options specifying the graph item data that will be updated from the deserialized server response. The options are given as a bitwise combination of OPTION_COPY constants defined in GraphCanvasComponent.
Custom deserializer implementations
API
addDeserializer(deserializer:IDeserializer):void
Description Add a deserializer that will be used by the input GraphMLIOHandler.
Accessing the GraphMLIOHandler
API
inputIOHandler:GraphMLIOHandler
Description The GraphMLIOHandler that will be used for graph deserialization. A custom set of GraphML input handlers can be used for deserialization by either setting a configured GraphMLIOHandler or by adding/removing input handlers to/from the GraphMLIOHandler instance used by the RoundtripHandler.
Animated update
API
animate:Boolean
Description Whether the optional update of the graph instance should be visualized as an animation.

The updateOptions define which data will be updated in the GraphML in addition to the structure and layout information. The options are defined in the OPTION_COPY constants of GraphCanvasComponent and can be combined by bitwise OR. The OPTION_COPY constants are listed in Table 5.1, “Constants to be used with updateOptions and sendOptions”.

Support for folded graphs

Folded graph (See also Chapter 3, Graph Hierarchies) can contain more states than visible in the current graph, contents of a closed group node, for instance. Generally, there are two ways to send a folded graph to the client: Sending the folder nodes as folders together with their nested graphs (the folder contents) or sending the closed folder nodes as "normal" nodes. The first case is the RoundtripHandler's default. For some use cases, e.g. layout roundtrips, on might want to send only the currently visible state (the second case). This can be achieved by setting RoundtripHandler's localViewMode to true.

Determining whether to send the current view or the master of a folded graph
API
localViewMode:Boolean
Description If set to false (default) the RoundtripHandler will transfer all states of the managed graph. If true only the current view state will be transferred.

Transfer of additional data

Additional mapped data (see also the section called “Mapping Data to Graph Elements”) can also be transferred by the RoundtripHandler. However, the RoundtripHandler has to be made aware of the existence of the mapped data. The RoundtripHandler method addMapperAttribute() allows to add custom graph item attributes which will be considered for both communication directions:

Adding graph item attributes to a RoundtripHandler
API
function addMapperAttribute(tag:Object,
        name:String = null,
        scope:String = GraphMLConstants.SCOPE_NODE,
        contentType:String = GraphMLConstants.TYPE_STRING):void
Description Adds a graph item attribute with the given attribute name for input and output. An IMapper instance has to be registered with the current graph's mapper registry for the given tag.

Alternatively, IMapper's default implementation, DictionaryMapper can be configured to be automatically transferred by the RoundtripHandler. To support this feature the RoundtripHandler's autoWriteMapperData and/or autoReadMapperData properties have to be enabled (which they are by default).

DictionaryMapper constructor parameters for automatic transfer
API
function DictionaryMapper(
        weakKeys:Boolean=false,
        name:String=null,
        scope:String=null,
        valueType:String=null,
        autoSerialize:Boolean=false )
Description Constructor of the DictionaryMapper. name: the name for the attribute in the GraphML. scope and valueType: the scope and type for the attribute as defined in the GraphMLConstantsSCOPE and TYPE constants. The autoSerialize parameter has to be set to true to enable auto (de)serialization for this mapper.
Configuring the RoundtripHandler for automatic transfer of attributes
API
autoWriteMapperData:Boolean
autoReadMapperData:Boolean
Description The properties which enable automatic serialization and deserialization on the RoundtripHandler.

The following example shows how to set up a mapper for automatic transfer:

Example 5.2. Automatic transfer of additional data

// set up the mapper to be auto-serialized with the name "my-map",
// the contents are of the type String and the mapper is bound to nodes
var map:IMapper = new DictionaryMapper(true, "my-map", GraphMLConstants.SCOPE_NODE, GraphMLConstants.TYPE_STRING, true);
// graph is of type IGraph
graph.mapperRegistry.addMapper("my-map", map);

// set up the handler.
// handler is of type RoundtripHandler
// to transfer node data, the options have to be
// at least GraphCanvasComponent.OPTION_COPY_NODE_DATA
handler.sendOptions = GraphCanvasComponent.OPTION_COPY_ALL;
handler.updateOptions = GraphCanvasComponent.OPTION_COPY_ALL;
// enable auto (de)serialization
handler.autoReadMapperData = true;
handler.autoWriteMapperData = true;

Detailed information about how to enable client-server roundtripping of custom graph item attributes can be found in a knowledge base article about this topic.

User tags (see also the section called “User Tags”) are automatically transferred if the sendOptions and/or updateOptions are set to transfer user tags (see also Table 5.1, “Constants to be used with updateOptions and sendOptions”).

Handling IDs with the RoundtripHandler

Proper IDs are needed for client-server communication so the client graph can be incrementally updated and the server knows which graph items to act upon. These IDs are stored in IMappers which are always registered with DefaultGraph's mapper registry. The mappers can be obtained using the keys DefaultGraph.MAPPER_KEY_NODE_2_ID and DefaultGraph.MAPPER_KEY_EDGE_2_ID. More information about handling IDs can be found in a knowledge base article about this topic.

Custom Error Handling

Class RoundtripHandler allows to customize error handling for any errors that might occur during client-server communication. Error handling can be configured both globally and for single RoundtripHandler instances. The properties of class RoundtripHandler that allow to register custom error handling delegates are listed below:

Global fault handler
API
[static] globalFaultEventHandler:Function
Description The fault event delegate that is used by all RoundtripHandler instances, unless a non-static faultEventHandler is registered.
Global custom error handler
API
[static] globalCustomErrorHandler:Function
Description The custom error handler that is used by all RoundtripHandlerinstances, unless a non-static customEventHandler is registered.
Local fault handler
API
faultEventHandler:Function
Description The fault event handler that will be used by this instance instead of the globalFaultEventHandler.
Local fault handler
API
customErrorHandler:Function
Description The custom error handler that will be used by this instance instead of the globalCustomErrorHandler.
Handling Fault Events

The fault event handler is called when the server request performed by the RoundtripHandler failed (e.g. an IOError or SecurityError occured). Example 5.3, “Custom Fault Event Handler” shows an example custom fault event handler and how it is registered globally so it will be called by all RoundtripHandler instances that do not have an individual handler registered.

Example 5.3. Custom Fault Event Handler


/**
 * Custom fault handler that displays the error message in an alert popup.
 */ 
private function faultHandler( evt:FaultEvent ):void {
    var titleString:String = "Service request failed";
    var buf:String = "Error details: \n\n";
    buf += evt.fault.faultDetail;
    Alert.show( buf, titleString );
    CursorManager.removeBusyCursor();
}

private function init():void {
    // register the custom fault handler
    RoundtripHandler.globalFaultEventHandler = faultHandler;
}

Handling Custom Errors

In addition to fatal server communication errors, class RoundtripHandler also allows to handle error messages generated by servlet requests using a custom error format. The format expected by the default custom error handler implementation is given below.

Default Service Error Format

<?xml version="1.0" encoding="UTF-8"?>
<response>
  <errors>
    <error>
      message
    <error>
  </errors>
</response>

The roundtrip support classes that are available both in the Java and .NET yFiles FLEX server libraries will generate error messages corresponding to the above format, if these classes are used for reporting errors to the client.

Example 5.4, “Custom Service Error Handler” shows an example handler that parses the xml result, displays the first error in an alert window and traces alle error messages.

Note

If normal processing of the result event should be prevented because the response contains an error message instead of the expected result, stopImmediatePropagation() has to be called on the event instance.

Example 5.4. Custom Service Error Handler

private function handleCustomError( evt:ResultEvent ):void {
    var xml:XML = XML( evt.result );
    var errors:XMLList = xml.errors;
    if( errors.length() > 0 ) {
        Alert.show( "ERROR: \n"+errors.error[ 0 ].toString() );
        for each( var error:XML in errors.children() ) {
                trace(error.toString());
        }
        // prevent any further processing of the result event.
        evt.stopImmediatePropagation();
        CursorManager.removeBusyCursor();
        Application.application.enabled = true;
    }
}

Encoding GraphML Data

Class RoundtripHandler offers two properties that influence the format that is used for transferring the GraphML serialization of the client graph to the server:

Compression
API
compress:Boolean
Description Whether zlib-compression is applied to the GraphML string.
URI encoding
API
uriEncode:Boolean
Description Whether the encodeURIComponent function is applied to the GraphML string.

The default value of the compress property is true, because the compression will speed up the client-server communication substantially. Both the Java and .NET server libraries are able to handle zlib-compressed graphs sent from the client. The uriEncode property should only be enabled when compression is disabled. URI-encoding ensures the correct transfer of special characters if compression is turned off. If compression is turned on, the compressed bytes will be transfered as a Base64-encoded string.

Subclassing RoundtripHandler

For most scenarious, a configured RoundtripHandler will suffice for general server communication in a yFiles FLEX application. If the various public properties and methods provided by class RoundtripHandler do not allow enough flexibility, protected methods are provided that can be overriden for further customization:

createAction():ServerAction
Description Creates the ServerAction that specifies the request properties and the HTTP service URL that will be used by this RoundtripHandler.
createOutputIOHandler():GraphMLIOHandler
createInputIOHandler():GraphMLIOHandler
Description Create and configure the GraphMLIOHandler instance that will be used for graph serialization and deserialzation, respectively.
doUpdate(newGraph:IGraph):void
Description Performs the update of the current graph instance using the graph instance that was populated upon deserilaization of the server response.
createParameters():Object
Description Create the object containing all parameters (including the graph) that will be send to the server.

Using RoundtripHandler

Example 5.5, “Custom style round-trip” shows an example usage of class RoundtripHandler. The handler is configured such that a custom node style and a custom node attribute is transferred to the server. The server may modify the node attribute, the properties of the custom style, the graph structure, and/or the graph layout. After the server response has been deserialized, these modifications will be reflected in the graph instance currently displayed in the graph canvas that was passed to the RoundtripHandler constructor. Note that the ISerializer instance that serializes the custom node style will be retrieved by the GraphML framework from the custom style renderer through the look-up mechanism.

Example 5.5. Custom style round-trip

private static const CUSTOM_NODE_ATTRIBUTE:String = "customNodeAttribute";

// Create a round-trip handler for a GraphCanvasComponent instance.
// The handler will call a service called "customStyleRoundtrip".
roundtripHandler = new RoundtripHandler(graphCanvas, "customStyleRoundtrip");
// Add a custom style deserializer that will be used for deserialization of the
// server response.
roundtripHandler.addDeserializer(CustomStyleDeserializer.instance);
// Add a custom node attribute that will be serialized and deserialized.
roundtripHandler.addMapperAttribute(
  CUSTOM_NODE_ATTRIBUTE, CUSTOM_NODE_ATTRIBUTE, GraphMLConstants.SCOPE_NODE);
roundtripHandler.run();

Class DownloadHandler

The yFiles FLEX remote API offers a class tailored for server requests that are expected to be responded with a file stream which is to be saved locally.

The DownloadHandler sends a serialized graph to the server and shows a download dialog that allows the user to select a download destination. The serialized graph that is send in response for local storage may of course differ from the data that was send to the server. Example 5.6, “Using DownloadHandler” shows a basic usage example of class DownloadHandler.

Example 5.6. Using DownloadHandler

// The service URL that responds with a file transfer.
var serviceURL = "http://localhost:8080/download";

// Create a DownloadHandler for the service URL.
var downloadHandler:DownloadHandler = new DownloadHandler(serviceURL);

// Trigger file download.
// 'graphCanvas' is of type com.yworks.ui.GraphCanvasComponent.
downloadHandler.download(graphCanvas.graph, "theGraph.graphml");

Note

Starting with Flash Player 10, opening a file dialog is only allowed as consequence of a user interaction, e.g. after clicking a button or pressing a key. To ensure compatibility with Flash Player 10, we recommend to use DownloadHandler's download method only in a method which is called as a result from a user interaction. Calling download from e.g. the initialization method or a result handler from a HttpService will be treated as a security violation by Flash Player.

The yFiles FLEX server API already offers a servlet (Java) or a handler (.NET) which can handle requests sent by the DownloadHandler: the DownloadServlet and the DownloadHandler, respectively. See the section called “Class DownloadServlet” for details about the Java implementation or the section called “Class DownloadHandler” for the .NET version.

The yFiles FLEX API offers a similar class which can be used to save a GraphML file directly to the client's file system. See the section called “Class SaveHandler” for details.

Configuring DownloadHandler

The DownloadHandler delegates the serialization process to a GraphMLIOHandler. By default, this handler is created by the protected method createOutputIOHandler(). It is possible to customize the DownloadHandler (e.g. adding mapper attributes or using a JavaCompatGraphMLIOHandler) by replacing this output handler.

There are two ways to set a customized output handler: passing a RoundtripHandler instance as the constructor's optional parameter roundtripHandler or setting a GraphMLIOHandler instance to the outputIOHandler property. The RoundtripHandler can be configured as shown above in the section called “Class RoundtripHandler”. It is possible and convenient to use the same RoundtripHandler instance as used for roundtripping.

Constructor
API
DownloadHandler(downloadURL:String, roundtripHandler:RoundtripHandler = null)
Description The constructor can be used to pass a custom RoundtripHandler which serves as a factory to retrieve a configured GraphMLIOHandler as outputIOHandler.
IO Handler
API
outputIOHandler:GraphMLIOHandler
Description The GraphMLIOHandler that will be used for graph serialization. A custom set of GraphML output handlers can be used for serialization by either setting a configured GraphMLIOHandler or by adding/removing output handlers to/from the GraphMLIOHandler instance used by the RoundtripHandler.

Subclassing DownloadHandler

For common file download requests, class DownloadHandler can be used directly. Nevertheless, if custom event handling of download requests is needed, the DownloadHandler offers event listeners for all events that may occur during a download request may be overriden.

Class UploadHandler

Class UploadHandler makes it easy to load a GraphML file from the local file system into a yFiles FLEX application. Due to security restrictions, the process involves a server roundtrip. Therefore, loading a local file will not work in standalone applications. Example 5.7, “Using UploadHandler” shows a basic usage example of class UploadHandler.

Example 5.7. Using UploadHandler

  // The service URL that sends the uploaded file back to the client.
  var serviceURL = "http://localhost:8080/upload";

  // Create an UploadHandler for the service URL.
  var uploadHandler:UploadHandler = new UploadHandler(serviceURL);
  
  // Show a file chooser, upload the selected file,
  // send it back to the client, and display it in the canvas.
  uploadHandler.upload();
  

Note

Starting with Flash Player 10, opening a file dialog is only allowed as consequence of a user interaction, e.g. after clicking a button or pressing a key. To ensure compatibility with Flash Player 10, we recommend to use UploadHandler's upload method only in a method which is called as a result from a user interaction. Calling upload from e.g. the initialization method or a result handler from a HttpService will be treated as a security violation by Flash Player.

The yFiles FLEX server API already offers a servlet (Java) or a handler (.NET) which can handle requests sent by the UploadHandler: the UploadServlet and the UploadHandler, respectively. See the section called “Class UploadServlet” for details about the Java implementation or the section called “Class UploadHandler” for the .NET version.

The yFiles FLEX API offers a similar class which can be used to load a GraphML file from the client's file system. See the section called “Class LoadHandler” for details.

Configuring UploadHandler

Class UploadHandler offers various methods and properties for configuring the upload and deserialization process of the GraphML file:

additionalParameters:Object
Description An object containing additional GET or POST parameters that will be transferred to the server.
inputIOHandler:GraphMLIOHandler
Description The GraphMLIOHandler that will be used for graph deserialization.
roundtripHandler:RoundtripHandler
Description The RoundtripHandler instance that is used for the server roundtrip.
fileFilter:Array
Description A filter that determines the files that can be chosen with the file chooser.

Class ImageExportHandler

Class ImageExportHandler creates a bitmap representation of the graph canvas and uploads it to the server. The server is expected to respond with a file stream, so the exported image can be saved on the client. Example 5.8, “Using ImageExportHandler” shows a basic usage example of class ImageExportHandler.

Example 5.8. Using ImageExportHandler

  // The service URL that sends the uploaded file back to the client.
  var serviceURL = "http://localhost:8080/export";

  // Create an ImageExportHandler for the service URL.
  var exportHandler:ImageExportHandler = new ImageExportHandler(serviceURL);

  // Create export options
  var exportOptions:ExportOptions = ExportOptions.defaultOptions;

  // Show a file chooser, create a PNG image from the canvas,
  // send the image to the server,
  // send it back to the client, and save it in the chosen file.
  exportHandler.export(canvas, exportOptions);
  

The image export is started by calling the export() method. Its parameter canvas defines the CanvasComponent to get the image from, the parameter exportOptions can be used to configure the export using an ExportOptions instance as explained below.

Note

Starting with Flash Player 10, opening a file dialog is only allowed as consequence of a user interaction, e.g. after clicking a button or pressing a key. To ensure compatibility with Flash Player 10, we recommend to use ImageExportHandler's upload method only in a method which is called as a result from a user interaction. Calling export from e.g. the initialization method or a result handler from a HttpService will be treated as a security violation by Flash Player.

The yFiles FLEX server API already offers a servlet (Java) or a handler (.NET) which can handle requests sent by the ImageExportHandler: the ExportServlet and the ExportHandler, respectively. See the section called “Class ExportServlet” for details about the Java implementation or the section called “Class ExportHandler” for the .NET version.

The yFiles FLEX API offers a similar class which can be used to save a bitmap image directly to the client's file system. See the section called “Class ImageSaveHandler” for details.

The export options and possible customizations are described in detail in the section called “Class ImageSaveHandler”.