SecureTransport Version 5.3.0 3 April 2019 Developer's Guide

Copyright © 2015 Axway

All rights reserved.

This documentation describes the following Axway software:

Axway SecureTransport 5.3.0

No part of this publication may be reproduced, transmitted, stored in a retrieval system, or translated into any human or computer language, in any form or by any means, electronic, mechanical, magnetic, optical, chemical, manual, or otherwise, without the prior written permission of the copyright owner, Axway.

This document, provided for informational purposes only, may be subject to significant modification. The descriptions and information in this document may not necessarily accurately represent or reflect the current or planned functions of this product. Axway may change this publication, the product described herein, or both. These changes will be incorporated in new versions of this document. Axway does not warrant that this document is error free.

Axway recognizes the rights of the holders of all trademarks used in its publications.

The documentation may provide hyperlinks to third-party web sites or access to third-party content. Links and access to these sites are provided for your convenience only. Axway does not control, endorse or guarantee content found in such sites. Axway is not responsible for any content, associated links, resources or services associated with a third-party site.

Axway shall not be liable for any loss or damage of any associated with your use of third-party content. Contents

Preface 8 should read this document 8 Related documentation 8 Get 9 Training 10

Accessibility 11 Documentation accessibility 11 Keyboard-only navigation 11 Screen reader support 11 Support for high contrast and accessible use of colors 11

1 Overview 12

2 Customizing SecureTransport 13 About customization 13 Transaction Manager 14 When to customize 14 How rules work 15 Conditions 15 Actions 15 Precedence 16 Using NextPrecedence 16 SecureTransport built-in rules packages 16 Custom rules 18 Using built-in agents 21 NextPrecedence 21 Continue 23 SetExitValue 24 SecureTransport Software Development Kit 25 SecureTransport APIs 25 Sample agents and applications 26

3 Developing external agents 27 External agent overview 27 Developing and triggering external agents 27 Calling interface 28 Running external agents 29 Chaining external agents 30

Axway SecureTransport 5.3.0 Developer's Guide 3 Installing external agents 31 External agent examples 32 Mail notification on receipt 32 Permissions 33

4 Developing in-process agents 34 Developing in-process agents overview 34 Creating in-process agents 35 Agent creation a glance 35 In-process agent interface 36 Installing in-process agents 37 In-process agent examples 38 Installing the examples 38 Mail notification on file receipt 39 Denying permission to upload specific file types 41 Deleting a file after it is transferred to a destination 42 About the Transaction Manager API 43 BaseAgent class 43 Events class 45 Logging 46

5 Using the application framework 47 About the application framework 47 Using the application framework or custom rules 48 Key terms 49 Application framework classes and interfaces 50 Pluggable UI overview 54 Custom JSP files 54 Implementing data handlers 57 Creating custom applications 62 Defining application settings 63 Defining subscription settings 65 Defining application agents 66 ApplicationRuntime interface 67 Using ApplicationManager 69 Custom attributes 71 Post-transfer actions 72 Certificate Manager 73 CertificateReference 74 CertificateDetails 74 CertificateManager 75 Working with AccountManager 76 Working with transfer sites 78 Working with template accounts 80

Axway SecureTransport 5.3.0 Developer's Guide 4 Working with business units 81 Example 81 Working with data transformations 82 Data transformation overview 82 Developing data transformation modules 83 Installing transformation modules 88 Transformation example 88 Working with ConfigurationManager 88 Working with InvocationManager 91 Utility script: option_value_change 92 ChangeConfigurationOption.java 93 DefaultResult.java 97 OptionValueChangeInvocableTask.java 99 Working with NavigationManager 101 Working with ServiceCheck 104 Working with ClusteredManager 105

6 Working with event types 106 Authentication and session management events 106 Sessions 107 Certificate Verification event 108 User Configuration event 110 Password Authentication event 114 Login event 116 Logout event 116 SessionEnd event 117 File transfer authorization and audit events 117 Incoming event 118 Incoming End event 119 Incoming Error event 120 Incoming Abort event 120 Outgoing Start event 121 Outgoing End event 122 Outgoing Error event 122 Outgoing Abort event 123 File transfer upload and download events 123 FTP Cmd - STOR event 124 FTP Cmd - RETR event 125 FTP Cmd - REST event 126 FTP Cmd - MDTM event 126 FTP Cmd - SIZE event 127 FTP Cmd - RTCK event 128 File and directory management events 129 FTP Cmd - LIST event 130

Axway SecureTransport 5.3.0 Developer's Guide 5 FTP Cmd - NLST event 132 FTP Cmd - CWD event 133 FTP Cmd - DELE event 134 FTP Cmd - MKD event 135 FTP Cmd - event 135 FTP Cmd - RMD event 136 FTP Cmd - RNFR event 136 FTP Cmd - RNTO event 137 FTP Cmd - event 138 FTP Cmd - MIRR event 139 Server extension events 139 HTTP Cmd - POST event 139 FTP Cmd - SITE event 140 Application framework events 140 Application - Init event 140 Application - Schedule event 141 Application - Incoming event 142 Server-initiated transfer events 142 Server Transfer - Pull event 143 Server Transfer - Push event 143 Schedule event 144 Environment variables 144 codes 145 Transformation event 145 Environment variables 145 Exit codes 145 Password Change event 146 FTP Cmd - CHPWD event 146 Arguments 146 Exit codes 146 PeSIT transfer state coordination events 147 PeSIT Pause event 147 PeSIT Resume event 148 PeSIT SaveMap event 148 PeSIT GetMap event 148 PeSIT ClearMap event 149 PeSIT Ack event 149 Mailbox folder event 149 PMfolderSummary event 150 150 Exit codes 150 Output stream 150 Address book events 150 AddressBook - CreateContact event 151

Axway SecureTransport 5.3.0 Developer's Guide 6 AddressBook - DeleteContact event 151 AddressBook - RetrieveContact event 152 AddressBook – UpdateContact event 153

7 Using environment variables 155 Predefined environment variables 155 Common environment variables 155 Session environment variables 156 Application framework object environment variables 159 Additional environment variables 168 LDAP session state variables 173 Adding custom environment variables 174 Displaying custom environment variables 175

8 File services interface 177 File services interface introduction 177 Registering a file services interface protocol 177 Example 179 Enabling PeSIT message parameters 180 Standard file services interface connectors 180 FileServicesInterfaceScriptBasedConnector 181 FileServicesInterfaceFileBasedConnector 182 Implementing a file services interface connector 184

9 REST API 185 REST API overview 185 REST API examples 186 Create an account 186 Push a file 209 Custom HTML template 211 Java file transfer library 218

Appendix A: Agent execution order 224 Client-initiated transfers 224 Server-initiated transfers 225

Appendix B: Developing condition functions 226 Condition functions overview 226 Condition functions 226 File content search example 226 Installing condition functions 227

Axway SecureTransport 5.3.0 Developer's Guide 7 Preface

The SecureTransport Developer's Guide describes the components and tasks associated with customizing the Axway SecureTransport Server. It provides background, conceptual, and procedural information for creating and modifying rules, including creating agents. Before implementing the tasks described in this manual, sure that SecureTransport is installed as described in the SecureTransport Installation Guide.

Who should read this document This guide is intended for developers who create customizations for SecureTransport. Developers can use a such as Perl or Python to create external agents or Java to create in- process agents when customizing SecureTransport. Some topics cover information dealing with system administration connected with customization.

Related documentation SecureTransport provides the following documentation:

l SecureTransport Installation Guide – This guide explains how to install, upgrade, and uninstall SecureTransport Server on UNIX-based platforms, Windows, and Axway Appliances.

l SecureTransport Getting Started Guide – This guide explains the initial setup and configuration of SecureTransport using the SecureTransport Administrator setup interface.

l SecureTransport Administrator's Guide – This guide describes how to use the SecureTransport Administration Tool to configure and administer your SecureTransport Server. The content of this guide is also available in the Administration Tool online help.

l SecureTransport Web Client User Guide – This guide describes how to use the SecureTransport Browser Client and Web Access Plus to transfer files between your local machine and your SecureTransport Server. The Web Access Plus content of this guide is also available in the Web Access Plus online help.

l SecureTransport Release Notes – This document contains information about new features and enhancements, late-breaking information that could not be included in one of the other documents, and a list of known and fixed issues.

l SecureTransport Developer's Guide – (This document) This guide explains how to use rules, rule packages, and agents to customize SecureTransport. Additional information includes an explanation of how to use the application framework.

l SecureTransport Capacity Planning Guide – This guide provides information useful when planning your production environment for SecureTransport.

Axway SecureTransport 5.3.0 Developer's Guide 8 Preface

l SecureTransport Security Guide - This guide provides security information necessary for the secure operation of the SecureTransport product.

l Axway Appliance Quick Start – This document provides instructions for unpacking, mounting, connecting, and powering up an appliance, provides instructions for installing and deploying an Axway Appliance, plus technical specifications and references to safety, regulatory, and recycling information.

l Axway Email Plug-ins Installation Guide – This guide provides instructions for installing and deploying the Axway Microsoft Outlook add-in and the Axway Lotus Notes plug-in.

l Axway Email Plug-ins Release Notes – This document contains information about installation and upgrade packages, new features, and a list of known limitations.

l Axway Outlook Add-in Installation Guide – This guide provides instructions for installing and deploying the Axway Microsoft Outlook add-in .

l Axway Outlook Add-in Release Notes – This document contains information about installation and upgrade packages, new features, and a list of known limitations.

l Axway Integrator and SecureTransport interoperability Guide – This guide describes the interface between Axway Integrator and Axway SecureTransport and how to configure those products to interoperate.

l SecureTransport Software Developer Kit (SDK) online help – The SDK includes an HTML-based API reference developers can use while customizing SecureTransport.

l SecureTransport REST API online reference – The SecureTransport Server hosts an HTML-based API reference developers can use while developing integrations for SecureTransport.

Go to Axway Sphere at support.axway.com to view or download documentation. The website requires login credentials and is for customers with active support contracts.

Get more help Go to Axway Sphere at support.axway.com to get technical support, download software, documentation, and knowledgebase articles. The website requires login credentials and is for customers with active support contracts.

The following support services are available:

l Official documentation

l Product downloads, service packs and patches

l Information about supported platforms

l Knowledgebase articles

l Access to your cases When you contact Axway Support with a problem, be prepared to provide the following information for more efficient service:

l Product version and build number

l Database and version

l type and version

Axway SecureTransport 5.3.0 Developer's Guide 9 Preface

l Service packs and patches applied

l Description of the sequence of actions and events that led to the problem

l Symptoms of the problem

l Text of any error or warning messages

l Description of any attempts you have made to fix the problem and the results

Training Axway offers training across the globe, including on-site instructor-led classes and self-paced online learning

training.axway.com

Axway SecureTransport 5.3.0 Developer's Guide 10 Accessibility

Axway strives to create accessible documentation for users. The following describes the accessibility features of SecureTransport documentation.

Documentation accessibility The product documentation provides the following accessibility features:

l Keyboard-only navigation on page 11

l Screen reader support on page 11

l Support for high contrast and accessible use of colors on page 11

The accessibility of the documentation has been tested with JAWS.

Keyboard-only navigation

l The documentation source code contains ARIA (Accessible Rich Internet Applications) to improve the natural tab order and add focus where needed.

l ARIA landmarks are used to identify the main elements of the online help windows.

Screen reader support

l The documentation structure is clear and the source code of the online help can be interpreted by JAWS.

l Alternative text is provided for images whenever necessary.

l The PDF documents are tagged to provide a logical reading order.

Support for high contrast and accessible use of colors

l The documentation can be used in high-contrast mode.

l There is sufficient contrast between the text and the background color.

l The graphics have the right level of contrast and take into account the way color-blind people perceive colors.

Axway SecureTransport 5.3.0 Developer's Guide 11 Overview 1

Axway SecureTransport is part of the Axway family of managed file transfer (MFT) products. SecureTransport allows organizations to adeptly control and manage the transfer of files inside and outside of the corporate firewall in support of mission-critical business processes, while satisfying policy and regulatory compliance requirements. SecureTransport serves as a hub and router for moving files between humans, systems and more. SecureTransport also completes tasks related to moving files (push or pull), hosting files in mailboxes or "FTP-like" folders, and provides portal access with configurable workflow for file handling and routing. SecureTransport delivers user- friendly governance and configuration capabilities, including delegated administration and pre- defined and configurable workflows, while providing the highest possible level of security.

Axway SecureTransport 5.3.0 Developer's Guide 12 Customizing SecureTransport 2

This section provides information about using rules and agents to customize SecureTransport.

The following topics describe customizing SecureTransport:

l About customization on page 13 - Describes customizing SecureTransport.

l How rules work on page 15 - Describes how customization rules work.

l Using built-in agents on page 21 - Describes using predefined built-in agents for customizing SecureTransport.

l SecureTransport Software Development Kit on page 25 - Describes the Software Development Kit (SDK) containing the SecureTransport API reference, code samples, and JAR files for creating application types and custom rules.

About customization Since you might have different uses for SecureTransport over , you can customize the software to perform various tasks using the following:

l SecureTransport supports creating custom applications that allow you to automate business processes that require data transfers. For more information about creating custom applications through the application framework, see Using the application framework on page 47.

l Using rules and agents executed by the Transaction Manager. The Transaction Manager is based on a powerful rules-based execution engine. Rules are defined with simple or compound conditions, which include SecureTransport events, environment variable evaluations, and external functions. Each rule also specifies one or more agents to be executed when conditions are met. An agent is code that implements all or part of the business logic associated with an event. Examples of how the Transaction Manager can be used include: File Processing, Automation, Single Sign-On Integration, EDI, File Distribution and Routing, Database Integration, Streaming File Processing, Notification and Alerting, File Tracking, and Customized Access Controls. In SecureTransport, agents are available only on SecureTransport Server and not on SecureTransport Edge.

The following topics provide descriptions of the Transaction Manager and provide examples of when to customize:

l Transaction Manager on page 14 - Describes the Transaction Manager and Transaction Manager rules.

l When to customize on page 14 - Provides a list of examples of when to customize.

Axway SecureTransport 5.3.0 Developer's Guide 13 2 Customizing SecureTransport

Transaction Manager Rules are grouped together into a rules package. Once the rules package is created, you can enable it for use by Transaction Manager. Transaction Manager, a component of the SecureTransport Server, executes the agents in an action by verifying that the rule conditions have been met.

The SecureTransport Administration Tool includes a web-based rule editor to define and manage rules and group application process or policy-related rules into rules packages. At run time, the Transaction Manager rules engine evaluates all enabled rules in the system and triggers actions for rules whose conditions have been satisfied.

Figure 1. Transaction Manager architecture

When to customize The following list shows some examples of tasks that require customization:

l To send an email notification after a file transfer failed, a custom agent to implement the mail functionality for the "Outgoing Error" event.

l To the transferred file to an external system, write a custom agent implementing the push logic for the "Incoming End" event.

l To perform a directory cleanup at the end of an outgoing transfer, write a custom agent implementing the cleanup logic for the "Outgoing End" event.

l To copy or a transferred file at the end of an incoming file transfer, write a custom agent for routing this file for the "Incoming End" event.

l To integrate with a third party directory product and use it as a source of user records, customize the "User Configuration' and 'Password Authentication' events by writing custom agents with the integration logic.

Some examples of complex customizations you can do using SecureTransport include: Providing custom UI forms for HTTP users or Enforcing custom password-policy rules.

Axway SecureTransport 5.3.0 Developer's Guide 14 2 Customizing SecureTransport

The Professional Services Organization can help you customize SecureTransport. Contact your account representative for more information.

How rules work A rule consists of a set of conditions and actions. The conditions contain events and the actions contain one of two types of agent: external or in-process. For more information about creating and using rules in the Administration Tool and the rule syntax, see the SecureTransport Administrator's Guide.

The following topics describe how rules work and how to build custom rules:

l Conditions on page 15 - Describes using rule conditions to customize.

l Actions on page 15 - Describes using rule actions to customize.

l Precedence on page 16 - Describes setting rule precedence.

l Using NextPrecedence on page 16 - Describes using NextPrecedence to switch precedence levels.

l SecureTransport built-in rules packages on page 16 - Describes the SecureTransport built-in rules packages.

l Custom rules on page 18 - Describes and provides how to instructions for building custom rules.

Conditions You can set the type of event or other attributes to be considered in the condition. You can select more than one attribute in a condition. A full list of events and environment variables can be found in Working with event types on page 106, and Using environment variables on page 155.

Actions An action calls one or more agents. Each agent consists of code that accomplishes a task you want controlled by the rule. You can use more than one agent in an action. The order in which you add the agent to the action controls the order the agents are executed.

l External Agents – External agents are called by a rule. External agents are typically created using a scripting language.

l In-process Agents – In-process agents are also called by a rule. In-process agents are created using Java.

In-process agents offer greater scalability and provide better performance. External agents offer more flexibility but can affect performance.

All rules also have a precedence setting which determines whether the rule will be executed when more than one rule is triggered.

Axway SecureTransport 5.3.0 Developer's Guide 15 2 Customizing SecureTransport

Precedence Each rule has a numeric value that defines the rule precedence. Many built-in processing rules have a precedence setting of 100. If a rule is set with a precedence to a number lower than 100, the rule will have a greater precedence than those rules with 100 or higher.

Using NextPrecedence Different precedence levels are linked using the NextPrecedence agent. This agent allows you to execute rules at the next lower precedence level after the current rule. For more information about the agent, see NextPrecedence on page 21.

SecureTransport built-in rules packages SecureTransport contains several rules packages that provide the default functionality. This functionality is critical for the proper operation of SecureTransport. Customization should be used with caution to make sure that the default functionality is not broken. For more information about the built-in rules packages, see the SecureTransport Administrator's Guide.

Note The built-in rules packages should not be copied or modified.

SecureTransport has reserved the following ranges of precedence for the three main types of rules:

Range Description

10 - 29 Pre-processing rules

30 - 49 Post-processing rules

100 - 500 Main processing rules

Rules within the pre-processing range are set up to execute the actions that perform pre-processing tasks, then execute the NextPrecedence action. The rules within the post-processing range are evaluated next. These rules execute the NextPrecedence action before executing the actions that perform post-processing tasks. Because the NextPrecedence action was executed, the rules within the main processing range are evaluated and the appropriate actions are performed before the post- processing rule actions. The following example illustrates this principle.

The following topic provides a built-in rule example:

l A built-in rule example on page 17

Axway SecureTransport 5.3.0 Developer's Guide 16 2 Customizing SecureTransport

A built-in rule example To illustrate the sequence of events, imagine a remote user wants to upload some files to the server. Several rules are used to process the upload. The Streaming rules package contains the rule VirtualAccessCheck that pre-processes the request. The InStreaming rules package contains the rule Incoming_Start that performs the main processing task for this request. The Streaming rules package contains the rule TransferLog_Start that performs post-processing upon the request.

The following example shows how the rules work:

1. The SecureTransport server receives a request to upload files from a remote user.

2. The Incoming start event is sent to the Transaction Manager.

3. After checking the precedence setting, Transaction Manager selects the VirtualAccessCheck rule from the Streaming rules package.

4. Transaction Manager executes the agents VirtualAccessCheckAgent and NextPrecedence as specified in the action for the rule. The NextPrecedence agent locates all rules that match the conditions and looks for the rule with the precedence level set to the closest value that is greater than 20. The TransferLog_Start rule is executed.

Axway SecureTransport 5.3.0 Developer's Guide 17 2 Customizing SecureTransport

5. The first action in the TransferLog_Start rule calls the NextPrecedence agent, which locates the first rule that meets the condition and has a precedence setting greater than 30. The Incoming_Start rule meets the condition and is executed.

After the Incoming_Start rule executes, the request is returned to the TransferLog_ Start rule where the remaining actions are executed. The TimeStamp agent records the time the transfer starts and TransferLogAgent creates a log entry.

6. Since there is no NextPrecedence agent at the end of the chain, the Transaction Manager returns the execution status to the protocol server. In this example, Transaction Manager returns an exit code specifying that files can be uploaded.

Custom rules Although SecureTransport is a fully functional protocol server out of the box, you can customize it to integrate with third party applications. Customization is handled inside rules created using the SecureTransport Administration Tool. SecureTransport allows you to create new rules and agents. You can also modify existing rules you created in the past, however, you should not modify the predefined rules built into SecureTransport. How to create a custom rule is explained in the SecureTransport Administrator's Guide.

The following topics describe how built-in and custom rules interact and provide how to instructions for customizing and creating custom rules:

l How built-in rules and custom rules interact on page 18

l Custom agents in a rule on page 19

l Customization at a glance on page 19

l Creating a custom rule on page 20

l A custom rule example on page 20

How built-in rules and custom rules interact The custom rules you create should be added into the appropriate stage of the default functionality process by controlling the rule precedence. Each built-in rule is given a precedence setting based on the type of task it performs: pre-processing, main processing, or post-processing. Typically custom rules are inserted before or after main processing.

Axway SecureTransport 5.3.0 Developer's Guide 18 2 Customizing SecureTransport

Different precedence levels are linked using the NextPrecedence agent. This agent allows you to execute rules at the next precedence level after the current rule.

Custom rules can have precedence scores outside the reserved ranges:

Range Description

0 - 9 Rules that completely override the default logic or perform custom pre-processing tasks.

50 - 99 Custom rules that insert logic before the main processing or override it.

To ensure the proper execution of the default rules, custom rules should always use the 50 - 99 range. You can do one of three things within this range to control how the custom rule is processed:

l If you want your custom agent executed before the built-in rules perform the main processing actions, include NextPrecedence after your custom agent.

l If you want to execute your custom agent after the built-in main processing, include NextPrecedence before your custom agent.

l If you want to override the built-in processing completely do not include NextPrecendence and only include your custom agent in the rule.

Note Do not use a custom agent before the built-in pre-processing rules or after the built-in post- processing rules.

You must allow the built-in pre-processing rules to be executed before the custom rules because they set up the requirements necessary for the proper handling of events. Built-in post-processing rules are also required for proper clean-up and completion of the event handling. The environment for handling events might be destroyed by the built-in post- processing rules.

Custom agents in a rule You can add an agent to an existing custom rule or to a newly created rule. Custom agents can be one of two types: in-process or external. External agents are developed using a scripting language and are explained in Developing external agents on page 27. In-process agents are developed in Java using the Transaction Manager API and are explained in Developing in-process agents on page 34.

Customization at a glance The following steps outline the high level process involved in customization tasks:

1. Determine which event type or rule condition suits your needs. 2. Determine the precedence level to use for the rule. Decide whether you need to use NextPrecedence in the rule.

Axway SecureTransport 5.3.0 Developer's Guide 19 2 Customizing SecureTransport

3. Implement the custom agent according to the event type interface described in Working with event types on page 106. 4. Install the agent. 5. Create the associated custom rule. 6. the new rule.

Creating a custom rule Here is an overview of the steps used to create a custom rule:

1. Create a rules package. This automatically opens rule creation page. 2. Type a rule name. Use a descriptive name, such as one that indicates the event type used. 3. Set the precedence value. For more information about setting the precedence for a rule, see Precedence on page 16. 4. Modify the condition that triggers the rule. 5. Modify the actions triggered by the rule. 6. Add any new custom agents with proper invocation parameters if needed. Add the NextPrecedence agent when required.

7. Click Save and enter a name for the new rules package. For information about creating rules and rules packages, see the SecureTransport Administrator's Guide.

Note Rules created for customization purposes should be created in their own rules package, the default built-in packages should not be modified.

A custom rule example If you do not want to allow users to upload files of a specific type, such as executables, from a remote user to the server, you can create a rule that prevents specific file types from uploading. This rule has a precedence setting of 50 so it will override the default Incoming_Start rule found in the InStreaming package.

Axway SecureTransport 5.3.0 Developer's Guide 20 2 Customizing SecureTransport

The following example shows how the custom rule works:

1. The SecureTransport server receives a request to upload files from a remote user.

2. The Incoming start event is sent to the Transaction Manager.

3. After checking the Precedence setting and determining that this rule has a greater precedence than other rules, Transaction Manager selects the custom rule, BlockExecutables from the custom rules package.

4. The DXAGENT_TARGET condition is evaluated by Transaction Manager which looks at the file extensions of all files being uploaded for a match.

5. If there are any files with an .exe extension, Transaction Manager executes the agent, DenyPermissionAgent as specified in the action for the rule.

6. DenyPermissionAgent is an in-process agent, so the action calls a Java class.

7. The Transaction Manager returns the execution status to the protocol server. In this example, Transaction Manager returns an exit code specifying that permission is denied and no .exe files can be uploaded.

Using built-in agents The predefined rules use agents that are built-in to SecureTransport. Almost all of these agents carry out a specific function and are not intended for use in custom rules. However, there are also agents that are generic and are designed for use in custom rules.

This following topics describe three of those agents:

l NextPrecedence on page 21 - Describes the NextPrecedence agent.

l Continue on page 23 - Describes the Continue agent.

l SetExitValue on page 24 - Describes the SetExitValue agent.

NextPrecedence When an event is evaluated against the rules packages, rules might be executed that span multiple levels of precedence.Normally, the Transaction Manager executes the rules with the highest level of precedence and discards all other rules.

By calling NextPrecedence, the Transaction Manager can switch to another precedence level and execute rules that match the evaluated conditions. The default behavior of NextPrecedence is to move to the next lower level of precedence and execute rules that match the conditions determined when the event was originally submitted. Rules are not reevaluated.

NextPrecedence is available as an in-process agent and as part of the API. Using NextPrecedence in combination with the precedence range definitions allows you to easily override, interlace, or extend the built-in rules.

The following example demonstrates how NextPrecedence works:

Axway SecureTransport 5.3.0 Developer's Guide 21 2 Customizing SecureTransport

Rule 1:

Precedence 80 if (EventType == e) then (A, NextPrecedence, B)

Rule 2:

Precedence 90 if (EventType == e) AND (e.account == MYACCOUNT) then (D, E)

1. Rule 1 meets the condition evaluation criteria and action A is executed. 2. Then NextPrecedence is executed and rules with a precedence of 90, the next lower precedence value, are evaluated. 3. Rule 2 meets the conditions and the actions D and E are executed. 4. Finally, since Rule 1 is still active, action B is executed after action E is finished.

There are situations when you might want to reevaluate the rules after some information is available in the event context. This situation can occur when one of the currently executing agents adds information to the event context that must be propagated to other rules at lower precedence levels. When you call NextPrecedence in an action, you can choose whether you want to trigger rule reevaluation by setting the reevaluateRules parameter.

If the reevaluateRules parameter for NextPrecedence is set to true, the Transaction Manager does the following tasks in the order listed:

l Discard all agents queued at precedence levels lower than the current precedence.

l Reprocess the event through the rules engine. This results in the regeneration of agent jobs at lower precedence levels using the changed event context as the condition to meet.

l Transaction Manager steps down to the next precedence level and continues execution. From this point, the behavior of Transaction Manager will be the same as that of the NextPrecedence agent without reevaluation.

The following example demonstrates how NextPrecedence works with the reevaluateRules parameter set to true:

Rule 1:

Precedence 80 if (EventType == e) then (A, NextPrecedence (reevaluateRules=true), B)

Rule 2:

Precedence 90 if (EventType == e) AND (e.account == OTHER) then (C)

Rule 3:

Axway SecureTransport 5.3.0 Developer's Guide 22 2 Customizing SecureTransport

Precedence 90 if (EventType == e) AND (e.account == MYACCOUNT) then (D, E)

1. Rule 1 meets the condition evaluation criteria and action A is executed. When action A executes, the associated agent sets the account variable equal to MYACCOUNT.

2. Then NextPrecedence is executed with the reevaluateRules parameter set to true. Rules with a precedence of 90, the next lower precedence value, are evaluated for the condition account = MYACCOUNT.

3. Rule 3 meets the condition and the actions D and E are executed. 4. Finally, since Rule 1 is still active, action B is executed when action E is finished.

Rule 2 containing action C is skipped since the account variable did not meet the new condition.

Continue Rule actions are composed of agents that are executed in a sequential chain. In-process agents have a to continue executing the agent chain or not through a return value. If an in-process agent returns false, the Transaction Manager breaks the chain and stops executing any other agents listed in the action. External agents can only return an exit code, but cannot control the chaining. The next agent in the chain is always executed.

The Continue agent is an in-process agent that facilitates communication between an external agent and the Transaction Manager. External agents can exit with any value, but the value must be interpreted by a Continue agent to determine whether or not the Transaction Manager should run the remaining agents in the chain. Without a Continue agent an external agent can fail, but the Transaction Manager does not stop the execution chain.

In-process agents normally do not require the use of Continue agent. If the agent has multiple exit codes to deal with, these might be interpreted internally within the agent and result in either a true or false outcome. In some situations, this might not be convenient. You can choose to have the in- process agent always return true and have a Continue agent following that to interpret the exit codes.

The Continue agent uses two parameters; stop and continue. The stop parameter is used to prevent further agent execution in a chain. Use the continue parameter when you want agents to keep executing. The values for the parameters are set in the rule and consist of space-delimited lists of values. You only need to specify one of the two parameters.

Use the Continue agent when you are using a mix of in-process and external agents or when you are using only external agents. For more information about using the Continue agent with external agents alone, Precedence on page 16.

The Continue agent can be used after a NextPrecedence agent. The following example from the Streaming rules package demonstrates this usage:

Axway SecureTransport 5.3.0 Developer's Guide 23 2 Customizing SecureTransport

In the TransferLog_Start rule, the actions TimeStamp and TransferLogAgent execute only if there are no error exit codes resulting from executing NextPrecedence.

Note This single NextPrecedence action at precedence level 30 can set off a whole chain of agent executions at several levels of precedence. Since control eventually returns back to the calling NextPrecedence, make sure you check that the event is successfully processed.

SetExitValue Use the SetExitValue agent when you want to pass a specific exit value during event execution. The exitCode parameter allows you to set the specific return code that is sent in response to the event. Unless the exitCode is set to 0, the agent also terminates the agent chain. For the exit codes associated with each event, see Working with event types on page 106.

Axway SecureTransport 5.3.0 Developer's Guide 24 2 Customizing SecureTransport

SecureTransport Software Development Kit SecureTransport provides a Software Development Kit (SDK) containing the SecureTransport API reference, code samples, and JAR files for creating application types and custom rules. Contact Axway Global Support to request the SDK. See Get more help on page 9.

The SecureTransport SDK is stored in a compressed file that uses the following naming convention: STEE--SDK-Build.zip, where is the build number used to identify the release and where is in x_y_ z-SPn:

l x - major version

l y - minor version

l z - maintenance version

l n - (Optional) Service Pack number

The SDK contains the following directories:

l doc – This folder contains the HTML files that comprise the API reference for SecureTransport.

l lib – This folder contains the JAR files necessary for compiling custom code and samples included in the SDK. The jar files in this folder are already deployed in the SecureTransport installation. They are provided here to help set up development environment. The main JAR file is st-server-api.jar. Make sure the JAR files are added to the CLASSPATH of your development environment.

l samples – This folder contains the source code for sample customizations. The full source code of many of the examples used in this guide can be found in this location. The sample application type, Sample Application, is also located in this folder.

Unzip the SDK on the computer where you are developing customizations for SecureTransport to access the samples, the API reference, and to set up the development environment using the included JAR files.

The following topics describes how to access the SecureTransport APIs and list the sample agents and applications:

l SecureTransport APIs on page 25 - Describes how to access the SecureTransport APIs.

l Sample agents and applications on page 26 - Lists the sample agents and applications.

SecureTransport APIs The SecureTransport API reference provides information on agents, events, environment variables, the application framework, the account manager, and the factory interface. Use this as a reference when designing and creating your applications, agents, and rules. The SecureTransport APIs are accessible through the JAR files.

Axway SecureTransport 5.3.0 Developer's Guide 25 2 Customizing SecureTransport

Sample agents and applications Study the sample agents and applications to learn how to use the API to implement your own customizations. Each sample includes a README.txt file with more information.

Sample Agents

Name Description

Anonymous Allows anonymous user to login in ST and act as a virtual user. Login

Cleanup Delete a file after it has been successfully transferred.

Notify Sends an e-mail notification when a file is uploaded to the server. Demonstrates how to use email logic and agent invocation parameters.

Permission Prevent upload of files when the file name matches a pattern set in a rule condition.

Sample Applications

Name Description

Password A non-subscribeable application that notifies users that their password will Expiration expire. Demonstrates the use of a scheduled application. Notify

Sample A simplified version of the Standard Router application.

Send to Sends a file to multiple users. Multiple

Zip Unzips an uploaded file. Demonstrates data transformation. Transformation

Axway SecureTransport 5.3.0 Developer's Guide 26 Developing external agents 3

The following topics provide an external agent overview, how to procedures for developing, chaining, and installing external agents. and external agent examples:

l External agent overview on page 27 - Provides an overview of external agents.

l Developing and triggering external agents on page 27 - Describes how to develop and trigger external agents.

l Chaining external agents on page 30 - Provides how to instructions for chaining external agents.

l Installing external agents on page 31 - Provides how to instructions for installing external agents.

l External agent examples on page 32 - Provides external agent examples.

External agent overview In the Transaction Manager, rules are used to trigger actions that are performed when certain conditions are met. Each action calls one or more agents. Multiple actions can be triggered as a result of a single condition.

There are two agent types:

l External Agents that run as separate processes and are managed by Transaction Manager.

l In-process Agents that run within the Transaction Manager process. For more details on In- process Agents, see Developing in-process agents on page 34.

External agents can be created using Java or a scripting language such as Perl or a shell script. This chapter discusses how to create external agents using a scripting language. All examples shown use Perl.

Developing and triggering external agents You can develop external agents using any programming or scripting language, for example, Java or Perl.

To trigger external agents, you have to define the agent in the Action Editor window when creating a rule. For more information, see the SecureTransport Administrator's Guide. When the rules are triggered, the agents get executed in a separate process.

The following topics describe how external agents receive input data and send back results and how to run external agents:

Axway SecureTransport 5.3.0 Developer's Guide 27 3 Developing external agents

l Calling interface on page 28 - Describes how your agent receives the input data and sends back the results.

l Running external agents on page 29 - Describes how to run external agents.

Calling interface When Transaction Manager executes your agent, input data is passed to the agent, and your agent should produce a set of results. The following topics describes how your agent receives the input data and sends back the results:

l Input data on page 28

l Results on page 28

Input data Agents can receive input data as:

l Environment variables – Environment variables pass contextual information to the agent, such as the current user and the target directory. For more information, see Using environment variables on page 155.

l Input parameters – Input parameters are specified as part of the command line for your agent. For example, if your agent is called deny.pl and your first parameter is Access_ Denied, then you would specify this as follows: deny.pl Access_Denied

l Standard input stream (STDIN) – STDIN is used in a few agents. In the upload agent, it is used to receive the input stream for the contents of a file being sent from the client. In the certificate agent, it receives the client certificate.

l Session variables – Session variables are set using the Perl module state.pm. The module state.pm uses get and set functions to configure the session variables. Session variables can also be retrieved using the state.pm Perl module. For example,

use SecureTransport::State; my $state = new SecureTransport::State; my CONFIG_PASSWD = $state->get("CONFIG_PASSWD");

Results Agents can return results using a combination of the following:

