U2 DBTools
U2 RESTful Web Services Help Version 3.60.6
April 2013 DBT-3606-RWS-UG-1
Notices
Edition
Publication date: April 2013
Book number: RWS-3606-WS-UG-1
Product version: U2 RESTful Web Services 3.60.6
Copyright
© Rocket Software, Inc. or its affiliates 2005-2013. All Rights Reserved.
Trademarks
Rocket is a registered trademark of Rocket Software, Inc. For a list of Rocket registered trademarks go to: www.rocketsoftware.com/about/legal. All other products or services mentioned in this document may be covered by the trademarks, service marks, or product names of their respective owners.
Examples
This information might contain examples of data and reports. The examples include the names of individuals, companies, brands, and products. All of these names are fictitious and any similarity to the names and addresses used by an actual business enterprise is entirely coincidental.
License agreement
This software and the associated documentation are proprietary and confidential to Rocket Software, Inc., are furnished under license, and may be used and copied only in accordance with the terms of such license.
Note: This product may contain encryption technology. Many countries prohibit or restrict the use, import, or export of encryption technologies, and current use, import, and export regulations should be followed when exporting this product.
Contact information
Website: www.rocketsoftware.com Rocket Software, Inc. Headquarters 77 4th Avenue, Suite 100 Waltham, MA 02451-1468 USA Tel: +1 781 577 4321 Fax: +1 617 630 7100
Contacting Technical Support
If you have current support and maintenance agreements with Rocket Software, you can access the Rocket Customer Portal to report and track a problem, to submit an enhancement request or question, or to find answers in the U2 Knowledgebase. The Rocket Customer Portal is the primary method of obtaining support.
To log in to the Rocket Customer Portal, go to:
www.rocketsoftware.com/support
If you do not already have a Rocket Customer Portal account, you can request one by clicking Need an account? on the Rocket Customer Portal login page.
Alternatively, you can contact Rocket Global Technical Support by email or by telephone:
Email: [email protected]
Telephone:
North America +1.800.729.3553
United Kingdom/France +44.0.800.773.771 or 020.8867.3691
Europe/Africa +44.0.20.8867.3692
Australia +1.800.707.703 or 612.9412.5450
New Zealand +0800.505.515
iv
Table of Contents Getting Started .......................................................................................................... 1
Welcome to the U2 RESTful Web Services help ............................................................ 1
System requirements ............................................................................................... 2
Installing U2 RESTful Web Services software............................................................... 3
U2 RESTful Web Services ............................................................................................ 4
U2 Restful Web Services overview ............................................................................. 4
Resources in U2 REST .............................................................................................. 8
Supported HTTP methods ....................................................................................... 14
U2 REST connection pooling support ........................................................................ 26
U2 REST transaction support................................................................................... 27
U2 RESTful Web Services Developer ........................................................................... 28
Available views in the developer .............................................................................. 29
Establishing server connections ............................................................................... 34
U2 REST security ..................................................................................................... 46
Communication security ......................................................................................... 46
Secure client HTTPS connections ............................................................................. 46
Secure U2 database connections ............................................................................. 46
User authentication and authorization ...................................................................... 47
SB+ and RESTful web services ................................................................................... 54
Accessing SB+ files................................................................................................ 54
Modifying SB+ parameters ..................................................................................... 55
Regenerating files .................................................................................................. 57
Tutorial ................................................................................................................... 59
Tutorial: Overview ................................................................................................. 59
Tutorial: Creating a U2 server entry ......................................................................... 60
Tutorial: Creating a REST server ............................................................................. 61
Tutorial: Creating a resource folder ......................................................................... 63
Tutorial: Creating a data resource ........................................................................... 65
Tutorial: Testing a data resource ............................................................................. 67
Tutorial: Linking multiple resources using a foreign key .............................................. 68
Table of Contents
v
Tutorial: Creating a REST subroutine resource .......................................................... 74
Tutorial: Defining input parameters ......................................................................... 77
Tutorial: Defining output parameters ....................................................................... 78
Testing the REST subroutine service ........................................................................ 82
Tutorial: Manually testing the REST subroutine service ............................................... 84
Deployment ............................................................................................................. 86
Deployment environment requirements .................................................................... 86
Creating a deployment package .............................................................................. 87
Exporting RESTful web services ............................................................................... 88
Deploying a U2 RESTful server as a Windows service ................................................. 89
Deploying a RESTful server using the U2 REST deployment tool .................................. 91
Deploying a REST server from the command line ....................................................... 99
Deploying a REST server from a configuration file .................................................... 106
Starting a RESTful service .................................................................................... 111
Stopping a U2 RESTful service .............................................................................. 112
Remote servers ................................................................................................... 113
Code Samples ........................................................................................................ 114
UniBasic code samples ......................................................................................... 114
UniVerse BASIC code samples ............................................................................... 123
Python for UniData code samples .......................................................................... 131
Python for UniVerse code samples ......................................................................... 137
U2 Basic subroutine ............................................................................................. 143
Output types ....................................................................................................... 145
1
Getting Started
Welcome to the U2 RESTful Web Services help
April 2013
The help provides conceptual, task-based, and reference information about U2 RESTful Web Services (U2 REST).
You can search for a word or phrase in these help topics by selecting the Search tab and entering your search topic. To narrow the search results to an exact phrase, enclose the phrase within quotation marks, for example, “dictionary files.”
The help topics cover the following areas:
• U2 REST overview
• System requirements
• Installing U2 RESTful Web Services
• Getting started
• Security
• SB+ and U2 REST
• Deploying your U2 RESTful web services
After you install the product, you can learn about the product interface and take a tutorial by reading the topics in the Getting started section.
Additional resources
For additional information about U2 products, training, and technical resources go to www.rocketsoftware.com/u2
U2 RESTful Web Services Help
2
System requirements
Before you install U2 RESTful Web Services, make sure that the computer you are installing it on meets the requirements.
• You must install U2 RESTful Web Services Developer on a computer that is on the same network as the server running UniData or UniVerse. The installation computer must be running Microsoft Windows 2008 or Windows 7.
• UniData or UniVerse services must be currently running on either a local or remote server.
• UniVerse 10.3 or later must be running on the server (UniVerse only). • UniData 7.2 or later must be running on the server (UniData only). • U2 RESTful web services use port number 9191 as the default port when the first
RESTful web service is created. Each subsequent web service port number will increase in increments of two. A second port number is also used when the U2 RESTful web service is started and it is always the defined port number plus one. For example, 9191 and 9192.
• The default port number used by the U2 RESTful web service to communicate to the U2 database engine is always 31438 unless changed.
• Firewalls must be open for incoming and outgoing traffic on all defined ports. • A screen resolution of 1280x1024 or higher and a text setting of 100% is
recommended for all U2 Eclipse-based applications.
Getting Started
3
Installing U2 RESTful Web Services software
Complete the following steps to install U2 RESTful Web Services on Windows:
1. From the U2 Database Tools Installation screen, select U2 RESTful Web Services. The U2 RESTful Web Services dialog box appears. Click Next to continue with the installation process.
2. Accept the licensing agreement and click Next.
3. Click Next to install U2 RESTful Web Services in the default folder, or click Browse to search for a different folder. By default, U2 RESTful Web Services is installed in the C:\U2\U2Tools\v3 folder.
4. The Select Program Folder dialog box opens. By default, the installation process adds the Rocket U2 icon to the Program Folders list. Click Next to accept this default, or select a different folder from the Existing Folders list and then click Next.
5. Review the information listed in the Start Copying Files dialog box. If the information is correct, click Next to begin copying files. If the information is not correct, click Back to make changes.
6. Click Finish to complete the installation process.
4
U2 RESTful Web Services
U2 Restful Web Services overview
Representational State Transfer (REST) defines a software architecture style of networked systems such as the World Wide Web, and is a popular way to build Web services. Systems that follow REST principles are often referred to as RESTful.
A RESTful web service, sometimes referred to as a RESTful web API, is a software system used to support machine-to-machine interactions using Hypertext Transfer Protocol (HTTP). It aims to capture the characteristics of a successful Web site, which is a RESTful system itself. In a RESTful system, a client requests some resource from the server through the resource’s Universal Resource Identifier (URI). The response from the server is a representation of the resource requested.
U2 RESTful Web Services provides a resource-oriented view of data and subroutines stored in U2 databases and supports simple, lightweight, HTTP-based access to these resources, ideal for the development of browser-based and smart phone-based Web 2.0 applications.
Principles of a RESTful system
RESTful systems typically adhere to the following design principles:
• A URI is used to identify all resources
• Hyperlinks are used for navigation
• Standard HTTP GET, PUT, POST, and DELETE methods are used on the resources
• Server resources with multiple representations, such as JSON or XML
• Communicate statelessly to ensure scalability
RESTful web services
A RESTful web service is built upon the architectural principles that define a RESTful system. A RESTful Web service, unlike a SOAP-based Web service, exposes many resources (URIs), but accepts only a fixed set of methods, such as HTTP GET, PUT, POST, and DELETE. The operation details are all included in the HTTP request. A RESTful Web service offers a resource-based interface to the service consumers.
In contrast, a SOAP-based Web service uses SOAP on top of a transport protocol, such as HTTP. The operation details are in the SOAP envelope, which is wrapped in an HTTP POST request. For SOAP-based Web services, HTTP is used only as a transport protocol. A SOAP-based Web service provides a procedure-based interface to the service consumers.
A RESTful Web service makes full use of HTTP. It has a uniform interface and always uses HTTP GET, PUT, POST, DELETE requests on the resources. This makes it less cumbersome to use than a SOAP-based Web service, and allows RESTful Web services to behave in a more Web-like manner.
RESTful Web services tend to perform faster and carry less overhead than SOAP-based Web services. This is because RESTful Web services have a smaller message size and do
U2 RESTful Web Services
5
not require as many layers in the protocol stack. This makes REST an ideal choice for mobile and cloud-based applications.
In a RESTful system, all meaningful resources, such as web pages, blog entries, pictures, and data records, are identified by using a URI or URL. These resources contain URIs to other related resources and resources that contain specialized information.
U2 RESTful Web Services Help
6
U2 RESTful web services
U2 RESTful Web Services (U2 REST) consist of a U2 REST server and the U2 RESTful Web Services Developer, which is an Eclipse-based development tool. U2 RESTful Web services enable U2 users to quickly and easily expose U2 data and subroutines as RESTful resources accessible through HTTP GET, PUT, POST, and DELETE methods.
U2 data is natively accessed and requires no normalization. The U2 RESTful Web Services consist of a Jetty-based REST server and an Eclipse-based development tool that lets users create, test (using GET on data and subroutine resources), debug, and deploy U2 RESTful Web Services within a single integrated development environment (IDE).
U2 REST offers SSL support for secure communications, as well as HTTP-based user authentication and authorization (Digest or Basic). Optimistic concurrency control and connection pooling are also supported to provide greater accessibility.
U2 REST supports the JavaScript Object Notation (JSON) data format, which is a lightweight data-interchange format and is part of the JavaScript language specification, supported by all Internet browsers. This process allows the REST server to transmit data between the client service and the U2 RESTful Web services.
The U2 RESTful Web Services Developer lets you define and publish U2 resources, such as data files and subroutines, to a U2 REST server so they can be accessed in a RESTful manner. The developer utilizes Eclipse-based tooling to enable the rapid development of U2 RESTful Web Services. The developer can also be used to start and stop a local RESTful server, and to stop a remote RESTful server. You can also manually start and stop the RESTful servers, using the provided .sh or .bat files.
A server log is provided to aid in debugging and tracing. You can quickly turn the server log on and off in the U2 RESTful Web Services Developer, and the log results can be viewed directly from within the developer. If the server response is not what you expect, you can turn on the log and check the operation.
U2 RESTful Web Services
7
U2 REST server
The U2 REST server is built on top of the Jetty HTTP server. It includes a U2 resource handler that processes HTTP requests for defined U2 REST resources. The U2 Resource handler calls U2JPA, via a UniObjects for Java (UOJ) call, to complete both the data requests and subroutine requests to the database server. It converts native U2 data formats, or dynamic arrays, into human-readable formats such as JSON.
U2 REST architecture
The following illustration shows the architecture of a U2 RESTful system, and its relationship with the UniData and UniVerse databases:
In a U2 RESTful system, the client computer can connect to the U2 REST server through a secure HTTP connection. The U2 REST server uses the U2 Java Persistence API to connect to the UniData or UniVerse database. It does this through a UniObjects for Java connection or an UniObjects for Java (SSL) connection.
U2 RESTful Web Services Help
8
Resources in U2 REST
U2 RESTful Web Services resources
U2 RESTful Web Services (U2 REST) resources refer to resources that are defined on the U2 REST server and are accessible through HTTP requests. There are two types of U2 REST resources: Data and subroutines.
U2 REST data resources
A U2 REST data resource is a resource that maps to U2 data. These resources are U2 Java Persistence API (U2JPA) entities that map fully or partially to U2 data files.
U2JPA entities support only Java String type fields, so the value of any U2 REST data resource is always a String value. This applies even when the U2 dictionary conversion code indicates the field is of a different type, such as a numeric type.
Subresources
There are two types of data resources: primary, top-level resources and sub-resources. A primary resource corresponds to a U2 data file, while the sub-resources correspond to the data file associations.
A primary resource typically contains collections of sub resources, or multi-subvalue associations. Sub-resources may contain collections of other sub-resources, or multi-subvalue associations.
For example, the UniVerse HS.SALES Customer resource is a primary resource that maps to the CUSTOMER file. It contains a collection of sub-resources, including the Order resource, which corresponds to the ORDER association. The Order resource, in turn, contains a collection of sub-resources, including Item, which represent all of the items in a single order and includes all of the multi-subvalue fields in the ORDER association.
Foreign resources
A referenced primary resource is a foreign resource to the host data source. Foreign resources can contain references to other primary resources. The references correspond to the TRANS () virtual fields in the host U2 data file.
In the preceding example, the subresource Item references the primary resource Product, which is mapped to the PRODUCT data file that contains the detailed information about an ordered product.
Virtual fields
A U2 REST data resource can contain both D-type fields and V-type fields. The V-type fields, or virtual fields, contain virtual information that is calculated or otherwise derived from other attributes, other files, or other information in the database. The result of a virtual attribute is information that does not actually exist in the data portion of a file.
In the example above, instead of referencing the Product resource, the sub-resource Item may include several TRANS () virtual fields that read data from the PRODUCT data file. In a situation like this, the product information is already in the Item resource when
U2 RESTful Web Services
9
it is read from the server, and there is no need to read the Product resource itself to see the detailed product information.
U2 RESTful Web Services Help
10
U2 REST resource folders
U2 REST resources are grouped under the resource folders on the REST server. A resource folder maps to a U2 account on the database server, which is where the REST server accesses the data and calls the subroutines.
A resource folder contains properties such as the host server name or IP address, UniRPC service name, UniRPC port number, account path, a database user name and password, and SSL options. This information is used by the U2 REST server to complete the database access request.
U2 RESTful Web Services
11
URI addresses in U2 REST resources
A U2 REST resource URI is designed to impart the resource location, the resource type (data or subroutine), and any parent-child relationships. Each resource address contains three distinct parts: the REST server URI, the Resource folder name, and the relative path of the URI. The three parts of the resource address are separated by a forward slash, “/”, and are described below:
1. REST Server URI Each REST server listens on a unique port number on the server machine. A REST server URI is a HTTP URL, and is formed by combining the host name or IP address with its port number, as shown: http://myserver:9191 or https://myserver:9191 Note: The REST server URI cannot be accessed directly.
2. Resource folder name The name of a resource folder that maps to a database account such as HS.SALES. The resource folder can be accessed via its URI using the HTTP GET method. This results in a list of URIs of all the top-level data resources in the folder.
3. Relative paths
For data resources:
For a collection-type resource, use the data resource name, as shown in the examples below:
http://myserver:9191/HS_SALES
http://myserver:9191/HS_SALES/CUSTOMER
http://myserver:9191/HS_SALES/CUSTOMER/2/ORDERS
Each of the above examples returns a list of the requested resources, such as CUSTOMER or ORDERS, in JSON. In a single primary resource, add the ID value after the data resource name, as shown:
http://myserver:9191/HS_SALES/CUSTOMER/2
The above example returns a JSON object representing a Customer with an ID of 2. For a single sub-resource, include the resource’s position in the association after its name, as shown:
http://myserver:9191/HS_SALES/CUSTOMER/2/ORDERS
http://myserver:9191/HS_SALES/CUSTOMER/2/ORDERS/2
Sub-resources must always be accessed under a single top-level resource.
For Subroutines:
U2 RESTful Web Services Help
12
In order to distinguish subroutines from data resources, the relative path of a subroutine must always begin with the word subroutine, followed by its name, as shown:
http://myserver:9191/HS_SALES/subroutine/CalculateCharge
The HTTP POST method is the only method that can be used to call a subroutine. The U2 REST server checks for the HTTP POST method on a subroutine URI before further processing occurs.
URI encoding must be applied on the resource URI in the HTTP request to U2 REST server. This is to avoid having URI-reserved delimiters in the text contained in the resource URI.
For example, if a resource ID contains any of the following characters: “:, /,?, #, &, space”
then the URI must be URI-encoded before sending the HTTP request to the U2 REST server. The U2 REST server decodes the URI to get the correct resource ID.
In the example below, the product ID contains an illegal “#” character:
http://myserver:9191/HS_SALES/CUSTOMER/Product/12#345
The U2 REST server sees the URI-reserved delimiter and decodes it using the standard %23 replacement, as shown:
http://myserver:9191/HS_SALES/CUSTOMER/Product/12%23345
U2 RESTful Web Services
13
U2 REST subroutine resources
U2 subroutines implement all of the server-side business logic of U2 applications. A subroutine must be cataloged, either locally or globally, on the U2 server and then mapped on the REST server. The resource then becomes a U2 REST subroutine resource and can be called by a service consumer. You can map a subroutine on the REST server by defining its parameters.
Subroutine parameters
You can use a subroutine parameter for input only, output only, or for both input and output purposes.
Subroutine parameters can be one of three data types: strings, dynamic arrays, or JSON. A string type is a series of characters that is enclosed in double quotes. Dynamic array parameters must reference a dynamic array definition. A dynamic array definition describes the structure of the dynamic arrays it represents. In a U2 dictionary, it does this by specifying all the fields contained in the dynamic array and also their value types and associations. The input and output JSON objects that move to and from the subroutine must be correctly formed JSON objects. It is expected that the U2 Dynamic Object (UDO) will be used to consume and present the JSON object both to and from the subroutine, which will ensure the correct JSON format is used.
Refer to UniData UniBasic Extensions for more information about the U2 Dynamic Object.
Note
If connection pooling is enabled, any change to a cataloged subroutine requires the connection pool to be restarted. It is suggested that connection pools be disabled during basic subroutine development.
HTTP POST
The HTTP POST method is the only HTTP method that can be used to call a subroutine; however, for testing purposes you can issue a GET request and will be prompted for input to execute a POST request. In a RESTful definition, you can use HTTP POST to create a resource on the server. You can also use an HTTP specification to send information to a Web server, such as submitting a Web form.
If the requested subroutine has input parameters, including parameters for both input and output purposes, the content of the HTTP POST request must contain a JSON object that includes all of the input parameters and their values. Missing input parameter values are treated as empty strings.
If the subroutine has output parameters, including parameters for both input and output purposes, the content of the HTTP response will contain a JSON object that includes all of the output parameters and their values.
Note
If you are using SSL and want to make a subroutine resource available in a new U2 RESTful web server, you must first create a dummy data resource for the RESTful service to work. This requirement is a permanent restriction of the U2 Restful web service.
U2 RESTful Web Services Help
14
Supported HTTP methods
U2 REST supported HTTP methods
U2 REST supports four HTTP methods: GET (read), PUT (update), POST (create or call subroutine), and DELETE (delete).
The PUT, POST, and DELETE methods can only be used on a single data resource, not a collection. U2 RESTful Web Services does not support batch operations, which groups multiple requests into one HTTP POST request.
U2 RESTful Web Services
15
HTTP GET
The HTTP GET method can only be used on U2 REST data resources.
The following example illustrates a typical BASIC CallHTTP GET request. The request calls the U2 REST server using a GET statement, and then returns a customer record based on the requested CUSTID:
logfile = "restget" stat = protocolLogging(logfile, "ON", 10) PRINT "WHICH CUSTOMER record ID would you like to GET?" INPUT CUSTID * * URL returned as html or json data * url="http://den-l-nk01.rocketsoftware.com:9191/HS_SALES/Customer/":CUSTID:"?tohtml= true" url="http://den-l-nk01.rocketsoftware.com:9191/HS_SALES/Customer/":CUSTID method="GET" * stat = setHTTPDefault("VERSION", "1.1") stat = createRequest(url, method, restGET) stat = setRequestHeader(restGET, "Content-Type", "application/json;charset=utf-8") stat = submitRequest(restGET, 5000, "", Header, restData, httpStatus) * GET response parser restData=CHANGE(restData, "{", "{":CHAR(10)) restData=CHANGE(restData, ",", ",":CHAR(10)) restData=CHANGE(restData, "}", "}":CHAR(10)) * PRINT "Response status: ":httpStatus PRINT "Response headers:":Header PRINT "Response data:":CHAR(10):restData * a = protocolLogging(logfile, "OFF", 10) END
In the above example, we call our HTTP functions to perform the HTTP GET request. We then create a simple parser for display purposes. The output of our GET request, which displays the information for CUSTID 2, is shown below:
{ @uri: http://den-l-aw03:9191/HS_SALES/Customer/2?tohtml=true statename: "Massachusetts" state: "MA" u2version: "8258654354592452458" fname: "Diana" city: "Waltham" lname: "Morris" sal: "Ms." phone: "(617)555-9823" fulladdr: "431 Third Ave." custid: "2" fullname: "Ms. Diana Morris" addr1: "431 Third Ave." ... }
U2 RESTful Web Services Help
16
Data Selection, Sorting, and Paging with HTTP GET
Different query strings can be specified on a URI using the HTTP GET method to shape or alter the return results.
Note: All HTTP GET query string keywords, such as select, sort, field, etc., must be made using lowercase commands.
Selection
U2 query conditions can be specified on a primary REST data resource to limit the return results to only those that meet the conditions, as shown in the examples below:
http://myserver:9191/HS_SALES/Customer?select=ZIP="01382" &tohtml=true http://myserver:9191/HS_SALES/Customer?select=ZIP="01382" AND fname LIKE "S..."&tohtml=true
http://myserver:9191/HS_SALES/Customer?select=ZIP="01382""75201" "80202"
U2 query SORT expressions (except BY.EXP and BY.EXP.DSND) can be applied on top-level REST data resources to put the return results in certain order, as shown in the examples below:
http://myserver:9191/HS_SALES/Customer?sort=BY fname
http://myserver:9191/HS_SALES/Customer?select=fname LIKE “D...”&sort=BY.DSND LNAME&tohtml=true
In order for these query strings to work, the query itself must follow the uQuery conventions for the account. The selection attributes must follow the dictionary conventions, including case.
Note
We recommend that you always surround your selection criteria with quotation marks. Although quotation marks are not required, under certain circumstances, particularly when you have spaces or wildcard characters, unpredictable results may occur if quotation marks are not used.
Projection
Projection limits the return results on a data resource to only a few specified fields, instead of all of them, as shown below:
http://myserver:9191/HS_SALES/Customer?fields=lname, fname
U2 RESTful Web Services
17
Paging
Two sets of query string parameters can be used to specify the desired starting position and the size of data returned, described in the examples below. In the first example, we use the pageno and pagesize parameters to specify that the default page size is 20 and the minimum pageno is 1, as shown:
http://myserver:9191/HS_SALES/Customer?pageno=3&pagesize=20
In this next example, we use the start and max parameters to specify that the default start value is 0, and the default max value is 20, as shown:
http://myserver:9191/HS_SALES/Customer?start=0&max=20
Detail level
The detail_level query string parameter is used to determine the level of nesting in a query. U2 REST supports the detail_level parameter, and uses it to expand or collapse the return results. The value of the detail_level is either 1, 2, or 3. The default value is 3. Each value is described in the following table:
detail_level Description
1 Top-level resources in the query.
2 Top-level, multivalue resources in the query.
3 Top-level, multivalue, multi-subvalue resources in the query.
In the following example, the detail_level is set to 3, as shown:
http://myserver:9191/HS_SALES/Customer/2?detail_level=3
The query then returns all the data, including the multi-subvalue information and the Orders information nested within the order _list association:
{ @uri: http://den-l-aw03.rocketsoftware.com:9191/HS_SALES/Customer/2?detail%5Flevel=3&tohtml=true company: "Fast Copy Center" zip: "01133" addr2: "" addr1: "431 Third Ave." -orders_list: { @uri: http://den-l-aw03.rocketsoftware.com:9191/HS_SALES/Customer/2/Orders -Orders: [ -{ @uri: http://den-l-aw03.rocketsoftware.com:9191/HS_SALES/Customer/2/Orders/1 list_price: "$6,890" ser_num: "600782"
U2 RESTful Web Services Help
18
svc_price: "$900" svc_start: "01/13/91" u2version: "8258654354592452458" paid_date: "02/05/91" buy_date: "01/08/91" description: "Moderate duty, entry level, color copier" svc_end: "01/15/92" svc_paid_date: "02/05/91" prodid: "C2000" price: "$6,600" discount: "4.2" } -{ @uri: http://den-l-aw03.rocketsoftware.com:9191/HS_SALES/Customer/2/Orders/2 list_price: "$12,990" ser_num: "700422" svc_price: "$500" svc_start: "01/13/91" u2version: "8258654354592452458" paid_date: "02/05/91" buy_date: "01/08/91" description: "Heavy duty monochrome copier" svc_end: "06/12/91" svc_paid_date: "02/05/91" prodid: "M3000" price: "$12,000" discount: "7.6" } -{ @uri: http://den-l-aw03.rocketsoftware.com:9191/HS_SALES/Customer/2/Orders/3 list_price: "$1,990" ser_num: "101456" svc_price: "$150" svc_start: "01/13/91" u2version: "8258654354592452458" paid_date: "02/12/91" buy_date: "01/22/91" description: "Sorting attachment for M3000/C3000" svc_end: "01/15/92" svc_paid_date: "02/12/91" prodid: "S3000" price: "$900" discount: "54.8" } ] } fullname: "Ms. Diana Morris" custid: "2" fulladdr: "431 Third Ave." phone: "(617)555-9823" sal: "Ms." city: "Waltham" lname: "Morris" fname: "Diana" u2version: "8258654354592452458" state: "MA" statename: "Massachusetts" }
If we change the URI in the above HTTP GET request to detail_level = 1,
http://myserver:9191/HS_SALES/Customer/2?detail_level=1
U2 RESTful Web Services
19
we see a much smaller result set that includes only the top-level field values and references, as shown:
@uri: http://den-l-aw03.rocketsoftware.com:9191/HS_SALES/Customer/2?detail%5Flevel=1&tohtml=true company: "Fast Copy Center" zip: "01133" addr2: "" addr1: "431 Third Ave." -orders_list: { @uri: http://den-l-aw03.rocketsoftware.com:9191/HS_SALES/Customer/2/Orders } fullname: "Ms. Diana Morris" custid: "2" fulladdr: "431 Third Ave." phone: "(617)555-9823" sal: "Ms." city: "Waltham" lname: "Morris" fname: "Diana" u2version: "8258654354592452458" state: "MA" statename: "Massachusetts" }
U2 RESTful Web Services Help
20
HTTP POST
The HTTP POST method is used to create a new data record or to call a BASIC subroutine. The following example demonstrates how to use the BASIC CallHTTP POST request. In this program, we call the U2REST server using an HTTP POST request. The request uses postData information to create a new record based on the CUSTID parameter. An HTTP GET request automatically runs when the request completes.
* logfile="restpost" url="http://den-l-nk01.rocketsoftware.com:9191/HS_SALES/Customer" * method="POST" * stat = protocolLogging(logfile, "ON", 10) stat = setHTTPDefault("VERSION", "1.1") * * postData json record * PRINT "Enter Unique Customer ID to create: " INPUT CUSTID * * Customer Record to be written to record CUSTID * postData="" postDATA='{' postDATA:=' "statename" : "Colorado",' postDATA:=' "state" : "CO",' postDATA:=' "fname" : "Neddy",' postDATA:=' "city" : "Denver",' postDATA:=' "lname" : "Seagoon",' postDATA:=' "sal" : "Mr.",' postDATA:=' "phone" : "8007293553",' postDATA:=' "custid" : "':CUSTID:'",' postDATA:=' "addr1" : "4700 South Syracuse Street",' postDATA:=' "addr2" : "",' postDATA:=' "zip" : "80237",' postDATA:=' "company" : "IBM Corporation."' postDATA:='}' * CRT stat = createRequest(url, method, restPOST) stat = setRequestHeader(restPOST, "Content-Type", "application/json; charset=utf-8") stat = submitRequest(restPOST, 5000, postDATA, Header, restData, httpStatus) * POST response restData=CHANGE(restData, "{", "{":CHAR(10)) restData=CHANGE(restData, ",", ",":CHAR(10)) restData=CHANGE(restData, "}", "}":CHAR(10)) PRINT "Response status: ":httpStatus PRINT "Response headers:":Header PRINT "Response data:":CHAR(10):restData * stat = protocolLogging(logfile, "OFF", 10) restPOST="" END
Using HTTP POST to call a subroutine resource
An HTTP POST request must point to the resource URI when it is used to call a subroutine.
U2 RESTful Web Services
21
The body of the HTTP POST request must include one unnamed JSON object that includes all the input parameters and their values. If the subroutine has output parameters, the U2 REST server sends back an HTTP response whose body contains an unnamed JSON object that encompass all of the output parameters and their values.
The following example illustrates how to use HTTP POST to call a locally cataloged subroutine:
a = protocolLogging("httpreq.log", "ON", 10) * call the REST subroutine service with HTTP POST url="http://DEN-L-AW01.rocketsoftware.com:9191/HS_SALES/subroutine/CUSTOMERSUB" method="POST" a = setHTTPDefault("VERSION", "1.1") a = createRequest(url, method, req4) a = setRequestHeader(req4, "Content-Type", "application/json; charset=utf-8") postData = '{"id":"2"}' Header = "" Data = "" httpStatus = "" a = submitRequest(req4, 5000, postData, Header, Data, httpStatus) * response PRINT "Response status: ":httpStatus PRINT "Response headers:":Header PRINT "Length of response data:":LEN(Data) PRINT "Response Data:":Data UV BASIC Subroutine - SUBROUTINE CUSTOMERSUB (ID, REC) OPEN "CUSTOMER" TO F.CUSTOMER ELSE REC = "" END READ REC FROM F.CUSTOMER, ID ELSE REC = "" END CLOSE F.CUSTOMER RETURN
U2 RESTful Web Services Help
22
HTTP PUT
The HTTP PUT method is used to update a single data resource. In order to update a U2 REST data resource, a client program must read the resource first. It does this by issuing an HTTP GET request to the U2 REST server.
To meet the optimistic locking requirement of U2REST, an HTTP PUT request must include the If-Match field in the HTTP header. The value of the If-Match field is the value of the u2version name/value pair in the HTTP GET response.The client program sends the changed data fields with an HTTP PUT request to the U2 REST server to persist the changes.
If the data resource has changed since the client program performed the HTTP GET request, then an HTTP 412 error is returned, indicating that optimistic locking failed and the update was terminated.
If a data resource contains collections of subresources, such as the orders_list association, changes to the sub-resources are ignored. A client program must modify each of the subresources individually, using an HTTP PUT method. Refer to the section on detail_level for more information.
After the data resource is updated, the U2 REST server returns an HTTP 200 OK response, with a JSON object representing the updated data resource.
The following example shows a BASIC CallHTTPGET/PUT combination being used to update a resource. A GET request executes to retrieve the contents of the u2version parameter, which is the record’s LastUpdate ID of the record. The client program then calls the U2 REST server with an HTTP PUT request, using the postData information to modify an existing record based on the CUSTID parameter. The value of the u2version parameter must be used in the If-Match HTTP header.
logfil="restput" a = protocolLogging(logfil, "ON", 10) * method="GET" * EXECUTE "CLS" EXECUTE "LIST CUSTOMER CUSTID" CRT PRINT "Which ID would you like to Update?" INPUT CUSTID url="http://den-l-nk01.rocketsoftware.com:9191/HS_SALES/Customer/":CUSTID * stat = setHTTPDefault("VERSION", "1.1") stat = createRequest(url, method, restGET) stat = setRequestHeader(restGET, "Content-Type", "application/json;charset=utf-8") * stat = submitRequest(restGET, 5000, "", Header, restData, httpStatus) * response PRINT "Response status: ":httpStatus PRINT "Response headers:":Header PRINT "Response data:":restData * * Get Data Record u2version ID * MYSTRING = CHANGE(restData, '"u2version"', @AM ) U2VERSION = FIELD(MYSTRING<2>, '"', 2) *
U2 RESTful Web Services
23
putData="" putDATA='{' putDATA:=' "statename" : "Colorado",' putDATA:=' "state" : "CO",' putDATA:=' "fname" : "Neddy",' putDATA:=' "city" : "Denver",' putDATA:=' "lname" : "Seagoon",' putDATA:=' "sal" : "Ms.",' putDATA:=' "phone" : "(800)729-3553",' putDATA:=' "custid" : "':CUSTID:'",' putDATA:=' "addr1" : "4600 South Ulster Street.",' putDATA:=' "addr2" : "",' putDATA:=' "zip" : "80237",' putDATA:=' "company" : "Rocket Software, Inc."' putDATA:='}' * * call the REST subroutine service with HTTP POST url="http://den-l-nk01:9191/HS_SALES/Customer/":CUSTID method="PUT" * stat = createRequest(url, method, restPUT) stat = setRequestHeader(restPUT, "Content-Type", "application/json; charset=utf-8") stat = setRequestHeader(restPUT, "If-Match", U2VERSION) * stat = submitRequest(restPUT, 5000, putDATA, Header, restData, httpStatus) * put response restData=CHANGE(restData, "{", "{":CHAR(10)) restData=CHANGE(restData, ",", ",":CHAR(10)) restData=CHANGE(restData, "}", "}":CHAR(10)) PRINT "Response status: ":httpStatus PRINT "Response headers:":Header PRINT "Response data:":CHAR(10):restData a = protocolLogging(logfil, "OFF", 10) END
U2 RESTful Web Services Help
24
HTTP DELETE
The HTTP DELETE method is used to delete a single data record. In order to delete a U2 REST data record, a client program must first read the record by issuing an HTTP GET request to the U2 REST server.
To meet the optimistic locking requirement of U2REST, an HTTP DELETE request must include the If-Match field in the HTTP header. The value of the If-Match field is the value of the u2version name/value pair in the HTTP GET response. The client program sends an HTTP DELETE request to the U2 REST server to persist the changes.
If the data resource has changed since it was last read, then an HTTP 412 error is sent to the client indicating that optimistic locking failed and that the delete operation aborted.
The following example demonstrates how to use the BASIC CallHTTP DELETE function in U2 REST. An HTTP GET request is called first, followed by the HTTP DELETE request. An existing RECORD ID record, based on the CUSTID parameter, is deleted. The value for the u2version parameter must be used in the If-Match HTTP DELETE header.
* logfile = "restdelete" a = protocolLogging(logfile, "ON", 10) * EXECUTE "CLS" EXECUTE "LIST CUSTOMER CUSTID" CRT PRINT "WHICH ID WOULD YOU LIKE TO DELETE?" INPUT CUSTID * url="http://den-l-nk01.rocketsoftware.com:9191/HS_SALES/Customer/":CUSTID method="GET" * stat = setHTTPDefault("VERSION", "1.1") stat = createRequest(url, method, restGET) stat = setRequestHeader(restGET, "Content-Type", "application/json;charset=utf-8") * a = submitRequest(restGET, 5000, "", Header, restData, httpStatus) * GET response restData=CHANGE(restData, "{", "{":CHAR(10)) restData=CHANGE(restData, ",", ",":CHAR(10)) restData=CHANGE(restData, "}", "}":CHAR(10)) * PRINT "Response status: ":httpStatus PRINT "Response headers:":Header PRINT "Response data:":restData * * Get Data Record u2version ID * MYSTRING = CHANGE(restData, '"u2version"', @AM ) U2VERSION = FIELD(MYSTRING<2>, '"', 2) * * call the REST subroutine service with HTTP POST url="http://den-l-nk01.rocketsoftware.com:9191/HS_SALES/Customer/":CUSTID method="DELETE" * stat = createRequest(url, method, restDELETE) stat = setRequestHeader(restDELETE, "Content-Type", "application/json; charset=utf-8") stat = setRequestHeader(restDELETE, "If-Match", U2VERSION) stat = submitRequest(restDELETE, 5000, "", Header, restData,| httpStatus) * DELETE response
U2 RESTful Web Services
25
* PRINT "Response status: ":httpStatus * PRINT "Response headers:":Header * PRINT "Response data:":CHAR(10):restData * stat = protocolLogging(logfile, "OFF", 10) END
U2 RESTful Web Services Help
26
U2 REST connection pooling support
The U2 REST server, by default, is configured to use connection pooling when making connections to a U2 database. Connection pooling is highly recommended because it improves both performance and scalability, both of which are vital in a Web environment. Connection pooling is an optional configuration and can be turned off on a REST server in the U2 RESTful Web Services Developer.
When connection pooling is turned on, the U2 REST server sets up connection pooling via a UOJ connection and relies on UOJ to manage the connection pools.
Because UOJ connection pools are process-based, there is no connection pool sharing between different U2 REST servers, even if they are on the same machine, as each runs in a separate Java runtime process. Connection pooling can only be utilized at the REST-server level only. Individual resource folders cannot be configured to use connection pooling.
U2 RESTful Web Services
27
U2 REST transaction support
U2 REST does not support running transactions across multiple HTTP requests. This means a user cannot group a set of REST requests (operations) together into one single transaction.
Optimistic concurrency control
U2 REST implements optimistic locking to prevent concurrent updates to the same data. Optimistic locking is a means of ensuring that no locks are put on a resource when it is read. However, when changes to the resource are ready to be written back, U2 REST first locks it and then checks to see if the resource has been changed since it was first read. If a change occurs, an optimistic locking violation error is thrown.
Since changes (including update, delete, and create requests) are generally much less frequent than reads, this technique improves performance and scalability, while at the same time guaranteeing data consistency.
The u2version field
The u2version field holds a calculated value when a data resource is read and sent back to the client as a name/value pair. When the client wants to make a change to the resource, the HTTP PUT or HTTP DELETE request must include the original u2version value in the If-Match HTTP header field. The U2 REST server uses this value to check against the current data on the U2 server. If they match, it allows the update or delete request to be processed; otherwise, it sends back an HTTP 412 error indicating an optimistic locking violation error has occurred. At this time, the client must re-read the data and try the update again.
A data resource shares the same u2version value with all of its sub-resources. Thus, when you update a sub resource, even though it may not have changed since first read, if the top-level resource or any of its sub-resources has changed, the update fails. The same process is true for a top-level resource.
Transactions in subroutines
U2 database server supports traditional ACID transactions. A U2 REST-based application can carry out transactions by putting them in the subroutines and enabling the client to call these subroutines. The only requirement is that a top-level transaction must be completely embedded within a single subroutine because of the non-persistent database connection model of U2REST.
28
U2 RESTful Web Services Developer
The U2 RESTful Web Services Developer (U2RSD) is an Eclipse-based IDE that includes a number of views, which allow users to easily connect to U2 data servers, create and manage U2 REST server instances, and define U2 REST resources on the REST servers.
U2RSD makes use of the U2JPA Eclipse plug-in to map U2 data files to U2JPA entities, which are the underlying objects for U2 REST resources. It also includes a U2 subroutine resource wizard, which creates U2 subroutine resources on the REST server. The subroutine is then implemented as a U2JPA native query.
The following figure shows the default U2 RESTful Web Services Developer perspective:
U2 RESTful Web Services Developer
29
Available views in the developer
U2 Resource view
The U2 Resource view contains information about each U2 account on the server to which you are connected. This information includes accounts, data files, dictionary files, UniBasic programs, UniVerse BASIC programs, XML/DB mapping files, and cataloged programs.
The following figure shows the U2 Resource information for the HS.SALES account:
Right-click on any of the nodes in this view to see the different options available to each node, including Open Dictionary.
U2 RESTful Web Services Help
30
U2 REST servers view
The U2 REST servers view contains information about each REST server and resource that you create. You can manage you RESTful servers, resources, and subroutine services from within this view. The following example illustrates the U2 REST information about the MyRestServer server:
When you create a new resource or subroutine service within the RESTful Developer, it appears in the RESTful Servers view. All data files are grouped under the Data Resources node. Subroutines are grouped under the Subroutine Resources node, with dynamic arrays nested together within Subroutine Resources under the Dynamic Array Definitions node.
Right-click on any of the nodes in this pane to view the different options available to each node.
To start a REST server, for example, right-click your RESTful server and select Start REST Server. You can also double-click any of the data resources in your REST server to test the service in the Test Browser. If the REST server is not running, double-click the resource to start the REST server.
U2 RESTful Web Services Developer
31
Properties view
The Properties view displays the properties defined for each file, account, program, server, and resource available. The following example illustrates the properties of HS_SALES folder, highlighted in the U2 Resource view:
Select a node in any of the views to see the properties for that node.
U2 RESTful Web Services Help
32
U2 Dictionary view
The U2 Dictionary view displays the dictionary information about the database files in the U2 Resource view. You can see data source information and view the structure of the file system from within this view. The following example illustrates how the CUSTOMER file displays in the U2 Dictionary view:
U2 RESTful Web Services Developer
33
U2 REST server log view
The Server Log view displays the logging details about your Web services. To enable the debug log when the server is running, right-click the REST server and then select Turn On REST Server Debug, as shown in the following example:
You can also turn logging on by changing the Debug Log option in the RESTful server properties. If you select true, the U2 RESTful Web Services Developer starts the debug log each time you start the server. You can only make this change when the server is not running.
To disable the debug log when the server is running, right-click the REST server and then select Turn Off REST Server Debug.
To view a REST server log, in the U2 REST Servers view, click the REST server.
U2 RESTful Web Services Help
34
Establishing server connections
U2 server definitions
To work with UniData or UniVerse accounts and data, you must enable your computer to connect to the server on which the accounts and data reside. Your computer (the client) requires a U2 server definition to make a connection with the server.
A U2 server definition is stored on the client computer on which it was created, and is not shared across a network. One or several users can create multiple U2 server definitions on the same client computer.
U2 server is the term for a defined connection to a server computer on which U2 accounts and data are stored. All existing U2 servers on the client computer are listed in the U2 Resource view. You can connect to any U2 server that is listed in the U2 Resource view.
U2 RESTful Web Services Developer
35
Creating U2 server definitions
To administer UniData or UniVerse accounts and data, you must create a U2 server definition that enables your computer to connect to the U2 data server on which the accounts and data are stored.
Procedure
1. Start U2 MDM by clicking Start > All Programs > Rocket U2 > U2 Metadata Manager.
2. Right-click the U2 Servers node in the U2 Resource view, and click New U2 Server.
3. In the Name field, enter a unique name to identify the U2 server definition. The name cannot contain a slash (/) or backslash (\) character.
4. In the Host field, enter the name or IP address of the computer on which UniData or UniVerse is running.
5. From the U2 data server options, select UniData or UniVerse.
6. Optional. To view or edit the protocol, port number, and other advanced settings defining the connection, click Advanced. See Viewing or editing advanced settings of a U2 server definition.
7. To save the U2 server definition, click Finish.
Result
U2 Metadata Manager creates a directory for the U2 server, registering the server definition so the tool can find it in future sessions. The name of the new U2 server is added to the list in the U2 Resource view.
Next step
Connecting to U2 servers
U2 RESTful Web Services Help
36
Editing U2 server definitions
You can modify the details of an existing U2 server definition, except for the name of the U2 server. However, you can create the U2 server again using a new name.
Prerequisite
Creating U2 server definitions
Procedure
1. Start U2 MDM by clicking Start > All Programs > Rocket U2 > U2 Metadata Manager.
2. Right-click the name of the U2 server definition in the U2 Resource view, and click Properties.
3. In the Host field, enter the name or IP address of the computer on which UniData or UniVerse is running.
4. From the U2 data server options, select UniData or UniVerse.
5. Optional. To view or edit the protocol, port number, and other advanced settings defining the connection, click Advanced. See Viewing or editing advanced settings of a U2 server definition.
Tip: The default values for advanced settings work best in most situations. Alter these settings only if necessary.
5. To save your changes to the U2 server definition, click Finish.
U2 RESTful Web Services Developer
37
Viewing or editing advanced settings
Viewing or editing the advanced settings of a U2 server definition
On the advanced settings page of the server definition, you can view or edit the protocol, port number, and other advanced settings that define the connection. You can also specify commands to run when you connect to the U2 server. The default values for advanced settings work best in most situations. Alter these settings only if necessary.
Prerequisite Creating U2 server definitions or Editing U2 server definitions
Procedure 1. Click Advanced on the U2 Server Definitions page.
2. The Protocol Type field displays TCP/IP as the communications protocol used by the UniData or UniVerse to access the Internet. At this time, the only supported protocol is TCP/IP, and this setting cannot be changed.
3. In the RPC Port # field, enter the port number of the UniRPC server running on the host. The default port number is 31438.
4. In the RPC Service Name field, enter the name of the remote procedure call (RPC) service on your system. For UniData, the name is normally udcs; for UniVerse, the name is normally uvcs.
5. In the Login Account field, enter the full path to the account folder on the server running UniData or UniVerse. You can enter just the account name if the account is defined in the UD.ACCOUNT or UV.ACCOUNT hash file.
6. If you run a RetrieVe command, a saved paragraph, or a globally cataloged program every time you connect to the U2 server, you can save time by entering the command in the U2 server definition. To enter a command to run on connection, click Add in the Commands to Execute group box. See Specifying a command to run on connection.
7. In the Specify the session to run/debug your BASIC program on server side group box, enter details for connecting to the server in a debug session.
a. From the Protocol options, select the network protocol to use when you connect to the U2 server in a debug session: Telnet or SSH (Secure Shell).
b. In the Port Number field, enter the port number on which the Telnet or SSH service runs on the server. The default Telnet port number is 23; the default SSH port number is 22.
c. If device licensing is supported on the server, select the Use Device License check box to conserve license usage in your debug session.
While running or debugging BASIC programs, you can use multiple server connections to browse files, check data, update records, or perform other tasks. If device licensing is not enabled, your debug session consumes one U2 license for each connection. With device licensing enabled, your session consumes one U2 license and one device license for up to 10 connections from a single device.
U2 RESTful Web Services Help
38
Tip: If you cannot establish a Telnet or SSH connection with the Use Device License check box selected, clear the check box and try again.
7. To save any changes to advanced settings and return to the main page, click Finish.
U2 RESTful Web Services Developer
39
Specifying a command to run on connection
You can save time when connecting to the U2 server by specifying a RetrieVE command, the name of a saved paragraph, or the name of a globally cataloged program in the U2 server definition.
Prerequisite Viewing or editing advanced settings of a U2 server definition
Procedure 1. While still on the Advanced Settings page, in the Specify a command field,
enter a RetrieVe command, the name of a saved paragraph, or the name of a globally cataloged program to run when you connect to the U2 server.
2. To save your changes and return to the details page, click OK.
U2 RESTful Web Services Help
40
Viewing or editing the advanced settings of a U2 server definition
On the advanced settings page of the server definition, you can view or edit the protocol, port number, and other advanced settings that define the connection. You can also specify commands to run when you connect to the U2 server. The default values for advanced settings work best in most situations. Alter these settings only if necessary.
Prerequisite Creating U2 server definitions or Editing U2 server definitions
Procedure 1. Click Advanced on the U2 Server Definitions page.
2. The Protocol Type field displays TCP/IP as the communications protocol used by the UniData or UniVerse to access the Internet. At this time, the only supported protocol is TCP/IP, and this setting cannot be changed.
3. In the RPC Port # field, enter the port number of the UniRPC server running on the host. The default port number is 31438.
4. In the RPC Service Name field, enter the name of the remote procedure call (RPC) service on your system. For UniData, the name is normally udcs; for UniVerse, the name is normally uvcs.
5. In the Login Account field, enter the full path to the account folder on the server running UniData or UniVerse. You can enter just the account name if the account is defined in the UD.ACCOUNT or UV.ACCOUNT hash file.
6. If you run a RetrieVe command, a saved paragraph, or a globally cataloged program every time you connect to the U2 server, you can save time by entering the command in the U2 server definition. To enter a command to run on connection, click Add in the Commands to Execute group box. See Specifying a command to run on connection.
7. In the Specify the session to run/debug your BASIC program on server side group box, enter details for connecting to the server in a debug session.
a. From the Protocol options, select the network protocol to use when you connect to the U2 server in a debug session: Telnet or SSH (Secure Shell).
b. In the Port Number field, enter the port number on which the Telnet or SSH service runs on the server. The default Telnet port number is 23; the default SSH port number is 22.
c. If device licensing is supported on the server, select the Use Device License check box to conserve license usage in your debug session.
While running or debugging BASIC programs, you can use multiple server connections to browse files, check data, update records, or perform other tasks. If device licensing is not enabled, your debug session consumes one U2 license for each connection. With device licensing enabled, your session consumes one U2 license and one device license for up to 10 connections from a single device.
Tip: If you cannot establish a Telnet or SSH connection with the Use Device License check box selected, clear the check box and try again.
U2 RESTful Web Services Developer
41
7. To save any changes to advanced settings and return to the main page, click Finish.
U2 RESTful Web Services Help
42
Specifying a command to run on connection
You can save time when connecting to the U2 server by specifying a RetrieVE command, the name of a saved paragraph, or the name of a globally cataloged program in the U2 server definition.
Prerequisite Viewing or editing advanced settings of a U2 server definition
Procedure 1. While still on the Advanced Settings page, in the Specify a command field,
enter a RetrieVe command, the name of a saved paragraph, or the name of a globally cataloged program to run when you connect to the U2 server.
2. To save your changes and return to the details page, click OK.
U2 RESTful Web Services Developer
43
Connecting to U2 servers
You must open a U2 server connection to work with the accounts stored on the associated UniData or UniVerse (U2) data server computer. You can connect to any U2 server that is listed in the U2 Resource view. If the U2 server is not listed, you can create a server definition that adds a new server to the view.
Prerequisite
Creating U2 server definitions
Procedure
1. Start U2 MDM by clicking Start > All Programs > Rocket U2 > U2 Metadata Manager.
2. Double-click the name of the U2 server in the U2 Resource view.
3. In the User ID field, enter your administrator user name or the user name of a valid user on the server computer running UniData or UniVerse.
4. In the Password field, enter the password for the administrator or user on the server computer.
5. To store the password for future connections, select the Remember me check box. With this check box selected, Microsoft Windows stores the encrypted password on the client computer.
6. If you are using a proxy server, select the Use Proxy Server check box.
a. In the Proxy Host field, enter the name or IP address of the computer on which the proxy server is running.
b. In the Proxy Port field, enter the number of the port on which the proxy server listens for communication from UniData or UniVerse.
6. To connect to the U2 server, click Connect.
Result
When the connection is established, the U2 Resource view displays a tree view of the U2 accounts and catalog programs on the U2 data server to which you are connected.
U2 RESTful Web Services Help
44
Disconnecting from U2 servers
After completing tasks for a U2 account, you can disconnect from the U2 server. Disconnecting only closes your connection to the U2 server. It does not delete the U2 server definition or remove the U2 server from the list in the U2 Resource view.
Prerequisite Connecting to U2 servers
Procedure
In the U2 Resource view, right-click the name of the U2 server from which you want to disconnect, and click Disconnect.
U2 RESTful Web Services Developer
45
Deleting U2 server definitions
If you no longer require access to the U2 accounts and catalog programs on a U2 data server, you can delete the associated U2 server definition. It is not possible to change the name of an existing U2 server. However, you can delete the U2 server definition and create it again using a new name.
Prerequisite Creating new U2 servers
Procedure In the U2 Resource view, right-click the name of the U2 server definition that you want to delete, and click Delete.
Result The name of the U2 server and folders for its U2 accounts and catalog programs are removed from the list in the U2 Resource view.
46
U2 REST security
U2 REST provides two methods of security for a RESTful Web project: communication security via a Secure Sockets Layer (SSL), and user authentication and authorization (Digest or Basic).
On Digest authentication, U2 REST server enforces a qop=auth quality of protection value. Therefore, your client software must support qop=auth. Refer to RFC-2617 for more information.
Communication security
U2 REST supports SSL connections between the U2 REST server and its clients. It also supports connections between the U2 REST server and the U2 database server. For instructions on how to set up and use SSL with U2, refer to the UniData Security Features manual or the UniVerse Security Features manual.
Secure client HTTPS connections
When a U2 RESTful service is SSL enabled, the server connection and all of the resources under it are changed from an HTTP connection to a secure HTTPS connection.
Secure U2 RESTful services are enabled using the U2 RESTful Web Services Developer. Secure U2 database connections
You can create secure connections between the U2 REST server and the U2 database server.
1. Enable the U2 database server for SSL connection using UniAdmin to secure the UOJ service connection (uvcs or udcs).
2. Install the U2 database server certificates in the U2 REST server’s keystore file. The JRE directory is located, by default, in the following location: $INSTALL_DIR/jre/jre/lib/security/cacerts You can use tools such as Java keytool, the Java key and certificate management tool, to create and maintain the JRE. The keytool utility is installed with Oracle’s JDK.
3. Check the SSL property on the resource folder inside U2 RESTful Web Services Developer
Note
For information on how to set up and use SSL with U2, refer to the UniData Security Features manual or the UniVerse Security Features manual. For more information on the Java keytool, see: http://download.oracle.com/javase/6/docs/technotes/tools/windows/keytool.html
U2 REST security
47
User authentication and authorization
U2 REST makes use of the Jetty HTTP server’s role-based user authentication and authorization to provide secure access to the web services. This allows you to manage how and by whom different files are accessed.
User authorization
User authorization, or user access control (UAC), is used to determine whether a user with the correct credentials is allowed to access a specific U2 REST resource. This is done by restricting access of certain resources to a set of roles. For example, only users who are in the HR role can access the resources under the resource folder “Human Resources”.
In U2 REST, such restrictions are specified as a set of access control rules. Each rule has three parts:
• A URI. This can be the URI of a REST server, a resource folder, a top-level data resource, or a subroutine resource. This rule applies to this URI.
• A set of HTTP methods. These are the operations that can be performed on the resource in the URI, or the resources under the URI if it points to a resource container such as a REST server or resource folder.
• A set of roles that define who is allowed to perform the operations defined on the resources.
When multiple rules can be applied to an HTTP request, the most specific rule is applied.
For example, the following table has three access control rules:
Rule URI HTTP method Roles
1 /* * Any
2 /xdemo/Product POST, PUT, DELETE Admin
3 /xdemo/Member * Admin, Sales, Service
In this example, both rule 1 and rule 2 can be applied to an HTTP POST request to /xdemo/Product. However, rule 2 is the one applied because it dictates that only the user defined as Admin can modify Product resources.
If no access control rules are applied to an HTTP request, it will be served by U2 REST server. There is no validation.
User authentication
You can control access to various accounts by defining a user ID and password for each user. Each user ID must also be assigned one or more user role.
User roles are defined by grouping a set of user privileges together, and then giving that group a meaningful name, such as Administrator or Guest. After you define a user role, you can assign each role(s) to a user ID. Multiple user IDs can be assigned to the same
U2 RESTful Web Services Help
48
user role. This allows you to quickly and easily change the privileges for all users assigned to a specific user role simultaneously.
U2 REST security
49
Authorizing a user
You can restrict access to certain resources by authorizing levels of access defined by various job roles, such as an administrator role or an HR role.
Procedure
1. Right-click the U2 REST server connection from the U2 REST server view. Select Access Control Setup from the U2RSD menu, as shown:
When you select the Access Control Setup menu option, the Define Access Control dialog box opens:
2. Click Add. The Add New Access Constraint dialog box opens:
U2 RESTful Web Services Help
50
3. Expand the navigation tree in the Path field and select the location for which you are creating a user role. In our example, we choose the TestServer file, as shown:
When you select a location, the directory path appears in the Path text box.
4. Select the privileges that will be available to the user role you are defining by checking the appropriate Methods check boxes. You can choose one or more methods, or you can select All to grant full privileges to the user.
U2 REST security
51
Click Finish. Focus returns to the Developer.
5. After you define the privileges you want to assign for a given role, you need to define that role. To select a role, choose an existing role from the list of available roles. If there are no roles defined yet, or if you need to create a new role, click Add Role.
U2 RESTful Web Services Help
52
Authenticating a user
You can control access to various accounts by defining a user ID and password for each user. Each user ID must also be assigned one or more user role.
Procedure
1. Right-click the U2 REST server connection from the U2 REST server view. Select Define HTTP Users from the U2RSD menu. The Define HTTP Users dialog box opens, as shown:
2. Click Add to define a new user role. The Add New HTTP User dialog box opens.
U2 REST security
53
Enter the correct user information, as described below:
• In the User Name field, enter the correct user name.
• In the Password field, enter the password.
• In the Confirm Password field, reenter the password.
• In the Roles field, select the appropriate user role from the list.
To select multiple user roles for a specific user, hold down the Ctrl while selecting the appropriate roles from the list.
3. When you are finished, click OK. Focus returns to the HTTP Users dialog box. If you are satisfied with your user definitions, click Finish. Focus returns to the Developer.
54
SB+ and RESTful web services
Accessing SB+ files
You can view and manipulate your SB+ files in U2 RESTful Web Services, just as you can any other U2 files. However, you may need to complete a few extra steps to make your SB+ derived files and dynamic fields accessible. Specifically, you may need to change the SB+ configuration parameters and run the REGEN.EXP process against your SB+ files. If you are using a version prior to SB/XA v6.2, you also need to add the SB.REMOTE.DBCLIENT program to your application account.
SB+ and RESTful web services
55
Modifying SB+ parameters
When you view items in SBClient, your data is presented in a PICK-style format, as shown:
You may need to change your SB+ parameters to make your files accessible to U2 RESTful Web Services, as described in the following section.
Procedure
1. In the SB text editor, change the SB+ configuration parameters to generate I-type and D-type dictionaries, as shown in the example below:
Top of "SB.CONTROL" in "DMCONT", 45 lines, 301 characters.
*--: 34
034: ýýýýý1
*--: C//1
034: 1ýýýýý1
*--: FI
Filed "SB.CONTROL" in file "DMCONT"
2. If you want to use subroutines in your dictionary, you need to ensure the Use Subroutines in Dictionaries flag is set appropriately. If the Use Subroutines in Dictionaries flag is set to 0, change the flag to 1, as shown:
Top of "SB.CONTROL" in "DMCONT", 45 lines, 301 characters.
*--: 42
042: 0
*--: C/0/1
042: 1
U2 RESTful Web Services Help
56
*--: FI
Filed "SB.CONTROL" in file "DMCONT"
This allows you to use subroutines in your dictionaries.
SB+ and RESTful web services
57
Regenerating files
If you change the SB+ parameters, you must regenerate your files to apply the changes.
Warning: Before you run the REGEN.EXP process, make sure that you are aware of any third-party processes that may be affected. For more information about how to use REGEN.EXP, refer to the SB/XA Application Server Reference manual.
Procedure
1. Run the REGEN.EXP process on each file you want to access using U2 RESTful Web services, as shown:
You can also choose to enter ALL as the file name. This selects all files in your dictionary.
When you run the REGEN.EXP process, it regenerates your files with the parameter changes you made in the last step. The REGEN.EXP process regenerates the following:
• All SB expressions found in the SB DICT item
• The OE version of the SB DICT item
• SB expressions found in screens and reports
• All expressions found in xxDEFN
• All expressions found in xxPROCESS
You can choose to run the REGEN.EXP process against individual files or all files in a system.
When the REGEN.EXP process completes, you can view your dictionary changes in SBClient, as shown:
U2 RESTful Web Services Help
58
2. After making changes to the SB+ parameters and running the REGEN.EXP process on your files, if you are using version prior to SB/XA v6.2, you also need to add the following SB.REMOTE.DBCLIENT program to your application account:
SUBROUTINE SB.REMOTE.DBCLIENT(L.SYSID, L.USER, L.PWD, L.STATE, L.ERR) $INCLUDE DMSKELCODE COMMON $INCLUDE DMSKELCODE STANDARD.EQU * L.ERR = "" PARAM<1> = L.USER PARAM<2> = L.PWD PARAM<5> = L.STATE IF PARAM<3> = "" THEN PARAM<3> = "WHO" SYSID = L.SYSID CALL SB.REMOTE.PROCESS(PARAM) OPEN SYSID:"DEFN" TO F.DEFN ELSE CRT "COULD NOT OPEN ":SYSID:"DEFN";L.ERR = "The file ":SYSID:"DEFN was not found" RETURN
3. Compile and catalog the SB.REMOTE.DBCLIENT program in the SBDEMO account. All SB+ examples are based in this file in the TUBP folder in the SBDEMO account.
Your files can now be accessed and utilized in the U2 RESTful Web Services Developer.
59
Tutorial
Tutorial: Overview
This topic gives you step-by-step instructions on how to create a U2 RESTful Web service that includes a data resource and a subroutine resource using the U2 RESTful Web Services Developer.
Tip
The examples in this topic are written using the UniVerse HS.SALES file.
Next step
Tutorial: Creating a data resource
U2 RESTful Web Services Help
60
Tutorial: Creating a U2 server entry
Procedure
1. Start the U2 RESTful Web Services Developer, which opens in Eclipse. 2. Locate the U2 Resource view. Create a U2 server entry by right-clicking the U2
Servers option and selecting New U2 Server. 3. Provide a name for the new server in the Name field. Enter the IP address or host
name in the Host field. Define your server as either UniData or UniVerse.
In this example, select UniVerse as the server and name the server localuv and the host localhost.
You can also click Advanced if you want to customize any settings for your environment, such as selecting a different UniRPC. For this example, accept the defaults.
4. Click Finish to create the U2 server connection. Focus returns to the U2 Resource view.
5. Right-click the U2 Server you just created and then click Connect to establish a connection to the server.
6. Provide the valid login criteria for the server to which you are connecting. 7. If you do not want to enter your user ID and password in subsequent sessions, select
the Remember Me check box. 8. Click Connect.
Your U2 data files are now available in the U2 Resource View. Click the white arrow symbol to expand the nodes:
Next step
Tutorial: Creating a REST server
Tutorial
61
Tutorial: Creating a REST server
After creating a U2 server entry, you must create a RESTful hosting server in the U2 REST Servers view, which is located under the U2 Resource view. When you create a new REST server, you can either create a new entry in the RESTful server configuration file, or you can create a pointer to an existing RESTful server. The U2 REST server is used to access a U2 database server, which holds the collection of resources to which you are connecting.
Procedure
1. Right-click the U2 REST Servers view and select the New REST Server option from the menu.
2. When the New REST Server dialog box opens, enter the correct information into the fields, as described in the following table:
Field name Description
Server Name
The name of the REST server to which your web services will connect.
Note: After you create the REST server, you cannot rename it later.
URL The Uniform Resource Identifier (URL) that specifies where the resource will be available.
Port Number The port number to which your RESTful Web Service requests will connect.
Root Path Specifies the path name where your RESTful services will reside.
Debug Log Set this option to True if you want the debug log to start each time you start the server. You can only change this setting when the server is not running.
Log File Name The name of the debug log file.
Connection Pooling Select this option if you want to use connection pooling.
Max Pool Size The maximum size of the connection pool.
Min Pool Size The minimum size of the connection pool.
3. Click Next. The REST Server - Connection Security dialog box opens. If you do not want to use SSL to define your connection security at this time, simply click NEXT and continue on to step 4.
4. Select the Use SSL check box. For more information about using SSL, refer to the Using UniAdmin manual. The SSL options are now be visible. Enter the appropriate Key and Key Store information,as described in the following table:
U2 RESTful Web Services Help
62
Field name Description
Key Store Enter the full path to the key store on the local server machine, or click Browse to navigate to the key store.
Key Store Password
The password corresponding to the key store you defined in the Key Store box.
Confirm Key Store Password Confirm the Key Store password.
Key Password The encryption key password, if one exists, in the Key Password box. This is optional.
Confirm Key Password Confirm the Key password, if one exists.
5. When you are done, click Finish. Focus returns to the U2 REST Servers view.
Next step
Tutorial: Creating a resource folder
Tutorial
63
Tutorial: Creating a resource folder
After creating a REST server, you must create a resource folder for the U2 files and subroutine access definitions in the REST server. This allows the REST server to publish the resource. The resource folder holds all data resources mapped from the database account.
Procedure
1. In the U2 Resource View, locate the folder you want to make available as a RESTful Web Service. In this example, we select the HS.SALES folder.
2. Drag the HS.SALES folder onto the MyRestServer server you created in the last exercise.
3. Enter the correct user information into the fields. The following table describes the available field options:
Field name Description
Name The name of the resource folder.
U2 Data Server The name of the U2 data server to which you are connecting.
U2 Account The U2 account to which you are connecting.
UniPPC Service Name
The name of the UniRPC service. For UniData this is udcs and for UniVerse it is uvcs.
User ID The user ID for the server to which you are connecting.
Login Password The login password for the server to which you are connecting.
SSL Select this box if you want to enable SSL.
Connection Pooling
Select this box if you want to enable connection pooling.
Max Pool Size The maximum number of sessions that may be contained within the pool.
Min Pool Size The minimum number of sessions that may be contained within the pool.
Client Encoding Select the type of encoding, if any, you want to use for this web service from the Client Encoding list.
You can verify that you have connection pooling licenses on the U2 server by running confprod in UniData or uvregen in UniVerse. For UniData, refer to the UniData Commands Reference manual for more information. For UniVerse, refer to the Administering UniVerse guide the for more information.
U2 RESTful Web Services Help
64
SB+ System Id (For SB+ users only) Enter the abbreviation code, or system ID, for your SB+ System.
The SB+ fields are optional and are only required if you have SB+ activated on your database account. Refer to the SB+ manuals and the SB/XA manuals for more information on using SB+ and SB/XA systems.
SB+ User Id (For SB+ users only) Enter the user ID for the SB+ system to which you are connecting.
SB+ Password (For SB+ users only) Enter the password for the SB+ system to which you are connecting.
4. Enter a name for your resource folder. In our example, we name the folder HS.SALES. You can also change the connection information using the fields on this form. For this exercise, however, we accept all defaults.
When you enter HS.SALES as the name, it automatically changes to HS_SALES to ensure the URL is valid.
5. Click Finish. Focus returns to the U2 REST Servers view, and an HS_SALES node now appears in the U2 REST Servers view, as shown:
Next step
Tutorial: Creating a resource folder
Tutorial
65
Tutorial: Creating a data resource
After you make your data available for publication as a RESTful service, it is time to actually create your data resource.
Procedure
1. In the U2 Resource view, navigate to the file you want to use. In this example, navigate to the HS.SALES > Database Files > CUSTOMER file and then drag it into the HS_SALES folder we created in the U2 REST Servers view.
2. Select the fields that you want to include in the data resource. In this example, we choose Select All.
3. Click Next. The Change Resource Names dialog box opens, as shown:
U2 RESTful Web Services Help
66
You can change the names or descriptions of the items in the resource file. In this example, we change the Orders resource name to Order.
4. Click Finish. Focus returns to the U2 REST Servers view. You now see the Customer and Order resources in the HS_SALES resource folder. Note that the Order resource is a sub-resource of the Customer resource.
Next step
Tutorial: Testing a data resource
Tutorial
67
Tutorial: Testing a data resource
After creating the data resource, you can test it in the RESTful test browser.
Procedure
1. In the U2 REST Servers pane, right-click the MyRestServer server and select the Start REST Server option to start the server.
2. Expand the Data Resources node and then double-click the CUSTOMER resource. The results appear in the Test Browser, as shown:
When the test browser opens, the URL displays in the text field. It’s important to notice three things about this URL.
• The IP address in your test browser will be different than the one shown here.
• The max = 10 option, embedded in the URL, limits the number of results that are returned. You can change the number of results displayed by modifying this option.
• The tohtml=true option, embedded in the URL, is typically used for interactive testing only. If the option is set to tohtml=false or left off the URL request, the results are returned as pure JSON text.
Next step
Tutorial: Linking multiple resources using a foreign key
U2 RESTful Web Services Help
68
Tutorial: Linking multiple resources using a foreign key
You can link the data resources from related files through the use of a foreign key. In native U2, a foreign key is a field that is used in the TRANS virtual field to bring data from another file into the host file.
Note
This is an optional exercise. If you want to continue with this exercise, delete the Customer resource you created in the last section.
Procedure
1. In the U2 REST Servers view, right-click the resource node you want to work with. In this example, select the Customer node.
The foreign key is the second parameter in a TRANS function. In our Customer resource example, there is a virtual field named DESCRIPTION that contains a TRANS function, which uses the PRODID field to fetch the product descriptions from the PRODUCTS file, shown below:
2. Select all of the fields that you want to generate in the U2 REST resource first, then locate the field that you want to link to another resource. You are going to define it as a foreign key. In this example, PRODID is the foreign key field. It is a member of the ORDERS association, which will be mapped to the Orders resource.
3. Click the empty Foreign Key column next to PRODID. Select the Foreign Key option from the list, as shown:
Tutorial
69
4. Click Next. The Products resource, associated with the Orders resource, is now highlighted in yellow, and linked to the CUSTOMER resource.
U2 RESTful Web Services Help
70
5. When you assign a foreign key, you need to make sure that you deselect any of the corresponding virtual fields. In this example, deselect the DESCRIPTION and LIST_PRICE fields.
6. Click Finish. Focus returns to the U2REST Servers view. 7. A red X now appears next to the Orders resource in the U2 REST Servers view, as
shown:
A red X next to any of the resources indicates some type of resource-related error. In this instance, the X is there because we have not yet added the Products file to our available RESTful resources.
You cannot create a REST server if there are resource-related errors.
Tutorial
71
8. Drag the PRODUCTS file from the U2 Resource view into the HS_SALES folder in the U2 REST Servers view. The Select Fields for Resources dialog box opens:
9. Select the U2 fields you want to generate. In this example, we choose to Select All. 10. Click Next. Make any changes that you want to the resource names, then click
Finish. Focus returns to the U2 REST Servers view.
U2 RESTful Web Services Help
72
The resources are now linked, and the Orders resource can pull information from the Products resource.
Double-click the CUSTOMER resource to test the service. The results appear in the Test Browser view:
Notice that the Orders information now contains a URL to the PRODUCTS information, instead of listing it directly into the Test Browser. If you click the URL, more detailed information about the specified product appears, as shown:
Tutorial
73
Next step
Tutorial: Creating a REST subroutine resource
U2 RESTful Web Services Help
74
Tutorial: Creating a REST subroutine resource
In this exercise, you will create a UniVerse BASIC subroutine exposed as a REST service. Before you can create a REST subroutine resource, you need to create a subroutine.
For this example, we use a locally cataloged subroutine named CUSTOMERSUB, as shown:
SUBROUTINE CUSTOMERSUB(ID, REC) OPEN "CUSTOMER" TO F.CUST ELSE REC = "" READ REC FROM F.CUST, ID ELSE REC = "" CLOSE F.CUST RETURN END
Tip
You must catalog the subroutine before you start the U2 RESTful service. Subroutines may be cataloged globally, locally, or directly.
For information about cataloging UniBasic programs, see the UniBasic Commands Reference. For information about cataloging UniVerse BASIC programs, see the UniVerse User Reference.
After you create the subroutine, you are ready to create your REST subroutine resource.
Procedure
1. In the U2 Resource view, right-click the account for which you want to create a Web service. Click the white arrow symbol next to the HS.SALES CatalogProgram to view the cataloged subroutines available in the account. These are locally cataloged subroutines; globally cataloged subroutines appear in the main Catalog Programs section, which does not reside within your database account.
Tip
Parameter values entered in a RESTful subroutine are pre-processed by the parser and string values can be altered. For example:
• Strings are trimmed for leading, trailing, and multiple embedded spaces. • Non-significant leading zeroes before the decimal point and trailing zeroes
after the decimal point are removed from numbers. • The backslash character in a string is used to indicate that the special
character following a backslash should be treated in it's literal form rather than interpreted. For example, the UniVerse &COMO& file will be addressed as \&COMO\&. Otherwise, the special character will not be used as intended.
In order to preserve exact formatting of data that contains normally non-significant zeroes or spaces, the string should be enclosed in double-quotes. The following examples illustrate how data can be modified and how to avoid the modification.
Tutorial
75
Parameter name Input value Result
Number 1E3 1000.0
Number 012345 5431
Number 012345.670 12345.67
Number 1234567890123456789 1234567890123456789
Number 12345678901234567890 1.2345678901234567E19
Number 1234567890123456789 1.23456789012345677E18
String "012345.670" 012356.670
String "A012345.670" A012345.670
String <space><space>abc<space> <space>def<space><space> abc<space>def
"<space>abc<space><space>def<space>" <space>abc<space> <space>def<space>
String "1E3" 1E3
String "12345678901234567890" "12345678901234567890"
Meta-characters (preceded by a backslash)
"\"" (a double quote)
Meta-characters (preceded by a backslash)
"<backslash><backslash>"
A single backslash. A backslash "escapes" the backslash character that follows and returns it as a literal character.
2. Locate the subroutine you want to consume as a RESTful Web Service and drag it to the Subroutine Service folder. In our example, we call the CUSTOMERSUB subroutine we created in the last step.
3. Drag the CUSTOMERSUB subroutine onto the MyRestServer server. The New Subroutine Service dialog box opens.
U2 RESTful Web Services Help
76
4. Enter a relevant name for your subroutine in the Subroutine Name box. In our example, we name the subroutine CUSTOMERSUB.
5. Enter the total number of parameters defined for your subroutine. In the example subroutine, two parameters are defined, one input and one output.
Next step
Tutorial: Defining input parameters
Tutorial
77
Tutorial: Defining input parameters
You must define the input parameters for your subroutine service.
Procedure
1. Click Add in the Input Parameters area of the New Subroutine Services dialog box. The Define Parameters dialog box opens.
In the example subroutine, the input parameter is the customer ID, and it is the first parameter in the subroutine.
In the Name box, enter a relevant name for the parameter. This name does not have to be the same as the one defined in the UniVerse BASIC program. In this example, we define the name as ID.
Change the position and type information as necessary. Enter the position the input parameter appears in the subroutine in the Position box.
In the Type box, select one of the following data types for the input parameter: string, dynamic array, or json. In this example, we accept the defaults.
2. Click OK. Focus returns to the New Subroutine dialog box.
Next step
Tutorial: Defining output parameters
U2 RESTful Web Services Help
78
Tutorial: Defining output parameters
You must define the output parameters for your subroutine service.
Procedures
1. Click Add in the Output Parameters area of the New Subroutine Service dialog box. The Define Parameter dialog box appears:
2. Enter the name of the output parameter in the Name box. Enter the position of the subroutine’s output parameter in the Position box. Enter the data type of your output parameter in the Type box. In our example, the output parameter is a dynamic array.
3. Enter the name of the dynamic array definition in the Dynamic Array Name box. You can choose an existing dynamic array, or create a new one.
4. Click OK to save you parameter changes and then click Finish. Focus returns to theU2 REST Servers view. You now see the subroutine and dynamic array listed under the Subroutine Service node, as shown:
5. Double-click the dynamic array for which you want to define the fields. The Edit Dynamic Array dialog box opens, as shown:
Tutorial
79
6. Click Import. The Import U2 Dictionary Attributes dialog box opens. Select the U2 source file from which the dictionary attributes are imported. In this example, we select the CUSTOMER file, as shown:
U2 RESTful Web Services Help
80
7. Click Next. Select the dictionary attributes you want to import.
Tutorial
81
Note: The LOC value must be unique for each attribute, and the number of attributes you select must match the number of fields in the parameter of the subroutine. To ensure this is correct, in this example we do not select any ID fields and only import the D-type dictionary attributes.
8. After you select the appropriate attributes, click Finish. The Edit Dynamic Array dialog box opens again, populated with all of the relevant attributes. If everything is correct, click Finish. Focus returns to the U2 REST Servers view.
Next step
Tutorial: Testing a REST service
U2 RESTful Web Services Help
82
Testing the REST subroutine service
After you define all of the subroutine parameters, you want to test your REST subroutine service. In the following sections, we test the service in two ways. In the first example, we test the service within the U2 REST tool. In the second example, we use the CallHTTP function to consume our subroutine service.
Note: For information about CallHTTP, refer to either the UniVerse BASIC Extensions manual, or the UniBasic Extensions manual.
Procedure
1. Double-click the subroutine service you defined in the last exercise. In this example, we double-click the CUSTOMERSUB subroutine. The results appear in the Test Browser, as shown:
When the test browser opens, the input and output parameters display, along with a Call service button. In this example, the input parameter is ID and the output parameter is the customer record.
2. Enter the appropriate input information. In this example, we enter 2. 3. Click Call service. The REST service calls the subroutine and searches for the
information requested in the input parameter. It then displays the results in the Results field, as shown:
Tutorial
83
Next step
Tutorial: Manually testing a REST service
U2 RESTful Web Services Help
84
Tutorial: Manually testing the REST subroutine service
If you do not want to use the test browser, you can choose to manually test the REST subroutine service.
Procedure
1. Right-click the MyRestServer node in the U2 REST Servers pane. Select the Start REST Server option.
2. Click the CUSTOMERSUB node to highlight subroutine. In the properties pane to the right, you can see the subroutine resource properties. Note the service URI for the resource. It should look similar to the following service URI:
3. Next, send a request to the subroutine service. In the UniVerse BASIC example below, use the CallHTTP API to send a request to the subroutine service:
Note
You must change the url value to the one you used in Step 2.
a = protocolLogging("httpreq.log", "ON", 10) * call the REST subroutine service with HTTP POST url="http://DEN-L-AW01.rocketsoftware.com:9191/HS_SALES/subroutine/CUSTOMERSUB" method="POST" a = setHTTPDefault("VERSION", "1.1") a = createRequest(url, method, req4) a = setRequestHeader(req4, "Content-Type", "application/json; charset=utf-8") postData = '{"id":"2"}' Header = "" Data = "" httpStatus = "" a = submitRequest(req4, 5000, postData, Header, Data, httpStatus) * response PRINT "Response status: ":httpStatus PRINT "Response headers:":Header
Tutorial
85
PRINT "Length of response data:":LEN(Data) PRINT "Response Data:":Data
Note
You can also choose to use a Web debugging tool, such as Rest Client or Fiddler, to send an HTTP POST request to the U2 RESTful service to test your subroutine service.Subroutine resources can only be tested using a POST method, and the parameter must be made in JSON format.
After the U2 RESTful service receives the HTTP POST request, it returns a response similar to the following:
Response status: 200 @VM OK
Response headers:Date @VM Mon, 15 Nov 2010 16:35:56 GMT @FM Server @VM Jetty/4.2.x (Windows
XP/5.1 build 2600 Service Pack 3 x86 java/1.5.0) @FM Content-Type @VM application/json;
charset=UTF-8 @FM Content-Length @VM 707
Length of response data:70
The status and headers contain strings separated by field marks (@FM) and value marks (@VM). Data returned from a generic Web debugging tool does not contain these marks. The raw data returned from the U2 RESTful service is in JSON format, as shown below:
Response Data:{"CustomerRec":{"SAL":"Ms.","FNAME":"Diana","LNAME":"Morris","COMPANY":"Fast Copy Center","ADDR1":"431 Third Ave.","ADDR2":"","CITY":"Waltham","STATE":"MA","ZIP":"01133", "PHONE":"(617)555-9823", "ORDERS":[{"PRODID":"C2000","SER_NUM":"600782","PRICE":"6600", "BUY_DATE":"8409","PAID_DATE":"8437","SVC_PRICE":"900", "SVC_START":"8414","SVC_END":"8781","SVC_PAID_DATE":"8437"}, {"PRODID":"M3000","SER_NUM":"700422","PRICE":"12000", "BUY_DATE":"8409","PAID_DATE":"8437","SVC_PRICE":"500", "SVC_START":"8414","SVC_END":"8564","SVC_PAID_DATE":"8437"}, {"PRODID":"S3000","SER_NUM":"101456","PRICE":"900", "BUY_DATE":"8423","PAID_DATE":"8444","SVC_PRICE":"150", "SVC_START":"8414","SVC_END":"8781","SVC_PAID_DATE":"8444"}]}
86
Deployment
Deployment environment requirements
Before deploying U2 RESTful web services, make sure that the computer it is installed on meets the requirements.
• Java Runtime Environment (JRE) 1.6 must be installed on the target deployment platform. Currently, JRE 1.6 is the only version supported by U2 REST. Problems may occur if other versions are used.
• The JRE_HOME environment variable must point to the location of the JRE installation directory.
• At least 1GB of memory must be available prior to running the development environment.
• The memory requirements for the deployment environment depend on a variety of variables, including number of connections, tasks performed, and work load.
• Connection pooling licenses on the database server if connection pooling is enabled.
Deployment
87
Creating a deployment package
The U2 RESTful Web Services Developer Export option enables you to generate a deployment package of the selected RESTful web service.
Prerequisites
• On Windows 7 and Windows 2008, you must run the Windows Command Prompt as an administrator. To do this, click Start > Accessories > Command Prompt. Right-click the Command Prompt option and select Run as administrator.
• Java Runtime Environment (JRE) 1.6 must be installed on the target deployment platform, and the JRE_HOME environment variable must point to the location of the JRE 1.6 installation directory. Currently, JRE 1.6 is the only version supported by U2 REST. Problems may occur if other versions are used. The deployment package is in the form of a zip file, that contains the following:
• rundeploytool.bat • rundeploytool.sh • runrestserver.bat • runrestserver.sh • runtime • stoprestserver.bat • stoprestserver.sh • u2rest • U2REST_deploy.conf • u2rest_workspace • u2restservice.exe • vcredist_x86.exe
The zip file contains script files for Windows (.bat) and UNIX/Linux (.sh) files, which allow you to deploy the RESTful Web services on most platforms.
U2 RESTful Web Services Help
88
Exporting RESTful web services
You must export your RESTful web services to a .zip file in order to deploy them.
Procedure
1. Right-click the REST server that contains the REST service that you want to export. 2. Select Export. 3. In the Available REST Servers section, select the REST server(s) that you want to
export. 4. Enter the path for the zip file that you want to create in the Archive File field. By
default, the zip file is created in C:\U2\U2tools\v3\servername.zip. Click Browse to choose a different directory path or file name.
Note
Some computers, such as those running UNIX, cannot use zip files. In those cases, recompress the file with a non-zip extraction tool, such as 7zip, into a ZG-type file.
Deployment
89
Deploying a U2 RESTful server as a Windows service
The u2restservice.exe is an executable program that is used to create or remove a U2 RESTful web service as a Windows service. It is located in the zip file that was created during the export process.
Restriction
A Windows service can only be created on a deployed package.
Prerequisite
• Deploying a RESTful server from the U2 REST deployment tool • On Windows 7 and Windows 2008, you must run the Windows Command Prompt as
an administrator. To do this, click Start > Accessories > Command Prompt. Right-click the Command Prompt option and select Run as administrator.
Procedure
The syntax for installing a U2 RESTful web service is as follows:
U2restservice.exe –i u2rest-server-name [-s u2rest-service-name] [-d "u2rest-service-description"]
The following table lists the options available for deploying a U2 RESTful web server as a Windows service.
Option Description
-i Installs a new U2 RESTful web service as a Windows service.
-s The name of the U2 RESTful web service.
-d
Description of the U2 RESTful web service. The default value is "U2 RESTful service to start and stop U2 RESTful server". The text of the description must be enclosed in quotation marks (“”).
-r Removes the U2 RESTful web service.
After installing the U2 RESTful web service, it can started and stopped as a Windows service from the Windows control panel. When the service starts, it runs the ‘runrestserver.bat u2rest-server’ program and waits until this bat file exits. When the service stops, it runs the ‘stoprestserver.bat u2rest-server’ program.
Additional arguments can be passed to the runrestserver.bat by specifying the start parameters to the service.
Note
If you are creating a Windows service using the u2restservice.exe program and you get an error similar to the one shown below, you must run the vcredist_x86.exe program
U2 RESTful Web Services Help
90
supplied with the U2 REST product to ensure the Windows platform has the compatible Microsoft Visual C++ 2005 redistributable runtime environment:
Error: The application has failed to start because its side-by-side configuration is incorrect. Please see the application event log for more detail
Removing the service
The syntax for removing a U2 RESTful web service is as follows:
U2restservice.exe –r u2rest-server
Deployment
91
Deploying a RESTful server using the U2 REST deployment tool
Use the U2 RESTful deployment tool to deploy the U2 RESTful server from the development computer to the deployment environment.
Prerequisite
Exporting U2 RESTful web services
Procedure
1. After exporting the U2 RESTful web services from within the U2 RESTful tool, extract the zip file on to the target machine. The contents of the zip file are extracted into the u2restdeploy folder, which should contain the following files:
• rundeploytool.bat • rundeploytool.sh • runrestserver.bat • runrestserver.sh • runtime • stoprestserver.bat • stoprestserver.sh • u2rest • U2REST_deploy.conf • u2rest_workspace • u2restservice.exe • vcredist_x86.exe
Tip
Some machines, such as those running UNIX, cannot use zip files. If this occurs, recompress the file with a non-zip extraction tool such as 7zip into a gz (gzip) type file.
2. Navigate to the server directory where you extracted the zip file and locate U2RESTdeploytool. Run the rundeploytool command, shown in the example below.
rundeploytool[.sh | .bat] deployable_server_dir source_target_directory
The following table describes each parameter of the syntax:
Parameter Description
rundeploytool[.bat | .sh]
The command to start the deployment tool. Use the .bat extension for Windows applications and the .sh extension for UNIX/Linux applications.
deployable_server_dir The current directory. This can be the full path or a dot (.) for the current directory.
U2 RESTful Web Services Help
92
source_target_directory The directory where the deployable U2 RESTful web server will be located.
For example: rundeploytool.bat . C:\temp\myservice
Running the command opens the U2 REST Service Deployment tool, as shown:
3. Expand the Deployable REST Servers node in the REST servers pane. Right-click the REST server you want to deploy, then click Deploy. The REST Server Configuration dialog box opens, as shown:
You can specify the environment for the new REST server by changing any of the fields, as described below:
• In the Server Name field, enter a unique name for your REST server. • The Site URL field displays the valid URL for the REST server. You cannot
change the information in this field. • In the Port Number field, enter the port number on which the server will
listen. • The Root Path field displays the path to the root directory where the
definitions to the Web service are stored. You cannot change the information in this field.
• Select the Debug On option if you want to capture debugging information. • In the Log File Name field, enter the name of the log file. • Select the Connection Pooling On option if you want to use connection
pooling. • In the Minimum Connection Pool Size field, enter the minimum number of
pooled connections. The minimum size defaults to 1. • In the Maximum Connection Pool Size field, enter the maximum number
of pooled connections. The minimum size defaults to 10.
Deployment
93
4. Click Next. The REST Server Connection Security dialog box opens.
Next step
Defining security between the client and the REST server
U2 RESTful Web Services Help
94
Defining security between the client and the REST server
During the deployment process, you can define the security between the client and the REST server using the deployment tool.
Prerequisite
Deploying a RESTful server from the U2 REST deployment tool
Procedure
1. Click the Specify Connection Security check box if you want to define connection security between the client and the REST server. The security options populate the dialog box, as shown:
2. Enter the correct security connection details, as described below:
Field name Description
Key Store The full path to the key store on the REST server.
Key Store Password The password corresponding to the key store you defined in the Key Store field.
Confirm Key Store Password
Reenter the password corresponding to the key store you defined in the Key Store field.
3. Click Next to add access controls to your project or click Finish to exit the wizard.
Next step
Defining user access
Deployment
95
Defining user access
The access control page allows you to define user access and privileges. The user access control parameters you defined in the developer tool are not transferable and are used primarily for testing purposes. You must define new user access controls when you deploy your U2 RESTful Web service.
Prerequisite
Defining security between the client and the REST server
Procedure
1. From the Access Control screen, click Add to define a new role. The Add New Access Constraint dialog box opens:
2. Expand the navigation tree in the Path field and select the location for which you are
creating a user role. In this example, choose the TestServer file.
When you select a location, the directory path appears in the Path text box.
U2 RESTful Web Services Help
96
3. Select the privileges that will be available to the user you are defining by checking the appropriate Methods check boxes. You can choose one or more methods, or you can select All to grant full privileges to the user.
4. After you define the privileges you want to assign for a given role, you need to define that role. To select a role, choose an existing role from the list of available roles. If there are no roles defined yet, or if you need to create a new role, click Add Role.
5. Enter a meaningful name for the new role you are creating. In our example, we create the admin role.
6. Click Finish. Focus returns to the Access Control dialog box. 7. Click Next. The HTTP Users dialog box opens. 8. Click Add to designate the users who will be assigned to the user role you just
created. 9. Enter the correct user information. To select multiple user roles for a specific user,
hold down the Ctrl button while selecting the appropriate roles from the list. 10. When you are done making changes, click Finish. Focus returns to the HTTP Users
dialog box. Click Next. The Resource Folder Properties window opens.
Tip
If you find that you need to make more changes to your deployment server, right-click the server name you want to change from the list of available REST servers and select the Update option.
Next step
Defining the Resource folder properties in the GUI tool
Deployment
97
Defining the Resource folder properties in the GUI tool
The Resource Folder Properties page allows you to define the properties for the selected resource folder.
Prerequisite
Defining user access
Procedure
1. When the Resource Folder Properties dialog box opens, it displays the properties for the resource folder you defined for your RESTful server. You can edit the resource properties, as defined in the following table:
Field name Description
Name Displays the name of the resource folder. You cannot edit this field.
U2 Data Server The name of the U2 data server to which you are connecting.
U2 Account The name of the U2 account to which you are connecting.
UniRPC Service Name The name of the UniRPC service to which you are connecting.
UniRPC Port The port number to which you are connecting.
User ID The correct user name.
Password The correct password.
SSL Select the check box if you want to use SSL.
Client Encoding
The type of encoding, if any, you want to use for this Web service from the Client Encoding list.
SB+ System Id The abbreviation code, or system ID, for your SB+ System.
Refer to the SB+ manuals and the SB/XA manuals for more information on using systems.
SB+ User Id The user ID for the SB+ system to which you are connecting.
SB+ Password The password for the SB+ system to which you are connecting.
2. Click Test Database Connection. A pop-up window opens and informs you when the connection is successful.
U2 RESTful Web Services Help
98
3. Click OK to close the window. Click Finish to accept the resource folder properties. Focus returns to the REST Server Configuration dialog box.
Tip
If you find that you need to make more changes to your deployment server, right-click the server name you want to change from the list of available REST servers and select the Update option.
Result
The RESTful service was deployed on the deployment computer.
Deployment
99
Deploying a REST server from the command line
Starting the U2 REST deployment tool from the command line
Use the command line options to deploy the U2 REST server from the development computer to the deployment environment. The command line options allow for option-driven, interactive command line deployment.
Prerequisite
Exporting RESTful web services
Procedure
1. After exporting the RESTful web services from within the U2 REST tool, extract the zip file on to the target machine. The contents of the zip file are extracted into the u2restdeploy folder, which should contain the following files:
• rundeploytool.bat • rundeploytool.sh • runrestserver.bat • runrestserver.sh • runtime • stoprestserver.bat • stoprestserver.sh • u2rest • U2REST_deploy.conf • u2rest_workspace • u2restservice.exe • vcredist_x86.exe
Tip
Some computers, such as those running UNIX, cannot use zip files. If this occurs, recompress the file with a non-zip extraction tool such as 7zip into a gz (gzip) type file.
2. Navigate to the server directory where you extracted the zip file and locate the U2RESTdeploytool.Run the rundeploytool command, as shown in the example below.
rundeploytool[.sh | .bat] deployable_server_dir [target_server_dir]-s server_name [-t target_server] [-f config_file [-u] ]
The following table describes each parameter of the syntax:
Parameter Description
rundeploytool[.bat | .sh]
The command to start the deployment tool. Use the .bat extension for Windows applications and the .sh extension for UNIX/Linux applications.
deployable_server_dir The current directory. This can be either the full path or
U2 RESTful Web Services Help
100
a dot (.) for current directory.
target_server_dir The target directory where you want to deploy your U2 RESTful service.
-s source_server_name The name of the source server.
-t target_server_name
The name of the server on which the U2 REST server will be deployed.
-f config_file (Optional). Add this parameter to input all data from the configuration file.
-u
The parameter to manually change the database connection credentials. This requires using the -f parameter If the -u parameter is not included in the command, while the connection credentials will be visible, they will not be editable.
-l Lists the servers available for deployment.
For example: rundeploytool.bat . C:\temp\myservice -s testserver -t prodserver
3. The U2 RESTful server configuration options open in the command-line window. Select the appropriate command-line option, as described in the following table:
Command line option Description
X eXit.
A Accept. When all of the configuration options are set correctly, click A to continue to the next set of configuration options.
1 Server name. A unique name for your REST server.
The Site URL field displays the valid URL for the REST server. You cannot change the information in this field.
2
Port number. The port number on which the server will listen.
Root Path. Displays the path to the root directory where the definitions to the Web service are stored. You cannot change the information in this field.
3 Debug on. Set this value to true to turn on the debug log. Set this value to false to turn the log off. By default, this value is set to false.
4 Log file name. Edit the name of the log file. By default, the
Deployment
101
name of the log file is defined by the name of the target server.
5 Connection Pooling On. Set this value to true to enable connection pooling.
6 Minimum Connection Pool Size. Sets the minimum number of connections in the connection pool. The minimum size defaults to 1.
7 Maximum Connection Pool Size. Sets the maximum number of connections in the connection pool. The minimum size defaults to 10.
4. After making any changes to the deployment configuration options, enter A to continue.
Next step
Defining RESTful server connection security from the command line
U2 RESTful Web Services Help
102
Defining U2 RESTful server connection security from the command line
After defining the connection configuration, you can define the connection security for the server.
Prerequisites
Deploying a RESTful server from the command line
Procedure
1. The U2 RESTful connection security options open in the command line window. Select the appropriate action from the options presented in the command line window, as described in the following table.
Command line option Description
X eXit.
A Accept. Accepts the options as defined.
S Specify the connection security parameters.
D Do not specify connection security. Select this option if connection security is not required.
1 Key Store. Enter the name of the Key Store.
2 Key Store password. Enter the password for the Key Store.
3 Key Password. Enter the password for the Key.
2. After defining any connection security settings for the server, enter A to continue.
Next step
Defining RESTful server connection security from the command line
Related links
Deployment
103
Defining Resource folder properties
After defining the server connection properties, you can define the properties for the selected resource folder.
Prerequisites
Defining RESTful server connection security from the command line
Procedure
1. The U2 RESTful Resource folder property options open in the command line window. Select the appropriate action from the options presented in the command line window, as described in the following table:
Command line option
Description
X eXit.
A Accept. Accepts the options as defined.
T Test. Tests the database connection.
1 The name of the U2 data server to which you are connecting.
2 The name of the U2 account to which you are connecting.
3 The name of the UniRPC service to which you are connecting.
4 The port number to which you are connecting.
5 The correct user name.
6 The correct password.
7 Select the check box if you want to use SSL.
8 The type of encoding, if any, you want to use for this Web service from the Client Encoding list.
9 The abbreviation code, or system ID, for your SB+ System.
Refer to the SB+ manuals and the SB/XA manuals for more information on using systems.
10 The user ID for the SB+ system to which you are connecting.
11 The password for the SB+ system to which you are connecting.
2. After making any changes to the Resource folder properties, enter A to continue.
U2 RESTful Web Services Help
104
Next step
Deploying a REST server from the command line
Deployment
105
Deploying a REST server from the command line
After any required changes are made to the Resource folder properties, the U2 REST server is ready to deploy on the deployment environment.
Prerequisites
Defining Resource folder properties from the command line
Procedure
1. The U2 RESTful Resource folder property options open in the command line window. Select the appropriate action from the options presented in the command line window, as described in the following table:
Command line option
Description
X eXit.
G
Generate configuration file. This option generates an XML file, server_name_ deploy_configuration.xml, that contains all of the configuration information. Select this option to make changes to the configuration file before deploying.
C Continue. This option deploys the server to the deployment environment.
Result
The U2 RESTful service was deployed to the deployment environment.
U2 RESTful Web Services Help
106
Deploying a REST server from a configuration file
Generating a configuration file
Use the U2 RESTful deployment tool to generate a configuration file that can be used to deploy the U2 RESTful server from the development computer to the deployment environment.
Prerequisite
Exporting U2 RESTful web services
Procedure
1. After exporting the U2 RESTful web services from within the U2 RESTful tool, extract the zip file on to the target machine. The contents of the zip file are extracted into the u2restdeploy folder, which should contain the following files:
• rundeploytool.bat • rundeploytool.sh • runrestserver.bat • runrestserver.sh • runtime • stoprestserver.bat • stoprestserver.sh • u2rest • U2REST_deploy.conf • u2rest_workspace • u2restservice.exe • vcredist_x86.exe
Tip
Some machines, such as those running UNIX, cannot use zip files. If this occurs, recompress the file with a non-zip extraction tool such as 7zip into a gz (gzip) type file.
2. Navigate to the server directory where you extracted the zip file and locate U2RESTdeploytool. Run the rundeploytool command, shown in the example below.
rundeploytool[.sh | .bat] deployable_server_dir source_target_directory
The following table describes each parameter of the syntax:
Parameter Description
rundeploytool[.bat | .sh]
The command to start the deployment tool. Use the .bat extension for Windows applications and the .sh extension for UNIX/Linux applications.
deployable_server_dir The current directory. This can be the full path or a dot (.) for the current directory.
Deployment
107
source_target_directory The directory where the deployable U2 RESTful web server will be located.
For example: rundeploytool.bat . C:\temp\myservice
Running the command opens the U2 REST Service Deployment tool, as shown:
3. Expand the Deployable REST Servers node in the REST servers pane. Right-click
the REST server you want to deploy, then click Generate configuration file.
4. Click Browse to select a different configuration file or accept the default
configuration file. Click Next.
5. The REST Server Configuration dialog box opens. You can specify the
environment for the new REST server by changing any of the fields, as described
below:
• In the Server Name field, enter a unique name for your REST server. • The Site URL field displays the valid URL for the REST server. You cannot
change the information in this field. • In the Port Number field, enter the port number on which the server will
listen. • The Root Path field displays the path to the root directory where the
definitions to the Web service are stored. You cannot change the information in this field.
• Select the Debug On option to capture debugging information. • In the Log File Name field, enter the name of the log file.
U2 RESTful Web Services Help
108
• Select the Connection Pooling On option to use connection pooling. • In the Minimum Connection Pool Size field, enter the minimum number of
pooled connections. The minimum size defaults to 1. • In the Maximum Connection Pool Size field, enter the maximum number
of pooled connections. The minimum size defaults to 10.
6. Click Next. The REST Server Connection Security dialog box opens. Select the
Specify Connection Security checkbox to make changes to the security settings.
Click Next to continue.
For more information, see Defining security between the client and the REST
server.
7. Click Add to add user access controls to the REST server. When you are done
making changes, click Next to continue.
For more information about user access controls, see Defining user access.
8. Make any necessary changes to the Resource folder properties and then click
Finish.
For more information, see Defining the Resource folder properties in the GUI tool.
Next step
Deploying a RESTful server from a configuration file
Deployment
109
Deploying a REST server from a configuration file
A U2 RESTful service can be deployed onto a deployment environment using a generated configuration file. The configuration file is an XML file, server_name_ deploy_configuration.xml, that contains all of the configuration information. The configuration file specifies values that can be changed during deployment, such as login credentials.
Prerequisite
Generating a configuration file
Procedure
1. After generating a configuration file, open a command prompt (cmd.exe) on the deployment machine. Navigate to the directory in which the configuration files are located. Run the following command to deploy the U2 REST server on the deployment environment: rundeploytool deployable_server_dir [target_server_dir]-s server_name [-t target_server] –f config_file [-u]
The following table describes each parameter of the syntax:
Parameter Description
rundeploytool[.bat | .sh]
The command to start the deployment tool. Use the .bat extension for Windows applications and the .sh extension for UNIX/Linux applications.
deployable_server_dir The current directory. This can be either the full path or a dot (.) for current directory.
target_server_dir The target directory where you want to deploy your U2 RESTful service.
-s source_server_name The name of the source server.
-t target_server_name
The name of the server on which the U2 REST server will be deployed.
-f config_file (Optional). Add this parameter to input all data from the configuration file.
-u
The parameter to manually change the database connection credentials. This requires using the -f parameter If the -u parameter is not included in the command, while the connection credentials will be visible, they will not be editable.
-l Lists the servers available for deployment.
U2 RESTful Web Services Help
110
Result
The U2 RESTful service is deployed to the deployment environment.
Deployment
111
Starting a RESTful service
After exporting the U2 RESTful web project and running it through the deployment tool, start the RESTful web services in the deployment environment.
Procedure
Use the following command to start a U2 RESTful service:
runrestserver[.sh | .bat] rest_server_name [rest_server_directory]
The table below describes each parameter of the syntax.
Parameter Description
runrestserver[.bat | .sh]
The command to run the REST server in the deployed environment. Use the .bat extension for Windows applica-tions and the .sh extension for UNIX/Linux applications.
. The current directory. You must include this parameter.
rest_server_name The name of the REST server to which you are connecting.
source_target_directory The target directory where the RESTful service will be deployed
For example:
runrestserver.bat . C:\temp\mynewservice
Your can check to ensure that the RESTful service is running by opening a browser window and navigating to the URL where the service is running.
Tip
UNIX users may want to run the runrestserver command as a background process, using a NOHUP command when the terminal session exits.
For example:
nohup runrestserver.sh "rest_server_name" "path to U2REST.config directory" &
U2 RESTful Web Services Help
112
Stopping a U2 RESTful service
You can stop any of the U2 RESTful web services running in the deployment environment.
Procedure
Use the following command to stop a U2 RESTful service:
stoprestserver[.sh | .bat] . source_target_directory
The following table describes each parameter of the syntax.
Parameter Description
stoprestserver[.bat | .sh]
The command to stop the REST server in the deployed environment. Use the .bat extension for Windows applica-tions and the .sh extension for UNIX/Linux applications.
. The current directory. You must include this parameter.
source_target_directory The target directory where you want to deploy your RESTful service.
For example:
stoprestserver.bat . C:\temp\mynewservice
Deployment
113
Remote servers
U2 RESTful Web Services allows for limited remote RESTful server monitoring. You can use this functionality to stop a remote server, but you cannot restart the server remotely.
You can also turn the REST Server Debug On/OFF remotely.
114
Code Samples
UniBasic code samples
The U2 RESTful Web Services code samples in this section are written for UniData in UniBasic. They demonstrate the following methods:
• HTTP GET • HTTP POST • HTTP PUT • HTTP DELETE • RESTSUB - An HTTP subroutine • RETPROG - A subroutine test program • RETSUB - A UniBasic subroutine • URLENC - An encoding program
Code Samples
115
UniBasic HTTP GET
The HTTP GET method can only be used on U2 REST data resources.
The following example illustrates a typical HTTP GET request. The request calls the U2 REST server using a GET statement, and then returns a customer record based on the requested CUSTID:
* logfile = "restget" * stat = protocolLogging(logfile, "ON", 10) * PRINT "WHICH CUSTOMER record ID would you like to GET?" INPUT CUSTID * * URL returned as html or json data url="http://myserver.com:9191/demo/Customer/":CUSTID method="GET" * stat = setHTTPDefault("VERSION", "1.1") stat = createRequest(url, method, restGET) stat = submitRequest(restGET, 5000, "", Header, restData,| httpStatus) * * GET response parser restData=CHANGE(restData, "{", "{":CHAR(10)) restData=CHANGE(restData, ",", ",":CHAR(10)) restData=CHANGE(restData, "}", "}":CHAR(10)) * PRINT "Response status: ":httpStatus * PRINT "Response headers:":Header PRINT "Response data:":CHAR(10):restData * * stat = protocolLogging(logfile, "OFF", 10) END
U2 RESTful Web Services Help
116
UniBasic HTTP POST
The HTTP POST method is used to create a new data record or to call a BASIC subroutine. The following example demonstrates how to use the HTTP POST request. In this program, we call the U2REST server using an HTTP POST request. The request then uses postData information to create a new record based on the CUSTID parameter.
* logfile="restpost" * stat = protocolLogging(logfile, "ON", 10) * method="POST" url="http://myserver.com:9191/demo/Customer" stat = setHTTPDefault("VERSION", "1.1") * PRINT "Enter Unique Customer ID to create: " INPUT CUSTID * * Customer Record to be written to record CUSTID * postDATA = '{' postDATA:=' "_id" : "':CUSTID:'",' postDATA:= "'_original': 'null'," postDATA:= "'_synonym': 'null'," postDATA:= "'activity': ''," postDATA:= "'address': ['4700 South Syracuse Street']," postDATA:= "'avg_out': ''," postDATA:= "'categories_liked': ['C']," postDATA:= "'city': 'Denver'," postDATA:= "'cur_balance': '0.00'," postDATA:= "'name': 'Seagoon, Neddy'," postDATA:= "'phone': '3034495641'," postDATA:= "'state': 'CO'," postDATA:= "'up_name': ''," postDATA:= "'zip': '80237'," postDATA:=' }' * stat = createRequest(url, method, restPOST) stat = setRequestHeader(restPOST, "Content-Type",| "application/json; charset=utf-8") stat = submitRequest(restPOST, 5000, postDATA, Header, restData,| httpStatus) * POST response restData=CHANGE(restData, "{", "{":CHAR(10)) restData=CHANGE(restData, ",", ",":CHAR(10)) restData=CHANGE(restData, "}", "}":CHAR(10)) * PRINT "Response status: ":httpStatus *PRINT "Response headers:":Header PRINT "Response data:":CHAR(10):restData * * stat = protocolLogging(logfile, "OFF", 10) * restPOST="" END
Code Samples
117
UniBasic HTTP PUT
The following example demonstrates a typical GET/PUT combination being used to update a resource. A GET request executes to retrieve the contents of the u2version parameter, which is the record’s LastUpdate ID. The client program then calls the U2 REST server with an HTTP PUT request, using the postData information to modify an existing record based on the CUSTID parameter. The value of the u2version parameter must be used in the If-Match HTTP header.
* logfile="restput" * a = protocolLogging(logfil, "ON", 10) * PRINT "WHICH ID WOULD YOU LIKE TO Update?" INPUT CUSTID * method="GET" url="http://myserver.com:9191/demo/Customer/":CUSTID * stat = setHTTPDefault("VERSION", "1.1") stat = createRequest(url, method, restGET) stat = submitRequest(restGET, 5000, "", Header, restData,| httpStatus) * * Get Data Record u2version ID * MYSTRING = CHANGE(restData, '"u2version"', @AM ) U2VERSION = FIELD(MYSTRING<2>, '"', 2) PRINT MYSTRING * putDATA = '{' putDATA:=' "_id" : "':CUSTID:'",' putDATA:= "'_original': 'null'," putDATA:= "'_synonym': 'null'," putDATA:= "'activity': ''," putDATA:= "'address': ['4600 South Ulster Street']," putDATA:= "'avg_out': ''," putDATA:= "'categories_liked': ['C']," putDATA:= "'city': 'Denver'," putDATA:= "'cur_balance': '0.00'," putDATA:= "'name': 'Seagoon, Neddy'," putDATA:= "'phone': '8007293553'," putDATA:= "'state': 'CO'," putDATA:= "'up_name': ''," putDATA:= "'zip': '80237'," putDATA:=' }' * * call the REST subroutine service with HTTP POST method="PUT" * stat = createRequest(url, method, restPUT) stat = setRequestHeader(restPUT, "Content-Type",| "application/json; charset=utf-8") stat = setRequestHeader(restPUT, "If-Match", U2VERSION) * stat = submitRequest(restPUT, 5000, putDATA, Header, restData,| httpStatus) * put response restData=CHANGE(restData, "{", "{":CHAR(10)) restData=CHANGE(restData, ",", ",":CHAR(10)) restData=CHANGE(restData, "}", "}":CHAR(10)) * PRINT "Response status: ":httpStatus * PRINT "Response headers:":Header PRINT "Response data:":CHAR(10):restData
U2 RESTful Web Services Help
118
* stat = protocolLogging(logfil, "OFF", 10) END
Code Samples
119
UniBasic HTTP DELETE
The following example demonstrates how to use the HTTP DELETE function in U2 REST. An HTTP GET request is called first, followed by the HTTP DELETE request. An existing RECORD ID record, based on the CUSTID parameter, is deleted. The value for the u2version parameter must be used in the If-Match HTTP DELETE header.
* logfile = "restdelete" * stat = protocolLogging(logfile, "ON", 10) PRINT "WHICH ID WOULD YOU LIKE TO DELETE?" INPUT CUSTID url="http://myserver.com:9191/demo/Customer/":CUSTID method="GET" * stat = setHTTPDefault("VERSION", "1.1") stat = createRequest(url, method, restGET) * stat = submitRequest(restGET, 5000, "", Header, restData,| httpStatus) * restData=CHANGE(restData, "{", "{":CHAR(10)) restData=CHANGE(restData, ",", ",":CHAR(10)) restData=CHANGE(restData, "}", "}":CHAR(10)) * PRINT "Response status: ":httpStatus PRINT "Response headers:":Header PRINT "Response data:":CHAR(10):restData * * Get Data Record u2version ID * MYSTRING = CHANGE(restData, '"u2version"', @AM ) U2VERSION = FIELD(MYSTRING<2>, '"', 2) PRINT U2VERSION * * call the REST subroutine service with HTTP DELETE method="DELETE" * stat = createRequest(url, method, restDELETE) stat = setRequestHeader(restDELETE, "Content-Type", "application/json; charset=utf-8") stat = setRequestHeader(restDELETE, "if-match", U2VERSION) stat = submitRequest(restDELETE, 5000, "", Header, restData,| httpStatus) * PRINT "Response status: ":httpStatus * PRINT "Response headers:":Header * PRINT "Response data:":CHAR(10):restData * stat = protocolLogging(logfile, "OFF", 10) END
U2 RESTful Web Services Help
120
UniBasic REST subroutine
This program calls a U2 Subroutine from the U2 REST Server with HTTP POST. Data in the procDATA indata field is sent to the U2 subroutine. Data from the subroutine attaches to the indata field and displays as returned data in the outdata field, as shown:
Note
U2 REST service fields are case sensitive.
* logfile="restpost" * stat = protocolLogging(logfile, "ON", 10) * method="POST" url="http://myserver.com:9191/demo/subroutine/RETSUB" stat = setHTTPDefault("VERSION", "1.1") * PRINT "Enter the data to send to RETSUB: " INPUT INDATA * * Customer Record to be written to record CUSTID * procDATA = "{" procDATA:=' "indata" : "':INDATA:'",' procDATA := "}" * stat = createRequest(url, method, procPOST) stat = setRequestHeader(procPOST, "Content-Type",| "application/json; charset=utf-8") stat = submitRequest(procPOST, 5000, procDATA, Header, restData,| httpStatus) * POST response restData=CHANGE(restData, "{", "{":CHAR(10)) restData=CHANGE(restData, ",", ",":CHAR(10)) restData=CHANGE(restData, "}", "}":CHAR(10)) * PRINT "Response status: ":httpStatus *PRINT "Response headers:":Header PRINT "Response data:":CHAR(10):restData * * stat = protocolLogging(logfile, "OFF", 10) * END
Code Samples
121
UniBasic RETSUB
RETSUB is a UniBasic subroutine that returns a "Calling Program sent:" message to the U2 REST server. Data from this subroutine attaches to the indata field and displays as returned data in the outdata field, as shown:.
Note
The U2 REST service fields are case sensitive.
SUBROUTINE RETSUB(p1, p2) p2="Calling Program sent: ":p1
RETPROG
This program tests the RETSUB subroutine by parsing the value “NED” and printing the return results.
A="NED: " B="" CALL RETSUB(A,B) PRINT B
U2 RESTful Web Services Help
122
UniBasic URLENC
The URLENC program takes the data in the mydata file and URL encodes it. The URL encoded data is sent to myresult. The program then decodes myresult and is URL decoded in myresult2.
CRT "URLEncode and URLDecode example" mydata=": / ? # &" encstat=ENCODE("URLENCODE", 1, mydata, 1, myresult, 1) PRINT "enco stat : ":encstat PRINT myresult encstat=ENCODE("URLENCODE", 2, myresult, 1, myresult2, 1) PRINT encstat PRINT myresult2
Code Samples
123
UniVerse BASIC code samples
The U2 RESTful Web Services sample codes in this section are written for UniVerse in UniBASIC. They demonstrate the following methods:
• HTTP GET • HTTP POST • HTTP PUT • HTTP DELETE • RESTSUB - An HTTP subroutine • RETPROG - A subroutine test program • RETSUB - A UniVerse BASIC subroutine • URLENC - An encoding program
U2 RESTful Web Services Help
124
UniVerse BASIC HTTP GET
The HTTP GET method can only be used on U2 REST data resources.
The following example illustrates a typical HTTP GET request. The request calls the U2 REST server using a GET statement, and then returns a customer record based on the requested CUSTID:
* * logfile = "restget" * stat = protocolLogging(logfile, "ON", 10) * PRINT "WHICH CUSTOMER record ID would you like to GET?" INPUT CUSTID * * URL returned as html or json data url="http://myserver.com:9193/HS_SALES/Customer/":CUSTID method="GET" * stat = setHTTPDefault("VERSION", "1.1") stat = createRequest(url, method, restGET) stat = submitRequest(restGET, 5000, "", Header, restData,| httpStatus) * * GET response parser restData=CHANGE(restData, "{", "{":CHAR(10)) restData=CHANGE(restData, ",", ",":CHAR(10)) restData=CHANGE(restData, "}", "}":CHAR(10)) * PRINT "Response status: ":httpStatus * PRINT "Response headers:":Header PRINT "Response data:":CHAR(10):restData * * stat = protocolLogging(logfile, "OFF", 10) END
Code Samples
125
UniVerse BASIC HTTP POST
The HTTP POST method is used to create a new data record or to call a BASIC subroutine. The following example demonstrates how to use the HTTP POST request. In this program, we call the U2REST server using an HTTP POST request. The request then uses postData information to create a new record based on the CUSTID parameter.
* logfile="restpost" * stat = protocolLogging(logfile, "ON", 10) * method="POST" url="http://myserver.com:9193/HS_SALES/Customer" stat = setHTTPDefault("VERSION", "1.1") * PRINT "Enter Unique Customer ID to create: " INPUT CUSTID * * Customer Record to be written to record CUSTID * postDATA='{' postDATA:=' "statename" : "Colorado",' postDATA:=' "state" : "CO",' postDATA:=' "fname" : "Neddy",' postDATA:=' "city" : "Denver",' postDATA:=' "lname" : "Seagoon",' postDATA:=' "sal" : "Mr.",' postDATA:=' "phone" : "8007293553",' postDATA:=' "custid" : "':CUSTID:'",' postDATA:=' "addr1" : "4700 South Syracuse Street",' postDATA:=' "addr2" : "444",' postDATA:=' "zip" : "80237",' postDATA:=' "company" : "IBM Corporation."' postDATA:='}' * stat = createRequest(url, method, restPOST) stat = setRequestHeader(restPOST, "Content-Type",| "application/json; charset=utf-8") stat = submitRequest(restPOST, 5000, postDATA, Header, restData,| httpStatus) * POST response restData=CHANGE(restData, "{", "{":CHAR(10)) restData=CHANGE(restData, ",", ",":CHAR(10)) restData=CHANGE(restData, "}", "}":CHAR(10)) * PRINT "Response status: ":httpStatus *PRINT "Response headers:":Header PRINT "Response data:":CHAR(10):restData * stat = protocolLogging(logfile, "OFF", 10) END
U2 RESTful Web Services Help
126
UniVerse BASIC HTTP PUT
The following example demonstrates a typical GET/PUT combination being used to update a resource. A GET request executes to retrieve the contents of the u2version parameter, which is the record’s LastUpdate ID. The client program then calls the U2 REST server with an HTTP PUT request, using the postData information to modify an existing record based on the CUSTID parameter. The value of the u2version parameter must be used in the If-Match HTTP header.
* logfile="restput" * a = protocolLogging(logfile, "ON", 10) * PRINT "WHICH ID WOULD YOU LIKE TO Update?" INPUT CUSTID * method="GET" url="http://myserver.com:9193/HS_SALES/Customer/":CUSTID * stat = setHTTPDefault("VERSION", "1.1") stat = createRequest(url, method, restGET) stat = submitRequest(restGET, 5000, "", Header, restData,| httpStatus) * * Get Data Record u2version ID * MYSTRING = CHANGE(restData, '"u2version"', @AM ) U2VERSION = FIELD(MYSTRING<2>, '"', 2) * putDATA='{' putDATA:=' "statename" : "Colorado",' putDATA:=' "state" : "CO",' putDATA:=' "fname" : "Neddy",' putDATA:=' "city" : "Denver",' putDATA:=' "lname" : "Seagoon",' putDATA:=' "sal" : "Ms.",' putDATA:=' "phone" : "(800)729-3553",' putDATA:=' "custid" : "':CUSTID:'",' putDATA:=' "addr1" : "4600 South Ulster Street.",' putDATA:=' "addr2" : "",' putDATA:=' "zip" : "80237",' putDATA:=' "company" : "Rocket Software, Inc."' putDATA:='}' * * call the REST subroutine service with HTTP POST method="PUT" * stat = createRequest(url, method, restPUT) stat = setRequestHeader(restPUT, "Content-Type",| "application/json; charset=utf-8") stat = setRequestHeader(restPUT, "if-match", U2VERSION) * stat = submitRequest(restPUT, 5000, putDATA, Header, restData,| httpStatus) * put response restData=CHANGE(restData, "{", "{":CHAR(10)) restData=CHANGE(restData, ",", ",":CHAR(10)) restData=CHANGE(restData, "}", "}":CHAR(10)) * PRINT "Response status: ":httpStatus * PRINT "Response headers:":Header PRINT "Response data:":CHAR(10):restData * stat = protocolLogging(logfil, "OFF", 10) END
Code Samples
127
UniVerse BASIC HTTP DELETE
The following example demonstrates how to use the HTTP DELETE function in U2 REST. An HTTP GET request is called first, followed by an HTTP DELETE request. An existing RECORD ID record, based on the CUSTID parameter, is deleted. The value for the u2version parameter must be used in the If-Match HTTP DELETE header.
* logfile = "restdelete" * stat = protocolLogging(logfile, "ON", 10) * *PRINT "WHICH ID WOULD YOU LIKE TO DELETE?" INPUT CUSTID * url="http://myserver.com:9193/HS_SALES/Customer/":CUSTID method="GET" * stat = setHTTPDefault("VERSION", "1.1") stat = createRequest(url, method, restGET) * stat = submitRequest(restGET, 5000, "", Header, restData,| httpStatus) * restData=CHANGE(restData, "{", "{":CHAR(10)) restData=CHANGE(restData, ",", ",":CHAR(10)) restData=CHANGE(restData, "}", "}":CHAR(10)) * PRINT "Response status: ":httpStatus PRINT "Response headers:":Header PRINT "Response data:":CHAR(10):restData * * Get Data Record u2version ID * MYSTRING = CHANGE(restData, '"u2version"', @AM ) U2VERSION = FIELD(MYSTRING<2>, '"', 2) PRINT U2VERSION * * call the REST subroutine service with HTTP DELETE method="DELETE" * stat = createRequest(url, method, restDELETE) stat = setRequestHeader(restDELETE, "Content-Type",| "application/json; charset=utf-8") stat = setRequestHeader(restDELETE, "if-match", U2VERSION) stat = submitRequest(restDELETE, 5000, "", Header, restData,| httpStatus) * PRINT "Response status: ":httpStatus * PRINT "Response headers:":Header * PRINT "Response data:":CHAR(10):restData * stat = protocolLogging(logfile, "OFF", 10) END
U2 RESTful Web Services Help
128
UniVerse BASIC REST subroutine
This program calls a U2 Subroutine from the U2 REST Server with HTTP POST. Data in the procDATA indata field is sent to the U2 subroutine. Data from the subroutine attaches to the indata field and displays as returned data in the outdata field, as shown:
Note
U2 REST service fields are case sensitive.
* logfile="restpost" * stat = protocolLogging(logfile, "ON", 10) * method="POST" url="http://myserver.com:9193/HS_SALES/subroutine/RETSUB" stat = setHTTPDefault("VERSION", "1.1") * PRINT "Enter the data to send to RETSUB: " INPUT INDATA * * Customer Record to be written to record CUSTID * procDATA = "{" procDATA:=' "indata" : "':INDATA:'",' procDATA := "}" * stat = createRequest(url, method, procPOST) stat = setRequestHeader(procPOST, "Content-Type",| "application/json; charset=utf-8") stat = submitRequest(procPOST, 5000, procDATA, Header, restData,| httpStatus) * POST response restData=CHANGE(restData, "{", "{":CHAR(10)) restData=CHANGE(restData, ",", ",":CHAR(10)) restData=CHANGE(restData, "}", "}":CHAR(10)) * PRINT "Response status: ":httpStatus *PRINT "Response headers:":Header PRINT "Response data:":CHAR(10):restData * * stat = protocolLogging(logfile, "OFF", 10) * END
Code Samples
129
UniVerse BASIC RETSUB
RETSUB is a UniBasic subroutine that returns a "Calling Program sent:" message to the U2 REST Server. Data from this subroutine attaches to the indata field and displays as returned data in the outdata field, as shown:.
Note: The U2 REST service fields are case sensitive.
* SUBROUTINE RETSUB(p1, p2) p2="Calling Program sent: ":p1 * CONVERT @AM TO CHAR(10):CHAR(13) IN p2 END
RETPROG
This program tests the RETSUB subroutine by parsing the value “NED” and printing the return results.
A="NED: " B="" CALL RETSUB(A,B) PRINT B
U2 RESTful Web Services Help
130
UniVerse BASIC URLENC
The URLENC program takes the data in the mydata file and URL encodes it. The URL encoded data is sent to myresult. The program then decodes myresult and is URL decoded in myresult2.
CRT "URLEncode and URLDecode example" mydata=": / ? # &" encstat=ENCODE("URLENCODE", 1, mydata, 1, myresult, 1) PRINT "enco stat : ":encstat PRINT myresult encstat=ENCODE("URLENCODE", 2, myresult, 1, myresult2, 1) PRINT encstat PRINT myresult2 *
Code Samples
131
Python for UniData code samples
The U2 RESTful Web Services sample codes in this section are written for UniData in Python. The Python examples demonstrate the following methods:
• HTTP GET • HTTP POST • HTTP PUT • HTTP DELETE • RESTSUB - An HTTP subroutine
The examples in this section were written using Python 3.2. Refer to www.python.org for more information on Python.
Note
The samples in this appendix are provided to demonstrate how Python can be used within U2 RESTful Web Services. UniData and UniVerse do not offer any support for Python.
U2 RESTful Web Services Help
132
Python for UniData: HTTP GET
The HTTP GET method can only be used on U2 REST data resources.
The following example illustrates a typical HTTP GET request. The request calls the U2 REST server using a GET statement, and then returns a customer record based on the requested CUSTID:
import httplib2 import json from pprint import pprint # custid = str(input("WHICH CUSTOMER record ID would you like to GET? ")) # UniData url (Select record id 2) url = "http://myserver.com:9191/demo/Customer/"+custid method="GET" # stat = httplib2.Http(".cache") restStatus, restData = stat.request(url, method) # print ("\nResponse Status: ", restStatus.status) # data = json.loads(restData.decode("UTF-8")) pprint(data)
Code Samples
133
Python for UniData: HTTP POST
The HTTP POST method is used to create a new data record or to call a BASIC subroutine. The following example demonstrates how to use the HTTP POST request. In this program, we call the U2REST server using an HTTP POST request. The request then uses postData information to create a new record based on the CUSTID parameter.
import httplib2 import json from pprint import pprint # #custid = str(input("Enter Unique Customer ID to create: ")) url = "http://myserver.com:9191/demo/Customer" method="POST" headers = {"Content-type": "application/json;charset=utf-8"} # # Customer Record to be written to record CUSTID # postDATA={ '_id' : ''+custid+'', '_original': 'null', '_synonym': 'null', 'activity': '', 'address': ['4700 South Syracuse Street'], 'avg_out': '', 'categories_liked': ['C'], 'city': 'Denver', 'cur_balance': '0.00', 'name': 'Seagoon, Neddy', 'phone': '3034495641', 'state': 'CO', 'up_name': '', 'zip': '80237', } # postDATA = json.dumps(postDATA) stat = httplib2.Http(".cache") restStatus, restData = stat.request(url,method, postDATA, headers) # print ("\nResponse Status: ", restStatus.status) data = json.loads(restData.decode("UTF-8")) pprint(data)
U2 RESTful Web Services Help
134
Python for UniData: HTTP PUT
The following example demonstrates a typical GET/PUT combination being used to update a resource. A GET request executes to retrieve the contents of the u2version parameter, which is the record’s LastUpdate ID. The client program then calls the U2 REST server with an HTTP PUT request, using the postData information to modify an existing record based on the CUSTID parameter. The value of the u2version parameter must be used in the If-Match HTTP header.
import httplib2 import json from pprint import pprint # custid= str(input("WHICH ID WOULD YOU LIKE TO Update? ")) # UniData url (Select record id 2) url = "http://myserver.com:9191/demo/Customer/"+custid method = "GET" # statget = httplib2.Http(".cache") restStatus, restData = statget.request(url, method) data = json.loads(restData.decode("UTF-8")) # u2version = (data["u2version"]) pprint (u2version) # method = "PUT" # putDATA={ '_id' : ''+custid+'', '_original': 'null', '_synonym': 'null', 'activity': '', 'address': ['4600 South Ulster Street'], 'avg_out': '', 'categories_liked': ['C'], 'city': 'Denver', 'cur_balance': '0.00', 'name': 'Seagoon, Neddy', 'nbr_tapes': '', 'num_rentals': '', 'phone': '8007293553', 'state': 'CO', 'up_name': '', 'zip': '80237' } # putDATA = json.dumps(putDATA) statput = httplib2.Http(".cache") headers = {"Content-type": "application/json;charset=utf-8", "If-Match": (u2version)} restStatus, restData = statput.request(url,method, putDATA,| headers=headers) # print ("\nResponse Status: ", restStatus.status) data = json.loads(restData.decode("UTF-8")) pprint(data) #
Code Samples
135
Python for UniData: HTTP DELETE
The following example demonstrates how to use the HTTP DELETE function in U2 REST. An HTTP GET request is called first, followed by the HTTP DELETE request. An existing RECORD ID record, based on the CUSTID parameter, is deleted. The value for the u2version parameter must be used in the If-Match HTTP DELETE header.
import httplib2 import json from pprint import pprint # custid= str(input("WHICH ID WOULD YOU LIKE TO Delete? ")) url = "http://myserver.com:9191/demo/Customer/"+custid method = "GET" # statget = httplib2.Http(".cache") restStatus, restData = statget.request(url, method) data = json.loads(restData.decode("UTF-8")) # u2version = (data["u2version"]) #print (u2version) # method = "DELETE" # statdelete = httplib2.Http(".cache") headers = {"Content-type": "application/json;charset=utf-8", "If-Match": (u2version)} restStatus, restData = statdelete.request(url,method, headers=headers) # print ("\nResponse Status: ", restStatus.status)
U2 RESTful Web Services Help
136
Python for UniData: REST subroutine
This program calls a U2 subroutine from the U2 REST Server with HTTP POST. Data in the procDATA indata field is sent to the U2 subroutine. Data from the subroutine attaches to the indata field and displays as returned data in the outdata field, as shown:
Note: U2 REST service fields are case sensitive.
import httplib2 import json from pprint import pprint # inpdata = str(input("Enter the data to send to RETSUB: ")) url="http://myserver.com:9191/demo/subroutine/RETSUB" method="POST" headers = {"Content-type": "application/json;charset=utf-8"} # # Customer Record to be written to record CUSTID # procDATA={ 'indata' : ''+inpdata+'', } procDATA = json.dumps(procDATA) # stat = httplib2.Http(".cache") restStatus, restData = stat.request(url,method, procDATA, headers) # print ("\nResponse Status: ", restStatus.status) data = json.loads(restData.decode("UTF-8")) pprint(data)
Code Samples
137
Python for UniVerse code samples
The U2 RESTful Web Services sample codes in this section are written for UniVerse in Python. The Python examples demonstrate the following methods:
• HTTP GET • HTTP POST • HTTP PUT • HTTP DELETE • RESTSUB - An HTTP subroutine
The examples in this section were written using Python 3.2. Refer to www.Python.org for more information on Python.
Note: The samples in this appendix are provided to demonstrate how Python can be used within U2 RESTful Web Services. UniData and UniVerse do not offer any support for Python.
U2 RESTful Web Services Help
138
Python for UniVerse: HTTP GET
The HTTP GET method can only be used on U2 REST data resources.
The following example illustrates a typical HTTP GET request. The request calls the U2 REST server using a GET statement, and then returns a customer record based on the requested CUSTID:
import httplib2 import json from pprint import pprint # # This program calls the CUSTOMER file in UniVerse HS.SALES account with HTTP GET. This call returns a Customer record based on custid # Use custid = 2 # Wr # custid = str(input("WHICH CUSTOMER record ID would you like to GET? ")) url = "http://myserver.com:9193/HS_SALES/Customer/"+custid method="GET" # stat = httplib2.Http(".cache") restStatus, restData = stat.request(url, method) # print ("\nResponse Status: ", restStatus.status) # data = json.loads(restData.decode("UTF-8")) pprint(data)
Code Samples
139
Python for UniVerse: HTTP POST
The HTTP POST method is used to create a new data record or to call a BASIC subroutine. The following example demonstrates how to use the HTTP POST request. In this program, we call the U2REST server using an HTTP POST request. The request then uses postData information to create a new record based on the CUSTID parameter.
import httplib2 import json from pprint import pprint # custid = str(input("Enter Unique Customer ID to create: ")) url="http://myserver.com:9193/HS_SALES/Customer" method="POST" headers = {"Content-type": "application/json;charset=utf-8"} # # Customer Record to be written to record CUSTID # postDATA={ 'statename' : 'Colorado', 'state' : 'CO', 'fname' : 'Neddy', 'city' : 'Denver', 'lname' : 'Seagoon', 'sal' : 'Mr.', 'phone' : '8007293553', 'custid' : ''+custid+'', 'addr1' : '4700 South Syracuse Street', 'addr2' : '', 'zip' : '80237', 'company' : 'IBM Corporation.', } # postDATA = json.dumps(postDATA) stat = httplib2.Http(".cache") restStatus, restData = stat.request(url,method, postDATA, headers) # print ("\nResponse Status: ", restStatus.status) data = json.loads(restData.decode("UTF-8")) pprint(data)
U2 RESTful Web Services Help
140
Python for UniVerse: HTTP PUT
The following example demonstrates a typical GET/PUT combination being used to update a resource. A GET request executes to retrieve the contents of the u2version parameter, which is the record’s LastUpdate ID. The client program then calls the U2 REST server with an HTTP PUT request, using the postData information to modify an existing record based on the CUSTID parameter. The value of the u2version parameter must be used in the If-Match HTTP header.
import httplib2 import json from pprint import pprint # custid= str(input("WHICH ID WOULD YOU LIKE TO Update? ")) url="http://myserver.com:9193/HS_SALES/Customer/"+custid method = "GET" # statget = httplib2.Http(".cache") restStatus, restData = statget.request(url, method) data = json.loads(restData.decode("UTF-8")) # u2version = (data["u2version"]) pprint (u2version) method = "PUT" # putDATA ={ 'statename' : 'Colorado', 'state' : 'CO', 'fname' : 'Neddy', 'city' : 'Denver', 'lname' : 'Seagoon', 'sal' : 'Ms.', 'phone' : '(800)729-3553', 'custid' : ''+custid+'', 'addr1' : '4600 South Ulster Street.', 'addr2' : '', 'zip' : '80237', 'company' : 'Rocket Software, Inc.' } # putDATA = json.dumps(putDATA) statput = httplib2.Http(".cache") headers = {"Content-type": "application/json;charset=utf-8", "If-Match": (u2version)} restStatus, restData = statput.request(url,method, putDATA, headers) # print ("\nResponse Status: ", restStatus.status) data = json.loads(restData.decode("UTF-8")) pprint(data)
Code Samples
141
Python for UniVerse: HTTP DELETE
The following example demonstrates how to use the HTTP DELETE function in U2 REST. An HTTP GET request is called first, followed by an HTTP DELETE request. An existing RECORD ID record, based on the CUSTID parameter, is deleted. The value for the u2version parameter must be used in the If-Match HTTP DELETE header.
import httplib2 import json from pprint import pprint # custid= str(input("WHICH ID WOULD YOU LIKE TO Delete?")) url="http://myserver.com:9193/HS_SALES/Customer/"+custid method = "GET" # stat = httplib2.Http(".cache") restStatus, restData = stat.request(url, method) # data = json.loads(restData.decode("UTF-8")) # u2version = (data["u2version"]) #print (u2version) # method = "DELETE" # headers = {"Content-type": "application/json;charset=utf-8", "If-Match": (u2version)} restStatus, restData = stat.request(url,method, headers=headers) # print ("\nResponse Status: ", restStatus.status)
U2 RESTful Web Services Help
142
Python for UniVerse: REST subroutine
This program calls a U2 Subroutine from the U2 REST Server with HTTP POST. Data in the procDATA indata field is sent to the U2 subroutine. Data from the subroutine attaches to the indata field and displays as returned data in the outdata field, as shown:
Note
U2 REST service fields are case sensitive.
import httplib2 import json from pprint import pprint # inpdata = str(input("Enter the data to send to RETSUB: ")) url="http://myserver.com:9193/HS_SALES/subroutine/RETSUB" method="POST" headers = {"Content-type": "application/json;charset=utf-8"} # # Customer Record to be written to record CUSTID # procDATA={ 'indata' : ''+inpdata+'', 'outdata': '', } procDATA = json.dumps(procDATA) # stat = httplib2.Http(".cache") restStatus, restData = stat.request(url,method, procDATA, headers) # print ("\nResponse Status: ", restStatus.status) data = json.loads(restData.decode("UTF-8")) pprint(data)
Code Samples
143
U2 Basic subroutine
The following U2 BASIC Subroutine UDOSUB performs a tax calculation on the input data from the U2REST Server.
The input JSON object from the U2REST server attaches to the INJSON parameter and performs a tax calculation on the subtotal parameter. The subtotal, Tax and Total value pairs are returned as JSON objects in the OUTJSON parameter.
The OUTJSON parameter must be a correctly formed JSON object if the data has been manipulated inside a subroutine. U2 Dynamic Object (UDO) is the perfect consumer and provider of a JSON object.
Refer to the UniData UniBasic Extensions manual for more information about the U2 Dynamic Object.
$INCLUDE INCLUDE UDO.H udohandle = "" STATUS =UDORead(INJSON, UDOFORMAT_JSON, udoHandle ) propertyName = "subTotal" STATUS = UDOGetProperty(udoHandle, propertyName, valueOut, valueTypeOut) TAX = valueOut * 0.085 TOTAL = valueOut + TAX STATUS = UDOSetProperty(udoHandle, "tax", TAX) totalProperty = "total" STATUS = STATUS = UDOSetProperty(udoHandle, totalProperty, TOTAL) STATUS = UDOWrite(udoHandle, UDOFORMAT_JSON, OUTJSON) RETURN
After you create the subroutine, set up the parameters for your subroutine service in the U2 RESTful Web Services developer. It should look similar to the following example:
U2 RESTful Web Services Help
144
When you run the subroutine service in the U2 RESTful Web Services developer, the return value should look similar to the following:
Code Samples
145
Output types
The following example shows how to create a multivalue array in a subroutine, based on a RESTful service.
Subroutine
When creating a RESTful call to a BASIC subroutine, the inputs and outputs can be defined as one of the following:
Input/Output type Description
String The contents of the variable are returned as one long string in the response.
Dynamic array Attributes, values and sub-values are mapped to JSON.
JSON The variable returned from the subroutine returns a JSON string.
The following subroutine returns all three output types: String, Dynamic array, and JSON.
SUBROUTINE exampleSub( string, dynamicArray, json ) * Start by building a simple U2 Dynamic array OUTPUT = "" OUTPUT<1> = "Doe, John" OUTPUT<2> = "34" OUTPUT<3,1> = "Jane" OUTPUT<3,2> = "Jim" * * Returns the same data for both the string and dynamic array. string = OUTPUT dynamicArray = OUTPUT * ** Create a JSON string from the data in the dynamic array json = '{ name: "':OUTPUT<1>:'", age: ':OUTPUT<2>:', children: [ "':OUTPUT<3, 1>:'", "':OUTPUT<3,2>'" ] }' * RETURN
Procedure
1. Add the subroutine to a DIR type file, and then compile and catalog the subroutine so that it is visible to the Restful web server.
2. In the RESTful web services developer, create a subroutine resource for the subroutine you cataloged in the previous step. Define the input/output parameters based on your subroutine. In this example, only the output parameters are defined. When you are done defining the subroutine resource output parameters, click Finish.
U2 RESTful Web Services Help
146
3. From the U2 REST Servers pane, double-click the dynamic array for which you want to define the fields. The Edit Dynamic Array dialog box opens. Enter the data type information for your dynamic array. In this example, name and age are single-valued data types and children is a multivalued data type. When you are done, click Finish.
Code Samples
147
4. From the U2 REST server pane, double-click the name of the subroutine to run the test subroutine service. The results appear in the Test Browser. Click Call Service to invoke the RESTful service and view the multivalued output you defined earlier. In this example, age is returned as a number type.
Note
The string type returns the attribute marks and value marks, the dynamic array returns the value mapped as a JSON object (all values are strings), and the JSON output type allows you to create more complex JSON requests in the subroutine.