66
Using TCP Adapters with Ensemble Version 2012.2 31 August 2012 InterSystems Corporation 1 Memorial Drive Cambridge MA 02142 www.intersystems.com

Using TCP Adapters with Ensemble

  • Upload
    others

  • View
    0

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Using TCP Adapters with Ensemble

Using TCP Adapters withEnsemble

Version 2012.231 August 2012

InterSystems Corporation 1 Memorial Drive Cambridge MA 02142 www.intersystems.com

Page 2: Using TCP Adapters with Ensemble

Using TCP Adapters with EnsembleEnsemble Version 2012.2 31 August 2012 Copyright © 2012 InterSystems CorporationAll rights reserved.

This book was assembled and formatted in Adobe Page Description Format (PDF) using tools and information from the following sources:Sun Microsystems, RenderX, Inc., Adobe Systems, and the World Wide Web Consortium at www.w3c.org.The primary document developmenttools were special-purpose XML-processing applications built by InterSystems using Caché and Java.

, ,

Caché WEBLINK, Distributed Cache Protocol, M/SQL, M/NET, and M/PACT are registered trademarks of InterSystems Corporation.

, , , ,

InterSystems Jalapeño Technology, Enterprise Cache Protocol, ECP, and InterSystems Zen are trademarks of InterSystems Corporation.

All other brand or product names used herein are trademarks or registered trademarks of their respective companies or organizations.

This document contains trade secret and confidential information which is the property of InterSystems Corporation, One Memorial Drive,Cambridge, MA 02142, or its affiliates, and is furnished for the sole purpose of the operation and maintenance of the products of InterSystemsCorporation. No part of this publication is to be used for any other purpose, and this publication is not to be reproduced, copied, disclosed,transmitted, stored in a retrieval system or translated into any human or computer language, in any form, by any means, in whole or in part,without the express prior written consent of InterSystems Corporation.

The copying, use and disposition of this document and the software programs described herein is prohibited except to the limited extentset forth in the standard software license agreement(s) of InterSystems Corporation covering such programs and related documentation.InterSystems Corporation makes no representations and warranties concerning such software programs other than those set forth in suchstandard software license agreement(s). In addition, the liability of InterSystems Corporation for any losses or damages relating to or arisingout of the use of such software programs is limited in the manner set forth in such standard software license agreement(s).

THE FOREGOING IS A GENERAL SUMMARY OF THE RESTRICTIONS AND LIMITATIONS IMPOSED BY INTERSYSTEMSCORPORATION ON THE USE OF, AND LIABILITY ARISING FROM, ITS COMPUTER SOFTWARE. FOR COMPLETE INFORMATIONREFERENCE SHOULD BE MADE TO THE STANDARD SOFTWARE LICENSE AGREEMENT(S) OF INTERSYSTEMS CORPORATION,COPIES OF WHICH WILL BE MADE AVAILABLE UPON REQUEST.

InterSystems Corporation disclaims responsibility for errors which may appear in this document, and it reserves the right, in its sole discretionand without notice, to make substitutions and modifications in the products and practices described in this document.

For Support questions about any InterSystems products, contact:

InterSystems Worldwide Customer Support+1 617 621-0700Tel:+1 617 374-9391Fax:[email protected]:

Page 3: Using TCP Adapters with Ensemble

Table of Contents

About This Book .................................................................................................................................... 1

1 Choosing a TCP Adapter ................................................................................................................... 31.1 Choosing an Inbound Adapter .................................................................................................... 31.2 Choosing an Outbound Adapter ................................................................................................. 4

2 Using the TCP Counted Inbound Adapter ....................................................................................... 52.1 Background Information ............................................................................................................ 52.2 Using the Adapter ....................................................................................................................... 72.3 Creating a New Business Service Class ..................................................................................... 72.4 Sample Business Service Class Code ......................................................................................... 92.5 Adapter Settings ....................................................................................................................... 10

3 Using the TCP Counted Outbound Adapter .................................................................................. 133.1 Background Information .......................................................................................................... 133.2 Using the Adapter ..................................................................................................................... 153.3 Creating a New Business Operation Class ............................................................................... 153.4 Sample Business Operation Class Code ................................................................................... 173.5 Available Helper Methods ........................................................................................................ 183.6 Adapter Settings ....................................................................................................................... 18

4 Using the TCP Counted XML Inbound Adapter .......................................................................... 214.1 Background Information .......................................................................................................... 214.2 Using the Adapter ..................................................................................................................... 234.3 Creating a New Business Service Class ................................................................................... 234.4 Adapter Settings ....................................................................................................................... 25

5 Using the TCP Counted XML Outbound Adapter ........................................................................ 275.1 Background Information .......................................................................................................... 275.2 Using the Adapter ..................................................................................................................... 295.3 Creating a New Business Operation Class ............................................................................... 295.4 Available Helper Methods ........................................................................................................ 315.5 Adapter Settings ....................................................................................................................... 32

6 Using the TCP Text Line Inbound Adapter ................................................................................... 356.1 Background Information .......................................................................................................... 356.2 Using the Adapter ..................................................................................................................... 376.3 Creating a New Business Service Class ................................................................................... 376.4 Sample Business Service Class Code ....................................................................................... 396.5 Adapter Settings ....................................................................................................................... 396.6 Adding a TCP Status Service ................................................................................................... 41

7 Using the TCP Text Line Outbound Adapter ................................................................................ 437.1 Background Information .......................................................................................................... 437.2 Using the Adapter ..................................................................................................................... 457.3 Creating a New Business Operation Class ............................................................................... 457.4 Available Helper Methods ........................................................................................................ 477.5 Adapter Settings ....................................................................................................................... 48

8 Creating Custom TCP Adapter Classes ......................................................................................... 518.1 Creating a Custom Subclass ..................................................................................................... 51

Using TCP Adapters with Ensemble                                                                                                                                      iii

Page 4: Using TCP Adapters with Ensemble

8.2 Common Customizations in TCP Adapter Subclasses ............................................................. 528.3 Customizing Callbacks of Inbound TCP Adapters ................................................................... 538.4 Customizing Callbacks of Outbound TCP Adapters ................................................................ 53

Appendix A:Settings for the Abstract TCP Adapters ....................................................................... 55A.1 Settings for EnsLib.TCP.InboundAdapter ............................................................................... 55A.2 Settings for EnsLib.TCP.OutboundAdapter ............................................................................ 56

Appendix B:Common Tasks in the Management Portal .................................................................. 59B.1 Accessing a Production ............................................................................................................ 59B.2 Adding a Business Host to a Production ................................................................................. 59B.3 Editing Runtime Settings of a Business Host .......................................................................... 60

iv                                                                                                                                      Using TCP Adapters with Ensemble

Page 5: Using TCP Adapters with Ensemble

List of Figures

Figure 2–1: Using the TCP Counted Inbound Adapter and Business Service ........................................ 6Figure 3–1: Business Operation and Using the TCP Counted Outbound Adapter ................................ 14Figure 4–1: Using the TCP Counted XML Inbound Adapter and Business Service ............................ 22Figure 5–1: Business Operation and Using the TCP Counted XML Outbound Adapter ...................... 28Figure 6–1: Using the TCP Text Line Inbound Adapter and Business Service ..................................... 36Figure 7–1: Business Operation and Using the TCP Text Line Outbound Adapter .............................. 44

Using TCP Adapters with Ensemble                                                                                                                                       v

Page 6: Using TCP Adapters with Ensemble

List of Tables

Table 6–1: TCP Status Service Commands ........................................................................................... 42

vi                                                                                                                                      Using TCP Adapters with Ensemble

Page 7: Using TCP Adapters with Ensemble

About This Book

TCP is a transport layer protocol that supports many types of higher-level communication protocol. This book providesinstructions for configuring and using the TCP adapters that Ensemble provides. These adapters support several simpletypes of TCP, with inbound and outbound versions of each type.

This book contains the following sections:

• “Choosing a TCP Adapter” provides information on all the TCP adapters, some of which are automatically includedin specialized Ensemble business hosts, discussed in other books.

• “Using the TCP Counted Inbound Adapter” discusses the inbound adapter you use for a counted block TCP connection.

• “Using the TCP Counted Outbound Adapter” discusses the outbound adapter you use for a counted block TCP con-nection.

• “Using the TCP Counted XML Inbound Adapter” discusses the inbound adapter you use to transfer XML over acounted block TCP connection.

• “Using the TCP Counted XML Outbound Adapter” discusses the outbound adapter you use to transfer XML over acounted block TCP connection.

• “Using the TCP Text Line Inbound Adapter” discusses the inbound adapter you use for a text line TCP connection.

• “Using the TCP Text Line Outbound Adapter” discusses the inbound adapter you use for a text line TCP connection.

• “Creating Custom TCP Adapter Classes” discusses how to create custom TCP adapter classes.

• “Settings for the Abstract TCP Adapters” describes the settings in the two abstract adapter classes on which all thepreceding classes are based.

• “Common Tasks in the Management Portal” provides more detail on some of the tasks described in this book.

For a detailed outline, see the table of contents.

The following books provide related information:

• Developing Ensemble Productions describes how to create Ensemble productions in general.

• Configuring Ensemble Productions describes how to configure the settings for Ensemble productions, business hosts,and adapters. It provides details on settings not discussed in this book.

• Monitoring Ensemble describes how to monitor the behavior of the adapter at runtime.

Using TCP Adapters with Ensemble                                                                                                                                       1

Page 8: Using TCP Adapters with Ensemble
Page 9: Using TCP Adapters with Ensemble

1Choosing a TCP Adapter

This chapter discusses the following topics:

• Choosing an Inbound Adapter

• Choosing an Outbound Adapter

1.1 Choosing an Inbound AdapterThe EnsLib.TCP.InboundAdapter is an abstract class that provides methods to allow you to establish and maintain a connectionbetween a TCP client and Ensemble as a TCP listener. No Ensemble business service references theEnsLib.TCP.InboundAdapter class directly, because this class does not have any specific methods for parsing data acrossthe TCP connection. You must either use an existing subclass or implement your own subclass.

The following list describes scenarios and applicable adapters.

Inbound HTTP

See Using HTTP Adapters with Ensemble.

Inbound SOAP

See Creating Web Services and Web Clients with Ensemble.

Inbound TCP

Consider using these adapters for inbound TCP connections:

• TCP Counted Inbound Adapter

• TCP Counted XML Inbound Adapter

• TCP Text Line Inbound Adapter

Inbound TCP for ASTM message routing

If you use the built-in Ensemble business services for ASTM, a TCP adapter comes into the Ensemble configurationautomatically. See “ASTM Business Services” in the chapter “Elements of a Routing Production” in theEnsemble ASTM Development Guide.

Using TCP Adapters with Ensemble                                                                                                                                       3

Page 10: Using TCP Adapters with Ensemble

Inbound TCP for HL7 message routing

If you use the built-in Ensemble business services for HL7, a TCP adapter comes into the Ensemble configurationautomatically. See “HL7 Business Services” in the chapter “Elements of a Routing Production” in the EnsembleHL7 Version 2 Development Guide.

Inbound TCP for X12 message routing

If you use the built-in Ensemble business services for X12, a TCP adapter comes into the Ensemble configurationautomatically. See “X12 Business Services” in the chapter “Elements of a Routing Production” in the EnsembleHL7 Version 2 Development Guide.

If your configuration uses TCP and you cannot get what you need from any of the inbound adapters provided, you candevelop a new inbound adapter class based on the EnsLib.TCP.InboundAdapter or any of its subclasses. See the chapter“Creating Custom TCP Adapter Classes.”

1.2 Choosing an Outbound AdapterThe EnsLib.TCP.OutboundAdapter establishes and maintains a connection between Ensemble as a TCP client and anexternal TCP listener. No Ensemble business operation references the EnsLib.TCP.OutboundAdapter class directly, becausethis class does not have any specific methods for parsing data across the TCP connection. You must either use an existingsubclass or implement your own subclass.

The following list describes scenarios and applicable adapters.

Outbound TCP

Consider using these adapters for outbound TCP connections:

• TCP Counted Outbound Adapter

• TCP Counted XML Outbound Adapter

• TCP Text Line Outbound Adapter

Outbound TCP for ASTM message routing

If you use the built-in Ensemble business operations for ASTM, Ensemble includes a TCP adapter in the configu-ration automatically. See “ASTM Business Operations” in the chapter “Elements of a Routing Production” inthe Ensemble ASTM Development Guide.

Outbound TCP for HL7 Message Routing

If you use the built-in Ensemble business operations for HL7, Ensemble includes a TCP adapter in the configurationautomatically. See “HL7 Business Operations” in the chapter “Elements of a Routing Production” in theEnsemble HL7 Version 2 Development Guide.

Outbound TCP for X12 Message Routing

If you use the built-in Ensemble business operations for X12, Ensemble includes a TCP adapter in the configurationautomatically. See “X12 Business Operations” in the chapter “Elements of a Routing Production” in theEnsemble HL7 Version 2 Development Guide.

If your configuration uses TCP and you cannot get what you need from any of the inbound adapters provided, you candevelop a new inbound adapter class based on the EnsLib.TCP.OutboundAdapter or any of its subclasses. See the chapter“Creating Custom TCP Adapter Classes.”

4                                                                                                                                       Using TCP Adapters with Ensemble

Choosing a TCP Adapter

Page 11: Using TCP Adapters with Ensemble

2Using the TCP Counted Inbound Adapter

EnsLib.TCP.CountedInboundAdapter is the adapter class to use for incoming TCP connections over which a TCP client andTCP listener exchange blocks of data, with the block length specified in the first 4 bytes of the block.EnsLib.TCP.CountedInboundAdapter uses the block length to acquire the meaningful portion of the data from the clientapplication. It then passes this data to the associated business service within Ensemble.

This chapter explains how to use the EnsLib.TCP.CountedInboundAdapter. It discusses the following topics:

• Background Information

• Using the Adapter

• Creating a New Business Service Class

• Sample Business Service Class Code

• Adapter Settings

2.1 Background InformationThe production configuration must include a business service, dedicated to the EnsLib.TCP.CountedInboundAdapter, thatknows how to receive and process the data that this adapter provides. In building your Ensemble production, you will eitherchoose or create a business service that works with the EnsLib.TCP.CountedInboundAdapter.

This business service decides what to do with the incoming data stream. Generally, the business service decides to issue amessage addressed to some Ensemble business process, with instructions to perform a task using some or all of the inputdata. The details are up to the business service.