l Exit Value – When an external agent returns, the exit value is interpreted by the server. Each event type defines specific exit values. Refer to the documentation for the specific event to understand what the exit values mean in a particular context.

Axway SecureTransport 5.3.0 Developer's Guide 28 3 Developing external agents

l Standard output stream (STDOUT) – STDOUT is used in a number of agents. In the download agent, it is used to stream the file content back to the client. In other agents, it is used to return configuration information and server side cookies.

Running external agents All external agents need to be executed using the runas program (runas.exe on Windows.) runas will run an agent in the security context of the logged-in user which initiated the execution of the agent.

Format: runas [options]

Arguments: the agent command and its arguments

Note You can pass command event arguments to external agents as command line arguments by appending $DXAGENT_EXTRAARGS to the agent’s command line specification.

Options:

l -r – Causes the agent to run in the security context of a privileged user, root in UNIX and System in

l -u \ – Impersonates a Windows user. The password of the user is retrieved from the password vault. You must escape the backslash to make SecureTransport recognize the option correctly when you are running on a Windows server. This option is not valid for local machine users.

When an agent is run, it uses the user ID that the server is using. If the server is running as a non- root user, the -r and -u switches are ignored.

When an external agent is executed through runas (runas.exe on Microsoft Windows), then errors reported on standard error are logged to the tm_agent_error.log file, otherwise stderr is not available and agent should redirect its error output to a custom log file.

Examples:

l [-u \]

External agent is run in the security context of user \.

l -r

External agent is run in the security context of Local System user.

l

External agent is run in the security context of logged in user.

In the above examples, runas with runas.exe for Microsoft Windows operating systems.

Axway SecureTransport 5.3.0 Developer's Guide 29 3 Developing external agents

Note To create portable rules packages that run on both Windows and UNIX-based servers, use runas.exe as the command wrapper and create a link from runas.exe to runas while installing the package on a UNIX-based server.

Chaining external agents A rule can contain a number of actions. Once the external agent is executed the next action in the chain invoked. To stop execution of other agents in the chain when you want to, SecureTransport provides an agent called Continue. This agent allows you to use the exit value of the previously executed agent to determine if you want to continue or stop running agents in a rule.

When the external agent exit value equals a continue value, the associated Continue agent returns true and the Transaction Manager continues to the next agent in the chain. When the external agent exit value equals a stop value, the associated Continue agent returns false and the Transaction Manager exits the action. For more information about the Continue agent, see Using built-in agents on page 21.

The following example shows how the built-in rule, ExtPermissionsCheck, uses the Continue agent to control whether the next agent can run or the rule will stop processing the agents. The ExtPermissionsCheck rule is located in the ExtPermissionsCheck rules package.

Axway SecureTransport 5.3.0 Developer's Guide 30 3 Developing external agents

1. If the condition for the ExtPermissionsCheck rule is met, the fscheck agent executes.

2. The Continue agent executes and regardless of the exit code, Transaction Manager executes the next agent in the chain.

Note Use Start in Windows or &/nohup in UNIX-based platforms in an external agent to run a command in the background.

Installing external agents After you have created the external agent file, you must install it in order to use the agent.

During the install process a ^M character is appended to each line of the script file. If you are using a Perl or shell script you need to the scripts to a UNIX format before installing.

Axway SecureTransport 5.3.0 Developer's Guide 31 3 Developing external agents

1. In the Administration Tool, Select Transaction Manager > Install Agents. The Install Agents page is displayed.

2. Browse your local file system and choose the agent’s script file.

3. Select the External Java Agent checkbox if the external agent you are installing is a .jar or .class file.

4. Click Install. If the file already exists on the server, you must confirm to overwrite it. 5. Make necessary changes to the SecureTransport Agents section so that the event is handled by the Transaction Manager. 6. Select Operations > Server Control. 7. Stop and restart the TM Server.

External agent examples The topic contains a few examples that illustrate how external agents can be used:

l A mail notification is sent upon receiving a file.

l A user is prevented from uploading an executable file.

Note You should have a working knowledge of Perl to fully understand these examples.

The following topics provide external agent examples:

l Mail notification on file receipt on page 32 - Provides an example of email notification on file receipt.

l Permissions on page 33 - Provides an example of executable file upload denial.

Mail notification on file receipt In this example, the Perl agent sends an email notification when a file is uploaded to the server. It demonstrates the use of the predefined environment variables, DXAGENT_TARGET and DXAGENT_LOGINNAME, containing the file name and the login name respectively. These variables are incorporated into the email.

Axway SecureTransport 5.3.0 Developer's Guide 32 3 Developing external agents

my $sendmail = $ENV{'MAILER'};

if($#ARGV eq -1) { $MAILTO = "root\@localhost"; } else { $MAILTO = @ARGV; }

open(SENDMAIL, "|$sendmail -s $subject ${MAILTO}") or die "Cannot run sendmail"; SENDMAIL $MAILTO,"\n"; print SENDMAIL "Confirmation of your file upload\n"; print SENDMAIL "File $ENV{'DXAGENT_TARGET'} has been uploaded successfully by $ENV{'DXAGENT_LOGINNAME'}\n" close(SENDMAIL);

exit 0;

Permissions In this example, the agent, triggered by the incoming start event, prevents the user from uploading files with an .exeextension.

To trigger this agent:

1. Create a rule that matches files that have an .exe extension.

2. In the action part of the rule, invoke an agent called deny.pl. This agent writes an error message to STDERR and returns an exit status of -1. This error message is written into the agent error log file. The error message is defined as an environment variable called MSG. The variable is set within the action part of the rule in the environment variable section.

print STDERR $ENV{‘MSG’}; exit -1;

Note If you see the exit code -128 in the log file after trying to execute an agent, the agent is unable to access a Perl module. This code is applicable to external agents written in Perl. The agent is running as a specific user, not as root.

The specific user assigned to the agent needs to have read/execute access to /lib/perl5 and its subdirectories, and /bin and its subdirectories. The specific user assigned to the agent needs to have read/write/execute access to the /var/run directory.

Axway SecureTransport 5.3.0 Developer's Guide 33 Developing in-process agents 4

The following topics provide information about implementing in-process agents:

l Developing in-process agents overview on page 34 - Provides an overview of developing in- process agents.

l Creating in-process agents on page 35 - Provides how to instructions for creating in-process agents.

l Installing in-process agents on page 37 - Provides how to instructions for installing in-process agents.

l In-process agent examples on page 38 - Provides in-process agent examples.

l About the Transaction Manager API on page 43 - Describes the basic Java APIs and provides a summary of how to implement an in-process agent

Developing in-process agents overview In the Transaction Manager, rules are used to trigger actions that are performed when certain conditions are met. Each action calls one or more agents. Multiple actions can be triggered as a result of a single condition.

There are two agent types:

l External Agents that run as separate processes and are managed by Transaction Manager. For more details on external agents, see Developing external agents on page 27.

l In-process Agents that run within the Transaction Manager process.

The following topics discuss creating and installing in-process agents.

To develop an in-process agent, you must use the Java programming language and follow the Transaction Manager framework. This framework includes the IInprocessAgent Java interface, a Java class called BaseAgent for basic implementation of IInprocessAgent and a session API for data that is persistent across agent execution. For details on the BaseAgent class, see About the Transaction Manager API on page 43.

Note Additional information about the Transaction Manager framework can be found in the API reference that ships with SecureTransport. For more information about the API reference and the SDK, see Customizing SecureTransport on page 13.

If you are creating an agent that communicates with outside machines and you want to go through a proxy, you will need to modify the configuration.xml file located in /conf directory. Look for the following section in the file:

Axway SecureTransport 5.3.0 Developer's Guide 34 4 Developing in-process agents

Add the appropriate user agent classes or classes that open a socket to the SocksClasses element using the Include element. You can use a package mask wildcard to specify the packages.

Creating in-process agents The code for an in-process agent can be either a java class (.class) file or contained within a .jar file. This .jar or .class file must be installed on the same machine as the SecureTransport Server which contains the Transaction Manager.

An in-process agent defines an executeAgent method that is called when the agent is invoked by extending the BaseAgent class. Parameters passed to the agent define the context for invoking the agent. After execution of a set of actions, the agent returns a value indicating that agent execution is complete.

In-process agents can retain state information between agent calls. The state information can be persisted either globally or relative to an end-user login session.

The following topics provide how to instructions for creating an in-process agent and describe how the in-process agent receives input data and produces results:

l Agent creation at a glance on page 35 - Provides how to instructions for creating an agent.

l In-process agent interface on page 36 - Describes how the in-process agent receives the input data and produces the results.

Agent creation at a glance The following is a summary of the steps used to implement an in-process agent:

Axway SecureTransport 5.3.0 Developer's Guide 35 4 Developing in-process agents

1. Create a class MyAgent extending BaseAgent.

2. Override the executeAgent method to implement your business logic.

The following topic provides how to instructions for compiling an in-process agent:

l Compiling an in-process agent on page 36

Compiling an in-process agent To set up the development environment for building in-process agents install the SDK by unzipping the archive on the computer where you will develop the agents. For more information about the SDK, see Customizing SecureTransport on page 13.

In-process agent interface When Transaction Manager executes an agent, input data is passed to the agent, and the agent returns a set of results. The following topics describe how the in-process agent receives the input data and produces the results:

l Input data on page 36

l Results on page 37

Input data The in-process agent receives input data in the following ways:

l Environment variables – Environment variables provide context information to the agent, such as the current user and the target directory. For more information, see Using environment variables on page 155.

l Input Stream – The InputStream is used by the in-process agents to read the data stream associated with the event. For example, In the upload agent, the InputStream is used to receive the input stream for the contents of a file being sent from the client. In the certificate agent, the InputStream receives the client certificate data.

The input stream can only be read by one agent. Once the input stream has been read, no other agent can access it. Additionally, an input stream must be read completely before writing to an output stream.

l Invocation parameters – Provides the parameters to the agent. Invocation parameters are passed as name value pairs. For example, you have an agent with two parameters:

Parameter Value

name user

emailid [email protected]

Axway SecureTransport 5.3.0 Developer's Guide 36 4 Developing in-process agents

The parameters are specified in the class description file:

l name=user, [email protected]

Results The agent returns results using a combination of the following:

l Return Code – A boolean value returned from the agent method executeAgent:

o true – Causes Transaction Manager to continue executing agents in the chain.

o false – Causes Transaction Manager to stop execution of the agent chain.

l Exit Value – The in-process agent can set the exit value using the method setEventExitValue. Each event type defines specific exit values. Refer to the documentation for the specific event to understand what the exit values mean in context. If an agent does not set the exit value, the exit value from the previous agent is used. If there is no previous agent, an exit value of 0 is used. For an agent for where 0 means an error; the agent must set the exit value.

l Output Stream – The output stream is used by the in-process agents to return information to the server. The input stream must be read completely before writing to the output stream.

Installing in-process agents After developing an in-process agent, you must install it in order to use the agent. You can install multiple agents in one jar file or install each agent in a separate class file. If you have additional jar files that an agent calls, install each jar file once only. Agents have access to all uploaded files, and will call any class specified in the agent that is available.

Classes installed using the Install Agents page can be selected from the Agent Class Name field when creating an in-process agent.

1. In the Administration Tool, Select Transaction Manager > Install Agents. The Install Agents page is displayed.

2. Type the name of the .class or .jar file of the agent or click Browse to select the .class or .jar file of the agent from your local system.

Note Make sure External Java Agent is not selected when installing in-process

Axway SecureTransport 5.3.0 Developer's Guide 37 4 Developing in-process agents

agents.

3. Click Install. If the file already exists on the server, you will be prompted for a confirmation to overwrite it. Class files are uploaded to the /brules/local/agents/inprocess/classes directory and .jar files are uploaded to the /brules/local/agents/inprocess/jars directory on the server. To add additional files, repeat the process from step 2. 4. Select Operations > Server Control. 5. Stop and restart the TM Server.

If you do not see the new in-process agent when editing an action, perform the following steps:

1. Log in to the SecureTransport Server as the user who installed and is running SecureTransport.

2. Edit /brules/local/agentlist.

3. Add the class name using the qualified path with package name like the following example: com.myexample.agents.NotifyAgent

4. Save the agentlist file and log out.

In-process agent examples The following topics provide a few examples to illustrate how agents can be installed and used:

l Installing the examples on page 38 - Describes how to install the in-process agent examples.

l Mail notification on file receipt on page 39 - Provides an example of an in-process agent sending an email notification when a file is uploaded to the server.

l Denying permission to upload specific file types on page 41 - Provides an example of an in- process agent preventing the uploading of executable files.

l Deleting a file after it is transferred to a destination on page 42 - Provides an example of an in- process agent deleting a transferred file after it is downloaded.

Note All the examples included in this chapter are included in the SecureTransport SDK. The SDK includes the Java classes and rules packages you can import to see how in-process agents work.

Installing the examples Each example is accompanied by a README text file containing a detailed description of building, installing, and testing the agent. Each example has an XML file for the rules package and the .java source files.

Axway SecureTransport 5.3.0 Developer's Guide 38 4 Developing in-process agents

Mail notification on file receipt This in-process agent sends an email notification when a file is uploaded to the server. It demonstrates the use of the predefined environment variables, DXAGENT_TARGET and SMTP_ HOST, containing the file name and the SMTP host name respectively. These variables are incorporated into the email.

To create a mail notification upon file receipt:

1. Define the class

public class IncomingEndNotifyAgent extends BaseAgent { ... }

2. Define an executeAgent method for this class. Transaction Manager executes this method when the agent is invoked. A return code of true instructs the Transaction Manager to continue executing other agents in the sequence.

protected boolean executeAgent() { try { ... } catch (AddressException exception) { return false; } catch (MessagingException exception) { return false; }

return true; }

The first step of the status method is to extract the invocation parameters.

String fileName = getEnvironmentVariable(Events.DXAGENT_TARGET); String smtpHost = getInvocationParameter(SMTP_HOST); if (smtpHost == null) { return false; }

String toAddress = getInvocationParameter(RECIPIENT_ADDRESS, "[email protected]"); String fromAddress = getInvocationParameter(SENDER_ADDRESS, "[email protected]"); String subject =

Axway SecureTransport 5.3.0 Developer's Guide 39 4 Developing in-process agents

getInvocationParameter(NOTIFY_SUB, "Upload successful"); String smtpUser = getInvocationParameter(SMTP_USER, ""); String smtpPass = getInvocationParameter(SMTP_PASS, "");

The remaining steps involve setting up a mail message to be sent using the javax.mail package. 3. Define the message content.

String content = getInvocationParameter(NOTIFY_MSG, "File " + fileName + " uploaded successfully\n" + "Have a good day.\n");

4. Define the mail session object.

Properties props = new Properties(); props.put("mail.smtp.host", smtpHost); Session session = Session.getDefaultInstance(props, null);

5. Create the MIME message.

Message message = new MimeMessage(session); Address addressList[] = {new InternetAddress(fromAddress)};

message.setFrom(new InternetAddress(fromAddress)); message.setReplyTo(addressList); message.setSubject("Upload successful"); message.setSentDate(new Date()); message.setText(content);

6. Send the message to the recipients. Set the smtpUser and smtpPass using the sender user name and password for the SMTP mail server.

Address toList[] = {new InternetAddress(toAddress)}; String smtpUser=""; // fill in this variable with specific value String smtpPass=""; // fill in this variable with specific value

Transport transport = session.getTransport("smtp"); transport.connect(smtpHost, smtpUser, smtpPass); transport.sendMessage(message, toList);

The email is sent.

Axway SecureTransport 5.3.0 Developer's Guide 40 4 Developing in-process agents

Denying permission to upload specific file types This agent, triggered by the Incoming Start event, prevents uploading of files with an .exe extension.

To create a filter to deny permission to a specific file type:

Note If you import the rule for this example from the SecureTransport SDK, you can skip the first two steps.

1. Create or modify a rule that matches files that have .exe extensions.

2. In the action part of the rule, invoke an agent named DenyPermissionAgent.

3. To implement the agent, define the class.

public class DenyPermissionAgent extends BaseAgent { protected boolean executeAgent() { getAgentAccess().logAgentError(getEnvironmentVariable("MSG")); setExitValue(1);

return false; } }

4. Define an executeAgent method for this class. Transaction Manager executes this method when the agent is invoked.

protected boolean executeAgent() {

The status method writes an error message to the agent log file using the logAgentError method. The error message is defined in an environment variable called MSG. The variable is set within the action part of the rule in the environment variable section. It then sets the event exit value to 1.

getAgentAccess().logAgentError(getEnvironmentVariable("MSG")); setExitValue(1);

5. The final step of the execute method is to return a code of false. A return code of false instructs the Transaction Manager to stop executing other agents in the sequence.

return false;

Axway SecureTransport 5.3.0 Developer's Guide 41 4 Developing in-process agents

Deleting a file after it is transferred to a destination This agent, triggered by the Outgoing end event, shows how to delete a transferred file after you finish downloading it. The example also shows how to implement logging using log4j. Log entries are created and stored in the tm.log file located in the /var/logs directory.

To configure cleanup:

1. To implement this agent, define the class and create a logger instance.

public class OutgoingEndCleanupAgent extends BaseAgent { private static Logger sLogger = Logger.getLogger (OutgoingEndCleanupAgent.class); ... }

2. Define the executeAgent method of this class. Transaction Manager executes this method when the agent is invoked.

protected boolean executeAgent() { ... }

Extract the environment variable and make a log entry. You are also defining the file name to delete.

String fileName = getEnvironmentVariable(Events.DXAGENT_FULLTARGET);

sLogger.("OutgoingEndCleanupAgent called for " + fileName); File transferredFile = new File(fileName);

3. Attempt to delete the transferred file. If the deletion fails, an error message is written in the log, and the agent stops execution.

if (!transferredFile.delete()) { sLogger.error("OutgoingEndCleanupAgent: failed to delete the file."); return false; }

Axway SecureTransport 5.3.0 Developer's Guide 42 4 Developing in-process agents

4. The final step of the execute method is to return a value of true. A return code of true instructs the Transaction Manager to continue executing other agents in the sequence.

return true;

About the Transaction Manager API The following topics describe the basic Java APIs and provide a summary of how to implement an in-process agent:

l BaseAgent class on page 43 - Describes the BaseAgent class.

l Events class on page 45 - Describes the Events class.

l Logging on page 46 - Describes Transaction Manager logging.

Note Additional information about the Transaction Manager API can be found in the API reference that ships with SecureTransport.

BaseAgent class The BaseAgent class is a direct implementation of IInprocessAgent interface. This class provides an easy to use base implementation for accessing Transaction Manager framework abstractions. Subclass BaseAgent to start the in-process agent. The main function in BaseAgent class is:

protected boolean executeAgent ();

This method should be overridden to implement specific business logic. The return value from the executeAgent method determines whether Transaction Manager should continue to execute agents. Return true to continue agent execution, return false to stop agent execution.

The following topics describe event-based methods, session-based methods, and impersonation:

l Event-based methods on page 43

l Session-based methods on page 44

l Impersonation on page 45

Event-based methods The following methods are used with events in an agent:

l Environment Variables – Agent environment variables can be accessed through the following methods:

protected String getEnvironmentVariable (String variableName,

Axway SecureTransport 5.3.0 Developer's Guide 43 4 Developing in-process agents

String default) protected String getEnvironmentVariable (String variableName)

For details about the environment variable agent interface, see the API reference.

l Input Stream – Agent input stream can be accessed through this method:

protected InputStream getInputStream();

If the input data is not very large, it can also be accessed by the following method:

protected String input ();

l Arguments – Invocation Parameters can be accessed through the following methods:

protected String getInvocationParameter (String parameterName, int index, String defaultValue) protected String getInvocationParameter (String parameterName, String defaultValue) protected String getInvocationParameter (String parameterName, int index) protected String getInvocationParameter (String parameterName)

l Output Stream – Agent output stream can be directly accessed through two methods

public void print (String s); public void println (String s);

The agent output stream can also be accessed directly through this method:

protected OutputStream getOutputStream ()

l Exit Codes – The Event exit code is set by calling the method:

protected void setEventExitValue(int status)

setEventExitValue sets the event exit value used to determine the result of processing the agent. To know what exit code your agent should set, see Working with event types on page 106. If another agent is executed following the event exit code, the exit code might be overridden.

Session-based methods The Session State API gives access to storage for data which should be persistent across agent execution. Functionality is implemented through methods in the BaseAgent class. You can use the following:

Axway SecureTransport 5.3.0 Developer's Guide 44 4 Developing in-process agents

public String readSessionString (String name) public String readOptionalSessionString (String name) public void writeSessionString (String name, String value)

For more information, see the API reference.

Using this API, you can store data during execution of the first agent and read it during execution of the last agent for the same event. Or you can store data during the agent execution for event A and read data during the agent execution of event B, provided event A and B are happening during the same session.

The session state is shared between in-process and external agents. To learn about accessing the session state from an external agent, see Developing and triggering external agents on page 27.

Some session state variables are defined by built-in agents but can be used by custom agents. Those variables are defined in com.tumbleweed.st.server.api.SessionVariables. For more information, see Sessions on page 107.

Impersonation BaseAgent supports an impersonation invocation parameter. This parameter allows the agent method executeAgent to run in the security context of the particular OS user. This only works on Microsoft Windows. On UNIX-based systems, use the runas utility that allows impersonation for the external agents.

Since impersonation is implemented in BaseAgent, any agent that is implemented as a subclass of BaseAgent can be configured to run impersonated. If your custom agent accesses system resources, consider enabling impersonation in your rules.

Events class The Events class in the package com.tumbleweed.st.server.api contains definitions related to the content of events. Included are definitions of event types, as well as event environment variables and values. Environment variable names are particularly useful when writing agents to make sure you correctly specify the name when accessing an environment variable. The Events class also contains definitions for the agent exit codes.

For example, an agent executeAgent method can use the Events class to retrieve the value of a user's login name and set the exit code based on the value returned:

protected boolean executeAgent() { if("bob".equals(getEnvironmentVariable(Events.DXAGENT_LOGINNAME))) { setEventExitValue(Events.EXIT_PERMISSION_DENIED); return false; } else { setEventExitValue(Events.EXIT_OK);

Axway SecureTransport 5.3.0 Developer's Guide 45 4 Developing in-process agents

return true; } }

Logging In-process agents can use the log4j framework for flexible logging. Transaction Manager uses the log4j configuration file /conf/tm-log4j.xml. Agents that don't require flexible logging can use the method IAgentAccess.logAgentError. This method places an error entry in the Transaction Manager log file.

Axway SecureTransport 5.3.0 Developer's Guide 46 Using the application framework 5

The following topics describe the application framework, provide a sample use case, and explain how to create and register application types:

l About the application framework on page 47 - Discusses how to develop custom applications in the context of the application framework.

l Pluggable UI overview on page 54 - Provides an overview of the Pluggable user interface.

l Creating custom applications on page 62 - Describes how to create custom applications.

l CertificateManager on page 75 - Describes the CertificateManager interface.

l Working with AccountManager on page 76 - Describes working with the AccountManager.

l Working with business units on page 81 - Describes working with business units.

l Working with data transformations on page 82 - Describes working business transformations.

l Working with ConfigurationManager on page 88 - Describes working with the ConfigurationManager.

l Working with InvocationManager on page 91 - Describes working with the InvocationManager.

l Working with NavigationManager on page 101 - Describes working with the NavigationManager.

l Working with ServiceCheck on page 104 - Describes working with the ServiceCheck.

l Working with ClusteredManager on page 105 - Describes working with the ClusteredManager.

About the application framework This topic discusses how to develop custom applications in the context of the application framework. For more information about how to use accounts, applications, and subscriptions in the Administration Tool, see the SecureTransport Administrator's Guide.

The application framework is an integral part of SecureTransport that allows development of custom applications. The custom applications integrate seamlessly with the built-in functionality. Custom applications can implement processing of data sent or received through SecureTransport to support specific business needs of an organization while allowing the administrator to specify who can use the applications, how data is transferred and how application needs to be configured.

The separation of the administration and application logic allows development of very generic applications. Some applications are provided as built-in components of SecureTransport Server such as the Standard Router, the Site Mailbox and the Basic application. For more information on the built-in applications, see the SecureTransport Administrator's Guide.

Axway SecureTransport 5.3.0 Developer's Guide 47 5 Using the application framework

The application framework facilitates custom application development by providing the following features:

l Exchanging data with accounts

l Defining an application-specific GUI integrated with the SecureTransport Administration Tool.

l Storing custom data associated with an application in SecureTransport-maintained storage.

l Using certificates stored in the SecureTransport certificate store for application purposes.

l Using the built-in scheduler for application-specific recurring tasks.

The following topics compare the application framework to using custom rules and agents alone and list the application framework key terms, classes, and interfaces:

l Using the application framework or custom rules on page 48 - Compares using the application framework to using custom rules and agents alone.

l Key terms on page 49 - Lists the application framework key terms.

l Application framework classes and interfaces on page 50 - Lists the application framework classes and interfaces.

Using the application framework or custom rules This topic compares using the application framework to using custom rules and agents alone. For example, how is a custom application different from a custom agent when using the Incoming End event? First, the application framework is not independent from custom rules and agents. In fact, creating a custom application involves creating a custom rule and custom agents.

Using the application framework has some advantages and disadvantages compared to defining custom agents and rules.

Advantages include:

l Better separation of responsibilities between a developer and SecureTransport administrator. A team of developers with different skill sets can develop and package generic data processing logic in a custom application. The application can be deployed, configured, and applied by an administrator as day-to-day business needs demand. The administrator can change how the files are sent or received by the application, what users can access the application, or when to schedule recurring application-specific tasks without having to change the application logic or change any rules.

l Better separation of custom logic and better management of different types of custom applications. When defining traditional custom rules and packages, great care must be taken not to override default processing. Also, you must manage different types of custom cases. This can lead to complicated rule conditions or implementing multiple unrelated requirements in a single agent. By comparison, the application custom rule and application custom agent are defined in such a way that the application logic must be implemented by a specific application agent allowing different types of applications to run in a single deployment without interfering with each other. None of the applications need to be aware of the presence of other applications.

Axway SecureTransport 5.3.0 Developer's Guide 48 5 Using the application framework

l Custom application administration is integrated with SecureTransport administration and can be tailored to the needs of the application. This allows the application to provide a user-friendly configuration interface. By comparison, custom agents and rules are configured using the generic rule editor interface.

l Custom applications are provided with custom storage for the configuration data, but custom agents have to either rely on parameters passed in the rules or define a separate storage component.

l The application framework allows SecureTransport administrators to define a schedule for recurring application tasks through a user interface in the Administration Tool.

l The application framework allows custom applications to take advantage of the built-in SecureTransport Certificate Management. For example, an application can request usage of a certificate associated with the account subscribed to the application.

Disadvantages include:

l Applications cannot be used for all customization types. For example, an application cannot be used to implement Single Sign On (SSO).

l Custom applications must follow the design rule imposed by the application framework. If the application framework design does not address a particular use case, other custom rules and agents might have to be used. For example, one such limitation is when a user uploads a file, the application that processes the file is determined based on which directory the file is uploaded into. If custom processing should be triggered by a file name or extension, regardless of the directory the file is uploaded into, a general custom rule must be used.

Key terms The following application framework concepts are relevant to custom application development:

l Application type – An application type identifies what processes the custom application performs. Developing a custom application consists of defining the application type and implementing the components required for the application type to function.

l Application instance – An application instance is created by the SecureTransport administrator based on the application type. An administrator can create multiple instances of the same application type and provide different configuration settings and subscriptions for each instance.

l Application events – Events designed to trigger application processing. These events should be handled by an application agent. For example, when data arrives in a folder, an event can trigger the application.

l Application agent – An agent designed to implement the application logic. The agent is created by the custom application developer. You can choose to create a single agent to handle all types of application events or create several agents. An application agent handles application events associated with the application instances of a particular application type.

l Application rule – A rule that triggers the application agent for the application events associated with the application type.

Axway SecureTransport 5.3.0 Developer's Guide 49 5 Using the application framework

l Application attributes – A set of attributes associated with the application instance. The custom application developer defines the kinds of attributes applicable to the given application type. The SecureTransport administrator through the developer-provided UI chooses the values for the attributes when configuring the application instance.

l Subscription – A persistent object maintained by SecureTransport that links an account with an application instance. Subscription objects are used to represent user account subscriptions to the applications. A SecureTransport administrator can subscribe multiple user accounts to the application instance. Subscription objects are also used to represent the application instance connection to a service account. The custom application developer defines how many service accounts the custom application needs and what purpose each service account serves. A SecureTransport administrator subscribes the service accounts when creating the application instance.

l Application-specific subscription attributes – A set of attributes associated with the User Account subscriptions whose meaning is specific to the application type the subscription is used for. The developer of the custom application defines the kinds of attributes applicable to the given application type. The system administrator provides the values for these attributes when configuring the subscription. This enables the application to associate some custom data with each user subscription. For example, a banking application can use this mechanism to associate a bank account number with the user subscription.

l Transfer configuration – Part of a subscription describing how files are sent or received through the subscription. Transfer configurations include an identifying tag. Subscriptions to user accounts have two transfer configurations: one for sending files to the user and one for receiving files from the user. These transfer configurations are identified by the tags Partner-Out and Partner-In. Subscriptions to the service account have one transfer configuration. The custom application developer must define the tag for the transfer configuration.

l Application schedule – A persistent object maintained by SecureTransport that defines a schedule for a recurring application-specific task. Application schedules have an identifying tag. The custom application developer defines one or more recurring tasks for an application and assigns a tag to each task. The SecureTransport administrator defines how often each task is performed when creating the application instance.

Application framework classes and interfaces The Application Framework offers a number of java classes and interfaces located in the package com.tumbleweed.st.server.api. The API reference in the SDK contains information on the classes and interfaces. The following topics provide a brief introduction:

l Factory on page 51

l Managers on page 51

l Persistent objects on page 52

l ID interfaces on page 52

l Criterion interfaces on page 53

Axway SecureTransport 5.3.0 Developer's Guide 50 5 Using the application framework

l ApplicationRuntime on page 53

l Data handlers on page 54

Factory A factory class that represents the entry point for the SecureTransport Server API. The factory is used to get the instances of specific components, such as managers. The Factory method getInstance is used to get the instance of the Factory class itself.

Managers Manager interfaces allow the use or manipulation of persistent objects maintained in the SecureTransport store. The following manager interfaces are available:

l AccountManager – creates, modifies, deletes, and searches accounts. This manager also contains a method related to authenticating accounts. For more information, see Working with AccountManager on page 76.

l AdministratorManager – creates, updates, deletes and lists administrators.

l ApplicationManager – creates, modifies, deletes, and searches subscriptions and application configurations. For example, the application agent can get the list of all user account subscriptions for a particular application instance. For more information, see Using ApplicationManager on page 69.

l BusinessUnitManager – creates, modifies, deletes, and searches business units. For more information, see Working with business units on page 81.

l CertificateManager – creates, modifies, deletes, and searches information about the certificates in the SecureTransport certificate store. For more information, see CertificateManager on page 75.

l ClusterManager – administers cluster management.

l ConfigurationManager – manipulates server configuration options and export rules. For more information, see Working with ConfigurationManager on page 88.

l Dmz*Manager – manage network zones, SecureTransport Edge configuration including IP addresses and protocols.

l InvocationManager – executes tasks on all nodes in a cluster. For more information, see Working with InvocationManager on page 91.

l LdapManager – manipulates LDAP domains and servers.

l MailTemplateManager – manipulates mail templates.

l NavigationManager – creates, updates, and deletes menus, pages, and navigation menus. For more information, see Working with NavigationManager on page 101.

l ResubmitManager – manages resubmitting failed transfers and canceling new attempts.

l ServerControllerManager – starts, stops, enables, and disables SecureTransport service. (To check if a service is functional, see Working with ServiceCheck on page 104.)

Axway SecureTransport 5.3.0 Developer's Guide 51 5 Using the application framework

l StPackageManager – stores, retrieves, and lists ad hoc file transfer packages.

l UserClassManager – creates, updates, deletes,and lists user classes.

Note SecureTransport uses a database to store persistent objects. The database schema used to store objects is subject to change in future releases. Avoid writing custom agents that rely directly on the database schema.

Persistent objects SecureTransport maintains a number of objects in its store. These interfaces provide access to the information stored in the those objects. The interfaces have getters to retrieve the information in the fields and setters for the fields that can be modified. Please note that invoking a setter method does not change the object in the persistent store. It simply modifies the in-memory copy of the object. Objects are modified persistently by either calling a manager method to modify an account object or by implementing a data handler. The persistent objects include:

l Account – represents a user or service account.

l Application – represents an application instance.

l CertificateReference – a reference to a certificate in the SecureTransport certificate store. Custom applications can use certificates from the SecureTransport certificate store. The certificate reference can be a part of the application attributes or application-specific subscription attributes. You need to define the number, type, and purpose of the certificates used by the application. The SecureTransport administrator chooses a specific certificate when configuring the application instance or user account subscription.

l CertificateDetails – represents detailed information about certificates such as expiration time and certificate data.

l Subscription – represents user or service account subscriptions to the application.

l CustomAttributes – represents application-specific attributes for an application instance or subscription. Custom attributes are designed to hold application-specific values. There are three types of custom attributes:

o Binary data – unstructured data. For example, it can be used to store application configuration in XML format.

o Properties – name/value pairs.

o Certificate References – named references to certificates.

ID interfaces The API includes ID interfaces a program can use to identify a persistent object uniquely. The ID interfaces available in the API are:

l Account.Id

l Application.Id

l BusinessUnit.Id

l CertificateReference.Id

Axway SecureTransport 5.3.0 Developer's Guide 52 5 Using the application framework

l CertificateRequest.Id

l DataTransformation.Id

l Site.Id

l SiteTemplate.Id

l Subscription.Id

l TransferConfiguration.Id

l User.Id

The other interfaces include methods to get the ID of an object, to get an object from its ID, and as a parameter to identify an object. For an example of the use of an ID object, see the example code in Using ApplicationManager on page 69.

Criterion interfaces Criterion is a special group of interfaces that define search criteria when looking for a persistent object. A criterion instance is obtained through the corresponding manager interface. Methods from the criterion interface are used to place conditions to determine the objects that should be returned. Each method invocation places a condition on a particular field of the object. the object must match the conditions on all fields. Placing a condition on the same field twice adds another condition to that field; it does not replace the previous condition. A manager interface has methods that return the list of objects matching the criterion. Typically, there is an option to retrieve a certain number of matching objects starting from a given offset to allow processing of a large number of matched objects. The criterion interfaces available in the API are:

l AccountCriterion – Used in AccountManager to filter and sort account searches.

l BusinessUnitCriterion – Used in BusinessUnitManager to filter and sort business unit searches.

l CertificateReferenceCriterion – Used in CertificateManager to filter and sort certificate searches.

l SiteCriterion – Used in AccountManager to filter and sort site searches.

l SiteTemplateCriterion – Used in AccountManager to filter and sort site template searches.

l SubscriptionCriterion – Used in ApplicationManager to filter and sort site subscription searches.

l TransferConfigurationCriterion – Used in ApplicationManager to filter and sort transfer configuration searches.

For an example of using a criterion object, see Using ApplicationManager on page 69.

ApplicationRuntime A Java interface implemented by SecureTransport and used by the application agent to get information about the application instance the agent is invoked to handle, send or request files to and from subscribed users, and perform other operations.

Axway SecureTransport 5.3.0 Developer's Guide 53 5 Using the application framework

Data handlers Data handlers are interfaces implemented by you to convert configuration data between the user interface and persistent object. For more information, see Pluggable UI overview on page 54. The API defines six data handler interfaces:

l ApplicationHandler – Customizes the application instance.

l ApplicationUpdateHandler – Extends ApplicationHandler to add methods that are called before and after an application instance is updated.

l DataTransformationHandler – Parses data associated with a data transformation.

l SiteHandler – Parses data associated with a site.

l SiteTemplateHandler – Parses data associated with a site template.

l SubscriptionHandler – Supports application-specific subscription attributes.

For more information, see Implementing data handlers on page 57.

Pluggable UI overview The pluggable UI is a part of the application framework that enables development of a custom user interface (UI) integrated with the built-in functionality in the Administration Tool. There are two types of custom UI pages: the Application UI which defines the UI for application instance settings and the Subscription UI which defines application-specific subscription settings

The following elements are involved in developing custom UI pages:

l Custom JSP Files – A Java Server Page (JSP) or JSP document (JSPX) used to display custom settings.

l Data Handler – The Java class accompanying the JSP to convert the settings from the UI to a persistent object or from the persistent object to the UI.

l CustomBean – A JavaBean used to exchange information between the data handler and the JSP page.

The following topics

l Custom JSP files on page 54 - Describes the custom JSP files.

l Implementing data handlers on page 57 - Provides how to instructions for implementing data handlers.

Custom JSP files JSP files provide a way for developers to include Java code in a web page. For SecureTransport, JSP files are used to provide a UI for your custom types. SecureTransport uses the pluggable UI framework to interact with the JSP and display the UI. Most of the code in the JSP uses XML tags.

Axway SecureTransport 5.3.0 Developer's Guide 54 5 Using the application framework

The main purpose of the custom JSP file is to display the form elements for custom settings. The values for the settings are prepared by a data handler and are made available to the JSP through the customBean object. In a typical J2EE web application JSPs are used to provide the content for the entire web page. However, the custom page is displayed within a built-in page and provides just the form fields for the custom settings. Also, the application framework can display multiple custom JSP files in the same web page. Due to these criteria, some rules for custom JSP pages must be followed:

l Pages cannot contain , , or

tags.

l Pages can only define form fields. These form fields will have to follow a naming convention so that they are unique across pages. Form fields must use the ${PluginNameSpace} variable to prefix a form field name so that a page can be included twice in the container page. They should also use a page name in the form field. For example: a text field defined by application type "MyApp":

l Buttons to do form submission are not supported. The form submission is handled by the parent page.

l Access custom beans using a ${customBean} variable.

l Access the name of the form that the custom fields belong to using the ${PluginFormName} variable. You can manipulate form fields through JavaScript with this variable.

l JavaScript functions should be included in the custom JSP file. The function name should follow a similar naming convention used by the form fields to avoid naming conflicts. Use ${PluginNameSpace} and the page name. For example, function can be named ${PluginNameSpace}_MyApp_myJavaScriptFunction().

l The JSP must specify the data handler associated with the page by using the SecureTransport tag library.

Note To learn more about JSP technology, refer to the JavaServer Pages technology documentation at the Oracle Sun Developer Network website.

The following topics describe the SecureTransport tag library and provide how to instructions for installing and registering the custom JSP files:

l SecureTransporttag library on page 55

l Installing and registering custom JSPs on page 56

SecureTransporttag library SecureTransport provides a tag library to assist in developing custom JSP files. A properly functioning custom JSP file must include the SecureTransport tag library. There are several types of tags:

Axway SecureTransport 5.3.0 Developer's Guide 55 5 Using the application framework

l The "main" tags that define the type of custom JSP and associated a data handler with it. A custom JSP must include exactly one instance of such tags at the beginning of the file (before defining any form elements). Five tags are available:

o – application

o – site templates

o – subscription

o – transfer site

o – transformation

l Tags to use special types of custom settings. These tags include:

o – to use a certificate from ST certificate store

o – to connect application to a service account

o – to define an application schedule

l The error tag – displays the errors generated by data handler when processing the custom form elements

When you create a JSP file you need to specify some namespaces to access various code libraries as shown in the following example:

The namespace identifies the library you are using. The st tag identifies the SecureTransport tag library.

Installing and registering custom JSPs To make the application framework aware of the presence of custom JSP pages, they need to be registered. For each type of pluggable pages, there is a configuration directory in the /tomcat/admin/webapps/coreadmin/WEB-INF/plugin/ directory that contains the JSP files.

l applicationtypes

l connectdirect

l sitetemplateconnectdirect

l subscriptions

l transfers

l transformations

Axway SecureTransport 5.3.0 Developer's Guide 56 5 Using the application framework

Each directory contains a plugin.xml file that lists the JSP files and associates certain parameters with them. So, installing a custom JSP involves placing the JSP file in the appropriate configuration directory and adding an entry to the correct plugin.xml file. Each JSP is specified in an element. The name of the JSP file is placed into the jspFile attributes. There are two additional attributes: displayName specifies a user-friendly name for the application type and value specifies the internal or API values of the application type. For example:

Implementing data handlers The Data handler class is needed to support custom JSP files. The application framework API defines the six data handler interfaces listed in Application framework classes and interfaces on page 50.

The data handler interfaces are similar to each other and follow the same pattern. The difference between them is that they are defined to work with different interfaces.

Each data handler interfaces defines methods to:

l Create an initial custom bean to represent the default settings using the newCustomBean method available in each interface.

l Retrieve the submitted values from the HTTP request and store them in a persistent object and its custom attributes using the populateApplication, populateDataTransformation, populateSite, populateSiteTemplate, and populateSubscription methods.

l Validate the custom data during updates by returning a collection of instances of the class ValidationError using the validate method.

l Generate a custom bean based on a previously created persistent object and its custom attributes. using the generateCustomBean method.

The following topics for provide how to instructions for implementing the Application and Subscription handlers and custom beans:

l Implementing ApplicationHandler on page 57

l Implementing SubscriptionHandler on page 60

l Custom beans on page 62

Implementing ApplicationHandler A data handler for each type of application implements the ApplicationHandler interface. The data handler validates the submitted data and saves application-specific data using an implementation of the Application interface.

The Sample application includes a simple implementation of ApplicationHandler:

Axway SecureTransport 5.3.0 Developer's Guide 57 5 Using the application framework

public class SampleAppDataHandler implements ApplicationHandler {

public void populateApplication(HttpServletRequest request, Application application) {

String pluginNameSpace = (String) request.getAttribute("PluginNameSpace"); CustomAttributes attributes = application.getCustomAttributes();

// outbox settings String outboxEnabled = (String) request .getParameter(SampleAppUtils .fomratPluginParam(pluginNameSpace, SampleAppUtils.APP_NAME, SampleAppUtils.OUTBOX_ENABLED));

if (Boolean.valueOf(outboxEnabled).booleanValue()) { attributes.getCustomProperties().put( SampleAppUtils.OUTBOX_ENABLED, outboxEnabled); // set the outbox folder as drop folder for the application

} else { attributes.getCustomProperties().put( SampleAppUtils.OUTBOX_ENABLED, Boolean.toString(false)); }

application.setDropFolder(new ClientPath (SampleAppUtils.OUTBOX_FOLDER_NAME));

// inbox settings String inboxEnabled = (String) request .getParameter(SampleAppUtils .fomratPluginParam(pluginNameSpace, SampleAppUtils.APP_NAME, SampleAppUtils.INBOX_ENABLED)); if (Boolean.valueOf(inboxEnabled).booleanValue()) { attributes.getCustomProperties().put( SampleAppUtils.INBOX_ENABLED, inboxEnabled); } else { attributes.getCustomProperties() .put(SampleAppUtils.INBOX_ENABLED, Boolean .toString(false)); }

}

Axway SecureTransport 5.3.0 Developer's Guide 58 5 Using the application framework

public Object generateCustomBean(Application application) { SampleAppBean customBean = new SampleAppBean(); CustomAttributes customData = application.getCustomAttributes();

//outbox settings String outboxEnabled = (String) customData.getCustomProperties() .get(SampleAppUtils.OUTBOX_ENABLED); if (Boolean.valueOf(outboxEnabled).booleanValue()) { customBean.setOutboxEnabled(outboxEnabled); } else { customBean.setOutboxEnabled(Boolean.toString(false)); }

//inbox settings String inboxEnabled = (String) customData.getCustomProperties() .get(SampleAppUtils.INBOX_ENABLED); if (Boolean.valueOf(inboxEnabled).booleanValue()) { customBean.setInboxEnabled(inboxEnabled); } else { customBean.setInboxEnabled(Boolean.toString(false)); }

return customBean; }

public Object newCustomBean() { return new SampleAppBean(); }

public Collection validate(HttpServletRequest request, Application application) { return Collections.EMPTY_LIST; }

}

The ApplicationUpdateHandler interface extends ApplicationHandler. An application that implements ApplicationUpdateHandler can also gain control before and after the set of custom properties represented by the custom bean are saved or updated. The interface adds two methods to the ApplicationUpdate interface:

l applicationWillUpdate is called if there are no validation errors just before the application custom properties are saved to the database. It can examine and update the Application object, perform actions on files or other external data, and prevent the application update by returning a validation error.

Axway SecureTransport 5.3.0 Developer's Guide 59 5 Using the application framework

l applicationUpdated is called after the application custom properties are saved to the database successfully. It can make other changes in conjunction with the successful application update, for example, modify a configuration file.

Implementing SubscriptionHandler An application implements the SubscriptionHandler interface to validate submitted data so that invalid data is not saved and to save subscription-specific data in the application’s implementation of the Subscription interface.

The Standard Router application installed with SecureTransport includes the following implementation of the SubscriptionHandler interface. It also illustrates how to retrieve application- specific attributes through ApplicationManager.

/* * This class parses data and generates custom bean associated with subscription to "StandardRouter" application. */ public class RouterAppSubscriptionHandler implements SubscriptionHandler { static final Logger sLogger = Logger.getLogger(RouterAppSubscriptionHandler.class);

/* * Implements SubscriptionHandler#generateCustomBean(Subscription)}. * Gets the subscriber id and set it as anchor to the subscription. */ public void populateSubscription(HttpServletRequest request, Subscription subscription) { String subscriberIdPattern = PluginUtils.getParam(request, RouterAppDataHandler.APP_TYPE, RouterUtils.ROUTER_SUBSCRIBER_ID); subscription.setAnchor(subscriberIdPattern); }

/* * Implements Subscription#generateCustomBean(Subscription). * In this case the custom bean is the anchor of the subscription. */ public Object generateCustomBean(Subscription subscription) { return subscription.getAnchor(); }

Axway SecureTransport 5.3.0 Developer's Guide 60 5 Using the application framework

/* * Creates new custom bean. In this case it is an empty String. */ public Object newCustomBean() { return ""; }

/* * Validates the subscriber ID pattern and returns ValidationError * objects. */ public Collection validate(HttpServletRequest request, Subscription subscription) { String subscriberId = PluginUtils.getParam(request, RouterAppDataHandler.APP_TYPE, RouterUtils.ROUTER_SUBSCRIBER_ID);

List errors = new ArrayList(); if(StringUtil.isNullOrEmpty(subscriberId)){ errors.add(new ValidationError("requiredSubscriberId")); }

//validate by getting the pattern from the actual application Application app = null; try { ApplicationManager appMgr = Factory.getInstance().getApplicationManager(); app = appMgr.getApplication(subscription .getApplicationId()); final String message = "Error while getting application for subscription with " + "id {0}"; sLogger.error(MessageFormat.format(message, new Object[]{subscription.getId()}), e); throw new RuntimeException(e); }

String subscriberIdPattern = (String) app.getCustomAttributes() .getCustomProperties().get(RouterUtils.INBOX_ID_PATTERN); if (!StringUtil.isNullOrEmpty(subscriberIdPattern) && !RouterFileName\ .isSubsciberIdValid(subscriberIdPattern, subscriberId)) { errors.add(new ValidationError("invalidSubscriberId", new Object[] { subscriberIdPattern })); }

Axway SecureTransport 5.3.0 Developer's Guide 61 5 Using the application framework

return errors; }

}

For more information about these interfaces, see the API reference.

Custom beans A custom bean is a standard JavaBean designed to hold custom settings in a way that is convenient for JSP files. Typically, custom settings are stored using CustomAttribute interfaces in the form of name-value pairs or possibly in an XML format. This method makes it difficult for JSP files to access custom settings and the storage of the settings might not map one-to-one to how the setting is represented in the UI. A custom bean class can have explicit setters and getters and the JSP file has well-defined access to the bean properties.

An instance of the custom bean class is created by a data handler associated with the custom JSP file and is made available to the JSP file through the ${customBean} variable. The following example shows a simple custom bean class:

public class MyBean { private String myValue = "myDefault"; public String getMyValue() { return myValue ; } public void setMyValue(String newValue) { myValue = newValue; } }

myValue represents something that needs to be displayed in the custom JSP file. It is accessed through the ${customBean.myValue} variable.

Creating custom applications In SecureTransport, when you create a custom application, you are defining an application type. Creating a custom application involves the following steps:

l Defining Application Settings

l Defining Subscription Settings

l Defining Application Agents

The following topics provide how to instructions for managing and creating customer applications:

Axway SecureTransport 5.3.0 Developer's Guide 62 5 Using the application framework

l Defining application settings on page 63 - Provides how to instructions for defining application settings.

l Defining subscription settings on page 65 - Provides how to instructions for defining subscription settings.

l Defining application agents on page 66 - Provides how to instructions for defining application agents.

l ApplicationRuntime interface on page 67 - Describes the ApplicationRuntime interface.

l Using ApplicationManager on page 69 - Provides how to instructions for using the ApplicationManager.

l Custom attributes on page 71 - Describes custom attributes and custom certificate usage.

l Post-transfer actions on page 72 - Describes post-transfer actions and provides how to instructions for implementing post-transfer actions.

Defining application settings The application type defines what settings are available to an application instance. The settings can be configured through the user interface by an administrator using the SecureTransport Administration Tool. The information provided by the administrator for the application instance is stored in the SecureTransport database.

There are three types of settings:

l Application attributes on page 63

l Service account subscriptions on page 65

l Application schedules on page 65

Application attributes There are two types of application attributes: common attributes and custom attributes. Common attributes are applied to all applications.

Common attributes include the following:

l Application Folder – The application working area. Use this when you need to store temporary files. The Transfer Log Maintenance application provided with SecureTransport uses this attribute.

l Shared Folder – Application storage shared by all the subscribers to the application. If the application defines a shared folder, all the application subscription folders map to this value. This provides a mechanism to automatically share application-related data with all application subscribers. The Shared Folder application provided with SecureTransport uses this attribute. Most applications will not use a shared folder. The application can define either a shared folder or an application folder, but not both.

Axway SecureTransport 5.3.0 Developer's Guide 63 5 Using the application framework

l Drop Folder – Specifies the location within the subscription folder to store files transferred from a site. If the drop folder is not specified the files are placed into the subscription folder directly. The drop folder can only be used with User Account subscriptions.

l Name – The unique name of the application instance.

l Notes – Text added by an administrator when creating the application instance.

Note The Name and Notes attributes are provided by the SecureTransport Administration Tool and you do not need to set these values in the application.

To define the application attributes and other application settings so an administrator can modify them, you must:

l Create a custom JSP file for the application including the supporting definitions of the data handler and the custom bean

l Pick the values to identify the application type in persistent storage, the API, and for display purposes in Administration Tool.

l Register the JSP file.

Each JSP file needs to be described in the appropriate plugin.xml file: The following example shows how to describe an application type in the XML file.

There is also a plug-in parameter you can use for additional configuration:

supportsSubscriptions – Determines if subscribing user accounts to applications from this type is allowed. The default setting is true. Most applications support subscriptions. If an application only performs a scheduled task or is designed to move data between service accounts, a user account subscription to that application might not be useful to the user account.

You need to determine what settings the application needs, if you want to use any of the common application attributes and whether to use custom attributes. Based on these decisions, custom JSP files, data handlers, and custom beans can be developed to display the settings and store them in an Application object. for more information, see Pluggable UI overview on page 54.

Axway SecureTransport 5.3.0 Developer's Guide 64 5 Using the application framework

Service account subscriptions In addition to the settings provided by Application object, a custom application can use service accounts and schedules. These special objects are maintained by the application framework so the application can use them.

An application can request the use of a service account. An application can either send files to or receive files from a service account. The application needs to determine how many service accounts should be used and for what purpose. An application requests a service account by placing the JSP tag into the application settings JSP file. The tag expands into UI elements needed to allow administrators to set up a subscription and transfer configuration for the service account. The transfer configuration tag is defined by the application and can be used to determine when data arrives from a specific service account. It can also be used when sending data to specific service accounts.

For more information about the tag, see the API reference included in the SDK.

Application schedules An application can request the use of multiple application schedules for periodic tasks. The application requests the use of a scheduler by placing the JSP tag into the application settings JSP file. The JSP tag expands into UI elements needed to allow administrators to configure the schedule. The application can also associate an identifying tag with the schedule. That allows the application to determine which periodic tasks to perform.

For more information about the tag, see the API reference included in the SDK.

Defining subscription settings An application can associate application-specific data with the User Account subscription to the application. This element is optional, an application does not need any subscription attributes defined. The following settings are available to the application:

l Subscription Anchor – A special value associated with the subscription to enable the application to uniquely identify the subscription. No two subscriptions to the same application instance can have the same anchor value. For example, banking application can choose to use subscription anchor to store the bank account number.

l Custom Attributes – Subscription custom attributes have the same structure as application custom attributes.

If you choose to use subscription attributes, you must do the following:

l Create a custom JSP file for the subscription including the supporting definitions of the data handler and the custom bean

l Register the subscription in the plugin.xml file

For more information, see Pluggable UI overview on page 54.

Axway SecureTransport 5.3.0 Developer's Guide 65 5 Using the application framework

Note You cannot create a pluggable custom subscription page for a connector. Connectors for service accounts are defined when the application is defined and any custom attributes are defined in the application. You do not want to display the same custom attributes in the subscription and the connector to an application.

Defining application agents The following topics discuss application processing:

l Application rules package on page 66

l Application agent on page 67

Application rules package An application executes in response to one of three Transaction Manager events:

l Application - Init – This event indicates that a subscription to an application needs to be initialized.

l Application - Schedule – This event indicates an application action needs to be performed according to a schedule associated with the application.

l Application - Incoming – This event is sent when a file associated with application arrives anywhere inside the subscription folder.

For more information about the application events, see Working with event types on page 106.

You need to provide a rules package containing a rule that triggers the application agent when one or more of the these events occur. This rule must also include conditions for the particular application type. Otherwise, the application agent is invoked when events are sent to any application. For more information on creating rules and rules packages, see the SecureTransport Administrator's Guide. Custom applications should set the rule precedence from within the custom range of 50-99. For more information on setting precedence, see Customizing SecureTransport on page 13.

You must also define an application agent invoked by the rule. When an application applies to multiple events, you need to decide how to structure the rules package – whether to use one or multiple rules. Having a separate rule and separate agent for each event results in a more straightforward configuration. The following image shows the sample application rules package. The sample application is included as part of the SDK.

Axway SecureTransport 5.3.0 Developer's Guide 66 5 Using the application framework

Application agent The application rules package is needed to trigger the application agent that performs the work for the application. Use in-process agents for better access to the Application Framework. All in-process agents must extend BaseAgent.

The application agent is basically a standard agent. What makes an application agent different is that it uses the ApplicationRuntime interface to perform tasks especially designed for applications.

ApplicationRuntime interface ApplicationRuntime is the main interface implemented by the application framework to support application agents. ApplicationRuntime is instantiated using the Factory interface:

ApplicationRuntime appRuntime = Factory .getInstance().getApplicationRuntime(getAgentEvent());

The ApplicationRuntime interface is available for all application events. Once instantiated, use the interface to do the following tasks:

l Getting information about the context on page 68

l Send data to account subscribed to the application on page 68

l Create files and folders inside the subscription folder on page 69

Axway SecureTransport 5.3.0 Developer's Guide 67 5 Using the application framework

Getting information about the context The getApplication method retrieves information about the application instance. It returns Application interface (it's the same interface passed the application data handler for pluggable UI). Typically an application agent uses the getCustomAttributes method to retrieve custom configuration information associated with the application and the getApplicationFolder method. For more information, see Custom attributes on page 71.

The methods getAccount and getSubscription return information about the specific subscription and the corresponding account the application agent is invoked to handle. These values are available to the Application - Init and Application - Incoming events. Since the Application - Schedule event is not associated with a subscription, these methods return null when invoked for this event.

The method getSubscription returns the Subscription interface. Use this interface to retrieve application-controlled values such as anchor and the custom attributes.

While these interfaces both have setter and getter methods, the application agent only uses the getter methods. Calling the setter methods does not result in the modification of the objects in the persistent store. Setter methods are used only by data handlers.

The getTransferConfiguration method is used to retrieve the information about the transfer configuration associated with the transfer. The TransferConfiguration#getTag method is used to determine what type of account is sending the data to the application. If it matches the value of the TransferConfiguration#USER_ACCOUNT_IN_TAG, the data is coming from a user account subscribed to the application. Otherwise, it comes from a service account and the value of the tag is same as what was specified in the name attribute of the tag in the application configuration page.

Send data to account subscribed to the application An application can send files to its subscribers (user or service accounts). When the application sends a file, the following occurs:

1. The subscription and transfer configuration information are determined based on the parameters provided by the application. 2. The target location for the file is determined. By default, it is the subscription folder. The application can specify a subfolder inside the subscription folder. 3. If data transformations are defined for the transfer configuration, they are applied to the specified file. The source file itself is not modified during this stage. The result of the transformation is placed into target location. If no data transformations are defined, then the source file is placed into the target location.

When the moveFile parameter is set, the source file is either maintained or removed during this process.

4. If the server push site was defined for the transfer configuration, the Server Transfer - Push event is generated to deliver the file to the site specified in the application configuration.

Axway SecureTransport 5.3.0 Developer's Guide 68 5 Using the application framework

5. The Send methods return without waiting for the file to be delivered to the remote site.

The ApplicationRuntime interface provides several methods for sending data:

l sendToServiceAccount(String transferTag, File sourceFile, ClientPath subFolder, boolean moveFile) is used to send a file to the service account. The transferTag parameter should match the value of the name attribute of the tag in the application configuration page.

l sendToUserAccount(File sourceFile, ClientPath subFolder, boolean moveFile) is used to send the file to the same user account subscription the ApplicationRuntime was created for. For example, in the Application- Incoming event, it is the subscription associated with the arrived data.

l sendToUserAccount(Subscription targetSubscription, File sourceFile, ClientPath subFolder, boolean moveFile) is used to send the file to a user account subscription. To use this method, the application first must the subscription where it should send the file to. The ApplicationManager method getSubscriptions is used for that purpose. For more information, see Using ApplicationManager on page 69.

Create files and folders inside the subscription folder The ApplicationRuntime interface methods createFile and createFolder create files and folders inside the subscription folder of accounts subscribed to an application. Using these methods is preferable to directly using java.io because they eliminate the need to determine the actual file system location corresponding to the subscription folder and use system-specific functionality to set the file ownership to the corresponding account. Methods can be invoked for any subscription to the application.

Using ApplicationManager The purpose of the application manager is to examine application instances and subscriptions. A typical use by the application agent of the application manager is to find subscriptions to the application instance so you can send data to those subscriptions. The Factory interface is used to obtain an instance of the application manager:

ApplicationManager appManager = Factory.getInstance () .getApplicationManager();

Use the SubscriptionCriterion interface to specify what kind of subscriptions to look for. Call the getSubscriptionCriterion method to get an instance of the interface. To start looking for a subscription to the application instance, do the following:

ApplicationRuntime appRuntime = Factory.getInstance ()

Axway SecureTransport 5.3.0 Developer's Guide 69 5 Using the application framework

.getApplicationRuntime(getAgentEvent()); Application app = appRuntime.getApplication(); SubscriptionCriterion criterion = appManager .getSubscriptionCriterion(app.getId());

Call appManager.getSubscriptions(criterion) to get all the subscriptions to this application instance. A list of subscriptions can grow very large and includes both user and service account subscriptions. Typically, the application agent can use SubscriptionCriterion methods to narrow down the set of subscriptions to look for. For example:

criterion.setAnchor("123-45-6789")

is used to find the subscription containing an anchor with the value of 123-45-6789.

Another example:

criterion.accountType(Account.ACCOUNT_SERVICE)

searches for all the service account subscriptions to the applications.

The SubscriptionCriterion methods have the following limitations:

l You cannot search using custom attributes values

l You can only search one application instance at a time

Once the criterion is set up, it can be used for getting the list of subscriptions as shown in the following examples:

getSubscriptions(SubscriptionCriterion criterion); getSubscriptions(SubscriptionCriterion criterion, int first, int count);

The first method returns all the subscriptions that match the criterion in a single operation. This method is convenient. However, for very large deployments, it can result in loading a lot of data into memory if there are a lot of matching subscriptions. The second method allows retrieving of the matched subscriptions in chunks of the requested size. The application agent can iterate over all matching subscriptions without loading them into memory.

The following example uses the second method to send a file to all user accounts subscribed to the application:

File fileTosend = new java.io.File("test.txt"); SubscriptionCriterion criterion = manager.getSubscriptionCriterion(app.getId()). accountType(Account.ACCOUNT_USER); boolean done = false; final int pageSize = 500;

Axway SecureTransport 5.3.0 Developer's Guide 70 5 Using the application framework

int index = 0; while(!done) { List subscriptions = manager. getSubscriptions(criterion, index, pageSize); for(Subscription subscription: subscriptions) { appRuntime.sendToUserAccount(subscription, fileTosend, null, false); } index += pageSize; done = subscriptions.size() < pageSize; }

Custom attributes An application can associate custom attributes with an application instance or with a subscription. When the application agent is invoked, the attributes are available to use as the application chooses. The CustomAttributes interface provides access to the attributes. The methods getCustomProperties, getEncryptedProperty, and getBinaryData get the values set by the data handler.

The following topic describes custom certificate usage:

l Custom certificate usage on page 71

Custom certificate usage The methods getLocalCerts and getPartnerCerts retrieve the certificate references inserted by the application framework in response to using the tag in the application JSP page. The tag group attribute specifies whether the certificate is local or a partner certificate.

The return value of these methods is a map of where the keys are the usages of the certificates specified in the usage attribute of the tag. The value is a CertificateReference object. This CertificateReference object used in conjunction with the CertificateManager gets the certificate and associated keys. For more information, see CertificateManager on page 75.

In the following example, the application specifies a tag in the subscription page to select a partner certificate:

The following code in the application agent retrieves the certificate reference.

ApplicationRuntime appRuntime = Factory.getInstance()

Axway SecureTransport 5.3.0 Developer's Guide 71 5 Using the application framework

.getApplicationRuntime(getAgentEvent()); CertificateReference reference = appRuntime.getSubscription() .getCustomAttributes().getPartnerCerts().get("encrypt");

For example, you want to get the public key corresponding to the certificate:

CertificateManager certManager = Factory.getInstance() .getCertificateManager(); PublicKey key = certManager.getCertificateDetails(reference) .getPublicKey();

Post-transfer actions As the name implies, a post-transfer action is run after a transfer. A local post-transfer action can modify, move, or delete a file or take some other action on the SecureTransport server. A remote post-transfer action occurs on the remote server, so it must be a action that can be implemented using commands of the transfer protocol.

The following topics outline the implementation of a post-transfer action. They do not cover how to add one to an existing application.

l Implementing a local post-transfer action on page 72

l Implementing a remote post-transfer action on page 73

Implementing a local post-transfer action A local post-transfer actions can modify a file or take another action on the local server after a transfer occurs. The action is triggered by one of the following event types:

l Incoming end

l Incoming error

l Incoming abort

l Outgoing end

l Outgoing error

l Outgoing abort

By default, SecureTransport includes post-transfer actions that modify a file name, move a file to a new location, or delete the file from the source directory. These post-transfer actions can be set if a transfer reports an error, fails to complete, or is successful. You set options for the built-in local post-transfer actions in the Subscription settings for an account or account template. They are available for all supported protocols. For more information about the built-in local post-transfer actions, see the SecureTransport Administrator's Guide.

Axway SecureTransport 5.3.0 Developer's Guide 72 5 Using the application framework

To add a local post-transfer action, your application must implement it using an agent and call that agent from a rule with a condition that includes one or more of the relevant event types. The subscription interface for the application might include enabling and configuring the post-transfer action.

The new post-transfer action might interact with the default post-transfer actions. For example, the new action might need to access information from or about a file before a default action deletes it. The PostTransmissionAgent implements the built-in local post-transfer actions. See the PostTransmission rule of the Streaming rules set. When you define the rule to trigger your new post- transfer action, be sure to set the rule precedence so that the Transaction Manager event engine evaluates the new rule and the PostTransmission rule in the correct sequence.

Implementing a remote post-transfer action By default, SecureTransport includes remote post-transfer actions for the FTP, HTTP, and SSH protocols. You set the options for remote post-transfer actions on the Transfer Site page for an account. The available actions include deleting, moving, or renaming the remote file. The transfer agents for each of the protocol implement the remote post-transfer actions by sending protocol commands to the remote server. The agents request the post-transfer actions in the same session as the transfer commands. For more information about the standard remote post-transfer actions, see the SecureTransport Administrator's Guide.

To add a remote port-transfer action, your application must implement it using an agent and call that agent from a rule with the same conditions as the rule that calls the built-in agent that processes the relevant protocol. To find these rules, examine the following rules sets: FtpTransfer, HttpTransfer, and SshTransfer.

Your agent will not be able to use the same session as the built-in agent for the protocol. It must establish a new session to the remote host using a relevant protocol (but not necessarily the same protocol as the transfer used) and transmit commands to perform the desired action. If your remote port-transfer action needs to be enabled or configured, you must provide an application with a subscription interface for that purpose. Be sure to set the rule precedence for the rule that runs your remote post-transfer action so that it runs after the transfer action with its built-in post-transfer actions.

Certificate Manager The Certificate Manager allows you to use the certificates managed by SecureTransport. Using the Certificate Manager, you can retrieve certificates and the public and private keys associated with them. Certificate Manager operations are read only – they do not modify the certificate store.

Certificates are categorized by how they are used:

l Local – The certificate and the corresponding private key are available in SecureTransport store. This certificate type is used for private key operations such as signing and decryption. Local certificates can be associated with a specific account. If a certificate is associated with an account, it should be used only for operations related to the account. Local certificates are used for the following certificates in the Administration Tool: Server Local, Server Internal, and User

Axway SecureTransport 5.3.0 Developer's Guide 73 5 Using the application framework

Private.

l Partner – The certificates that belong to an entity represented by a SecureTransport account. The SecureTransport store does not contain a private key for partner certificates. Partner certificates can be used for public key operations such as signature verification or data encryption. Partner certificates are always associated with a particular account. In the Administration Tool, partner certificates are called Account certificates. Partner certificates are used for the User Partner certificates in the Administration Tool.

l Trusted – The certificate that represents a trusted root used for chain-trust validation. Trusted certificates are not associated with any account. A single list of trusted certificates is maintained for a given deployment. Trusted certificates are used for the Server Trusted certificates in the Administration Tool.

l User – This certificate type is used to validate a user who log in to the SecureTransport Server using a certificate or SSH key. User certificates are used for the User Login certificates in the Administration Tool.

Certificates are also categorized by type. Currently SecureTransport supports two types of certificates:

l X.509

l PGP

Certificates also have a name used in the Administration Tool to identify the certificate.

The SecureTransport Server API has three interfaces related to the certificates:

l CertificateReference on page 74 - Describes the CertificateReference interface.

l CertificateDetails on page 74 - Describes the CeritificateDetails interface.

l CertificateManager on page 75 - Describes the CertificateManager interface.

CertificateReference Identifies the certificate in the store and provides very basic information about the certificate. This includes the usage, type, and name. Certificate references also have an id property that uniquely identifies the reference. The certificate reference can be obtained in one of two ways:

l From the application configuration using the CustomAttributes interface. For more information, see Custom attributes on page 71.

l By searching the certificate store using the CertificateManager interface.

CertificateDetails Represents the actual certificate data. This includes the certificate content encoded in a standard format, such as PEM format for X.509 certificates and ASCII armor format for PGP certificates. The certificate data also includes the public key associated with the certificate.

Axway SecureTransport 5.3.0 Developer's Guide 74 5 Using the application framework

The following example shows how to get the certificate details when using the package java.security.cert:

CertificateDetails certDetails = certificateManager .getCertificateDetails(certRef); CertificateFactory certFactory = CertificateFactory .getInstance("X.509"); Certificate cert = certFactory.generateCertificate( new ByteArrayInputStream(certDetails.getCertContent()));

The certificate details obtained are based on the CertificateReference called through the CertificateManager interface.

CertificateManager The CertificateManager interface provides methods for:

l Generating certificates using the generateCACertificate, generateLocalPGPCertificate, generateLocalX509Certificate, generatePartnerPGPCertificate, and generateX509Certificate methods.

l Retrieving the certificate references for various types of certificates in the store using the getPartnerCertificates, getLocalCertificates, getTrustedCertificates, and getUserCertificates methods. These methods retrieve a list of certificate references so you can work with a large number of certificates.

l Managing certificates using the importCertificate, importLocalX509Certificate, exportCertificate, deleteCertificate, and related methods.

l Generating certificate signing requests and managing signed certificates using the generateKeyPairAndCSR, importCertificateForCSR, and importPrivateKeyAndCSR methods. These methods return a certificate reference.

l Retrieving the certificate details for a given certificate reference using the method getCertificateDetails and GetCertificateReference.

l Retrieving the private key for local certificates using the method getPrivateKey.

l Retrieving PGP subkeys for PGP certificates.

l Creating a Java Secure Socket Extension (JSSE) SSLContext based on a local key using the method createSSLContext(). This is useful when the local key is used to establish an SSL connection.

These examples illustrate use of CertificateManager:

//import a certificate

Axway SecureTransport 5.3.0 Developer's Guide 75 5 Using the application framework

CertificateFile crtFile = new CertificateFile(); CertificateManager certManager = Factory.getInstance () .getCertificateManager(); certManager.importCertificate("name", CertificateReference.TYPE_X509, CertificateReference.USAGE_TRUSTED, null, null, crtFile.get("fileName"));

//get a certificate reference using CertificateReferenceCriterion CertificateReferenceCriterion certificateCriterion = certManager.getCertificateReferenceCriterion(); certificateCriterion.type(CertificateReference.TYPE_X509); certificateCriterion.usage(CertificateReference.USAGE_TRUSTED); certificateCriterion.hasAccount(false); certificateCriterion.named("ca"); List crts = certManager .getCertificateReferences(certificateCriterion, 0, Integer.MAX_ VALUE); Context.getInstance().setCurrentCertificateReference(crts); CertificateReference certRef = Context.getInstance () .getCurrentCertificateReference().get(0);

//export a certificate ByteArrayOutputStream baos = new ByteArrayOutputStream(); baos.write(certManager.exportCertificate(certRef, false, null)); crtFile.put("fileName2", baos);

//generate a certificate certRef = certManager.generateCACertificate(2048, new Subject("certificate name", "", "", "", "", ""), "CAPassword", 100);

Working with AccountManager The AccountManager is a programmatic method of manipulating users and accounts that allows customized management of accounts in SecureTransport. It provides methods to create, retrieve, update, and delete accounts and their associated authentication information. There are also methods to authenticate access, change the password, and manage the account attributes.

The Account object contains the attributes of an account. The attributes include a unique account name, type, user ID, group ID, home folder, email, phone, html template folder path, RBFT mode, and notes. The account must have a type of either user, service, or template.

Each Account object has one associated User object that provides the authentication information for access to the account. Access to the account can be authenticated using a login and password or certificate defined by the SecureTransport system or it can be authenticated using an

Axway SecureTransport 5.3.0 Developer's Guide 76 5 Using the application framework

external authentication agent like LDAP or Siteminder. The User object contains the unique user login name and an attribute to optionally identify it as externally authenticated. If the user is not externally authenticated, the User object contains a Password object with authentication credentials.

The following example shows how to authenticate a user for access to an account:

AccountManager mgr = Factory.getInstance().getAccountManager(); User user; Account account; try { mgr.authenticate("mylogin", "mypassword".toCharArray()); user = mgr.getUser("mylogin"); account = mgr.getAccount(user); catch (NoSuchUserException ) {

// Try another authentication method. Throw exception of failure. } catch (NoSuchAccountException ex) { // User authenticates but is not associated with an account. }

The authenticate method throws a NoSuchUserException if the user is unknown or should be externally authenticated. Customized authentication code can authenticate the user through some other method and if successful, check if the user is associated with an account.

Note The method AccountManager#newAccountId(String) does not allow "" as an argument Invoking this method with "", null, or a malformed argument throws an IllegalArgumentException.

AccountManager includes method to create, retrieve, update, delete the following:

l Account

l AddressBookContact

l Idf (transfer profile)

l Site

l SiteTemplate

l User

For each of these types, the following methods are defined:

l newData – Returns a new object.

l create – Make the object persistent.

l gets – Returns a list of objects based on Criterion.

l update – Save changes to a persistent object.

l delete – Deletes a persistent object.

The following topics describe how to work with transfer sites and template accounts:

Axway SecureTransport 5.3.0 Developer's Guide 77 5 Using the application framework

l Working with transfer sites on page 78 - Describes how to work with transfer sites.

l Working with template accounts on page 80 - Describes how to work with template accounts.

Working with transfer sites As described in the SecureTransport Administrator's Guide, a transfer site is a location, such as a local folder or a protocol server used during a transfer. Each SecureTransport account can have zero or more transfer sites. Use methods of the AccountManager and Site interfaces to create, read, update, and delete Site objects and to associate them with accounts.

The following topics describe how to with transfer sites:

l Overview on page 78

l Protocol-specific properties on page 78

l Transfer site templates on page 79

l Creating, reading, updating, and deleting on page 79

Overview A transfer site has the following properties:

l Name – Each site of an account must have a unique name.

l Protocol – A string that identifies the file transfer protocol for the site. SecureTransport supports the following protocols:'AS2', 'Connect:Direct', 'Folder Monitor', 'FTP(S)', 'HTTP(S)', 'Recipient Based File Transfer', and 'SFTP (SSH)'.

l Anchor – A string that, combined with the Protocol, identifies the site uniquely among the sites of the account.

l Custom Attributes – Provides access to the properties of the site that are specific to the Protocol.

l Site Template – If present, an object that specifies the Protocol and the Custom Attributes.

Protocol-specific properties Each protocol has a custom property bean that a program can access using the setCustomAttributes and getCustomAttributes methods of the Site interface. The custom property beans for the pre-defined protocols are defined by the following annotated interfaces:

l AdHocSiteProperty

l As2SiteProperty

l ConnectDirectSiteProperty

Axway SecureTransport 5.3.0 Developer's Guide 78 5 Using the application framework

l FolderSiteProperty

l FtpSiteProperty

l HttpSiteProperty

l PesitSiteProperty

l SshSiteProperty

Each of these interfaces can be extended to add properties. For the details of these interfaces, see the API online help.

The following example illustrates how to set custom properties for a site:

CustomAttributes customAttributes = site.getCustomAttributes(); HttpSiteProperty httpSiteProperties = customAttributes.getCustomProperties(HttpSiteProperty.class); httpSiteProperties.setHost(server); httpSiteProperties.setPort(port); httpSiteProperties.setUsername(username); httpSiteProperties.setPassword(password); accManager.updateSite(site);

Transfer site templates A transfer site template represents a protocol and its protocol-specific properties. Every protocol- specific property, represented by a custom property of the site template custom attributes, must have a value. The value can be a fixed value or a placeholder. A placeholder has a name and an optional default value. For a description of the syntax and usage of placeholders in a site template, see the topic on site templates in the SecureTransport Administrator's Guide. In SecureTransport 4.9, site templates are supported only for the Connect:Direct protocol.

When a transfer site is defined using a site template, the protocol must match and the protocol- specific properties of the site template are used. If the site template uses placeholders for any custom properties, the custom properties of the site must define the values of the placeholders. The custom properties are represented by a Java map. To define a placeholder, the map key is the placeholder name and the map value is the value to be substituted for the placeholder. To use the default value of the placeholder, defined in the site template, the map key is the placeholder name followed by a hyphen character and the map value is ignored.

Creating, reading, updating, and deleting Use the AccountManager methods to create, access, update, use, and delete site templates.

The following example illustrates how to create and use a site template:

Axway SecureTransport 5.3.0 Developer's Guide 79 5 Using the application framework

// Create a site template AccountManager accountManager = Factory.getInstance() .getAccountManager(); SiteTemplate siteTemplate = accountManager.newSiteTemplateData("TestTmplt", Events.PROTOCOL_NAME_CD);

// Set the site template protocol-specific properties CustomAttributesBean customAttributes = new CustomAttributesBean(); ConnectDirectSiteProperty cdSiteProperties = customAttributes. getCustomProperties(ConnectDirectSiteProperty.class); cdSiteProperties.setLocalServerName(server); cdSiteProperties.setLocalServerPort(port); cdSiteProperties.setUserName(username); cdSiteProperties.setPassword(password); cdSiteProperties.setRecScript(recScript); cdSiteProperties.setSendScript(sendScript); siteTemplate.setCustomAttributes(customAttributes); // Save the site template SiteTemplate persistedSiteTemplate = accountManager.createSiteTemplate(siteTemplate);

// Create a site that references the site template Site site = accountManager.newSiteData("TestSite", Events.PROTOCOL_NAME_CD); site.setSiteTemplate(persistedSiteTemplate);

// Save the site in an account accountManager.createSite(site, account);

Working with template accounts As described in the SecureTransport Administrator's Guide, an account template can be used to provide access to users defined in LDAP directory or other external user repository. Using the SecureTransport server API, an account template can be represented as a template account, an account created with its type set to Account.ACCOUNT_TEMPLATE.

The following example illustrates creating a template account:

AccountManager mgr = Factory.getInstance().getAccountManager(); Account acct = mgr.newAccountData("Virtual Users", Account .ACCOUNT_TEMPLATE); acct.setUsrId("${sess['STSESSION_LDAP_DIR_uidNumber']}"); // Other set method calls for acct as required... acct = mgr.createAccount(account, null); // Persist the account.

Axway SecureTransport 5.3.0 Developer's Guide 80 5 Using the application framework

The parameter to the call to setUsrId in the example is an expression. For more information about using expressions in account templates, see the SecureTransport Administrator's Guide.

Working with business units Business units are used to divide the administration of a SecureTransport server among delegated administrators. They can be arranged in a hierarchy so that administration can be delegated down to lower levels. For more information, see the SecureTransport Administrator's Guide.

The Account, Application, and DelegatedAdminitrator interfaces includes methods to set and get the business unit.

The BusinessUnitManager interface includes methods such as newBusinessUnitData, getBusinessUnit, createBusinessUnit, updateBusinessUnit, and deleteBusinessUnit to create, get, save, update, and delete business units. The BusinessUnit interface includes methods such as getCustomAttributes, getParent, setCustomAttributes, and setParent to set and get the properties of a business unit.

Example This example creates a business unit, saves it, and assigned it to an account.

BusinessUnitManager mgr = Factory.getInstance() .getBusinessUnitManager(); BusinessUnit newBusinessUnit = mgr.newBusinessUnitData("unique_businees_unit_name"); newBusinessUnit.setBaseFolder(new File("file_name")); newBusinessUnit.setBaseFolderAllowedForModifying(true); newBusinessUnit.setHomeUserFolderAllowedForModifying(false); newBusinessUnit.setHtmlTemplateAllowedForModifying(true); newBusinessUnit.setRbftModeAllowedForModifying(false); newBusinessUnit.setHtmlTemplateFolderPath("path"); newBusinessUnit.setRbftMode(RbftModes.ENABLED.toString()); newBusinessUnit = mgr.createBusinessUnit(newBusinessUnit); newBusinessUnit.setHomeUserFolderAllowedForModifying(true); mgr.updateBusinessUnit(newBusinessUnit); account.setBusinessUnit(newBusinessUnit);

For more information, see the API reference.

Axway SecureTransport 5.3.0 Developer's Guide 81 5 Using the application framework

Working with data transformations Using the data transformation API, you can create transformation modules that process both inbound and outbound files. SecureTransport provides a standard transformation module responsible for PGP encryption/decryption. A code sample that ships with the SDK demonstrate how to create a custom ZIP file transformation module.

The following topics describe how to manage and work with data transformations:

l Data transformation overview on page 82 - Provides an overview of data transformations.

l Developing data transformation modules on page 83 - Provides how to instructions for developing data transformation modules.

l Installing transformation modules on page 88 - Provides how to instructions for installing data transformation modules.

l Transformation example on page 88 - Provides a data transformation example.

Data transformation overview Data Transformation consists of the following parts:

l Data Transformation Controller on page 82

l Data transformation modules on page 83

Data Transformation Controller The Data Transformation Controller (DTC) is responsible for invoking the configured transformation modules. The DTC is invoked in two places:

l By the Application Controller agent on the Incoming End event. This can happen when the account receiving the file has subscription to an application and the subscription is configured to transform an incoming file. For example, in the PGP module, this is the place where the incoming files are decrypted and their signature is verified.

l By an Application agent. Application types such as the Basic Application or Standard Router can transform outgoing files. Examples of when transformations can occur include performing an outgoing server- initiated transfer or moving a file to a service account.

To send a file to a subscription, use ApplicationRuntime.sendToUserAccount().

To send a file to a service account, use ApplicationRuntime.sendToServiceAccount().

Axway SecureTransport 5.3.0 Developer's Guide 82 5 Using the application framework

Create an instance of the ApplicationRuntime by calling Factory.getApplicationRuntime(IInProcEvent) from an agent where IInProcEvent is the event provided to your agent by the DTC, for example, calling getAgentEvent() in BaseAgent. Your agent should already have subclassed BaseAgent.

Example: ApplicationRuntime runtime = Factory.getApplicationRuntime (getAgentEvent());

Data transformation modules The DTC by itself is only a framework for performing transformations. The actual work is performed by a set of data transformation modules. A data transformation module has four components:

l Data transformation agent

l Transformation configuration

l TM rules package for transformation event

l Pluggable UI for per-subscription transformation configuration

Developing data transformation modules Each part of the data transformation module is discussed in the following topics:

l Data transformation agent on page 83

l Data Transformation configuration file on page 84

l Rules package for transformation agent on page 85

l Pluggable UI for per-subscription transformation configuration on page 86

l Installing and registering JSPs on page 86

l SecureTransport tag libraries for transformation on page 86

l JavaScript functions and transformations on page 87

Data transformation agent The data transformation agent (DTA) is responsible for reading an input file or the contents of a directory path, performing a transformation on the data, and writing out the resulting data to a new file or set of files containing the transformed data. The DTA class should subclass com.valicert.brules.executionengine.BaseAgent. For more information on BaseAgent, see the API reference in the SDK or Customizing SecureTransport on page 13. The agent is supplied with a set of transformation configuration attributes using the DXAGENT_ TRANSFORMATION_XXX environment variables. The agent can use this information to configure this instance of the transformation. The agent can be implemented as either an in-process agent or

Axway SecureTransport 5.3.0 Developer's Guide 83 5 Using the application framework

as an external agent. There are no special requirements or APIs enforced on an agent. For more information on the DXAGENT_TRANSFORMATION_XXX environment variables than can be used by the DTA, see Application framework object environment variables on page 159. The following environment variables are the most commonly used:

l DXAGENT_TRANSFORMATION_INPUT – the path of the input file

l DXAGENT_TRANSFORMATION_OUTPUT – the path of the output directory

l DXAGENT_TRANSFER_DIRECTION – the direction of the transformation

When using DXAGENT_TRANSFER_DIRECTION you can specify TransferConfiguration.INPUT_FROM_ACCOUNT_TO_APPLICATION for incoming transfers or TransferConfiguration.OUTPUT_FROM_APPLICATION_TO_ACCOUNT for outgoing transfers.

The agent should set the event exit value to one of the following by calling the setEventExitValue() method:

Events.EXIT_TRANSFORM_OK – The transformation was successful and the output directory contains the resulting files/directories

Events.EXIT_TRANSFORM_PASSED – There was no transformation needed and the input is not modified. Pass the file on for further processing

Events.EXIT_TRANSFORM_BLOCKED – There is a problem with the input and transformation processing should stop

For more information, see Transformation event on page 145.

Data Transformation configuration file Each DTM has an associated configuration present in a global transformation configuration file. This file contains all the static attributes of the transformation that are required to manage the transform and map it to a Transaction Manager (TM) rule. The runtime characteristics of each transformation are configured on a per-subscription basis and stored in a database along with the other subscription attributes.

The configuration file is also used to establish the global ordering of the transformations. Here is an example configuration file:

Axway SecureTransport 5.3.0 Developer's Guide 84 5 Using the application framework

The action attribute specifies the state the SecureTransport reports to Axway Sentinel when the integration is enabled.

The transformation name is used in a TM rule to determine which transformation is being applied for a given transformation event. The transformation order is determined by the order of the entries in the configuration file. The transformation agent can be implemented as either an in-process class or as an external agent.

Note When you register multiple transformations for a single subscription, the DTC links them in a chain such that each transformation takes the output from the last one. The order in which multiple transformations are called is listed in the file conf/transforms.xml. The file specifies incoming and outgoing transformations separately. If you change the order in which the transformations are listed, the change affects all subscriptions.

Rules package for transformation agent Each transformation must have a Transaction Manager (TM) rules package installed that allows the TM to execute the associated agent when the transform event is thrown. The following example shows a TM rule for a data transformation agent:

EventType Transformation DXAGENT_TRANSFORMATION_TYPE PGP

Axway SecureTransport 5.3.0 Developer's Guide 85 5 Using the application framework

"true"

Pluggable UI for per-subscription transformation configuration Each transformation can have its own configuration to provide customization on a per-subscription basis. The transformation API allows a pluggable UI using simple JSP files. for more information about the pluggable UI, see Pluggable UI overview on page 54.

Installing and registering JSPs The JSP file for a transformation should be placed in the folder /tomcat/admin/webapps/coreadmin/WEB- INF/plugin/transformations/ and registered in the plugin.xml file also located in the transformations folder. For transformations, the plugin.xml file contains the following information:

Add new pluggable UI files under the element. The following example shows the plugin.xml file with the default PGP transformation and the sample ZIP transformation added.

SecureTransport tag libraries for transformation The JSP file should strictly follow the XML format. There are several tag libraries defined in SecureTransport that can be used. For more information, see Custom JSP files on page 54.

A typical header for a JSP page contains:

Axway SecureTransport 5.3.0 Developer's Guide 86 5 Using the application framework

The tag libraries needed for a transformation are:

where {DATAHANLDERCLASS} represents the fully qualified name of a data handler class implementing com.tumbleweed.st.server.api.DataTransformationHandler. A fully qualified name includes the package and class name.

Use the transformation name as typed in the /conf/transforms.xml file for the {TRANSFORMATION_NAME}

An instance of {DATAHANLDERCLASS} handles user changes after they are sent by the browser. The class also sets custom attributes into the correct context for transformation using the dataTransformation.getCustomAttributes().getCustomProperties() map. The map is automatically serialized by the Data Transformation Controller (DTC) to the SecureTransport database. When needed, the map is populated from the database back through the DTC.

Note The DTA that catches the transformation event accesses the parameters through the BaseAgent.getAgentEnvironmentVariables() map.

The Zip transformation sample uses the following code in the samples/ZipTransformationAgent/dist/tomcat/admin/webapps/coreadmi n/WEB-INF/plugin/transformations/compression.jspx file to implement the st:transformation tag:

JavaScript functions and transformations Use the following format when adding the JavaScript function for a transformation:

Axway SecureTransport 5.3.0 Developer's Guide 87 5 Using the application framework

${PluginNameSpace}_${TRANSFORMATION_NAME}_${CUSTOM_ATTR_NAME}

where ${PluginNameSpace} is predefined by the DTC and equals input for incoming transfers and output for outgoing ones. ${CUSTOM_ATTR_NAME} is the name the Data Transformation Agent (DTA) looks for in the custom attributes map.

The Zip transformation sample uses the following code in the samples/ZipTransformationAgent/dist/tomcat/admin/webapps/coreadmi n/WEB-INF/plugin/transformations/compression.jspx file to implement the JavaScript functions:

Installing transformation modules Perform the following steps to install and configure a transformation module.

1. Before installing a transformation module you need to edit the global transformation configuration file, located in /conf/transforms.xml.

2. Install the transformation agent using the steps described in Installing external agents on page 31 or Installing in-process agents on page 37. 3. Create a rule for executing the agent installed as described in Custom rules on page 18. 4. Install the UI plugin. For more information, see Developing data transformation modules on page 83.

Transformation example A sample transformation application is provided in the samples/ZipTransformationAgent folder of the SDK. The sample application contains Java source code, an ant build script, an install script, pluggable UI files, and Eclipse project files. The sample transformation application allows you to compress or uncompress files in the ZIP format. You can customize the application to compress files in other formats. Parts of the sample application are included in this guide to illustrate how data transformations work.

Working with ConfigurationManager Using the Configuration Manager API you can manipulate server configuration options (also called parameters) and export rules that enable synchronization between the system configuration and configuration files. Class ConfigurationManager depends on st-server-api.jar.

Axway SecureTransport 5.3.0 Developer's Guide 88 5 Using the application framework

The following simple example shows how to create a configuration option, delete a configuration option, and change the value of an option. It also shows how to enable automatic synchronization of an option to an existing file.

Exceptions – ConfigurationException is thrown when there is no parameter with the given name or when a database error occurs during the process.

/* Copyright (c) Axway Software, 2010. All Rights Reserved. */ package devguide;

import com.tumbleweed.st.server.api.Factory; import com.tumbleweed.st.server.api.configuration.Configuration; import com.tumbleweed.st.server.api.configuration.ConfigurationExceptio n; import com.tumbleweed.st.server.api.configuration.ConfigurationManager; import com.tumbleweed.st.server.api.configuration.ExportRule; import com.tumbleweed.st.server.api.configuration.Option; public class ConfigurationDevGuide {

public static final void main(String[] argv) {

// ConfigurationManager instance ConfigurationManager confMan = Factory.getInstance().getConfigurationManager(); // Delete information from previous runs try { Option forDel = confMan.getOption("MyCustomOpt"); if (forDel != null) { confMan.deleteOption(forDel); } } catch (ConfigurationException e) { e.printStackTrace(); } try { confMan.deleteConfiguration("my-custom-config"); } catch (ConfigurationException e) { e.printStackTrace(); } // Set the ftpd listen address to 127.0.0.1 try { confMan.changeOptionValue("Ftp.Host", "127.0.0.1"); } catch (ConfigurationException e) { throw new RuntimeException

Axway SecureTransport 5.3.0 Developer's Guide 89 5 Using the application framework

("Failed to set ftpd listen address", e); } // Create a new configuration option (parameter) named MyCustomOpt Option newOption = confMan.newOptionData(); newOption.setName("MyCustomOpt"); // Option is not a local one newOption.setNode(Option.UNSPECIFIED_NODE); // Option value can be changed on Server Configuration page newOption.setReadOnly(false); newOption.setDescription ("This option controls my custom agent behaviour"); newOption.setValue("default_value"); try { confMan.createOption(newOption); newOption = confMan.getOption("MyCustomOpt"); } catch (ConfigurationException e) { throw new RuntimeException("Failed to create option", e); } // Enable automatic synchronization of MyCustomOpt in the file // /conf/my-custom-config.properties. // This causes the value in the file to be updated whenever the // value of the option is changed. Note that the specified file // must exist. // Specify unique name Configuration myCustomConfig = confMan.newConfigurationData("my-custom-config"); myCustomConfig.setDescription("My custom config file"); // Java properties file myCustomConfig.setFileFormat (Configuration.Format.PROPERTIES); // Specify path relative to , starting with ./ // Use forward slash for Windows path as well myCustomConfig.setFilePath("./conf/my-custom- config.properties"); try { confMan.mergeConfiguration(myCustomConfig); //get the newly persisted Configuration object myCustomConfig = confMan.getConfigurationByName("my-custom-config");

Axway SecureTransport 5.3.0 Developer's Guide 90 5 Using the application framework

} catch (ConfigurationException e) { throw new RuntimeException("Failed to create configuration", e); } // Map the value of MyCustomOpt to the record for my_opt // in the config file ExportRule rule = confMan.newExportRuleData (myCustomConfig, newOption, "", "my_opt"); try { confMan.createExportRule(rule); } catch (ConfigurationException e) { throw new RuntimeException("Failed to create mapping", e); } try { confMan.changeOptionValue("MyCustomOpt", "test"); } catch (ConfigurationException e) { throw new RuntimeException("Failed to chenge option value", e); } // At this point the file /conf/ // my-custom-config.properties contains an entry my_ opt=test }

}

Working with InvocationManager Using the Invocation Manager API you can execute a task on all servers in a large enterprise cluster. All classes depend only on st_server_api.jar.

The following simple example is a command-line utility that changes the value of a configuration option (parameter) on all servers (nodes) in a cluster. You can use this utility to change local options remotely. The utility takes two arguments:

l The name of the configuration option

l The new value for the option

To install the utility:

1. Compile the three Java file.

2. Copy the resulting .jar files to /lib/jars/ of all servers.

Axway SecureTransport 5.3.0 Developer's Guide 91 5 Using the application framework

3. Copy the option_value_change script file to /bin/ and make it executable.

The following topics provide scripts for working with the InvocationManager:

l Utility script: option_value_change on page 92 - Provides the option_value_change utility script.

l ChangeConfigurationOption.java on page 93 - Provides the ChangeConfigurationOption.java script.

l DefaultResult.java on page 97 - Provides the DefaultResult.java script.

l OptionValueChangeInvocableTask.java on page 99 - Provides the OptionValueChangeInvocableTask.java script.

Utility script: option_value_change

#!/bin/sh # # Copyright (c) Axway Software, 2010. All Rights Reserved. # #

PATH=/usr/bin:/bin:/usr/sbin:/sbin

myname=` "${0}"` mydir=` "${0}"`

. "${mydir}/common.sh"

initialize_runas

check_cygwin check_root set_paths

check_java

# # This value must be a multiple of 1024 greater than 1MB. Append the letter # k or K to indicate kilobytes, or m or M to indicate megabytes. # JAVA_MEM_MIN="64M"

Axway SecureTransport 5.3.0 Developer's Guide 92 5 Using the application framework

# # Specify the maximum size, in bytes, of the memory allocation pool. # This value must a multiple of 1024 greater than 2MB. Append the letter # k or K to indicate kilobytes, or m or M to indicate megabytes. # Allocate greater of 120M and 10M * # JAVA_MEM_MAX="200M"

JAVA_OPTS="$JAVA_OPTS -Xms${JAVA_MEM_MIN} -Xmx${JAVA_MEM_MAX}" JAVA_OPTS="-Dtangosol.coherence.cacheconfig=$JAVA_OPTS" JAVA_OPTS="hibernate-cache-config.xml $JAVA_OPTS" JAVA_OPTS="-Dtangosol.coherence.hibernate.cacheconfig= $JAVA_OPTS" JAVA_OPTS="\$Default\$ $JAVA_OPTS" JAVA_OPTS="-Dtangosol.coherence.distributed.localstorage=$JAVA_OPTS" JAVA_OPTS="false $JAVA_OPTS"

JAVA="${JAVA_HOME}/bin/java" CLASS="com.tumbleweed.st.server.sdk.sample.ChangeConfigurationOption"

"${JAVA}" ${JAVA_OPTS} -DFILEDRIVEHOME="${FILEDRIVEHOME}" -classpath \ "${STCLASSPATH}" ${CLASS} "${1}" "${2}"

exit 0

ChangeConfigurationOption.java Note Due to limited line width, two import statements, noted in this example, appears on two lines in this document. They must each appear on one line in the Java code.

package com.tumbleweed.st.server.sdk.sample;

import java.util.List; import java.util.Map;

Axway SecureTransport 5.3.0 Developer's Guide 93 5 Using the application framework

import com.tumbleweed.st.server.api.Factory; import com.tumbleweed.st.server.api.cluster.InvocableTask; import com.tumbleweed.st.server.api.cluster.InvocationManager; import com.tumbleweed.st.server.api.cluster.InvocationManager .InvocationMember; import com.tumbleweed.st.server.api.cluster.InvocationManager .InvocationPackage;

/** * Provides functionality for changing local configuration option on all * nodes in a cluster * */

public class ChangeConfigurationOption { /** * Invocation manager to push tasks through. */ private final InvocationManager mInvocationManager; /** * Default constructor to initialize InvocationManager instance */ public ChangeConfigurationOption() { mInvocationManager = Factory.getInstance ().getInvocationManager(); }

/** * Fire events for calling InvocableTask instances on each node which * changes the option * * @param optionName - name of ConfigurationOption to be changed * @param value - new value of the option * @return - true if change is successful on all nodes, * false otherwise

Axway SecureTransport 5.3.0 Developer's Guide 94 5 Using the application framework

*/ public boolean changeOption(String optionName, String value) { // submit invocation package to change option on all nodes InvocationPackage transaction = mInvocationManager.beginPackage(); transaction.addJob(new OptionValueChangeInvocableTask (optionName, value)); Map> results = transaction.commit(); return getResultFromTransactionExecution(results); }

/** * Fire events for calling InvocableTask instances on each node which * changes the option * * @param optionName - name of ConfigurationOption to be changed * @param value - new value of the option * @return - true if change is successful on all nodes, * false otherwise */ public boolean changeOption(String optionName, String value) { // submit invocation package to change option on all nodes InvocationPackage transaction = mInvocationManager.beginPackage(); transaction.addJob(new OptionValueChangeInvocableTask (optionName, value)); Map> results = transaction.commit(); return getResultFromTransactionExecution(results); }

/**

Axway SecureTransport 5.3.0 Developer's Guide 95 5 Using the application framework

* Display information how to use the script, that call this class */ private static void displayUsage() { StringBuilder output = new StringBuilder("Usage:"); output.append(LINE_SEPARATOR); output.append("option_value_change " + ""); System.out.println(output.toString()); }

/** * Iterate over given map of results * * @param transactionResult - Map of results of task execution * on all nodes * @return true if all tasks executions finish successfully, * false otherwise */ public boolean getResultFromTransactionExecution( Map transactionResult) {

for (InvocationMember nodeMember : transactionResult.keySet()) { List singleNodeResults = transactionResult.get(nodeMember); if (singleNodeResults != null) { for (InvocableTask.Result taskResult : singleNodeResults) { if (taskResult != null && !taskResult.isSuccessful()) { return false; } } } }

return true; }

public static void main(String args[]) { if (args.length != 2) {

Axway SecureTransport 5.3.0 Developer's Guide 96 5 Using the application framework

displayUsage(); } else { String optionName = args[0]; String newOptionValue = args[1]; ChangeConfigurationOption configurator = new ChangeConfigurationOption(); boolean isSuccessfull = configurator.changeOption (optionName, newOptionValue); if (isSuccessfull) { System.out.println("Option value was successfully " + "changed."); } else { System.out.println("Error during change of option value."); } } }

}

DefaultResult.java

package com.tumbleweed.st.server.sdk.sample;

import java.util.Arrays; import java.util.Collections; import java.util.List; import com.tumbleweed.st.server.api.cluster.InvocableTask; /** * Default Result interface implementation. */ public class DefaultResult implements InvocableTask.Result { /** * Serial. */ private static final long serialVersionUID = 1L; /** * Is successful or not. */

Axway SecureTransport 5.3.0 Developer's Guide 97 5 Using the application framework

private final boolean mIsSuccessful; /** * Exception list if any. */ private final List mExceptionList; /** * Construct with successful flag. * * @param isSuccessful see {@link DefaultResult#mIsSuccessful} */ public DefaultResult(boolean isSuccessful) { this(isSuccessful, Collections. emptyList()); } /** * Construct with flag and an exception. * * @param isSuccessful see {@link DefaultResult#mIsSuccessful} * @param e exception to add in the result */ public DefaultResult(boolean isSuccessful, Exception e) { this(isSuccessful, Arrays.asList(e)); } /** * Construct with flag and exception list. * * @param isSuccessful see {@link DefaultResult#mIsSuccessful} * @param exceptionList exceptions to add in the result */ public DefaultResult(boolean isSuccessful, List exceptionList) { mIsSuccessful = isSuccessful; mExceptionList = exceptionList; } @Override public boolean isSuccessful() { return mIsSuccessful; } @Override public List getExceptions() { return mExceptionList; }

}

Axway SecureTransport 5.3.0 Developer's Guide 98 5 Using the application framework

OptionValueChangeInvocableTask.java

package com.tumbleweed.st.server.sdk.sample;

import com.tumbleweed.st.server.api.Factory; import com.tumbleweed.st.server.api.cluster.InvocableTask; import com.tumbleweed.st.server.api.configuration .ConfigurationException; import com.tumbleweed.st.server.api.configuration .ConfigurationManager; import com.tumbleweed.st.server.api.configuration.Option; /** * InvocableTask implementation that is called on each node to change * the option value * */ public class OptionValueChangeInvocableTask implements InvocableTask {

/** * Serial. */ private static final long serialVersionUID = 1L; /** * Name of the option to be changed. */ private final String mOptionName; /** * New value of the option. */ private final String mOptionValue; /** * ConfigurationManager to use. */ private transient ConfigurationManager mConfManager; /** * Result from execution. */ private Result mResult; /** * Whether current process is the Admin console. */ private transient boolean mIsAdmin; public OptionValueChangeInvocableTask(String optionName,

Axway SecureTransport 5.3.0 Developer's Guide 99 5 Using the application framework

String value) { this(optionName, value, Factory.getInstance().getConfigurationManager()); } public OptionValueChangeInvocableTask(String optionName, String value, ConfigurationManager manager) { mOptionName = optionName; mOptionValue = value; mConfManager = manager; } @Override public Result getResult() { return mResult; } @Override public void init(String role) { mIsAdmin = ROLE_NAME_ADMIN.equals(role); if (mConfManager == null) { mConfManager = Factory.getInstance().getConfigurationManager(); } } @Override public void run() { // execute task only on admin role of the cluster //(There is two roles - Admin and TM) if (mIsAdmin) { try { mConfManager.openDatabaseSession(); Option option = mConfManager.getOption(mOptionName); option.setValue(mOptionValue); mConfManager.updateOption(option); mResult = new DefaultResult(true); } catch (ConfigurationException ex) { mResult = new DefaultResult(false, ex); } finally { mConfManager.closeDatabaseSession(); } } }

}

Axway SecureTransport 5.3.0 Developer's Guide 100 5 Using the application framework

Working with NavigationManager You can use the Navigation Manager API to manipulate objects related to navigation entities. Class NavigationManagerDevGuide depends on st-server-api.jar.

The following example shows how to create menus, pages, and navigation menus and how to update and delete them.

Exceptions – MenuConstraintException, PageConstraintException, or NavigationMenuConstraintException are thrown when an attribute violates a constraint.

/* * Copyright (c) Axway Software, 2010. All Rights Reserved. */

package com.tumbleweed.st.server.devguide;

import com.tumbleweed.st.server.api.Factory; import com.tumbleweed.st.server.api.NavigationManager;

import com.tumbleweed.st.server.api.Menu; import com.tumbleweed.st.server.appframework.MenuBean; import com.tumbleweed.st.server.api.MenuConstraintException;

import com.tumbleweed.st.server.api.NavigationMenu; import com.tumbleweed.st.server.appframework.NavigationMenuBean; import com.tumbleweed.st.server.api.NavigationMenuConstraintException;

import com.tumbleweed.st.server.api.Page; import com.tumbleweed.st.server.appframework.PageBean; import com.tumbleweed.st.server.api.PageConstraintException;

public class NavigationManagerDevGuide {

public static void main(String[] args) throws NavigationMenuConstraintException, MenuConstraintException, PageConstraintException {

//navigation manager instance NavigationManager navigationManager = Factory.getInstance() .getNavigationManager();

Axway SecureTransport 5.3.0 Developer's Guide 101 5 Using the application framework

/* Create a new menu */ int parentCode = 1; //holds the parent menu int orderUnderParent = 20; //holds the order under its parent MenuBean menu = new MenuBean(parentCode, orderUnderParent, "CodeNew", "menu ", "/coreadmin/configuration/menunew.jspx"); Menu persistedMenu = navigationManager.createMenu(menu);

/* Update an existing menu */ String newitle = "new title"; //set new title for an existing menu: persistedMenu.setTitle(newitle); navigationManager.updateMenu(persistedMenu);

/* Delete an existing menu */ navigationManager.deleteMenu(persistedMenu.getId());

/* Create a new page */ //holds the unique code number of the page: String code = "tm.servlet.editconditionnew"; //holds the URL of the page: String relativeURL = "/brules/servlet/editconditionnew"; PageBean page = new PageBean(code, relativeURL); Page persistedPage = navigationManager.createPage(page);

/* Update an existing page */ // set new description for an existing page: String newDescription = "new description"; persistedPage.setDescription(newDescription); navigationManager.updatePage(persistedPage);

/* Delete an existing page */ navigationManager.deletePage(persistedPage.getId());

/* Create a new menu */ //holds the unique order of navigation menu: int orderNumber = 8; NavigationMenuBean navigationMenu = new NavigationMenuBean(orderNumber, "TITLE NAVIGATION MENU"); NavigationMenu persistedNavigationMenu = navigationManager.createNavigationMenu(navigationMenu);

/* Update an existing navigation menu */ //set new description for an existing navigation menu String newNavigationDescription = "navigation description";

Axway SecureTransport 5.3.0 Developer's Guide 102 5 Using the application framework

persistedNavigationMenu.setDescription(newNavigationDescription); navigationManager.updateNavigationMenu(persistedNavigationMenu);

/* Delete an existing navigation menu */ navigationManager.deleteNavigationMenu (persistedNavigationMenu.getOrderNumber());

}

}

The following example shows how to create a custom page and assign it to administrative roles.

public void createPage() throws Exception { NavigationManager navigationManager = Factory.getInstance().getNavigationManager();

Page page = navigationManager.newPageData(); page.setCode("test"); page.setRelativeUrl("/coreadmin/account/test.html"); page = navigationManager.createPage(page);

Menu menu = navigationManager.newMenuData(); menu.setCode("TEST_PAGE"); menu.setOrderUnderParent(7); menu.setPageLink("/coreadmin/account/test.html"); menu.setParent(0); menu.setTitle("Test Page"); Set pages = new HashSet(); pages.add(page); menu.setPages(pages); Menu newMenu = navigationManager.createMenu(menu);

List roles = navigationManager.getAdministrativeRoles(null); for(AdministrativeRole role : roles) { navigationManager.createAdministrativeRoleMenus(role.getId(), newMenu.getId(), false); } }

Axway SecureTransport 5.3.0 Developer's Guide 103 5 Using the application framework

Working with ServiceCheck You can use the Service Check API to check if a SecureTransport service is functional or not. Class ServiceCheckDevGuide depends on st-server-api.jar.

This example shows how to perform a check on a service, how to determine if a service is enabled, and how to determine if a service can be restarted.

Exceptions – ServiceCheckException is thrown when a service check error is indicated.

/* Copyright (c) Axway Software, 2010. All Rights Reserved. */

package devguide;

import com.tumbleweed.st.server.api.Factory; import com.tumbleweed.st.server.api.ServerControllerManager; import com.tumbleweed.st.server.api.servicecheck.ServiceCheck; import com.tumbleweed.st.server.api.servicecheck.ServiceCheckException;

public class ServiceCheckDevGuide {

public static void main(String[] args) {

//instance of server controller manager ServerControllerManager scm = Factory.getInstance().getServerControllerManager(); ServiceCheck checker; try { checker = scm.getServiceChecker(ServerControllerManager.HTTPD); } catch (ServiceCheckException e) { throw new RuntimeException("Unable to obtain httpd service checker", e); }

if (!checker.isEnabled()) { System.out.println("Httpd is disabled"); System.exit(0); }

if (checker.isFunctional()) { System.out.println("Httpd is running"); System.exit(0);

Axway SecureTransport 5.3.0 Developer's Guide 104 5 Using the application framework

} else { System.out.println("Httpd is not running"); if (checker.isRestartable()) { System.out.println("Try restarting it"); } else { System.out.println("This is external service and cannot " + "be recovered from within SecureTransport"); } System.exit(1); } }

}

Working with ClusteredManager Clustered Manager provides a facility for making remote procedure calls (RPC) from one node of a standard cluster to another. Although this functionality is not limited, it is most useful for keeping database objects synchronized. The solution is ad-hoc, so you do not need to register your extension anywhere. Just use the SecureTransport Server API, provided in the SDK.

For more information, refer to the sample in the samples/api-samples directory included in the SDK. The implemented CustomDataManager in the sample shows how to replicate method invocations across all nodes and synchronizing all actions on the database table CustomData.

As in the sample, any class can have replicated method calls on all nodes of a standard cluster. The class must meet the following requirements:

l Class annotation @ClusteredManager

l Extends the com.tumbleweed.st.server.api.cluster.ClusteredManagerBase class from the API

l All methods whose calls must be replicated are public and annotated with the @Clustered annotation

The sample also includes a simple example of exception handling. To handle exceptions, call the ClusteredManagerBase.setCallbackHandler (com.tumbleweed.st.server.api.ManagerCallbackHandler) method using your implementation of ManagerCallbackHandler.

Note Clustered Manager RPC is only applicable to a standard cluster. For a large enterprise cluster, see Working with InvocationManager on page 91.

Axway SecureTransport 5.3.0 Developer's Guide 105 Working with event types 6

SecureTransport supports a number of event types. The following topics provide descriptions of the interface for each event type. For more information about the environment variables listed with each event, see Using environment variables on page 155.

l Authentication and session management events on page 106 - Describes and lists the authentication and session management events.

l File transfer authorization and audit events on page 117 - Describes and lists the file transfer authorization and audit events.

l File transfer upload and download events on page 123 - Describes and lists the file transfer upload and download events.

l File and directory management events on page 129 - Describes and lists the

l Server extension events on page 139 - Describes and lists the file and directory management events.

l Application framework events on page 140 - Describes and lists the application framework events.

l Server-initiated transfer events on page 142 - Describes and lists the server-initiated transfer events.

l Schedule event on page 144 - Describes the schedule events

l Transformation event on page 145 - Describes the transformation event.

l Password Change event on page 146 - Describes the password Change event.

l PeSIT transfer state coordination events on page 147 - Describes and lists the PeSIT transfer state coordination events.

l Mailbox folder event on page 149 - Describes the mailbox folder event.

l Address book events on page 150 - Describes and lists the address book events.

Authentication and session management events The following events are used when starting, authenticating, or stopping a session. The events are listed in the order called for logging in and authenticating a user.

l Sessions on page 107 - Describes the user and server sessions.

l Certificate Verification event on page 108 - Describes the Certificate Verification event.

l User Configuration event on page 110 - Describes the User Configuration event.

l Password Authentication event on page 114 - Describes the Password Authentication event.

Axway SecureTransport 5.3.0 Developer's Guide 106 6 Working with event types

l Login event on page 116 - Describes the Login event.

l Logout event on page 116 - Describes the Logout event.

l SessionEnd event on page 117 - Describes the SessionEnd event.

Sessions All Transaction Manager events happen within a session. When a session is first created a unique identifier available through the DXAGENT_SESSIONID environment variable is assigned. Agents can associate data with the session using the Session State API. For more information, see BaseAgent class on page 43. When a session is terminated, the session state is removed.

There are two types of sessions created in SecureTransport:

l User sessions on page 107

l Server sessions on page 107

User sessions A session initiated by users logging in through protocol servers such as FTP, SSH, or HTTP and transferring files and performing other activities interactively. The session begins with a series of authentication events:

1. Certificate Verification – optional 2. User Configuration – always sent 3. Password Authentication – optional 4. Login – always sent

Once the user is logged in, any number of events can occur depending on the actions taken by the user. When a user logs out or the session is terminated because of a , a Logout event is sent.

Server sessions A server session is initiated within the SecureTransport Server. SecureTransport Server performs a number of tasks outside of user sessions. These tasks include:

l Scheduled Activities

l Folder Monitoring

l AS2 Message Handling

l Persistent Event Processing

Unlike a user session, there is no special event indicating the start of a server session. The first event in a server session depends on the particular task the session was created for. Regardless of how a server session is started, it always ends with a Session End event.

Axway SecureTransport 5.3.0 Developer's Guide 107 6 Working with event types

Certificate Verification event The purpose of the certificate event is to authenticate an end user based on the user's certificate or key. The certificate event is sent to verify the user certificate during SSL negotiation or to verify the user SSH key during SSH authentication.

The following topics provide detailing information about the Certificate Verification event:

l Input stream on page 108

l Environment variables on page 108

l Exit codes on page 109

l Customization considerations on page 109

Input stream

l During the SSL negotiation using client certificate authentication – An agent triggered by this event receives the client certificate in PEM-encoded format using standard input that is delimited by:

-----BEGIN CERTIFICATE----- -----END CERTIFICATE-----

l During SSH authentication using key authentication– An agent triggered by this event receives the client public key. The public key is first encoded according to the format defined in the X.509 standard. The resulting binary data is then encoded into a text form using base-64. The resulting text is available to the agent in standard input format.

Environment variables DXAGENT_INPUTFORMAT

DXAGENT_LOGINNAME

Note DXAGENT_LOGINNAME is available only for SSH authentication.

The agent is expected to decode the data and validate the certificate. If the login name is present, the agent must determine whether the user identified by the login name can be authenticated using the submitted certificate or key. Otherwise the agent must determine the user name.

The agent must output multiple lines of information. Each line is terminated with the newline character.

Axway SecureTransport 5.3.0 Developer's Guide 108 6 Working with event types

Line Function Number

Line 1 Specifies the certificate cookie. This cookie is present in other events in the session through the DXAGENT_CERTCOOKIE environment variable. The presence of the cookie can indicate that certificate authentication has occurred.

Line 2 Specifies the SecureTransport user name authorized to login.

Lines 3 Data in these lines is sent back to the client, which displays the text in the interactive through FTP session or in its logs. n

Exit codes The agent must output multiple lines of information. Each line is terminated with the newline character.

Exit Code Result

0 The user is authenticated, requires password authentication with the user name returned on the second line of output.

1 The user is authenticated, does not require a password.

2 The verification did not complete. The user is not authenticated, SecureTransport terminates the SSL negotiation and disconnects.

Any other The user is not authenticated, SecureTransport terminates the SSL negotiation and exit code disconnects.

Customization considerations Built-in pre-processing rules for this event normalize the input for the event and enable agent chaining. If the original input to the agent is a certificate, that certificate is saved in a session variable called CLIENT_CERTIFICATE. If the original input is a public key, the certificate corresponding to the key is looked up in the user certificate store and saved in the same session variable. Built-in pre-processing rules also perform basic validation of the certificate including an expiration and effective date check and chaining to a trusted root.

Built-in main processing rules contain agents implementing different methods of certificate verification and associating a user with the certificate supported by SecureTransport.

Axway SecureTransport 5.3.0 Developer's Guide 109 6 Working with event types

Built-in post-processing rules for the certificate event are organized differently from other events. The post processing step is not expected to be reached if certificate authentication is performed successfully in the main processing rules. It is defined at a lower precedence setting than the main processing rules and relies on execution of the NextPrecedence agent at the end of main processing. For best results, perform the following steps to add a custom certificate verification:

1. Define a custom rule in the custom precedence range of 50-99, such as 50. 2. In the actions, include the custom certificate verification agent followed by the NextPrecedence agent.

The custom certificate agent should use the CLIENT_CERTIFICATE session variable instead of accessing the input stream to get the certificate data. 3. When verification is successful, the custom agent should produce the required output and terminate the agent chain. 4. If verification fails, the custom agent should continue with the chain to allow the built-in agents to try validating the certificate.

User Configuration event This event provides user information such as a password, upload restrictions, and access control rights for SecureTransport. The event occurs during the early stages of user login.

The output from the configuration agent can contain one or more of the sections defined in the following table. Zero or more sections can appear in the output stream, but each section can appear no more than once. Each section heading must appear on a line by itself, and the line or lines in that section follow it. The [passwd] section has exactly one line following the heading.

Section Syntax

[passwd] [virtual | real] user:password:uid:gid:gcos:home:shell

[config] class name *:*:*:* passwd-policy length:alpha:numeric:special

In the following example, a password entry for the user demo is provided by a configuration agent so the system running SecureTransport does not require a /etc/passwd entry for a Windows- based user. The user is tagged as virtual, effectively making the virtual user home directory the root directory. The configuration agent must output the sections as shown in the following examples:

For UNIX

[passwd] virtual demo::100:100:Demo User:/home/demo:/bin/sh [config] class VirtClass *:*:*:*

For Windows

Axway SecureTransport 5.3.0 Developer's Guide 110 6 Working with event types

[passwd] virtual demo::100:100:sysuser=domain\\user:/drives/c/demo:/bin/ sh [config] class VirtClass *:*:*:*

Note The home directory on Microsoft Windows requires special processing. The expected format is /drives// so c:\demo\home is represented as /drives/c/demo/home.

The following topics provide detailed information about the User Configuration event:

l Environment variables on page 111

l Exit codes on page 111

l Customization considerations on page 112

l Example on page 113

Environment variables DXAGENT_LOGINNAME

DXAGENT_LOGINPASS

DXAGENT_TARGET

Note In Single Sign On (SSO) environments, DXAGENT_LOGINNAME and DXAGENT_ LOGINPASS might not be set when a user logs in through an SSO portal using a web browser. DXAGENT_LOGINPASS is only available if password authentication is requested. When a user is authenticated based only on the certificate, the password is not available.

Exit codes

Exit Code Description

0 OK

1 Unsupported user type

2 No such user

Axway SecureTransport 5.3.0 Developer's Guide 111 6 Working with event types

Customization considerations The main purpose of the event is to produce information about the user. In many environments this requires authenticating the user first. If password authentication will be performed, the password is available in the event. When the password is available during configuration, the built-in agents authenticate the user as part of the process of retrieving configuration information and save the authentication results in the AUTHENTICATION_RESULT session variable. The password authentication agent returns the result from the AUTHENTICATION_RESULT variable. Custom configuration agents can set this state variable, eliminating the need to write a custom password authentication agent.

Also, some of the user configuration information might not come from a single source or agent. Built-in rules allow agents to produce a part of the output through the use of session variables. The built-in post-processing agent combines the session variables to produce the final output required by the event. These session variables are:

CONFIG_PASSWD – [passwd] section of the User Configuration event output.

CONFIG_CLASS – [class] section of the User Configuration event output.

CONFIG_PASSWD_POLICY – password policy

Built-in post-processing rules for the user configuration event are organized differently from other events. The post-processing step is defined at a lower precedence setting than main processing rules and relies on executing the NextPrecedence agent at the end of the main processing.

Most user configuration event customizations should follow this pattern:

1. Define a custom rule in the custom precedence range of 50-99, such as 50.

2. Include the one or more custom agents followed by the NextPrecedence agent.

3. A custom agent can perform one or more of the following actions:

l Set the CONFIG_PASSWD session variable and authenticate the user if the password is available. Save the authentication result in the AUTHENTICATION_RESULT session variable. Regardless of the result the agent chain should continue to allow built-in processing.

l Set the CONFIG_CLASS session variable to override the default user class assignment.

l Set the CONFIG_PASSWD_POLICY to supply a custom password policy.

If an agent implements an authentication mechanism where the login name is case insensitive, the agent should convert the login name into a canonical form when inserting it into the CONFIG_ PASSWD session variable. The canonical form of all login names that identify the same user should be exactly the same string. This can be achieved by converting the login name to either lower or upper case. SecureTransport maintains certain information associated with login names. This association is case sensitive.

Additionally, a custom User Configuration agent can define directory mapping to map a virtual client path to an absolute native path. The mapping is specified using session state variables. There is one variable for each mapping. The name of the variable containing the map entry is CONFIG_ DIRENTRY_MAP_X where X is the sequence number of the map starting with 0. Each mapping

Axway SecureTransport 5.3.0 Developer's Guide 112 6 Working with event types

variable contains the virtual client path, then a carriage return line feed sequence, followed by the absolute native path specifying what the client path is mapped to. The CONFIG_COUNT_ DIRENTRIES session variable contains the total number of mappings.

The following example shows a two entry map:

mymapped -> //shared/somefolder myfolder/anotherMap -> /var/real/path

represented with the following session variables:

CONFIG_DIRENTRY_MAP_0 mymapped /net/shared/somefolder CONFIG_DIRENTRY_MAP_1 myfolder/anotherMap /var/real/path CONFIG_COUNT_DIRENTRIES 2

An agent should not assume the map is empty, it should first retrieve the value of the CONFIG_ COUNT_DIRENTRIES session variable and if present, use it as a starting index for the new entries.

Note For the mapping to function properly, both the virtual client path and the directory it is mapped to must exist on the file system. The content of the mapped directory gets replaced with the content of the target directory.

Example

package com.tumbleweed.st.server.tm.agents; import java.io.File;

import com.tumbleweed.st.server.api.Events; import com.tumbleweed.st.server.api.SessionVariables; import com.tumbleweed.st.server.api.ClientPath; import com.valicert.brules.executionengine.BaseAgent; import java.text.MessageFormat;

public class TestAgent extends BaseAgent { public boolean executeAgent() { int newConfigCountEntries; try { File sharedFolder = new File("/tmp/share"); String homedir = getEnvironmentVariable(Events

Axway SecureTransport 5.3.0 Developer's Guide 113 6 Working with event types

.DXAGENT_HOMEDIR); ClientPath = new ClientPath("/myshare"); File clientFolder = new File(homedir, cp.getPath()); int currentMapEntry = 0; try { currentMapEntry = Integer.parseInt(readOptionalSessionString (SessionVariables.CONFIG_COUNT_DIRENTRIES)); } catch (Exception e) {

}

final String currentMapVariable = SessionVariables.CONFIG_DIRENTRY_MAP_PREFIX + Integer.toString(currentMapEntry); final String currentMapValue = MessageFormat.format( "{0}" + SessionVariables.CONFIG_DIRENTRY_MAP_SEPARATOR + "{1}", new Object[] {cp, sharedFolder.getAbsolutePath()}); writeSessionString(currentMapVariable, currentMapValue); writeSessionString(SessionVariables.CONFIG_COUNT_DIRENTRIES, Integer.toString(++currentMapEntry)); } catch (Exception e) { e.printStackTrace(); } return true; } }

Password Authentication event This event follows the user configuration event if a user is authenticated using a password. If the user is authenticated using only a certificate or SSH key, the password authentication event is not sent.

Note The password might be verified during the processing of the User Configuration Event. Agents should avoid checking the password twice.

The following topics provide detailed information about the Password Authentication event:

l Environment variables on page 115

l Output stream on page 115

l Exit codes on page 115

l Customization considerations on page 116

Axway SecureTransport 5.3.0 Developer's Guide 114 6 Working with event types

Environment variables DXAGENT_TARGET

DXAGENT_LOGINNAME

DXAGENT_LOGINPASS

Output stream The first line of output (if any) is used to set DXAGENT_AUTHCOOKIE. If you do not wish to set this cookie, either output nothing, or if an authentication message is desired, output a single newline.

All subsequent lines of output (if any) are sent to the client as an authentication message.

Line Function Number

Line 1 Specifies the authentication cookie that is used to identify this session. This cookie is passed to other agents to allow state maintenance across agents.

Line 2 Data in these lines is sent back to the client as a server side message. The client through displays this information in the interactive FTP session or in its logs. n

Exit codes Any non-zero exit status is treated as an authentication failure by SecureTransport.

Exit Code Result

-64 General failure.

-5 Virtual user password is expired.

-4 Real user or mapped real user password is expired.

-3 Error retrieving password/user information.

-2 Account expired.

-1 Account locked.

0 OK.

Axway SecureTransport 5.3.0 Developer's Guide 115 6 Working with event types

Exit Code Result

1 Authentication failed.

2 Access denied.

Customization considerations The built-in agent expects the AUTHENTICATION_RESULT session variable to be set and sets the exit code to its value. For best results, implement custom authentication through an agent triggered by the User Configuration event instead of the Password Authentication event.

Login event This event occurs in the last stages of the login after successful authentication. An agent triggered by this event can set the user cookie and return a login message back to the client.

The following topics provide detailed information about the Login event:

l Output stream on page 116

l Exit codes on page 116

Output stream The first line of output, up to a newline character to set the value of the DXAGENT_USERCOOKIE environment variable. All remaining lines are sent transparently to the user as a login message. The agent exit status is ignored and has no effect on the login process.

Exit codes Exit codes for this event are ignored by the protocol servers and do not affect the flow of agents.

Logout event This event occurs when the user session is terminated. An agent triggered by this event can generate a logout message.

The following topics provide detailed information about the Logout event:

l Output stream on page 117

l Exit codes on page 117

l Customization considerations on page 117

Axway SecureTransport 5.3.0 Developer's Guide 116 6 Working with event types

Output stream The agent should send the logout message to the output stream.

Exit codes Exit codes for this event are ignored by the protocol servers and do not affect the flow of agents.

Customization considerations The post-processing rules release the session state and other resources associated with the session. It is critical for custom rules not to interfere with post-processing steps and not to perform any actions after built-in post processing.

SessionEnd event This event occurs when a server-initiated session is terminated.

The following topics provide detailed information about the SessionEnd event:

l Exit codes on page 117

l Customization considerations on page 117

Exit codes Exit codes for this event are ignored by the protocol servers and do not affect the flow of agents.

Customization considerations The post-processing rules release the session state and other resources associated with the session. It is critical for custom rules not to interfere with post-processing steps and not to perform any actions after built-in post processing.

File transfer authorization and audit events File Transfer Authorization events start an upload or download. File Transfer Audit events perform tracking tasks on uploads and downloads. Incoming and outgoing events are used for the following reasons when users upload and download files from a server:

l To move data

l To allow or deny permission to perform the file transfer

Axway SecureTransport 5.3.0 Developer's Guide 117 6 Working with event types

l To notify the system administrator or other designated users when files have been uploaded to or downloaded from the server

Incoming events are called when a user uploads data to the server. Outgoing events occur when a user downloads data from the server.

Exit codes for the following events are ignored by the protocol servers and do not affect the flow of agents:

l Incoming End

l Incoming Error

l Incoming Abort

l Outgoing End

l Outgoing Error

l Outgoing Abort

Each transfer begins with a start event and ends with one error, end, or abort event. If the start event was not processed successfully, no end, error, or abort events are sent.

The following topics describe the file transfer authorization and audit events:

l Incoming Start event on page 118 - Describes the Incoming Start event.

l Incoming End event on page 119 - Describes the Incoming End event.

l Incoming Error event on page 120 - Describes the Incoming Error event

l Incoming Abort event on page 120 - Describes the Incoming Abort event.

l Outgoing Start event on page 121 - Describes the Outgoing Start event.

l Outgoing End event on page 122 - Describes the Outgoing End event.

l Outgoing Error event on page 122 - Describes the Outgoing Error event.

l Outgoing Abort event on page 123 - Describes the Outgoing Abort event.

Incoming Start event This event occurs at the start of an upload. Allow or deny permissions for users to upload a file to the server can be defined by the agent triggered by this event. A nonzero exit code prevents uploading.

The following provide detailed information about the Incoming Start event:

l Environment variables on page 118

l Exit codes on page 119

Environment variables DXAGENT_TARGET

DXAGENT_FULLTARGET

Axway SecureTransport 5.3.0 Developer's Guide 118 6 Working with event types

DXAGENT_XFERTYPE

DXAGENT_NOOVERWRITE

Exit codes Any exit code not listed in the following table is treated as an error and the upload is denied.

Exit Code Result

-64 Failure, any code other than 0 is treated as an error, the default value is -64

-2 No such file

-1 Permission denied

0 Allow transfer

Incoming End event This event occurs at the end of an upload session. It primarily alerts someone that files have been uploaded to the server.

The following topics provide detailed information about the Incoming End event:

l Environment variables on page 119

l Exit codes on page 120

l Customization Considerations on page 120

Environment variables DXAGENT_TARGET

DXAGENT_FULLTARGET

DXAGENT_XFERTYPE

DXAGENT_CHMODTO

DXAGENT_CHOWNUID

DXAGENT_CHOWNGID

DXAGENT_TRANSFERRED_BYTES

Axway SecureTransport 5.3.0 Developer's Guide 119 6 Working with event types

Exit codes Exit codes for this event are ignored by the protocol servers and do not affect the flow of agents.

Customization Considerations Built-in pre-processing rules set up the event to be processed as a persistent event without retries. For more information about persistent events, see Additional environment variables on page 168.

Built-in post-processing rules include triggering applications. If a custom agent modifies or deletes the transferred file, it can interfere with application processing.

Incoming Error event This event occurs when an unexpected interruption occurs when a file is being uploaded to the server. This kind of error usually occurs due to network problems. For HTTPS transfers, aborts also generate this event.

The following topics provide detailed information about the Incoming Error event:

l Environment variables on page 120

l Exit codes on page 120

Environment variables DXAGENT_TARGET

DXAGENT_FULLTARGET

DXAGENT_XFERTYPE

DXAGENT_TRANSFERRED_BYTES

Exit codes Exit codes for this event are ignored by the protocol servers and do not affect the flow of agents.

Incoming Abort event This event occurs when the user interrupts a file transmission by using a method such as Ctrl+C or break. Depending on the protocol, it can be difficult to distinguish between an error and an abort case. Both HTTPS and SSH transfers generate an incoming error event when the transfer is aborted.

Note Treat abort and error events using the same technique, do not rely upon the differences between an abort and an error event.

Axway SecureTransport 5.3.0 Developer's Guide 120 6 Working with event types

Environment variables DXAGENT_TARGET

DXAGENT_FULLTARGET

DXAGENT_XFERTYPE

DXAGENT_TRANSFERRED_BYTES

Exit codes for this event are ignored by the protocol servers and do not affect the flow of agents.

Note Many native FTP clients including UNIX and Windows do not resolve an abort properly. The server does not report these aborts and incoming or outgoing abort agents are not triggered.

Outgoing Start event This event occurs at the start of a download. An agent triggered by this event can give or deny permissions for users to download a file. A non-zero return code prevents the download.

The following topics provide detailed information about the Outgoing Start event:

l Environment variables on page 121

l Exit codes on page 121

Environment variables DXAGENT_TARGET

DXAGENT_FULLTARGET

DXAGENT_XFERTYPE

Exit codes Any exit code not listed in the following table is treated as an error and the upload is denied. The default error code used by the stream_start.pl agent is -64.

Exit Code Result

-2 No such file

-1 Permission denied

0 Allow transfer

Axway SecureTransport 5.3.0 Developer's Guide 121 6 Working with event types

Outgoing End event This event occurs at the end of a download session. An agent triggered by this event primarily alerts you that files have been downloaded from the server.

The following topics provide detailed information about the Outgoing End event:

l Environment variables on page 122

l Exit codes on page 122

Environment variables DXAGENT_TARGET

DXAGENT_FULLTARGET

DXAGENT_XFERTYPE

DXAGENT_TRANSFERRED_BYTES

Exit codes Exit codes for this event are ignored by the protocol servers and do not affect the flow of agents.

Outgoing Error event This event occurs when an unexpected interruption occurs during a file download from the server. The most common reason for this type of error is usually due to a network problem. For HTTP/S transfers, aborts are handled by this agent.

The following topics provide detailed information about the Outgoing Error event:

l Environment Variables on page 122

l Exit codes on page 123

Environment Variables DXAGENT_TARGET

DXAGENT_FULLTARGET

DXAGENT_XFERTYPE

DXAGENT_TRANSFERRED_BYTES

Axway SecureTransport 5.3.0 Developer's Guide 122 6 Working with event types

Exit codes Exit codes for this event are ignored by the protocol servers and do not affect the flow of agents.

Outgoing Abort event This event occurs when users interrupts a file transmission using a kill method like Ctrl+C or break. For HTTPS transfers it is not possible to detect an abort. So, aborts are handled by the Outgoing Error Agent.

The following topics provide detailed information about the Outgoing Abort event:

l Environment variables on page 123

l Exit codes on page 123

Environment variables DXAGENT_TARGET

DXAGENT_FULLTARGET

DXAGENT_XFERTYPE

DXAGENT_TRANSFERRED_BYTES

Exit codes Exit codes for this event are ignored by the protocol servers and do not affect the flow of agents.

File transfer upload and download events These events are used by multiple protocols to move files to or from the server.

Every FTP, SSH, or HTTP command that involves file system access has an associated command event. Rules and agents contained in the built-in Streaming rules package provide the default processing of those commands. Most commands are preceded by FTP Cmd - although the events are not specific to the FTP protocol.

Note Some command events are used only by the FTP protocol, and not for other protocols.

Certain command events carry command line arguments that are passed by the user. A space- delimited list of these arguments is passed in using the DXAGENT_EXTRAARGS environment variable.

The following topics describe the file transfer upload and download events:

Axway SecureTransport 5.3.0 Developer's Guide 123 6 Working with event types

l FTP Cmd - STOR event on page 124 - Describes the FTP Cmd - STOR event.

l FTP Cmd - RETR event on page 125 - Describes the FTP Cmd - RETR event.

l FTP Cmd - REST event on page 126 - Describes the FTP Cmd - REST event.

l FTP Cmd - MDTM event on page 126 - Describes the FTP Cmd - MDTM event.

l FTP Cmd - SIZE event on page 127 - Describes the FTP Cmd - SIZE event.

l FTP Cmd - RTCK event on page 128 - Describes the FTP Cmd - RTCK event.

FTP Cmd - STOR event The file upload event occurs when a file is in the process of being uploaded. An agent should read the file content data from the input stream.

The following topics provide detailed information about the FTP Cmd - STOR event:

l Environment variables on page 124

l Exit codes on page 124

l Input stream on page 124

Environment variables DXAGENT_TARGET

DXAGENT_FULLTARGET

DXAGENT_XFERTYPE

DXAGENT_UMASK

Exit codes

Exit Code Result

-64 General failure.

-1 Permission denied.

0 OK.

1 Command not implemented.

Input stream Contents of file

Axway SecureTransport 5.3.0 Developer's Guide 124 6 Working with event types

Note For text files, STOR receives the file with native line endings. The server automatically translates line endings as needed.

FTP Cmd - RETR event The file download event occurs when a file is in the process of being downloaded. An agent triggered by this event should write the file content data to the output stream.

The following topics provide detailed information about the FTP Cmd - RETR event:

l Environment variables on page 125

l Exit codes on page 125

l Output stream on page 125

Environment variables DXAGENT_TARGET

DXAGENT_FULLTARGET

DXAGENT_XFERTYPE

Exit codes

Exit Code Result

-64 General failure

-2 No such file or directory.

-1 Permission denied.

0 OK.

1 Command not implemented.

Output stream Contents of File

Note For text files, RETR sends the file with native line endings. The server automatically translates line endings as needed.

Axway SecureTransport 5.3.0 Developer's Guide 125 6 Working with event types

FTP Cmd - REST event The transfer restart event occurs when restarting a previous upload or download transfer. An agent triggered by this event stores the position in a session state variable (REST). When a file download or upload request is received, the restart position is retrieved by the agent triggered by the STOR or RETR event and used to set the starting position for the transfer.

The following topics provide detailed information about the FTP Cmd - REST event:

l Arguments on page 126

l Exit codes on page 126

Arguments The DXAGENT_EXTRAARGS environment variable contains the following argument.

Argument Description

Restart Offset Zero-based restart point.

Exit codes

Exit Code Result

-64 General failure.

0 OK.

1 Command not implemented.

FTP Cmd - MDTM event The modification time event occurs when a request to get the modification time of a file is made. An agent triggered by this event outputs the modification time to the output stream. The format you use depends on the server type.

The following topics provide detailed information about the FTP Cmd - MDTM event:

l Environment variables on page 127

l Exit codes on page 127

l Output stream on page 127

Axway SecureTransport 5.3.0 Developer's Guide 126 6 Working with event types

Environment variables DXAGENT_TARGET

DXAGENT_FULLTARGET

Exit codes

Exit Code Result

-64 General failure.

-2 No such file or directory.

-1 Permission denied.

0 OK.

1 Command not implemented.

Output stream HTTP format: DOW MMM HH:MM:SS YYYY where DOW is the day of the week.

All other protocols: YYYYMMDDHHMMSS

FTP Cmd - SIZE event The file size event occurs when the server obtains the size of a file. An agent triggered by this event should output the size of the file to the output stream. Only the first line of output, up to a newline character, is sent to the client as the size. All other output is discarded.

The following topics provide detailed information about the FTP Cmd - SIZE event:

l Environment variables on page 127

l Exit Codes on page 128

l Output stream on page 128

Environment variables DXAGENT_TARGET

DXAGENT_FULLTARGET

DXAGENT_XFERTYPE

Axway SecureTransport 5.3.0 Developer's Guide 127 6 Working with event types

Exit Codes

Exit Code Result

-64 General failure.

-3 Not a plain file.

-2 No such file or directory.

-1 Permission denied.

0 OK.

1 Command not implemented.

Output stream size

FTP Cmd - RTCK event The checksum event occurs in response to a request to do a checksum. An agent triggered by this event outputs the checksum to the output stream, based on the algorithm argument (currently only MD5 is supported).

The following topics provide detailed information about the FTP Cmd - RTCK event:

l Environment variables on page 128

l Arguments on page 129

l Exit codes on page 129

l Output stream on page 129

Environment variables DXAGENT_EXTRAARGS

DXAGENT_TARGET

DXAGENT_FULLTARGET

DXAGENT_XFERTYPE

Axway SecureTransport 5.3.0 Developer's Guide 128 6 Working with event types

Arguments The DXAGENT_EXTRAARGS environment variable contains the following arguments.

Argument Description

method Describes the algorithm to use. Either md5 or crc32.

offset A zero-based offset of the file portion to be hashed.

size The length of the portion to be hashed.

file The target file.

Exit codes

Exit Code Result

-64 General failure.

-2 No such file or directory.

-1 Permission denied.

0 OK.

1 Command not implemented.

Output stream The value of the checksum as a hexadecimal string followed by a newline character.

Note The output is a sequence of 32 hexadecimal digits for md5 or 8 hexadecimal digits for crc32.

File and directory management events These events are used by multiple protocols to manage files and directories on the server. Every FTP, SSH, or HTTP command that involves file system access has an associated command event. Rules and agents contained in the built-in Streaming rules package provide the default processing of those commands. Most commands are preceded by FTP Cmd - . Unless otherwise specified, the events can be used all the supported protocols.

The following topics describe the file and directory management events:

Axway SecureTransport 5.3.0 Developer's Guide 129 6 Working with event types

l FTP Cmd - LIST event on page 130 - Describes the FTP Cmd - LIST event.

l FTP Cmd - NLST event on page 132 - Describes the FTP Cmd - NLST event.

l FTP Cmd - CWD event on page 133 - Describes the FTP Cmd - CWD event.

l FTP Cmd - DELE event on page 134 - Describes the FTP Cmd - DELE event.

l FTP Cmd - MKD event on page 135 - Describes the FTP Cmd - MKD event.

l FTP Cmd - PWD event on page 135 - Describes the FTP Cmd - PWD event.

l FTP Cmd - RMD event on page 136 - Describes the FTP Cmd - RMD event.

l FTP Cmd - RNFR event on page 136 - Describes the FTP Cmd - RNFR event.

l FTP Cmd - RNTO event on page 137 - Describes the FTP Cmd - RNTO event.

l FTP Cmd - CHMOD event on page 138 - Describes the FTP Cmd - CHMOD event.

l FTP Cmd - MIRR event on page 139 - Describes the FTP Cmd - MIRR event.

FTP Cmd - LIST event The directory list event occurs as a result of the directory list command (). An agent triggered by this event should send an ls -al-type directory listing to the output stream. The agent can also provide HTML output if the client is a web browser.

The following topics provide detailed information about the FTP Cmd - LIST event:

l Environment variables on page 130

l Arguments on page 130

l Exit codes on page 132

Environment variables DXAGENT_TARGET

DXAGENT_FULLTARGET

DXAGENT_LISTTARGET

DXAGENT_EXTRAARGS

Arguments The DXAGENT_EXTRAARGS environment variable contains the following options for the directory listing:

-1lcutrfFRaAdgikqsTn -

Axway SecureTransport 5.3.0 Developer's Guide 130 6 Working with event types

Option Description

-1

l Lists in long format, giving mode, number of links, owner, group, size in bytes, and time of last modification for each file. If the file is a special file, the size field contains the major and minor device numbers. If the time of last modification is greater than six months ago it is shown in the format month date year. Files modified within six months show month date time.

c Uses time of last modification of the i-node (file created, mode changed, etc.) for sorting (-t) or printing (-l or -n).

u Uses time of last access instead of last modification for sorting (with the -t option) or printing (with the -l option).

t Sorts by time stamp (latest first) instead of by name. The default is the last modification time.

r Reverses the sort order to get a reverse alphabetic or oldest first order.

f Forces each argument to be interpreted as a directory and list the name found in each slot. This option turns off -l, -t, -s, and -r, and turns on -a. The order is the order in which entries appear in the directory.

F Marks directories with a trailing slash (/), executable files with a trailing asterisk (*), FIFOs with a trailing vertical bar (|), symbolic links with a trailing 'at' sign (@), and AF_ UNIX address family sockets with a trailing equal sign (=).

R Recursively lists subdirectories encountered

a Lists all entries, including those that begin with a period (.), that are normally not listed.

A Lists all entries, including those that begin with a period (.), with the exception of the working directory (.) and the parent directory (..).

d If an argument is a directory, lists only its name (not its contents). Often used with -l to get the status of a directory.

g deprecated

i For each file, prints the i-node number in the first column of the report.

k

q Forces printing of non-printable characters in file names as the character question mark (?)

Axway SecureTransport 5.3.0 Developer's Guide 131 6 Working with event types

Option Description

s Shows the size of the file as the number of file system blocks used instead of bytes

T Shows the file time in seconds since 00:00:00 UTC, Jan. 1, 1970

n The same as -l, except that the owner UID and group GID numbers are printed, rather than the associated character strings.

Exit codes

Exit Code Result

-64 General failure.

-2 No such file or directory.

-1 Permission denied.

0 OK.

1 Command not implemented.

FTP Cmd - NLST event The NLST event occurs in response to a directory listing request for clients issuing the mget and mdelete commands. An agent triggered by this event sends a list of files, one per line, to the output stream.

The following topics provide detailed information about the FTP Cmd - NLST event:

l Environment variables on page 132

l Arguments on page 133

l Exit codes on page 133

Environment variables DXAGENT_TARGET

DXAGENT_FULLTARGET

DXAGENT_LISTTARGET

DXAGENT_EXTRAARGS

Axway SecureTransport 5.3.0 Developer's Guide 132 6 Working with event types

Arguments The DXAGENT_EXTRAARGS environment variable contains the following options for the directory listing:

-Aacfqrtu

This is a subset of options supported by the LIST event. For a description of each option, see FTP Cmd - LIST event on page 130.

Exit codes

Exit Code Result

-64 General failure.

-2 No such file or directory.

-1 Permission denied.

0 OK.

1 Command not implemented.

FTP Cmd - CWD event The CWD event occurs in response to a request to change directory. An agent triggered by this event validates the target directory and stores its value. The value is retrieved through the FTP Cmd - PWD event. See FTP Cmd - PWD event on page 135.

The following topics provide detailed information about the FTP Cmd - CWD event:

l Environment variables on page 133

l Exit codes on page 134

Environment variables DXAGENT_TARGET

DXAGENT_FULLTARGET

Axway SecureTransport 5.3.0 Developer's Guide 133 6 Working with event types

Exit codes

Exit Code Description

-64 General failure.

-2 No such file or directory.

-1 Permission denied.

0 OK.

FTP Cmd - DELE event Subject to the delete restrictions, the DELE event occurs in response to a request to delete a file.

The following topics provide detailed information about the FTP Cmd -- DELE event:

l Environment variables on page 134

l Exit codes on page 134

Environment variables DXAGENT_TARGET

DXAGENT_FULLTARGET

Exit codes

Exit Code Result

-64 General failure.

-2 No such file or directory.

-1 Permission denied.

0 OK.

1 Command not implemented.

Axway SecureTransport 5.3.0 Developer's Guide 134 6 Working with event types

FTP Cmd - MKD event The MKD event occurs in response to a request to make a directory.

The following topics provide detailed information about the FTP Cmd - MKD event:

l Environment variables on page 135

l Exit codes on page 135

Environment variables DXAGENT_TARGET

DXAGENT_FULLTARGET

DXAGENT_UMASK

Exit codes

Exit Code Result

-1 Permission denied

0 OK

1 Command not implemented

FTP Cmd - PWD event The PWD event occurs in response to a request to get the working directory. An agent triggered by this event outputs the current working directory to the output stream. Only the first line of output, up to a newline character, is sent to the client as the current working directory. All other output is discarded.

Exit codes

Exit Code Result

-64 General failure.

-1 Permission denied.

Axway SecureTransport 5.3.0 Developer's Guide 135 6 Working with event types

Exit Code Result

0 OK.

1 Command not implemented.

FTP Cmd - RMD event The RMD event occurs in response to a request to remove a directory. An agent triggered by this event should remove the specified directory. This agent is subject to the restrictions.

The following topics provide detailed information about the FTP Cmd - RMD event:

l Environment variables on page 136

l Exit codes on page 136

Environment variables DXAGENT_TARGET

DXAGENT_FULLTARGET

Exit codes

Exit Code Result

-64 General failure.

-2 No such file or directory.

-1 Permission denied.

0 OK.

1 Command not implemented.

FTP Cmd - RNFR event The RNFR event occurs immediately after the rename command is issued, to determine if the source file exists. An agent triggered by this event returns a zero to indicate that the file exists.

The following topics provide detailed information about the FTP Cmd - RNFR event:

Axway SecureTransport 5.3.0 Developer's Guide 136 6 Working with event types

l Environment variables on page 137

l Exit codes on page 137

Environment variables DXAGENT_TARGET

DXAGENT_FULLTARGET

Exit codes

Exit Code Result

-64 General failure.

-2 No such file or directory.

-1 Permission denied.

0 OK.

1 Command not implemented.

FTP Cmd - RNTO event The RNTO event occurs after the RNFR event, to perform the actual renaming of the file. An agent triggered by this event renames the file and returns a zero to indicate success.

The following topics provide detailed information about the FTP Cmd - RNTO event:

l Environment variables on page 137

l Exit codes on page 138

Environment variables DXAGENT_TARGET

DXAGENT_FULLTARGET

Axway SecureTransport 5.3.0 Developer's Guide 137 6 Working with event types

Exit codes

Exit Code Result

-64 General failure.

-2 No such file or directory.

-1 Permission denied.

0 OK.

1 Command not implemented.

FTP Cmd - CHMOD event The CHMOD event occurs in response to a request to change the modes and permissions of a file.

The following topics provide detailed information about the FTP Cmd - CHMOD event:

l Environment variables on page 138

l Exit codes on page 138

Environment variables DXAGENT_TARGET

DXAGENT_FULLTARGET

DXAGENT_CHMODTO

Exit codes

Exit Code Explanation

-64 General failure.

-2 No such file or directory.

-1 Permission denied.

0 OK.

1 Command Disabled.

Axway SecureTransport 5.3.0 Developer's Guide 138 6 Working with event types

FTP Cmd - MIRR event The MIRR event occurs in response to a request to get a list of mirror locations. An agent triggered by this event outputs mirroring data in the form of a URL, including the pathname in the URL, hostname, and port of each mirror server.

Arguments The DXAGENT_EXTRAARGS environment variable contains the following argument.

Argument Description

Path name Name of path to find mirror for.

Server extension events The following events perform server-specific commands.

The HTTP Cmd - POST command is HTTP-specific and the FTP Cmd - SITE command is FTP-specific.

The following topics describe the server extension events:

l HTTP Cmd - POST event on page 139 - Describes the HTTP Cmd - POST event.

l FTP Cmd - SITE event on page 140 - Describes the FTP Cmd - SITE event.

HTTP Cmd - POST event This event is only for the HTTP protocol. The POST event occurs when a non-SecureTransport related POST request is received from a web client. An agent triggered by this event cannot override the following SecureTransport-specific POST requests:

l Login POST

l File Upload POST

l Set ASCII/Binary POST

l Change Password POST

All other POST requests received from the client can be intercepted and handled by the triggered agent. The agent should accept input on stdin, and provide a response on stdout. Any non-zero agent exit status indicates an error.

The input format sent by the Axway SecureTransport Server to the Post Agent is as follows:

HTTP Request Headers CRLF POST Request Data

Axway SecureTransport 5.3.0 Developer's Guide 139 6 Working with event types

The agent should also manage the parsing and interpretation of POST request data.

The output format sent by Post Agent to the Axway SecureTransport Server is as follows:

HTTP Custom Response Headers CRLF POST Response Data

Note For best results, set binmode STDOUT before sending any output to STDOUT from the POST agent.

The custom response headers are appended to the standard response headers that SecureTransport provides. If no custom response headers are present, the first line of output must be a CRLF pair.

Note SecureTransport sets the HTTP response headers after processing the custom response headers, so it is not possible to override the standard set of headers through agent output. The custom response headers are additive only.

FTP Cmd - SITE event The SITE event occurs in response to a SITE command.

Arguments The DXAGENT_EXTRAARGS environment variable contains the following argument.

Argument Description

Site command Arguments passed to site command.

Application framework events The following events are part of the application framework and are used to control applications.

l Application - Init event on page 140 - Describes the Application - Init event.

l Application - Schedule event on page 141 - Describes the Application - Schedule event.

l Application - Incoming event on page 142 - Describes the Application - Incoming event.

Application - Init event This event indicates that a subscription to an application needs to be initialized. The application agent creates the necessary folder hierarchy under subscription folder or performs other initialization tasks. For example, an application creates a readme file in the subscription folder with instructions on how the application can be used. The event is sent when the user associated with the account that owns the subscription logs in or within a server-initiated session that involves interaction with an application. The event is sent only for those subscriptions that are considered uninitialized. This

Axway SecureTransport 5.3.0 Developer's Guide 140 6 Working with event types

includes: newly created subscriptions, newly modified subscriptions, subscriptions that are associated with an account whose home directory was modified. This event might be sent for a subscription that is fully or partially initialized. Application agents are expected to handle such conditions gracefully. If an application does not have any special initialization needs, it can ignore the event.

The following topics provide detailed information about the Application - Init event:

l Environment variables on page 141

l Exit codes on page 141

Environment variables Application – For more information, see Application framework object environment variables on page 159.

Subscription – For more information, see Application framework object environment variables on page 159.

Exit codes

Exit Code Result

0 success

all others unknown failure

Application - Schedule event This event indicates an application action needs to be performed according to a schedule associated with the application. The TransferLogMaintence application type uses this event. For information on using schedules to transfer data, see Schedule event on page 144.

Environment variables DXAGENT_SCHEDULEDTAG

Application – For more information, see Application framework object environment variables on page 159.

Axway SecureTransport 5.3.0 Developer's Guide 141 6 Working with event types

Application - Incoming event This event is sent when a file associated with application arrives anywhere inside the subscription folder. If a PGP data transformation was configured for the subscription, the file is a result of the data transformation. PGP data transformations are applied prior to invoking an application.

The following topics provide detailed information about the Application - Incoming event:

l Environment variables on page 142

l Exit Codes on page 142

Environment variables DXAGENT_TARGET DXAGENT_FULLTARGET

Application – For more information, see Application framework object environment variables on page 159.

Subscription – For more information, see Application framework object environment variables on page 159.

Transfer Configuration – For more information, see Application framework object environment variables on page 159.

Exit Codes

Exit Code Result

0 success

all others unknown failure

Server-initiated transfer events These events are called during server-initiated transfers to either download files from or upload files to the server.

The server-initiated transfer events use the Site Variables to describe the remote site and location. The event target describes the location of where the files are stored locally. For more information, see Application framework object environment variables on page 159.

Both push and pull events are processed as persistent events with retries. For more information, see Additional environment variables on page 168.

Axway SecureTransport 5.3.0 Developer's Guide 142 6 Working with event types

Each file transfer triggers a sequence of events similar to client initiated transfers. For the sequence of events triggered by each protocol., see Agent execution order on page 224.

The following topics describe the server-initiated transfer events:

l Server Transfer - Pull event on page 143 - Describes the Server Transfer - Pull event.

l Server Transfer - Push event on page 143 - Describes the Server Transfer - Push event.

Server Transfer - Pull event This event is used by the Transaction Manager to trigger a server-initiated download. The actions are expected to include a transfer agent that performs the requested transfer. A single event can be used to download one or many files. Multiple file downloads use wildcards. Site attributes provide information on where to connect to, how to connect, and what files to download. The downloaded files are deposited into a location accessible by an account and are subject to the same type of processing as if the files were uploaded by a remote client to the SecureTransport Server. The event target specifies the directory to store the downloaded file in.

The following topics provide detailed information about the Server Transfer - Pull event:

l Environment variables on page 143

l Exit codes on page 143

Environment variables DXAGENT_TARGET DXAGENT_FULLTARGET

Site – For more information, see Application framework object environment variables on page 159.

Exit codes

Exit Code Result

0 success

1 Wildcard expansion step successful. The resulting transfer are performed

all others unknown failure

Server Transfer - Push event This event is used by the Transaction Manager to trigger a server-initiated upload. The actions are expected to include a transfer agent that performs the requested transfer. Site attributes provide information on where to connect to, how to connect, and where to store the file on the remote

Axway SecureTransport 5.3.0 Developer's Guide 143 6 Working with event types

server. The uploaded file must reside in a location accessible by an account holder and is subject to the same type of processing as if the file was downloaded by a remote client from SecureTransport Server.

Note The event target can be a file or a directory. The built-in transfer agents transfer the files found in the root of the specified directory.

The following topics provide detailed information about the Server Transfer - Push event:

l Environment variables on page 144

l Exit codes on page 144

Environment variables DXAGENT_TARGET DXAGENT_FULLTARGET

Site – For more information, see Application framework object environment variables on page 159.

Exit codes

Exit Code Result

0 success

all others unknown failure

Schedule event A low-level event indicating that a scheduled task should be performed. The environment variables identify the type of task and its parameters. Currently the event is used to trigger server initiated pull and application schedules resulting in Server Transfer - Pull or Application - Schedule event. For more information, see Application - Schedule event on page 141 and Server Transfer - Pull event on page 143.

The following topics provide detailed information for schedule event:

l Environment variables on page 144

l Exit codes on page 145

Environment variables Schedule – See Application framework object environment variables on page 159 for more information.

Axway SecureTransport 5.3.0 Developer's Guide 144 6 Working with event types

Exit codes

Exit Code Result

0 success

all others unknown failure

Transformation event This event is sent to trigger a data transformation. Input for a data transformation is a file or a directory specified by the DXAGENT_TRANSFORMATION_INPUT variable. The DXAGENT_ TRANSFORMATION_INPUT_IS_DIRECTORY variable specifies whether the input is a file or a directory. When a directory is specified, all files and folders recursively contained represent the input as a single unit. The transformation agent can choose to process one file at a time or it can process all the files as a unit and generate a completely different set of files. For example, a transformation output can be a single file archive containing all the submitted files.

Data transformation can output one or multiple files. The transformation agent can also indicate that no transformation is required for a given input. If the transformation agent produces any output, it should place the resulting files or directory structure into the directory specified by the DXAGENT_TRANSFORMATION_OUTPUT variable. It should not modify the input in any way.

The type of the transformation and transformation options are defined by transformation attributes.

The following topics provide detailed information for the transformation event:

l Environment variables on page 145

l Exit codes on page 145

Environment variables Transformation – See Application framework object environment variables on page 159 for more information.

Exit codes

Exit Result Code

0 TRANSFORM - The transformation occurred and output directory contains the resulting files/directories

Axway SecureTransport 5.3.0 Developer's Guide 145 6 Working with event types

Exit Result Code

1 PASS - No modification is required. It is okay to pass the submitted data for further processing

2 BLOCK - There is a problem with input and processing should stop

Password Change event The following event is triggered by password change requests.

The following topics provide detailed information for the password change event:

l FTP Cmd - CHPWD event on page 146

l Arguments on page 146

l Exit codes on page 146

FTP Cmd - CHPWD event The CHPWD event occurs in response to a password change request.

Arguments The DXAGENT_EXTRAARGS environment variable contains the following arguments.

Argument Description

User name Name of the user.

Old password base64 encoded old password.

New password base64 encoded new password.

Exit codes Special Exit codes are defined for this event in the table below.

Axway SecureTransport 5.3.0 Developer's Guide 146 6 Working with event types

Exit Code Description

-64 General failure.

-2 Password policy failure.

-1 Password verification failure.

0 OK.

1 Command not implemented.

2 Command deferred.

PeSIT transfer state coordination events The PeSIT server uses the following events to coordinate the state of the transfer with the Transaction Manager. For more information about PeSIT transfers, refer to the SecureTransport Administrator's Guide.

The following topics describe the PeSIT transfer state coordination events:

l PeSIT Pause event on page 147 - Describes the PeSIT Pause event.

l PeSIT Resume event on page 148 - Describes the PeSIT Resume event.

l PeSIT SaveMap event on page 148 - Describes the PeSIT SaveMap event.

l PeSIT GetMap event on page 148 - Describes the PeSIT GetMap event.

l PeSIT ClearMap event on page 149 - Describes the PeSIT ClearMap event.

l PeSIT Ack event on page 149 - Describes the PeSIT Ack event.

PeSIT Pause event This event is sent when a transfer is paused or voluntarily interrupted by the sending partner. When this event is received, the transfer is marked as paused on the File Tracking page.

Environment variables

l DXAGENT_TRANSFERRED_BYTES – the number of bytes transferred before the transfer is interrupted

l DXAGENT_TARGET – the relative target of the file

l DXAGENT_FULLTARGET – the absolute path to the file

Axway SecureTransport 5.3.0 Developer's Guide 147 6 Working with event types

PeSIT Resume event This event is sent when a remote partner resumes a previously paused or interrupted transfer. Refer to the documentation for the Pesit pause event for details.

PeSIT SaveMap event This event is sent just after the Pesit pause for paused transfers or when a transfer fails. The event holds checkpoint data for the transfer. A checkpoint can be used to restart from one that point instead of from the beginning. The Transaction Manager (TM) saves the checkpoints in a file with the transferred file.

Environment variables

l DXAGENT_MAP_CONTENT – a Base64-encoded byte array as specified by the Axway PeSIT specification

l DXAGENT_PESIT_FILE_DESTINATION – The PI 62 value or final destination partner name

l DXAGENT_PESIT_FILE_FILENAME – PI 12 – ASCII alphanumeric name

l DXAGENT_PESIT_FILE_ORIGINATOR – PI 61 – Initiating partner

l DXAGENT_PESIT_FILE_RECEIVER – PI 4 – Receiver/Server identifier

l DXAGENT_PESIT_FILE_SENDER – PI 3 – Sender/Caller identifier

l DXAGENT_PESIT_FILE_FILETYPE – PI 11

l DXAGENT_PESIT_FILE_TRANSFERID – PI 13

PeSIT GetMap event This event is sent when a previously paused or failed transfer is resumed or retried. In response to this event, the TM reads the file it saved when it received the Pesit savemap event and streams it back to the caller using the event’s output stream. Do not modify the agent execution sequence that handles this event. If you must change this functionality, modify what the agent saves when a Pesit savemap event occurs. For more information, See PeSIT SaveMap event on page 148.

Environment variables See PeSIT SaveMap event on page 148.

Axway SecureTransport 5.3.0 Developer's Guide 148 6 Working with event types

PeSIT ClearMap event The event is sent just after a transfer completes successfully. The TM then deletes any checkpoint file created by the Pesit savemap execution for that file.

Environment variables See PeSIT SaveMap event on page 148.

PeSIT Ack event This event is sent when the PeSIT daemon detects an incoming acknowledgement.

Environment variables

l DXAGENT_PESIT_FILE_DESTINATION – The PI 62 value or final destination partner name

l DXAGENT_PESIT_FILE_FILENAME – PI 12 – ASCII alphanumeric name

l DXAGENT_PESIT_FILE_ORIGINATOR – PI 61 – Initiating partner

l DXAGENT_PESIT_FILE_RECEIVER – PI 4 – Receiver identifier

l DXAGENT_PESIT_FILE_SENDER – PI 3 – Sender identifier

l DXAGENT_PESIT_FILE_TRANSFERID – PI 13

l DXAGENT_PESIT_PI_msgData – PI 91 - the message's content

Mailbox folder event The following event is part of the application framework and are used to get information about mailbox folders.

The following topics provide detailed information for the mailbox folder event:

l PMfolderSummary event on page 150

l Environment variable on page 150

l Exit codes on page 150

l Output stream on page 150

Axway SecureTransport 5.3.0 Developer's Guide 149 6 Working with event types

PMfolderSummary event This event used to retrieve mailbox folder summary for single folder or all folders in account mailbox from the Package Manager. The folder summary contains the information for total packages and unread packages in each folder.

Environment variable ST_PACKAGE_FOLDER_NAME – Name of the folder to summarize

Exit codes

Exit Code Result

-64 General failure.

-2 No such file.

0 OK.

Output stream A list FolderSummary objects, each containing name of the folder, the number of packages in that folder, and the number of unread packages in that folder.

Address book events The following events are used to manage address book contacts:

l AddressBook - CreateContact event on page 151 - Describes the AddressBook - CreateContact event.

l AddressBook - DeleteContact event on page 151 - Describes the AddressBook - DeleteContact event.

l AddressBook - RetrieveContact event on page 152 - Describes the AddressBook - RetrieveContact event.

l AddressBook – UpdateContact event on page 153 - AddressBook – UpdateContact event.

Axway SecureTransport 5.3.0 Developer's Guide 150 6 Working with event types

AddressBook - CreateContact event This event occurs as the result of a client request to create a contact in the address book associated with their account.

The following topics provide detailed information about the AddressBook - CreateContact event:

l Environment variables on page 151

l Exit codes on page 151

l Output stream on page 151

Environment variables DXAGENT_CONTACT_FULL_NAME – Address book contact full name

DXAGENT_CONTACT_EMAIL – Address book contact email address

Exit codes

Exit Code Result

-64 General failure.

0 OK.

Output stream A JSON object that represents the AddressBookContact with the following properties:

l id

l fullName

l primaryEmail

AddressBook - DeleteContact event This event occurs as the result of a client request to delete an existing contact in the address book associated with their account.

The following topics provide detailed information about the AddressBook - DeleteContact event:

l Environment variables on page 152

l Exit codes on page 152

Axway SecureTransport 5.3.0 Developer's Guide 151 6 Working with event types

Environment variables DXAGENT_EXTRAARGS – Contact ID

Exit codes

Exit Code Result

-64 General failure.

0 OK.

AddressBook - RetrieveContact event This event occurs as the result of a client request to retrieve contacts from the address book associated with their account.

The following topics provide detailed information about the AddressBook - RetrieveContact event:

l Environment variables on page 152

l Exit codes on page 153

l Output stream on page 153

Environment variables DXAGENT_EXTRAARGS – A search string with the following format:

where:

l Search items can be null and are separated by single space characters

l – Full name of the contact or contacts to search for

l – Primary email address of the contact or contacts to search for

l – Maximum number of contacts to return

l – Position of the first contact in the list

Axway SecureTransport 5.3.0 Developer's Guide 152 6 Working with event types

Exit codes

Exit Code Result

-64 General failure.

0 OK.

Output stream A JSON object that represents the list the AddressBookContacts that met the search criteria with the following properties:

l id

l fullName

l primaryEmail

AddressBook – UpdateContact event This event occurs as the result of a client request to create a contact in the address book associated with their account.

The following topics provide detailed information about the AddressBook - UpdateContact event:

l Environment variables on page 153

l Exit codes on page 153

l Output stream on page 154

Environment variables DXAGENT_CONTACT_FULL_NAME – Address book contact full name

DXAGENT_CONTACT_EMAIL – Address book contact email address

Exit codes

Exit Code Result

-64 General failure.

0 OK.

Axway SecureTransport 5.3.0 Developer's Guide 153 6 Working with event types

Output stream A JSON object that represents the AddressBookContact with the following properties:

l id

l fullName

l primaryEmail

Axway SecureTransport 5.3.0 Developer's Guide 154 Using environment variables 7

SecureTransport offers many predefined environment variables that can be used when creating a condition for a rule. You can also add your own environment variables.

The following topics describe the environment variables and provide how to instructions for adding and displaying custom environment variables:

l Predefined environment variables on page 155 - Lists and describes the predefined environment variables.

l Adding custom environment variables on page 174 - Provides how to instructions for adding custom environment variables.

l Displaying custom environment variables on page 175 - Provides how to instructions for displaying custom environment variables.

Predefined environment variables The environment variables are divided into groups. The following topics describe the predefined environment variables that are passed to agents:

l Common environment variables on page 155 - Lists and describes the common environment variables.

l Session environment variables on page 156 - Lists and describes the session environment variables.

l Application framework object environment variables on page 159 - Lists and describes the application framework object environment variables.

l Additional environment variables on page 168 - Lists and describes the additional environment variables.

l LDAP session state variables on page 173 - Lists and describes the LDAP session state variables.

Common environment variables These environment variables are common across all event types.

System variables These variables are common to all events and are configured through the Transaction Manager configuration file brules.xml or set as a system property.

Axway SecureTransport 5.3.0 Developer's Guide 155 7 Using environment variables

Variable Name Description

DXAGENT_ Environment variable name to pass in the log file name. LOGFILENAME

FILEDRIVEHOME Represents the SecureTransport installation directory. For example, /opt/TMWD/SecureTransport or C:\Program Files\SecureTransport.

IMPERSONATION_ System-wide flag controlling impersonation. The values used for this flag ENABLED are specified in the file /brules/conf/brules.xml and can be set for a specific deployment. Typically, agents accessing the file system are configured to run impersonated. This flag can be used to turn impersonation off. If IMPERSONATION_ENABLED is set to 1, the agents run impersonated depending on the parameter settings for each agent. If IMPERSONATION_ENABLED is set to 0, no agents run impersonated regardless of the parameters of the particular agent.

Session environment variables The following environment variables are present in client- and server-initiated sessions. Unless indicated otherwise, each predefined variable is supported by all SecureTransport protocol servers (AS2D, FTPD, HTTPD, PESITD, and SSHD).

The following topics describe the session environment variables:

l Generic session variables on page 156

l Client session variables on page 157

l Client and account session variables on page 158

l Connection variables on page 159

Generic session variables These variables are present in all types of sessions whether client- or server-initiated.

Variable Description Name

DXAGENT_ The type of client connecting to the Transaction Manager to trigger this agent. CLIENT The value of this variable is set to as2d, ftpd, httpd, pesit, or sshd. For server sessions, the variable is set to server.

Axway SecureTransport 5.3.0 Developer's Guide 156 7 Using environment variables

Variable Description Name

DXAGENT_ The ID of the session. This variable is set to a unique value that is constant for all SESSIONID agent calls within the session. For more information, see Sessions on page 107.

Client session variables Variables applicable to client-initiated sessions.

Variable Name Description

DXAGENT_ Cookie output by auth agent. The variable that is set by the auth event. AUTHCOOKIE

DXAGENT_ Cookie output by cert agent. The variable that is set by the cert event. CERTCOOKIE

DXAGENT_ The channel ID for the current SSH event. This variable is only supported in CHANNELID SSH.

DXAGENT_ Contains the hostname or IP Address of the Edge in use. CLIENTADDR

DXAGENT_ The process ID (PID) of the SecureTransport process calling the agent. This CLIENTPID is inserted in the agentlog to help associate an Transaction Manager connection with a specific calling process. This variable is not available for AS2, SSH, or server sessions.

DXAGENT_ A persistent cookie that can be set in response to the cert, auth, or COOKIE login events. The last cookie that is set as the result of one of these three events. If no cookie is supplied, the value of this variable is null. For best results, use DXAGENT_SESSIONID as a session identifier instead of DXAGENT_COOKIE.

DXAGENT_ Contains the ID of the current SecureTransport Edge server. The variable is EDGEID only set by protocol servers HTTP(S), FTP(S), SSH and AS2. The identification string is set in the SecureTransport Edge EdgeId server configuration variable and is stored in ConfigurationOption database table. The DXAGENT_EDGEID variable is set during creation or setup of AgentSession for each FTP IO command object. It is reused by all other protocols for transfers. DXAGENT_EDGEID is set to each event object initialized from an AgentSession.

Axway SecureTransport 5.3.0 Developer's Guide 157 7 Using environment variables

Variable Name Description

DXAGENT_LDAP_ LDAP Domain Name (DN) if this is an LDAP session. DN

DXAGENT_ Login name of the user. LOGINNAME

DXAGENT_PWD The current working directory.

DXAGENT_PWD_ Current resolved working directory. RESOLVED

DXAGENT_ The user class of the user calling the agent. USERCLASS

DXAGENT_ The variable that is set by the user event. USERCOOKIE

DXAGENT_ The GID of the user. USERGID

DXAGENT_ The type of the user login for the user calling the agent. Possible values are USERLOGINTYPE Real, Virtual, LDAP, and SiteMinder.

DXAGENT_ The user type – real or virtual. USERTYPE

DXAGENT_ The UID of the user. USERUID

Client and account session variables Variables applicable to client- and server-initiated sessions created for an account.

Variable Description Name

DXAGENT_ The user or account home directory. HOMEDIR In the case of virtual users, this is the directory SecureTransport performs a virtual chroot into, and always appears as / to the virtual user.

Axway SecureTransport 5.3.0 Developer's Guide 158 7 Using environment variables

Variable Description Name

DXAGENT_ The filesystem root in effect for a user. ROOTDIR For real and virtual users, this is always /.

DXAGENT_ The GID of the user calling the agent. This variable is used by the Transaction USERGID Manager server.

DXAGENT_ The UID of the user calling the agent. This variable is used by the Transaction USERUID Manager server.

Connection variables These environment variables describe connection to or from a remote server. They are present in user sessions and for server-initiated transfers.

Variable Name Description

DXAGENT_PROTOCOL Protocol used to communicate with a remote machine either as a client or a server.

DXAGENT_REMOTEADDR The IP address of the host from which the client is connecting to SecureTransport. In a proxy environment, this can be the address of the proxy server host.

DXAGENT_REMOTEHOST The DNS name of the host from which the client is connecting to SecureTransport. In a proxy environment, this can be the name of the proxy server host.

DXAGENT_SECURE_ Contains a flag indicating whether the connection to a remote server COMMAND is secure.

DXAGENT_SECURE_ Contains a flag indicating whether the data channel is secured. DATA

Application framework object environment variables The following environment variables are used by application framework objects such as accounts, applications, and PGP transformations.

Axway SecureTransport 5.3.0 Developer's Guide 159 7 Using environment variables

The following topics describe the application framework object environment variables:

l Account variables on page 160

l Application variables on page 161

l Schedule variables on page 162

l Site variables on page 162

l FolderMonitor variables on page 164

l Subscription variables on page 165

l Transfer configuration variables on page 166

l Transformation variables on page 167

Account variables Account environment variables are present in the events occurring within a context of an account. This includes client-initiated sessions after login when the logged-in user is associated with an account. It also includes events that occur within server-initiated sessions on behalf of an account such as a server initiated pull or push.

Variable Name Description

DXAGENT_ACCOUNT_ Specifies that the account is enabled or disabled. Note that disabled DISABLED accounts are not allowed to perform any operations.

DXAGENT_ACCOUNT_ The email address of the account holder, if defined. EMAIL

DXAGENT_ACCOUNT_ The HTML template for the account holder. HTMLTEMPLATE

DXAGENT_ACCOUNT_ Opaque unique identifier of the account. ID

DXAGENT_ACCOUNT_ The account name. NAME

DXAGENT_ACCOUNT_ Contains any notes added to the account, if defined. NOTES

DXAGENT_ACCOUNT_ The account phone number, if defined. PHONE

DXAGENT_ACCOUNT_ The account type. TYPE

Axway SecureTransport 5.3.0 Developer's Guide 160 7 Using environment variables

Application variables Application environment variables provide information about the application relevant to the event. Some attributes are applicable to all applications. An application can also define a number of custom attributes. Names of custom application attributes must have the DXAGENT_ APPLICATION_ATTR_ prefix. They are not documented because their meaning changes based on the application.

Application environment variables are present in the Application events. They are also present in the events sent within the application context. For example, if an application requests that a file is sent to one of its subscribers, the resulting transfer event contains application environment variables.

Variable Name Description

DXAGENT_ The drop folder specifies the location within a subscription folder for files APPLICATION_ transferred from a site. If not set, the files are placed into the subscription DROP_FOLDER folder directly.

DXAGENT_ Application Folder – folder assigned to the application instance for its private APPLICATION_ storage needs. The application folder is typically inaccessible by the FOLDER subscribers. If absent, the application does not require storage outside of subscription folder or uses a shared folder.

DXAGENT_ Opaque unique identifier of the application instance. APPLICATION_ ID

DXAGENT_ The application name. APPLICATION_ NAME

DXAGENT_ Contains any notes associated with the application instance, if defined. APPLICATION_ NOTES

DXAGENT_ Application Shared Folder – folder used by application instance for storage APPLICATION_ shared by all subscribers. All subscription folders associated with the SHARED_ application instance are mapped to the this value. If absent, the application FOLDER does not use shared storage or it uses private storage through the Application Folder.

DXAGENT_ String that identifies application type. APPLICATION_ TYPE

Axway SecureTransport 5.3.0 Developer's Guide 161 7 Using environment variables

Schedule variables Schedule environment variables describe scheduled items. A scheduled item defines a particular task. Different kinds of tasks can be scheduled. Schedule environment variables are present in the Schedule event. The DXAGENT_SCHEDULED_TAG environment variable is also present in the Application–Schedule event. It is used to specify specific application-defined schedule tasks.

Variable Description Name

DXAGENT_ Opaque unique ID of the scheduled item. The ID is used to distinguish SCHEDULED_ scheduled items of the same type. For example, for an application schedule, the ID variable contains the ID of the application instance. Both application and subscription schedules define IDs.

DXAGENT_ Tag identifying the purpose of the schedule within the type. The exact meaning SCHEDULED_ depends on the scheduled type. For example, for application schedules, one TAG application can have multiple schedules. Tags are used to distinguish between these schedules. Both application and subscription schedules define tags.

DXAGENT_ The type of the scheduled item. Currently two values are defined: SCHEDULED_ application and subscription. When set to application, use a TYPE schedule associated with an application. when set to subscription, uses a schedule for transferring files associated with a subscription.

Site variables Site environment variables provide information about the site used for the data transfers. Sites represent connections through different protocols, including FTP, AS2, and local file system (FOLDER). Some environment variables are applicable to all protocols, some are applicable to a subset of protocols and some of the site environment variables are applicable only to a single protocol.

Site environment variables are present in the Server Transfer - Pull, and Server Transfer - Push events. They are also present in events such as Incoming Start and Incoming End, Outgoing Start and Outgoing End, and Store and Retrieve that are sent within the context of a server transfer. When these events are sent within the context of a client transfer, site information is not present.

Protocol-specific environment variables change based on the protocol and are not described here. Only agents implementing the protocols should access those environment variables.

Axway SecureTransport 5.3.0 Developer's Guide 162 7 Using environment variables

Variable Description Name

DXAGENT_ Site anchor. This is an internal site variable that defines a value unique to the SITE_ given protocol. ANCHOR

DXAGENT_ Directory location on the remote server to examine for presence of files to SITE_ATTR_ download. The files selected for download are determined by the value of DOWNLOAD_ DXAGENT_SITE_ATTR_DOWNLOAD_PATTERN. FOLDER

DXAGENT_ Download pattern used to determine which files should be downloaded from SITE_ATTR_ the remote server. Applied to the file names found in the Download Folder. DOWNLOAD_ PATTERN

DXAGENT_ The remote host represented by the site. If absent, the Site does not define a SITE_ATTR_ connection to a remote host. HOST

DXAGENT_ A flag indicating whether the connection is secure. Absence of this attribute for SITE_ATTR_ a Site means that it does not support the secure vs. non-secure configuration ISSECURE option.

DXAGENT_ Optional Site attribute. If the attribute is unavailable, the transfer site does not SITE_ support this configuration option. Opaque reference to a local certificate LOCALCERT_ presented to a remote server for authentication. CLIENT

DXAGENT_ Password presented to a remote server for authentication. SITE_ATTR_ PASSWORD

DXAGENT_ Port to connect to on a remote host represented by the Site. If absent, the Site SITE_ATTR_ does not define a connection to a remote host. PORT

DXAGENT_ The prefix used to build environment variables for site protocol specific SITE_ attributes. PREFIX

Axway SecureTransport 5.3.0 Developer's Guide 163 7 Using environment variables

Variable Description Name

DXAGENT_ Transfer mode to use when transferring files to or from the given Site. This SITE_ATTR_ attribute overrides the default logic used to determine the transfer mode based TRANSFER_ on file extension. There are 2 valid values:I - binary transfer or A - text transfer MODE

DXAGENT_ Upload folder specifies the directory location on the remote server to place SITE_ATTR_ uploaded files into. UPLOAD_ FOLDER

DXAGENT_ User name presented to a remote server for authentication. SITE_ATTR_ USERNAME

DXAGENT_ Verifies the remote host certificate when using a TLS/SSL connection. SITE_ATTR_ VERIFYCERT

DXAGENT_ Opaque unique identifier of the site. SITE_ID

DXAGENT_ The Site name. SITE_NAME

DXAGENT_ Contains the site protocol. Protocol choices are: as2, as2mdn, , folder, SITE_ ftp, http, pesit, ssh, or synchrony transfer. PROTOCOL

DXAGENT_ Represents the remote filepath. Overrides the Site configuration when selecting SITE_ files to transfer. Currently used to download a particular file from the Site. TARGET Overrides the Site download folder and download pattern. Uses a POSIX-style path.

DXAGENT_ The prefix used to build environment variables for the transfer site local SITE_ certificates attributes. LOCALCERT_ PREFIX

FolderMonitor variables The following variables describe extended FolderMonitor functionality.

Axway SecureTransport 5.3.0 Developer's Guide 164 7 Using environment variables

Variable Name Description

DXAGENT_SITE_ATTR_ Download file pattern type. Value can be glob for GLOB type DOWNLOAD_PATTERN_ pattern or regexp for regular expression. TYPE

DXAGENT_SITE_ATTR_ Download sub-folder pattern used to determine which folders DOWNLOAD_SUBFOLDER_ should be downloaded or traversed from the remote server. PATTERN Applied to the subfolder names in the Download Folder.

DXAGENT_SITE_ATTR_ Download subfolder pattern type. Value can be glob for GLOB DOWNLOAD_SUBFOLDER_ type pattern or regexp for regular expression. PATTERN_TYPE

DXAGENT_SITE_ATTR_ Subfolder traverse maximum depth. 0 traverses the whole DOWNLOAD_SUBFOLDER_ download subfolder . 1 traverses only the download folder, MAX_DEPTH 2 traverses the download folder and subfolders.

DXAGENT_SITE_ATTR_ Boolean property indicating whether download folder pattern DOWNLOAD_PATTERN_ must respect case-sensitivity of file names. CASE_SENSITIVE

DXAGENT_SITE_ATTR_ Boolean property indicating whether download subfolder DOWNLOAD_SUBFOLDER_ pattern must respect case-sensitivity of subfolder names. PATTERN_CASE_ SENSITIVE

Subscription variables Subscription environment variables provide information about the subscription relevant to the event. Some attributes are applicable to all subscriptions. An application can also define a number of custom subscription attributes. Names of custom subscription attributes must have the DXAGENT_SUBSCRIPTION_ATTR_ prefix.

Subscription environment variables are present in the Application - Init and Application - Incoming events. They are also present in the events sent within the application context. For example, if an application requests that a file is sent to one of its subscribers, the resulting transfer event contains subscription environment variables.

Axway SecureTransport 5.3.0 Developer's Guide 165 7 Using environment variables

Variable Name Description

DXAGENT_ The subscription folder in the form of POSIX-style path relative to the user SUBSCRIPTION_ home directory. This value represents the client path. To determine the FOLDER corresponding absolute native path, call ApplicationManager#getAbsoluteSubscriptionFolder (Subscription) .

DXAGENT_ Opaque unique identifier for the subscription. SUBSCRIPTION_ ID

DXAGENT_ Subscription anchor is an attribute that has a unique value for each SUBSCRIPTION_ subscription to a specific application instance. It provides the application ANCHOR with the ability to and find a particular subscription. For example, if an application is associated with banking, it can use a subscription anchor to store the bank account number.

Transfer configuration variables Transfer configuration environment variables provide information about the Transfer Configuration relevant to the event.

Transfer configuration environment variables are present in the events associated with transferring files that represent input or output of applications. They are always present in the Application - Incoming event. They are also present in the events sent within the application context to transfer files. For example, if an application requests that a file is sent to one of its subscribers, the resulting transfer event contains transfer configuration attributes.

Variable Description Name

DXAGENT_ The direction of the transfer configuration. Transfers defined in a user account TRANSFER_ subscription are identified by PARTNER-IN and PARTNER-OUT values for the DIRECTION subscription input and output respectively. Tag values for transfer configuration to or from a service account are chosen by the application.

DXAGENT_ The ID for the transfer. Used to update the transfer log. TRANSFER_ STATUS_ID

Axway SecureTransport 5.3.0 Developer's Guide 166 7 Using environment variables

Variable Description Name

DXAGENT_ The start time for the transfer. Used to update the transfer log. TRANSFER_ STATUS_ START_ TIME

DXAGENT_ Tag identifying the transfer configuration. TRANSFER_ TAG

Transformation variables Transformation environment variables provide information about the configured transformation to the agent implementing the transformation. Some environment variables are applicable to all transformations. Transformation environment variables are present in the Transformation event.

Variable Name Description

DXAGENT_ String that identifies transformation input directory. Format for TRANSFORMATION_INPUT the directory is absolute native path.

DXAGENT_ String that identifies transformation output directory. Format for TRANSFORMATION_ the directory is absolute native path. OUTPUT

DXAGENT_ String that identifies transformation type. TRANSFORMATION_TYPE

DXAGENT_ Set to 1 if the value of DXAGENT_TRANSFORMATION_INPUT TRANSFORMATION_ is a directory. If not, this variable is not set. This variable can be INPUT_IS_DIRECTORY used in rule conditions or in the transformation agent to easily distinguish between file and directory input without having to check the file system.

DXAGENT_ Set to 1 if the signed/encrypted data must be encoded in ASCII TRANSFORMATION_ATTR_ armor. When set to 0, the file will not use ASCII armoring. ASCIIARMOR For more information, see Pluggable UI overview on page 54.

Axway SecureTransport 5.3.0 Developer's Guide 167 7 Using environment variables

Variable Name Description

DXAGENT_ Identifies the compression level to use when encrypting/signing TRANSFORMATION_ATTR_ files. The value can range between 1 to 9. Use the following COMPRESSIONLEVEL values to match the settings shown in the Subscription settings in the Administration Tool:

l Fast = 2

l Normal = 5

l Good = 7

l Best = 9 For more information, see the information about creating accounts and advanced account administration in the SecureTransport Administrator's Guide.

DXAGENT_ Identifies the compression algorithm to use when TRANSFORMATION_ATTR_ encrypting/signing files. Use the following values for each COMPRESSIONALGORITHM compression type:

l ZIP = 1

l ZLIB = 2

l BZIP2 = 3

l UNCOMPRESSED = 0 For more information, see the information about creating accounts and in the SecureTransport Administrator's Guide.

Additional environment variables The following environment variables are used under the conditions described for each group.

The following topics describe the additional environment variables:

l Persistence variables on page 169

l AS2 variables on page 170

l AS2-specific DXAGENT_HTTP_XXX variables on page 170

l Event-specific variables on page 171

l File source and target variables on page 172

l HTTP variables on page 173

Axway SecureTransport 5.3.0 Developer's Guide 168 7 Using environment variables

Persistence variables A persistent event, once submitted to the Transaction Manager, is saved in persistent storage and can be processed repeatedly until the processing either succeeds or reaches some configurable limit of attempts. A component submitting a persistent event receives the reply immediately after the event is stored, not when the processing of the event completes. If there are multiple attempts and delays, the processing of the event can take a long time. Persistent events are asynchronous. A persistent event is not an event type, but an indication of how an event can be processed. Certain types of events can be processed in this manner. Currently the Incoming End, Schedule, Server Transfer - Pull, and Server Transfer- Push event types are processed persistently. Only the Server Transfer - Pull and Server Transfer- Push events are retried.

When an event is persisted, a new session is generated. The session state strings associated with the current session are copied into the new session. The new session is maintained across multiple attempts to process the event. For example, the session state can be used to keep track of the processing stage reached by the current attempt so that the next attempt can start where the previous one stops.

Variable Description Name

DXAGENT_ Marks an event that is already persisted. Events coming from the event queue are PERSISTED_ set to 1. Presence of this attribute with value 1 indicates that the event is a EVENT persistent event.

DXAGENT_ Used by the event queue to associate persisted events. Opaque identifier for a PERSISTED_ group of persistent events. A set of persistent events that originate from EVENT_ processing of another persistent event form a group. A unique group identifier is GROUP generated when first persistent event is generated; the event that does not have any group ID. Additional events sent while processing the originating event carry the same group ID. For example, a Schedule Event for server initiated pull can result in generating a number of Transfer Events to download files from the remote site. A new group identifier is generated for the Schedule Event and Transfer Events are persisted with the same identifier.

DXAGENT_ The last retry attempt for the event when set to 1. PERSISTED_ EVENT_ LAST_ CHANCE

DXAGENT_ Set by the Event Queue Processor whenever the event is sent again as part of a PERSISTED_ recovery attempt. If the value of this attribute is 1, it's an indication that the EVENT_ previous attempt of the event processing is deemed stalled or failed in an abrupt manner and event is being resubmitted for processing.

Axway SecureTransport 5.3.0 Developer's Guide 169 7 Using environment variables

Variable Description Name

DXAGENT_ An attribute set by the RetryAgent to indicate the further processing of a PERSISTED_ persistent event. EVENT_ RETRY_TYPE

DXAGENT_ Set by the Event Queue Processor to indicate the number of retries done for the PERSISTED_ current event. The value represents the number of previous failed attempts to EVENT_ process the event. RETRY_ COUNT

AS2 variables These variables provide information about the AS2 payload.

Variable Name Description

DXAGENT_ The content type (as defined in MIME). CONTENTTYPE

DXAGENT_ The original name of the file on the client. AS2 only. The logical name of RAWSOURCE the source entity.

AS2-specific DXAGENT_HTTP_XXX variables AS2 supports all the standard DXAGENT_HTTP_XXX variables and the following AS2-specific HTTP variables:

Variable Name Description

DXAGENT_ The name of the partner to which the data is sent. This is the AS2 name of the HTTP_AS2_TO remote partner, which is defined in the AS2 partnership.

DXAGENT_ The name of the partner that is sending the data. This is the AS2 name of the HTTP_AS2_ local partner, which is defined in the AS2 partnership. FROM

Axway SecureTransport 5.3.0 Developer's Guide 170 7 Using environment variables

Event-specific variables Individual events use these variables to carry information specific to the particular event type.

Variable Name Description

DXAGENT_ Mode to set file to after upload. Set if there is an upload rule in effect that CHMODTO wants to change the file mode after an upload. This variable is used by the Incoming End Agent.

DXAGENT_ GID to set file to after upload. Set if there is an upload rule in effect that CHOWNGID wants to change the file group after an upload. This variable is used by the Incoming End Agent.

DXAGENT_ UID to set file to after upload. Set if there is an upload rule in effect that CHOWNUID wants to change the file owner after an upload. This variable is used by the Incoming End Agent.

DXAGENT_ This variables receives a space delimited list of arguments for the command EXTRAARGS associated with a command event. See the individual command event descriptions for more details.

DXAGENT_ HTTP command arguments. HTTPCMDARGS

DXAGENT_ Variable indicating the type of input provided. Currently used to indicate the INPUTFORMAT type of data submitted to the Certificate event:

l X509-PEM for PEM certificate format

l KEY-X.509-BASE64 – for public key format If the variable is not set, the X509-PEM value is assumed.

DXAGENT_ The fully resolved client path of the filesystem object being listed. LISTTARGET DXAGENT_LISTTARGET can contain wildcards.

DXAGENT_ Password of the user. LOGINPASS

DXAGENT_ Set to 1 if there is a 'no overwrite' rule in effect. This variable is used by the NOOVERWRITE STOR agent.

DXAGENT_ Open mask for current operation. OPENMASK

Axway SecureTransport 5.3.0 Developer's Guide 171 7 Using environment variables

Variable Name Description

DXAGENT_ Used by the transfer log to set protocol specific flags for a file transfer. This TRANSFERLOG_ allows protocol servers to set different flags depending on the options of the FLAGS transfer. The variable is only meaningful for the Incoming Start and Outgoing Start events.

DXAGENT_ Contains the number of bytes transferred during a completed or aborted TRANSFERRED_ transfer. Present in Incoming End, Incoming Error, Incoming Abort, BYTES Outgoing End, Outgoing Error, and Outgoing Abort events.

DXAGENT_ Set to the of the SecureTransport process calling the agent. This is UMASK used by the STOR/MKD agents to set the umask before creating a file or directory.

DXAGENT_ Represents the transfer type of the file that triggered the event. Set to I (for XFERTYPE binary) or A (for ASCII).

DXAGENT_ The event trigger type, such as start, end, error. TRIGGER

DXAGENT_TYPE The event type.

File source and target variables These variables describe the event source or target when the source or target is a file system object.

Variable Name Description

DXAGENT_ Complete absolute path name of the source. FULLSOURCE

DXAGENT_ Complete absolute path name of the target. FULLTARGET

DXAGENT_ The target supplied by the user. No path expansion or globing is done. It is RAWTARGET the 'raw' target supplied by the Axway SecureTransport client.

DXAGENT_ This variable is set to the file name for incoming or outgoing events, or the TARGET user name for auth, config, login, and logout events.

Axway SecureTransport 5.3.0 Developer's Guide 172 7 Using environment variables

Variable Name Description

DXAGENT_ Used by the Application event for incoming data and by the ServerTransfer TARGET_IS_ event for push. Set to 1 if DXAGENT_TARGET is a directory and 0 if it is DIRECTORY not.

DXAGENT_ This is the directory name part of the fully qualified target path, relative to TARGETDIR the root of the filesystem in effect for this user.

DXAGENT_ This is the directory name portion of the fully qualified target path, relative TARGETPATH to the real root of the filesystem. For real users, DXAGENT_TARGETDIR and DXAGENT_TARGETPATH are the same. For virtual users, DXAGENT_TARGETPATH is the concatenation of the DXAGENT_HOMEDIR and DXAGENT_TARGETDIR variables.

HTTP variables These variables are applicable to user sessions established over the HTTP protocol and are designed to carry HTTP request headers.

Variable Name Description

DXAGENT_HTTP_ The prefix to prepend to HTTP header names before the headers are passed PREFIX as agent environment variables.

DXAGENT_HTTP_ SecureTransport makes all HTTP header variables available to agents. XXX Variables starting with DXAGENT_HTTP_ represent header variables for HTTP transactions.

DXAGENT_ HTTP command arguments. HTTPCMDARGS

DXAGENT_ HTTP User-Agent. Contains the name of the HTTP client. HTTPUSERAGENT

LDAP session state variables When a user is authenticated with LDAP, the following session state variables are available:

Axway SecureTransport 5.3.0 Developer's Guide 173 7 Using environment variables

Variable Description Name

LDAP_AUTH_ Boolean flag indicating whether current user has been authenticated by BY_EMAIL email in an LDAP authentication.

LDAP_DIR_XXX SecureTransport makes all the user’s LDAP directory entry attributes available to agents. Variables starting with this LDAP_DIR_ represent these attributes.

LDAP_DN SecureTransport sets this value to the DN of the authenticated user.

LDAP_DOMAIN_ Internal unique identifier of a LDAP configuration unit in ST. ID

LDAP_DOMAIN_ Logical name of a LDAP configuration unit in ST NAME

LDAP_fdxGid This is set to the GID of the user.

LDAP_ This is set to the home directory of the user. fdxHomeDir

LDAP_ This is set to the shell for the user. UNIX and only. fdxShell

LDAP_ Windows system account under which a logged-in LDAP user is represented fdxSysUser in ST in Windows environment and on behalf of whom File IO operations are executed.

LDAP_fdxUid This is set to the UID of the user. UNIX and Linux only.

LDAP_ This is set to the user type for the user. This can be either real or virtual. fdxUserType

Unlike other variables discussed in this chapter, these are session variables and not environment variables. For more information, see BaseAgent class on page 43 and Developing and triggering external agents on page 27.

Adding custom environment variables You can add custom environment variables by editing the brules.xml configuration file. This topic explains how to add custom environment variables for agents running under Transaction Manager.

Axway SecureTransport 5.3.0 Developer's Guide 174 7 Using environment variables

External and in-process agents run under the SecureTransport Transaction Manager. Custom environment variables for agents running under Transaction Manager must be added to the brules.xml file. After changing the brules.xml file, you must restart the Transaction Manager.

To add custom environment variables for external and in-process agents:

1. In the /brules/conf/brules.xml file, add the following line under the section:

2. Save the file.

Note When using the attribute, you do not have to set the variable value if you want to pass the value from the Transaction Manager system environment.

Displaying custom environment variables By default, user-defined environment variables are not displayed in the Condition Editor window. To specify conditions based on user-defined environment variables, these variables have to be displayed in the Condition Editor window. User-defined environment variables can be added to the st.attr attribute list using the format:

attribute name:friendly display name:allowEmpty:operators allowed:values allowed

Name Description

attribute Name of the user-defined environment variable. The built-in environment variables name are already listed in st.attr.

friendly (Optional) Name displayed in Condition Editor. display name

allowEmpty When set to 1, allows the Value field to accept empty strings. When no value is set, empty strings are not accepted.

operators Determines which operators can be used as part of the condition. Possible operators allowed include: equals, not equals, equals without cases, match, contains, less than, less than or equal to, greater than, and greater than or equal to. The integer you enter is converted to a nine digit binary control. The st.attr file provides examples of how to use this setting.

values (Optional) When used, controls the choices available in the Value field. allowed

Axway SecureTransport 5.3.0 Developer's Guide 175 7 Using environment variables

To display a user-defined environment variable:

1. Add the user-defined environment variable in the st.attr attribute list located under /brules/local/attributelists.

A typical entry looks like the following:

LC_ALL:::31

where LC_ALL is the environment variable name, there is no friend display name, allowEmpty is disabled, the operators allowed is set to 31 which allows the equals, not equals, equals without cases, match, and contains operators. No specific values have been specified so the condition supports any entered value other than empty.

2. Add the passenv entry under the section in the brules.xml file using the following format:

Both the value and the type attributes are optional. For example:

3. Save the file.

If the value attribute is not specified, the value of the Java system property or the system environment variable is passed to the agents.

The value assigned to var is found in this order:

1. The value of the value attribute of the passenv element.

2. The value of the system property available to Transaction Manager. 3. The value of the system environment variable.

If the type attribute is set to "path", Transaction Manager expects an absolute file or directory name in native format for the value.

Axway SecureTransport 5.3.0 Developer's Guide 176 File services interface 8

The following topics describe file services interface transfer protocols and how to implement them:

l File services interface introduction on page 177 - Provides an introduction to the file services interface.

l Registering a file services interface protocol on page 177 - Provides how to instructions for registering a file services interface protocol.

l Enabling PeSIT message parameters on page 180 - Provides how to instructions for enabling PeSIT message parameters.

l Standard file services interface connectors on page 180 - Describes the standard file services interface connectors.

l Implementing a file services interface connector on page 184 - Provides how to instructions for implementing a file services interface connector.

File services interface introduction The file services interface is a generic facility that you can use to implement file transfers between Axway SecureTransport and another system. A file services interface protocol uses metadata that describes the transfer from another system to SecureTransport and uses a directory that both systems can access to deliver the payload file. A file transfer from SecureTransport to another system can also use a a directory that both systems can access to deliver the payload file.

Once you implement a file services interface protocol, a SecureTransport administrator can use it like any other SecureTransport protocol.

Overall, to implement a file services interface protocol, you need to:

l Either select a standard file services interface connector or implement a custom one

l Register the file services interface protocol

Registering a file services interface protocol To register a file services interface protocol in SecureTransport, add a protocol element that describes the protocol inside the registry element in the /conf/FileServicesInterfaceRegistry.xml file.

The protocol element has these attributes:

Axway SecureTransport 5.3.0 Developer's Guide 177 8 File services interface

l name – a unique name for the protocol

l displayName – a unique name for the protocol to display in the Administration Tool and in Axway Sentinel reporting (if not speficied, the name attribute is used)

The protocol element contains these elements:

l properties – a list of property element that describe the protocol

l connector – a reference to the connector implementation for the protocol

The property element has these attributes:

Name Description Valid Note values

name Name of the property Any string Required

displayName Name displayed as a site Any string Optional setting or optional If not supplied, the value of the parameter when adding name attribute is used. or editing a transfer site or a site templates pages

description Description of the Any string Optional property

type Data type of the boolean Used by the Transaction Manager to property float validate the value of the property integer after it is evaluated string (default)

hidden Visibility of the property true Set this to true for properties that on a transfer site or site false are used only internally (for templates page (default) example, CycleId)

optional Whether a value is true Required required for this false property on a transfer site or site templates page

Axway SecureTransport 5.3.0 Developer's Guide 178 8 File services interface

Name Description Valid Note values

defaultValue Value to be used when String Optional none is specified on a value valid Can be an expression. transfer site or site for the If a protocol property is optional, templates page property does not have default value, and no data type value is specified on the Transfer Site or Site Templates page, the property is not passed to the connector.

The connector element has the following attribute:

l className – The full class path of an implementation of the FileServicesInterfaceConnector interface

Example

Axway SecureTransport 5.3.0 Developer's Guide 179 8 File services interface

Enabling PeSIT message parameters If you enable the PeSIT message parameters in the environment, you can select the parameters by their parameter identifier (PI) as optional parameters when you define the file services interface protocol transfer site to implement the integration.

1. Log in to the SecureTransport Server as the user who installed and runs SecureTransport. 2. Make a backup copy of /brules/local/wptdocuments/FileServicesInterfac e.xml.

3. Edit /brules/local/wptdocuments/FileServicesInterfac e.xml

a. Replace

with

Impersonation "true"

b. Save the change. 4. Restart the TM.

Standard file services interface connectors SecureTransport includes two standard implementations of the FileServicesInterfaceConnector interface. The standard implementations are:

l FileServicesInterfaceScriptBasedConnector on page 181 - Describes the FileServicesInterfaceScriptBasedConnector standard implementation.

Axway SecureTransport 5.3.0 Developer's Guide 180 8 File services interface

l FileServicesInterfaceFileBasedConnector on page 182 - Describes the FileServicesInterfaceFileBasedConnector standard implementation.

FileServicesInterfaceScriptBasedConnector Use FileServicesInterfaceScriptBasedConnector to execute a script or program to send a file to the external system. SecureTransport passes all the information about the transfer in command-line arguments. The following protocol property is required:

l OutputScriptFile – the full path of the program or script to execute

The command-line arguments include:

l SourceFileLocation=

l = for each protocol property

Example Registration for a protocol that uses FileServicesInterfaceScriptBasedConnector:

Axway SecureTransport 5.3.0 Developer's Guide 181 8 File services interface

optional="false"/>

Script for a protocol that uses FileServicesInterfaceScriptBasedConnector to copy the source file to a fixed location:

#!/bin/sh

PATH=/usr/bin:/bin:/usr/sbin:/sbin

args=("$@") @args >> test1.txt

for i do OPT=`echo ${i} | -d= -f1` case "${OPT}" in -SourceFileLocation) Config_File=`echo ${i} | cut -d= -f2` ;; esac done

cp $Config_File /DEV/resultfile

FileServicesInterfaceFileBasedConnector Use FileServicesInterfaceFileBasedConnector to create a file that contains all the information about the transfer where it can be processed to complete the transfer. FileServicesInterfaceFileBasedConnector can write an XML file or a text file with = lines. The following protocol properties are required:

Axway SecureTransport 5.3.0 Developer's Guide 182 8 File services interface

l OutputFileName – the full path of the file to create (overwritten if it exists)

l OutputFileFormat – the format of the file (XML, or PLAIN for a text file with = lines)

Example For registration for a protocol that uses FileServicesInterfaceFileBasedConnector, see Example on page 181.

XML output from a protocol that uses FileServicesInterfaceFileBasedConnector:

Text file with = output from a protocol that uses FileServicesInterfaceFileBasedConnector:

Host=2 DownloadFolder=/test/a Port=21 DownloadPattern=1 SourceFileLocation=/DEV/FSITransfers/rhel2130/CustomAttributesCache.data OutputFileFormat=PLAIN OutputFileName=/DEV/out.txt LocalSharePath=/DEV/FSITransfers

Note If OutputFileFormat is PLAIN, null values are not included in the output file.

Axway SecureTransport 5.3.0 Developer's Guide 183 8 File services interface

Implementing a file services interface connector You can create a custom file services interface connector in Java by implementing the FileServicesInterfaceConnector interface. If the external system has a Java client API, you can implement file transfer using a custom file services interface connector.

For a custom connector, the protocol properties are passed to the implementation in a map that contains the values indexed by their names.

For more information about the FileServicesInterfaceConnector interface, refer to the SDK online help.

Axway SecureTransport 5.3.0 Developer's Guide 184 REST API 9

The following topics include an overview of the SecureTransport representational state transfer (REST) web service API and some examples of its use:

l REST API overview on page 185 - Provides an overview of the REST API.

l REST API examples on page 186 - Provides some REST API examples.

REST API overview The new version of REST API in SecureTransport 5.3.0 is v1.2. New versions include new resources and all existing resources (backward compatible), which are still available in the previous versions.

With administrator credentials, you can use the SecureTransport REST API to query, create, modify, and delete user accounts and related SecureTransport configuration including applications, business units, certificates, sites, subscriptions, and transfer profiles.

You can also use the REST API to perform the following actions:

l Query and kill FTP and HTTP sessions

l Query and export logs

l Query, create, modify, and delete network zones to configure the SecureTransport Edge protocol

For more information about network zones, refer to the SecureTransport Administrator's Guide.

With user credentials, you can use the SecureTransport REST API to perform the following actions:

l Perform and manage server-initiated transfers using your transfer sites.

l Upload files to your home folder

l List your home folder

l Change your password

l Trigger an email from SecureTransport Server with instructions for resetting you password

The base URI for the REST is https://:/api// where

l is the hostname or the IP address of the SecureTransport server

l is the one of the following:

o Administrator resources – Administration Tool port (default 444)

o User resources – HTTP or HTTPS port (default 80 or 443)

l is the SecureTransport REST API version (vx.y where x is the major version and y is the minor version, v1.2 for SecureTransport 5.3.0)

Axway SecureTransport 5.3.0 Developer's Guide 185 9 REST API

Some useful URIs:

l https://:/api/ – lists all available versions

l https://:/api/v1.2/ – resource descriptions

l https://:/api/application.wadl – WADL application description

l https://:/api/v1.2/docs/index.html – API reference

The HTTP methods used by the API are GET, PUT, POST, and DELETE. These methods and the provided resources allow access to a single element or a collection of elements.

The Internet media data types supported by the REST API are application/json and application/xml. For Java use of the REST API, the SecureTransport Java API provides a library called ws-representation which includes Java classes that represent the data that can be accessed using the REST API. The ws-representation library depends on the jersey- core and jersey-server-linking libraries version 1.13 which are available from http://jersey.java.net/. In addition to them, Java programs require the jackson libraries version 1.9.2 and validation-api v1.0.0GA from J2EE 6. Representations are annotated according to JSR 303. Validation is done on the server side.

REST API examples The following topics contain examples that illustrate uses of the SecureTransport REST API:

l Create an account on page 186 - Provides create an account REST API examples.

l Push a file on page 209 - Provides a push a file REST API example.

l Custom HTML template on page 211 - Provides a custom HTML template REST API example.

l Java file transfer library on page 218 - Provides a Java file transfer library REST API example.

Create an account These examples illustrate use of the SecureTransport REST API to create an account using a Java application, a Python application, and a shell script that calls cURL. It uses the following resources:

l Accounts

l Sites

l Applications

l Subscriptions

l Certificates

In all cases, the inputs are:

l Account name

l Home folder

Axway SecureTransport 5.3.0 Developer's Guide 186 9 REST API

l User ID (UID)

l Group ID (GID)

l Email contact

l Phone contact

l Business unit

l File path for the SSH key file

Each example creates a SecureTransport account with the given attributes. Then it imports the SSH key, creates a predefined FTP transfer site, and a subscription to site mailbox application for pushing files to the created transfer site.

The following topics provide Java, Python, and Shell script example of creating an account using REST API:

l Java on page 187

l Python on page 196

l Shell script using cURL on page 202

Java This example is a Java application, AccountCreate.java, which gets its input from the command line.

The command line to run the compiled programs is:

java AccountCreate -name account_name -homefolder home_folder_path \ -uid UID -gid GID -email user_email -phone user_telephone_ number \ -bu business_unit_name -key SSH_key_file_path

/* * This example program illustrates the usage of * SecureTransport REST API to create an user account, * import SSH key, create a predefined FTP transfer site and * a subscription to site mailbox application for pushing files * to the created transfer site. * * This program requires the following input values: account name, * home folder, User ID (UID), Group ID (GUI), email contact, * phone contact, business unit and a filepath to a SSH key. * * The input values are given respectively with the following * options:

Axway SecureTransport 5.3.0 Developer's Guide 187 9 REST API

* * - name Specify the account name * - homefolder Specify the user home directory. * - uid Specify the user ID (UID) * - gid Specify the group ID (GID) * - email Specify the email contact * - phone Specify the phone contact * - bu Specify the account business unit * - key Specify the filepath to a valid ssh key * * * This program requires the jar files jackson-jaxrs.jar, * jersey-client.jar, jersey-core.jar, jersey-multipart.jar, * and ws-representation.jar to be added to the build path. */

package com.axway.securetransport.dev.examples

import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map;

import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import javax.ws.rs.core.MediaType;

import org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider; import org.codehaus.jackson.jaxrs.JacksonJsonProvider;

import com.axway.st.ws.representation.Account;

Axway SecureTransport 5.3.0 Developer's Guide 188 9 REST API

import com.axway.st.ws.representation.AccountContact; import com.axway.st.ws.representation.Accounts; import com.axway.st.ws.representation.Application; import com.axway.st.ws.representation.Applications; import com.axway.st.ws.representation.Certificate; import com.axway.st.ws.representation.Site; import com.axway.st.ws.representation.Sites; import com.axway.st.ws.representation.Subscription; import com.axway.st.ws.representation.Subscriptions; import com.axway.st.ws.representation.TransferConfiguration; import com.axway.st.ws.representation.TransferConfigurations; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; import com.sun.jersey.client.urlconnection.HTTPSProperties; import com.sun.jersey.multipart.MultiPart; import com.sun.jersey.multipart.MultiPartMediaTypes; import com.sun.jersey.multipart.impl.MultiPartWriter;

public class AccountCreate {

private static String url = "https://st.example.com:444/api/v1.0"; private static String adminName = "admin"; private static String adminPassword = "adminPassword"; private static final String NAME_OPT = "-name"; private static final String HOMEFOLDER_OPT = "-homefolder"; private static final String UID_OPT = "-uid"; private static final String GID_OPT = "-gid"; private static final String EMAIL_OPT = "-email"; private static final String PHONE_OPT = "-phone"; private static final String BU_OPT = "-bu"; private static final String KEY_OPT = "-key";

public static void main(String[] args) throws Exception {

Map options = validateArgs(args); Client client = getClient();

Axway SecureTransport 5.3.0 Developer's Guide 189 9 REST API

WebResource webResource = client.resource(url);

// Create account Account account = accountObjectInstance(options); webResource.path("/accounts/" + account.getName()) .type(MediaType.APPLICATION_XML_TYPE).put(account);

// Create Transfer Site for the created account Sites sites = sitesObjectInstance(account.getName()); webResource.path("/sites").type(MediaType.APPLICATION_XML_TYPE) .post(sites);

// Create application Applications apps = ApplicationsOb(); webResource.path("/applications") .type(MediaType.APPLICATION_XML_TYPE).post(apps);

// Subscribe the account to the created application Subscriptions subscriptionsToPost = subscribtionsObjectInstance( account.getName(), apps.getApplications().get(0)); webResource.path("/subscriptions") .type(MediaType.APPLICATION_XML_TYPE) .post(subscriptionsToPost);

// Get the subscription's ID

WebResource webResource2 = client.resource(url + "/subscriptions?account=" + account.getName() + "&application=" + subscriptionsToPost.getSubscriptions().get(0) .getApplication()); Subscriptions subscriptionsGet = webResource2.type( MediaType.APPLICATION_XML_TYPE) .get(Subscriptions.class); String subscriptionID = subscriptionsGet.getSubscriptions() .get(0).getId();

// Create Transfer configuration for the subscription webResource .path("/subscriptions/" + subscriptionID + "/transferConfigurations")

Axway SecureTransport 5.3.0 Developer's Guide 190 9 REST API

.type(MediaType.APPLICATION_XML_TYPE) .post(TransferConfigurationsOb(sites.getSites().get(0) .getName()));

MultiPart cert = sshKey(account.getName(), options); webResource.path("/certificates/import") .type(MultiPartMediaTypes.MULTIPART_MIXED_TYPE) .post(cert); }

private static Map validateArgs(String args[]) throws Exception { Map result = new HashMap(); List params = Arrays.asList(new String[] { NAME_OPT, HOMEFOLDER_OPT, UID_OPT, GID_OPT, EMAIL_OPT, PHONE_OPT, KEY_OPT, BU_OPT });

for (int i = 0; i < args.length; i += 2) { if (!params.contains(args[i])) { throw new Exception("Invalid option " + args[i]); } else if (i + 1 >= args.length || params.contains(args[i + 1])) { throw new Exception("Missing value for option " + args[i]); } else { result.put(args[i], args[i + 1]); } }

for (String param : params) { if (!result.containsKey(param)) { throw new Exception("Missing option " + param + "\n All the options: " + params.toString() + " are requiered"); } }

return result; }

private static MultiPart sshKey(String account, Map options)

Axway SecureTransport 5.3.0 Developer's Guide 191 9 REST API

throws IOException { MultiPart result = new MultiPart( MultiPartMediaTypes.MULTIPART_MIXED_TYPE); result.bodyPart(readFile(options.get(KEY_OPT)), MediaType.APPLICATION_OCTET_STREAM_TYPE); result.bodyPart(certDescr(account), MediaType .APPLICATION_JSON_TYPE); return result; }

private static String readFile(String path) throws IOException { StringBuffer result = new StringBuffer(); FileInputStream fin = new FileInputStream(path); InputStreamReader reader = new InputStreamReader(fin); char[] tmp = new char[1024];

while (reader.read(tmp) != -1) { result.append(tmp); }

return result.toString(); }

private static Account accountObjectInstance( Map options){ Account result = new Account(); result.setName(options.get(NAME_OPT)); result.setHomeFolder(options.get(HOMEFOLDER_OPT)); result.setUid(Integer.parseInt(options.get(UID_OPT))); result.setGid(Integer.parseInt(options.get(GID_OPT))); result.setContact(new AccountContact()); result.getContact().setEmail(options.get(EMAIL_OPT)); result.setType("user"); result.getContact().setPhone(PHONE_OPT); result.setBusinessUnit(options.get(BU_OPT)); return result; }

// Creates an object for the predefined FTP transfer site creation private static Sites sitesObjectInstance(String account) { Sites result = new Sites(); result.setSites(new ArrayList());

Axway SecureTransport 5.3.0 Developer's Guide 192 9 REST API

Site site = new Site(); site.setName("ftpSite1"); site.setProtocol("ftp"); site.setAccount(account); site.setDefault(false); Map customProperties = new HashMap(); site.setCustomPropertiesMap(customProperties); customProperties.put("port", "21"); customProperties.put("host", "10.232.3.238"); customProperties.put("download.pattern", "download_*"); customProperties.put("upload.folder", "/up"); customProperties.put("download.folder", "/down"); customProperties.put("username", "user"); customProperties.put("issecure", "1"); result.getSites().add(site); return result; }

private static Subscriptions subscribtionsObjectInstance( String account, Application app) { Subscriptions result = new Subscriptions(); result.setSubscriptions(new ArrayList()); Subscription subscr = new Subscription(); result.getSubscriptions().add(subscr); subscr.setAccount(account); subscr.setApplication(app.getName()); subscr.setFolder(app.getFolder()); return result; }

// Creates an object for the predefined site mailbox application // creation private static Applications ApplicationsOb() { Applications apps = new Applications(); apps.setApplications(new ArrayList()); apps.getApplications().add(new Application()); apps.getApplications().get(0).setName("SMB"); apps.getApplications().get(0).setFolder("/smb"); apps.getApplications().get(0).setType("SiteMailbox"); apps.getApplications().get(0) .setCustomPropertiesMap(new HashMap());

Axway SecureTransport 5.3.0 Developer's Guide 193 9 REST API

apps.getApplications().get(0).getCustomPropertiesMap() .put("INBOX_FOLDER", "inbox"); apps.getApplications().get(0).getCustomPropertiesMap() .put("OUTBOX_FOLDER", "outbox"); return apps; }

// Creates an object for the predefined Transfer Configuration for // outbound transfer to a given Transfer site private static TransferConfigurations TransferConfigurationsOb (String site) { TransferConfigurations result = new TransferConfigurations(); result.setTransferConfigurations( new ArrayList()); result.getTransferConfigurations() .add(new TransferConfiguration()); result.getTransferConfigurations().get(0).setSite(site); result.getTransferConfigurations().get(0).setDirection(1); result.getTransferConfigurations().get(0).setTag("PARTNER-OUT"); return result; }

private static Certificate certDescr(String account) { Certificate result = new Certificate(); result.setAccount(account); result.setName("cert1"); result.setType("ssh"); result.setUsage("login"); result.setCaPassword("password"); result.setSubject( "CN=qwew,OU=fsdfs,O=wedf,L=fsdf,S=frwer,C=efwe"); result.setValidityPeriod(365); return result; }

private static Client getClient() throws KeyManagementException, NoSuchAlgorithmException { SSLContext context = SSLContext.getInstance("TLS"); context.init(null, new TrustManager[] { new DummyTrustManager() }, null);

Axway SecureTransport 5.3.0 Developer's Guide 194 9 REST API

HTTPSProperties prop = new HTTPSProperties( new DummyHostnameVerifier(), context);

ClientConfig config = new DefaultClientConfig(); config.getProperties().put(HTTPSProperties .PROPERTY_HTTPS_PROPERTIES, prop);

config.getClasses().add(JacksonJsonProvider.class); config.getClasses().add(JacksonJaxbJsonProvider.class); config.getClasses().add(MultiPartWriter.class);

Client result = Client.create(config); result.addFilter(new HTTPBasicAuthFilter(adminName, adminPassword));

return result; }

private static final class DummyTrustManager implements X509TrustManager { @Override public X509Certificate[] getAcceptedIssuers() { X509Certificate certs[] = new X509Certificate[0]; return null; }

@Override public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { }

@Override public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } }

private static final class DummyHostnameVerifier implements HostnameVerifier { public boolean verify(String hostname, SSLSession session) { return true; }

Axway SecureTransport 5.3.0 Developer's Guide 195 9 REST API

} }

Python This example is a Python program, AccountCreate.py. It depends on two libraries, wadllib and httplib2.

Edit the application.py file of the wadllib library and replace

return '{http://research.sun.com/wadl/2006/10}' + tag_name

with

return '{http://wadl.dev.java.net/2009/02}' + tag_name

The application requires the WADL specification from https://:/api/application.wadl.

The program reads its inputs from the user.

import os import import pkg_resources from wadllib.application import Application import httplib2 import json

class Resource(object): def __init__(self, resource, contentType): self.resource = resource self.contentType = contentType self.element = {}

def body(self): return json.dumps(self.element)

class Contact(object): def __init__(self, email = None, phone = None): self.contact = {} if email is not None: self.contact["email"] = email if phone is not None: self.contact["phone"] = phone

Axway SecureTransport 5.3.0 Developer's Guide 196 9 REST API

class Account(object): def __init__(self, name, homefolder = None, uid = None, gid = None, \ email = None, phone = None, mtype = "user"): self.account = {} self.account["type"] = mtype if name is not None : self.account["name"] = name if homefolder is not None : self.account["homeFolder"] = homefolder if uid is not None : self.account["uid"] = uid if gid is not None : self.account["gid"] = gid if email is not None or phone is not None : self.account["contact"] = Contact(email, phone).contact

class Accounts(Resource): def __init__(self, account = None): self.account_list = [] if account is not None: self.account_list.append(account.account) super(Accounts, self).__init__('accounts', 'application/json') self.element["accounts"] = self.account_list

class FTPSite(object): def __init__(self, name, account = None, default = False, \ port = "21", host = None, download_pattern = '*', \ upload_folder = '/upload', download_folder = '/download', \ username = None, issecure = "0"): self.site = {} self.site["name"] = name self.site["protocol"] = "ftp" if account is not None: self.site["account"] = account self.site["default"] = default if port is not None: self.site["port"] = port if host is not None: self.site["host"] = host self.site["download.pattern"] = download_pattern

Axway SecureTransport 5.3.0 Developer's Guide 197 9 REST API

self.site["upload.folder"] = upload_folder self.site["download.folder"] = download_folder if username is not None: self.site["username"] = username self.site["issecure"] = issecure

class Sites(Resource): def __init__(self, site = None): super(Sites, self).__init__('sites', 'application/json') self.site_list = [] if site is not None: self.site_list.append(site.site) self.element["sites"] = self.site_list

class SiteMailboxApplication(object): def __init__(self, name, folder, inbox_folder = "inbox", \ outbox_folder = 'outbox'): self.application = {} self.application["type"] = "SiteMailbox" self.application["name"] = name self.application["folder"] = folder self.application["INBOX_FOLDER"] = inbox_folder self.application["OUTBOX_FOLDER"] = outbox_folder

class Applications(Resource): def __init__(self, application = None): super(Applications, self).__init__('applications', \ 'application/json') self.application_list = [] if application is not None: self.application_list.append(application.application) self.element["applications"] = self.application_list

class Subscription(object): def __init__(self, account, application, folder = None): self.element = {} self.element["account"] = account.account["name"] self.element["application"] = application.application["name"] if folder is None: self.element["folder"] = application.application["folder"] else : self.element["folder"] = folder

Axway SecureTransport 5.3.0 Developer's Guide 198 9 REST API

class Subscriptions(Resource): def __init__(self, subscription = None): super(Subscriptions, self).__init__('subscriptions',\ 'application/json') self.element_list = [] if subscription is not None: self.element_list.append(subscription.element) self.element["subscriptions"] = self.element_list

class TransferConfiguration(object): def __init__(self, site, direction, tag): self.element = {} self.element["site"] = site self.element['direction'] = direction self.element['tag'] = tag

class TransferConfigurations(Resource): def __init__(self, transferConfiguration = None): super(TransferConfigurations, self) .__init__('transferConfigurations', 'application/json') self.element_list = [] if subscription is not None: self.element_list.append(transferConfiguration.element) self.element["transferConfigurations"] = self.element_list

class SSHKeyDescription(object): def __init__(self, account, usage, caPassword, subject, name = 'cert', validityPeriod = 365): self.element = {} self.element["account"] = account self.element['name'] = name self.element['usage'] = usage self.element['caPassword'] = caPassword self.element['type'] = 'ssh' self.element['subject'] = subject self.element['validityPeriod'] = validityPeriod

class Cretificate(object): def __init__(self, filePath): f = open(filePath); self.certificate = f.read();

Axway SecureTransport 5.3.0 Developer's Guide 199 9 REST API

print f.read();

class MultipartMixed(object): def __init__(self, boundary = 'bbb'): self.boundary = boundary; self.content = []

def addBodyPart(self, part, contentType): self.content.append([contentType, part])

class CertificateRequest (MultipartMixed, Resource): def __init__(self, filePath, account, usage, caPassword, subject, \ name = 'cert1', validityPeriod = 365, boundary = 'bbb'): MultipartMixed.__init__(self, boundary = 'bbb') Resource.__init__(self, 'certificates/import', \ ' multipart/mixed; boundary=' + self.boundary) self.addBodyPart(Cretificate(filePath), \ 'application/octet-stream') self.addBodyPart(SSHKeyDescription(account, usage, caPassword, \ subject, name,validityPeriod), 'application/json')

def body(self): result = '' for part in self.content: result += '\n--' + self.boundary + "\nContent-Type: " + \ part[0] if(part[0] == 'application/json'): result += '\n\n' + json.dumps(part[1].element) else: result += '\n' + part[1].certificate result += '\n--' + self.boundary + '--' return result

class MyClient(object): def __init__(self, wadl_file, wadl_url): self.client = httplib2 \ .Http(disable_ssl_certificate_validation=True) self.client.add_credentials("admin", "admin") self.wadl_string = open(wadl_file, 'r').read() self.wadl = Application(wadl_url, self.wadl_string)

def post(self, element, request_url = None):

Axway SecureTransport 5.3.0 Developer's Guide 200 9 REST API

if (request_url is None): request_url = self.wadl \ .get_resource_by_path(element.resource) \ .get_method('POST').build_request_url() response, body = self.client .request(request_url,'POST',element.body(), {'Content-Type': element.contentType}) print response['status'] print body

def get(self, resource, param): resource = self.wadl.get_resource_by_path(resource) print resource._url get_method = resource.get_method('GET') response, body = self.client .request(get_method.build_request_url(param), 'GET') print response['status'] return json.loads(body)

a = raw_input('Enetr:') print a

wadlFile = 'application.wadl.xml' url = 'https://st.example.com:444/api/v1.0/'

client = MyClient(wadlFile, \ "https://st.example.com:444/api/application.wadl")

accountName = raw_input('Account name: ') accountHomefolder = raw_input('User\'s homefolder: ') accountID = raw_input('pid:') groupID = raw_input('gid: ') accountEmail = raw_input('email: ') accountPhone = raw_input('phone: ') sshkeyPath = raw_ input('sshkey file: ')

account = Account(name = accountName, homefolder = accountHomefolder, \ uid = accountID, gid = groupID, email = accountEmail, \ phone = accountPhone) print json.dumps(account.account) accounts = Accounts(account) client.post(accounts)

Axway SecureTransport 5.3.0 Developer's Guide 201 9 REST API

site = FTPSite(name = "FTPSite3", account = account.account["name"], \ host = "st.example.com", username = "usr", issecure = "1") sites = Sites(site) client.post(sites)

smb = SiteMailboxApplication("SMB7", "/SMB7") print json.dumps(smb.application) applications = Applications(smb) print json.dumps(applications.element) client.post(applications)

subscription = Subscription(account, smb) subscriptions = Subscriptions(subscription) client.post(subscriptions) body = client.get('subscriptions', \ {'account' : account.account["name"], \ 'application' : smb.application["name"]}) print body subscr_id = body['subscriptions'].pop()['id'] print subscr_id

transferConfiguration = TransferConfiguration(site.site['name'], 1, \ 'PARTNER-OUT') transferConfigurations = TransferConfigurations(transferConfiguration) print json.dumps(transferConfigurations.element) client.post(transferConfigurations, url + 'subscriptions/' + subscr_id \ + '/' + transferConfigurations.resource)

cert = CertificateRequest(sshkeyPath, account.account['name'], \ 'login', 'SECRET123', \ 'CN=qwew, OU=fsdfs, O=wedf, L=fsdf, S=frwer, C=efwe') client.post(cert, url + cert.resource)

Shell script using cURL This example is a bash shell script, AccountCreate.sh, that uses cURL for the HTTP functionality. The script takes the values for the account attributes as parameters. The command to run it:

Axway SecureTransport 5.3.0 Developer's Guide 202 9 REST API

./AccountCreate.sh –name -homefolder \ -uid -gid -email \ -phone -key

#!/bin/bash

# The script creates ST user account, FTP push transfer site and Site # Mailbox application , imports SSH key and subscribes the user to # the application using the transfer site. The account's name, home # folder, email address, phone, user id and group id are given # respectively with options -name, -homefolder, -email, -phone, # -uid, -gid. The SSH key that is going to be imported should be # stored in a file and the file should be given using the option # -key. All the options are required. The configurations of the # application, the subscription, the FTP transfer site and the # certificate description are hardcoded.

validate () { echo -e "\n"${2} case ${1} in *http_code=200*) echo -e "successful operation" returncode=0 ;; *http_code=204*) echo -e "successful operation" returncode=0 ;; *) echo -e "operation failed" returncode=1 echo -e "\n"${2}"\noperation failed\n"${1} ;; esac

#echo -e ${1} return ${returncode} }

#The ST administrator's : authentication="admin_name:admin_password" #The ST's version 1.0 Resstful API's resourse url="https://${authentication}@ST_host:port/api/v1.0/" json_media_type="Content-Type: application/json" xml_media_type="Content-Type: application/xml"

Axway SecureTransport 5.3.0 Developer's Guide 203 9 REST API

#The requiered options' names opts=("name" "homefolder" "uid" "gid" "email" "phone" "key") opts_string=""

for opt in "${opts[@]}" do opts_string="${opts_string} -${opt}" done

test_opts=""

#validate the options until [ -z "${1}" ] do option=${1} shift value=${1} shift if [ -z "${value}" ] then echo "No value for the ${option} argument" >&2 exit 2 fi for opt in "${opts[@]}" do if [ "-${opt}" == "${value}" ] then echo "No value for the ${option} arument" >&2 exit 2 fi done case ${option} in -name) #name='"name" : "'${value}'"' account_name=${value} test_opts="${test_opts} name" ;; -homefolder) homefolder=${value} test_opts="${test_opts} homefolder" ;; -uid) uid=${value} test_opts="${test_opts} uid" ;;

Axway SecureTransport 5.3.0 Developer's Guide 204 9 REST API

-gid) gid=${value} test_opts="${test_opts} gid" ;; -email) email=${value} test_opts="${test_opts} email" ;; -phone) phone=${value} test_opts="${test_opts} phone" ;; -key) if [ -f ${value} ] then key=${value} test_opts="${test_opts} key" else echo "The file ${value} doesn't exist." >&2 exit 2 fi ;; *) echo "${option} is not a valid option.\ The only valid options are: ${opts_string}" >&2 exit 2 ;; esac done