If the data source expects an acknowledgment or response to its input, the business service is also responsible for formulatingthis response and relaying it back to the data source, via the EnsLib.TCP.CountedInboundAdapter. The adapter does notevaluate or supplement the response, but relays it, if it is provided.

You can simply set up the EnsLib.TCP.CountedInboundAdapter as instructed in the next section, “Using the Adapter.”However, you may want more details about how the adapter communicates with its configured business service. This sectionprovides those details.

Using TCP Adapters with Ensemble                                                                                                                                       5

Page 12: Using TCP Adapters with Ensemble

Figure 2–1: Using the TCP Counted Inbound Adapter and Business Service

The figure above shows the flow of a request from an external data source into Ensemble after you have set up an Ensemblebusiness service to work with an inbound adapter. This figure shows the ingoing data stream only; any response simplyretraces this path. The sequence is as follows:

1. At production startup, Ensemble creates a background process for each of the business services in the productionconfiguration. Ensemble can allocate more than one background process per business service. The business service’sconfigured PoolSize specifies the number of background processes.

2. Within each background process, Ensemble creates an instance of the business service class and an instance of itsassociated inbound adapter class.

3. Ensemble calls the OnInit() methods of the business service object and inbound adapter object, respectively.

4. Thereafter, whenever the production is running and the business service is enabled and scheduled to be active, thefollowing cycle can occur:

• Each time the adapter encounters input from its configured data source, it calls the Ensemble framework’sProcessInput() method.

• The call to ProcessInput() automatically prompts the Ensemble framework to call the associated business service’sOnProcessInput() method.

• Code within OnProcessInput() determines what to do with the incoming data stream. For example, if anEnsemble business process needs to be started, the business service formulates an Ensemble request message andissues the synchronous or asynchronous call that starts the business process.

If the data source expects an acknowledgment or response of some kind, it is the business service’sOnProcessInput() that constructs it. The inbound adapter simply relays this response back to the external datasource.

Note: There is no default implementation of OnProcessInput(). The developer of each business service classis responsible for writing an OnProcessInput() method for that class. For instructions, see the nextsection, “Using the Adapter.”

6                                                                                                                                       Using TCP Adapters with Ensemble

Using the TCP Counted Inbound Adapter

Page 13: Using TCP Adapters with Ensemble

An Ensemble production continues running until it is stopped, either programmatically or by an administrator using theManagement Portal. When a production stops, the following events related to inbound adapters occur:

1. Ensemble disables each business service; no more incoming requests are accepted for this production.

2. The OnTearDown() method in each inbound adapter is called.

3. All inbound adapter and business service objects are destroyed and their background processes are killed.

4. Each business service’s OnProductionStop class method is called, once for each configured item of that class in theproduction.

When a business service is disabled by a system administrator, or becomes inactive according to its configured schedule,the production continues to run but the associated inbound adapter is shut down, and its OnTearDown() method is executed,as described above.

2.2 Using the AdapterOnce you determine that your production needs the EnsLib.TCP.CountedInboundAdapter, you can include it in the productionconfiguration as follows:

1. Choose or create a business service class that uses the EnsLib.TCP.CountedInboundAdapter.

2. If you create a new business service class, be sure to:

• Implement its OnProcessInput() method.

• Compile the class.

3. Configure the production. Add a business service of the chosen class.

4. Configure the new business service. To do so, click it and specify values for the settings on the right.

To enable it, select the Enabled box.

The next sections provide details.

2.3 Creating a New Business Service ClassThe simplest way to deploy the EnsLib.TCP.CountedInboundAdapter is to choose an existing business service class thatalready uses it.

If no existing class has the functionality you need, create a business service class that uses theEnsLib.TCP.CountedInboundAdapter. Create the new class in Studio as follows:

1. From the File menu, choose New. A dialog pops up. Edit it as follows:

• Click on the Production tab.

• Select the Business Service icon and click OK.

• Enter a package and class name and click Next.

Important: Be sure to avoid reserved package names; see “Reserved Package Names” in DevelopingEnsemble Productions.

Using TCP Adapters with Ensemble                                                                                                                                       7

Using the Adapter

Page 14: Using TCP Adapters with Ensemble

• Choose EnsLib.TCP.CountedInboundAdapter from the drop-down list.

• Click Finish.

The result is a template class like the following:

Class Dev.Test.NewService1 Extends Ens.BusinessService [ ProcedureBlock ]{Parameter ADAPTER = "EnsLib.TCP.CountedInboundAdapter";

Method OnProcessInput(pInput As %RegisteredObject, pOutput As %RegisteredObject) As %Status{ Quit $$$ERROR($$$NotImplemented)}}

2. Implement the OnProcessInput() method in your new business service class. This is the method that uses the inputdata gathered by the EnsLib.TCP.CountedInboundAdapter.

You can implement the OnProcessInput() method by replacing the following line in the template class with your owncode:

Quit $$$ERROR($$$NotImplemented)

Your OnProcessInput() method must know the types of incoming and outgoing data for communicating with theEnsLib.TCP.CountedInboundAdapter. However, the New Business Service Wizard specifies both types in theOnProcessInput() method signature as the generic object type %RegisteredObject.

InterSystems suggests that, as your first action in coding the new business service, you change each OnProcessInput()argument to its specific type passed from the adapter:

Method OnProcessInput(pInput As %Library.GlobalCharacterStream, Output pOutput As %Library.AbstractStream) As %Status

Where:

• pInput is of type %Library.GlobalCharacterStream and contains the incoming data stream that the TCP client hasdirected to the adapter.

• pOutput is of type %Library.AbstractStream and contains any response that the business service might provide tothe TCP client.

Keep in mind that the method must quit by returning a %Status object. See the code sample in the next section,“Sample Business Service Class Code.”

3. Optionally, you may implement the OnConnect() callback method in your business service class.

OnConnect() is available for a TCP inbound adapter to call back to its associated business service. If present in thebusiness service, this method is called each time the TCP inbound adapter establishes a new connection to or from aremote system.

If you add an OnConnect() method to your business service class, it must have the following signature:

Method OnConnect(pTimeout As %Numeric) As %Status

Implement an OnConnect() method in your business service if you need to take some action each time a new connectionis established, for example to send a logon sequence or a handshake token. The timeout argument is automaticallyprovided by the TCP inbound adapter. It takes its value from the ReadTimeout adapter setting. For details aboutReadTimeout, see “Adapter Settings.”

Returning an error status from OnConnect() causes the new connection to fail and be disconnected. If an untrappedexception occurs within OnConnect(), the adapter catches it and continues as if OnConnect() were not implemented.

8                                                                                                                                       Using TCP Adapters with Ensemble

Using the TCP Counted Inbound Adapter

Page 15: Using TCP Adapters with Ensemble

4. Compile your new business service class. Compiling also saves it.

5. After creating and compiling the business service class in Studio, add an instance of the business service to the productionand configure it using the Management Portal. See the appendix “Common Tasks in the Management Portal.”

When you configure the adapter, you specify a value for the AllowedIPAddresses settings, along other settings. Notethat AllowedIPAddresses provides a way to enable the adapter to initiate the connection; see “Adapter Settings.”

2.4 Sample Business Service Class CodeThe following is an example of a business service class that references the EnsLib.TCP.CountedInboundAdapter.