#Validate if all the options have values for opt in "${opts[@]}" do contains=`echo ${test_opts} | "${opt}"` if [ -z "${contains}" ] then echo "Missing option -${opt}" >&2 exit 2 fi done

returncode=0

json_rq_account='{ "name" : "'${account_name}'", "homeFolder" : "'${homefolder}'",

Axway SecureTransport 5.3.0 Developer's Guide 205 9 REST API

"uid" : "'${uid}'", "gid" : "'${gid}'", "type" : "user", "contact" : { "email" : "'${email}'", "phone" : "'${phone}'" } }'

response=a` -k -w "\nhttp_code=%{http_code}\n" \ -H "${json_media_type}" \ -X PUT -d "${json_rq_account}" ${url}"accounts/"${account_name} \ 2>/dev/null`

(validate "${response}" "Creating account") if [ ${?} -ne "0" ] then returncode=${?} fi

#create Transfer Site site_name="ftpSite" #The "issecure" parameter defines if the Transfer site uses ftp #(value "0") or ftps (value "1") json_rq_sites='{ "sites" : [ { "name" : "'${site_name}'", "protocol" : "ftp", "account" : "'${account_name}'", "transferType" : "N", "port" : "21", "host" : "remote", "download.pattern" : "*", "upload.folder" : "/upload", "username" : "user", "download.folder" : "/download", "issecure" : "1" }] }'

response=`curl -k - w "http_code=%{http_code}" \ -H "${json_media_type}" \ -X POST -d "${json_rq_sites}" ${url}"sites/" 2>/dev/null`

Axway SecureTransport 5.3.0 Developer's Guide 206 9 REST API

(validate "${response}" "Creating Transfer Site") if [ ${?} -ne "0" ] then returncode=${?} fi

#create SiteMailbox application application_name="smb" json_rq_applications='{ "applications" : [ { "folder" : "/'${application_name}'", "INBOX_FOLDER" : "inbox", "OUTBOX_FOLDER" : "outbox", "type" : "SiteMailbox", "name" : "'${application_name}'" } ] }'

response=`curl -k - w "\nhttp_code=%{http_code}\n" \ -H "${json_media_type}" \ -X POST -d "${json_ rq_applications}" ${url}"applications/" \ 2>/dev/null`

(validate "${response}" "Creating Application") if [ ${?} -ne "0" ] then returncode=${?} fi

#create subscription json_rq_subscriptions='{ "subscriptions" : [ { "account" : "'${account_name}'", "application" : "'${application_name}'", "folder" : "/'${application_name}'" } ] }'

response=`curl -k - w "\nhttp_code=%{http_code}\n" \ -H "${json_media_type}" \ -X POST -d "${json_ rq_subscriptions}" ${url}"subscriptions/" \ 2>/dev/null`