Class Test.HL7v3.InterfaceEngine.Service.HL7TCPIn Extends Ens.BusinessService [ ProcedureBlock ]{

Parameter ADAPTER = "EnsLib.TCP.CountedInboundAdapter";

Parameter SINGLEPOOLJOB = 1;

Parameter SETTINGS = "TargetConfigNames";

/// Configuration item to which to send messages Property TargetConfigNames As %String;

Method OnProcessInput(pInput As %GlobalCharacterStream, pOutput As %RegisteredObject) As %Status { Set $ZTrap = "OnProcessInputET"

Set tRequest = ##class(Test.HL7v3.InterfaceEngine.Request.Message).%New() Set tRequest.Stream = pInput Set tRequest.DocType = $Case(pInput.Size < 10000, 1:"MCOA", :"CDAR2")

If (..TargetConfigNames '= "") { For tCount = 1:1:$Length(..TargetConfigNames, ",") { Set tTarget = $ZStrip($Piece(..TargetConfigNames, ",", tCount), "<>W") Set tStatus = ..SendRequestAsync(tTarget, tRequest) } }

Quit $$$OK

OnProcessInputET Set $ZTrap = "" Quit $$$ERROR($$$GeneralError,"Error in OnProcessInput: "_$ZError) }

/// Return an array of connections for /// drawing lines on the config diagram ClassMethod OnGetConnections(Output pArray As %String, item As Ens.Config.Item) { Set (tValue,tIndex)="" For { Set tIndex = item.Settings.Next(tIndex) Quit:tIndex="" Set tSetting = item.Settings.GetAt(tIndex) If tSetting.Name="TargetConfigNames" Set tValue=tSetting.Value } For i=1:1:$L(tValue,",") { Set tOne=$P(tValue,",",i) Continue:""=tOne Set pArray(tOne)="" } Quit }}

Using TCP Adapters with Ensemble                                                                                                                                       9

Sample Business Service Class Code

Page 16: Using TCP Adapters with Ensemble

2.5 Adapter SettingsThis topic describes the settings that are specific to the EnsLib.TCP.CountedInboundAdapter associated with the businessservice. For settings not listed here, see “Business Service Settings” in the chapter “Configuration” in ManagingEnsemble Productions.

AllowedIPAddresses

A comma-separated list of remote IP addresses from which to accept connections. The adapter accepts named IPaddresses, IPV4 addresses, or IPV6 addresses. An optional :port designation is supported; so, for example, bothof the following address formats are acceptable: 192.168.1.22 or 192.168.1.22:3298.

If a port number is specified, connections from other ports will be refused.

If the string starts with a ! character, the adapter initiates a connection to the specified address. In this case, onlyone address may be given, and if a port is specified, it supersedes the value of the Port setting; otherwise, the Port

setting is used.

CallInterval

Number of seconds that the adapter will listen for incoming data from its configured source, before checking fora shutdown signal from the Ensemble framework.

If the adapter finds input, it acquires the data and passes it to the business service. The business service processesthe data, and then the adapter immediately begins waiting for new input. This cycle continues whenever the pro-duction is running and the business service is enabled and scheduled to be active.

The default CallInterval is 5 seconds. The minimum is 0.1 seconds.

Charset

Specifies the text character set to use to translate characters for the input file. The string is not case-sensitive. Thedefault is Binary. Use Binary for binary files, or for any data in which newline and linefeed characters aredistinct or must remain unchanged, for example in HL7 Version 2 or EDI messages. Other settings may be usefulwhen transferring text documents. Choices include:

• Binary — Binary transfer (the default)

• Ascii — Ascii mode FTP transfer but no character encoding translation

• Default — The default character encoding of the local Ensemble server

• Latin1 — The ISO Latin1 8-bit encoding

• ISO-8859-1 — The ISO Latin1 8-bit encoding

• UTF-8 — The Unicode 8-bit encoding

• UCS2 — The Unicode 16-bit encoding

• UCS2-BE — The Unicode 16-bit encoding (Big-Endian)

• Any other alias from an international character encoding standard for which NLS (National Language Support)is installed in Ensemble.

10                                                                                                                                     Using TCP Adapters with Ensemble

Using the TCP Counted Inbound Adapter

Page 17: Using TCP Adapters with Ensemble

Endian

A choice of Big or Little indicates the byte order of the 4-byte block count prefix. Big endian means the mostsignificant byte (MSB) goes over the wire first; Little endian means the least significant byte (LSB) goes overthe wire first. The default value for this string is Big.

JobPerConnection

When True, the adapter spawns a new job to handle each incoming TCP connection and allows simultaneoushandling of multiple connections. When False, it does not spawn a new job for each connection. False is usuallythe appropriate choice for HL7 or X12 connections. The default is True.

For TCP services, JobPerConnection causes each new incoming socket connection to be handled by a freshlyspawned job rather than by the listener job itself. Only one job at a time can be the listener, and one job must bethe listener, so TCP services configured with PoolSize greater than 1 still only start one listener job. However, thislistener can spawn an unlimited number of connection jobs if JobPerConnection is set to True. This release ofEnsemble makes the PoolSize setting, if configured to a value greater than 1, serve as a limit on the number ofsimultaneous connection jobs that can exist. When this limit is reached, the listener does not accept any moreconnections until one or more of the existing connection jobs quits or dies. An Event Log warning appears whenit first reaches the limit.

LocalInterface

Specifies the network interface through which the TCP connection should go. Select a value from the list or typea value. An empty value means use any interface.

Port

Identifies the TCP port to connect to. TCP port numbers have a maximum value of 65535.

QSize

How many incoming connections the operating system should hold in reserve on behalf of this business service.Set to 0 if only 1 connection at a time is expected. Set to a large number if many clients will connecting rapidly.The default is 100. The range is 0–1000.

ReadTimeout

Number of seconds to wait for each successive incoming TCP read operation, following receipt of initial datafrom the remote TCP port. The default is 5 seconds. The range is 0–600 seconds (a maximum of 10 minutes).

SSLConfig

The name of an existing Secure Socket Layer (SSL) or Transport Layer Security (TLS) configuration to use toauthenticate this connection.

You can create and manage SSL/TLS configurations using the Management Portal. See the “Using SSL/TLS withCaché” chapter in the Caché Security Administration Guide.

The first field on the Edit SSL/TLS Configuration form is Configuration Name. This is the string to use in the adapter’sSSLConfig field. The SSLConfig string may also add a | (vertical bar) character followed by the private keypassword. The | character is unique because it is not allowed as part of a Configuration Name.

StayConnected

If StayConnected is a positive value, the adapter stays connected to the remote system for this number of secondsbetween input events. A zero value means to disconnect immediately after every input event. The default of –1means to stay permanently connected, even during idle times. Adapters are assumed idle at startup and thereforeonly auto-connect if they are configured with a StayConnected value of –1.

Using TCP Adapters with Ensemble                                                                                                                                     11

Adapter Settings

Page 18: Using TCP Adapters with Ensemble
Page 19: Using TCP Adapters with Ensemble

3Using the TCP Counted Outbound Adapter

EnsLib.TCP.CountedOutboundAdapter contains methods that an Ensemble business operation can call to read or write blocksof data across the TCP connection. Ensemble acts as a TCP client exchanging blocks of data with a TCP listener. The blocklength specified in the first 4 bytes of the block. This convention allows an Ensemble business operation to send requeststo an external TCP server for fulfillment. The adapter makes no decisions about the data it relays out to the external system.It simply maps the request from the business operation to a format that is acceptable to the external system.

This chapter explains how to use the EnsLib.TCP.CountedOutboundAdapter. It discusses the following topics:

• Background Information

• Using the Adapter

• Creating a New Business Operation Class

• Sample Business Operation Class Code

• Available Helper Methods

• Adapter Settings

3.1 Background InformationYou can simply set up the EnsLib.TCP.CountedOutboundAdapter as instructed in the next section, “Using the Adapter.”However, some developers want more details about how a business operation communicates with its configured adapter.This section provides those details.

Using TCP Adapters with Ensemble                                                                                                                                     13

Page 20: Using TCP Adapters with Ensemble

Figure 3–1: Business Operation and Using the TCP Counted Outbound Adapter

The figure above shows the flow of a request from Ensemble out to an external system after you have set up an Ensemblebusiness operation to work with an outbound adapter. The sequence is as follows:

1. At production startup, Ensemble creates a background process for each business operation in the production configu-ration. Ensemble can allocate more than one background process per business operation. The business operation’sconfigured PoolSize specifies the number of background processes.

2. Within each background process, Ensemble creates an instance of the business operation class and an instance of itsassociated outbound adapter class.

3. Ensemble calls the OnInit() methods of the business operation object and outbound adapter object, respectively.

4. Thereafter, whenever the production is running and the business operation is enabled and scheduled to be active, thefollowing sequence can occur:

• The business operation receives an Ensemble request message.

• The business operation’s message map matches the Ensemble request type with a business operation method.

Note: The developer of each business operation class is responsible for writing its message map and methods.For instructions, see the next section, “Using the Adapter.”

• The business operation method calls a method in the associated outbound adapter object.

• The adapter method sends a request to the external system. If this request generates an acknowledgment or responseof some kind, the outbound adapter relays that data back to the business operation method that invoked it.

• If the original Ensemble request message requires a response, the business operation returns it.

14                                                                                                                                     Using TCP Adapters with Ensemble

Using the TCP Counted Outbound Adapter

Page 21: Using TCP Adapters with Ensemble

An Ensemble production continues running until it is stopped, either programmatically or by an administrator using theManagement Portal. When a production stops, the following events related to outbound adapters occur:

1. Ensemble waits for each business operation to reach a quiescent state (that is, Ensemble waits until each businessoperation has completed all of its synchronous requests).

2. The OnTearDown() method in each outbound adapter is called.

3. All outbound adapter and business operation objects are destroyed and their background processes are killed.

4. Each business operation’s OnProductionStop class method is called, once for each configured item of that class inthe production.

When a business operation is disabled by a system administrator, or becomes inactive according to its configured schedule,the production continues to run but the associated outbound adapter is shut down, and its OnTearDown() method is executed,as described above.

3.2 Using the AdapterOnce you determine that your production needs the EnsLib.TCP.CountedOutboundAdapter, you can include it in the productionconfiguration as follows:

1. Choose or create a business operation class that uses the EnsLib.TCP.CountedOutboundAdapter.

2. If you create a new business operation class, be sure to:

• Add at least one method to the method map.

• Implement each method in the method map.

• Write the business operation methods so that they call methods from the EnsLib.TCP.CountedOutboundAdapter

class.

• Compile the new class.

3. Configure the production. Add a business operation of the chosen class.

4. Configure the new business operation. To do so, click it and specify values for the settings on the right.

To enable it, select the Enabled box.

The next sections provide details.

3.3 Creating a New Business Operation ClassThe simplest way to deploy the EnsLib.TCP.CountedOutboundAdapter is to choose an existing business operation class thatalready uses it.

If no existing class has the functionality you need, create a business operation class that uses theEnsLib.TCP.CountedOutboundAdapter. Create the new class in Studio as follows:

1. From the File menu, choose New. A dialog pops up. Edit it as follows:

• Click on the Production tab.

• Select the Business Operation icon and click OK.

Using TCP Adapters with Ensemble                                                                                                                                     15

Using the Adapter

Page 22: Using TCP Adapters with Ensemble

• Enter a package and class name and click Next.

Important: Be sure to avoid reserved package names; see “Reserved Package Names” in DevelopingEnsemble Productions.

• Choose EnsLib.TCP.CountedOutboundAdapter from the drop-down list of adapter classes.

• Choose the default invocation style Queue. The alternative is InProc, but generally you want Queue. The differencesare as follows:

– Queue means the message is created within one background job and placed on a queue, at which time theoriginal job is released. Later, when the message is processed, a different background job will be allocatedfor the task.

– InProc means the message will be formulated, sent, and delivered in the same job in which it was created.The job will not be released to the sender’s pool until the message is delivered to the target. This is onlysuitable for special cases.

• Add at least one entry to the method map as follows:

–Click the Add icon.

– Enter the method name.

– Choose a request type and a response type.

– Click OK.

Repeat these steps as needed to add entries to the method map.

• Click Finish.

The result is a template class like the following:

Class Dev.Test.NewOperation1 Extends Ens.BusinessOperation [ ProcedureBlock ]{

Parameter ADAPTER = "EnsLib.TCP.CountedOutboundAdapter";

Parameter INVOCATION = "Queue";

Method SampleCall(pRequest As Ens.Request, Output pResponse As Ens.Response) As %Status{ Quit $$$ERROR($$$NotImplemented)}

XData MessageMap{<MapItems> <MapItem MessageType="Ens.Request"> <Method>SampleCall</Method> </MapItem></MapItems>}

}

2. Implement the method(s) in your new business operation class.

Where the following line appears, replace it with your own code:

Quit $$$ERROR($$$NotImplemented)

Keep in mind that the method must quit by returning a %Status object. See the code sample in the next section,“Sample Business Operation Class Code.”

16                                                                                                                                     Using TCP Adapters with Ensemble

Using the TCP Counted Outbound Adapter

Page 23: Using TCP Adapters with Ensemble

3. When you want to call one of the methods in EnsLib.TCP.CountedOutboundAdapter, use the Adapter property to identifythe adapter object. The following example calls the EnsLib.TCP.CountedOutboundAdapter method WriteCountedStreamfrom a business operation method:

Set tSC=..Adapter.WriteCountedStream(myAbstractStream)

You can use similar syntax to call any of the EnsLib.TCP.CountedOutboundAdapter methods described in “AvailableHelper Methods. ”

4. Optionally, you may implement the OnConnect() callback method in your business operation class.

OnConnect() is available for a TCP outbound adapter to call back to its associated business operation. If present inthe business operation, this method is called each time the TCP outbound adapter establishes a new connection to orfrom a remote system.

If you add an OnConnect() method to your business operation class, it must have the following signature:

Method OnConnect(pTimeout As %Numeric) As %Status

Implement an OnConnect() method in your business operation if you need to take some action each time a new con-nection is established, for example to send a logon sequence or a handshake token. The timeout argument is automaticallyprovided by the TCP outbound adapter. It takes its value from the ConnectTimeout adapter setting. For details, see“Adapter Settings.”

Returning an error status from OnConnect() causes the new connection to fail and be disconnected. If an untrappedexception occurs within OnConnect(), the adapter catches it and continues as if OnConnect() were not implemented.

5. Compile your new business operation class. Compiling also saves it.

6. After creating and compiling the business operation class in Studio, add an instance of the business operation to theproduction and configure it using the Management Portal. See the appendix “Common Tasks in the ManagementPortal.”

3.4 Sample Business Operation Class CodeThe following is an example of a business operation class that references the EnsLib.TCP.CountedOutboundAdapter.

Class Test.GeneralTCPOperation Extends Ens.BusinessOperation [ ProcedureBlock ]{ Parameter ADAPTER = "EnsLib.TCP.CountedOutboundAdapter"; Parameter MAXREAD=30000;

Method OnMessage(pReq As Test.GeneralSendRequest, Output pResponse As Test.GeneralSendResponse) As %Status { Set str= pRq.Hr_pRq.DataLth_pRq.BID_pRq.Hr2_pRq.HrVacant_pRq.Cat_pRq.Hr3_pRq.Hr4 Set tTextStream= ##class(%GlobalCharacterStream).%New() Set tSC=tTextStream.Write(str) Do pReq.Body2.Read(32) // Throw it away Set len=..#MAXREAD Set token= pReq.Body2.Read(.len) Set i=0 While(len>0) { Set i=i+1 Do tTextStream.Write(token) Set len=..#MAXREAD Set token= pReq.Body2.Read(.len) } Set tSC= ..Adapter.SendMessageStream(tTextStream,.tStreamReply) Quit:$$$ISERR(tSC) tSC Set pResponse=##class(Test.GeneralSendResponse).%New() Do tStreamReply.Rewind() Set pResponse.Body = tStreamReply.Read(,.tSC)

Using TCP Adapters with Ensemble                                                                                                                                     17

Sample Business Operation Class Code

Page 24: Using TCP Adapters with Ensemble

Quit tSC }}

3.5 Available Helper MethodsWhen your business operation class references the EnsLib.TCP.CountedOutboundAdapter, the following adapter methodsbecome available. You can call these adapter methods from the methods in your business operation class using the Adapter

property as described in the previous section:

Connect()

Method Connect(pTimeout As %Numeric) As %Status

Connect() opens a TCP socket to a port on the TCP listener machine. Connect() has one input argument, a%Numeric value that identifies the number of seconds to wait for the connection attempt to succeed. A typical callto the Connect() method gives this input argument the value of the configurable ConnectTimeout property.

If the StayConnected adapter setting is set to –1, the Ensemble framework will create the connection automaticallyat startup time, from within the OnInit() method.

Disconnect()

Method Disconnect()

Disconnect() takes down the connection to the TCP listener.

SendMessageStream()

Method SendMessageStream(pRequestStream As %Stream.Object, ByRef pResponseStream As %CharacterStream = "%GlobalCharacterStream") As %Status

SendMessageStream() sends the stream contents as a counted block on the TCP socket.

SendMessageString()

Method SendMessageString(pRequestString As %String, Output pResponseString As %String) As %Status

SendMessageString() sends the string contents as a counted block on the TCP socket.

TestConnection()

Method TestConnection()

TestConnection() corrects the properties reflecting the connection state. If the adapter is connected,TestConnection() returns True. If not, TestConnection() calls Disconnect() and returns False.

3.6 Adapter SettingsThis topic describes the settings that are specific to the EnsLib.TCP.CountedOutboundAdapter associated with the businessoperation. For settings not listed here, see “Business Operation Settings” in the chapter “Configuration” in ManagingEnsemble Productions.

18                                                                                                                                     Using TCP Adapters with Ensemble

Using the TCP Counted Outbound Adapter

Page 25: Using TCP Adapters with Ensemble

Charset

Specifies the text character set to use to translate characters for the input file. The string is not case-sensitive. Thedefault is Binary. Use Binary for binary files, or for any data in which newline and linefeed characters aredistinct or must remain unchanged, for example in HL7 Version 2 or EDI messages. Other settings may be usefulwhen transferring text documents. Choices include:

• Binary — Binary transfer (the default)

• Ascii — Ascii mode FTP transfer but no character encoding translation

• Default — The default character encoding of the local Ensemble server

• Latin1 — The ISO Latin1 8-bit encoding

• ISO-8859-1 — The ISO Latin1 8-bit encoding

• UTF-8 — The Unicode 8-bit encoding

• UCS2 — The Unicode 16-bit encoding

• UCS2-BE — The Unicode 16-bit encoding (Big-Endian)

• Any other alias from an international character encoding standard for which NLS (National Language Support)is installed in Ensemble.

ConnectTimeout

Number of seconds to wait on each attempt to connect to the remote TCP listener. The default is 5 seconds.

Endian

A choice of Big or Little indicates the byte order of the 4-byte block count prefix. Big endian means the mostsignificant byte (MSB) goes over the wire first; Little endian means the least significant byte (LSB) goes overthe wire first. The default value for this string is Big.

GetReply

If 1 (true) wait to read a reply message back from the socket before returning. If 0 (false) do not wait. The defaultvalue is 1.

IPAddress

IP address to make a TCP connection to. The adapter accepts a named IP address, an IPV4 address, or an IPV6address.

If the address starts with a ! character, the adapter waits for a connection from a remote system. In this case, followthe exclamation point with a comma-separated list of remote IP addresses from which to accept connections. Theadapter accepts named IP addresses, IPV4 addresses, or IPV6 addresses. An optional :port designation is supported;so, for example, both of the following address formats are acceptable: 192.168.1.22 or 192.168.1.22:3298.

If no IP address follows the ! character, any remote system may connect; otherwise only the listed IP addresses(and ports) are allowed to connect.

LocalInterface

Specifies the network interface through which the TCP connection should go. Select a value from the list or typea value. An empty value means use any interface.

Using TCP Adapters with Ensemble                                                                                                                                     19

Adapter Settings

Page 26: Using TCP Adapters with Ensemble

This setting allows you to specify that a virtual IP address should be used to send outbound traffic, which is usefulin the case of mirroring. If a remote application is configured to accept traffic from the virtual IP address, and boththe primary and the secondary use that IP address to connect to the remote application, then everything continuesto work when the secondary starts sending.

Port

Identifies the TCP port to connect to. TCP port numbers have a maximum value of 65535.

QSize

How many incoming connections the operating system should hold in reserve on behalf of this business operation.There is generally no reason to change the default value of 0. Either the connection is outbound, or the businessoperation is using '!' inbound mode, in which case only 1 client is allowed at a time, per business operation pooljob.

ReadTimeout

Number of seconds to wait for each successive incoming TCP read operation, following receipt of initial datafrom the remote TCP port. The default is 5 seconds. The range is 0–600 seconds (a maximum of 10 minutes).

ReconnectRetry

Number of retries at which to drop the connection and try reconnecting again. A value of 0 (zero) means neverdisconnect. The default value is 5.

ResponseTimeout

Number of seconds to wait for a response to begin arriving back from the remote system after sending a request.The default is 15 seconds.

SSLConfig

The name of an existing Secure Socket Layer (SSL) or Transport Layer Security (TLS) configuration to use toauthenticate this connection.

You can create and manage SSL/TLS configurations using the Management Portal. See the “Using SSL/TLS withCaché” chapter in the Caché Security Administration Guide.

The first field on the Edit SSL/TLS Configuration form is Configuration Name. This is the string to use in the adapter’sSSLConfig field. The SSLConfig string may also add a | (vertical bar) character followed by the private keypassword. The | character is unique because it is not allowed as part of a Configuration Name.

StayConnected

If StayConnected is a positive value, the adapter stays connected to the remote system for this number of secondsafter completing an operation. A zero value means to disconnect immediately after every operation. The defaultof –1 means to stay permanently connected, even during idle times. Adapters are assumed idle at startup andtherefore only auto-connect if they are configured with a StayConnected value of –1.

20                                                                                                                                     Using TCP Adapters with Ensemble

Using the TCP Counted Outbound Adapter

Page 27: Using TCP Adapters with Ensemble

4Using the TCP Counted XML InboundAdapter

The EnsLib.TCP.CountedXMLInboundAdapter acts as a TCP listener for an XTE server. The adapter receives XML data incounted TCP format and imports the XML data into Ensemble. The result is an instantiated Ensemble object.

This chapter explains how to use the EnsLib.TCP.CountedXMLInboundAdapter. It discusses the following topics:

• Background Information

• Using the Adapter

• Creating a New Business Service Class

• Adapter Settings

4.1 Background InformationYou can simply set up the EnsLib.TCP.CountedXMLInboundAdapter as instructed in the next section, “Using the Adapter.”However, some developers want more details about how the adapter communicates with its configured business service.This section provides those details.

If you look at the EnsLib.TCP.CountedXMLInboundAdapter class code, you see that it contains a call to an Ensembleframework method called ProcessInput(). However, the code for the business service class provides a method calledOnProcessInput(). This section explains the relationship between the two methods. If you want to view Ensemble classcode, try the following:

• In Studio, from the Tools menu choose Class Browser. The Class Browser dialog displays. In the window at left, nav-igate the hierarchy to find the class of interest. In the window at right, display details about class members and theclass hierarchy by clicking the tabs along the lower edge of the display: All, Properties, Methods, Parameters, and soon.

• In Studio, from the Help menu choose On-line Documentation. The documentation home page displays. Scroll downand choose Class Reference Information. The Caché Class Reference home page displays. At top left, for Classes in

choose an Ensemble-enabled namespace. Navigate the hierarchy of package names to find the class of interest.

Using TCP Adapters with Ensemble                                                                                                                                     21

Page 28: Using TCP Adapters with Ensemble

Figure 4–1: Using the TCP Counted XML Inbound Adapter and Business Service

The figure above shows the flow of a request from an external data source into Ensemble after you have set up an Ensemblebusiness service to work with an inbound adapter. This figure shows the ingoing data stream only; any response simplyretraces this path. The sequence is as follows:

1. At production startup, Ensemble creates a background process for each of the business services in the productionconfiguration. Ensemble can allocate more than one background process per business service. The business service’sconfigured PoolSize specifies the number of background processes.

2. Within each background process, Ensemble creates an instance of the business service class and an instance of itsassociated inbound adapter class.

3. Ensemble calls the OnInit() methods of the business service object and inbound adapter object, respectively.

4. Thereafter, whenever the production is running and the business service is enabled and scheduled to be active, thefollowing cycle can occur:

• Each time the adapter encounters input from its configured data source, it calls the Ensemble framework’sProcessInput() method.

• The call to ProcessInput() automatically prompts the Ensemble framework to call the associated business service’sOnProcessInput() method.

• Code within OnProcessInput() determines what to do with the incoming data stream. For example, if anEnsemble business process needs to be started, the business service formulates an Ensemble request message andissues the synchronous or asynchronous call that starts the business process.

If the data source expects an acknowledgment or response of some kind, it is the business service’sOnProcessInput() that constructs it. The inbound adapter simply relays this response back to the external datasource.

Note: There is no default implementation of OnProcessInput(). The developer of each business service classis responsible for writing an OnProcessInput() method for that class. For instructions, see the nextsection, “Using the Adapter.”

22                                                                                                                                     Using TCP Adapters with Ensemble

Using the TCP Counted XML Inbound Adapter

Page 29: Using TCP Adapters with Ensemble

An Ensemble production continues running until it is stopped, either programmatically or by an administrator using theManagement Portal. When a production stops, the following events related to inbound adapters occur:

1. Ensemble disables each business service; no more incoming requests are accepted for this production.

2. The OnTearDown() method in each inbound adapter is called.

3. All inbound adapter and business service objects are destroyed and their background processes are killed.

4. Each business service’s OnProductionStop class method is called, once for each configured item of that class in theproduction.

When a business service is disabled by a system administrator, or becomes inactive according to its configured schedule,the production continues to run but the associated inbound adapter is shut down, and its OnTearDown() method is executed,as described above.

4.2 Using the AdapterOnce you determine that your production needs the EnsLib.TCP.CountedXMLInboundAdapter, you can include it in theproduction configuration as follows:

1. Choose or create a business service class that uses the EnsLib.TCP.CountedXMLInboundAdapter.

2. If you create a new business service class, be sure to:

• Implement its OnProcessInput() method.

• Compile the class.

3. Configure the production. Add a business service of the chosen class.

4. Configure the new business service. To do so, click it and specify values for the settings on the right.

To enable it, select the Enabled box.

The next sections provide details.

4.3 Creating a New Business Service ClassThe simplest way to deploy the EnsLib.TCP.CountedXMLInboundAdapter is to choose an existing business service classthat already uses it.

If no existing class has the functionality you need, create a business service class that uses theEnsLib.TCP.CountedXMLInboundAdapter. Create the new class in Studio as follows:

1. From the File menu, choose New. A dialog pops up. Edit it as follows:

• Click on the Production tab.

• Select the Business Service icon and click OK.

• Enter a package and class name and click Next.

Important: Be sure to avoid reserved package names; see “Reserved Package Names” in DevelopingEnsemble Productions.

Using TCP Adapters with Ensemble                                                                                                                                     23

Using the Adapter

Page 30: Using TCP Adapters with Ensemble

• Choose EnsLib.TCP.CountedXMLInboundAdapter from the drop-down list of adapter classes.

• Click Finish.

The result is a template class like the following:

Class Dev.Test.NewService1 Extends Ens.BusinessService [ ProcedureBlock ]{Parameter ADAPTER = "EnsLib.TCP.CountedXMLInboundAdapter";Method OnProcessInput(pInput As %RegisteredObject, pOutput As %RegisteredObject) As %Status{ Quit $$$ERROR($$$NotImplemented)}}

2. Implement the OnProcessInput() method in your new business service class. This is the method that uses the inputdata gathered by the EnsLib.TCP.CountedXMLInboundAdapter.

You can implement the OnProcessInput() method by replacing the following line in the template class with your owncode:

Quit $$$ERROR($$$NotImplemented)

Your OnProcessInput() method must know the types of incoming and outgoing data for communicating with theEnsLib.TCP.CountedXMLInboundAdapter. However, the New Business Service Wizard specifies both types in theOnProcessInput() method signature as the generic object type %RegisteredObject.

InterSystems suggests that, as your first action in coding the new business service, you change each OnProcessInput()argument to its specific type passed from the adapter:

Method OnProcessInput(pInput As %RegisteredObject, Output pOutput As %RegisteredObject) As %Status

Where:

• pInput is of type %RegisteredObject and can be any of the objects specified by the AcceptClassNames adaptersetting.

For details about AcceptClassNames, see “Adapter Settings.”

• pOutput is of type %RegisteredObject and contains any response that you might need to return to the XTE server.

Keep in mind that the method must quit by returning a %Status object.

3. Optionally, you may implement the OnConnect() callback method in your business service class.

OnConnect() is available for a TCP inbound adapter to call back to its associated business service. If present in thebusiness service, this method is called each time the TCP inbound adapter establishes a new connection to or from aremote system.

If you add an OnConnect() method to your business service class, it must have the following signature:

Method OnConnect(pTimeout As %Numeric) As %Status

Implement an OnConnect() method in your business service if you need to take some action each time a new connectionis established, for example to send a logon sequence or a handshake token. The timeout argument is automaticallyprovided by the TCP inbound adapter. It takes its value from the ReadTimeout adapter setting.

For details about ReadTimeout, see “Adapter Settings.”

Returning an error status from OnConnect() causes the new connection to fail and be disconnected. If an untrappedexception occurs within OnConnect(), the adapter catches it and continues as if OnConnect() were not implemented.

4. Compile your new business service class. Compiling also saves it.

24                                                                                                                                     Using TCP Adapters with Ensemble

Using the TCP Counted XML Inbound Adapter

Page 31: Using TCP Adapters with Ensemble

5. After creating and compiling the business service class in Studio, add an instance of the business service to the productionand configure it using the Management Portal. See the appendix “Common Tasks in the Management Portal.”

When you configure the adapter, you specify a value for the AllowedIPAddresses settings, along other settings. Notethat AllowedIPAddresses provides a way to enable the adapter to initiate the connection; see “Adapter Settings.”

4.4 Adapter SettingsThis topic describes the settings that are specific to the EnsLib.TCP.CountedXMLInboundAdapter associated with the businessservice. For settings not listed here, see “Business Service Settings” in the chapter “Configuration” in ManagingEnsemble Productions.

AcceptClassnames

Comma-separated list, giving the names of classes that this adapter will instantiate from XML blocks received.

AllowedIPAddresses

A comma-separated list of remote IP addresses from which to accept connections. The adapter accepts named IPaddresses, IPV4 addresses, or IPV6 addresses. An optional :port designation is supported; so, for example, bothof the following address formats are acceptable: 192.168.1.22 or 192.168.1.22:3298.

If the string starts with a !, the adapter will initiate a connection to the specified address. In this case only oneaddress may be given. If a port is included, it will supersede the value of the Port setting; otherwise the Port settingwill be used to connect to the remote system.

CallInterval

Number of seconds that the adapter will listen for incoming data from its configured source, before checking fora shutdown signal from the Ensemble framework.

If the adapter finds input, it acquires the data and passes it to the business service. The business service processesthe data, and then the adapter immediately begins waiting for new input. This cycle continues whenever the pro-duction is running and the business service is enabled and scheduled to be active.

The default CallInterval is 5 seconds. The minimum is 0.1 seconds.

Charset

Specifies the text character set to use to translate characters for the input file. The string is not case-sensitive. Thedefault is Binary. Use Binary for binary files, or for any data in which newline and linefeed characters aredistinct or must remain unchanged, for example in HL7 Version 2 or EDI messages. Other settings may be usefulwhen transferring text documents. Choices include:

• Binary — Binary transfer (the default)

• Ascii — Ascii mode FTP transfer but no character encoding translation

• Default — The default character encoding of the local Ensemble server

• Latin1 — The ISO Latin1 8-bit encoding

• ISO-8859-1 — The ISO Latin1 8-bit encoding

• UTF-8 — The Unicode 8-bit encoding

• UCS2 — The Unicode 16-bit encoding

Using TCP Adapters with Ensemble                                                                                                                                     25

Adapter Settings

Page 32: Using TCP Adapters with Ensemble

• UCS2-BE — The Unicode 16-bit encoding (Big-Endian)

• Any other alias from an international character encoding standard for which NLS (National Language Support)is installed in Ensemble.

Endian

A choice of Big or Little indicates the byte order of the 4-byte block count prefix. Big endian means the mostsignificant byte (MSB) goes over the wire first; Little endian means the least significant byte (LSB) goes overthe wire first. The default value for this string is Big.

JobPerConnection

When True, the adapter spawns a new job to handle each incoming TCP connection and allows simultaneoushandling of multiple connections. When False, it does not spawn a new job for each connection; False is usuallythe appropriate choice for HL7 or X12 connections. The default is True.

LocalInterface

Specifies the network interface through which the TCP connection should go. Select a value from the list or typea value. An empty value means use any interface.

Port

TCP Port to connect to.

QSize

How many incoming connections the operating system should hold in reserve on behalf of this business service.Set to 0 if only 1 connection at a time is expected. Set to a large number if many clients will connecting rapidly.The default is 100. The range is 0–1000.

StayConnected

If StayConnected is a positive value, the adapter stays connected to the remote system for this number of secondsbetween input events. A zero value means to disconnect immediately after every input event. The default of –1means to stay permanently connected, even during idle times. Adapters are assumed idle at startup and thereforeonly auto-connect if they are configured with a StayConnected value of –1.

ReadTimeout

Number of seconds to wait for each successive incoming TCP read, following receipt of initial data from remoteTCP port. The default value is 5. The range is from 0 to 600.

SSLConfig

The name of an existing Secure Socket Layer (SSL) or Transport Layer Security (TLS) configuration to use toauthenticate this connection.

You can create and manage SSL/TLS configurations using the Management Portal. See the “Using SSL/TLS withCaché” chapter in the Caché Security Administration Guide.

The first field on the Edit SSL/TLS Configuration form is Configuration Name. This is the string to use in the adapter’sSSLConfig field. The SSLConfig string may also add a | (vertical bar) character followed by the private keypassword. The | character is unique because it is not allowed as part of a Configuration Name.

26                                                                                                                                     Using TCP Adapters with Ensemble

Using the TCP Counted XML Inbound Adapter

Page 33: Using TCP Adapters with Ensemble

5Using the TCP Counted XML OutboundAdapter

EnsLib.TCP.CountedXMLOutboundAdapter is a TCP adapter that sends XML exported objects out as a counted block ofbytes over a TCP connection and imports a response object. The adapter makes no decisions about the data it relays out tothe external system. It simply maps the request from the business operation to a format that is acceptable to the externalsystem.

This chapter explains how to use the EnsLib.TCP.CountedXMLOutboundAdapter. It discusses the following topics:

• Background Information

• Using the Adapter

• Creating a New Business Operation Class

• Available Helper Methods

• Adapter Settings

5.1 Background InformationYou can simply set up the EnsLib.TCP.CountedXMLOutboundAdapter as instructed in the next section, “Using the Adapter.”However, some developers want more details about how a business operation communicates with its configured adapter.This section provides those details.

Using TCP Adapters with Ensemble                                                                                                                                     27

Page 34: Using TCP Adapters with Ensemble

Figure 5–1: Business Operation and Using the TCP Counted XML Outbound Adapter

The figure above shows the flow of a request from Ensemble out to an external system after you have set up a Ensemblebusiness operation to work with an outbound adapter. The sequence is as follows:

1. At production startup, Ensemble creates a background process for each of the business operations in the productionconfiguration. Ensemble can allocate more than one background process per business operation. The business operation’sconfigured PoolSize specifies the number of background processes.

2. Within each background process, Ensemble creates an instance of the business operation class and an instance of itsassociated outbound adapter class.

3. Ensemble calls the OnInit() methods of the business operation object and outbound adapter object, respectively.

4. Thereafter, whenever the production is running and the business operation is enabled and scheduled to be active, thefollowing sequence can occur:

• The business operation receives an Ensemble request message.

• The business operation’s message map matches the Ensemble request type with a business operation method.

Note: The developer of each business operation class is responsible for writing its message map and methods.For instructions, see the next section, “Using the Adapter.”

• The business operation method calls a method in the associated outbound adapter object.

• The adapter method sends a request to the external system. If this request generates an acknowledgment or responseof some kind, the outbound adapter relays that data back to the business operation method that invoked it.

• If the original Ensemble request message requires a response, the business operation returns it.

28                                                                                                                                     Using TCP Adapters with Ensemble

Using the TCP Counted XML Outbound Adapter

Page 35: Using TCP Adapters with Ensemble

An Ensemble production continues running until it is stopped, either programmatically or by an administrator using theManagement Portal. When a production stops, the following events related to outbound adapters occur:

1. Ensemble waits for each business operation to reach a quiescent state (that is, Ensemble waits until each businessoperation has completed all of its synchronous requests).

2. The OnTearDown() method in each outbound adapter is called.

3. All outbound adapter and business operation objects are destroyed and their background processes are killed.

4. Each business operation’s OnProductionStop class method is called, once for each configured item of that class inthe production.

When a business operation is disabled by a system administrator, or becomes inactive according to its configured schedule,the production continues to run but the associated outbound adapter is shut down, and its OnTearDown() method is executed,as described above.

5.2 Using the AdapterOnce you determine that your production needs the EnsLib.TCP.CountedXMLOutboundAdapter, you can include it in theproduction configuration as follows:

1. Choose or create a business operation class that uses the EnsLib.TCP.CountedXMLOutboundAdapter.

2. If you create a new business operation class, be sure to:

• Add at least one method to the method map.

• Implement each method in the method map.

• Write the business operation methods so that they call methods from the EnsLib.TCP.CountedXMLOutboundAdapter

class.

• Compile the new class.

3. Configure the production. Add a business operation of the chosen class.

4. Configure the new business operation. To do so, click it and specify values for the settings on the right.

To enable it, select the Enabled box.

The next sections provide details.

5.3 Creating a New Business Operation ClassThe simplest way to deploy the EnsLib.TCP.CountedXMLOutboundAdapter is to choose an existing business operation classthat already uses it.

If no existing class has the functionality you need, create a business operation class that uses theEnsLib.TCP.CountedXMLOutboundAdapter. Create the new class in Studio as follows:

1. From the File menu, choose New. A dialog pops up. Edit it as follows:

• Click on the Production tab.

• Select the Business Operation icon and click OK.

Using TCP Adapters with Ensemble                                                                                                                                     29

Using the Adapter

Page 36: Using TCP Adapters with Ensemble

• Enter a package and class name and click Next.

Important: Be sure to avoid reserved package names; see “Reserved Package Names” in DevelopingEnsemble Productions.

• Choose EnsLib.TCP.CountedXMLOutboundAdapter from the drop-down list of adapter classes.

• Choose the default invocation style Queue. The alternative is InProc, but generally you want Queue. The differencesare as follows:

– Queue means the message is created within one background job and placed on a queue, at which time theoriginal job is released. Later, when the message is processed, a different background job will be allocatedfor the task.

– InProc means the message will be formulated, sent, and delivered in the same job in which it was created.The job will not be released to the sender’s pool until the message is delivered to the target. This is onlysuitable for special cases.

• Add at least one entry to the method map as follows:

–Click the Add icon.

– Enter the method name.

– Choose a request type and a response type.

– Click OK.

Repeat these steps as needed to add entries to the method map.

• Click Finish.

The result is a template class like the following:

Class Dev.Test.NewOperation1 Extends Ens.BusinessOperation [ ProcedureBlock ]{Parameter ADAPTER = "EnsLib.TCP.CountedXMLOutboundAdapter";Parameter INVOCATION = "Queue";Method SampleCall(pRequest As Ens.Request, Output pResponse As Ens.Response) As %Status{ Quit $$$ERROR($$$NotImplemented)}XData MessageMap{<MapItems> <MapItem MessageType="Ens.Request"> <Method>SampleCall</Method> </MapItem></MapItems>}}

2. Implement the method(s) in your new business operation class.

Where the following line appears, replace it with your own code:

Quit $$$ERROR($$$NotImplemented)

Keep in mind that the method must quit by returning a %Status object.

3. When you want to call one of the methods in EnsLib.TCP.CountedXMLOutboundAdapter, use the Adapter property toidentify the adapter object, with dot syntax to refer to the adapter method. See “Available Helper Methods.”

4. Optionally, you may implement the OnConnect() callback method in your business operation class.

30                                                                                                                                     Using TCP Adapters with Ensemble

Using the TCP Counted XML Outbound Adapter

Page 37: Using TCP Adapters with Ensemble

OnConnect() is available for a TCP outbound adapter to call back to its associated business operation. If present inthe business operation, this method is called each time the TCP outbound adapter establishes a new connection to orfrom a remote system.

If you add an OnConnect() method to your business operation class, it must have the following signature:

Method OnConnect(pTimeout As %Numeric) As %Status

Implement an OnConnect() method in your business operation if you need to take some action each time a new con-nection is established, for example to send a logon sequence or a handshake token. The timeout argument is automaticallyprovided by the TCP outbound adapter. It takes its value from the ConnectTimeout adapter setting. For details, see“Adapter Settings.”

Returning an error status from OnConnect() causes the new connection to fail and be disconnected. If an untrappedexception occurs within OnConnect(), the adapter catches it and continues as if OnConnect() were not implemented.

5. Compile your new business operation class. Compiling also saves it.

6. After creating and compiling the business operation class in Studio, add an instance of the business operation to theproduction and configure it using the Management Portal. See the appendix “Common Tasks in the ManagementPortal.”

5.4 Available Helper MethodsWhen your business operation class references the EnsLib.TCP.CountedXMLOutboundAdapter, the following adaptermethods become available. You can call these adapter methods from the methods in your business operation class usingthe Adapter property as described in the previous section:

Connect()

Method Connect(pTimeout As %Numeric) As %Status

Connect() opens a TCP socket to a port on the TCP listener machine. Connect() has one input argument, a%Numeric value that identifies the number of seconds to wait for the connection attempt to succeed. A typical callto the Connect() method gives this input argument the value of the configurable ConnectTimeout property.

If the StayConnected adapter setting is set to –1, the Ensemble framework will create the connection automaticallyat startup time, from within the OnInit() method.

Disconnect()

Method Disconnect()

Disconnect() takes down the connection to the TCP listener.

SendMessageXMLObj()

Method SendMessageXMLObj(pRequest As %RegisteredObject, Output pResponse As %RegisteredObject) As %Status

SendMessageXMLObj() sends the request object to the TCP listener as a counted XML block. If the GetReply

adapter setting is True, SendMessageXMLObj() also gets a reply from the TCP listener as a counted XML block,which it imports as an Ensemble object.

Using TCP Adapters with Ensemble                                                                                                                                     31

Available Helper Methods

Page 38: Using TCP Adapters with Ensemble

TestConnection()

Method TestConnection()

TestConnection() corrects the properties reflecting the connection state. If the adapter is connected,TestConnection() returns True. If not, TestConnection() calls Disconnect() and returns False.

5.5 Adapter SettingsThis topic describes the settings that are specific to the EnsLib.TCP.CountedXMLOutboundAdapter associated with thebusiness operation. For settings not listed here, see “Business Operation Settings” in the chapter “Configuration” inManaging Ensemble Productions.

Charset

Specifies the text character set to use to translate characters for the input file. The string is not case-sensitive. Thedefault is Binary. Use Binary for binary files, or for any data in which newline and linefeed characters aredistinct or must remain unchanged, for example in HL7 Version 2 or EDI messages. Other settings may be usefulwhen transferring text documents. Choices include:

• Binary — Binary transfer (the default)

• Ascii — Ascii mode FTP transfer but no character encoding translation

• Default — The default character encoding of the local Ensemble server

• Latin1 — The ISO Latin1 8-bit encoding

• ISO-8859-1 — The ISO Latin1 8-bit encoding

• UTF-8 — The Unicode 8-bit encoding

• UCS2 — The Unicode 16-bit encoding

• UCS2-BE — The Unicode 16-bit encoding (Big-Endian)

• Any other alias from an international character encoding standard for which NLS (National Language Support)is installed in Ensemble.

ConnectTimeout

Number of seconds to wait on each connection attempt. The default value is 5.

Endian

A choice of Big or Little indicates the byte order of the 4-byte block count prefix. Big endian means the mostsignificant byte (MSB) goes over the wire first; Little endian means the least significant byte (LSB) goes overthe wire first. The default value for this string is Big.

IPAddress

IP address to make a TCP connection to. The adapter accepts a named IP address, an IPV4 address, or an IPV6address.

If the address starts with a ! character, the adapter waits for a connection from a remote system. In this case, followthe exclamation point with a comma-separated list of remote IP addresses from which to accept connections. Theadapter accepts named IP addresses, IPV4 addresses, or IPV6 addresses. An optional :port designation is supported;so, for example, both of the following address formats are acceptable: 192.168.1.22 or 192.168.1.22:3298.

32                                                                                                                                     Using TCP Adapters with Ensemble

Using the TCP Counted XML Outbound Adapter

Page 39: Using TCP Adapters with Ensemble

If no IP address follows the ! character, any remote system may connect; otherwise only the listed IP addresses(and ports) are allowed to connect.

GetReply

If 1 (true) wait to read a reply message back from the socket before returning. If 0 (false) do not wait. The defaultvalue is 1.

LocalInterface

Specifies the network interface through which the TCP connection should go. Select a value from the list or typea value. An empty value means use any interface.

This setting allows you to specify that a virtual IP address should be used to send outbound traffic, which is usefulin the case of mirroring. If a remote application is configured to accept traffic from the virtual IP address, and boththe primary and the secondary use that IP address to connect to the remote application, then everything continuesto work when the secondary starts sending.

Port

TCP port to connect to.

QSize

How many incoming connections the operating system should hold in reserve on behalf of this business operation.There is generally no reason to change the default value of 0. Either the connection is outbound, or the businessoperation is using '!' inbound mode, in which case only 1 client is allowed at a time, per business operation pooljob.

ReadTimeout

Number of seconds to wait for each successive incoming TCP read, following receipt of initial data from remoteTCP port. The default value is 5. The range is from 0 to 600.

ReconnectRetry

Number of retries at which to drop the connection and try reconnecting again. A value of 0 (zero) means neverdisconnect. The default value is 5.

ResponseTimeout

Number of seconds to wait for a response to begin arriving back from the remote system after sending a request.The default value is 15.

SSLConfig

The name of an existing Secure Socket Layer (SSL) or Transport Layer Security (TLS) configuration to use toauthenticate this connection.

You can create and manage SSL/TLS configurations using the Management Portal. See the “Using SSL/TLS withCaché” chapter in the Caché Security Administration Guide.

The first field on the Edit SSL/TLS Configuration form is Configuration Name. This is the string to use in the adapter’sSSLConfig field. The SSLConfig string may also add a | (vertical bar) character followed by the private keypassword. The | character is unique because it is not allowed as part of a Configuration Name.

Using TCP Adapters with Ensemble                                                                                                                                     33

Adapter Settings

Page 40: Using TCP Adapters with Ensemble

StayConnected

If StayConnected is a positive value, the adapter stays connected to the remote system for this number of secondsafter completing an operation. A zero value means to disconnect immediately after every operation. The defaultof –1 means to stay permanently connected, even during idle times. Adapters are assumed idle at startup andtherefore only auto-connect if they are configured with a StayConnected value of –1.

34                                                                                                                                     Using TCP Adapters with Ensemble

Using the TCP Counted XML Outbound Adapter

Page 41: Using TCP Adapters with Ensemble

6Using the TCP Text Line Inbound Adapter

EnsLib.TCP.TextLineInboundAdapter is the adapter class to use for incoming TCP connections over which a TCP client andTCP listener exchange data as text strings that end with a line terminator character. The default terminator is the newlinecharacter (ASCII 10).

This chapter explains how to use the EnsLib.TCP.TextLineInboundAdapter. It discusses the following topics:

• Background Information

• Using the Adapter

• Creating a New Business Service Class

• Sample Business Service Class Code

• Adapter Settings

• Adding a TCP Status Service

An important example of a business service that uses the EnsLib.TCP.TextLineInboundAdapter is the built-in business serviceclass EnsLib.TCP.StatusService. This class provides a command-line interface that allows a console user or command-linescript to retrieve basic status information from a running Ensemble production. For more information, see “TCP StatusService” at the end of this chapter.

6.1 Background InformationYou can simply set up the EnsLib.TCP.TextLineInboundAdapter as instructed in the next section, “Using the Adapter.”However, some developers want more details about how the adapter communicates with its configured business service.This section provides those details.

If you look at the EnsLib.TCP.TextLineInboundAdapter class code, you see that it contains a call to an Ensemble frameworkmethod called ProcessInput(). However, the code for the business service class provides a method called OnProcessInput().This section explains the relationship between the two methods. If you want to view Ensemble class code, try the following:

• In Studio, from the Tools menu choose Class Browser. The Class Browser dialog displays. In the window at left, nav-igate the hierarchy to find the class of interest. In the window at right, display details about class members and theclass hierarchy by clicking the tabs along the lower edge of the display: All, Properties, Methods, Parameters, and soon.

• In Studio, from the Help menu choose On-line Documentation. The documentation home page displays. Scroll downand choose Class Reference Information. The Caché Class Reference home page displays. At top left, for Classes in

choose an Ensemble-enabled namespace. Navigate the hierarchy of package names to find the class of interest.

Using TCP Adapters with Ensemble                                                                                                                                     35

Page 42: Using TCP Adapters with Ensemble

Figure 6–1: Using the TCP Text Line Inbound Adapter and Business Service

The figure above shows the flow of a request from an external data source into Ensemble after you have set up an Ensemblebusiness service to work with an inbound adapter. This figure shows the ingoing data stream only; any response simplyretraces this path. The sequence is as follows:

1. At production startup, Ensemble creates a background process for each of the business services in the productionconfiguration. Ensemble can allocate more than one background process per business service. The business service’sconfigured PoolSize specifies the number of background processes.

2. Within each background process, Ensemble creates an instance of the business service class and an instance of itsassociated inbound adapter class.

3. Ensemble calls the OnInit() methods of the business service object and inbound adapter object, respectively.

4. Thereafter, whenever the production is running and the business service is enabled and scheduled to be active, thefollowing cycle can occur:

• Each time the adapter encounters input from its configured data source, it calls the Ensemble framework’sProcessInput() method.

• The call to ProcessInput() automatically prompts the Ensemble framework to call the associated business service’sOnProcessInput() method.

• Code within OnProcessInput() determines what to do with the incoming data stream. For example, if anEnsemble business process needs to be started, the business service formulates an Ensemble request message andissues the synchronous or asynchronous call that starts the business process.

If the data source expects an acknowledgment or response of some kind, it is the business service’sOnProcessInput() that constructs it. The inbound adapter simply relays this response back to the external datasource.

Note: There is no default implementation of OnProcessInput(). The developer of each business service classis responsible for writing an OnProcessInput() method for that class. For instructions, see the nextsection, “Using the Adapter.”

36                                                                                                                                     Using TCP Adapters with Ensemble

Using the TCP Text Line Inbound Adapter

Page 43: Using TCP Adapters with Ensemble

An Ensemble production continues running until it is stopped, either programmatically or by an administrator using theManagement Portal. When a production stops, the following events related to inbound adapters occur:

1. Ensemble disables each business service; no more incoming requests are accepted for this production.

2. The OnTearDown() method in each inbound adapter is called.

3. All inbound adapter and business service objects are destroyed and their background processes are killed.

4. Each business service’s OnProductionStop class method is called, once for each configured item of that class in theproduction.

When a business service is disabled by a system administrator, or becomes inactive according to its configured schedule,the production continues to run but the associated inbound adapter is shut down, and its OnTearDown() method is executed,as described above.

6.2 Using the AdapterOnce you determine that your production needs the EnsLib.TCP.TextLineInboundAdapter, you can include it in the productionconfiguration as follows:

1. Choose or create a business service class that uses the EnsLib.TCP.TextLineInboundAdapter.

2. If you create a new business service class, be sure to:

• Implement its OnProcessInput() method.

• Compile the class.

3. Configure the production. Add a business service of the chosen class.

4. Configure the new business service. To do so, click it and specify values for the settings on the right.

To enable it, select the Enabled box.

The next sections provide details.

6.3 Creating a New Business Service ClassThe simplest way to deploy the EnsLib.TCP.TextLineInboundAdapter is to choose an existing business service class thatalready uses it. You can choose any business service class that uses the EnsLib.TCP.TextLineInboundAdapter, for examplethis built-in business service:

• EnsLib.TCP.StatusService — Parses a string request to determine what type of production status information is beingrequested. Produces a reply string suitable for writing out to a console screen.

If no existing class has the functionality you need, create a new business service class that uses theEnsLib.TCP.TextLineInboundAdapter. Create the new class in Studio as follows:

1. From the File menu, choose New. A dialog pops up. Edit it as follows:

• Click on the Production tab.

• Select the Business Service icon and click OK.

• Enter a package and class name and click Next.

Using TCP Adapters with Ensemble                                                                                                                                     37

Using the Adapter

Page 44: Using TCP Adapters with Ensemble

Important: Be sure to avoid reserved package names; see “Reserved Package Names” in DevelopingEnsemble Productions.

• Choose EnsLib.TCP.TextLineInboundAdapter from the drop-down list of adapter classes.

• Click Finish.

The result is a template class like the following:

Class Dev.Test.NewService1 Extends Ens.BusinessService [ ProcedureBlock ]{

Parameter ADAPTER = "EnsLib.TCP.TextLineInboundAdapter";

Method OnProcessInput(pInput As %RegisteredObject, pOutput As %RegisteredObject) As %Status{ Quit $$$ERROR($$$NotImplemented)}

}

2. Implement the OnProcessInput() method in your new business service class. This is the method that uses the inputdata gathered by the EnsLib.TCP.TextLineInboundAdapter.

You can implement the OnProcessInput() method by replacing the following line in the template class with your owncode:

Quit $$$ERROR($$$NotImplemented)

Your OnProcessInput() method must know the types of incoming and outgoing data for communicating with theEnsLib.TCP.TextLineInboundAdapter. However, the New Business Service Wizard specifies both types in theOnProcessInput() method signature as the generic object type %RegisteredObject.

InterSystems suggests that, as your first action in coding the new business service, you change each OnProcessInput()argument to its specific type passed from the adapter:

Method OnProcessInput(pInput As Ens.StringContainer, Output pOutput As Ens.StringContainer) As %Status

Where:

• pInput is of type Ens.StringContainer and contains the incoming line of text.

• pOutput is of type Ens.StringContainer and contains the outgoing response string (if any).

Keep in mind that the method must quit by returning a %Status object. See the code sample in “Sample BusinessService Class Code.”

3. Optionally, you may implement the OnConnect() callback method in your business service class.

OnConnect() is available for a TCP inbound adapter to call back to its associated business service. If present in thebusiness service, this method is called each time the TCP inbound adapter establishes a new connection to or from aremote system.

If you add an OnConnect() method to your business service class, it must have the following signature:

Method OnConnect(pTimeout As %Numeric) As %Status

Implement an OnConnect() method in your business service if you need to take some action each time a new connectionis established, for example to send a logon sequence or a handshake token. The timeout argument is automaticallyprovided by the TCP inbound adapter. It takes its value from the ReadTimeout adapter setting. For details, see “AdapterSettings.”

38                                                                                                                                     Using TCP Adapters with Ensemble

Using the TCP Text Line Inbound Adapter

Page 45: Using TCP Adapters with Ensemble

Returning an error status from OnConnect() causes the new connection to fail and be disconnected. If an untrappedexception occurs within OnConnect(), the adapter catches it and continues as if OnConnect() were not implemented.

4. Compile your new business service class. Compiling also saves it.

5. After creating and compiling the business service class in Studio, add an instance of the business service to the productionand configure it using the Management Portal. See the appendix “Common Tasks in the Management Portal.”

When you configure the adapter, you specify a value for the AllowedIPAddresses settings, along other settings. Notethat AllowedIPAddresses provides a way to enable the adapter to initiate the connection; see “Adapter Settings.”

6.4 Sample Business Service Class CodeThe following is an example of a business service class that references the EnsLib.TCP.TextLineInboundAdapter.

Class TestTCPTextLine.AuthorizationTCPService Extends Ens.BusinessService [ ProcedureBlock ]{/// Name of the adapter classParameter ADAPTER = "EnsLib.TCP.TextLineInboundAdapter";

Method OnProcessInput(pInput As Ens.StringContainer, pOutput As Ens.StringContainer) As %Status{ set $ZT = "EXCEPTION" set st = $$$OK

do { if ('$isobject($get(pInput))) { quit }

// Input must have the following format: 'PatientCode:ProcedureCode' set tSubject = pInput.StringValue $$$TRACE("received line "_tSubject)

set req = ##class(TestTCPTextLine.AuthorizationRequest).%New() set req.PatientCode = $piece(tSubject,":",1) set req.ProcedureCode = $piece(tSubject,":",2)

set st = ..SendRequestSync("AuthorizationProcess", req, .resp) quit:$$$ISERR(st)

set pOutput= ##class(Ens.StringContainer).%New(resp.AuthorizationFlag_ ":"_resp.AuthorizationCode) } while (0)

EXIT //do ..Adapter.Disconnect() quit st

EXCEPTION set $ZT = "" set st = $$$EnsSystemError goto EXIT}}

6.5 Adapter SettingsThis topic describes the settings that are specific to the EnsLib.TCP.TextLineInboundAdapter associated with the businessservice. For settings not listed here, see “Business Service Settings” in the chapter “Configuration” in ManagingEnsemble Productions.

Using TCP Adapters with Ensemble                                                                                                                                     39

Sample Business Service Class Code

Page 46: Using TCP Adapters with Ensemble

AllowedIPAddresses

A comma-separated list of remote IP addresses from which to accept connections. The adapter accepts named IPaddresses, IPV4 addresses, or IPV6 addresses. An optional :port designation is supported; so, for example, bothof the following address formats are acceptable: 192.168.1.22 or 192.168.1.22:3298.

If a port number is specified, connections from other ports will be refused.

If the string starts with a ! character, the adapter initiates a connection to the specified address. In this case, onlyone address may be given, and if a port is specified, it supersedes the value of the Port setting; otherwise, the Port

setting is used.

CallInterval

Number of seconds that the adapter will listen for incoming data from its configured source, before checking fora shutdown signal from the Ensemble framework.

If the adapter finds input, it acquires the data and passes it to the business service. The business service processesthe data, and then the adapter immediately begins waiting for new input. This cycle continues whenever the pro-duction is running and the business service is enabled and scheduled to be active.

The default CallInterval is 5 seconds. The minimum is 1 second.

Charset

Specifies the text character set to use to translate characters for the input file. The string is not case-sensitive. Thedefault is Binary. Use Binary for binary files, or for any data in which newline and linefeed characters aredistinct or must remain unchanged, for example in HL7 Version 2 or EDI messages. Other settings may be usefulwhen transferring text documents. Choices include:

• Binary — Binary transfer (the default)

• Ascii — Ascii mode FTP transfer but no character encoding translation

• Default — The default character encoding of the local Ensemble server

• Latin1 — The ISO Latin1 8-bit encoding

• ISO-8859-1 — The ISO Latin1 8-bit encoding

• UTF-8 — The Unicode 8-bit encoding

• UCS2 — The Unicode 16-bit encoding

• UCS2-BE — The Unicode 16-bit encoding (Big-Endian)

• Any other alias from an international character encoding standard for which NLS (National Language Support)is installed in Ensemble.

JobPerConnection

When True, the adapter spawns a new job to handle each incoming TCP connection and allows simultaneoushandling of multiple connections. When False, it does not spawn a new job for each connection; False is usuallythe appropriate choice for HL7 or X12 connections. The default is True.

LocalInterface

Specifies the network interface through which the TCP connection should go. Select a value from the list or typea value. An empty value means use any interface.

40                                                                                                                                     Using TCP Adapters with Ensemble

Using the TCP Text Line Inbound Adapter

Page 47: Using TCP Adapters with Ensemble

Port

Identifies the TCP port to connect to. TCP port numbers have a maximum value of 65535.

QSize

How many incoming connections the operating system should hold in reserve on behalf of this business service.Set to 0 if only 1 connection at a time is expected. Set to a large number if many clients will connecting rapidly.The default is 100. The range is 0–1000.

ReadTimeout

Number of seconds to wait for each successive incoming TCP read operation, following receipt of initial datafrom the remote TCP port. The default is 5 seconds. The range is 0–600 seconds (a maximum of 10 minutes).

SSLConfig

The name of an existing Secure Socket Layer (SSL) or Transport Layer Security (TLS) configuration to use toauthenticate this connection.

You can create and manage SSL/TLS configurations using the Management Portal. See the “Using SSL/TLS withCaché” chapter in the Caché Security Administration Guide.

The first field on the Edit SSL/TLS Configuration form is Configuration Name. This is the string to use in the adapter’sSSLConfig field. The SSLConfig string may also add a | (vertical bar) character followed by the private keypassword. The | character is unique because it is not allowed as part of a Configuration Name.

StayConnected

If StayConnected is a positive value, the adapter stays connected to the remote system for this number of secondsbetween input events. A zero value means to disconnect immediately after every input event. The default of –1means to stay permanently connected, even during idle times. Adapters are assumed idle at startup and thereforeonly auto-connect if they are configured with a StayConnected value of –1.

6.6 Adding a TCP Status ServiceThe EnsLib.TCP.StatusService parses an incoming text string to determine what type of production status information isbeing requested, and then produces a reply string suitable for writing out to the console screen. A user can interact with thestatus service directly, or write a command script that contacts the status service, issues commands, and writes the repliesto a text file for later analysis.

A developer enables interactions via the status service as follows:

1. Add an instance of EnsLib.TCP.StatusService to the production.

2. Configure the instance of EnsLib.TCP.StatusService to accept communications via a particular TCP port. Set a Port

number and a list of AllowedIPAddresses from which to accept connections. These are only two of the several settingsthat are available to configure the TCP text line inbound adapter associated with the status service. For details, see“Adapter Settings.”

Once you have completed these steps, any time the status service is enabled and running, a user or command-line scriptcan initiate a Telnet connection to the configured Port and send commands to the status service. Each command must be atext string that ends with the newline character (ASCII 10). The reply strings will also terminate with a newline.

The following table describes the supported command lines and the contents of the text string returned in each case.

Using TCP Adapters with Ensemble                                                                                                                                     41

Adding a TCP Status Service

Page 48: Using TCP Adapters with Ensemble

Table 6–1:TCP Status Service Commands

Text String ReturnedCommand Line

The full name of the Ensemble software version, for example Cache forWindows (x86-32) 2007.1.2 (Build 514U) Mon Aug 13 2007 11:30:37

EDT

build

When you enter this command with the configured name of any business hostin the currently running production, the status service returns a string thatexpresses the current state of that business host.

A host that has currently running jobs, or active connections, records thoseactivities in the returned string. If the identified host is not a member of the cur-rently running production, the returned string indicates this.

configitemstatusname

No string is returned. This command disconnects from the status service.Youmay enter x instead of exit

exit

If Ensemble is running, this returns the start time of the currently runningproduction, expressed in local time coordinates. Otherwise, it returns a stringwith the message <UNDEFINED>

localstarttime

The current time, in local time coordinates.localtime

The Ensemble namespace where the currently running production resides.namespace

The configured name of the currently running production.production

No string is returned. This command disconnects from the status service.Youmay enter q instead of quit

quit

If Ensemble is running, this returns the start time of the currently runningproduction, is expressed in universal time coordinates (UTC). Otherwise, it returnsa string with the message <UNDEFINED>

utcstarttime

The current time, in universal time coordinates (UTC).utctime

The abbreviated name of the Ensemble software version, for example2007.1.0.514/2171

version

Same as exitx

42                                                                                                                                     Using TCP Adapters with Ensemble

Using the TCP Text Line Inbound Adapter

Page 49: Using TCP Adapters with Ensemble

7Using the TCP Text Line OutboundAdapter

EnsLib.TCP.TextLineOutboundAdapter contains methods that an Ensemble business operation can call to read or write textstrings across a TCP connection. Ensemble acts as a TCP client exchanging blocks of data with a TCP listener. The defaultterminator for the text strings is the newline character (ASCII 10). The adapter makes no decisions about the data it relaysout to the external system. It simply maps the request from the business operation to a format that is acceptable to theexternal system.

This chapter explains how to use the EnsLib.TCP.TextLineOutboundAdapter. It discusses the following topics:

• Background Information

• Using the Adapter

• Creating a New Business Operation Class

• Available Helper Methods

• Adapter Settings

7.1 Background InformationYou can simply set up the EnsLib.TCP.TextLineOutboundAdapter as instructed in the next section, “Using the Adapter.”However, some developers want more details about how a business operation communicates with its configured adapter.This section provides those details.

Using TCP Adapters with Ensemble                                                                                                                                     43

Page 50: Using TCP Adapters with Ensemble

Figure 7–1: Business Operation and Using the TCP Text Line Outbound Adapter

The figure above shows the flow of a request from Ensemble out to an external system after you have set up an Ensemblebusiness operation to work with an outbound adapter. The sequence is as follows:

1. At production startup, Ensemble creates a background process for each of the business operations in the productionconfiguration. Ensemble can allocate more than one background process per business operation. The business operation’sconfigured PoolSize specifies the number of background processes.

2. Within each background process, Ensemble creates an instance of the business operation class and an instance of itsassociated outbound adapter class.

3. Ensemble calls the OnInit() methods of the business operation object and outbound adapter object, respectively.

4. Thereafter, whenever the production is running and the business operation is enabled and scheduled to be active, thefollowing sequence can occur:

• The business operation receives an Ensemble request message.

• The business operation’s message map matches the Ensemble request type with a business operation method.

Note: The developer of each business operation class is responsible for writing its message map and methods.For instructions, see the next section, “Using the Adapter.”

• The business operation method calls a method in the associated outbound adapter object.

• The adapter method sends a request to the external system. If this request generates an acknowledgment or responseof some kind, the outbound adapter relays that data back to the business operation method that invoked it.

• If the original Ensemble request message requires a response, the business operation returns it.

44                                                                                                                                     Using TCP Adapters with Ensemble

Using the TCP Text Line Outbound Adapter

Page 51: Using TCP Adapters with Ensemble

An Ensemble production continues running until it is stopped, either programmatically or by an administrator using theManagement Portal. When a production stops, the following events related to outbound adapters occur:

1. Ensemble waits for each business operation to reach a quiescent state (that is, Ensemble waits until each businessoperation has completed all of its synchronous requests).

2. The OnTearDown() method in each outbound adapter is called.

3. All outbound adapter and business operation objects are destroyed and their background processes are killed.

4. Each business operation’s OnProductionStop class method is called, once for each configured item of that class inthe production.

When a business operation is disabled by a system administrator, or becomes inactive according to its configured schedule,the production continues to run but the associated outbound adapter is shut down, and its OnTearDown() method is executed,as described above.

7.2 Using the AdapterOnce you determine that your production needs the EnsLib.TCP.TextLineOutboundAdapter, you can include it in the productionconfiguration as follows:

1. Choose or create a business operation class that uses the EnsLib.TCP.TextLineOutboundAdapter.

2. If you create a new business operation class, be sure to:

• Add at least one method to the method map.

• Implement each method in the method map.

• Write the business operation methods so that they call methods from the EnsLib.TCP.TextLineOutboundAdapter

class.

• Compile the new class.

3. Configure the production. Add a business operation of the chosen class.

4. Configure the new business operation. To do so, click it and specify values for the settings on the right.

To enable it, select the Enabled box.

The next sections provide details.

7.3 Creating a New Business Operation ClassThe simplest way to deploy the EnsLib.TCP.TextLineOutboundAdapter is to choose an existing business operation class thatalready uses it.

If no existing class has the functionality you need, create a business operation class that uses theEnsLib.TCP.TextLineOutboundAdapter. Create the new class as follows:

1. From the File menu, choose New. A dialog pops up. Edit it as follows:

• Click on the Production tab.

• Select the Business Operation icon and click OK.

Using TCP Adapters with Ensemble                                                                                                                                     45

Using the Adapter

Page 52: Using TCP Adapters with Ensemble

• Enter a package and class name and click Next.

Important: Be sure to avoid reserved package names; see “Reserved Package Names” in DevelopingEnsemble Productions.

• Choose EnsLib.TCP.TextLineOutboundAdapter from the drop-down list of adapter classes.

• Choose the default invocation style Queue. The alternative is InProc, but generally you want Queue. The differencesare as follows:

– Queue means the message is created within one background job and placed on a queue, at which time theoriginal job is released. Later, when the message is processed, a different background job will be allocatedfor the task.

– InProc means the message will be formulated, sent, and delivered in the same job in which it was created.The job will not be released to the sender’s pool until the message is delivered to the target. This is onlysuitable for special cases.

• Add at least one entry to the method map as follows:

–Click the Add icon.

– Enter the method name.

– Choose a request type and a response type.

– Click OK.

Repeat these steps as needed to add entries to the method map.

• Click Finish.

The result is a template class like the following:

Class Dev.Test.NewOperation1 Extends Ens.BusinessOperation [ ProcedureBlock ]{

Parameter ADAPTER = "EnsLib.TCP.TextLineOutboundAdapter";

Parameter INVOCATION = "Queue";

Method SampleCall(pRequest As Ens.Request, Output pResponse As Ens.Response) As %Status{ Quit $$$ERROR($$$NotImplemented)}

XData MessageMap{<MapItems> <MapItem MessageType="Ens.Request"> <Method>SampleCall</Method> </MapItem></MapItems>}

}

2. Implement the method(s) in your new business operation class.

Where the following line appears, replace it with your own code:

Quit $$$ERROR($$$NotImplemented)

Keep in mind that the method must quit by returning a %Status object.

46                                                                                                                                     Using TCP Adapters with Ensemble

Using the TCP Text Line Outbound Adapter

Page 53: Using TCP Adapters with Ensemble

3. When you want to call one of the methods in EnsLib.TCP.TextLineOutboundAdapter, use the Adapter property to identifythe adapter object. In the following example, the Demo.Loan.FindRateTCPOperation class calls theEnsLib.TCP.TextLineOutboundAdapter method SendMessageString:

/// Send an approval to the output TCP listenerMethod TCPSendReply(pRequest As Demo.Loan.Msg.SendReply, Output pResponse As Ens.Response) As %Status{ Set tSC=..Adapter.SendMessageString(pRequest.Text) Quit tSC}

You can use similar syntax to call any of the EnsLib.TCP.TextLineOutboundAdapter methods described in “AvailableHelper Methods.”

4. Optionally, you may implement the OnConnect() callback method in your business operation class.

OnConnect() is available for a TCP outbound adapter to call back to its associated business operation. If present inthe business operation, this method is called each time the TCP outbound adapter establishes a new connection to orfrom a remote system.

If you add an OnConnect() method to your business operation class, it must have the following signature:

Method OnConnect(pTimeout As %Numeric) As %Status

Implement an OnConnect() method in your business operation if you need to take some action each time a new con-nection is established, for example to send a logon sequence or a handshake token. The timeout argument is automaticallyprovided by the TCP outbound adapter. It takes its value from the ConnectTimeout adapter setting. For details, see“Adapter Settings.”

Returning an error status from OnConnect() causes the new connection to fail and be disconnected. If an untrappedexception occurs within OnConnect(), the adapter catches it and continues as if OnConnect() were not implemented.

5. Compile your new business operation class. Compiling also saves it.

6. After creating and compiling the business operation class in Studio, add an instance of the business operation to theproduction and configure it using the Management Portal. See the appendix “Common Tasks in the ManagementPortal.”

7.4 Available Helper MethodsWhen your business operation class references the EnsLib.TCP.TextLineOutboundAdapter, the following adapter methodsbecome available. You can call these adapter methods from the methods in your business operation class using the Adapter

property as described in the previous section:

Connect()

Method Connect(pTimeout As %Numeric) As %Status

Connect() opens a TCP socket to a port on the TCP listener machine. Connect() has one input argument, a%Numeric value that identifies the number of seconds to wait for the connection attempt to succeed. A typical callto the Connect() method gives this input argument the value of the configurable ConnectTimeout property.

If the StayConnected adapter setting is set to –1, the Ensemble framework will create the connection automaticallyat startup time, from within the OnInit() method.

Using TCP Adapters with Ensemble                                                                                                                                     47

Available Helper Methods

Page 54: Using TCP Adapters with Ensemble

Disconnect()

Method Disconnect()

Disconnect() takes down the connection to the TCP listener.

SendMessageString

Method SendMessageString(pRequestString As %String, Output pResponseString As %String) As %Status

SendMessageString sends the string contents as a text line on the TCP socket.

TestConnection()

Method TestConnection()

TestConnection() corrects the properties reflecting the connection state. If the adapter is connected,TestConnection() returns True. If not, TestConnection() calls Disconnect() and returns False.

7.5 Adapter SettingsThis topic describes the settings that are specific to the EnsLib.TCP.TextLineOutboundAdapter associated with the businessoperation. For settings not listed here, see “Business Operation Settings” in the chapter “Configuration” in ManagingEnsemble Productions.

Charset

Specifies the text character set to use to translate characters for the input file. The string is not case-sensitive. Thedefault is Binary. Use Binary for binary files, or for any data in which newline and linefeed characters aredistinct or must remain unchanged, for example in HL7 Version 2 or EDI messages. Other settings may be usefulwhen transferring text documents. Choices include:

• Binary — Binary transfer (the default)

• Ascii — Ascii mode FTP transfer but no character encoding translation

• Default — The default character encoding of the local Ensemble server

• Latin1 — The ISO Latin1 8-bit encoding

• ISO-8859-1 — The ISO Latin1 8-bit encoding

• UTF-8 — The Unicode 8-bit encoding

• UCS2 — The Unicode 16-bit encoding

• UCS2-BE — The Unicode 16-bit encoding (Big-Endian)

• Any other alias from an international character encoding standard for which NLS (National Language Support)is installed in Ensemble.

ConnectTimeout

Number of seconds to wait on each attempt to connect to the remote TCP listener. The default is 5 seconds.

48                                                                                                                                     Using TCP Adapters with Ensemble

Using the TCP Text Line Outbound Adapter

Page 55: Using TCP Adapters with Ensemble

GetReply

If 1 (true) wait to read a reply message back from the socket before returning. If 0 (false) do not wait. The defaultvalue is 1.

IPAddress

IP address to make a TCP connection to. The adapter accepts a named IP address, an IPV4 address, or an IPV6address.

If the address starts with a ! character, the adapter waits for a connection from a remote system. In this case, followthe exclamation point with a comma-separated list of remote IP addresses from which to accept connections. Theadapter accepts named IP addresses, IPV4 addresses, or IPV6 addresses. An optional :port designation is supported;so, for example, both of the following address formats are acceptable: 192.168.1.22 or 192.168.1.22:3298.

If no IP address follows the ! character, any remote system may connect; otherwise only the listed IP addresses(and ports) are allowed to connect.

LocalInterface

Specifies the network interface through which the TCP connection should go. Select a value from the list or typea value. An empty value means use any interface.

This setting allows you to specify that a virtual IP address should be used to send outbound traffic, which is usefulin the case of mirroring. If a remote application is configured to accept traffic from the virtual IP address, and boththe primary and the secondary use that IP address to connect to the remote application, then everything continuesto work when the secondary starts sending.

Port

Identifies the TCP port to connect to. TCP port numbers have a maximum value of 65535.

QSize

How many incoming connections the operating system should hold in reserve on behalf of this business operation.There is generally no reason to change the default value of 0. Either the connection is outbound, or the businessoperation is using '!' inbound mode, in which case only 1 client is allowed at a time, per business operation pooljob.

ReadTimeout

Number of seconds to wait for each successive incoming TCP read operation, following receipt of initial datafrom the remote TCP port. The default is 5 seconds. The range is 0–600 seconds (a maximum of 10 minutes).

SSLConfig

The name of an existing Secure Socket Layer (SSL) or Transport Layer Security (TLS) configuration to use toauthenticate this connection.

You can create and manage SSL/TLS configurations using the Management Portal. See “Using SSL/TLS withCaché” in the Caché Security Administration Guide.

The first field on the Edit SSL/TLS Configuration form is Configuration Name. This is the string to use in the adapter’sSSLConfig field. The SSLConfig string may also add a | (vertical bar) character followed by the private keypassword. The | character is unique because it is not allowed as part of a Configuration Name.

ReconnectRetry

Number of retries at which to drop the connection and try reconnecting again. A value of 0 (zero) means neverdisconnect. The default value is 5.

Using TCP Adapters with Ensemble                                                                                                                                     49

Adapter Settings

Page 56: Using TCP Adapters with Ensemble

ResponseTimeout

Number of seconds to wait for a response to begin arriving back from the remote system after sending a request.The default is 15 seconds.

StayConnected

If StayConnected is a positive value, the adapter stays connected to the remote system for this number of secondsafter completing an operation. A zero value means to disconnect immediately after every operation. The defaultof –1 means to stay permanently connected, even during idle times. Adapters are assumed idle at startup andtherefore only auto-connect if they are configured with a StayConnected value of –1.

50                                                                                                                                     Using TCP Adapters with Ensemble

Using the TCP Text Line Outbound Adapter

Page 57: Using TCP Adapters with Ensemble

8Creating Custom TCP Adapter Classes

This chapter discusses how to create custom TCP adapter classes. It discusses the following topics:

• Creating a Custom Subclass

• Common Customizations in TCP Adapter Subclasses

• Customizing Callbacks of Inbound TCP Adapters

• Customizing Callbacks of Outbound TCP Adapters

8.1 Creating a Custom SubclassTo create a custom subclass of an adapter class, do the following in Studio:

1. On the File menu, click New, and then click the General tab.

2. Start the New Class Wizard by clicking Caché Class Definition and clicking OK.

a. Enter a package and class name and click Next.

Important: Be sure to avoid reserved package names; see “Reserved Package Names” in DevelopingEnsemble Productions.

b. Click Extends for the Class type.

c. Click Browse next to Name of super class and navigate to the class that you want to subclass.

d. Click OK.

e. Click Finish.

The result is a template class like the following, depending on the class you chose:

Class MyTest.NewClass1 Extends EnsLib.TCP.InboundAdapter [ ProcedureBlock ]{

}

3. You can override any property, method, class parameter, or other class member inherited from the class or its parentclasses, or you can add new class members. The only requirements are as follows:

• An inbound adapter class must implement the OnConnected() method.

In your implementation, use helper methods inherited by your class.

Using TCP Adapters with Ensemble                                                                                                                                     51

Page 58: Using TCP Adapters with Ensemble

• An outbound adapter class define methods that create a TCP connection, read or write over the connection, anddisconnect.

To define these methods, use helper methods inherited by your class.

4. Compile the class, which also saves it.

8.2 Common Customizations in TCP Adapter SubclassesThe following list suggests some common customizations in TCP adapter subclasses, in addition to implementing themethods that the adapter needs:

• The Terminators property is a common property to edit. You can specify an initial expression for this property.

Your adapter class can set a value for Terminators using the ObjectScript function $CHAR or $C to identify the ASCIIvalue for the character. The following example from EnsLib.TCP.TextLineInboundAdapter sets Terminators to thenewline character (ASCII 10):

Property Terminators As %String [ InitialExpression = {$C(10)} ];

For more information about functions like $CHAR, see “Caché ObjectScript Functions” in the Caché ObjectScriptReference.

You can set Terminators to a single character or to a multi-character string. If you supply a string for the Terminators

value, Ensemble uses the string as follows:

– Any one of the characters in the string serves to terminate the input.

– The complete string of characters is appended to the output.

• You can expose additional properties for runtime configuration by providing a SETTINGS parameter whose value isa comma-separated list of the properties that you want to expose. For example:

/// The full pathname for a transaction log file on the local computerProperty LogPath As %String(MAXLEN = 200) [ Required ];

/// The simple file name for the logProperty LogSpec As %String(MAXLEN = 60) [ InitialExpression = "*" ];

/// These properties are exposed for runtime configuration via the portalParameter SETTINGS = "LogPath,LogSpec";

At runtime, properties from this SETTINGS list appear in the display on the [Ensemble] > [Production Configuration]

page as additional settings.

• If you need to require login credentials for the connection, simply add the property name Credentials to theSETTINGS list. The Credentials property is already defined as a %String in the base class Ens.Adapter.

For background information, see “Username and Password Credentials” in the chapter “Production Concepts” inDeveloping Ensemble Productions.

• (For inbound adapters) You can also enforce a pool size of 1 by setting the parameter SINGLEPOOLJOB = 1:

/// Force a single listener job regardless of PoolSize settingParameter SINGLEPOOLJOB = 1;

Any subclass of this adapter class or a business service class that uses such an adapter class can use this parameter inits class code to better control the pool size.

52                                                                                                                                     Using TCP Adapters with Ensemble

Creating Custom TCP Adapter Classes

Page 59: Using TCP Adapters with Ensemble

8.3 Customizing Callbacks of Inbound TCP AdaptersIf you subclass or copy an inbound TCP adapter, you can override these methods with unique behaviors:

OnConnected()

Method OnConnected() As %Status

Whenever a connection exists to the configured TCP client, the adapter calls OnConnected() to read a streamfrom the TCP data source. This read operation is controlled by adapter settings.

OnConnected() uses helper methods to parse the data.

Upon successfully reading data, OnConnected() calls the Ensemble framework’s ProcessInput() method to passthe received data stream to the associated business service. If this call returns an outbound stream, OnConnected()writes that data as a reply to the TCP client.

If no data is available to read from the TCP connection during the CallInterval time, OnConnected() returnswithout doing anything.

Also see the OnTask() method.

OnInit()

Method OnInit() As %Status

The Ensemble framework calls OnInit() after creating the inbound adapter instance and setting its configurableproperty values. The OnInit() method provides a way for the inbound adapter to perform any special setup actions.Depending on the values of the relevant adapter settings, one of these actions might be to initiate a connectionbetween the adapter and the TCP client it will listen to, or to construct any object properties that the adapter willuse.

OnTearDown()

Method OnTearDown() As %Status

The Ensemble framework calls OnTearDown() during shutdown, before destroying the inbound adapter object.The OnTearDown() method provides a way for an inbound adapter to perform any special cleanup actions suchas disconnecting from the TCP client.

OnTask()

Method OnTask() As %Status

All inbound adapters have an OnTask() method, where the bulk of the adapter work is done. Once a productionstarts, each business service calls the OnTask() method of its associated inbound adapter class, at the time intervaldetermined by the adapter’s CallInterval setting. For details, see “Business Service Life Cycle” in the “BusinessServices” in Developing Ensemble Productions.

For more detailed information about adapter class internals, open the class in Studio or use the InterSystems Class Reference.

8.4 Customizing Callbacks of Outbound TCP AdaptersIf you subclass or copy an outbound TCP adapter, you can override these methods with unique behaviors:

Using TCP Adapters with Ensemble                                                                                                                                     53

Customizing Callbacks of Inbound TCP Adapters

Page 60: Using TCP Adapters with Ensemble

OnInit()

Method OnInit() As %Status

The Ensemble framework calls OnInit() after creating the outbound adapter object and setting its configurableproperty values. The OnInit() method provides a way for an outbound adapter to perform any special setup actions.Depending on the values of the relevant adapter settings, one of these actions might be to open a socket to a porton the TCP listener.

OnTearDown()

Method OnTearDown() As %Status

The Ensemble framework calls OnTearDown() during shutdown, before destroying the outbound adapter object.The OnTearDown() method provides a way for an outbound adapter to perform any special cleanup actions suchas disconnecting from the TCP listener.

54                                                                                                                                     Using TCP Adapters with Ensemble

Creating Custom TCP Adapter Classes

Page 61: Using TCP Adapters with Ensemble

ASettings for the Abstract TCP Adapters

For reference, this appendix describes the settings defined in the two abstract TCP adapters:

• Settings for EnsLib.TCP.InboundAdapter

• Settings for EnsLib.TCP.OutboundAdapter

A.1 Settings for EnsLib.TCP.InboundAdapterThis topic describes the settings that are specific to the EnsLib.TCP.InboundAdapter or any subclass.

AllowedIPAddresses

A comma-separated list of remote IP addresses from which to accept connections. The adapter accepts named IPaddresses, IPV4 addresses, or IPV6 addresses. An optional :port designation is supported; so, for example, bothof the following address formats are acceptable: 192.168.1.22 or 192.168.1.22:3298.

If a port number is specified, Ensemble refuses connections from other ports.

If the string starts with an exclamation point (!) character, the adapter initiates a connection to the specified address.In this case, you can only provide one address, and if you specify a port, it supersedes the value of the Port setting.

CallInterval

Number of seconds that the adapter listens for incoming data from its configured source, before checking for ashutdown signal from the Ensemble framework.

If the adapter finds input, it acquires the data and passes it to the business service. The business service processesthe data, and then the adapter immediately begins waiting for new input. This cycle continues whenever the pro-duction is running and the business service is enabled and scheduled to be active.

The default CallInterval is 5 seconds. The minimum is 1 second.

JobPerConnection

When True, the adapter spawns a new job to handle each incoming TCP connection and allows simultaneoushandling of multiple connections. When False, it does not spawn a new job for each connection; False is usuallythe appropriate choice for HL7 or X12 connections. The default is True.

Using TCP Adapters with Ensemble                                                                                                                                     55

Page 62: Using TCP Adapters with Ensemble

For TCP services, when JobPerConnection is True, a freshly spawned job handles each new incoming socketconnection rather than the listener job itself. Only one job at a time can be the listener, and one job must be thelistener, so a TCP service configured with a PoolSize greater than 1 still only starts one listener job. However, thislistener can spawn an unlimited number of connection jobs if JobPerConnection is set to True. If you set thePoolSize to a value greater than 1, it serves as a limit on the number of simultaneous connection jobs that can exist.When this limit is reached, the listener does not accept any more connections until one or more of the existingconnection jobs quits or dies. An Event Log warning appears when it first reaches the limit.

LocalInterface

Specifies the network interface through which the TCP connection should go. Select a value from the list or typea value. An empty value means use any interface.

Port

Identifies the TCP port to which to connect. TCP port numbers have a maximum value of 65535.

OSAcceptConnectionQueueSize

How many incoming connections the operating system should hold in reserve on behalf of this business service.Set to 0 if only 1 connection at a time is expected. Set to a large number if you expect many clients to connectrapidly. The default is 100. The range is 0–1000.

ReadTimeout

Number of seconds to wait for each successive incoming TCP read operation, following receipt of initial datafrom the remote TCP port. The default is 5 seconds. The range is 0–600 seconds (a maximum of 10 minutes).

StayConnected

If StayConnected is a positive value, the adapter stays connected to the remote system for this number of secondsbetween input events. A zero value means to disconnect immediately after every input event. The default of -1means to stay permanently connected, even during idle times. Adapters are assumed idle at startup and thereforeonly auto-connect if you set StayConnected to a value of -1.

SSLConfig

The name of an existing Secure Socket Layer (SSL) or Transport Layer Security (TLS) configuration to use toauthenticate this connection.

You can create and manage SSL/TLS configurations using the System Management Portal. See the “UsingSSL/TLS with Caché” chapter in the Caché Security Administration Guide.

The first field on the Edit SSL/TLS Configuration form is Configuration Name. This is the string to use in the adapter’sSSLConfig setting. The SSLConfig string may also add a | (vertical bar) character followed by the private keypassword. The | character is unique because it is not allowed as part of a Configuration Name.

A.2 Settings for EnsLib.TCP.OutboundAdapterThis topic describes the settings that are specific to the EnsLib.TCP.OutboundAdapter or any subclass.

GetReply

If True, wait to read a reply message back from the socket before returning. If False, do not wait. The default valueis True.

56                                                                                                                                     Using TCP Adapters with Ensemble

Settings for the Abstract TCP Adapters

Page 63: Using TCP Adapters with Ensemble

IPAddress

IP address to make a TCP connection to. The adapter accepts a named IP address, an IPV4 address, or an IPV6address.

If the address starts with a ! character, the adapter waits for a connection from a remote system. In this case, followthe exclamation point with a comma-separated list of remote IP addresses from which to accept connections. Theadapter accepts named IP addresses, IPV4 addresses, or IPV6 addresses. An optional :port designation is supported;so, for example, both of the following address formats are acceptable: 192.168.1.22 or 192.168.1.22:3298.

If no IP address follows the ! character, any remote system may connect; otherwise only the listed IP addresses(and ports) are allowed to connect.

Port

Identifies the TCP port to which to connect. TCP port numbers have a maximum value of 65535.

StayConnected

If StayConnected is a positive value, the adapter stays connected to the remote system for this number of secondsafter completing an operation. A zero value means to disconnect immediately after every operation. The defaultof -1 means to stay permanently connected, even during idle times. Adapters are assumed idle at startup andtherefore only auto-connect if they are configured with a StayConnected value of -1.

ConnectTimeout

Number of seconds to wait on each attempt to connect to the remote TCP listener. The default is 5 seconds.

LocalInterface

Specifies the network interface through which the TCP connection should go. Select a value from the list or typea value. An empty value means use any interface.

This setting allows you to specify that a virtual IP address should be used to send outbound traffic, which is usefulin the case of mirroring. If a remote application is configured to accept traffic from the virtual IP address, and boththe primary and the secondary use that IP address to connect to the remote application, then everything continuesto work when the secondary starts sending.

ReconnectRetry

Number of retries at which to drop the connection and try reconnecting again. A value of 0 (zero) means neverdisconnect. The default value is 5.

ResponseTimeout

Number of seconds to wait for a response to begin arriving back from the remote system after sending a request.The default is 15 seconds.

ReadTimeout

Number of seconds to wait for each successive incoming TCP read operation, following receipt of initial datafrom the remote TCP port. The default is 5 seconds. The range is 0–600 seconds (a maximum of 10 minutes).

SSLConfig

The name of an existing Secure Socket Layer (SSL) or Transport Layer Security (TLS) configuration to use toauthenticate this connection.

Using TCP Adapters with Ensemble                                                                                                                                     57

Settings for EnsLib.TCP.OutboundAdapter

Page 64: Using TCP Adapters with Ensemble
Page 65: Using TCP Adapters with Ensemble

BCommon Tasks in the Management Portal

This appendix provides a little more detail on some of the tasks described in this book. It discusses:

• Accessing a Production

• Adding a Business Host to a Production

• Editing Runtime Settings of a Business Host

B.1 Accessing a ProductionTo access a production, do the following:

1. In the Management Portal, switch to the appropriate namespace.

To do so, click Switch in the title bar, click the namespace, and click OK.

2. Click Ensemble.

3. Click Configure.

4. Click Production and then click Go.

Ensemble then displays the last production you accessed, within the [Ensemble] > [Production Configuration] page.

5. To display a different production:

a. Click Actions.

b. Click Open.

c. Click the name of the production and then click OK.

B.2 Adding a Business Host to a ProductionTo add a business service, process, or operation to a production, do the following:

1. Access the production, as described earlier in this appendix.

2.In the Services, Processes, or Operations column, as appropriate, click the Add button .

Using TCP Adapters with Ensemble                                                                                                                                     59

Page 66: Using TCP Adapters with Ensemble

Ensemble displays a dialog box.

3. In the first drop-down list, choose the class on which to base the new business host.

4. Optionally specify the other items as follows:

• Service Name (or Business Process Name or Operation Name) — Type the name of this business host. The nameshould be unique within this category of business host. Do not use periods or spaces.

The default is the name of the class on which the host is based.

• Display Category — Choose or type the name of the display category to which this business host belongs. Youcan use this to display different sets of business hosts in the Production Configuration page. If a production has alarge number of business hosts, it can be helpful to display only a subset. This setting does not affect how theproduction works.

Display Category names are case-sensitive, and space characters are allowed. To place an item in multiple categories,list them in the Display Category field separated by commas (do not allow spaces around these commas).

• Comment — Type a comment.

• Enable Now — Select this to enable the host immediately.

5. Click OK.

B.3 Editing Runtime Settings of a Business HostTo edit the settings of a business service, process, or operation, use the following general process:

1. Access the production in which this host is defined, as described earlier in this appendix.

2. Click the business service, process, or operation in the main area of the page.

3. Click the Settings tab in the right area.

This tab displays settings in groups, which you can display or hide separately.

The setting names that appear in the right pane are, in many cases, localized descriptions of the class property names.You can hover the cursor over any setting name to display its help text as it appears in the Class Reference or click thesetting name to display the help text in a separate pop-up window.

4. Make edits as needed.

5. Click Apply to save changes or click Cancel to discard them.

When you click Apply, all changes immediately take effect, even if the production is currently running.

60                                                                                                                                     Using TCP Adapters with Ensemble

Common Tasks in the Management Portal