(validate "${response}" "Subscribing account to application") if [ ${?} -ne "0" ] then returncode=${?} fi

Axway SecureTransport 5.3.0 Developer's Guide 207 9 REST API

#filter subscription from given account and to given application filter='?application='${application_name}'&account='${account_name}

#get the transfer configuration resource url for this subscription transferconf_url=`curl -k -H "${json_media_type}" \ -X GET $url'subscriptions' ${filter} 2>/dev/null | \ grep "transferConfigurations" | ' ' '\n' | \ grep "https" | tr -d ',"'`

#create transfer configuration #direction 1 for Send files, 0 for receive json_rq_trsfr_confs='{ "transferConfigurations": [ { "direction" : 1, "tag" : "PARTNER-OUT", "site" : "'${site_name}'" } ] }'

response=`curl -k - w "\nhttp_code=%{http_code}\n" \ -H "${json_media_type}" -X POST - u ${authentication} \ -d "${json_rq_trsfr_confs}" ${transferconf_url} \ 2>/dev/null`

(validate "${response}" "Creating transfer configuration") if [ ${?} -ne "0" ] then returncode=${?} fi

#import ssh key if [ -e ${$} ] then echo "File with name ${$} exists. To execute the script \ it shouldn't exist." >&2 exit 1 fi

json_cert_info='{ "name" : "certificate", "type" : "ssh", "usage" : "login", "validityPeriod" : "365", "caPassword" : "tumbleweed", "account" : "'${account_name}'",

Axway SecureTransport 5.3.0 Developer's Guide 208 9 REST API

"subject" : "cn=sc, ou=ou, o=o" }'

content_part0="--bbb\n\ Content-Type: application/octet-stream\n\ \n"

content_part2="\n\ \n\ --bbb\n\ ${json_media_type}\n\ \n\ ${json_cert_info}\n\ --bbb--"

echo -e ${content_part0} >> ${$} ${key} >> ${$} echo -e ${content_part2} >> ${$}

response=`curl -k - w "\nhttp_code=%{http_code}\n"\ -H 'Content-Type: multipart/mixed; boundary=bbb' -X POST\ --data-binary "@${$}" $url'certificates/import' \ 2>/dev/null`

(validate "${response}" "Importing certificate") if [ ${?} -ne "0" ] then returncode=${?} fi

-f ${$}

exit ${returncode}

Push a file This example illustrates use of the SecureTransport REST API to push a file from the SecureTransport Server using the cURL command-line tool to post the request. In this case, the push uses a System To Human file transfer site.

In addition to parameters that specify the file to send and the transfer site to use, the call include two custom properties that create variables and set their values. Such new variables are named DXAGENT_TRANSFERSAPI_NAME, where NAME is the name in the call. In this example, the custom variables can be used as follows in the System To Human transfer site:

Axway SecureTransport 5.3.0 Developer's Guide 209 9 REST API

l ${DXAGENT_TRANSFERSAPI_RECIPIENT} – the value of the To field

l ${DXAGENT_TRANSFERSAPI_NAME} – used in the email body

The command-line call specifies the required parameters, show as placeholders:

$ curl -k --user user_name:password -X POST -i \ -H "Content-type: application/json" \ -H "Accept: application/json" -d " { \"file\" : \"file_name\", \"site\" : \"site_name\", \"asynchronousCall\" : false, \"RECIPIENT\" : \"recipient_email_address\", \"NAME\" : \"recipient_name\" }" https:// ST_Server_host_name_or_IP_address/api/v1.0/transfers/push

A specific example with values instead of placeholders:

$ curl -k --user [email protected]:W4g9xPtz4 -X POST -i \ -H "Content-type: application/json" \ -H "Accept: application/json" -d " { \"file\" : \"/outgoing/report.xml\", \"site\" : \"Mail-To\", \"asynchronousCall\" : false, \"RECIPIENT\" : \"[email protected]\", \"NAME\" : \"Ralph Reported\" }" https://st.example.com/api/v1.0/transfers/push

The output reports the outcome of the transfer and includes a link to detailed transfer results:

HTTP/1.1 200 OK Server: SecureTransport 5.2 (build: 3946) Features: CHPWD;RTCK;STCK;ASC;DNDISP Accept-Ranges: bytes X-Frame-Options: SAMEORIGIN Set-Cookie: FDX=1d5f1ps3bybc81mr768n416win;Path=/;Secure Set-Cookie: loggedIn=yep Expires: Thu, 01 Jan 1970 00:00:00 GMT Content-Type: application/json Pragma: no-cache Expires: 0 Cache-Control: no-cache Cache-Control: no-store Content-Encoding: UTF-8 Transfer-Encoding: chunked

Axway SecureTransport 5.3.0 Developer's Guide 210 9 REST API

{ "message" : "Transfer is successful. Follow link to view file tracking information.", "link" : "https://ST_Server_host_name_or_IP_ address/api/v1.0/transfers?operationIndex=869247b5-f60c-46c6-b019- 0e16865c00eb&startTimeAfter=Wed,+24+Oct+2012+12:34:56+-0700&limit=100" }

Custom HTML template This example illustrates the use of the SecureTransport REST API in a custom HTML template. It uses the Files resource to add a custom file property that the user can view and set. The custom property, confidential.level, is implemented for each file. The property can take one of the following values:

l unset, the default

l confidential

l secret

l top secret

Custom JavaScript in the example uses the REST Files API to set and get confidential.level for a file.

To demonstrate the example, you must make a copy of the SecureTransport Default HTML Template and replace the options.html file with the example file. The resulting HTML template show the value of confidential.level on the file options page and includes controls to change its value. This section includes a procedure to add a custom HTML template, called My Orange Potato, to the HTML templates in the SecureTransport server.

SecureTransport File Options

  

Axway SecureTransport 5.3.0 Developer's Guide 214 9 REST API

   Welcome to SecureTransport Logout 
 

 

 Download and Delete Files

Axway SecureTransport 5.3.0 Developer's Guide 215 9 REST API

Axway SecureTransport 5.3.0 Developer's Guide 216 9 REST API

application/octet-stream
text/plain
text/html
confidential secret top secret

To implement the custom My Orange Potato template and include it to the HTML templates in SecureTransport server:

1. Make the /share/ftdocs/html/skin/myOrangePotato directory.

2. Copy the /share/ftdocs/html/C directory into the /share/ftdocs/html/skin/myOrangePotato directory.

3. Create the /share/ftdocs/html/skin/myOrangePotato/skin.conf file with the following content:

description "My Orange Potato" icons-access "public"

4. Replace /share/ftdocs/html/skin/myOrangePotato/C/option s.html with the example options.html file.

5. Restart the SecureTransport server.

To view the customized browser client page, create a user account with the HTML Template field set to setting to My Orange Potato, log in to SecureTransport, and navigate to the file properties page.

The custom fields are in the Download and Delete Files pane.

Axway SecureTransport 5.3.0 Developer's Guide 217 9 REST API

Java file transfer library This example illustrates use of the SecureTransport REST API to create a Java library that uses Jersey client and allows clients to upload files, move files and push files to transfer sites. It uses the following resources:

l Files

l Transfers

l Applications

l Subscriptions

l Certificates

The library uses basic authentication for log in to the SecureTransport server. The library supports both synchronous and asynchronous file transfers and checking file transfer status based on the returned ID.

The library is STClient.java:

package files;

import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.text.ParseException; import java.util.UUID;

import javax.net.ssl.SSLContext;

Axway SecureTransport 5.3.0 Developer's Guide 218 9 REST API

import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLSession; import javax.ws.rs.core.MediaType;

import org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider; import org.codehaus.jackson.jaxrs.JacksonJsonProvider;

import com.axway.st.ws.providers.JsonContextResolver; import com.axway.st.ws.representation.File; import com.axway.st.ws.representation.TransferLogEntries; import com.axway.st.ws.representation.TransferPush; import com.axway.st.ws.representation.TransferResult; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; import com.sun.jersey.client.urlconnection.HTTPSProperties; import com.sun.jersey.core.header.ContentDisposition; import com.sun.jersey.multipart.BodyPart; import com.sun.jersey.multipart.MultiPart; import com.sun.jersey.multipart.impl.MultiPartWriter;

public class STClient {

String name; String password; String serverAddress; Client client; WebResource webResource;

public STClient(String name, String password, String serverAddress) throws KeyManagementException, NoSuchAlgorithmException { this.name = name; this.password = password; client = clientConfig(); setServerAddress(serverAddress); }

Axway SecureTransport 5.3.0 Developer's Guide 219 9 REST API

public void setServerAddress(String serverAddress) { this.serverAddress = serverAddress; webResource = client.resource(serverAddress); }

public String getName(String name) { return this.name; }

public String getPassword(String password) { return this.password; }

public String getServerAddress(String serverAddress) { return this.serverAddress; }

private Client clientConfig() throws KeyManagementException, NoSuchAlgorithmException { SSLContext context = SSLContext.getInstance("TLS"); context.init(null, new TrustManager[] { new DummyTrustManager() }, null);

HTTPSProperties prop = new HTTPSProperties( new DummyHostnameVerifier(), context);

ClientConfig config = new DefaultClientConfig(); config.getProperties().put(HTTPSProperties .PROPERTY_HTTPS_PROPERTIES, prop);

config.getClasses().add(JsonContextResolver.class); config.getClasses().add(JacksonJsonProvider.class); config.getClasses().add(JacksonJaxbJsonProvider.class); config.getClasses().add(MultiPartWriter.class);

Client result = Client.create(config); result.addFilter(new HTTPBasicAuthFilter(this.name, this.password));

return result; }

Axway SecureTransport 5.3.0 Developer's Guide 220 9 REST API

public void uploadFile(java.io.File file, String toUploadPath, String name, String transferMode) throws IOException, ParseException { if (name == null) name = file.getName(); MultiPart f = file(file, name); WebResource webResource2 = client.resource(serverAddress + "files" + toUploadPath + "?transferMode=" + transferMode); System.out.println(webResource2 .type(MediaType.MULTIPART_FORM_DATA) .post(ClientResponse.class, f)); }

public void moveFile(String path, String newPath) { File file = new File(); file.setNewFilePath(newPath); webResource.path("files" + path) .type(MediaType.APPLICATION_XML_TYPE).post(file); }

public void pushFileSync(String filepath, String siteName) { TransferPush tp = new TransferPush(); tp.setOperationIndex((UUID.randomUUID()).toString()); pushFile(filepath, siteName, tp); }

public String pushFileAsync(String filepath, String siteName) { TransferPush tp = new TransferPush(); return pushFile(filepath, siteName, tp); }

public String pushFile(String filepath, String siteName, TransferPush tp) { tp.setFile(filepath); tp.setSite(siteName); ClientResponse r = webResource.path("transfers/push") .type(MediaType.APPLICATION_XML_TYPE) .post(ClientResponse.class, tp); TransferResult tr = r.getEntity(TransferResult.class); return tr.getLink();

Axway SecureTransport 5.3.0 Developer's Guide 221 9 REST API

}

public String checkStatus(String webResource) throws InterruptedException { WebResource wr = client.resource(webResource); TransferLogEntries tre = wr.type(MediaType.APPLICATION_XML).get( TransferLogEntries.class); return tre.getTransferEntries().get(0).getStatus(); }

private MultiPart file(java.io.File file, String name) throws IOException, ParseException { MultiPart result = new MultiPart(MediaType .MULTIPART_FORM_DATA_TYPE); BodyPart bp = new BodyPart(); bp.contentDisposition(ContentDisposition .type("form-data; name=\"File\";") .fileName(name).build()); bp.entity(readFile(file.getPath())); bp.type(MediaType.TEXT_PLAIN_TYPE); result.bodyPart(bp); return result; }

private static String readFile(String path) throws IOException { StringBuffer result = new StringBuffer(); FileInputStream fin = new FileInputStream(path); InputStreamReader reader = new InputStreamReader(fin); char[] tmp = new char[1024];

while (reader.read(tmp) != -1) { result.append(tmp); }

return result.toString(); }

private static final class DummyTrustManager implements X509TrustManager { @Override public X509Certificate[] getAcceptedIssuers() {

Axway SecureTransport 5.3.0 Developer's Guide 222 9 REST API

X509Certificate certs[] = new X509Certificate[0]; return null; }

@Override public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { }

@Override public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } }

private static final class DummyHostnameVerifier implements HostnameVerifier { public boolean verify(String hostname, SSLSession session) { return true; } } }

Axway SecureTransport 5.3.0 Developer's Guide 223 Appendix A: Agent execution order

The following topics lists the order of execution of agents when commands are executed:

l Client-initiated transfers on page 224 - Lists the sequence in which agents are executed for a file transfer in SecureTransport Command Line, Windows, and Browser clients using the supported protocols.

l Server-initiated transfers on page 225 - Lists the sequence in which agents are executed for a file transfer for Server Transfer - Pull and Server Transfer - Push events using the supported protocols.

Client-initiated transfers The following table lists the sequence in which agents are executed for a file transfer in SecureTransport Command Line, Windows, and Browser clients using the supported protocols. Each client has already logged onto the server before the file transfer sequence shown is started. If the Windows client is transferring multiple files, the login agent is executed only once during the initial transfer.

Protocol Command Line Windows Browser

Upload Download Upload Download Upload Download

FTP size, size, rtck, login, size, login, size, rest, N/A N/A start, size, start, rest, rest, rest, start, retr, stor, retr, end, start, stor, end, size, rtck, end, rtck rtck end, size, logout rtck, logout

HTTPS size, size, mdtm, login, size, login, size, start, start, size, start, size, start, mdtm, size, mdtm, size, stor, mdtm, retr, stor, size, mdtm, rest, start, mdtm, size, end end size, rest, retr, stor, size, start, size, rtck, end, size, rtck, end, mdtm, rest, retr, end, mdtm, rtck size, mdtm, end, size, size, rtck, logout mdtm, rtck, mdtm, logout rtck

SSH mdtm, mdtm, start, N/A N/A N/A N/A (SCP and start, retr, end SFTP) stor, end

Axway SecureTransport 5.3.0 Developer's Guide 224 Appendix A: Agent execution order

Server-initiated transfers The following table lists the sequence in which agents are executed for a file transfer for Server Transfer - Pull and Server Transfer - Push events using the supported protocols.

Protocol Server Transfer - Push Server Transfer - Pull

FTP size, start, retr, end start, stor, end

SFTP size, start, retr, end start, stor, end

HTTP size, rtck, rtck, start, rest, retr, end size, rtck, start, rest, stor, rtck, end

AS2 start, end start, end

Folder start, retr, end start, stor, end

Axway SecureTransport 5.3.0 Developer's Guide 225 Appendix B: Developing condition functions

The following topics describe how to develop condition functions:

l Condition functions overview on page 226 - Provides an overview of condition functions.

l Condition functions on page 226 - Describes condition functions.

l File content search example on page 226 - Provides a file content search example using condition functions.

l Installing condition functions on page 227 - Provides how to instructions for installing condition functions.

Condition functions overview SecureTransport supports a set of built-in capabilities to define rule triggering conditions. SecureTransport provides support for an extension mechanism allowing users to define new condition functions. These functions have to be written in Java, and installed on the server before they can be used. For example, you can write a class that parses an Electronic Data Interchange (EDI) file and compares the value of a data element with a string.

Condition functions To write a condition function, you must use Java programming language and develop them according to the API described in the SecureTransport Software Development Kit. This topic provides an overview of the structure of a condition function.

The code for a condition function must be a Java class file or should be packed within a .jar file. This .jar file must be uploaded to Transaction Manager. A condition function defines a method, called examine, which is executed when the condition function is invoked. A set of parameters that define the context of the invocation are passed to the function. The condition function evaluates the input parameters and returns a true or false value depending on the result.

When Transaction Manager executes the condition function, the agent processes the input data and returns a true or false value depending on the result.

File content search example The topic contains an example to illustrate how condition functions are used.

Axway SecureTransport 5.3.0 Developer's Guide 226 Appendix B: Developing condition functions

1. Declare the class that implements CallableItem.

public class Condition implements ConditionFunction { ... }

2. Write the method called "examine".

public boolean examine(ConditionEvent event, Map params) throws Exception { ... }

3. In this function, extract the file name and the string to search.

String fileName = params.get("filename"); String strLookFor = params.get("target");

4. The function searches for the string in the file. If the string is found, it returns true; otherwise it returns false.

BufferedReader in = new BufferedReader( new FileReader(fileName)); String aLine;

try { while((aLine = in.readLine()) != null) if (aLine.indexOf(strLookFor) != -1) return true; return false; } finally { in.close(); }

Installing condition functions After developing a condition function, you must install it on the server to use it.

1. Select Transaction Manager > Install Functions from the Administration Tool.

The Install Function Classes page is displayed.

Axway SecureTransport 5.3.0 Developer's Guide 227 Appendix B: Developing condition functions

Enter the complete path to the .jar or .class file or click Browse to locate the file.

2. Click Install. 3. The file is uploaded to the server. If the file already exists on the server, you are prompted for confirmation to overwrite it.

The .class files are uploaded to /brules/local/callable/classes directory and .jar files are uploaded to /brules/local/callable/jars directory on the server.

Axway SecureTransport 5.3.0 Developer's Guide 228