11.3.1

Web Services Guide Web Services Guide

Product version: 11.3.1 Release date: 12-07-18 Document identifier: WebServicesGuide1812040101

Copyright © 1997, 2018 Oracle and/or its affiliates. All rights reserved.

This and related documentation are provided under a license agreement containing restrictions on use and disclosure and are protected by intellectual property laws. Except as expressly permitted in your license agreement or allowed by law, you may not use, copy, reproduce, translate, broadcast, modify, license, transmit, distribute, exhibit, perform, publish, or display any part, in any form, or by any means. Reverse engineering, disassembly, or decompilation of this software, unless required by law for interoperability, is prohibited.

The information contained herein is subject to change without notice and is not warranted to be error-free. If you find any errors, please report them to us in writing.

If this is software or related documentation that is delivered to the U.S. Government or anyone licensing it on behalf of the U.S. Government, the following notice is applicable:

U.S. GOVERNMENT END USERS: Oracle programs, including any operating system, integrated software, any programs installed on the hardware, and/or documentation, delivered to U.S. Government end users are "commercial computer software" pursuant to the applicable Federal Acquisition Regulation and agency-specific supplemental regulations. As such, use, duplication, disclosure, modification, and adaptation of the programs, including any operating system, integrated software, any programs installed on the hardware, and/or documentation, shall be subject to license terms and license restrictions applicable to the programs. No other rights are granted to the U.S. Government.

This software or hardware is developed for general use in a variety of information management applications. It is not developed or intended for use in any inherently dangerous applications, including applications that may create a risk of personal injury. If you use this software or hardware in dangerous applications, then you shall be responsible to take all appropriate fail-safe, backup, redundancy, and other measures to ensure its safe use. Oracle Corporation and its affiliates disclaim any liability for any damages caused by use of this software or hardware in dangerous applications.

Oracle and are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective owners.

Intel and Intel Xeon are trademarks or registered trademarks of Intel Corporation. All SPARC trademarks are used under license and are trademarks or registered trademarks of SPARC International, Inc. AMD, Opteron, the AMD logo, and the AMD Opteron logo are trademarks or registered trademarks of Advanced Micro Devices. UNIX is a registered trademark of The Open Group.

This software or hardware and documentation may provide access to or information about content, products, and services from third parties. Oracle Corporation and its affiliates are not responsible for and expressly disclaim all warranties of any kind with respect to third-party content, products, and services unless otherwise set forth in an applicable agreement between you and Oracle. Oracle Corporation and its affiliates will not be responsible for any loss, costs, or damages incurred due to your access to or use of third-party content, products, or services, except as set forth in an applicable agreement between you and Oracle.

Documentation Accessibility: For information about Oracle's commitment to accessibility, visit the Oracle Accessibility Program website at http://www.oracle.com/pls/topic/lookup?ctx=acc&id=docacc.

Access to Oracle Support: Oracle customers that have purchased support have access to electronic support through My Oracle Support. For information, visit http://www.oracle.com/pls/topic/lookup?ctx=acc&id=info or visit http://www.oracle.com/pls/topic/lookup?ctx=acc&id=trs if you are hearing impaired. Table of Contents

1. Creating and Using Web Services ...... 1 Web Services ...... 2 Creating Custom Web Services ...... 4 JAX-RPC Support ...... 4 Automatic Generation of Web Services ...... 4 Session and Security Support ...... 4 Method Limitations ...... 5 Web Service Creation Wizard ...... 5 Anatomy of a Web Service ...... 7 Web Service Security ...... 12 Deploying Web Services ...... 13 Managing Web Services ...... 14 Creating JMS Web Services ...... 15 Using the JMS Message Web Service Wizard ...... 16 Structure of a JMS Web Service ...... 16 Patch Bay Configuration ...... 17 Creating Repository Web Services ...... 18 Using the Repository Web Service Wizard ...... 18 Repository Web Service Limitations ...... 19 Modifying Repository Web Services ...... 20 RepositoryService Class ...... 20 Repository to XML Data Binding ...... 21 Mapping Files and XML Schemas ...... 22 Repository Operations ...... 29 Accessing Web Services from Java Clients ...... 35 About Web Services ...... 35 Before You Begin Using a Java Client ...... 36 Writing a CookieContainer Class ...... 37 Calling Web Services from a Java Client ...... 39 Creating a Serializer and Deserializer ...... 42 Accessing Web Services from .NET Clients ...... 44 About Web Services in the Oracle Commerce Platform ...... 44 Before You Begin Using a .NET Client ...... 46 Calling Web Services from a .NET Client ...... 47 Using the Atg.DotNet.WebService API with RepositoryItems ...... 49 2. Introduction to REST Web Services ...... 55 REST Web Services Overview ...... 55 REST Web Services URLs ...... 56 HTTP Request Methods ...... 56 HTTP Status Codes ...... 57 Returning Data ...... 58 Using cURL for Examples ...... 58 Writing cURL Examples ...... 58 Server Response to cURL Examples ...... 59 cURL Command Components ...... 60 Adding Control Parameters ...... 61 Functional Parameters for Oracle Commerce Platform REST Web Services ...... 62 Using Positional Parameters ...... 63 Using URL Parameters ...... 63 Using Message Body Parameters ...... 63 I. Oracle Commerce Platform JAX-RS REST Web Services ...... 65

Web Services Guide iii 3. The Oracle Commerce Platform JAX-RS Framework ...... 67 Framework Overview ...... 67 Support for OAUTH 2.0 ...... 69 API Versioning ...... 70 Filtering the Requests ...... 70 Wrapping the Endpoint Methods ...... 70 Caching ...... 71 Converting Responses ...... 71 Configuring Caching and Locking ...... 72 Working with Multiple Sites ...... 72 4. Writing Resources and Endpoints ...... 73 Before You Begin ...... 73 Creating Naming Standards ...... 73 Types of Resources ...... 73 Working with Endpoints ...... 73 Using the REST Entry Point ...... 74 Using Utility Classes ...... 74 Working with Resource Representation Models ...... 75 Using Embedded Resources ...... 76 Understanding Sub-Resource Locators ...... 76 Working with URIs ...... 77 Working with REST Resource Nucleus Components ...... 78 Registering Nucleus Resources ...... 79 Resolving a Non-Nucleus Component in the Endpoint or Resource Class ...... 80 Extending the Framework ...... 80 Working with Resource Metadata ...... 80 Annotating Resource Classes ...... 81 Annotating Endpoint Methods ...... 81 Returning Hypermedia Endpoint Methods ...... 82 Naming Fields ...... 82 Representing Resources ...... 82 Working with Links ...... 84 Understanding Link Relations ...... 85 Automatically Adding Endpoint Links ...... 87 Excluding Links in the Response ...... 87 Using Links with HATEOAS ...... 88 Understanding Collection Resources ...... 88 Configuring Pagination for Collection Resources ...... 89 Running Methods Before or After Endpoints ...... 91 Invoking a Method Before an Endpoint ...... 91 Working with Transactions ...... 92 Invoking a Method After an Endpoint ...... 92 Enabling Locking ...... 93 Handling Exceptions ...... 94 Validating Input and Filtering Output ...... 95 Validating Input ...... 95 Filtering Output ...... 98 Setting Server-Side Security ...... 103 Configuring Endpoint Security ...... 104 Configuring Access Checkers ...... 104 Defining Security Mapping ...... 105 Working with Caching ...... 106 Configuring Server-Side Caching ...... 107

iv Web Services Guide Working with Client-Side Caching ...... 107 Setting Language Support ...... 108 Working with Form Handlers ...... 109 Working with REST Actor Endpoints ...... 110 Working with Statelessness ...... 110 Passing State Data in the HTTP Header ...... 111 Passing State Data in the HTTP Body ...... 111 Understanding Oracle Core Commerce-Specific Statelessness ...... 112 Example of Creating an Endpoint ...... 113 Self Documenting with Swagger ...... 114 Setting up Context or Versions ...... 114 Using Swagger Annotations ...... 114 Adding Swagger Annotation ...... 117 Using Validator and Filter Definitions ...... 118 5. Working with the Payload Schema ...... 121 Understanding Validator Components ...... 121 Validator Components ...... 123 Configuring the Validator Context Class ...... 124 Using the Payload Schema Registry ...... 125 Validating Simple Properties ...... 126 Validating Child Repository Items ...... 128 Exposing Sub-Properties ...... 129 Working with Sub-Classes and Repository Sub-Types ...... 129 Validating Maps and Collections ...... 131 Wrapping a Validator ...... 132 Validating Inter-Related Properties ...... 132 II. Oracle Commerce Platform REST MVC Web Services ...... 135 6. Installing and Configuring the REST MVC Server ...... 137 Installing the REST MVC Module ...... 137 Enabling REST Services ...... 137 Using Dynamo Session Confirmation Numbers ...... 138 7. The REST MVC Definition Framework ...... 139 Architecture Overview ...... 139 REST MVC Service Flow Example ...... 139 Actor Types ...... 140 Request URLs ...... 141 XML Definition Elements ...... 141 The Actor-Template Element ...... 142 The Actor-Chain Element ...... 143 The Actor Element ...... 143 The Component Element ...... 145 The Droplet Element ...... 149 The Form Element ...... 152 The JSP Element ...... 157 The Output Element ...... 160 The Input Element ...... 161 The Depends and Depends-If-Present Element ...... 162 The Set Variable Element ...... 163 Actor XML Definition File Examples ...... 164 Working with Implicit Objects ...... 166 Combining Actor Definitions ...... 168 Bean Filtering ...... 169 The Bean Element ...... 170

Web Services Guide v The Filter Element ...... 171 The Property Element ...... 173 The Attribute Element ...... 175 The Repository Element ...... 175 The Item-Descriptor Element ...... 176 Working with Filters ...... 176 Configuring REST MVC Output ...... 177 REST MVC Access Control ...... 178 Example: External User Access Control ...... 178 Example: Internal User Access Control ...... 178 Creating a New REST MVC Call ...... 179 8. External REST MVC Service Call Examples ...... 183 External Service Call Workflow Example ...... 183 Getting the Session Confirmation Number ...... 184 Specifying Site Context in a Multisite Environment ...... 184 Working with Customers ...... 184 Logging In Customers ...... 185 Logging Out Customers ...... 185 Creating New Customer Profiles ...... 186 Editing or Updating a Customer Profile ...... 187 Viewing a Customer Profile ...... 189 Viewing the Shopping Cart ...... 189 Working with the Shopping Cart ...... 192 Adding Multiple Items to the Shopping Cart ...... 193 Adding an Item to a Shopping Cart ...... 194 Updating the Shopping Cart by SKU ID ...... 195 Updating the Shopping Cart by Commerce ID ...... 195 Updating the Shopping Cart By Shipping Group Relationship ID ...... 196 Removing and Adding an Item to the Cart ...... 196 Removing an Item From the Shopping Cart ...... 196 Removing an Item From the Shopping Cart By Relationship ID ...... 197 Starting the Checkout Process ...... 197 Working with the Shipping Page ...... 197 Displaying Shipping Groups ...... 198 Specifying the Default Shipping Group ...... 199 Applying the Default Shipping Group ...... 199 Obtaining the Current Shipping Info List ...... 200 Applying Shipping Groups and Shipping Methods ...... 200 Splitting Commerce Items into Different Shipping Groups ...... 200 Displaying Available Shipping Methods ...... 201 Creating a New Hardgood Shipping Group ...... 201 Editing a Shipping Group ...... 202 Working with the Billing Page ...... 203 Display the Billing Page ...... 204 Specifying the Default Payment Group ...... 205 Applying Default Payment Group ...... 205 Obtaining Current Payment Info Lists ...... 206 Applying Multiple Payment Groups to an Order ...... 208 Creating a New Credit Card ...... 209 Updating a Credit Card ...... 210 Working with Catalogs ...... 211 Identifying if Fractional Quantities Are Allowed ...... 211 Getting the User’s Current Catalog ...... 212

vi Web Services Guide Browsing the Catalog By Category ID ...... 213 Browsing the Catalog by Product ID ...... 214 Browsing the Catalog by SKU ID ...... 215 Return Product Prices ...... 215 Return Product Summary Prices ...... 216 Getting Product Prices ...... 216 Getting Lowest and Highest Prices for a Product ...... 217 Getting List Price and Sale Prices for a SKU ...... 217 Working with Orders ...... 218 Looking Up an Order by Order ID or User ID ...... 218 Cancelling or Deleting an Order ...... 219 Saving an Order ...... 220 Claiming a Coupon ...... 220 Confirming an Order ...... 220 Committing an Order ...... 224 Sending Order Confirmation ...... 224 Obtaining Closeness Qualifiers ...... 224 Working with Returns and Exchanges ...... 225 Initiating a Return ...... 226 Selecting Items to Return ...... 226 Getting Return Reason Codes ...... 228 Confirming a Return ...... 229 Displaying Return Confirmation Details ...... 229 Canceling a Return ...... 229 Returning Refund Methods ...... 230 Applying Non-Default Refund Values ...... 230 Identifying Returnable Orders ...... 231 Viewing Details of Returned Items ...... 231 Reviewing Return History ...... 231 Showing Non-Return Items ...... 232 Identifying if an Order is Part of an Active Return ...... 232 Updating Credit Cards for a Returns ...... 232 Displaying Lost Promotions ...... 233 Working with Gift Lists ...... 234 Creating a Gift List ...... 234 Updating a Gift List ...... 235 Adding Items to a Gift List ...... 236 Adding Items to a Wish List ...... 236 Removing Items from a Gift List ...... 237 Removing Items from a Wish List ...... 237 Moving Items to a Gift or Wish List from a Shopping Cart ...... 237 Deleting a Gift List ...... 238 Viewing the Current Profile’s List of Gift Lists ...... 238 Viewing a Gift List ...... 239 Viewing a Gift List’s Items ...... 239 Viewing a Wish List ...... 241 Searching for a Gift List ...... 242 Working with In-Store Pickup ...... 244 Searching for a Store ...... 244 Displaying Search Results for In-Store Pickup ...... 245 Identifying a State ...... 245 9. Internal REST MVC Service Call Examples ...... 247 Internal REST MVC Service Calls Workflow Example ...... 247

Web Services Guide vii Getting the Internal Session Confirmation Number ...... 248 Logging Agents In and Out ...... 249 Logging In Agents ...... 249 Logging Out Agents ...... 249 Confirming Log Out ...... 250 Changing Agents Passwords ...... 250 Setting Default Login Page ...... 251 Restoring Defaults ...... 251 Working with Calls ...... 251 Starting a Call ...... 251 Ending a Call ...... 252 Adding a Call Note ...... 253 Working with Tickets ...... 254 Selecting a Ticket to Work On ...... 255 Creating a New Ticket ...... 255 Saving a Ticket ...... 256 Associating a Ticket ...... 256 Escalating a Ticket ...... 257 Closing a Ticket ...... 258 Releasing a Ticket ...... 258 Deferring a Ticket ...... 259 Reassigning a Ticket ...... 260 Sending a Ticket to a Group ...... 260 Closing a Ticket as Duplicate ...... 261 Editing a Ticket ...... 261 End Editing a Ticket ...... 262 Viewing Active Tickets ...... 263 Looking Up a Ticket ...... 264 Searching for a Ticket ...... 268 Reviewing a Ticket Status ...... 270 Viewing a Customer ...... 270 Working with Customer Profiles ...... 271 Creating a New Customer Profile ...... 271 Updating an Existing Customer Profile ...... 273 Adding a Note to a Customer Profile ...... 274 Searching for a Customer Profile ...... 274 Clearing a Customer Search Session ...... 276 Selecting a Customer to Work On ...... 276 Working with Customer Profile Addresses ...... 277 Adding an Address to a Customer Profile ...... 278 Editing an Address in a Customer Profile ...... 279 Deleting an Address from a Customer Profile ...... 279 Working with Credit Cards Within a Customer Profile ...... 280 Adding a Credit Card to a Customer Profile ...... 280 Editing a Credit Card in a Customer Profile ...... 281 Deleting a Credit Card from a Customer Profile ...... 283 Viewing a Customer’s Shopping Cart ...... 283 Working with a Customer’s Shopping Cart ...... 286 Adding Multiple Items to a Customer’s Shopping Cart ...... 287 Adding Items to a Customer’s Shopping Cart ...... 288 Updating the Customer’s Shopping Cart by SKU ID ...... 289 Updating the Customer’s Shopping Cart by Commerce ID ...... 289 Updating the Customer’s Shopping Cart By Shipping Group Relationship ID ...... 290

viii Web Services Guide Removing and Adding an Item to the Customer’s Shopping Cart ...... 290 Removing an Item From the Customer’s Shopping Cart ...... 290 Removing an Item From a Customer’s Shopping Cart By Relationship ID ...... 291 Starting the Checkout Process with SKU ID ...... 291 Starting the Checkout Process with Commerce ID ...... 291 Starting the Checkout Process with Relationship ID ...... 292 Changing the SKU of an Item ...... 292 Assisting the Customer with the Shipping Page ...... 292 Displaying Available Shipping Groups ...... 293 Specifying a Single Shipping Group ...... 293 Specifying Multiple Shipping Groups ...... 294 Splitting Items into Different Shipping Groups ...... 294 Applying Shipping Methods ...... 295 Displaying All Available Shipping Methods ...... 296 Creating New Hardgood Shipping Groups ...... 296 Editing a Hardgood Shipping Group ...... 297 Obtaining the Customer’s Current Shipping Info List ...... 298 Assisting the Customer with the Billing Page ...... 298 Display the Customer’s Payment Groups ...... 299 Getting Available Payment Information ...... 299 Claiming Store Credit or a Gift Certificate ...... 301 Claiming a Customer’s Coupon ...... 302 Applying Multiple Payment Groups ...... 302 Working with Credit Cards Within an Order ...... 303 Getting a Customer’s Existing Address ...... 303 Adding a Credit Card to an Existing Address in an Order ...... 303 Adding a Credit Card to a New Address in an Order ...... 304 Updating a Credit Card in an Order ...... 305 Assisting Customers with Orders ...... 306 Creating New Orders ...... 306 Viewing the Current or Active Customer ...... 307 Viewing the Customer Order History ...... 307 Searching and Clearing Searches for an Order ...... 309 Finding an Order by Order ID ...... 311 Selecting an Order to Work On ...... 311 Cancelling or Deleting the Current Order ...... 312 Viewing Cross Sell Items in a Shopping Cart ...... 313 Saving or Committing an Order ...... 314 Confirming a Customer’s Order ...... 315 Sending a Customer Order Confirmation ...... 317 Modifying a Submitted Order ...... 318 Submitting a Modified Order ...... 318 Duplicating an Order ...... 319 Adding a Note to a Customer’s Current Order ...... 319 Adding a Note to a Customer’s Original Order ...... 320 Creating a Quote for a Customer’s Order ...... 320 Working with Scheduled Orders ...... 321 Creating a Scheduled Order ...... 321 Updating a Scheduled Order ...... 324 Submitting a Scheduled Order ...... 325 Activating a Scheduled Order ...... 326 Deactivating a Scheduled Order ...... 326 Displaying Scheduled Order Details ...... 327

Web Services Guide ix Displaying Scheduled Order Confirmation ...... 328 Working with Scheduled Order Templates ...... 328 Creating a Template from a Scheduled Order ...... 329 Validating a Scheduled Order Template ...... 329 Sending E-Mail Confirmation for a Scheduled Order Template ...... 330 Identifying a Template Order ...... 330 Reviewing a Template ...... 330 Viewing a Template Order List of Submitted Orders ...... 331 Viewing a User’s List of Template Orders ...... 332 Adjusting Customer’s Orders ...... 333 Adjusting a Customer’s Order ...... 333 Deleting an Adjustment from a Customer’s Order ...... 334 Overriding an Item’s Price in the Customer’s Order ...... 334 Viewing the Adjustment Limits ...... 335 Viewing the Reason Code for an Adjustment ...... 335 Assisting Customers with Catalogs ...... 335 Getting the Customer’s Current Catalog ...... 336 Browsing the Customer’s Catalog By Category ID ...... 336 Browsing the Customer’s Catalog By Product ID ...... 337 Searching for Catalogs with Criteria ...... 337 Working with the Current Catalog ...... 338 Obtaining Product Prices ...... 339 Getting Price Ranges for a Product ...... 339 Obtaining List Price and Sale Prices for a Product by SKU ...... 340 Working with Customer’s Price Lists ...... 340 Selecting a Current Price List ...... 341 Retrieving the Current Price List ...... 341 Resetting the Current Price List ...... 341 Searching for a Price List ...... 342 Working with Customer’s Promotions ...... 342 Getting Available Promotions ...... 343 Updating Prices After Promotions ...... 344 Adding a Promotion ...... 344 Removing a Promotion ...... 345 Include Promotions from Wallet ...... 345 Ignoring Promotions from Wallet ...... 345 Saving the Promotions Wallet ...... 346 Reverting the Promotions Wallet ...... 346 Obtaining Closeness Qualifiers ...... 346 Searching for Promotions ...... 347 Adding Store Credit ...... 348 Displaying Lost Promotions ...... 348 Displaying Changed Promotions ...... 348 Working with Customer’s Gift Lists ...... 349 Creating a Customer’s Gift or Wish List ...... 349 Updating a Customer’s Gift or Wish List ...... 351 Adding Items to a Customer’s Gift List ...... 352 Adding Items to a Customer’s Wish List ...... 353 Removing Items from a Customer’s Gift List ...... 353 Removing Items from a Customer’s Wish List ...... 354 Moving Items to a Gift or Wish List from a Customer’s Shopping Cart ...... 354 Deleting a Customer’s Gift List ...... 354 Viewing a Customer’s Gift List ...... 355

x Web Services Guide Viewing a Customer’s Wish List ...... 356 Searching for a Customer’s Gift List ...... 356 Viewing a List of Customer’s Gift or Wish Lists ...... 358 Assisting Customers with In-Store Pickup ...... 359 Working with Approvals ...... 359 Finding Pending Approvals ...... 359 Approving or Rejecting a Pending Order ...... 360 Assisting the Customer with Returns and Exchanges ...... 361 Returns and Exchange Process Overview ...... 361 Creating a Return ...... 363 Adding Items to a Return Request ...... 364 Obtaining Return Reason Codes ...... 367 Confirming a Return Request ...... 367 Displaying Return Request Confirmation Details ...... 368 Cancelling a Return Request ...... 368 Receiving Return Items ...... 368 Retrieving Available Refund Methods ...... 369 Applying Refunds ...... 369 Displaying Return History ...... 370 Identifying if the Order is Returnable ...... 370 Identifying if an Item is Returnable ...... 370 Identifying if the Order Contains an Active Return ...... 371 Reviewing Details of Returned Items ...... 371 Displaying Non-Return Items ...... 372 Updating a Credit Card for a Returns ...... 372 Applying Appeasements to a Customer’s Order ...... 373 Initiating an Appeasement ...... 374 Applying an Appeasement ...... 374 Validating an Appeasement ...... 374 Submitting an Appeasement ...... 375 Cancelling an Appeasement ...... 375 Sending a Confirmation Message for an Appeasement ...... 375 Approving an Appeasement ...... 376 Rejecting an Appeasement ...... 376 Modifying Refund Values ...... 376 Modify a Refund Value ...... 377 Resetting a Refund Value ...... 377 Responding to Customers ...... 378 Sending a Customer E-Mail ...... 378 Adding an Attachment to an E-Mail ...... 378 Discarding an E-Mail ...... 379 Sending Customer E-Mail and Closing Ticket ...... 379 Working with the Commerce Service Center Environment ...... 380 Obtaining Global Session Information ...... 381 Listing Available Sites ...... 382 Selecting a Site ...... 382 Viewing Messages ...... 383 Working with Ticket Disposition Warnings and Messages ...... 384 Index ...... 387

Web Services Guide xi xii Web Services Guide 1 Creating and Using Web Services

A common requirement for enterprise applications is the ability to share data and business logic with other applications. For example, suppose you have an employee portal built with the Oracle Commerce Platform, and also a payroll system based on some other software package. When a new employee starts, or an existing employee changes his or her marital status, you need to create or modify the employee’s profile in both systems. Ideally, you’ like the employee to be able to make the changes in one application and have those changes automatically propagate to the other application.

One way to address this issue is through Web Services, a widely supported standard for packaging remote procedure calls in an XML-based structure. In the example above, you could create a Web Service that automatically updates an employee’s profile in the employee portal when the information in the payroll system is modified.

The Dynamo Application Framework includes tools that allow you to create custom Web Services that call methods on Nucleus components. These custom Web Services can expose methods on existing Oracle Commerce Platform Nucleus components, or on Nucleus components you write yourself. You can call these Web Services from an external application client, such as the payroll system mentioned above.

The Oracle Commerce Platform packages Web Services as: J2EE applications, in accordance with the JAX-RPC (JSR 101) and Implementing Enterprise Web Services (JSR 109) specifications. Note that this manual assumes that you’re familiar with these specifications and with Web Services in general. For more information about these specifications, see the Java Community Process Web site at:

http://www.jcp.org

The following sections discuss how to create Web Services in the Oracle Commerce Platform, and how to write Java and .NET clients that call these services:

Creating Custom Web Services (page 4)

Creating JMS Web Services (page 15)

Creating Repository Web Services (page 18)

Repository to XML Data Binding (page 21)

Accessing Web Services from Java Clients (page 35)

Accessing Web Services from .NET Clients (page 44)

1 Creating and Using Web Services 1 Web Services

In addition to any Web Services you create, the Oracle Commerce Platform includes a number of prepackaged Web Services that you can call from Java and .NET clients. These services are packaged in three separate application modules. You can include any of these services in an assembled EAR file by including the module that contains the desired services. For example, to include the prepackaged Oracle Commerce Core Commerce Web Services, specify the DCS.WebServices module when you assemble your application.

The following table summarizes these Web Services.

Note: The following services are available in DAS.WebServices. For more information about these Web Services, see the Repository Guide.

Web Application Web Services

Generic Repository Services getRepositoryItem performRQLQuery performRQLCountQuery

The following services are available in DPS.WebServices. For more information about these Web Services, see the Personalization Programming Guide.

Web Application Web Services

User Session loginUser

logoutUser getProfileId setLocale setContactInfo setPassword getProfile createUser updateUser getPasswordHashKey getPasswordHashAlgorithm canClientEncryptPasswords executeRepositoryTargeter

Messaging sendPageVisit sendClickThrough

The following services are available in DCS.WebServices. For more information about these Web Services, see Core Commerce Programming Guide.

2 1 Creating and Using Web Services Web Application Web Services

Order createOrderFromXML submitOrderWithReprice cancelOrder getOrderStatus getOrderAsXML getOrdersAsXML getOrderStatus getCurrentOrderId addItemToOrder addItemToShippingGroup createOrder createOrderForUser removeItemFromOrder setItemQuantity addCreditCardToOrder addShippingAddressOrder removePaymentGroupFromOrder removeCreditCardFromOrder removeShippingGroupFromOrder moveItemBetweenShippingGroups removeItemQuantityFromShippingGroup setOrderAmountToPaymenGroup getDefaultPaymentGroupId getDefaultShippingGroupId

Pricing calculateOrderPrice calculateOrderPriceSummary calculateItemPriceSummary

Promotions grantPromotion revokePromotion claimCoupon getPromotionsAsXML

Inventory getInventory getInventoryStatus setStockLevel setStockLevels

Catalog getProductXMLById getProductXMLByDescription getProductXMLByRQL getProductSkusXML catalogItemViewed

Profile setDefaultShippingAddress setDefaultBillingAddress setDefaultCreditCard getDefaultShippingAddress getDefaultBillingAddress getDefaultCreditCard

1 Creating and Using Web Services 3 Creating Custom Web Services

The Oracle Commerce Platform provides infrastructure and tools that enable you to expose a wide range of functionality as Web Services. There are three kinds of Web Services you can create:

• Web Services that invoke methods on Nucleus components

• Web Services that send JMS messages through Patch Bay

• Web Services that perform operations on repository items

This section describes the infrastructure for creating these services. It focuses on Web Services that invoke Nucleus methods, but most of what is described here applies to all three types of services. For information specific to Web Services that send JMS messages, see the Creating JMS Web Services (page 15) section. For information specific to Web Services that perform repository operations, see the Creating Repository Web Services (page 18) section.

This section includes the following:

Web Service Creation Wizard (page 5)

Anatomy of a Web Service (page 7)

Web Service Security (page 12)

Deploying Web Services (page 13)

Managing Web Services (page 14)

JAX-RPC Support

The Web Services support in the Oracle Commerce Platform is based on JAX-RPC (Java API for XML-based RPC). The JAX-RPC specification defines a standard way for incoming XML-based SOAP messages to be converted to Java-based RPC calls. The Oracle Commerce Platform uses Oracle’s reference implementation of JAX-RPC. Parts of this reference implementation are used to generate Web Services, and other parts of it handle the processing of SOAP messages when a Web Service is called.

Automatic Generation of Web Services

Creating a Web Service by hand can be a laborious process, due to the large number of Java and XML files you must create and package. The Oracle Commerce Platform automates this process through the Web Service Creation Wizard in the Dynamo Administration UI. You select the type of service you want to generate, and the wizard takes you through a series of screens where you specify the necessary information. You then click a button, and the wizard automatically generates the necessary classes, WSDL documents, and deployment descriptors, and packages them in EAR and WAR files.

Session and Security Support

When you create a Web Service, you specify whether it should be executed within the context of an HTTP session. Associating Web Services with a session enables an application to maintain state across Web Service calls and to use login information for security purposes.

4 1 Creating and Using Web Services To enable multiple Web Services to execute within the same session, a client application must pass a session cookie between calls. Some Web Services frameworks, such as Microsoft’s .NET, provide support for passing session cookies. Java clients typically require applications to manage session cookies themselves.

For more information about using sessions with Java clients, see the Accessing Web Services from Java Clients (page 35) section. For more information about using sessions with .NET clients, see the Accessing Web Services from .NET Clients (page 44) section.

Method Limitations

You can create Web Services from most Nucleus methods, both from components Oracle Commerce Platform provides and components that you write. There are, however, some methods that cannot be exposed as valid Web Services. The Web Service Creation Wizard does not create Web Services from these methods. In particular, it enforces the following restrictions by preventing you from selecting these methods:

• You cannot create a Web Service from any method that has a parameter or return type that is an abstract data type (such as a Map, Collection, Interface, abstract class, or an object with abstract data type properties)

• You cannot create a Web Service from any method that has a parameter or return type that is a wrapper class for a primitive data type. The prohibited classes are Byte, Boolean, Character, Integer, Short, Long, Float, and Double. Note, however, that methods that use actual primitives are valid. If there is a method that you want to expose that has one of these wrapper classes as a parameter or return type, you can either rewrite the method to use a primitive instead (if the method’s class is your own custom code), or else subclass the method’s class (if it is a class provided by Oracle Commerce Platform) and overload the method with a version that uses primitives

In addition, you cannot create a Web Service from a method that has the same name and signature as any of the methods of atg.webservice.ManagedComponentProperties or java.lang.Object. Attempting to do so results in a naming conflict, because the service implementation class of each Web Service subclasses atg.webservice.ManagedComponentProperties, which subclasses java.lang.Object. Note that the wizard does not prevent you from selecting these methods, but when you try to generate a Web Service, an exception is thrown and the service generation fails.

Web Service Creation Wizard

The process of creating Web Services is automated by the Web Service Creation Wizard in the Dynamo Administration UI. This wizard guides you through the steps of selecting a Nucleus component and method, specifying input parameters and other settings; it then automatically creates the Web Service by performing the following steps:

• Create the service endpoint interface that specifies the method to be exposed

• Create the service endpoint class that implements the service endpoint interface and is responsible for handing incoming SOAP requests

• Create the WSDL document that describes the resources required by the service endpoint class, as well as its inputs and outputs

• Create the web.xml file for the Web application of which the service is a part

• Create the JAX-RPC deployment descriptor (webservices.xml) and mapping file

• Build the runtime classes

1 Creating and Using Web Services 5 • Package these elements in a JSR 109 compliant EAR file

These steps are described in more detail in the Anatomy of a Web Service (page 7) section.

The wizard uses the component /atg/webservice/WebServiceGenerator to perform the actual work of generating the service. This component of the class atg.webservice. WebServiceGeneratorImpl performs all of the operations listed above, either through its own methods or through other components it refers to.

Using the Wizard

The top-level page of the Dynamo Administration UI includes a Web Service Administration link. This link takes you to the Web Service Administration page, which has three links for working with Web Services:

• Web Service Registry – Takes you to a page for viewing and managing currently loaded Web Services. The Web Services registry is discussed in the section Managing Web Services (page 14)

• Web Service Security Manager – Enables you to create and edit Web Service security configurations. These security configurations can be used to define which users can access specific Web Services. When you create a Web Service, you have the option of associating a security configuration with the service. Security configurations are discussed in the section Web Service Security (page 12)

• Web Service Creation Wizard – Takes you to a page with links for creating each of the three kinds of Web Services (Component Method Web Service, JMS Message Web Service, Repository Web Service)

To create a Web Service that invokes a method on a Nucleus component, starting from the Web Service Administration page:

1. Click the Web Service Creation Wizard link. This takes you to a page titled Select Type, where you can select the type of Web Service to create.

2. Click the Component Method Web Service link. This takes you to the Select Nucleus Component page.

3. On the Select Nucleus Component page, specify the pathname of the Nucleus component you want to create the Web Service from. You can either enter the pathname directly in the field at the top of the page and then click the Next button, or you can use the component browser below it to navigate to the component and select it.

4. On the Select A Method page, select the method you want to expose as a Web Service.

5. If the method requires any input parameters, the Set Parameter Names page provides you with fields for specifying the names of these parameters. The names you specify are used for the parameters of the Web Service call, and can be anything you like.

6. When the Web Service is called, the service passes the values of these parameters to the parameters of the exposed Nucleus method. There is thus a one-to-one correspondence between the parameters of the Web Service call and the parameters of the underlying Nucleus methods.

7. The next two pages are titled EAR Name & Servlet Settings and Enterprise and Web Application Settings. When the wizard creates a Web Service, it packages it in a WAR file, which is in turn packaged in an EAR file. It is possible to have any number of services in a single Web application (WAR file), and any number of Web applications in a single Enterprise application (EAR file). This flexibility gives you a good deal of control over how you deploy your Web Services. For each new Web Service, the wizard can do any of the following:

• Create a new EAR file for the service, and put it in a WAR file within the EAR file

• Use an existing EAR file, and put the service in a new WAR file within it

6 1 Creating and Using Web Services • Put the service in an existing WAR file within an existing EAR file

To add a Web Service to an existing EAR file, you specify that file as the EAR file name on the EAR Name & Servlet Settings page. The Web Application Settings page then gives you the choice of creating a new Web application for the service, or adding the service to an existing Web application.

The wizard also gives you the option of specifying the host name and port number for a Web Service, or of leaving these fields blank. If you leave the fields blank, the values are dynamically assigned at runtime from the URL used for the WSDL file request.

8. The Session & Security Options page allows you to specify whether the Web Service should be executed within the context of an HTTP session. The wizard gives you these options:

• Neither provide a session nor security constraints

• Provide a session, but no security constraints

• Provide both a session and security constraints

If you want to call the Web Service from a client that uses sessions or session sharing, you must choose one of the last two options. If you choose the last option, the wizard then prompts you to select a security configuration. See Web Service Security (page 12) for information about security configurations for Web Services.

9. On the Create EAR File page, click the Create EAR File button to create the Web Service. If there is already an EAR file with the specified name, the wizard first appends .old to the name of the existing file so that new file does not overwrite it.

Once you have created an EAR file, you must deploy it in order to run the Web Services in it. See the Deploying Web Services (page 13) section for more information.

Naming Restrictions

Most of the class names and filenames for Web Services are generated automatically by the wizard. As a result, certain circumstances can result in naming conflicts. For example, if you create a Web Service from a Nucleus method, you cannot then create a second Web Service from another method with the same name (such as an overloaded method) and put it in the same WAR file, even if the two methods have different signatures or capitalization. If you attempt to do this, the second Web Service simply overwrites the first.

To prevent the second service from overwriting the first, put the second service in a different WAR file. In addition, be sure to give the second WAR file a different context root from the first WAR file. (The default value for the context root in the wizard is based on the method name, so you will need to change the value when you run the wizard.) It is then be possible to differentiate calls to the two services based on their context roots.

Anatomy of a Web Service

As mentioned above, the Web Service Creation Wizard automatically performs a number of tasks, greatly simplifying the creation of Web Services from Nucleus components. The wizard enables you to simply create Web Services and begin using them, without needing to understand all of their underpinnings. However, in some cases you may need to troubleshoot or make changes to your Web Services, so it is helpful to have some familiarity with their form and packaging. This section discusses the various pieces that make up a Web Service, including:

• Service endpoint interface and implementation class

1 Creating and Using Web Services 7 • WSDL document

• web.xml file

• JAX-RPC deployment descriptor (webservices.xml) and mapping file

• Runtime classes

• JSR 109 compliant EAR file

Note that the business logic of the Web Service is actually contained in the method of the Nucleus component that is being exposed. The Web Service handles only the RPC infrastructure, and passes the actual processing to the Nucleus component.

Service Endpoint Interface and Implementation Class

The service endpoint interface (SEI) is a Java interface class that defines the methods to be exposed as a Web Service. This interface must extend the java.rmi.Remote interface and each method must throw java.rmi.RemoteException. The SEI for any Web Service generated by the Oracle Commerce Platform has a single method, corresponding to the Nucleus method being exposed.

The service implementation class (also referred to as the service bean) implements the service endpoint interface and handles the actual servicing of incoming SOAP requests. In addition, service implementation classes generated by the Oracle Commerce Platform implement the interface javax.xml.rpc.server.ServiceLifecyle, and extend the atg.webservice.ManagedComponentProperties class, which registers services with the Oracle Commerce Platform Web Service Registry. The Web Service Registry is discussed in the Managing Web Services (page 14) section.

The service endpoint interface and implementation class are generated by the /atg/webservice/ WebServiceGenerator component. The names for these classes are based on the name of the Nucleus method being exposed. For instance, if the Nucleus method is getOrderStatus, the service endpoint interface is named GetOrderStatusSEI, and the implementation class is named GetOrderStatusSEIImpl.

WSDL Document

Web Services Description Language (WSDL) is an XML language for describing Web Services in a platform- independent way. A WSDL document describes a Web Service’s methods by specifying the locations of the resources they use and defining the methods’ inputs and outputs. (A WSDL document for a Web Service generated by the Oracle Commerce Platform always describes one method, because each Web Service can expose only one Nucleus method.)

There must be a separate WSDL document for each Web Service. The WSDL document is generated by the / atg/webservice/WSDLGenerator component, which is of class atg.webservice.WSDLGeneratorImpl. This document is used for two key purposes:

• It is used by the JAX-RPC API to generate runtime classes

• At runtime, it is used by Web Service clients to look up the semantics of the SOAP messages to send to invoke the service

When the Web Service’s input and output values are primitive types, they are defined in the primary WSDL document. For example:

8 1 Creating and Using Web Services

Each non-primitive input or output requires its own WSDL document that is imported by the primary WSDL document. Import statements similar to the following are included in the primary WSDL document when the Web Service is created using the Dynamo Administration UI:

The location specified is relative to the primary WSDL document. Some Web Service clients are able to interpret relative locations, but others require fully qualified URLs. To work with these clients, when the Oracle Commerce Platform receives a request for a WSDL document, it uses the servlet class atg.webservice.WSDLFinderServlet and the filter class atg.webservice.WSDLImportFilter to translate the location value into a fully qualified URL:

1. At runtime, JAXRPCServlet updates the SOAP address in the WSDL document to include the domain host name and port number.

2. When WSDLFinderServlet detects a WSDL request, WSDLImportFilter appends the domain name and port number (from the SOAP address provided by JAXRPCServlet) and the context path (by calling request.getContextPath on the Dynamo request) to the location value in the import statement. The resulting import statement looks similar to this:

The WSDLFinderServlet and WSDLImportFilter classes are declared in the web.xml file for the Web application that the Web Service is a part of, as discussed in the next section. For more information about request handling, see the Platform Programming Guide. web.xml File

The web.xml file is the standard deployment descriptor for the Web application that the Web Service is a part of. It declares the filters and servlets used by the service.

With Oracle Commerce Platform, the servlet that listens for the SOAP request is com.sun.xml.rpc.server.http.JAXRPCServlet. This servlet is part of the JAX-RPC reference implementation, and is responsible for receiving the incoming SOAP request and determining how to dispatch the call. For example, if you create a Web Service called getOrderStatus, the entry for it in the web.xml file looks something like this:

getOrderStatus getOrderStatus com.sun.xml.rpc.server.http.JAXRPCServlet configuration.file WEB-INF/wsconfig/getOrderStatus_Config.properties ...

1 Creating and Using Web Services 9 getOrderStatus /getOrderStatus/*

When a call to the getOrderStatus Web Service is sent to the Oracle Commerce Platform, the JAXRPCServlet receives the request and dispatches it based on the information in the file that the configuration.file parameter points to. This configuration file is included in the WAR file, and looks similar to this:

port0.wsdl.serviceName=GetOrderStatusSEIService port0.tie=webservices.GetOrderStatusSEI_Tie wsdl.transform=true port0.name=getOrderStatus portcount=1 wsdl.location=WEB-INF/getOrderStatus.wsdl port0.servant=webservices.GetOrderStatusSEIImpl port0.wsdl.targetNamespace=http\://www.atg.com/webservices port0.wsdl.portName=GetOrderStatusSEIPort

Note that the port0.servant property is set to the name of the service implementation class. This property designates the class that JAXRPCServlet dispatches the SOAP request to.

Handling Imported WSDL Documents in web.xml

As discussed in the WSDL Document section, there are two resources that assist in handling WSDL requests. These resources are declared in the web.xml file:

• WSDLImportFilter, which is a filter of class atg.webservice.WSDLImportFilter, is mapped to a parent directory that has subdirectories holding WSDL documents

• WSDLFinder, which is a servlet of class atg.webservice.WSDLFinderServlet, should be defined and mapped to each path that will lead to a WSDL document

For example:

WSDLImportFilter atg.webservice.WSDLImportFilter ... WSDLImportFilter /getOrderStatus/* ... WSDLFinder WSDLFinder Used to lookup imported wsdl files. atg.webservice.WSDLFinderServlet ... WSDLFinder atg.commerce.order.status.wsdl

10 1 Creating and Using Web Services WSDLFinder atg.security.wsdl WSDLFinder atg.commerce.wsdl

Web Service Registrar in web.xml

To register Web Services with the Web Services Registry, the web.xml file declares the WebServiceRegistrar servlet, and sets it to load on startup:

WebServiceRegistrar WebServiceRegistrar ATG WebServiceRegistrar for registering servlet web-services. atg.webservice.WebServiceRegistrar 1

For more information about the Web Services Registry, see Managing Web Services (page 14).

Other Elements of web.xml

The web.xml file may declare certain additional elements:

• The servlet atg.nucleus.servlet.NucleusServlet, which runs Nucleus as a servlet within a Web application

• The filter atg.filter.dspjsp.PageFilter, which invokes the DAF request-handling pipeline

• The context parameter atg.session.parentContextName; its value is set to /dyn, which enables the Web Services to share information with the atg_bootstrap.war application

JAX-RPC Deployment Descriptor and Mapping Files

The JAX-RPC deployment descriptor, webservices.xml, provides metadata (such as names and descriptions of the SEIs, service beans, and WSDL documents) about all of the Web Services in a given Web application.

The mapping file defines the association between a WSDL file and an ISEI and implementation class, by mapping namespaces to Java packages. This mapping is used when serializing and deserializing XML files. There is a separate JAX-RPC mapping file for each Web Service, and the name of each file reflects the method the service is based on. For example, if the method is getOrderStatus, the mapping file for the Web Services is named getOrderStatusMapping.xml.

Runtime Classes

The runtime classes are generated using the Oracle JAX-RPC reference implementation. These classes include:

• The tie class that JAXRPCServlet invokes the method on, and which in turn invokes the method on the service implementation class

1 Creating and Using Web Services 11 • Classes for handling serializing and deserializing SOAP requests and responses

JSR 109 Compliant EAR File

The JSR 109 Java specification includes information about how a Web Service should be packaged within an EAR file. The wizard combines all the generated files (class files, web.xml, WSDL document, webservices.xml, and JAX-RPC mapping file) into a WAR file, which is then added to a JSR 109 compliant EAR file.

Web Service Security

When you create a Web Service, you have the option of applying security constraints so that only approved clients (those with administrator privileges, for example) can execute it. You specify the security constraints using a security configuration, which is a repository item that stores information that controls access to the Web Service. You can create any number of different security configurations using the Web Services Administration UI, and you can apply a security configuration to any number of Web Services.

A security configuration has a corresponding security policy component, plus an optional ACL. A security configuration is identified by its functional name, which is a property of the repository item that maps the security configuration to a security component and ACL.

This section describes the main components involved in securing Web Service methods, as well as how to create security configurations through the Web Services Administration UI. For a broader discussion of the Oracle Commerce Platform security API, see the Managing Access Control section in the Platform Programming Guide.

Security Components

There are two primary components involved in securing a Web Service method:

• /atg/webservice/security/NucleusSecurityManager (an instance of atg.webservice.NucleusSecurityManager) uses the security configuration associated with the Web Service to apply the corresponding security policy and ACL, to determine whether to grant or deny access. See NucleusSecurityManager (page 12)

• /atg/webservice/security/NucleusSecurityRepository (an instance of atg.adapter.gsa.GSARepository) stores the Web Service security configurations used by the NucleusSecurityManager. See NucleusSecurityRepository (page 13)

NucleusSecurityManager

At startup time, the NucleusSecurityManager retrieves the repository items from the NucleusSecurityRepository (described below) and creates an internal mapping between each functional name and the SecurityPolicy component and ACL associated with it.

When a client calls a Web Service, the service invokes the hasAccess method on the /atg/webservice/ security/NucleusSecurityManager component, passing it the functional name of the service’s security configuration, the name of the Nucleus component and method exposed by the service, and a Map containing the method’s parameters. The NucleusSecurityManager uses the functional name to find the associated SecurityPolicy component and ACL, applies them to the call, and returns the result (true or false) to the client. If true is returned, the Nucleus method exposed by the Web Service is invoked; if false is returned, access to the method is denied, and an exception of class atg.security.SecurityException is thrown.

If the NucleusSecurityManager is unable to apply the security configuration to a Web Service call (for example, if the SecurityPolicy is not valid), it determines whether to grant access based on the value of its defaultGrantAccess property. The default value of this property is false (deny access).

12 1 Creating and Using Web Services Setting defaultGrantAccess to true facilitates the development process, because it allows any Web Service that does not have an associated security configuration to be called by any client.

For deployment purposes, though, this behavior is undesirable, because of the security risks involved. Therefore, when you enable liveconfig settings for the Oracle Commerce Platform, the defaultGrantAccess property is set to false. Note, however, that this means that each of your Web Services must have an associated security configuration, because any call to a service without a security configuration will fail.

For information about enabling liveconfig settings, see the Platform Installation and Configuration Guide

NucleusSecurityRepository

Web Service security configurations are stored in the NucleusSecurityRepository. This repository includes a single item descriptor called nucleusSecurity, which has properties called functionalName, policy, and ACL. The NucleusSecurityManager parses the items in this repository at startup time.

The Web Services Administration interface provides an easy way to add new security configurations to this repository. See the next section for details.

Creating and Editing Security Configurations

The Web Services Administration page in the Dynamo Server Admin includes a Web Service Security Manager link that takes you to a page that where you can view and edit the security configurations stored in the NucleusSecurityRepository, or create new security configurations.

Follow these steps to create a new security configuration:

1. Click the Create New link.

2. On the Create Security Configuration page, enter a name for the security configuration in the Functional Name field, and click Create New button.

3. On the Edit Web Service Security Configuration page, click the Add buttons to add users, roles, and organizations to the security configuration. You can change the security policy (from the /atg/dynamo/ security/SecurityPolicy default) if necessary.

The new security configuration appears on the main Web Service Security Configurations page. If you need to make changes to it, click the Edit link to open the Edit Web Service Security Configuration page. Note that you cannot change the functional name.

Deploying Web Services

When you create a Web Service, the wizard places the EAR file in the /home directory. The Web Service is not ready to run, however, because it does not include the necessary Nucleus classes.

In order to run the Web Service, these additional steps are necessary:

1. Use the runAssembler command to assemble a Nucleus-based application, using the -add-ear-file flag to incorporate the contents of the Web Services EAR file.

2. Deploy the assembled EAR file on your application server, and start up the application.

For example, if your Web Services EAR file is called WS.ear, you might use a command like this to assemble a Nucleus-based application named MyApp.ear:

1 Creating and Using Web Services 13 runAssembler -add-ear-file WS.ear MyApp.ear -m MyApp DSS

If you make any subsequent changes to the Web Service, you must reassemble and redeploy the application for the changes to take effect.

Note that in addition to any Web Services you create, the Oracle Commerce Platform includes a number of prepackaged Web Services. These services are packaged in three separate application modules. You can include any of these services in an assembled EAR file by including the module that contains the desired services. For example, to include the prepackaged Core Commerce Web Services, specify the DCS.WebServices module when you assemble your application.

For more information about the runAssembler command, see the Platform Programming Guide. For information about deploying EAR files, see the documentation from your application server vendor.

Managing Web Services

The Dynamo Server Admin UI provides a facility for managing the Web Services deployed on your server. To access this facility, open the top-level page of the Dynamo Server Admin UI and click the Web Service Administration link. On the Web Service Administration page, click the Web Service Registry link. This takes you to the page for the /atg/webservice/WebServiceRegistry component, which stores information about the available Web Services.

For example, if the Web Services included with Oracle Commerce Platform are running on your Dynamo server, the top of the page will look similar to this:

The Service Info indicates that there are six Web applications running that include Web Services. You can get more information about the services in a Web application by clicking the Details link next to the application’s name. For example, if you click on the link for the Pricing application, the Service Info looks like this:

14 1 Creating and Using Web Services The lower table summarizes the status of the Web Services in the Web application. The Name and URI Pattern are the values of the display-name and url-pattern tags in the web.xml file, and the WSDL file is the value of the wsdl.location property in the configuration file for the JAXRPCServlet. The Security functional name is the name that the service implementation class passes to the hasAccess method of the NucleusSecurityManager to determine if the client has permission to call the Web Service.

Some of the information shown in this table, such as the functional name, does not appear until the Web Service has been executed. If a service has been executed, the Instance Running and Registered value is true. You can stop a running service by clicking the Off link in the Enabled column. Registering Services

Web Services generated by the Web Service Creation Wizard have the necessary code and configuration information to register the Web Service with the Web Service Registry.

To register the service, the service implementation class extends the class atg.webservice.ManagedComponentProperties, which includes a register method for registering the service. In addition, the web.xml file for the Web application the service is part of declares the WebServiceRegistrar servlet, as described in the Anatomy of a Web Service (page 7) section.

Creating JMS Web Services

In addition to Web Services that call Nucleus methods, the Oracle Commerce Platform enables you to create Web Services that send JMS messages through Patch Bay. Many events in the Oracle Commerce Platform

1 Creating and Using Web Services 15 are triggered by JMS messages, so by calling a Web Service that sends a JMS message, a client can start execution of various services and processes. In particular, scenario actions are triggered by JMS messages, so you can use Web Service calls to invoke scenario actions remotely. For example, suppose a new user registers in some application, which invokes a Web Service that sends the registration information to the Oracle Commerce Platform. The client application could then call a Web Service that sends a JMS message of type atg.dps.Register into Patch Bay, thereby triggering a scenario action that (for instance) sends an e-mail message to the new user.

This section discusses how to create Web Services that send JMS messages, and how to configure components to listen for these messages. For more information about JMS and Patch Bay, see the Dynamo Message System chapter of the Platform Programming Guide.

Using the JMS Message Web Service Wizard

To create a Web Service that sends a JMS message, you use the Web Service Creation Wizard, just as you do for Web Services that invoke Nucleus methods. On the first screen of the wizard, however, you click the JMS Message Web Service link (rather than the Component Method Web Service link). In this version of the wizard, you do not select a Nucleus component and method; instead, the key selections are the message type and the Patch Bay port name to use. The message type is the JMSType value for the message. This is a String, stored in the message’s header, that identifies the kind of message it is. For example, a message of JMSType atg.dps.PageVisit is sent when a site visitor displays a page.

For the port name, the wizard gives you two options, IndividualEvents and GlobalEvents. These are the standard ports where the Scenario Manager listens for scenario events.

The names of the classes generated by the wizard are based on the JMS message type of the message. For example, if you create a Web Service that sends a message whose JMSType is atg.dps.PageVisit, the service implementation interface is named SendPageVisitSEI, and the service implementation class is named SendPageVisitSEIImpl.

Structure of a JMS Web Service

JMS Web Services generated by the wizard are similar to Web Services that call Nucleus methods. JMS services expose a Nucleus method, but it is always the receiveObjectMessage method of the component /atg/ dynamo/messaging/MessageImporter. This method receives the message object and forwards it into Patch Bay.

The receiveObjectMessage method takes three parameters:

• The message object

• A String indicating the JMSType of the message

• A String indicating the Patch Bay port name to use

The Web Service call itself takes only a single argument, the message object. The JMSType and port name are hard-coded when you generate the Web Service, and the service implementation class passes them (along with the message object supplied by the client) to the receiveObjectMessage method. This simplifies the client’s task, because it does not need to be aware of either the JMSType or the port name.

For example, a Web Service that sends a JMS message when a user views a page would be called like this:

public void sendPageVisit(atg.userprofiling.dms.PageVisitMessage a);

16 1 Creating and Using Web Services The service implementation class then calls the receiveObjectMessage method like this:

messageImporter.receiveObjectMessage(a, "atg.dps.PageVisit", "IndividualEvents");

For information about calling Web Services that send JMS messages from Java clients, see the Accessing Web Services from Java Clients (page 35) section. (Note that you cannot use the dynamic process described in that section for calling these Web Services.) For information about calling Web Services that send JMS messages from .NET clients, see the Accessing Web Services from .NET Clients (page 44) section.

Patch Bay Configuration

The /atg/dynamo/messaging/MessageImporter component, whose receiveObjectMessage method is invoked by JMS Web Services, is a Patch Bay message source. When a Web Service invokes the method, the message passed to that method is sent either to the destination patchbay:/sqldms/MessageImporter/ IndividualEvents or to patchbay:/sqldms/MessageImporter/CollectiveEvents, depending on the message type.

The standard Patch Bay configuration file, /atg/dynamo/messaging/dynamoMessagingSystem.xml, includes the necessary declarations for the message source and destinations:

/atg/dynamo/messaging/MessageImporter

IndividualEvents patchbay:/sqldms/MessageImporter/IndividualEvents Topic GlobalEvents patchbay:/sqldms/MessageImporter/CollectiveEvents Queue

1 Creating and Using Web Services 17 The Scenario Manager is a message sink configured to receive messages from these destinations. This configuration occurs in two places:

• In the standard Patch Bay configuration file, the Scenario Manager is configured to receive individual scenario events from the destination patchbay:/sqldms/MessageImporter/IndividualEvents

• In the /atg/dynamo/messaging/dynamoMessagingSystemDSSGlobal.xml file, the Scenario Manager is configured to receive global scenario events from the destination patchbay:/sqldms/MessageImporter/ CollectiveEvents

You can configure other message sinks to receive messages from the patchbay:/sqldms/MessageImporter/ IndividualEvents destination by declaring them in the dynamoMessagingSystem.xml file. Note, however, that you cannot configure other sinks to receive messages from patchbay:/sqldms/MessageImporter/ CollectiveEvents. This destination is a queue, used by global Scenario Managers only; adding sinks to this destination may interfere with the global Scenario Managers receiving messages. If you want another message sink to receive these messages, configure an additional destination for MessageImporter to send global scenario events to, and configure your sink to listen to that destination instead.

Creating Repository Web Services

The Dynamo Serve Admin interface provides an easy, browser-based way to create Web Services based on repository items. This Repository Web Service wizard is part of the Web Service Administration user interface, which is introduced in the Web Service Creation Wizard (page 5) section of the Creating Custom Web Services (page 4) section. You can use the Repository Web Service wizard to create Web Services that add, remove, update, or get a complete repository item, or a single property of a repository item.

Using the Repository Web Service Wizard

To use the Repository Web Service wizard to create a repository Web Service:

1. Open the Dynamo Server Admin interface and navigate to the Web Service Administration > Web Service Creation Wizard > Repository Web Service page.

2. Identify the repository component that the Web Service should access. You can do this in one of two ways. The Create Repository Web Service page displays a text field in which you can enter the Nucleus address of the repository component and click the Submit button. The Create Repository Web Service page also displays a list of all repository components that are registered in the initialRepositories property of the /atg/ registry/ContentRepositories component. You can select a repository component by clicking the link with the Nucleus address of the repository component.

3. The next page, with the heading Select item descriptor, displays all of the item descriptors in the repository component you selected. Click the link for the item descriptor you want to expose in your Web Service.

4. The next page, with the heading Select Method, displays the methods that are available for the item descriptor you selected. For example, if the item descriptor is mutable, the following methods are available:

• add

• remove

• update

18 1 Creating and Using Web Services • get

The Select Method page also allows you to create a Web Service for a specific property. The page displays a list of links for each of the properties of the item descriptor you selected. Click one of these property names to create a Web Service for an individual repository item property.

The property name link leads to a list of the Web Service methods that are available for that repository item property, as well as notes about the Web Service limitations, if any, related to the repository item property. See Repository Web Service Limitations (page 19) for more information.

Click the name of the method you want to expose in your Web Service.

5. In the EAR Name & Servlet Settings page, the Web Service Creation Wizard displays default names for the EAR file and servlet to be created. You can modify the default names. You can also, if you choose, enter a description for the servlet and a network hostname and port number for the Web Service. If you leave the fields blank, the values are dynamically assigned at runtime from the URL used for the WSDL file request. You should generally leave these fields blank, unless you want to require the Web Service to be accessed on a specific server and port.

Enter any settings you want to change and click the Next button.

6. In the Enterprise & Web Application Settings page, the Web Service Creation Wizard displays default names for the enterprise application and Web application to be created. You can modify the default names. You can also, if you choose, enter a description for the enterprise application and Web application.

Enter any settings you want to change and click the Next button.

7. The Session & Security Options page allows you to select one of the following three options for the Web Service:

• Provide neither a session nor security constraints

• Provide a session, but no security constraints

• Provide both a session and security constraints

If you choose the last option, the wizard then prompts you to select a security configuration. See the Creating Custom Web Services (page 4) section for information about security configurations for Web Services.

8. The Create EAR File page displays the parameter values you have selected for your Web Service. Review them, then click the Create EAR File button to create the Web Service.

The Web Service is created in an EAR file. You will find the EAR file in the /home directory, with the name you selected in step 4.

To use the new Web Service, you need to deploy it. See the Deploying Web Services (page 13) section.

Repository Web Service Limitations

Because of the limitations inherent in Web Services, repository items must generally be passed in XML form. See the Repository to XML Data Binding (page 21) section for information about transforming repository items into XML files and vice versa. In particular, you should bear in mind the following restrictions when you are creating repository Web Services: get/setPropertyValue

• Collection properties may not be set or gotten as a whole. Only elements of the collection may be set

1 Creating and Using Web Services 19 • RepositoryItem properties are set or gotten as Strings in XML form

• There is no type of service that can get or set sub-properties. You must act upon the actual RepositoryItem you wish to read from or write to

• You cannot get or remove elements from a set or list. This is because in order to remove elements from either, you need to provide the object to remove (or index, see below), and a Web Service cannot guarantee that that object is of a type that can be transformed from XML into a Java object

• You cannot get or set a property of a type that corresponds to a Java primitive. For example, you cannot get or set a java.lang.Integer or a java.lang.Boolean

• You cannot get or set a property of a non-simple type, other than atg.repository.RepositoryItem. This includes types such as java.util.Timestamp and java.sql.Date. Note, however, that if you retrieve a Date property, a java.util.Calendar will be returned

• You cannot get a property that is not readable, or set a property that is not writable addItem

• The item to be added must be supplied in XML form updateItem

• The item to be updated must be supplied in XML form

• By default, when a repository item is passed into the Web Service, the existing RepositoryItem is found by matching repository IDs. We determine the value of the repository ID from the top-level XML element in the instance document, and then find a repository item with a matching ID removeItem

• Users must pass in only the repository ID of the item to be removed

Modifying Repository Web Services

Note that when you create a repository Web Service using the Web Service Creation Wizard, the component path of the repository, the item descriptor name and, if applicable, the property name, are all hardcoded in the generated Web Service. If any of these variables is changed, the Web Service will need to be regenerated.

Please note that the repository name is not taken into consideration when naming the Web Service. Only the item descriptor name and, if applicable, property name, is used to name a service. This means that if you are generating Web Services for two or more repositories with the same item descriptor names, you should consider placing them into different WAR files, or giving them different servlet URLs.

RepositoryService Class

The atg.repository.RepositoryService class contains many methods that perform basic Repository operations, independent of any particular repository implementation or instance. Such operations include getting, adding, removing and updating a repository item, setting and getting properties of repository items, and performing queries for repository items using RQL. Using the Web Service generator, you can directly make some of these methods into Web Services by simply clicking a form submit button.

Some others of these methods are too generic to be made available as a Web Service without limiting the types of the inputs or outputs. For example, the method setPropertyValue takes a java.lang.Object as

20 1 Creating and Using Web Services a method argument for the property value. Since Web Services do not allow java.lang.Object to act as an input (or output), this method cannot be used as a Web Service in this form. However, we can restrict the type of this argument using the code generator template functionality, so when the Web Service is generated, the outward-facing method will be strongly typed based on the property being set, and can simply call through to the more generic setPropertyValue method in the body of the Web Service. The RepositoryService class has the following properties:

Property Name Type Description

transaction javax.transaction. The service that manages any transactions that are Manager TransactionManager used to execute repository methods on this instance.

mappingManager atg.repository.xml. The component that manages mapping files ItemDescriptor based on repository and item descriptor name MappingManager combinations. For any methods that return a RepositoryItem, this service will be consulted to retrieve mapping files to use when transforming these items into XML. See the Mapping Files and XML Schemas (page 22) section for more information abut mapping files and the ItemDescriptorMappingManager class.

xmlGetService atg.repository.xml. The service that knows how to turn GetService RepositoryItems into XML.

xmlAddService atg.repository.xml. The service that knows how to add AddService RepositoryItems in XML format to a repository.

xmlUpdateService atg.repository.xml. The service that knows how to take UpdateService RepositoryItems in XML format and update them in their corresponding repositories.

For information about the XML service properties, see the Repository Operations (page 29) section.

Repository to XML Data Binding

One of the key aspects of integrating the Oracle Commerce Platform with a remote system is sharing data between the two systems. Data sharing and synchronization are often complex, because the two systems may store their data in dissimilar formats. The Oracle Commerce Platform data is typically stored in a Dynamo repository, which handles the mapping of data in Java objects to the underlying data store (such as a SQL database).

The Oracle Commerce Platform Integration Framework includes a data binding facility for reading and writing data between a repository and XML documents. Using this facility, you can write out repository data to XML documents that can then be read into a remote system, or read data into a repository from XML documents that store data from a remote system. A key aspect of this system is the use of mapping files to specify the data to include or exclude, and to map the names of repository properties to the names used by the remote system.

1 Creating and Using Web Services 21 The data binding facility also includes tools for generating XML Schemas that describe the structure of data in a repository, and to use these XML Schemas to validate the data written out from or read into the repository. For information on the Integration Framework, refer to the Platform Programming Guide.

The data binding facility provides services that perform these four operations with repository items:

• Getting items (retrieving items from a repository and writing them out to XML documents)

• Adding items (creating new items in a repository from data in XML documents)

• Updating items (modifying existing items using data in XML documents)

• Removing items (deleting items as indicated in XML documents)

This section discusses:

Mapping Files and XML Schemas (page 22)

Repository Operations (page 29)

Note that the classes described in this section work only with repositories included in the initialRepositories property of the /atg/registry/ContentRepositories component.

Mapping Files and XML Schemas

In addition to the XML instance documents that store the actual data, data binding uses two other types of documents:

• Mapping files control which data is exchanged between system, and which data is omitted

• XML Schemas describe the structure of the data, and can be used to validate XML instance documents

Mapping Files

When you exchange data between the Oracle Commerce Platform and a remote system, you will typically want to exclude certain data. For example, the Core Commerce profile usually includes Dynamo-specific information about scenarios.

When you create an XML instance document from data in a repository, Dynamo includes and excludes certain properties by default:

• If a property is readable and does not point to another item descriptor, it is included

• If a property is readable, points to another item descriptor, and its cascade attribute is set to "delete", it is included

• All other properties are excluded

For more information about the default inclusion rules, see the isIncludeProperty method of the atg.repository.xml.RepositoryXMLTools class in the ATG Platform API Reference. RepositoryXMLTools is a utilities class with various methods for encoding and decoding item descriptors, property names, and mapping files to and from XML-compatible namespaces and identifiers.

If you want more explicit control over the properties that are written out, you can use a mapping file. A mapping file specifies what properties to include or exclude when moving data between a repository and an XML instance document, and provides a way to map the names of Dynamo properties to their equivalents in a remote system. For example, a Dynamo profile might have an email property that stores the same information as the Email_Address attribute on another system.

22 1 Creating and Using Web Services The following is the Document Type Definition (DTD) for mapping files:

The following is a sample mapping file for the Dynamo profile repository:

1 Creating and Using Web Services 23 name="user" default-include="true">

The data binding services all work with a single item descriptor and its properties (including any other item descriptors that are properties of the main item descriptor). The mapping file uses the item-descriptor tag to specify the repository and item descriptor that the mapping file is associated with:

The default-include attribute specifies whether the item’s properties should be included or excluded by default. This value can be overridden for individual properties. In this mapping file, various scenario-related properties are excluded:

If a property is an item descriptor, there must be an item-descriptor tag inside the property tag. For example, the homeAddress property points to a contactInfo item descriptor:

Note that the item-descriptor tag for contactInfo can have property tags within it. The nesting of property tags and item-descriptor tags must reflect the hierarchy of the item descriptors in the repository. If you do not include a property tag for a property that points to an item descriptor (such as the homeAddress property shown above), the Oracle Commerce Platform uses the default inclusion rules for determining which properties of that item descriptor to include.

Finally, the property tag has an optional targetName attribute for mapping the property name to its corresponding name in the remote system:

24 1 Creating and Using Web Services

Managing Mapping Files for Repository Item Descriptors

The Oracle Commerce Platform includes two classes that help identify the appropriate mapping file for each item descriptor that you want to use with the repository2xml data binding facility. These classes are used by Web Service clients:

atg.repository.xml.ItemDescriptorMapping atg.repository.xml.ItemDescriptorMappingManager

ItemDescriptorMapping

An ItemDescriptorMapping is a simple bean that holds information about relationships between repository item descriptors and mapping files. The mapping files describe what properties are to be exposed when an item from that item descriptor is to be transformed into XML. Each ItemDescriptorMapping pertains to exactly one repository: for example, you would have a UserProfileItemDescriptorMapping, or a PromotionItemDescriptorMapping component, each of which would provide a list of item descriptor names from the corresponding repository and their corresponding mapping files.

An ItemDescriptorMapping contains only three properties:

Property Name Type Description

repositoryPath java.lang.String The path to the repository supported by this ItemDescriptorMapping. This is a read-only property

repository atg.repository. The path to the repository supported by Repository this ItemDescriptorMapping. Similar to repositoryPath but this property will resolve to an actual Repository instance, and is writeable.

itemDescriptorMapping java.util.Map A map where the keys are item descriptor names and the values are locations of mapping files, relative to the configuration path, which provide rules for how an item of the keyed item descriptor name appears in XML format

Here is an example properties file for an ItemDescriptorMapping that supports the profile repository:

$class=atg.repository.xml.ItemDescriptorMapping repository=/atg/userprofiling/ProfileAdapterRepository itemDescriptorMapping=\ user=/atg/userprofiling/userMapping.xml,\ contactInfo=/atg/userprofiling/contactInfoMapping.xml

1 Creating and Using Web Services 25 Here we see the there are two entries in the itemDescriptorMapping property, one for the user item descriptor, and one for the contactInfo item descriptor.

Whenever an entry is added to the itemDescriptorMapping property, whether through a properties file, or directly in code, the ItemDescriptorMapping checks to make sure that the key of the entry, the item descriptor name, resolves to an actual item descriptor of the repository this service is configured to support. If any item descriptor name does not resolve, a RepositoryException is thrown.

By themselves, ItemDescriptorMappings perform no work. They simply hold state. In order to put them to work, you must add them to the ItemDescriptorMappingManager, described below.

ItemDescriptorMappingManager

Class atg.repository.xml.ItemDescriptorMappingManager

Component /atg/repository/xml/ItemDescriptorMappingManager

Module DAS

The ItemDescriptorMappingManager serves as a registry of ItemDescriptorMappings. It is through this service that you obtain mapping files for all repository and item descriptor combinations. The mapping files are registered in the itemDescriptorMappings property of the ItemDescriptorMappingManager component:

Property Name Type Description

itemDescriptorMappings atg.repository.xml. An array of ItemDescriptorMapping ItemDescriptor components. When a user calls methods to Mapping[] retrieve mapping files, this component sifts through the itemDescriptorMappings to determine the correct mapping.

Here is an example properties file:

$class=atg.repository.xml.ItemDescriptorMappingManager itemDescriptorMappings=\ /atg/userprofiling/UserProfileItemMapping,\ /atg/userprofiling/ContactInfoItemMapping

The following ItemDescriptorMappingManager methods can be used to retrieve mapping files:

getMappingFileName(String pRepositoryPath, String pItemDescriptorName) Using the given repository path and item descriptor name, returns the mapping file for that given path:name combination, or null if none exists.

getMappingFileName(Repository pRepository, String pItemDescriptorName) Using the given repository and item descriptor name, returns the mapping file for that given repository:name combination, or null if none exists.

26 1 Creating and Using Web Services When you use the atg.repository.xml.GetService to get repository items in XML form, you can pass along a mapping file name using these ItemDescriptorMappingManager methods. Using the ItemDescriptorMappingManager, you can centralize all mapping files in one component for all item descriptors, and just call that to determine which mapping file to use for a given item descriptor.

XML Schemas

The Oracle Commerce Platform provides tools for creating and working with XML Schemas for the XML documents written and read by the various data binding services. XML Schema is a schema language for XML that describes and restricts what a particular XML instance document might look like. An XML document can be validated against an XML Schema to check that it conforms to that Schema. Additionally, many developer tools make use of XML Schemas. For example, some tools provide a visual representation of XML Schemas to allow mapping from one XML Schema to another. See Generating XML Schemas (page 27).

Generating XML Schemas

The Oracle Commerce Platform provides a command-line tool that generates an XML Schema for a given item descriptor. The XML generated by the Get data binding service conforms to this Schema. Similarly, the XML Schema describes an instance document that is capable of being processed by the Add, Update, or Remove service.

The command-line tool is named generateXMLSchema.sh (on Unix) or generateXMLSchema.bat (on Windows) and is found in the /home/bin directory. The following table lists the arguments that can be supplied to this command:

Argument Description

-repository Nucleus path to the repository containing the item descriptor that the XML Schema is being generated for. Required.

-itemDescriptor Name of the item-descriptor that the XML Schema is being generated for. Required.

-outputDirectory Specifies a directory to save the XML Schema to. This directory is in addition to the directory specified by the XMLSchemaFileDirectory property of the XMLSchemaManager. Not required.

-saveSchemas If set to true, then the Schemas will be saved via the configured XMLSchemaManager. If omitted, defaults to true.

-mappingFile Specifies the mapping file to use. Not required.

-schemaGenerator Nucleus path to the Schema Generator component. If omitted, defaults to / atg/repository/xml/SchemaGenerator.

-m Specifies the set of modules to use in the repository definition. Required.

-help Prints out a usage message. Not required.

The following command generates an XML Schema for the user item descriptor of the default Dynamo profile repository, using the properties defined in the repository definition file for the DSSJ2EEDemo application module (and the modules required by the DSSJ2EEDemo module):

1 Creating and Using Web Services 27 generateXMLSchema -m DSSJ2EEDemo –repository /atg/userprofiling/ProfileAdapterRepository -itemDescriptor user

The generated XML Schema is saved by the Schema Manager specified by the schemaManager property of the Schema Generator component. The default Schema Generator is the /atg/repository/xml/ SchemaGenerator component, and its schemaManager property points by default to the /atg/repository/ xml/SchemaManager component. Note that if the user item descriptor contains other item descriptors as properties, the generated Schema will reflect these other item descriptors as well.

To save the Schema to the current working directory in addition to the directory determined by the XMLSchemaFileDirectory property of the Schema Manager:

generateXMLSchema -m DSSJ2EEDemo –repository /atg/userprofiling/ProfileAdapterRepository -itemDescriptor user -outputDirectory .

Managing Schemas and Mapping Files

As mentioned above, the default Schema Generator has a schemaManager property that points to the /atg/repository/xml/SchemaManager component. In addition, each of the data binding service components (described below) has an XMLSchemaManager property that points to this SchemaManager component. This component is of class atg.repository.xml.XMLSchemaManager. This class, which extends atg.repository.databinding.MappingManager, manages XML Schemas and mapping files. For example, this class has mappingFileDirectories and XMLSchemaFileDirectory properties that specify the directories where mapping files and Schemas are stored. Note that Schemas must have the extension .xsd and mapping files must have the extension .xml.

For example, suppose you want to generate an XML Schema and specify a mapping file to use. The command would look something like this:

generateXMLSchema -m DSSJ2EEDemo –repository /atg/userprofiling/ProfileAdapterRepository -itemDescriptor user -mappingFile profileMapping.xml

Notice that only the name of the mapping file is specified, not the entire pathname. The Schema Manager’s mappingFileDirectories property points to the directories where the mapping file should be stored.

PropertyElementNameSeparator

The repository2xml feature specifies a separator character, which functions to separate a property name from the name of its item descriptor. By default, this separator character is . (dot). The default separator character may not work for you if, for example, you use composite repository IDs that also use the . (dot) character to separate elements of the repository ID. You can specify a different separator character in the propertyElementNameSeparator property of the /atg/repository/xml/RepositoryXMLTools component.

Item References

In a repository schema, a map, set, list, or array property can point to a single other item using the itemRef attribute. The value assigned to the itemRef attribute concatenates the item descriptor name, the property element separator, and the repository ID. In the following example, the item descriptor name is role, the property element separator is . (dot) and the repository ID is 2900004:

28 1 Creating and Using Web Services

The following is a more extended example, showing the context for the itemRef attribute:

Repository Operations

The atg.repository.xml package includes a service class for each of the four repository operations supported by the data binding facility. The following table lists these classes and the Nucleus instances included in Dynamo:

Class Nucleus component

atg.repository.xml.GetService /atg/repository/xml/GetService

atg.repository.xml.AddService /atg/repository/xml/AddService

atg.repository.xml.UpdateService /atg/repository/xml/UpdateService

atg.repository.xml.RemoveService /atg/repository/xml/RemoveService

The following sections discuss each of these classes and the operations they perform. See the entries for these classes in the ATG Platform API Reference for more information.

Getting Repository Items

You use getItemAsXML method of the atg.repository.xml.GetService class to create XML documents from repository items. This method takes a repository item as an input argument and returns a String containing an XML representation of this item. If you write out this String (e.g., to a file), be sure to use the same character encoding that the repository uses.

Some versions of the getItemAsXML method take additional inputs for specifying a String array of the names of the properties to write out or a String containing the name of the mapping file to use. If you supply only a repository item as input, the method uses the default inclusion rules (described in the Mapping Files (page 22) section) to determine which properties to include.

By default, GetService writes out an XML document as a single line, because it is intended to be machine- readable. If you want the generated XML to be human-readable, set the indentXMLOutput property of the GetService component to true. The resulting XML will have appropriate line breaks.

1 Creating and Using Web Services 29 The following example shows a repository operation to get a repository item.

Suppose you want to generate XML for a user profile, based on a mapping file named profileMapping.xml. The following code finds the user repository item whose ID is "user747" and generates an XML representation of it:

RepositoryItem userItem = getProfileRepository().getItem("user747", "user"); String userAsXML = GetService.getItemAsXML(userItem,"profileMapping.xml");

The following is sample output from this code. The data represents the profile of the user sandy in the following demo:

0 long-term female 500 220 180 260 short-term 1976-12-09 none 4 conservative en_US 2002-08-14T18:33:49.604 5 Pieta conservative tax international 747 /repositories/Funds/en_US/overseas.xml /repositories/Funds/en_US/moneymarket.xml /repositories/Funds/en_US/growth.xml /repositories/Funds/en_US/growthincome.xml [email protected] d686a53fb86a6c31fa6faa1d9333267e 1999-04-15T00:00:00.0 investor true 734 3 sandy

30 1 Creating and Using Web Services false false true

Notice that information about the XML Schema for this data is included in the user:user tag at the beginning of the document:

xsi:schemaLocation="http://www.atg.com/ns/profileMapping/UserProfiles/user profileMapping+UserProfiles+user.xsd "

The xsi:schemaLocation attribute specifies the URL and name of the Schema file. The Schema filename (profileMapping+UserProfiles+user.xsd) is determined by the name of the mapping file (profileMapping.xml), the name of the repository (UserProfiles), and the item descriptor (user). If no mapping file is used to create the document, the Schema filename indicates the repository and item descriptor. If you want the Schema filename to include the entire pathname, set the appendRelativeSchemaLocation property of the GetService component to true. This is especially important if you’re using an external Schema verification tool, which will generally need the complete pathname to find the Schema file.

If you use a mapping file when you create an instance document, you should be sure to supply the name of this mapping file to the generateXMLSchema command (using the –mappingFile argument) when you generate the Schema. Otherwise the actual Schema filename will not match the name in the xsi:schemaLocation tag, and the Schema may not accurately reflect the data in the instance document; as a result, you may not be able to validate the data when reading it into a remote system (or reading it back into Dynamo using AddService). Note also that if your call to getItemAsXML includes an input argument that specifies the names of properties to write out, the Schema will not accurately reflect the data in the instance document, so validation will not be possible.

To avoid any conflict between tag names, the XML tags in the generated instance document are named using the convention itemType:propertyName; for example the user:userType tag stores the value of the userType property of the user item type. If the addItemTypeToPropertyNames property of the RepositoryXMLTools component that GetService points to is set to true, the tags are named using the convention itemType:itemType.propertyName; in this case, the tag name would be user:user.userType. By default addItemTypeToPropertyNames is set to true, because the resulting XML is less likely to result in naming collisions.

Adding Repository Items

You use the addItem method of the atg.repository.xml.AddService class to create new repository items from XML documents. This method takes an XML document as an input argument and returns a repository item. The XML document can be in the form of a String, a java.io.Reader, or a java.io.InputStream. The method examines the schemaLocation attribute in the XML document to determine if there is a mapping file associated with the document. Some versions of the method take additional arguments for specifying how to handle missing or empty tags, and whether the data should be validated against a Schema.

For some examples of how a repository item might look in XML document form, see the / RL/Example/j2ee-apps/example/web-app/public directory. The Repository Loader (RL) module also includes a page you can use to generate XML documents from existing repository items. This page is located at /RL/Example/j2ee-apps/example/web-app/itemAsXml.jsp.

Note that addItem cannot create new read-only elements in a repository. By default, any data in the instance document that corresponds to a read-only element in the repository is silently ignored. If you want addItem to log a warning each time it skips a read-only element, set the logWarningOnReadOnly property of the AddService component to true.

1 Creating and Using Web Services 31 Validating Repository Item Data

The addItem method can optionally validate the data in an XML instance document against the Schema specified in the instance document. Validation is enabled or disabled by the validate property of the AddService component. By default, this property is set to false, because validation slows down processing of the document. To enable validation, set the validate property to true.

The addItem method can also take a Boolean argument to specify whether to validate the document. The value of this argument overrides the validate property. If you do not specify this argument, addItem uses the validate property to determine whether to validate the document.

If you are confident that your data is valid, you can disable validation, and the instance document will be processed more quickly. However, if the data turns out to be invalid, the invalid data may be written to the repository. If you enable validation and the data is invalid, the addItem method does not write the contents of the instance document to the repository.

Updating Repository Items

You use the updateItem method of the atg.repository.xml.UpdateService class to modify a repository item. For example, the following instance document updates a user’s email address:

[email protected]

The updateItem method can optionally validate the instance document against the specified Schema. The logic for this is similar to the AddService.addItem method: the UpdateService component has a validate property whose default value is false, and the updateItem method can take a Boolean argument that overrides the value of the validate property.

See Selecting Repository Items to Update (page 32) and Using the repositoryId Attribute (page 34).

Selecting Repository Items to Update

There are two ways to select the item to update:

• You can specify the item explicitly when you call updateItem

• You can specify a set of match properties, and updateItem selects the item whose values match the corresponding values in the instance document

For example, the login property is often used for matching, because it is unique to a specific user item and its value does not change. The following XML instance document could be used to select the item and then update its emailAddress property:

[email protected] sandy

32 1 Creating and Using Web Services The application would then use the following code to update the user repository item whose login value is sandy (assuming the inputXML String contains the instance document shown above):

String[] matchProperties = {"login"}; RepositoryItem updatedItem = UpdateService.updateItem(inputXML, matchProperties);

Note that UpdateService determines the repository and item type from the namespace of the instance document. See Getting Repository Items (page 29).

The matchProperties array can contain any number of property names. If the value of each repository item property named in matchProperties matches its corresponding attribute in the XML instance document, the item is selected for update. All of the specified properties must match for the item to be selected; for example, if matchProperties lists login and lastName properties, the values of both properties must match. If multiple items are selected, an exception is thrown and no update occurs.

Matching is limited to top-level properties of the repository item. Subproperties (such as properties of other repository items) cannot be matched. So, for example, if a user item has a lastName property that is a String, you can include lastName in matchProperties; but if a user item has a shippingAddress property that is another repository item, you cannot include, say, shippingAddress.city in matchProperties.

If a property has been mapped to a different name in the instance document, the name to match on is the property name used in the repository, not the instance document. For example, suppose you use a mapping file to map a user item’s dateOfBirth property to the name birthday, like this:

The corresponding instance document might look like this:

02-06-1975

To specify this property in matchProperties, you use the name of the property as it is defined in the repository (dateOfBirth), not the target name (birthday). For example:

String[] matchProperties = {"dateOfBirth"};

You can configure the UpdateService to add a repository item if an attempt to update does not find a match. If you want the UpdateService to add items when no items are matched, set the addWhenNoMatchedItems property of the UpdateService to true.

If the property you are updating is a simple type (such as a String), then its value is updated by the UpdateService. When the property being updated is a list, map or array, then the old value is replaced by the new value. The new value is not appended to the old value. If the property being updated is an item descriptor, then the appropriate fields of the existing item descriptors are updated.

1 Creating and Using Web Services 33 Using the repositoryId Attribute

The repositoryId attribute of an item can be used as a special match property. If the repositoryId String is passed to UpdateService as a match property, the service will determine the value of this attribute from the top-level XML element in the instance document, and then find a repository item with a matching repository ID. The following XML example uses the repositoryId attribute as a match property:

[email protected] String[] matchProperties = {"repositoryId"}; RepositoryItem updatedItem = UpdateService.updateItem(inputXML, matchProperties);

In this case, the UpdateService selects the user item whose repositoryId is “user707” from /atg/ userprofiling/ProfileAdapterRepository.

Note: Do not confuse with the repositoryId attribute, which identifies a repository item, with the ID attribute used in the XML schema to identify an XML element. The repositoryId attribute and not the ID attribute is used to identify which repository item to update.

Removing Repository Items

You use the removeItems method of the atg.repository.xml.RemoveService class to delete repository items specified in XML documents. This method takes an XML document in the form of a String array, a java.io.Reader, or a java.io.inputStream.

Some versions of removeItems take a matchProperties String array. Property matching for RemoveService.removeItems uses the same logic as UpdateService.updateItem, except it is legal for multiple repository items to be marked for deletion. For example, an instance document to remove all users whose date of birth is 02-06-1975 would look like:

02-06-1975

The application then uses the following code to remove all the user repository items whose dateOfBirth value is 02-06-1975 (assuming the inputXML String contains the instance document shown above):

String[] matchProperties = {"dateOfBirth"}; String[] removedItemIds = RemoveService.removeItem(inputXML,matchProperties);

The maximum number of matching items is specified by the maxSelectedItems property of RemoveService. If the number of matching repository items exceeds this value, an exception is thrown. In the /atg/ repository/xml/RemoveService component, maxSelectedItems is set to 5 by default.

34 1 Creating and Using Web Services Accessing Web Services from Java Clients

The Oracle Commerce Platform permits external Java clients to access Nucleus methods by exposing them as Web Services. Many such Web Services are included with the Oracle Commerce Platform, as are tools for creating custom Web Services. For a list of these Web Services, see Web Services (page 2). Java clients can execute those Web Services through calls that are translated into XML wrapped in SOAP, transmitted to the Oracle Commerce Platform, and routed to the Nucleus method itself. Other Oracle Commerce Platform resources, such as JMS messages and RepositoryItems, can also be exposed as Web Services.

The Oracle Commerce Platform implementation of Web Services follows the standard Web Service guidelines outlined by JAX-RPC 1.0 and SOAP 1.1 specifications. You may use Apache Axis 1.4 to create your Web Service calls, and this section includes code examples that assume you are using Axis.

This section aims to inform you how to call Web Services from an Axis client. Rather than provide a broad discussion on how to use Axis, this section describes Oracle Commerce Platform-specific features and processes that you need to be familiar with. Please see the Axis documentation for comprehensive instructions.

To access a Web Service, you need to be familiar with the following topics:

About Web Services (page 35)

Before You Begin Using a Java Client (page 36)

Writing a CookieContainer Class (page 37)

Calling Web Services from a Java Client (page 39)

Creating a Serializer and Deserializer (page 42)

About Web Services

For the most part, you call Oracle Commerce Platform Web Services in the same way you call Web Services elsewhere. While the general process may not differ, it’s important that you are aware of these platform-specific features.

Security

The content you see as a response to a Web Service call depends on your access privileges. When you login using the loginUser Web Service, you provide your user identity. If session sharing is enabled, all subsequent Web Service calls in that session are associated with that identity and related role.

For more information on loginUser, see the Personalization Programming Guide. You may also want to learn how other Web Services handle the security information provided by loginUser. Such information exists in the Repository Guide and the Core Commerce Programming Guide.

Transactions

When a client calls a Web Service, the transactional behavior of the service is managed entirely on the server side. The method that is exposed as a Web Service can use standard transaction demarcation techniques, but the calling client has no control over this.

There are some practical considerations you should be aware of. If a single Web Service call attempts to perform some operation, and the operation fails, the operation can be rolled back (provided that the Nucleus method is demarcated properly). However, a transaction cannot span multiple Web Service calls so if an operation is performed by a sequence of Web Service calls, and the final call fails, there is no way to roll back the steps performed by the previous calls.

1 Creating and Using Web Services 35 Sharing Sessions

When you create a Web Service, you specify whether it should be executed within the context of an HTTP session. Associating Web Services with a session enables an application to maintain state across Web Service calls and to use login information for security purposes.

To allow multiple Web Services to share a session, two things need to happen:

1. The Web Service client must allow a session to be shared across certain Web Service calls. To do this, the client must pass a session cookie between calls.

2. The Web Services themselves must support sessions. When you create custom Web Services, the Web Service Creation Wizard gives you the option of supporting sessions.

This section includes an example of a helper class that you can use to simplify cookie management. See Writing a CookieContainer Class (page 37). RepositoryItems

If your Web Services access RepositoryItems, you need to provide a serializer and deserializer so the RepositoryItem content can be interpreted by non-Oracle Commerce Platform systems. The following Web Services transmit content that is natively stored as RepositoryItems:

• getProfile

• getRepositoryItem

• performRQLQuery

• getOrderAsXML (Core Commerce users only)

• getOrdersAsXML (Core Commerce users only)

• getProductXMLById (Core Commerce users only)

• getProductXMLByDescription (Core Commerce users only)

• getProductXMLByRQL (Core Commerce users only)

• getProductSkusXML (Core Commerce users only)

• getPromotionsAsXML (Core Commerce users only)

The Oracle Commerce Platform includes several tools for working with RepositoryItems. To make a client able to serialize and deserialize RepositoryItems, you need to translate the RepositoryItem class into a language that’s native to your client. See Creating a Serializer and Deserializer (page 42) for more information.

Before You Begin Using a Java Client

Before you can access a Web Service, you need to make sure the Oracle Commerce Platform is ready for your call and Axis 1.4 is configured:

1. Confirm that the application that includes the Web Service is deployed on your application server and is running. For more information, see Deploying Web Services (page 13).

2. Download Axis 1.4 from the Apache Web site:

http://ws.apache.org/axis

3. Extract the contents of the Axis download file.

36 1 Creating and Using Web Services 4. Add the axis libraries to your CLASSPATH.

See the Apache site for more information about using Axis.

Writing a CookieContainer Class

The following example shows a sample CookieContainer class. You can use this as a model for your own class. Note that:

• This class relies on the Axis API. If you are using a different Java client, you will need to use the API for your client

• This class works with both static and dynamic Web Service calls. (See Calling Web Services from a Java Client (page 39).) If you always make only one of these call types, your own CookieContainer class does not need to handle both cases

package com.example.webservice;

import org.apache.axis.MessageContext; import org.apache.axis.client.Call; import org.apache.axis.client.Stub; import org.apache.axis.transport.http.HTTPConstants;

/** * A class that can be passed between web service clients that keeps track of * the cookies received from the server. These cookies are then used by * subsequent web service client calls in order to ensure that session * state is maintained. **/ public class CookieContainer { //------// Member variables //------

/** Array of cookies from the Set-Cookie HTTP header **/ private String[] mCookies = null;

/** Array of cookies from the Set-Cookie2 HTTP header **/ private String[] mCookies2 = null;

//------// Methods //------

/** * Gets the cookies set by the Set-Cookie HTTP header * @return the cookies from the Set-Cookie HTTP header, which * may be null **/ public String[] getCookies() { return mCookies; }

/** * Gets the cookies set by the Set-Cookie2 HTTP header * @return the cookies from the Set-Cookie2 HTTP header, which * may be null

1 Creating and Using Web Services 37 **/ public String[] getCookies2() { return mCookies2; }

/** * Extracts the cookies from the given Axis MessageContext, and * sets the cookies and cookies2 properties from them. * @param pContext the Axis message context to examine. This * cannot be null **/ public void extractCookies(MessageContext pContext) { mCookies = (String[])pContext.getProperty (HTTPConstants.HEADER_COOKIE); mCookies2 = (String[])pContext.getProperty (HTTPConstants.HEADER_COOKIE2); }

/** * Extracts the cookies from the given Axis Call, and * sets the cookies and cookies2 properties from them. * @param pCall the Axis call to examine. This * cannot be null **/ public void extractCookies(Call pCall) { extractCookies(pCall.getMessageContext()); }

/** * Extracts the cookies from the given Axis Stub, and * sets the cookies and cookies2 properties from them. * @param pStub the Axis stub to examine. This * cannot be null **/ public void extractCookies(Stub pStub) { extractCookies(pStub._getCall()); }

/** * Pushes the cookie values that are set on the instance to * the given Call * @param pCall the call to set the cookies on. This cannot be null **/ public void pushCookies(Call pCall) { if(mCookies != null) pCall.setProperty(HTTPConstants.HEADER_COOKIE, mCookies); if(mCookies2 != null) pCall.setProperty(HTTPConstants.HEADER_COOKIE2, mCookies2); }

/** * Pushes the cookie values that are set on the instance to * the given Stub * @param pStub the stub to set the cookies on. This cannot be null **/ public void pushCookies(Stub pStub) { if(mCookies != null) pStub._setProperty(HTTPConstants.HEADER_COOKIE, mCookies); if(mCookies2 != null) pStub._setProperty(HTTPConstants.HEADER_COOKIE2, mCookies2);

38 1 Creating and Using Web Services } }

Calling Web Services from a Java Client

When you call a Web Service, you create resources that describe the Web Service you want to call, its location, and initial inputs. Axis then takes those resources and produces from them a SOAP message that it then sends to the Web Service itself.

There are two ways to create a Web Service call:

• Use a client stub to create a static Web Service call

• Use the Dynamic Invocation Interface to create a dynamic Web Service call

The main distinction between the two processes is the data types they can handle. Because using Web Services requires that data be converted into several formats — from a native format into an XML representation of that format back into the native form — it is important that you choose a process designed to work with the data types accessed by the Web Services you want to employ.

The static process can handle any data type regardless of whether it’s primitive, complex, object, or non- standard. Non-standard types may require some extra effort as is the case when accessing RepositoryItems or JMS messages. The dynamic process, conversely, is limited to only working with object versions of these data types (as permitted by SOAP 1.1):

• Boolean

• Byte

• Double

• Float

• Int

• Long

• Short

Some complex types such as Array, List, Set, and Map may be supported using the dynamic process in a restricted way. See the JAX-RPC Specification for details on data type restrictions.

The subsequent sections describe how you would make a call to the loginUser Web Service following the static and dynamic processes.

Creating a Call Using a Client Stub (Static)

When you create a call following the static method, you represent the server-side Web Service architecture on the client by creating a client stub and a client:

• The client stub describes the associated Web Services resources as well as the remote procedure call that the Web Service executes

• The client configures a particular Web Service instance by specifying initial values and methods on various Web Services resources

The call is constructed by compiling information from the client stub, client, and various other supporting classes that hold static information.

1 Creating and Using Web Services 39 For example, to create a static call to the loginUser Web Service:

1. Create and compile the client stub, if one does not already exist for the Web Service. See Creating and Compiling a Client Stub (page 40) below.

2. Add the client stub to the CLASSPATH variable so the client stub is available to local Web Services resources.

3. Create and compile the client. See Creating and Compiling a Client (page 40) below.

4. Use Axis to execute the Web Service call:

loginStub.createUser(pProfileAsXML)

The format of this call is:

clientStub.web_service(generated_web_Service_Call_instance)

Axis creates the XML message, wraps it in SOAP, and sends it via HTTP to the Web Service location in the client stub.

See the Creating and Compiling a Client Stub (page 40) and Creating and Compiling a Client (page 40) sections. Creating and Compiling a Client Stub

The client stub describes the Web Service method and supporting resources in a structure that’s familiar to the client. Each Web Service requires a stub for each client that executes it. You can reuse a stub for subsequent calls so you only need to create it once. However, simultaneous calls to a Web Service made by different threads will require that a unique client stub instance exists for each thread.

To create and compile a client stub for the loginUser Web Service:

1. Locate the active WSDL file via HTTP for the Web Service you want to call. The URL is provided in with the documentation that describes each Web Service:

• For Repository Web Services, see the Repository Guide

• For Oracle Commerce Personalization Web Services, see the Personalization Programming Guide

• For Core Commerce Web Services, see the Core Commerce Programming Guide

It’s important that you access the runtime and not the static version of the WSDL document. Assuming that you included the modules holding the Web Services you want to access when you assembled your application, you should be able to download the runtime version of the WSDL.

2. Use the Axis WSDL-to-Java tool to generate the client stub based on the WSDL.

3. Compile the client stub. Creating and Compiling a Client

A Web Service client is a Java file that describes precisely what the Web Service should do. It provides the actions the Web Service should commit and initial values.

If you want to enable Web Services to share sessions, your code needs to pass cookies between calls. The following example, which creates a static Web Service call to the loginUser Web Service, uses the CookieContainer class shown in Writing a CookieContainer Class (page 37):

{ LoginUserSEIService loginService = new LoginUserSEIServiceLocator();

40 1 Creating and Using Web Services LoginUserSEI loginStub = loginService.getLoginUserSEIPort(); org.apache.axis.client.Stub axisStub = (org.apache.axis.client.Stub) loginStub; CookieContainer cookieContainer = new CookieContainer();

axisStub.setMaintainSession(true); // Don't allow XML elements to reference other XML elements axisStub._setPropertyValue(AxisEngine.PROP_DOMULTIREFS, new Boolean(false)); // Push cookies onto the Stub cookieContainer.pushCookies(stub);

String userId = loginStub.loginUser("bhavern", " xyo8bnif", false);

// Get cookies out of the Stub, and pass them to subsequent calls as needed cookieContainer.extractCookies(stub); }

Creating a Call Using the Dynamic Invocation Interface (Dynamic)

A dynamic Web Service call holds all relevant information in one file, the client, which Axis converts directly into the SOAP message. Essentially, the client you create is a Java version of the call itself, excluding some relative values that are replaced with absolute ones at compile time.

Keep in mind that if you want to access a Web Service that uses non-standard data types, you need to create your Web Service call following the static process. See Creating a Call Using a Client Stub (Static) (page 39).

If you want to enable Web Services to share sessions, your code needs to pass cookies between calls. The following example, which creates a dynamic Web Service call to the loginUser Web Service, uses the CookieContainer class shown in Writing a CookieContainer Class (page 37):

Service service = new Service(); Call call = (Call) service.createCall();

// Get a hold of a CookieContainer passed to this method/class CookieContainer cookieContainer = new CookieContainer();

// Push previous cookies (if any) to the new Call object cookieContainer.pushCookies(call); call.setMaintainSession(true);

call.setTargetEndpointAddress(new java.net.URL("http://hostname:port/userprofiling/usersession/loginUser/ loginUser") );

// Don't allow XML elements to reference other XML elements call.setProperty(AxisEngine.PROP_DOMULTIREFS,Boolean.FALSE)

call.addParameter("Login", org.apache.axis.Constants.XSD_STRING, javax.xml.rpc.ParameterMode.IN); call.addParameter("Password", org.apache.axis.Constants.XSD_STRING, javax.xml.rpc.ParameterMode.IN); call.addParameter("IsPasswordEncrypted", org.apache.axis.Constants.XSD_BOOLEAN, javax.xml.rpc.ParameterMode.IN); call.setReturnType(org.apache.axis.Constants.XSD_STRING); call.setOperationName(new QName("http://www.atg.com/webservices", "loginUser"));

1 Creating and Using Web Services 41 String userId = (String) call.invoke( new Object[] { "bhavern", "xyo8bnif", Boolean.FALSE } );

// Extract new cookies from the Call into the CookieContainer object, // which can then be passed to subsequent calls cookieContainer.extractCookies(call); }

Creating a Serializer and Deserializer

When you want to use a Web Service that accesses RepositoryItems, you can create a mechanism for translating foreign content into different formats:

• A serializer will convert content from a native format into XML that will eventually undergo another conversion into a RepositoryItem. You need to create a serializer for “set” operations in which the client sends content to the Web Service in the context of the call

• A deserializer constructs XML content that was originally formatted as RepositoryItems into a native content format. You need to create a deserializer for “get” operations in which a Web call returns content that represents a RepositoryItem

Both a serializer and a deserializer will need to understand the RepositoryItem schema. When you create the XML schema and a mapping file, you need information about the Web Service itself. You can find that information in the sections that describe the Web Service:

• For getProfile, see the Personalization Programming Guide

• For getOrderAsXML, getOrdersAsXML, getProductXMLById, getProductXMLByDescription, getProductXMLByRQL, getProductSkusXML, getPromotionAsXML, see the Core Commerce Programming Guide

• For Repository Web Services , see the Repository Guide

Two Repository Web Services, getRepositoryItem and performRQLQuery, require a serializer and deserializer, but they can apply to any RepositoryItems you choose, which is different from the other Web Services that are only available to specific RepositorityItems and item descriptors.

The serializers and deserializers you create require a Repository schema, which you can create by following these steps:

1. Create a Mapping file that determines which RepositoryItem properties will be captured by the Web Service and returned by the call. See Creating a Mapping File (page 42).

2. Use the generateXMLSchema tool to convert the RepositoryItem class into a standard XML schema. See Generating an XML Schema (page 43).

3. Insert a reference to the XML schema in your instance document, which is a document that represents an instance of the Web Service call. You complete this step when you configure the client stub; see Creating and Compiling a Client Stub (page 40) for instructions. Creating a Mapping File

If you were to create an XML schema that included all RepositoryItem properties, some content may not be understood by standard deserializers and some may not conform to the XML 1.0 specification. Instead, you create a mapping file that determines which properties, from the RepositoryItem's item descriptor, to include or exclude from your XML schema. For instructions on how to create a mapping file, see Mapping Files (page 22).

42 1 Creating and Using Web Services To create a mapping file, you need to know the properties defined by your item descriptor so you can decide which of them ought to be represented in the XML schema. You can find the location of a Repository’s item descriptor in the Oracle Commerce Platform Dynamo Server Admin UI:

1. In the Dynamo Server Admin, click the Component Browser link.

2. Navigate to the Repository component that correlates to your Web Service as indicated in the appropriate documentation for the Web Service.

3. Click the See Property Descriptions link beside the item descriptor name. For the item descriptor name, see the documentation for your Oracle Commerce Platform application’s Web Service.

This list that displays includes all properties that are available to the item descriptor based on the modules that are currently running.

To make this XML schema compatible with the expectations of the resources that will use it, exclude the following items from your XML schema:

• RepositoryItem properties that accept primitive data types and may be null

• RepositoryItem properties that accept Maps, Lists, or Sets

Generating an XML Schema

The generateXMLSchema is a script that takes a given Repository component and item descriptor as arguments and produces an XML schema. For instructions on using this tools, see XML Schemas (page 27).

When you create an XML schema in support of a Web Service, make sure that the same modules in the Oracle Commerce Platform are running now as those that will be running when the client calls the Web Service.

For a list of Web Services, associated Repository components and items descriptors, see the documentation for the Web Service.

You may find these two optional arguments helpful:

• outputDirectory copies the resultant XML schema to the directory of your choosing

• mappingFile specifies a file that describes the RepositoryItem properties to include in the resultant XML schema

Other Required Schemas

When a client deserializes a RepositoryItem, it uses the schema derived from the item descriptor to reconstruct each repository object and its properties in the appropriate data types. Depending on the makeup of the item descriptor, you may need to also generate a schema for related item descriptors.

Consider the Profile repository that uses the user item descriptor. There are two item descriptors, broker and investor, that are subtypes of user. If you were to use the updateProfile Web Service call while the Relationship Management platform is running, user and all subtypes of it that are part of Relationship Management are accessible. When you call updateProfile, it’s unclear which version of user you want to call: user, investor or broker. In this case, you need to generate XML schemes for all three item descriptors.

In short, you need to generate an XML schema for all item descriptors used by RepositoryItems that are accessed by a Web Service call and for any related (parent or child) item descriptors that are running when the call is made.

It is difficult to supply a general list of all item descriptors for which this added step applies because the contents of that list depend on many factors. When deciding if you need to create supplemental XML schemas for an item descriptor, consider the following:

1 Creating and Using Web Services 43 • The Web Service you are calling

• The modules running when you call that Web Service

• The contents of your Oracle Commerce Platform module stack

• The custom Oracle Commerce Platform components you have created that may extend existing components accessed by the Web Service

Note: The previous discussion addresses item descriptors and their subtypes, meaning item descriptors that inherit from the parent class. This relationship should not be confused with that which item descriptors share with extensions of themselves, which are added by other modules. For example, the order item descriptor has one set of properties provided by the Oracle Commerce Core Commerce consumer-based module. A second order item descriptor is supplied by Core Commerce for business users and, when both modules are running, the order item descriptors are concatenated so that Core Commerce properties for businesses take precedence. Because all versions of order for the running module are combined into one, you need only one XML schema for the order item descriptor. When you create that XML schema for order, remember to do so while the same modules are running as will run when your Web Service calls that item descriptor.

Accessing Web Services from .NET Clients

The Oracle Commerce Platform permits .NET clients to access Nucleus methods by exposing them as Web Services. There are many Web Services included with the Oracle Commerce Platform, as are tools for creating custom Web Services. For a list of Oracle Commerce Platform Web Services, see Web Services (page 2). .NET clients are able to contact those Web Services through a carefully constructed call that’s built in .NET, translated into XML wrapped in SOAP, transmitted to the Oracle Commerce Platform, and routed to the Nucleus method itself. Other Oracle Commerce Platform resources, such as JMS messages and RepositoryItems can also be exposed as Web Services.

This section describes how to call Web Services from a .NET client. Rather than provide a broad discussion on how to use .NET, this section describes Oracle Commerce Platform-specific features and processes that you need to be familiar with. Please see your .NET documentation for comprehensive instructions.

To access a Web Service, you need to be familiar with the following topics:

About Web Services in the Oracle Commerce Platform (page 44)

Before You Begin Using a .NET Client (page 46)

Calling Web Services from a .NET Client (page 47)

Using the Atg.DotNet.WebService API with RepositoryItems (page 49)

About Web Services in the Oracle Commerce Platform

For the most part, you call Web Services in the same way you call Web Services elsewhere. While the general process may not differ, it’s important that you are aware of these platform-specific features. Security

The content you see as a response to a Web Service call depends on your access privileges. When you login using the loginUser Web Service, you provide your user identity. If session sharing is enabled, all subsequent Web Service calls in that session are associated with that identity and related role.

44 1 Creating and Using Web Services For more information on loginUser, see the Personalization Programming Guide. You may also want to learn how other Web Services handle the security information provided by loginUser. Such information exists in the Repository Guide and the Core Commerce Programming Guide. Transactions

When a client calls a Web Service, the transactional behavior of the service is managed entirely on the server side. The method that is exposed as a Web Service can use standard transaction demarcation techniques, but the calling client has no control over this.

There are some practical considerations you should be aware of. If a single Web Service call attempts to perform some operation, and the operation fails, the operation can be rolled back (provided that the Nucleus method is demarcated properly). However, a transaction cannot span multiple Web Service calls so if an operation is performed by a sequence of Web Service calls, and the final call fails, there is no way to roll back the steps performed by the previous calls. Session Sharing

When you create a Web Service, you specify whether it should be executed within the context of an HTTP session. Associating Web Services with a session enables an application to maintain state across Web Service calls and to use login information for security purposes.

To allow multiple Web Services to share a session on .NET, two things need to happen:

1. The Web Service client must allow a session to be shared across Web Service calls. To do this, you need to define the Web Service calls in the same Web Control and assign a CookieContainer for each call. For instructions, see Calling Web Services from a .NET Client (page 47).

2. The Web Services themselves must support sessions. When you create custom Web Services, the Web Service Creation Wizard gives you the option of supporting sessions. Client Stubs

The Oracle Commerce Platform provides preconfigured client stubs for all Web Services in ATGWS.dll. To use these stubs you need to install ATGWS.dll. See Installing ATGWS.dll (page 46) for instructions. The client stubs provided here should be sufficient for your Web Services. Note that simultaneous calls to a Web Service made by different threads will require that a unique client stub instance exist for each thread. Web Services that Access RepositoryItems

Standard serializers and deserializers can handle some complex types, such as JMS messages sent to the ContentViewed and ContentRecommended Web Services. When Web Services interact with proprietary technologies, such as RepositoryItems, standard serializers and deserializers do not understand the source data type so they are not able to recreate it.

A RepositoryItem is a specialized JavaBean called a Dynamic Bean that produces basic get and set methods for the fields you define for it. Many complex items are stored by the Oracle Commerce Platform as RepositoryItems. The following Web Services transmit content that is natively stored as RepositoryItems:

• getProfile

• getRepositoryItem

• performRQLQuery

• getOrderAsXML (Core Commerce users only)

• getOrdersAsXML (Core Commerce users only)

• getProductXMLById (Core Commerce users only)

1 Creating and Using Web Services 45 • getProductXMLByDescription (Core Commerce users only)

• getProductXMLByRQL (Core Commerce users only)

• getProductSkusXML (Core Commerce users only)

• getPromotionsAsXML (Core Commerce users only)

For these Web Services, you can use the Atg.DotNet.WebService API to serialize and deserialize related content. Descriptions for API classes are in Using the Atg.DotNet.WebService API with RepositoryItems (page 49). You can find this API in ATGWS.dll, which you need to install in order to access them. See Installing ATGWS.dll (page 46).

Before You Begin Using a .NET Client

Before you can access a Web Service, you need to make sure the Oracle Commerce Platform is ready for your call and .NET is configured:

1. Confirm that the application that includes the Web Service is deployed on your application server and is running. For more information, see Deploying Web Services (page 13).

2. Install Internet Information Service (IIS) and then Active Server Page.Net (ASP.NET) and VisualStudio.NET (VS.NET).

3. Install ATGWS.dll so you can access the stub and API classes it contains. Installing ATGWS.dll

ATGWS.dll is a library that includes a stub class for each Web Service. It also provides the Atg.DotNet.WebService API used for serializing and deserializing RepositoryItems. All users who want to access Web Services from a .NET client should install ATGWS.dll. You need two versions of ATGWS.dll on your system. One version lives in you Global Assembly Cache (GAC) so ASP.NET is able to access it when compiling the Web Service call. Another version should exist in a location that VS.NET recognizes.

The instructions provided here direct you to use GACutil, a utility provided by .NET, although you can use any utility that can install ATGWS.dll to the Assembly folder in your windows directory. While the library does not need to live on the same machine as .NET, .NET needs to be able to access it.

To install ATGWS.dll:

1. Copy /DAS/os_specific_files/i486-unknown- win32/ATGWS.dll to your Windows\Assembly folder.

2. Open a command prompt and enter the following command:

:\ gacutil/i /DAS/os_specific_files/i486-unknown- win32/ATGWS.dll

In this example, represents the parent directory, such as c:\DotNet that holds your .NET software.

Keep in mind that each time you install a new version of ATGWS.dll, it coexists with older versions. The latest version of ATGWS.dll will instruct the .NET client to use it. There’s no need to uninstall ATGWS.dll when you want to install a new version. Remember when you do install new versions, you need to update references in VS.NET to the old version of ATGWS.dll. If you’d like to remove all versions of ATGWS.dll, use this command in a command prompt:

gacutil/u /DAS/os_specific_files/i486-unknown-

46 1 Creating and Using Web Services win32/ATGWS

Calling Web Services from a .NET Client

This section describes the components you need in order to call a Web Service. Because there are a few ways that you can generate a Web Service call on .NET, this section focuses only on the Oracle Commerce Platform resources you will use and assumes that you will refer to your .NET documentation for specific instructions.

The following sections should provide guidance when creating a Web Service call:

Accessing a Web Service (page 47)

Accessing a Custom Web Service (page 47)

Sample Web Service Calls (page 47) Accessing a Web Service

The Oracle Commerce Platform provides client stubs for all Web Services in ATGWS.dll. Once you have installed a version of ATGWS.dll to your GAC and Assembly folders (see Installing ATGWS.dll (page 46) for instructions), you need to do two things:

1. In your Visual Studio .NET project, make a reference to ATGWS.dll.

2. Create instances of the client stubs and use them in your Web Service call. Accessing a Custom Web Service

To access a Web Service that you created in the Oracle Commerce Platform, you create client stub and a reference to it in your Visual Studio.NET project:

1. Assemble your application. Make sure you include the modules that contain the Web Services you want to access.

2. Deploy the application on your application server and start it up.

3. In your Visual Studio .NET project, add the Web Services as Web References.

4. When prompted for an Address, provide the WSDL URI, such as:

http://hostname:port/repository/generic/getItem?WSDL

You can find the URI for Web Services in the documentation for the specific Web Service:

• For Repository Web Services, see the Repository Guide

• For Personalization Web Services, see the Personalization Programming Guide

• For Commerce Web Services, see the Core Commerce Programming Guide Sample Web Service Calls

The Web Service call is a document that incorporates calls to any number of Web Services that may exist in the same session. For each Web Service, you create an instance of the client stub, call methods on the Web Service, and call the Web Service itself. These Web Service calls are written in C#. Simple Call Example

This Web Service call obtains a RepositoryItem by accessing the getRepositoryItem Web Service.

1 Creating and Using Web Services 47 using Atg.DotNet.WebService.Repository.GetRepositoryItem;

// ...

// create stub instance GetRepositoryItemSEIService getItemClientStub = new GetRepositoryItemSEIService(); // assign URL of web service getRepositoryItemClientStub.Url = "http://example.com/repository/generic/getItem/getRepositoryItem"; // call web service string itemXml = getRepositoryItemClientStub.getRepositoryItem("/nucleus/path/to/repository", "itemDescriptorName", "repositoryId"http://example.com/repository/generic/getItem/ getRepositoryItem

Complex Call Example

The following code demonstrates how you would construct a call that uses security controls to restrict the information users can access. Notice that the loginUser Web Service establishes the user identity role, which other Web Services refer to. Because an instance of a CookieContainer is created in this code and assigned to each Web Service stub, all Web Services called here exist in the same session.

For brevity these examples omit some details such as an exception handling for the SoapException as well as class syntax.

using System.Net; // for CookieContainer using Atg.DotNet.WebService.Repository.GetItem; using Atg.DotNet.WebService.Repository.PerformRQLQuery; using Atg.DotNet.WebService.UserSession.LoginUser; using Atg.DotNet.WebService.UserSession.LogoutUser;

// create stub instances GetItemSEIService getItemClientStub = new GetItemSEIService(); PerformRQLQuerySEIService performRQLQueryClientStub = new PerformRQLQuerySEIService(); LoginUserSEIService loginUserClientStub = new LoginUserSEIService(); LogoutUserSEIService logoutUserClientStub = new LogoutUserSEIService();

// create a new cookie container for our session and share it between // the various stub instances CookieContainer cookieContainer = new CookieContainer(); getItemClientStub.CookieContainer = cookieContainer; performRQLQueryClientStub.CookieContainer = cookieContainer; loginUserClientStub.CookieContainer = cookieContainer; logoutUserClientStub.CookieContainer = cookieContainer;

// authenticate the user for the session loginUserClientStub.loginUser("user", "password", false);

// call services string itemXml = getItemClientStub.getItem("/nucleus/path/to/repository", "itemDescriptorName", "repositoryId"); string[] itemsXml = performRQLQueryClientStub.performRQLQuery("/nucleus/path/to/repository", "itemDescriptorName", "property = 'value'");

48 1 Creating and Using Web Services // log out the user logoutUserClientStub.logoutUser();

Using the Atg.DotNet.WebService API with RepositoryItems

The Atg.DotNet.WebService API is a mechanism that you can use to serialize and deserialize RepositoryItem content. The primary role of this API is to:

• Converts a RepositoryItem into an XML document (serialization)

• Formats an XML document into a RespositoryItem (deserialization)

By understanding the RepositoryItem API, Atg.DotNetWebService.RepositoryItem is able to convert into objects any content that uses the RepositoryItem API for its underlying data type. You can use this API for any Web Services that access RepositoryItems.

The Atg.DotNet.WebService is made up of the following classes:

RepositoryItem Class (page 50)

Property Class (page 51)

RepositoryItemRef Class (page 52)

Complex Type Class (page 52)

NoSuchPropertyException Class (page 53)

RepositoryItemSerializer Class (page 53)

RepositoryItemSerializationException Class (page 54)

Note: Rather than use this API, you could generate an XML schema representation of the RepositoryItem and use that serialize/deserialize content. The advantage of using an XML schema is that you can control the properties you use, meaning you can easily exclude certain properties from your schema. You may find the disadvantages, namely the limitations in property types and values that this method supports, reason to use the provided API instead. For instructions on how to use an XML schema for serialization/deserialization, see the Creating a Serializer and Deserializer (page 42).

About the Atg.DotNet.WebService API

Collectively, these classes provide you with the ability to serialize and deserialize RepositoryItems and to configure both processes. Although this discussion specifically describes the serialization process, the same principles apply to both processes.

When you want to deserialize content from a Web Service, for example, you use the response sent by a Web Service resulting from your initial Web Service call. The response, formatted in XML, holds a string object that represents RepositoryItems. Once you make the call to the API to deserialize the string, the deserializer parses the string into a RepositoryItem object.

Not all content in the string is emitted by the serializer. By default, only content specified as “dirty,” meaning a different value for it exists in the Oracle Commerce Platform and the external system .NET communicates with, is serialized. Once an item has been serialized, there’s parity across systems so all properties on that item are marked as “clean.” You can alter the default dirty/clean designation in the following ways:

• Use the RepositoryItem.Dirty property to toggle an object’s clean/dirty status

1 Creating and Using Web Services 49 • Use the RepositoryItem.setPropertyDirty methods to toggle a property’s clean/dirty status

During deserialization, content that represents RepositoryItem properties is parsed based on a few rules. All properties are converted back to the native data type, assuming that data type is available in .NET. The following data types do not exist in .NET and so values for these types are converted as follows:

• Map properties use Hashtable data type in .NET

• Date or Timestamp properties are stored as .NET DateTime data type

• Set properties are formatted as .NET Array data type

• Properties that refer to other RepositoryItems behave as .NET Hashtables

For the most part, Atg.DotNet.WebService determines format output type by relying on prior processing. For example, if it had deserialized a particular RepositoryItem, such a Growth fund, then assuming no new properties are added, when the Growth fund is serialized, Atg.DotNet.WebService.RepositoryItem is aware of each property’s destination data type. However, in all other circumstances, you should explicitly include the XML data type for the property. In short, under these circumstances include data types:

• The first time a RepositoryItem is serialized when it has not been previously deserialized, such as in the case of adding a new item to the Oracle Commerce Platform

• A new property value is assigned to an empty RepositoryItem

Note: In order to use the classes in this interface, make sure that the Oracle Commerce Platform atg/ repository/xml/RepositoryXMLTools component has the encodeRepositoryIdAsAttr property set to true. This is the default setting.

RepositoryItem Class

The Atg.DotNet.WebService.RepositoryItem class is designed to manage XML serialization and deserialization for easy interoperability with the .NET Web Services framework.

To serialize or deserialize a RepositoryItem, you need only to pass in the RepositoryName and RepositoryId. When you are working with content for the first time, you also need to call setPropertyType to instruct the deserializer/serializer to use a specific output data type.

Class Element Description

properties Dirty Determines the overall dirtiness of an object by specifying whether all properties are clean (false) or one of more properties are dirty (true).

ItemDescriptorName Name of the item descriptor associated with the object’s RepositoryItem.

Properties List of properties for this RepositoryItem.

RepositoryId ID provided to the object’s RepositoryItem representation.

RepositoryName Name of the repository that the RepositoryItem is part of.

50 1 Creating and Using Web Services Class Element Description

constructors RepositoryItem() Constructs a new, empty RepositoryItem object. When you serialize or deserialize a property with a value that is a pointer to a RepositoryItem, be sure to supply it a RepositoryName, RepositoryId, and ItemDescriptorName when you invoke the setRepositoryItem method.

RepositoryItem(string) Constructs a new RepositoryItem in the Oracle Commerce Platform, populating it with values parsed from the XML instance of the Web Service call. The XML instance is a by- product from the Web Service call generation.

methods clearPropertyValues Clears all property values for a given RepositoryItem. Before using RepositoryItemSerializer.deserialize, it’s a good idea to use this method to clear all previous values.

isPropertyDirty Determines whether a given property value is dirty (true) or clean (false).

setPropertyDirty Designates a given property as dirty.

getPropertyValue Returns the value provided for a property in the Oracle Commerce Platform. If the property does not exist, an error of type ATGWS.NoSuchPropertyException is thrown.

setPropertyValue Sets a value for a property in the Oracle Commerce Platform.

getPropertyType Returns the property’s XML data type.

setPropertyType Specifies the XML data type for the property value.

serialize Creates a string representation of an XML document for the RepositoryItem.

Property Class

This class represents a given property’s name and value.

1 Creating and Using Web Services 51 Class Element Description

properties Dirty Determines whether a given property is dirty (true) or clean (false). If you indicate that a property value should change by invoking the RepsoitoryItem setPropertyValue call, this property is set to true. Once a response is returned from the setPropertyValue call, this property is set to false.

XmlType XML data type that will be used to represent the property’s value.

constructor Property() Constructs an empty object representing a property.

methods getName Returns the name of the property.

getValue Returns the value of the property.

setValue Sets a new value to the property.

RepositoryItemRef Class

This class represents a reference to another RepositoryItem.

Class Element Description

properties RepositoryName Name of the repository of which the referenced RepositoryItem is a part.

ItemDescriptorName Name of the item descriptor used by the referenced RepositoryItem .

RepositoryId ID for the referenced RepositoryItem .

method setRepositoryItem Initializes the ItemRef to refer to the provided RepositoryItem.

Complex Type Class

This class permits you to serialize/deserialize properties that use complex types by specifying an output data type explicitly.

52 1 Creating and Using Web Services Class Element Description

properties TypeName Data type for the RepositoryItem property.

Properties Name of any properties that are either deserialized from or serialized into the complex type.

constructor ComplexType() Constructs an empty object to represent all properties of a complex data type.

methods getPropertyValue Retrieves values from the Oracle Commerce Platform for the specified properties. If the property does not exist, an error of type ATGWS.NoSuchPropertyException is thrown.

setPropertyValue Sets a property to a value supplied as an input.

getPropertyType Returns the XML data type for the property value.

setPropertyType Specifies the XML data type for the property value.

NoSuchPropertyException Class

This class generates an exception each time a getProperty or getPropertyValue method tries to interact with a property that has not been specified for the designated RepositoryItem.

Class Element Description

property PropertyName Name of the property that you are trying to work with.

constructor NoSuchPropertyException Constructs the exception.

RepositoryItemSerializer Class

This class conducts serialization/deserialization and permits you to decide if you want all or only dirty properties to be updated.

1 Creating and Using Web Services 53 Class Element Description

constructors RepositoryItemSerializer() Constructs a serializer instance.

RepositoryItemSerializer(RepositoryItem) Constructs an object holding serialized content.

methods deserialize (string) Deserializes an XML-formatted string into a new RepositoryItem.

deserialize (string, boolean) Deserializes an XML document string into a RepositoryItem. Additional arguments true or false indicate whether values for only dirty properties (true) or all properties (false) should be deserialized.

serialize (string) Serializes a RepositoryItem into an XML-formatted string document.

serialize (boolean) Serializes a RepositoryItem into an XML document. Additional arguments true and false indicate whether values for only dirty properties (true) or all properties (false) should be deserialized.

RepositoryItemSerializationException Class

This class creates an exception object when errors occur during serialization or deserialization.

Class Element Description

constructor RepositoryItemSerializationException() Constructs an empty exception object.

54 1 Creating and Using Web Services 2 Introduction to REST Web Services

This section provides information about and instructions for using the Oracle Commerce Platform Representational State Transfer (REST) Web Services.

Oracle Commerce Platform REST Web Services provide access to Nucleus components. Nucleus components are server-side JavaBeans and servlets that perform the back-end functionality of a Web application, such as enabling database connectivity, logging, scheduling, and handling HTTP requests.

This section is divided into three parts:

• Introduction to REST Web Services (this section) describes generic REST Web Services and terminology.

• Part I, “Oracle Commerce Platform JAX-RS REST Web Services” (page 65) describes the Oracle REST services that use JAX RS. This section describes the framework, components and resources that you can use to develop endpoints for REST services.

• Part II, “Oracle Commerce Platform REST MVC Web Services” (page 135) describes the extensible REST MVC API, describing the architecture and components that allow you to create REST services, as well as instructions on creating your own REST services. This section also provides detailed examples of REST services that have been provided for quick implementation

REST Web Services Overview

In general, a REST Web Services exposes data and function resources through the use of Uniform Resource Identifiers (URIs). These resources are used within simple, well-defined operations. HTTP methods are used by the REST services to point to a resource. Each HTTP request returns an HTTP response, which indicates the status of the operation. The application that receives the request identifies the format of the response, which is JSON or XML.

REST clients may be accessed from any browser, and security can be configured for each call.

2 Introduction to REST Web Services 55 REST Web Services URLs

URLs are a central component of REST Web Services, as you access different components and functions of the Oracle Commerce Platform using specific URLs.

The application path for REST URLs, which is the portion of the URL that follows the hostname and port number, starts with /rest/. For example, you would use the following URL to initiate adding an item to a shopping cart using the /atg/commerce/order/purchase/CartModifierActor/addItemToOrder component.

http://servername:port/rest/REST framework type/atg/ commerce/order/purchase/CartModifierActor/addItemToOrder

The portion of the application path following /rest/ identifies which version of the Oracle Commerce Platform REST framework type you are using.

The REST MVC framework uses /model, for example:

http://servername:port/rest/model/atg/commerce/order/purchase/ CartModifierActor/addItemToOrder

For additional information, refer to The REST MVC Definition Framework (page 139) section.

URLs can supply additional data to the REST Web Service using parameters or form post data. By setting control parameters, as described in the Adding Control Parameters (page 61) section, or standard query and/or post parameters, you can set values, supply arguments to a method, or supply form field values. You use standard URL query string syntax when adding parameters.

HTTP Request Methods

As discussed earlier, HTTP requests and responses are the way that the Oracle Commerce Platform REST Web Services communicate. The following HTTP methods are used and supported by Oracle Commerce Platform REST Web Services:

56 2 Introduction to REST Web Services Method Explanation

GET Use this method to return data.

Examples of the values you may get are repository item and Nucleus component property values, RQL query results, repository items, and Nucleus components.

POST Use this method to invoke functionality or make changes to your Oracle Commerce Platform server.

For example, you may invoke methods, update Nucleus component properties, and create repository items.

For additional information on these and other HTTP methods, refer to the W3 definitions, available at http:// www.w3.org.

HTTP Status Codes

Whenever an Oracle Commerce Platform REST Web service is called, an HTTP status code is sent to indicate the result of each request. The HTTP status codes that are used with Oracle Commerce Platform REST Web Services are:

Code Description

200 (OK) The request was processed successfully. This does not mean that it had the result you intended. See information about how to determine success or failure in the instructions for specific operations.

201 (Created) Returned only for POST requests that create repository items. The request was successful and the repository item was created.

400 (Bad Request) The request could not be completed because the request URL and/or parameters were improperly formatted.

401 (Unauthorized) The user session does not have the proper security credentials to execute the method, property, or access the repository for the requested resource.

403 (Forbidden) The specified property has been configured as not writeable via the filtering configuration.

404 (Not Found) The request could not be completed because it was made for a resource that does not exist.

410 (Gone) Returned only for DELETE requests that remove repository items. The request was successful and the repository item was deleted.

500 (Internal Server Error) The request could not be completed because an unexpected exception occurred.

2 Introduction to REST Web Services 57 For additional information on these and other HTTP status codes, refer to the W3 definitions, available at http:// www.w3.org/.

Returning Data

Oracle Commerce Platform REST Web Services returns the results of operations that you perform in an HTTP response message body. The output data can be returned in either JavaScript Object Notation (JSON) or eXtensible Markup Language (XML) format.

The following example shows output data in JSON format.

{"password": "280001"}

The following example shows output data in XML markup.

280001

You can configure your return output data to be provided in the format you choose by setting the default return output type on the REST server. Additionally, using the atg-rest-output command, you can override the default output type. Refer to the Adding Control Parameters (page 61) section for additional information.

For information on configuring output in REST MVC, refer to the Configuring REST MVC Output (page 177) section.

Using cURL for Examples

The examples in this document use the cURL command-line tool to send and receive HTTP messages. cURL is shown in these examples because its command-line invocation shows the input and the HTTP activity that takes place when using the REST Web Services. For additional information about the cURL command-line tool, refer to http://curl.haxx.se/.

Note: You can use any client software to exchange HTTP messages with REST Web Services. Oracle Commerce Platform is not associated with the makers of the cURL command-line tool in any way.

The cURL examples use several command-line flags. These flags configure the behavior of the cURL command- line tool as it makes HTTP requests. The flags are included in examples to better show the HTTP requirements of the Oracle Commerce Platform REST Web Services interface and to help you reproduce the examples if you choose to do so.

Writing cURL Examples

When writing an example, use cURL to perform the following:

1. Invoke cURL using the curl command.

58 2 Introduction to REST Web Services 2. Identify command components that identify locations, cookie files or write verbose output. Refer to the cURL Command Components (page 60) table for a list of commonly used commands.

3. Identify the cookie file that the service will write to upon completing an operation.

4. Specify the HTTP communication method with the –X command. Note that for REST MVC, the communication method is limited to GET and PUT.

5. Indicate that the specified content type should be declared in the HTTP request header by using the –H command.

6. Identify the content type to use. For information on content types, refer to Setting the Content-Type Value in REST Services (page 63).

7. Indicate that the following text should be used within the message body of the HTTP request.

8. Provide the parameters and their values to be included within the message body.

9. Identify the REST server and port, as well as the REST call. Note that the REST call, which is identified using the http://… syntax, is included in quotation marks (“ “). Technically, cURL does not require this, however any parameters that follow an ampersand (&) will not be recognized if the command is not included in quotation marks.

10.Provide any control parameters. Refer to Adding Control Parameters (page 61) for detailed information.

REST MVC cURL Format

When invoking cURL for REST MVC examples, use the following format:

curl -H -d "{ : , : }" "http://:/rest/model/ /?"

The following is a cURL example of a REST MVC external user log in. This example uses the cookie file customer_cookies.txt, identifies the content type as JSON, and provides the parameters and their values that are used by the ProfileActor login actor-chain.

curl -L -v -c customer_cookies.txt -H "Content-Type: application/json" -d "{ "login" : "[email protected]" , "password" : "password123" }" "http://localhost:8080/rest/model/atg/userprofiling/ProfileActor/ login"

Server Response to cURL Examples

A few of the examples that follow will provide specific server responses. An example of this format for this output may be similar to the following:

{ "shippingGroups": {"Test": { "specialInstructions": {}, "priceInfo": {

2 Introduction to REST Web Services 59 "amount": 0, "currencyCode": null, "amountIsFinal": false, "discounted": false }, "description": "sg140012", "actualShipDate": null, "submittedDate": null, "state": 0, "locationId": null, "shipOnDate": null, "shippingMethod": "hardgoodShippingGroup", …

cURL Command Components

The following table lists commonly used cURL commands. For additional information or components, refer to http://curl.haxx.se/.

Component Explanation

curl Names the program being invoked. The manner in which you invoke the cURL command- line tool depends on how it has been installed in your environment.

-L Identifies an HTTP Location. If the server reports that the requested page has moved to a different location (indicated with a Location: header and a 3XX response code), this option will make cURL redo the request at the new location.

-v Writes verbose output while sending and receiving HTTP messages. This option exposes more details of the HTTP transaction.

-b Uses cookies stored in the specified file to authenticate the client. The customer_cookies.txt file is used for external REST MVC calls, and the agent_cookies.txt file is used for agent-based internal REST MVC calls.

A session identifier must be stored in the file. When cURL logs into the REST Web Services, the cookies.txt instructs it to write the cookies it receives in that file.

-c This command line option activates the cookie engine that makes cURL record and use cookies. You can also activate cookies by using the -b cookie option. Using –c provides the HTTP cookie file where cURL writes all cookies after a completed operation. cURL writes all cookies previously read from a specified file, as well as all cookies received from remote server(s). If no cookies are identified, no file will be written.

-X Use the specified HTTP method when communicating with the REST Web Services.

-H Include the specified Content-Type declaration in the HTTP request header. This describes the nature of the data in the message body of the HTTP request.

-d Include the following content in the message body of the HTTP request.

URL The URL of the REST Web Service that is used in the example.

60 2 Introduction to REST Web Services Note: The HTTP transactions shown in the examples in this document may include specific details of the testing environment used to produce them. Some details may differ in the HTTP transactions you conduct with the REST Web Services. For example, the application server version identifiers shown in the HTTP transaction may not match the application that your Oracle Commerce Platform server uses.

Adding Control Parameters

Include control parameters with HTTP requests to alter the way that the REST Web Services handle them. For example, if you would like the server to include an identifying string in the response, you can use the atg- rest-user-input control parameter to specify that identifying string.

You can include control parameters either in the URL for the REST Web Service or in the message body of a POST or PUT request.

Note: Several control parameters have equivalent configuration properties. Set these configuration properties to control the way that REST MVC Web Services are processed by default. See The REST MVC Definition Framework (page 139).

The following table explains the control parameters recognized by the REST Web Services server.

Parameter Explanation

atg-rest-class- Use this parameter to specify the container and element Java classes for descriptor nested object property values.

atg-rest-class-type Use this parameter to specify a Java class when you are setting an object property value.

atg-rest-index Use this parameter to specify the entry in an array or ordered list that will be the starting point when that array or ordered list is returned by the server. Set the value of the parameter to the integer value of the starting position.

Use this parameter with atg-rest-count.

atg-rest-input Use this parameter to override the default input format configured for the server.

Set the value of this parameter to json or xml.

atg-rest-json-input Use this parameter to control whether the REST Web Services server will accept standard JSON markup for setting collection or map values on repository item properties.

atg-rest-method Use this parameter to specify the Java method signature when calling an overloaded method.

This parameter is only needed if two or more instances of the overloaded method have the same number of arguments.

atg-rest-null Use this parameter to set the value of a component or repository item property to null. Set the property and include this parameter as the new value.

2 Introduction to REST Web Services 61 Parameter Explanation

atg-rest-output Use this parameter to override the default output format configured for the server. Set the value of this parameter to json or xml.

atg-rest-param-class- Use this parameter to specify the Java classes for multiple values in JSON types functional parameters. The atg-rest-param-class-types parameter includes three components, container-class, element-class, and key- class.

For example, if a functional parameter is a java.util.ArrayList, set the atg-rest-param-class- types as shown below.

{'container-class': 'java.util.ArrayList', 'element-class':'java.lang.String'}

Use the key-class attribute when the container-class implements java.util.Map. For example:

{'container-class':'java.util.HashMap', 'key-class':'java.lang.String', 'element-class':'java.lang.String'}

atg-rest-simple- Include this parameter to cause the server to return OK (200) for success response-codes rather than CREATED (201) or GONE (410).

atg-rest-transient Use this parameter to create transient repository items.

atg-rest-user-input Use this parameter to specify an identifying string that the REST Web Services server will include in the HTTP response.

Functional Parameters for Oracle Commerce Platform REST Web Services

Functional parameters provide data that is required by the Oracle Commerce Platform REST Web Services operation you are performing. For example, if you are setting a property value, the new value is a functional parameter of the operation.

You can include functional parameters either in the URL for the Oracle Commerce Platform REST Web Service or in the message body of a POST or PUT request.

The functional parameters you provide for an Oracle Commerce Platform REST Web Services operation depend on the nature of that operation. When invoking a method, you may supply arguments to it. When invoking a form handler, you will supply the form field values. When setting a repository item property value, you will supply the new value. The functional parameters for each operation are explained in the procedures for those operations.

62 2 Introduction to REST Web Services Using Positional Parameters

Some Oracle Commerce Platform REST Web Services operations require parameters that are not named. For example, if you invoke the loginUser method of the /atg/userprofiling/ProfileServices component you must pass in two positional arguments. The first is the login value for a user and the second is the password value for that user.

Using URL Parameters

You can include control and functional parameters in the URL for Oracle Commerce Platform REST Web Services by using standard URL query string syntax and URL encoding. The following Oracle Commerce Platform MVC REST example shows a URL with two functional parameters and a control parameter.

http://localhost:8280/rest/model/atg/userprofiling/ProfileActor/ [email protected]&password=1234&atg-rest-user-input=MyMessageId

Using Message Body Parameters

You can include control and functional parameters in the HTTP message body of an Oracle Commerce Platform REST Web Services request. The following HTTP request includes two functional parameters and a control parameter in its message body. The content in the message body is specified by the -d flag in this cURL command.

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" -d "{ "login" : "[email protected]" , "password" : "password123" }" "http://localhost:8280/rest/model/atg/userprofiling/ProfileActor/ login?atg-rest-user-input=MyMessageId"

The Oracle Commerce Platform REST Web Services server can interpret message body parameters in one of the following three markup formats. Make sure you set the correct Content-Type value for the markup that you use.

• XML

• JSON

Setting the Content-Type Value in REST Services

Set the Content-Type value when you send an HTTP message with parameters in its message body. The Oracle Commerce Platform REST Web Services server uses this value to determine how to interpret the parameters. If you do not include the Content-Type or include a value that does not match the markup of your parameters, the server will ignore the message body.

Use one of the following Content-Type values to specify the markup of the parameters in a message body.

• Content-Type: application/xml

• Content-Type: application/json

• Content-Type: application/x-www-form-urlencoded

The following REST MVC example shows an HTTP request that sets its Content-Type to application/xml.

2 Introduction to REST Web Services 63 curl -L -v -b customer_cookies.txt -H "Content-Type: application/xml" -d "{ "login" : "[email protected]" , "password" : "password123" }" "http://localhost:8280/rest/model/atg/userprofiling/ProfileActor/ login?atg-rest-user-input=MyMessageId"

Using Array Types

To specify an array type in the atg-rest-class-descriptor control parameter, use the standard Java notation for arrays.

Array Type Java Notation

String [Ljava.lang.String;

byte [B

int [I

Two-dimensional array of Strings [[Ljava.lang.String;

64 2 Introduction to REST Web Services Part I. Oracle Commerce Platform JAX-RS REST Web Services

The Oracle Commerce Platform REST framework uses JAX-RS, which is a standard used to develop Restful Web Services. JAX- RS provides annotations that allow you to map a resource class as a Web resource. The framework is an extension of the Jersey application, which extends the JAX-RS standard with additional features and utilities.

RESTful architectures use resources, which are identified by logical URLs. Every component is a resource, and resources are accessed by a common interface. REST servers provide access to resources; and REST clients can access the resource. The system also provides you with REST endpoints within the application allowing you to map a URI and an HTTP method to a resource.

3 The Oracle Commerce Platform JAX- RS Framework

RESTful Web services target resources that are used explicitly by a Web service client using a subset of HTTP operators. The Web service requests are routed through a single Jersey servlet, through which all endpoint services are registered. The servlet routes incoming calls to the appropriate endpoint, depending on the composition of the request and the configuration of the endpoint class or method.

Some key capabilities of the JAX-RS framework are:

• Annotation-based resource development

• XML-based filtering and validation schema support, which is easily configured and extensible with configuration layering

• Built-in support for API versioning, locking, transactions, caching, localization, filtering, validation, resource version tracking, exception mapping, relation registry, self-documentation with Swagger and asynchronous endpoints

• Support for both the standard Oracle JSON REST media type, and the HAL media type and HATEOAS

• Extensible with Nucleus component-based resources and framework feature providers

• Support that allows endpoints to invoke form handlers, droplets or Actor chains to reuse preexisting functionality

• A registry that provides extensible mapping of application exceptions to specific HTTP response codes

• The ability to control the fields and links in the response and request representation of a resource

• User authentication using OAuth

• Custom annotations for creating service endpoints

For detailed information on creating your own resources and endpoints, refer to the Writing Resources and Endpoints (page 73) section.

Framework Overview

The Oracle Commerce Platform REST framework supports the JAX-RS standard with Jersey as the underlying implementation.

3 The Oracle Commerce Platform JAX-RS Framework 67 The Jersey configuration defines the components of the JAX-RS application, such as resource classes and components, filters, and additional metadata.

The following diagram shows the flow of the main REST framework components that are used when an HTTP request is made. The REST framework is initiated when a request is received by the Jersey servlet. The servlet is responsible for invoking the provider components in the correct order:

The framework supports multiple versions and/or contexts of the REST JAX-RS API. Each version and context must configure the Jersey servlet with the appropriate context root URI.

The Jersey servlet is configured in the web.xml file to reference the JAXRSApplication class which, during server startup, gets the set of providers and resources from the RestResourceRegistry Nucleus component for that version. The web.xml file also includes the appropriate validation registry. These registries provide the configuration for a specific context or version, for example, /public/v1. Each context and version of the API is configured with its own Web application and Jersey servlet, for example, /public/v1 would be a separate Web application and servlet from /public/v2 or/admin/v1.

The following is an example of a web.xml configuration:

Jersey atg.service.jaxrs.JerseyServletWrapper atg.service.jaxrs.JerseyServletWrapper.servletClasses org.glassfish.jersey.servlet.ServletContainer, atg.service.swagger.SwaggerBootstrap javax.ws.rs.Application atg.service.jaxrs.JAXRSApplication

68 3 The Oracle Commerce Platform JAX-RS Framework jersey.config.server.provider.classnames atg.service.swagger.SwaggerApiListingResource, io.swagger.jaxrs.listing.SwaggerSerializers atg.service.jaxrs.JAXRSApplication.resourceRegistryPath /atg/dynamo/service/jaxrs/RestResourceRegistry atg.service.jaxrs.JAXRSApplication.validatorRegistryPath /atg/dynamo/service/validator/ValidatorRegistry atg.service.swagger.SwaggerBootstrap.bootstrapService /atg/dynamo/service/swagger/SwaggerBootstrapService 2 true Jersey /*

When setting up the web.xml file there are four configurations that you must provide.

• You must configure a JAXRSApplication class that will be used as the Jersey access point for the provider and resource classes in the API.

• The RestResourceRegistry Nucleus component should be configured with the provider and resources for the API that are available to the JAXRSApplication instance. For additional information on the RestResourceRegistry, refer to the Working with REST Resource Nucleus Components (page 78) section.

• The ValidatorRegistry component must be configured with the validator XML schema definition file that validates request input and filters the response output. For information on configuring validation, refer to the Validating Input and Filtering Output (page 95) section.

• You should also configure the SwaggerBootstrapService component, which scans the API and builds the Swagger definitions and documentation. For information on configuring Swagger definitions, refer to the Self Documenting with Swagger (page 114) section.

Support for OAUTH 2.0

The OAuthService supports OAUTH 2.0 authentication. Additionally, a logged-in access checker that can enforce a valid token is contained within the request before allowing access to an endpoint. For additional information, refer to the Configuring Endpoint Security (page 104) section.

3 The Oracle Commerce Platform JAX-RS Framework 69 API Versioning

The REST module contains sub-modules with Web configuration for each specific context and version. For example, the public/v1 API is configured under the REST.JAXRSPublic.Version1 module. You can use a request to replace the version in the URI by using the keyword latest, for example, /public/ latest, which then uses the most recent version of that context API. Note that this requires that a separate Web configuration is available. For example, /public/latest is supported using the configuration in the REST.JAXRSPublicLatest module.

Filtering the Requests

The framework uses container request filters, which are executed before the resource method is invoked. Pre- matching request filters are called before a suitable resource method has been found for the resource, allowing you to identify which method is matched for the HTTP request. Post-matching request filters are run after a method has been matched for the resource and enable you to stop a request before the resource method is invoked.

The Jersey servlet references the JAXRSContextPreMatchRequestFilter, which is an implementation of a pre-match filter request. This filter initializes a RestContext instance for the request, which is a holder class that keeps data that has been gathered during the processing of the request. The RestContext instance is kept in a thread-local stack that can be accessed statically. The filter also provides support for tunneling using the x- http-method-override header, which allows a client to specify the HTTP method that the server should use for the request regardless of the actual request HTTP method. This filter sets the value as the HTTP method in context. This allows clients who may be restricted in the HTTP methods they can use for a request to still invoke other endpoints. For example, if a client can only issue GET and POST requests, they could issue a POST request with the x-http-method-override = "PATCH" to invoke a patch-based endpoint.

The JAXRSContextPostMatchingRequestFilter, which is the first post-matching filter called by Jersey, populates the current RestContext with details of the resource that matched the request and populates its filter properties if any applicable query parameters have been passed in by the client. It is executed after the resource method has been selected and sets up the current RestContext for the matched resource.

The SecurityPostMatchRequestFilter, which runs after the JAXRSContextPostMatchingRequestFilter, invokes the access control for the request URI and HTTP method and rejects the request if access is denied. If access is denied, an exception is thrown with the appropriate response code.

Once the request security has been verified, the CachePostMatchRequestFilter component performs validation on the request. By default, this Nucleus component is configured with a set of validators that include XSS checks and asset language checks. If locking is enabled for the resource, the CachePostMatchRequestFilter acquires a lock for the resource. This filter also provides Etag pre-condition support for the If-Match header. If the request is a GET request and there is a server-side cached response available that matches the request, the response is returned to the client and processing ends.

The CachePostMatchRequestFilter uses either the JSONMessageBodyReader or the HALMessageBodyReader to read the request header. The HALMessageBodyReader is used when the content- type header is application/hal+json; otherwise the JSONMessageBodyReader is used.

Wrapping the Endpoint Methods

The RestEndpointInvocationHandler wraps the endpoint resource method, followed by the CacheResponseFilter. The RestEndpointInvocationHandler is the main Nucleus component responsible

70 3 The Oracle Commerce Platform JAX-RS Framework for invoking matched resource endpoints. This allows you to wrap the endpoint resource method with extra behaviors, and allows the framework to resolve Nucleus request-scoped resource components. If the endpoint is transactional, the RestEndpointInvocationHandler creates a transaction to wrap the rest of the processing. It also invokes the validation service to validate the input JSON against the schema. If the resource is not a Nucleus component, then it ensures that any fields annotated with NucleusComponent are resolved. The RestEndpointInvocationHandler also invokes any preAction or postAction annotated methods for the endpoint, as well as invoking the endpoint itself. It then ends the transaction. If the resource is a global Nucleus component, then the RestEndpointInvocationHandler resolves it and ensures that any Jersey injection needed to populate fields occurs.

For detailed information on wrapping endpoint methods, refer to the Running Methods Before or After Endpoints (page 91) section.

Caching

Once the RestEndpointInvocationHandler has invoked all of the endpoint methods, the CacheResponseFilter automatically generates HATEOAS links for the response based on the other endpoints available for the resource. It also ensures that any response headers are populated, including the authentication and Etag headers. Once that is done, it releases any acquired locks, unless the lock should be maintained to process sub-resources for the request.

Once the CacheResponseFilter has finished, the CacheWriterInterceptor is invoked if the response entity contains a body. It ensures that the writers will only write to a temporary in-memory output stream, allowing the interceptor to modify the response before it is streamed back to the client. It then tells Jersey to invoke the message body writer. On return from the message body writer, it saves state data to the client response stream, if needed for stateless support. This interceptor also sets up a no-cache header if client side caching should be disabled for the resource. It also creates an Etag for the response. If server-side caching is enabled, the response is saved in a cache and the response is written out to the client output stream.

For additional information, refer to the Working with Caching (page 106) section.

Converting Responses

The CacheWriterInterceptor invokes the JSONMessageBodyWriter, OracleJSONMessageBodyWriter or HALMessageBodyWriter by matching the Accept header media-type specified by the client. Responses that are not resource representations or error responses are output using the JSONMessageBodyWriter. If the response entity has no body, no writer is invoked.

MessageBodyWriters use JSONService and JSONObject to convert and write out responses. The HALMessageBodyWriter writes a HAL-formatted JSONObject to a response, while the OracleJSONMessageBodyWriter converts the object to Oracle format and includes any embedded resources.

MessageBodyWriters use an output producer and filtering manager to render the resource representation state for output. They also add any links needed to the output. For embedded resources, the MessageBodyWriter classes use the internal client in the JAXRSApplication to invoke a GET through Jersey to retrieve the embedded resource. This means that the request is routed back through Jersey and will go through the entire framework process again to obtain a representation of the embedded resource. Once the embedded resource representation is retrieved it is added to the output. For additional information on embedded resources, refer to the Using Embedded Resources (page 76) section.

On collection resources, members are retrieved by doing a lookup for the GET method, and directly invoking the collection to get each member resource representation model, which is then rendered for output using the output producer and filtering manager.

3 The Oracle Commerce Platform JAX-RS Framework 71 For detailed information on configuring resource filtering, refer to the Validating Input and Filtering Output (page 95) section.

Configuring Caching and Locking

The framework uses components that are called during request processing to provide functionality such as transactions, locking and caching. Custom annotations allow you to use this functionality in your service endpoints.

The JAXRSCachePostMatchRequestFilter, which implements request validation and locking, is executed once the resource method is selected, but before Jersey invokes the resource method. The JAXRSCacheResponseFilter, which is executed after a response is provided for a request, releases any locks, adds Etag headers to the response and provides caching. For information on Etag headers, refer to the Using Etags for Version Tracking (page 108) section.

For detailed information on working with locking and caching refer to the Enabling Locking (page 93) and Configuring Server-Side Caching (page 107), as well as the Working with Caching (page 106) sections.

Working with Multiple Sites

The framework supports multiple site environments provided that the sites are differentiated by name-based domains and not URL paths. For example, the following multiple site configuration is supported:

http://site1.domain.com/public/v1/products/{productId} http://site2.domain.com/public/v1/products/{productId}

The following multiple site configuration is not supported:

http://domain.com/site1/public/v1/products/{productId} http://domain.com/site2/public/v1/products/{productId}

For information on configuring domain name-based URLs, refer to the Multisite Administration Guide.

72 3 The Oracle Commerce Platform JAX-RS Framework 4 Writing Resources and Endpoints

This section discusses and instructs you on how to set up and configure REST endpoints.

Before You Begin

This section describes information that you should familiarize yourself with before writing resources and endpoints for the Oracle Commerce Platform REST framework.

Creating Naming Standards

When creating REST resources, it is best to provide consistent and meaningful names. Names that provide context will assist your users when performing REST calls. Name your resources and endpoints using nouns, and not verbs or actions. REST JAX-RS APIs should refer to a resource rather than an action.

Types of Resources

Resources can be individual resources or part of a collection. Collection resources are the plural format of a resource. For example, order is an individual resource while orders denotes a collection.

Resources can can are also categorized as a root resource or a sub-resource. A root resource is a resource that has no parent associated resource. A sub-resource is a resource that exists only in the context of a parent resource, for example an address resource exists in conjunction with a profile resource.

When creating a resource, it is best not to create dependencies between resource classes. Instead, use the REST resource registry and other framework components, such as LinkUtils, to resolve URIs or resolve sub-resource references.

Working with Endpoints

Endpoints can either specify an HTTP method or can use a specific JAX-RS annotation, such as @GET, @HttpMethod, @PATCH, and so on. Endpoints are methods on a resource that can be invoked by a client. An endpoint method may have its own @Path annotation that appends to the resource path. Endpoints should never specify an empty path. Should that be necessary, remove the annotation.

4 Writing Resources and Endpoints 73 Using the REST Entry Point

The framework provides a number of endpoints for services. A REST entry point is available using the base URL, which can be accessed on the server using HTTP. For example:

http://example.org/public/v1

The response from this entry point might be similar to this:

{ isLatest: "true", catalog: { links: [ { method: "GET", rel: "self", href: "http://example.com/public/v1/metadata-catalog? useFilterId=metadataCatalog-Default" }, { rel: "up", href: "http://example.com/public/v1" }, { method: "GET", rel: "canonical", href: "example.com/public/v1/metadata-catalog" } ], items: [ { name: "promotions", links: [ { method: "GET", rel: "/rels/getResourceSchema", href: "http://example.com/public/v1/metadata-catalog/promotions" }, …

Using Utility Classes

The following classes provide helper methods that assist you when working with data and links.

REST Utilities

RestUtils allows you to, for example, validate input or get a handle on another resource. This Nucleus component, which can be accessed statically using the getRestUtils method, also provides you with a way of storing and retrieving data for a request. This can be helpful when you load an object in a root resource that is required by a sub-resource. The object can be retrieved using RestUtils in the sub-resource. For example, the /orders/{old} endpoint may want to store the order object so that the /commerceitems/{cId} endpoint can retrieve the stored order object for the request, rather than load the order object to get every commerce item.

74 4 Writing Resources and Endpoints Use the RestUtils.addRestRequestData (String pKey, Object pValue) method or the RestUtils.getRestRequestData (String pkey) method to store or retrieve data.

For additional information on these methods, refer to the ATG Platform API Reference.

Link Utilities

The LinkUtils Nucleus component can be accessed statically and provides helper methods that allow you to build links or other URIs for a resource. LinkUtils is also used by the framework when performing actions related to link generation.

Working with Resource Representation Models

The RepresentationModel is a holder class that allows you to build a representation of a resource for a response. It contains properties that specify the resource state, embedded resources, collection members, links, headers, and other properties. If an endpoint needs to respond with a representation of the resource, create an instance of this class.

The RepresentationModel has a version property that allows the endpoint to specify the version number for the resource. If the version property is not set, the framework attempts to get the version from the RepresentationModel state, provided that the state is a RepositoryItem and the RepositoryItem has a version property. If the version number cannot be obtained from the RepresentationModel, the framework uses the ResourceVersionRepository to track version numbers. For more information, refer to the Working with Client-Side Caching (page 107) section.

If an endpoint response is not a representation of a resource and does not require any HATEOAS support, the endpoint can return objects other than RepresentationModel. For example, the login endpoint responds with access token information by returning a Map. The JAX-RS Response class can also create a response.

The status code of a response defaults to 200 (ok) but you can customize response codes using the status method of the RepresentationModel. There are also utility methods for created and accepted status. Response headers can also be set using the header method of the RepresentationModel as well as add member to embedded collection resources.

Endpoints can also return a RepresentationModel object where a representation of the resource is transformed into the media type requested by the client. RepresentationModel should include the URI of any embedded sub-resources and let the payload schema configuration process determine if the sub-resource is returned in a representation response.

If the resource is a collection, then the member URIs of the resource should be added to the RepresentationModel.

When you add a definition to the relations registry, the RepresentationModel builds the relation name preceded with the relation definition key. For example:

RepresentationModel model = new RepresentationModel.Builder().state(order).links (Link.fromPath("/test/order/o12345").rel("oc:submitMyOrder"));

4 Writing Resources and Endpoints 75 Using Embedded Resources

When a resource URI has been embedded in a RepresentationModel, the framework message body writer invokes the URI to get the resource representation to embed. Note that an embedded resource will only appear in the response if the payloadSchema.xml includes an embedded tag for the embedded relation name. The use-validator-id attribute of the embedded tag identifies the validator to use for the embedded resource.

Embedded collection resources members can be added to the RepresentationModel by calling the members method and passing the array of string URIs or the links that contain the self link to each individual member of the collection.

When retrieving embedded resources, if the client request does not specify that an Etag should be generated by using the generateEtags query parameter, the framework will set the parameter to false so that Etags will not be generated. For additional information, refer to the Working with Client-Side Caching (page 107) section.

To embed a resource, add the URI of the resource to the model. You can find the URI of the resource by using the LinkUtils class. To obtain an instance of LinkUtils, use the static LinkUtils.getLinkUtils() method, or resolve the global Nucleus component.

The LinkUtils class contains the following methods that can be used to find the resource’s URI:

Method Description

buildResourceUri Provides support for generating a URI for any resource for a given resource ID.

buildMemberUris Provides support for generating member URIs for collection resources.

selfLinkFromContext Provides a way to generate a self link based on the data in context. Normally this is invoked automatically by the framework and does not need to be invoked by an endpoint. However, if an endpoint needs a custom self link, it can call this method. Note: If a collection resource endpoint needs to respond with a singular resource representation, then the endpoint must invoke the overloaded version of the method selfLinkFromContext (true, singular ID) to generate the self link for the singular resource.

Understanding Sub-Resource Locators

Sub-resources, unlike resources, do not have a class level @Path annotation. They are invoked using sub- resource locator methods from their parent resource. For example, the CartRestResource class uses a sub- resource locator method that retrieves the CommerceItemRestSubresource. Sub-resource locator methods must have a @Path annotation and should not have a @httpMethods annotation. Locator methods must also contain a @SubresourceLocator annotation that contains the IDs of the sub-resources that can be returned by the method. If the sub-resource is globally scoped, the locator method should return an instance of the sub- resource. If the sub-resource is request-scoped, the locator method should return the class of the sub-resource.

The RestUtils class contains a static utility method that you can use to return the sub-resource. To do this, use the getResourceReference (String pResourceId) method, which calls into the getSubresource (String pSubresourceId) method in the current REST resource registry.

Note: If your sub-resource is composed of multiple classes or components, do not use the RestUtils.getResourceReference method. You can obtain the current registry using the RestUtils

76 4 Writing Resources and Endpoints static utility method getCurrentRegistry. Then the registry getSubresourceByEndpointId (String pEndpointId) method can be used where the endpoint ID is an endpoint in the specific class or component you want to return.

Adding Sub-Resources

When an endpoint response should include sub-resources, you can embed them in the RepresentationModel. For example, you could retrieve order resources along with commerce items as sub- resources. The framework allows you to include the embedded resource when it is provided in an endpoint method. Note that you can add both singular and collection resources.

You can add sub-resources by performing the following steps:

1. Identify the embedded resource ID that needs to be embedded into the response.

2. Identify the relation name that will be added to the response to hold the embedded resource. It is a good idea to use compact URIs (curies) that allows you to define a generic syntax for addressing your URI. For example, oc:commerceItems.

3. Use the LinkUtils.instance.buildResourceUri(…) to create the URI.

4. Add the URI when you build the RepresentationModel of the resource. The following is an example of an order with a sub-resource.

RepresentationModel model = new RepresentationModel.Builder() .state(order) // hold the commerce items in property name "oc:commerceItems" .embedded("oc:commerceItems", commerceItemsUri) .build();

Note: If a parent resource has access controls configured, its sub-resources will have the same configuration. If you use the RestResourceRegistry component in the Dynamo Server Admin to review security, it will display only the parent’s access, even though the sub-resource also uses the same access.

Working with URIs

Resources are registered with a REST resource registry that has a context root defined in the web.xml file. This context root takes the following format:

/context/version

The context is the root context of the Web application with the version number, which indicates the version number of the resource and provides tracking for backward compatibility. For example, a URI may be /public/ v1. The full URI would be http://localhost:8080/public/v1.

Code endpoint responses to work with URIs that are relative to the context root. For example, the URI would be /cart instead of /public/v1/cart.

Locating Collection URIs

When creating a URI to locate a collection resource, use the /resourceName convention. As described in the Before You Begin (page 73) section, resource names should be nouns, should follow a generic naming standard, and should start with a lower case letter. For example, the order resource URI might be /orders.

4 Writing Resources and Endpoints 77 Best Practices When Creating URIs

When creating a singular resource URI, it is best to follow the collectionResourceUri/resourceId convention, for example, /orders/01/items/c1, where the collectionResourceUri is the corresponding collection resource URI and that the resourceId identifies a resource within its collection.

An endpoint or resource class contains methods that provide operations that are specific for that resource. It is best to define the URI of the endpoint method in accordance with your resource naming standards. When you are writing endpoint/resource classes it is helpful to keep the following in mind:

• It is best if endpoint APIs are not dependent on a state.

• Root resource classes should be written using consistent naming conventions, such as XRestResource, where X is the singular name of the endpoint resource. For example, a singular name might be OrderRestResource. When a resource has endpoints across multiple classes, it is best if additional classes use the endpoints post-fix and should still be explanatory, such as OrderQuoteEndpoints.java.

• Sub-resource classes should use a RestSubresource post-fix, for example, CommerceItemRestSubresource.

• Endpoint classes will be easier to identify if they are written in their corresponding module. For example, the CurrentUserRestResource would be written in the DPS module.

• It is suggested that your endpoint and resource classes are contained in the X.restresources package where X is the name of any package. For example, the CurrentUserRestResource class would be defined in the atg.userprofiling.restresources package.

• Root resource classes should have a class-level @Path annotation with the resource name. Conversely, your sub-resource classes should not contain any path annotations. The following example is an order resource with a path annotation setting:

@Path("/orders") public class OrderRestResource { }

• Endpoints should be registered with the correct context/version REST resource registry and the resource components and classes should be placed in a restresources package.

Working with REST Resource Nucleus Components

The Web configuration for the API references a RestResourceRegistry component that is configured with all of the provider classes and components for the framework, and all of the resource classes and components for the API. On startup, this component scans all of the registered pieces and builds internal metadata objects for each resource and endpoint. It can be accessed using a Dynamo Server Admin interface that displays all of the endpoint information for the API. Note that if multiple context and/or versions are supported, each must have its own configured registry component.

Note: All resource classes must have a class level RestResource annotation to provide the ID of the resource. All sub-resource locator methods must have a method level subresourceLocator annotation to provide the IDs of the sub-resources that the method may return.

78 4 Writing Resources and Endpoints The registry uses four main classes to track resources. These classes are the ResourceHolder, ResourceSettings, SubresourceLocatorSettings and EndpointSettings classes. ResourceHolders contain all of the information for a single resource. It is a container of a set of ResourceSettings. The ResourceSettings object represents a single resource class or component, and is a container for one or more EndpointSettings. The EndpointSettings represents a single endpoint method and contains all of its information. The following is an example of a portion of a RestResourceRegistry.properties file:

providerClassNames=\ atg.service.jaxrs.JAXRSContextPreMatchRequestFilter,\ atg.service.jaxrs.JAXRSContextPostMatchRequestFilter

nucleusProviders=\ GenericExceptionMapper,\ JSONMessageBodyReader,\ JSONMessageBodyWriter,\ OracleJSONMessageBodyWriter,\ NotFoundExceptionMapper,\ CachePostMatchRequestFilter,\ CacheResponseFilter,\ CacheWriterInterceptor,\ hal/HALMessageBodyReader,\ hal/HALMessageBodyWriter,\ InvocationHandlerBinder,\ RestExceptionMapper

#restResourceClasses=

nucleusRestResources=\ /atg/dynamo/service/jaxrs/restresources/MetadataCatalogRestSubresource,\ /atg/dynamo/service/jaxrs/restresources/VersionRestResource/atg/jaxrs/test/ TestRootEndpoints

Registering Nucleus Resources

The RestResourceRegistry can also register a Nucleus REST resource with Jersey. To register a Nucleus component, you must add it to the RestResourceRegistry.properties file. For example:

nucleusRestResources=\ /atg/jaxrs/mysite/MyNewNucleusEndpoints,\

REST resources can be either a global or a request-scoped Nucleus or non-Nucleus component. REST resource classes can be registered as a request or singleton-scoped. Note that singleton classes and globally-scoped components have some JAX-RS annotation limits. Refer to the Jersey documentation for additional information.

By default, all resources are global Nucleus components.

How to Register a Nucleus REST Resource

Perform the following steps to register a REST resource:

1. Create your Nucleus endpoint class.

2. Register the Nucleus endpoint with the RestResourceRegistry. For example:

4 Writing Resources and Endpoints 79 RestResourceRegistry.properties nucleusRestResources=/atg/mycodearea/restresources/MyNucleusRestResource

3. Ensure that the endpoint is defined as a global request. For example:

NucleusRestResource.properties $class=atg.jaxrs.sample.NucleusRestResource $classloader=/atg/dynamo/service/jaxrs/JerseyClassLoaderService loggingDebug=true injected=testInjectedString

Resolving a Non-Nucleus Component in the Endpoint or Resource Class

Should a resource class need to reference other Nucleus components, the framework provides the @NucleusComponent annotation. This annotation resolves the component and allows you to inject it as a value for the field. This annotation should only be used when a REST resource class is not itself a Nucleus component. It is recommended that any resource that needs a reference to another Nucleus component should itself be a Nucleus component with the reference a standard Nucleus property of the resource component.

The following steps describe how to resolve a non-Nucleus component:

1. Identify the global or request scope that should be resolved in the endpoint or resource.

2. Use the @NucleusComponent annotation to resolve the component. Place the annotation on the line preceding the variable definition. Note: It is best not use the @NucleusComponent annotation to resolve session-scope components in an endpoint or resource class.

Extending the Framework

Most of the framework providers are Nucleus components and can be replaced or extended. Because all providers are registered with the RestResourceRegistry, they can be configured. The default media type support is for the Oracle JSON media type and the HAL media type. You can introduce new media types by creating an additional message body reader and writer. You can create custom lock key provider logic if a resource implements the LockKeyProvider interface. By default the CachePostMatchRequestFilter component is configured with two RestRequestValidator components, one for XSS checks and one for asset locale checks. Additional validators can be configured for any custom request checking that you might need.

Because resources are Nucleus components, you can easily replace or extend them using configuration layering.

Working with Resource Metadata

Resource metadata contains information about the resource that is not specific to a particular representation. This data is important when building a dynamic UI using REST resources or when binding UI components to REST endpoints. All endpoint methods should be defined with proper metadata information.

Metadata can be retrieved by a request to the context, for example, /public, or for a specific version, for example, /public/{version}. Metadata for all resource can be retrieved by a request to /metadata- catalog, for example, /public/v2/metadata-catalog. Metadata for an individual resource can be retrieved by a request to /metadata-catalog/{resource name}, where the resource name is a simple dot-notated

80 4 Writing Resources and Endpoints name of the resource that matches the URI, but without any templated parts, for example, /metadata- catalog/cart or /metadata-catalog/orders.commerceItems.

JSON schema for the resource can be retrieved by the same request to /metadata-catalog/{resource name} but for media type application/schema+json. This JSON schema is built based on the internal swagger model.

Note: When creating endpoints, it is best if they do not depend on specific media types. This prevents you from specifying a Media Type annotation in your endpoint.

Annotating Resource Classes

Use the following annotations when creating resource classes:

• @Path – When you create a root resource, you must provide the @Path annotation. The annotation contains the URI path for the resource. For example, @path ("/cart"). Note: If you are creating a sub-resource, ensure that there is no @Path annotation.

• @RestResource – The @RestResource must be present for all resource classes, as it specifies the ID of the resource. The ID is a string that uniquely identifies the resource and does not change when the context and/or version change.

Annotating Endpoint Methods

You can use the @Endpoint annotation to annotate resource methods and configure the various setting for the endpoint, such as transactions, security, and cache.

Use the following annotations when creating an endpoint method:

• @Path - When creating an endpoint method, use the @Path annotation if there are additional path elements beyond the resource path or the sub-resource methods. The annotation is not required if the path is empty.

• @GET, @POST, @PUT, @PATCH, and, @DELETE – These annotations are used as necessary when working with the endpoint.

• @Endpoint – This annotation identifies the endpoint with a unique string ID. The ID does not change if the context or version changes. If the endpoint is for a singular resource, the isSingular attribute must be true.

Naming Endpoint Annotations

When you define an ID in a @Endpoint annotation, it is best to name it as a combination of the resource URI and the method request type. For example, a product resource might be:

@Endpoint(id="/products/{productId}#GET, isSingular = true)

Ordering Endpoint Annotations

When creating an endpoint, it is best to be consistent with the order of the annotations. For example:

@GET @Path("/{productId}") @Endpoint(id="/products/{productId}#GET", isSingular = true)

4 Writing Resources and Endpoints 81 The following is an example of the metadata definitions of login endpoints of the CurrentUserRestResource:

@POST @Endpoint(id = "/loginId", isSingular = true) public Object login(JSONObject pJSON) throws RestException {}

Returning Hypermedia Endpoint Methods

This REST framework supports the application/json media type in the Content-Type of the requestor request header. The Oracle media type, defined as application/vnd.oracle.resource+json and the HAL media type, defined as application/hal+json are also supported.

The endpoint method should be public, and if the endpoint response is a representation of the resource, the return type should be RepresentationModel. The model holds the data needed to support hypermedia formats. It includes properties, links, the representation state and any embedded resources URI that should be included in the response.

Note: In some cases, the endpoint method may return only the status code. If this is the case, you should use the javax.ws.rs.core.Response class that has the javax.ws.rs.core.Response.Status enum to set and return the proper status code.

Naming Fields

When creating names for fields, adhere to the naming conventions you created as referenced in the Before You Begin (page 73) section. When naming fields, consider to the following:

• The primary identifier field should have the Id or id name suffix.

• Path parameters or query parameters should be written next. For example:

@PathParam("id") final String pId @QueryParam("catalogId") final String pCatalogId

• Fields in a Boolean domain should have a flag suffix.

• A field that indicates a user action should have a By suffix, such as lastUpdatedBy.

Representing Resources

An endpoint should return an instance of a RepresentationModel if the response is a representation of the resource. You can obtain an instance of a RepresentationModel by using the build method of a RepresentationModel.Builder instance. The RepresentationModel.Builder method begins a RepresentationModel.Builder instance. The following builder methods are available:

State Builder Method

The state(Object pState) bean or dynamic bean holds the current state of the resource, for example a repository item or an Order bean. This object is filtered and rendered by the framework into the media type, and can be null, although it would normally be null only for collection resources.

82 4 Writing Resources and Endpoints Properties Builder Methods

The property or properties method allows you to add metadata properties for the resource to the response. The format for these methods should be property(String pkey, String pValue) or properties(Map pProperties).

Links Builder Method

The links method allows additional links to be specified for the resource. Generally, an endpoint will not need to do this, since all standard HATEOAS links are automatically added. However, you may occasionally want to add additional links to an endpoint, for example, to endpoints outside of the current resource.

Use the format links(Links… pLinks) when using this method.

Note: A link URI appearing in a response should use an absolute path or the full path. However, it is best when coding resources to use relative URIs and allow the framework to turn it into an absolute URI.

Self Builder Methods

Although not generally required by an endpoint, the self method allows you to specify a self link. You may want to identify a custom self link or an endpoint may build a representation for a resource that is not currently in context. Use the format self(Link pSelf) when using this method.

The self(String pSelfUri) method takes the URI of the self link.

Exclude Link Relation Builder Method

The excludeLinkRelation method allows an endpoint to specifically exclude an automatically generated link from the response. Use the format excludeLinkRelation(String… pLinkRelations) when using this method.

Embedded Builder Method

The embedded method allows you to add the URI of any resource that should be embedded in the response. For example, the commerce item resource may embed a product resource URI. The framework retrieves the embedded resource if it is not filtered out. Use the format embedded(String pRel, String… pURIs) when using this method.

An embedded URI can be created using the LinkUtils.instance().buildResourceUri method.

Members Builder Method

An endpoint that returns a collection resource representation should use the members method to set the members of the collection. Use the format members(String… pMemberURIs) when using this method. Member URIs can be created using the LinkUtils.instance().buildMemberUri method.

Resource Type Builder Method

The ResourceType method allows you to specify if the RepresentationModel is for a collection or a singular resource. Use the format resourceType (ResourceType pResourceType) when using this method.

Override Filter ID Builder Method

The overrideFilterId method allows you to set up an endpoint that specifies the filter ID to use when rendering this RepresentationModel. By default, the framework uses filter ID associated with the @Endpoint

4 Writing Resources and Endpoints 83 annotation of the endpoint method. Use the format overrideFilterId(String pOverrideFilterId) format when using this method.

Status Builder Methods

By default, a RepresentationModel response uses a 200 (OK) status code. However, you may want to respond with a different status code at times. For example, creating a new resource using a POST endpoint method would require responding with a 201 (CREATED) status and should include a LOCATION header with a URI to the new resource. An endpoint may also respond with a 202 (ACCEPTED) status code.

Use the format status(int pStatus), created(URI pLocation) or accepted when using these methods.

Header Builder Methods

A response can also include additional headers, which have specific methods that support the CONTENT_LANGUAGE and LOCATION headers. Use the format header(String pName, Object pHeader), language(Locale pLanguage) or location(URI pLocation) when using these methods.

Additional State Builder Method

You can add secondary state objects to the response with the additionalState method. Use the format additionalState (String pKey, Object pState) when using this method.

Language Builder Method

This method sets the language header for the specified locale. Use the format language (Locale pLanguage) when using this method.

Location Builder Method

This method allows you to add a location header for the given URI. Use the format location (Locale plocation) when using this method.

Listing Response Builder Method

You can allow pagination links and properties to be included when getting a response for a collection resource by setting the listingResponse method. Use the format listingResponse (ListingResponse pListingResponse) when using this method.

Version Builder Method

At times, it may be necessary to explicitly set the version of a resource. Use the version method for this. Use the format version (int pVersion) when using this method.

Working with Links

One of the benefits of providing users with REST resources is that the client does not need to have prior knowledge of the links other than the initial URI. Instead, the client only has to know about the links provided by the server to navigate from one resource to another. With the exception of the context root resource, all resources should be accessible through different resources.

84 4 Writing Resources and Endpoints When you create a resource, it should always contain a link to itself. This current resource link is known as the self link, which determines how to access the resource. It is best to use canonical links for a resource, which are added by default.

Links should consist of a link relation name, a URL and any other optional attributes. Links for every endpoint in the resource are automatically generated for representation responses. The link uses a linkRelation that you can define using the @Endpoint annotation linkRelation attribute. If an attribute is not specified, the system automatically generates a link relation from the endpoint method’s name. For example, the link relation for a SubmitOrder endpoint might be:

@Endpoint(linkRelation="SubmitOrder")

By adding a self link, you ensure that relative links can be resolved and that responses from the client can be returned to the server.

The selfLinkFromContext method of the LinkUtils provides a way to generate a self link based on the data in context. If an endpoint needs a custom self link, it can call this method. Refer to the Customizing Self Links (page 87) section for additional information.

Understanding Link Relations

Links and embedded resources are keyed by a relation name. Link relations are descriptive attributes that define the type of link, or the relationship between the source and destination resources, for example a self link. If a standard relation name is not appropriate, a URI is used for the relation name. The relations registry allows for Compact URI (CURIE) support where a prefix can be configured to reference a URI. The relation name then becomes a concatenation of this prefix with a shortened name. By default, the CURIE prefix is configured in the registry as oc=/rels{rel} and is used if no other prefix is explicitly provided when a relation name is specified. For example, oc:checkout would resolve the relation name /rels/checkout. Standardized link relations are a foundation of HATEOAS, as they allow the user to understand the meaning of the available state transitions in a REST system.

A global standard set of link relations can be found at www.iana.org/assignments/link-relations/link- relations.xml. For additional information on link relations, refer to the Using Links with HATEOAS (page 88) section.

Link relations, though defined in multiple endpoints of a resource, are aggregated at the resource level. When an endpoint method is invoked, the response includes the links of other endpoints of that resource. The following is an example of a resource where a linkRelation attribute is specified for the endpoints SubmitOrder and getOrder:

The request is made for getOrder endpoint. @Path("/orders") public class OrderRestResource {

@POST @Path(/{orderId}/submitOrder) @Endpoint(id="/orders/{orderId}/submitOrder#POST", linkRelation="submitOrder") public Object submitOrder(@PathParam("orderId") pOrderId, JSONObject pOrderJSON) { }

@GET

4 Writing Resources and Endpoints 85 @Path(/{orderId}) @Endpoint(id="/orders/{orderId}#GET", linkRelation="getOrder") public Object getOrder(@PathParam("orderId") pOrderId) { } } Request http://localhost:9080/public/v1/orders/o12345 Method: GET

Response: { links :[ {"rel ": "self", "href": "/orders/o12345"}, {"rel ": "submitOrder", "href": "/orders/o12345/submitOrder"} ] }

Note that any link relation names that are not in the default set should define themselves using a URI and should be described as part of your documentation. Use the RelationsRegistry component, which holds the definitions for the link relations, to define any new link relations:

$class=atg.service.jaxrs.RelationsRegistry $classloader=/atg/dynamo/service/jaxrs/JerseyClassLoaderService relationDefinitions=\ oc=/rels/{rel}

For example, if you use a non-standard link, such as SubmitOrder, you can use the relationDefinitions property of the RelationsRegistry component to add the new definition. The following example shows how the oc relation definition is added to the RelationsRegistry:

relationDefinitions=\ oc=/rels/{rel}

When building the RepresentationModel, prefix the relation name with the relation definition key oc. The link will be expanded by the message body writer. For example:

RepresentationModel model = new RepresentationModel.Builder().state(order). links(Link.fromPath("/order/o12345").rel("oc:submitOrder"));

The message body writers parse relation names and expand the definition while writing the JSON response for an Oracle JSON media type, so the output would be:

{ links :[ { "rel" : "public/v1/rels/submitOrder", "href": "/orders/012345" }]}

When using a HAL response, the link is left in compact form, with a separate section output in the response.

86 4 Writing Resources and Endpoints Customizing Self Links

If an endpoint needs a custom self link, use the selfLinkFromContext method. This generates a self link based on the context. If a collection resource endpoint needs to respond with a singular resource representation, then the endpoint must invoke the overloaded version of the method selfLinkFromContext(true,singular ID) to generate the self link for the singular resource.

Note: If you use a link that is not standard, you must have a URI pointing to the self link.

Automatically Adding Endpoint Links

By default, the link relation name used for another endpoint is the endpoint method name. The @Endpoint annotation contains the linkRelation attribute. If this attribute is set on any endpoint, the link is automatically generated for the endpoint and added to the response model. For example, to generate a link automatically for SubmitOrder you could configure the following:

@Endpoint (linkRelation="SubmitOrder")

As such, the JSON presentation would be:

{ "id" : "user1234", "name" : "John Doe" }

Excluding Links in the Response

You can remove links from the response by either excluding or filtering the link. Exclude Link Relations

While building the RepresentationModel object, you can specify which relations should be excluded from the response. The following example excludes the self and submitMyOrder links:

RepresentationModel model = new RepresentationModel.Builder().state(order). excludeLinkRelation("self","submitMyOrder");

Filter Links

You can implement the LinkFilter in a resource class to remove links that are not required in the response. The endpoint implements this interface by overriding the filterLinks method.

For example:

@Path("/test/orders") public class OrderRESTResource implements LinkFilter { @Override public void filterLinks(RepresentationModel pModel) { Link[] links = // Links not to be included pModel.removeLinks(links); } }

4 Writing Resources and Endpoints 87 Using Links with HATEOAS

Hypermedia as the Engine of Application State (HATEOAS) enables a client to interact with a network application through hypermedia that is provided dynamically by an application server. A REST client, who enters through a fixed URL, can take actions that are discovered within a resource representation that is returned from the server. Media types are standardized and there are a standard set of IANA link relations that can be included by the resource. Additionally, a response can include resource-specific link relations as URIs that are not included within the IANA standard. The REST client transitions through these application states by selecting from the links within the representation. For example, these are a few of the standard links that are available within a response: self, next, previous, first and last.

With all resource types, the self link is added to the response. For example:

{"rel":"self", "href":"http://localhost:8380/public/v1/test/orders"}

If an endpoint responds with a ReprentationModel, the framework will automatically add links to the response. These links will include a self link for the request, as well as links for other endpoints in that resource.

Understanding Collection Resources

Collection resources that return a representation of each member of a collection might create performance problems. Therefore, the framework provides a mechanism to call the singular resource directly, based on the URI, for every member of a collection. This allows you to retrieve a representation without needing to call the singular resource for each member of a collection. You can pass an array of the strings that represent the URI path to each individual member of the collection by using the members method. Or, you can pass an array of Jersey link objects that contain the self link to each individual member of the collection.

You can retrieve a static instance of the LinkUtils component by using the getLinksUtils() method. Use the buildMemeberUris method to generate member URIs for collection resources and the buildResourceUri method to generate a URI for any resource with a given resource ID.

The embedded tag of the payload schema determines if the embedded members are included in the output. Refer to the Validating Input and Filtering Output (page 95) section for additional information on the payload schema used for collection resources.

Note: If a collection resource endpoint responds with a singular resource representation model, the endpoint must generate a self link for the model using the selfLinkFromContext (true, singular ID) method of LinkUtils.

Should you require a collection resource endpoint that uses query parameters, you can configure your custom endpoint to support the q query parameter. The value of the q query parameter should be an RQL query string that can be applied to the resource. For example:

/public/v1/skus?q=margin>1.0

The collection endpoint can use the ListingRequestUtils class to construct a listing request from query parameters. Use the executeItemQuery method to invoke the q query parameter and return a valid listing response for the collection. For example:

88 4 Writing Resources and Endpoints ListingResponse response; try { response = ListingRequestUtils.executeItemQuery( LinkUtils.instance().getCurrentQueryParameters(), getCatalogTools().getCatalog().getItemDescriptor("sku"), "id");

} catch (Exception e) { throw RestUtils.createException("Failed to query for skus", e); }

Configuring Pagination for Collection Resources

Most collection resources support pagination. The client can specify the start index, the start page size, and sorting query parameters. The framework uses the endpoint defaults if the client does not specify these parameters. The response also includes the standard prev, next , first and last relation links to retrieve the page before or after the requested page.

A client may also request a collection and pass in the getForUpdate=true query parameter. The response then includes the full collection of items that belong to the request page as well as all of the other items, which are represented by their IDs. Subsequent PATCH calls for the collection can then pass in those IDs for the elements that should not be updated.

Working with Pagination Framework Support

Collection resource endpoint pagination uses the following classes:

• ListingRequest – Contains pagination properties to specify the page of items to be retrieved by the server. This is usually configured based on the client request query parameters.

• ListingResponse – This class contains the collection of items and the pagination properties related to the specific page results to be used to generate the response. This is created with a combination of the listing request and the retrieval of the items for the response.

• ListingRequestUtils – This class contains a queryParamsToListingRequest utility method that generates a listing request based on the client query parameters. It also includes a method to support query- based pagination.

Collection endpoints typically:

• Call the queryParamsToListingRequest method to generate an initial ListingRequest instance.

• Retrieve a page of items for the collection. The page size and offset definitions are based on the listing request properties.

• Create an instance of a ListingResponse by calling the ListingResonse(ListingRequest) constructor and setting any related property values.

Use the listingResponse representation model building method to provide the listing response to the RepresentationModel. By doing this, the framework message body writer automatically generates the expected pagination links and properties for the response.

The collection resource representation for the response can include additional paging links. The response may include the following paging properties:

4 Writing Resources and Endpoints 89 • next – Displays the next page.

• prev – Displays the previous page.

• first – Displays the first page.

• last – Displays the last page.

• count – The number of items in the response. This matches the limit query parameter value provided by the client; however, in certain cases it may not match, for example if the limit value is greater than the number of items to be returned.

• hasMore – This Boolean value is true if there are more pages in the collection after the current page. Note: If the media type of the response is Oracle JSON, this property cannot be filtered from a paging response.

The LinkUtils class provides the utility methods to generate the links based upon the listing response, and is invoked automatically by the message body writers. In addition to links, the following query parameters may be specified:

• totalResults – The total number of items in the collection. Note: If the media type of the response is Oracle JSON and the client specifies the totalResults=true query parameter for the request, this property cannot be filtered out of the response.

• limit – The actual page size used by the server. This matches the limit query parameter value provided by the client; however, in certain cases it may not match, for example, if the client limit exceeds the server’s maximum limit.

• offset – The page 0-based index into the collection used for the response.

• getForUpdate – If set to true, the response also includes the ID fields for all of the elements in the collection.

• orderBy – The name of the field to sort by. A post fix of asc or desc indicates the direction, for example, orderBy=price:asc would display the price field in ascending order.

Note that with the exception of the totalResults and the hasMore properties, these properties can be filtered out of the response.

For example:

links: [ {"rel": "next", "href":"http://localhost:8380/public/v1/test/orders?offset=4&limit=2"}, {"rel": "prev", "href": "http://localhost:8380/public/v1/test/orders?offset=2&limit=2"}, {"rel": "first","href": "http://localhost:8380/public/v1/test/orders?offset=0&limit=2"}, {"rel": "last", "href": "http://localhost:8380/public/v1/test/orders?offset=8&limit=2"} ]

Configuring Query-Based Pagination

A resource can support the client retrieving collection items one page at a time. The number of items to return in the response determines the size limit of the page. Client requests can use a q query parameter, the value of which is an RQL query string that is applicable to a collection resource. The ListingRequestUtils contains

90 4 Writing Resources and Endpoints the executeItemQuery utility method used by a collection resource endpoint to generate a listing response based on a query.

If a collection endpoint uses the executeItemQuery method, the endpoint does not need to create its own listing request or response. However, the listing response generated by the executeItemQuery must still be added to the RepresentationModel.

For example:

// Execute an rql query based on the 'q' query parameter value to return // skus ListingResponse response; try { response = ListingRequestUtils.executeItemQuery( LinkUtils.instance().getCurrentQueryParameters(), getCatalogTools().getCatalog().getItemDescriptor("sku"), "id");

} catch (Exception e) { throw RestUtils.createException("Failed to query for skus", e); }

A client can provide offset and limit query parameters that specifies the offset and size limit of the page. In addition, if the client wants the total number of items in the collection to be included in the response, the client can specify totalResults=true as a query parameter.

Running Methods Before or After Endpoints

Resource classes can specify methods to be run before or after an endpoint method is invoked, allowing you to add custom code before or after the endpoint method.

Invoking a Method Before an Endpoint

To invoke a method before an endpoint method, annotate it with the @PreAction annotation. The value parameter of the annotation is the endpoint method name. This method should use the same parameters as the endpoint method.

For example:

@PreAction("addItems") public void preAddItems(JSONObject pInputData) throws RestException { // pre endpoint logic }

@POST @Endpoint(id="/{commerceItems}/#POST", validatorId="commerceitems.add", filterId="commerceitems-CollectionDefault", updateTarget=true) public RepresentationModel addItems(JSONObject pInputData) throws RestException { // endpoint logic

4 Writing Resources and Endpoints 91 }

Working with Transactions

The @Endpoint annotation contains the isTransactional method that can identify endpoints that require a transaction. The framework supports the @preAction and @postAction annotations. A method that is annotated with the @preAction annotation is invoked by the framework immediately prior to invoking the endpoint itself. A method that is annotated with the @postAction annotation is invoked by the framework immediately after invoking the endpoint.

By default, the framework wraps any endpoint method invocation in its own transaction. Any preAction or postAction methods or validation also takes place inside this transaction. Automatic transactions can be disabled by setting the @Endpoint annotation isTransactional to false.

Note: It is best to use global resource components, which are resolved upon server start up and reused rather than being resolved for every request. You can use request-scoped resource components, unless the resource is a parent resource that contains sub-resources.

You can also add transaction support and protection against concurrent updates for your endpoint resources by using the isTransactional flag in the @Endpoint annotation to create a new transaction for a resource. The flag is set to true by default.

The invoke method of the RestEndpointInvocationHandler class checks for the value true for this annotation on the target endpoint and, if found, wraps the endpoint invocation in a new transaction. For endpoints that are called asynchronously, use the JAXRSEndpointWorker class, which configures the new thread. You can subclass the JAXRSEndpointWorker class and implement your logic in the doAction method. For information on this class, refer to the ATG Platform API Reference

Invoking a Method After an Endpoint

Use the @PostAction annotation to invoke a method after an endpoint method. The value parameter of the annotation is the endpoint method’s name. This method should use the same parameters as the endpoint method, as well as use an extra parameter that matches the return type of the endpoint method. This ensures that the endpoint response can be passed into the post action method. The post action should return the response object again, following any modifications to the response:

For example:

@POST @Endpoint(id="/{commerceItems}/#POST", validatorId="commerceitems.add", filterId="commerceitems-CollectionDefault", updateTarget=true) public RepresentationModel addItems(JSONObject pInputData) throws RestException { // endpoint logic }

@PostAction("addItems") public RepresentationModel afterAddItems(JSONObject pInputData, RepresentationModel pRepresentationModel) throws RestException { // post endpoint logic

return pRepresentationModel; }

92 4 Writing Resources and Endpoints Enabling Locking

By default, the framework tries to acquire a lock from the client lock manager for a resource before processing a request. If the request is a GET request, only a READ lock is acquired; otherwise a WRITE lock is acquired. By default, the lock key is the request URI for the root resource of the request. For example, if the request was / orders/o12345/commerceItems, the framework locks on order /orders/o12345. You can create your own lock key provider component for custom locking behavior using the @Endpoint annotation lockType attribute by setting it to READ, WRITE or NONE. By default, the lock uses the current request URI string as the lock key.

You can turn global locking on or off by using the enabled property of the RestLockService to make associated autolock properties mark all operations as requiring locks. When autolocking is enabled, those endpoints that do not have a lockType annotation are assigned a lock type based on their HTTP method. The RestLockService is enabled by default.

The @Endpoint annotation uses the lockType property to define the lock type as read or write. The RestLockService uses the autolock property that assigns endpoints with no lockType defined to a lock type based on their HTPP method.

The LockKeyProvider allows you to provide the key used in locking by implementing the getLockKey method. For example:

public interface LockKeyProvider { /** * Get the lock key * @param pRestContextTypically RestContext for the current request * @return the lock key */ public Serializable getLockKey(RestContext pRestContext); }

The following is an example of implementing a lock mechanism using your own lock key. Root resources should implement an interface such as this when locking is required during read/write operations on the resource itself or any of its sub-resources. The following example shows how you determine what keys are used as locks. Note that by default the LockKeyProvider uses the current request URI string as the lock key:

@Path("/SomeResources") public class SomeResourceRestResource implements LockKeyProvider { ...

@Path("/{id}") @GET @Endpoint(lockType="READ") public RepresentationModel defaultGet(@PathParam("id") String pId){ ... }

@Override public Serializable getLockKey(RestContext pRestContext) { // This implementation will use the ID of the resource // present in the request path param as the Lock Key // Note - in this particular example all requests to // Endpoints that require locking must set this path param MultivaluedMap info = pRestContext.getRequestContext().getUriInfo().getPathParameters(); List idList = info.get("id");

4 Writing Resources and Endpoints 93 String id = idList.get(0); return (Serializable) id; } }

Handling Exceptions

Endpoint resource exceptions are handled as a RestException. A RestException class can be instantiated through utility methods in RestUtils, allowing an endpoint to specify a response status code with an error. Exceptions are automatically rendered by the framework output producer into the correct format before returning back to the client. The RestExceptionMapper instance of the Jersey ExceptionMapper builds a response from the RestException that is returned to the client.

If you add error conditions to your endpoint, you should build a RestException, setting HTTP response codes, error messages, debug information and, optionally, error codes that are returned from your endpoint method.

The framework can also handle other types of exception thrown by endpoint methods. It wraps the exceptions and converts them into RestExceptions. Every REST method should be constructed with an error message, which should be stored as resource strings in a property file residing in your custom module. Once you have constructed an error message, you can create string constants that refer to the error string keys within your endpoint class. Additionally, you can refer to a new constant class if the String constants are shared with multiple endpoints. For example:

protected static final String ERROR_INVALID_DATE_TIME = "noProfileRequestToCreateProfile" // Use the existing resource bundle utility if it is available or create the new // resource bundle utility if it is not there. // Example: An excerpt from ProfileServiceUtils class

public final static String RESOURCE_BUNDLE_NAME = "atg.mybundle.BundleResources";

/** Resource bundle **/ public static java.util.ResourceBundle sResourceBundle = ResourceUtils.getBundle(RESOURCE_BUNDLE_NAME, java.util.Locale.getDefault());

public static String getStringResource(String pResource) throws MissingResourceException { String ret = ResourceUtils.getMsgResource (pResource, RESOURCE_BUNDLE_NAME, sResourceBundle); }

public static String getMessage(String pString, Object[] pArgs) { return MessageFormat.format(pString, pArgs); }

To define a custom response code with a particular exception type, add a response code with an exception- type HTTP response code in the RestExceptionRegistry class.

94 4 Writing Resources and Endpoints Validating Input and Filtering Output

A resource’s schema is controlled using the ValidatorManager component and payloadSchema.xml files. These XML files configure multiple validators that contain the definitions for expected input fields, as well as required output fields. Endpoints can specify which validator definition to use for input, using the validatorId attribute, and for output, using the filterId attribute.

For additional information on using the filter ID, refer to the Associating a Filter with an Endpoint (page 99) section. Endpoints can be configured with the RepresentationModel to be more dynamic by overriding these values at run time, as described in Override Filter ID Builder Method (page 83).

Validating Input

The ValidatorService provides the link between the REST framework and the validator framework. You can invoke the ValidatorService directly by using the invokeValidator method or by using the methods available in the RestUtils class.

If the endpoint has been annotated with isValidatedByFramework=true, then the REST framework invokes the ValidationService using the invokeValidator method. For example:

/** * Main entry point for validating an input object when * wanting to allow the framework to control selection of * validator, target bean, type of update etc. * @param pInputObject object to validate */ public void invokeValidator(Object pInputObject)

The service tries to obtain the validator to use for a particular object by obtaining the validatorId endpoint setting from the RestContext.

The ValidationService provides access to the validator framework for the validation of incoming JSON JAX- RS messages and, optionally, the updating of target beans or repository items.

Whenever a PUT, POST or Patch operation occurs, its input is run through a validator service. The rules for this validation are configured using the payload schema XML file. Validation can be performed automatically by the framework or can be done manually using the endpoint. Validators are associated with an endpoint by using the validatorId endpoint annotation, which references the unique ID associated with a schema in the validation XML file. If validation fails, a 400 BAD_REQUEST response is returned to the client along with details of the property or properties whose values are invalid.

For additional information on the payload schema, refer to the Working with the Payload Schema (page 121) section.

Configuring Automatic Validation

The ValidatorManager manages the validation of property values and maintains a Hashtable for the creating and updating of mapping from a property name to a validator. It also provides code to update one dynamic bean from another, enabling a way of going from input endpoint JSON to updating objects.

Validation is automatically performed for any update request by the ValidatorManager component using the defined schema for the endpoint. In addition to rejecting invalid input, the validation process also determines any sets of changes that the endpoint may need to apply, and can pre-populate target beans directly with the

4 Writing Resources and Endpoints 95 input values. The validation process first tries to GET the latest version of the resource. While validating against the schema, the validation process can also update the resource with the values taken from the input. For collection resources, elements are matched against the input by comparing ID fields.

If you want validation to occur automatically, your endpoints must specify a validatorId endpoint annotation. If you do not want the framework to validate an endpoint, change the isValidatedByFramework endpoint annotation from its default to false. The automatic update of the target beans by the validation process can be disabled using the @Endpoint annotation updateTarget attribute. RestUtils also has a method that you can use to manually invoke the validation process if automatic validation has been disabled for an endpoint. For additional information on validation, refer to the Working with the Payload Schema (page 121) section.

Configuring Manual Validation

You can manually handle input validation by using the validateInputObject utility method that is available in RestUtils.

The payload schema framework can also provide additional support for an endpoint, depending on the endpoint type. For example, an endpoint can create a new resource or update an existing resource. If the message validates successfully, then a requestUpdateInfo property is populated on the current RestContext.

Use the endpoint annotation to assign a validator to a specific endpoint.

public @interface Endpoint { ... String validatorId() default NULL_STRING; ... }

This allows a validator to be associated to an endpoint:

@Endpoint(id="test.addorders.orderId", validatorId="type.id.addItem") public RepresentationModel defaultGet(@PathParam("orderId") String pOrderId){

Working with Endpoints that Create Resources

For endpoints that create resources, the ResourceUpdateInfo, which is available using the RestUtils.getRestUtils().getResourceUpdateInfo() method, can provide validated input in the form of a map or an actual instance of the bean. Additionally, you can use the getUpdates() method to get the actual single item to be created.

If getUpdates is set to true, the framework tries to create an instance of the bean or repository item defined by the validator. The factory attribute can identify a Nucleus component or Java class that can create an instance of the target class. This may be required where the target instance requires initialization before it can be used. The Java class referenced by the factory attribute must implement the atg.service.validator.BeanInstanceFactory interface. For example:

...

96 4 Writing Resources and Endpoints If getUpdates is set to false, the ResourceUpdateInfo contains the validated input in the form of a java.utl.Map, which may be more convenient for the endpoint than working with the raw org.json.JSONObject. However the raw org.json.JSONObject is still available from the RestContext.inputJson property.

Working with Endpoints that Update Resources

For endpoints that update existing resources, the framework can validate and then apply incoming changes to the target bean.

Use the getMembersUpdateInfos() method of the ResourceUpdateInfo object to get information on the updated for a collection. Use the getTarget method of the ResourceUpdateInfo object to get information on the update of a single resource.

For detailed information on validation, refer to the Working with the Payload Schema (page 121) section.

Reusing Validators

Both schema and bean-property properties allow the validators to be reused with the use-validator-id attribute. When this attribute is specified, the validator code retrieves the properties and bean-properties of the referred validator. The filtering code must inspect the schema and bean-property for the use-validator-id and, if populated, retrieve the properties and bean properties from that validator.

For example:

Validating Collections

Validators can be configured for beans and bean properties. To do this, set the treat-container-as-bean attribute of the schema and bean-property properties. The key/value pairs of the map are written to the output according to the schema and bean-property configuration, which will refer to the map keys.

Note: There may be errors upon startup of the ValidatorRegstry component since Map has neither description nor quantity properties.

The following is an example of using the treat-container-as-bean attribute:

For additional information on the treat-container-as-bean attribute, refer to the Working with the Payload Schema (page 121) section.

4 Writing Resources and Endpoints 97 Use the pseudo-property value when you do not want a map to be treated as a dynamic bean. This configuration is applied to all values of the map when producing output:

When working with collections, use the element pseudo-property. The configuration is applied to all elements of the collection when producing output:

If the value or element pseudo-property is not specific but the output code detects a map or collection, the framework attempts to apply the schema or bean-property configuration to all of the values or elements of the collection.

Configuring Timestamps

By default, timestamp properties returned in output are configured as Long. You can create a custom instance of a PropertyCustomizer that converts the Long format to a formatted date using the request locale. For example:

Filtering Output

Filtering allows you to determine the output that is displayed from a resource. This allows you to control the fields and links in the response from a resource, as well as enable clients to have similar controls from the request by creating filters. Filters also provide support for custom properties and data-type extensions.

You filter a resource by using the payload schema XML, which is described in detail in the Working with the Payload Schema (page 121) section.

The validation schema can filter a resource by any of the following steps:

• Using the filterId property of the @Endpoint annotation, which is described in Associating a Filter with an Endpoint (page 99)

• Setting the overrideFilterId property on the RepresentationModel, which is described in Override Filter ID Builder Method (page 83)

98 4 Writing Resources and Endpoints • Setting the useFilterId query parameter, which is described in Using Query Parameters (page 103)

Using the Payload Schema XML

Definitions for filtering are contained within a single XML file located at /atg/dynamo/service/ validator/payloadschema.xml. You can access the PayloadSchemaRegistry component using the Dynamo Server Admin. The following is an example of a payload schema for the default API order summary:

The attributes and elements that you use to set up filtering are described in the Working with the Payload Schema (page 121) section.

Associating a Filter with an Endpoint

The @Endpoint annotation has a filterId property that defines which filter to use during output. Endpoints that output data should have a filterId defined or an exception will be thrown.

Note: Assigning a filter to an endpoint is not required, as there are additional methods that you can use to set a filter for an endpoint; however, it is best if you provide a filterId for each endpoint so that there is always a default ID. If a filterId is not defined, the framework attempts to retrieve the validator defined by the validatorId on the endpoint and use it to filter the output.

The following is an example of an Orders resource with a filter specified for the endpoint:

@Endpoint(id="test.orders.orderId", filterId="orders.id-Full") public RepresentationModel defaultGet(@PathParam("orderId") String pOrderId) { }

Working with Simple and Hidden Properties

You can activate the include-all-simple attribute on the schema element and the hidden attribute on the property or bean-property elements. This makes the PayloadSchemaRegistry attempt to create configuration and validators for all simple properties. By default, both the include-all-simple and hidden attributes are set to false. Setting the include-all-simple attribute to true allows the inclusion of properties in the JSON output that are not hidden by the hidden attribute, as well as simple properties that are not explicitly specified.

For additional information on the include-all-simple property, refer to the Working with the Payload Schema (page 121) section.

The following example shows a bean of class atg.TestOrder that contains the id, description, state and profileId properties and the following filter:

4 Writing Resources and Endpoints 99 Based on the example above, this JSON output would be produced:

{ "id": "o12345", "state": "SUBMITTED", "description": "This is a test Order", ... < + resource metadata > }

By default the include-all-simple attribute is set to false, and only those properties that have been explicitly specified and not hidden will display.

The following example excerpt shows the atg.TestOrder bean with the include-all-simple attribute set to false:

Based on this example, the following JSON would be produced. Note that only the id and state properties are displayed as they are explicitly not hidden:

{ "id": "o12345", "state": "SUBMITTED", ... < + resource metadata > }

Customizing Property Output

You can customize the output of properties by using the property-customizer attribute of the property element. This attribute specifies a Nucleus component that is a class implementing the atg.service.filter.bean.PropertyCustomizer interface. For example:

The following example shows a PricePropertyCustomizer:

public class PricePropertyCustomizer implements PropertyCustomizer { public Object getPropertyValue(Object pTargetObject, String pPropertyName, Map pAttributes) throws BeanFilterException { Double value = (Double)DynamicBeans.getPropertyValue(pTargetObject, pPropertyName);

100 4 Writing Resources and Endpoints return "£" + String.valueOf(value); } }

The above example would produce the following JSON:

{ "id": "o12345", "state": "SUBMITTED", "orderTotal": "£100.21", ... < + resource metadata > }

Filtering Embedded Resources

You can use the embedded element of the payload schema XML for filtering embedded resources. By default, embedded resources and sub-resources occur in the response as a self link. The following is an example of a HAL output for a resource with a product sub-resource:

{ ... ... _embedded":{ "product":{ "_links":{ "self":{ "href": "test/products/prod0001" } } } } }

Schemas can be configured to provide the whole representation of the embedded resource or sub-resource by using the hidden attribute on the embedded element. For example:

The above example would produce the following JSON:

{ "id": "o12345", "state": "SUBMITTED", ... "commerceItems": [ { "id": "ci1", "quantity": "3",

4 Writing Resources and Endpoints 101 "productId": "prod001" "_links":{ "self":{ "href": "test/orders/commerceitems/ci1" } } }, { "id": "ci2", "quantity": "2", "productId": "prod006" "_links":{ "self":{ "href": "test/orders/commerceitems/ci2" } } }, ], }

The embedded element has a use-schema-id attribute that you can use to override the schema defined by an endpoint when the embedded resource or sub-resource is provided as part of the root response. For example, the commerceItems GET endpoint could be configured to use the commerceitem.id-Full validator:

@Endpoint(id="test.orders.commerceitems", filterId="commerceitems.id-Full") public RepresentationModel defaultGet(@PathParam("itemId") String pItemId){

The payload schema XML can override this so that the commerceitem.id-Summary validator is used when posting the order root resource:

For additional information on the embedded and hidden elements, refer to the Working with the Payload Schema (page 121) section.

Working with the Collection Resource Payload Schema XML

If a collection resource does not have any state, then it should be set to the type of collection that will be returned. The members for a collection are embedded in the output in an items array. The payload schema XML should include an embedded tag for items if the members of the collection should be included in the response. A self link for each member of the collection will be included unless the hidden="false" attribute is explicitly set on the embedded tag. If the hidden="false" attribute is set, the resource representation will be returned in the response. In this case, the use-schema-id must be set so that the framework can filter each individual member of the collection:

102 4 Writing Resources and Endpoints For additional information on collections, refer to the Using Embedded Resources (page 76) section. For detailed information on filtering tags, refer to the Working with the Payload Schema (page 121) section.

Setting the Filter Depth

As well as using the payload schema XML to filter individual properties of a bean, you can also filter the whole resource to a depth known as a filter depth. This allows you to control the nested level at which a filter is applied. Filter depth is useful when working with embedded resources that have a potential for circular reference.

The @Endpoint annotation has an optional filterDepth property that allows you to determine resource hierarchy depth. A filterDepth of 0 indicates that all resource properties will be displayed, but bean properties will be filtered out. A filterDepth of 1 indicates that all resource properties will be display, as well as bean properties, etc.

The filterDepth of a root resource overrides the setting on any sub-resource output of a representation. If an order resource has a filterDepth of 1 and it contains CommerceItem sub-resources whose endpoint settings had a filterDepth of 2, the filterDepth of the order resource overrides that of the CommerceItems.

Using Query Parameters

You can filter the response output using query parameters:

• useFilterId – The useFilterId specifies a preconfigured schema when filtering a resource. For example:

context/v1/orders/getOrder/012345?useFilterId=orders.Id-Full

• fields – The fields query parameter specifies which fields or embedded relation names should be returned, separating each by commas. Only the specified fields are included in the response. Note that you can use dot (.) notation and asterisk (*) wildcards to include nested fields in a response. For example:

context/v1/orders/getOrder/012345?fields=id,description,st*

• links – By default, all links for a resource are included in the response. The links query parameter specifies which links should be returned, with links separated by commas. For example:

context/v1/orders/getOrder/012345?links=self,submitOrder

• expand – By default, all embedded resources and sub-resources of a root resource output contain a self link. The expand query parameter returns the entire representation of the embedded resource or sub- resource. Resource names are separated by a comma. To get the entire representation of all embedded or sub-resources, use ?expand=all. The following example displays all resource for commerceItems and shippingGroups:

context/v1/orders/getOrder/012345?expand=commerceItems,shippingGroups

• exclude – Opposite to the fields parameter, this is a comma separated list of field and/or embedded relation names that should be excluded from the response. Dot notation is supported, however wildcards are not.

• filterDepth – Specifies a response depth that overrides the endpoint filter for this request. Refer to the Setting the Filter Depth (page 103) section for additional information.

For information on additional query parameters, refer to Configuring Pagination for Collection Resources (page 89) and Using Etags for Version Tracking (page 108).

Setting Server-Side Security

You can prevent cross-site request forgery attacks by registering the org.glassfish.jersey.sever.

4 Writing Resources and Endpoints 103 filter.CsrfProtectionFilter with the Jersey application. This indicates that the filter expects X- Requested-By to be set on the header of every request except for those that do not change state, such as a GET request. If the X-Requested-By header is not found, a 400 Bad Request is returned to the client.

The Nucleus component for CsrfProtectionFilter allows easy registration of the filter. The following is an example of a CsrfProtectionFilter.properties file:

$class=org.glassfish.jersey.server.filter.CsrfProtectionFilter $classloader=/atg/dynamo/service/jaxrs/JerseyClassLoaderService

The filter should be registered as a provider with the /atg/dynamo/service/jaxrs/ ApplicationService Nucleus component by adding the following to the ApplicationService.properties file:

providerInstances+=/atg/dynamo/service/jaxrs/security/CsrfProtectionFilter

For additional information on endpoint security, refer to Configuring Endpoint Security (page 104).

Configuring Endpoint Security

By default, endpoints are public; however, it is possible to set up security on endpoints using access control and access checkers. There are two ways to set up access control mappings. You can specify an access checker that the endpoint will use, or you can set up a configuration file to specify access checkers for a URL and HTTP method.

Configuring Access Checkers

Endpoint security is done through access control and access checkers. Once you have configured and set up access checkers, you can indicate access levels for endpoints.

Access controllers use URLs to define the type of access an endpoint has. The type value, which is defined in accessControllers.xml, is used by the AccessControlService to map access to the access checker Nucleus component, which is used to perform the access check.

The following is an example of the AccessControlService that defines accessCheckers:

accessCheckers=\ allowAll=AllowAllAccessChecker,\ denyAll=DenyAllAccessChecker,\ combineOr=CombineOrAccessChecker,\ combineAnd=CombineAndAccessChecker,\ loggedIn=LoggedInAccessChecker,\ transientOrLoggedIn=TransientOrLoggedInAccessChecker,\ https=HttpsAccessChecker

Access checkers identify if access to an endpoint is allowed. There are several access checkers that are available by default. These include:

104 4 Writing Resources and Endpoints • allow-all – This security checker allows all access to an endpoint.

• deny-all – This security checker denies all access to an endpoint.

• logged-in – This checker verifies that a user is logged in before allowing access to an endpoint by checking for a valid OAuth token.

• https – This checker verifies that the request is secure before allowing access to an endpoint.

• combinedAndAccessChecker – This checker combines multiple access checker using an AND operator.

• combinedOrAccessChecker – This checker combines multiple access checkers using an OR operator.

• accessControllerAccessChecker – This checker looks for access controllers that were created for use with ATG MVC REST calls to verify that the access should be granted to an endpoint.

You can create custom access checkers by implementing the atg.service.jaxrs.security. AccessChecker interface and configuring an access checker as necessary. You can also create access checkers from existing ATG MVC REST atg.userprofiling.AccessController implementations. For example, a logged in access checker that uses the ATG MVC REST /atg/userprofiling/LoggedInAccessController might look like this:

$class=atg.service.jaxrs.security.AccessControllerAccessChecker $classloader=/atg/dynamo/service/jaxrs/JerseyClassLoaderService

accessController=/atg/userprofiling/LoggedInAccessController

Access checkers can be combined to create more complex access checkers using the combineOr and the combineAnd types. For example, this could be added to the accessControllers.xml file:

Defining Security Mapping

By default, all endpoints are public and available to all callers. There are two ways that you can map access checkers for use with an endpoint. Using the @Endpoint annotation security property allows you to specify the access checker to be used for the endpoint. You can also use an XML configuration file to specify the access checker for a URL and HTTP method.

Note: It is best to use the security property of the @Endpoint annotation to define security mappings. Security mappings defined in the @Endpoint annotation can be overridden by configuration in the accessControllers.xml file. Using Endpoint Annotations

By default, an endpoint is public and available to any caller. However, the @Endpoint annotation has a security property that allows you to specify an access checker for the endpoint. The value of the security property should be the ID of the access checker as defined in the accessControllers.xml file, for example,

4 Writing Resources and Endpoints 105 allow-all, deny-all, https, etc. Additionally, the @Endpoint annotation isPrivate can be set to true to automatically enable a deny-all access checker for the endpoint.

Once you have configured the security property, on startup, the RestResourceRegistry detects any security mappings defined for the endpoint. For example:

@Path("/{productId}") @GET @Endpoint(id="productById", security="logged-in") public RepresentationModel singularGet(@Context HttpServletRequest servletRequest, @PathParam("productId") String pProductId){ // endpoint implementation }

Note: Security mappings that are defined with the @Endpoint annotation can be overridden by configurations defined in the accessControllers.xml file.

Using XML Annotations

Access control mappings can be created using XML. XML configurations allows you to map an access checker to a URL and a set of HTTP methods. For example

This allows the AccessControlService to paste the XML file and create AccessControlItems, which hold details of the access control mappings.

Cross-Site Request Forgery Protection Filters

The CsrfProtectionFilter provides server-side protection against cross-site request forgery attacks. When you register this filter with the Jersey application, the filter looks for X-Requested-By to be set on the header of every request that changes state. Register the filter as a provider in the ApplicationService Nucleus component:

providerInstances+=/atg/dynamo/service/jaxrs/security/CsrfProtectionFilter

If the header is not found, Jersey returns a 400 Bad Request response to the client.

Working with Caching

You can configure and enable caching for both the server and client. Server-side caching uses the cacheConfig.xml, while client-side caching uses the @Endpoint annotation.

106 4 Writing Resources and Endpoints Configuring Server-Side Caching

Caching is configured using the filterId of the cacheConfig.xml file. As well as specifying the filterId to cache, you must specify any repository or item descriptor related to the cached resource. The RepresentationCache creates listeners that flush the cache when repository items that have cached representations change, such as during a deployment event or a PUT/DELETE request. Only representations of static resources, such as categories, products or SKUs are cached, so as not to create large numbers of caches.

The maximumCacheEntries for the cache created for the filter can also be set using cacheConfig.xml file.

The following is an example of a cache configuration:

/atg/dynamo/service/jaxrs/cache/cacheConfig.xml

Each filterId cache is keyed off of the URI to the resource, header values and any parameters. The RepresentationCache component has a keyHeaders property that allows you to specify which request headers should be keyed. Additionally, the RepresentationCache also has an excludeParametersFromKey property that excludes specific request parameters. For example:

enabled=true invalidatePerChange=true defaultMaxCacheEntries=1000 cacheConfigFile=/atg/dynamo/service/jaxrs/cache/cacheConfig.xml … keyHeaders=\ Accept,\ Accept-Language,\ X-OCAsset-Language

excludeParametersFromKey=\ jsessionid

JSON responses are added to the cache in the CacheWriterInterceptor after the MessageBodyWriters have been invoked to produce the JSON. The response is cached only when the response entity is a RepresentationModel. This avoids caching any error JSON unnecessarily. When caching is enabled, responses for a GET request are cached on the server.

Working with Client-Side Caching

Client caching is enabled or disabled using the @Endpoint cache property. By default, the cache property is set to false, which disables client caching. When client-side caching is disabled, the framework adds a no-cache header to the response indicating to the client that the response cannot be cached. You must explicitly set the cache property to true to allow client caching. For example, you might use this property if a resource response is fairly static and does not include sensitive data.

4 Writing Resources and Endpoints 107 The no-cache headers can be configured. For example:

noCacheHeaders=\ Cache-Control=public,,must-revalidate,,proxy-revalidate,\ Edge-control=no-store

Using Etags for Version Tracking

The framework supports client caching by creating Etags, which is a hash of the JSON response, the URI, and the resource version.

The framework generates an Etag for every resource representation in a response. These Etags include the version of the resource instance, which can be used for caching the response. Additionally, they can be used for If-Match or If-None-Match header preconditions.

If a PUT request uses an If-Match header that contains an Etag value, the ETagService verifies that the Etag’s resource version number matches the current resource version. This allows the framework to track the version of a resource.

If a GET request uses an If-None-Match header, the ETagService verifies that the hash of the current response matches the hash of the Etag set by the client. If the hash matches, then a Not Modified response code is returned. If the Etags do not match, or if the If-None-Match header is not set, a new Etag is created for the response.

Etag generation can be disabled by setting generateETags=false as a query parameter of the request. The query parameter is parsed from the request by the framework and sets the generateETags property of the current REST context. If the client request does not specify the generateETags query parameter when retrieving embedded resources, it is set to false by default.

Tracking the Current Resource Version

The version property of the RepresentationModel allows the endpoint to specify the version number for the resource. If the version property is not set then the framework attempts to get the version number from the RepresentationModel state, provided that the state is a RepositoryItem and the RepositoryItem has a version property. If the version number cannot be obtained from the RepresentationModel the framework uses the ResourceVersionRepository to track the version. The version number is incremented for each PUT request so that the appropriate error can be returned if a client as a stale version of the resource.

Version tracking can be disabled by setting the RestResource annotation trackVersion attribute to false. When false, the resource version is identified as 1.

Disabling Client-Side Caching

To disable client caching, use the cache property of the @Endpoint annotation. When you set the cache property to false, no cache headers are set on the response headers.

Setting Language Support

Endpoints can set the localeHint property of the @Endpoint annotation to let the client know if it must provide a locale for the request. The framework looks for the X-OCAssetLanguage custom request header to

108 4 Writing Resources and Endpoints get the request locale. If an endpoint uses this locale hint, then any request that gets matched to this endpoint must contain the custom header or the request is rejected.

If the header is not set, the user profile provides the locale. If the user profile does not contain a locale the system checks the locales property in the request and then, if not finding a locale, checks the server locale.

The LOCALE_HINT_ASSET_LANGUAGE_REQUIRED enables endpoints that require the asset to be updated with the correct locale. If an endpoint uses this locale hint, any requests matched to this endpoint must contain the custom header or the request will be rejected. The following is an example of a localeHint:

header(String pName, Object pHeader) localeHint = RestConstants.LOCALE_HINT_ASSET_LANGUAGE_REQUIRED

Working with Form Handlers

You can invoke form handler handlers from within any endpoint by using the FormHandlerExecutor class. You must configure the FormHandlerExecutor with a handle method that is contained within the form handler that you wish to call.

The FormHandlerExecutor is where form handler input is added. For example, the CartCommerceItemRestSubresource.addItem handle method uses the addInputsForAddItem hook method to set up the data required by the form handler. It accepts parameters such as those accepted by the endpoint, or a ResourceUpdateInfo, which contains the updates as detected by the framework.

The parameters for this method are:

FormHandlerExecutor pExecutor, Order pOrder, JSONObject pInputJson, ResourceUpdateInfo pResourceUpdateInfo, AddCommerceItemInfo[] pItemsToAdd

The following shows how you might invoke the CartModifierFormHandler:

FormHandlerExecutor executor = new FormHandlerExecutor (getCartModifierFormHandlerPath(), getAddItemsHandleMethod()); addInputsForAddItem(executor, order, pInputJson, RestUtils.getRestUtils(). getResourceUpdateInfo(), itemsToAdd); executor.processFormHandlerResult(executor.execute());

The result returns as a FormHandlerInvocationResult that contains the FormExceptions or FormError.

Note: It is recommended that you do not set properties directly on the form handler itself, but use one of the addinputFor hook methods.

To invoke a form handler:

1. Identify the handle method of the resource or its sub-class.

2. Create the instance FormHandlerExecutor by passing the form handler path and handler method name as displayed above.

4 Writing Resources and Endpoints 109 Working with REST Actor Endpoints

You can call your existing actor-based endpoints by exposing them through the JAX-RS endpoints using the RestServletUtilsImpl class. The response returns to the JAX-RS endpoint that handles the call, for example, wrapped into the RepresentationModel, or by using the actor endpoint.

To execute a MVC REST actor endpoint:

1. Identify the actor endpoint to invoke.

2. Register the endpoint in the actor chain registry.

3. Disable the session confirmation number by setting the enforceSessionConfirmation parameter in your local /atg/dynamo/service/actor/Configuration.properties file to false.

4. Define a JAX-RS endpoint method that invokes the actor chain framework using the invokeActorRestEndpoint method of RestServletUtilsImpl.

The following example shows how you might get a summary of the current user:

@Path("/currentUser/update") @POST @Endpoint(id = "/currentUser/update") public Object update() { return RestServletUtilsImp .invokeActorRestEndpoint("/model/atg/userprofiling/ProfileActor/ update"); }

Working with Statelessness

One of the defining features of RESTful services is that they are stateless, meaning that a client’s state is not kept on the server. This allows each request to be treated independently and the Web services do not need to maintain the previous interactions from clients. Statelessness necessitates that each request from a client to a server to contain all of the information necessary to understand the request.

Oracle Core Commerce passes state data to the client in the HTTP response and requires the client to pass the state data back to the server on the next request. There are two main components that pass data during a session.

• The profile maintains data for a shopper, which includes the profile ID, security status, and active promotions.

• The shopping cart passes a JSON representation of the cart to the client in the HTTP response body for any endpoint that interacts with the cart.

By default, the framework is configured to be stateful. However, the framework contains a stateless configuration layer. When a server runs with this layer, both the session and the window scope are remapped to a request scope, indicating that the server is no longer storing state across the session. You can pass session state data to a client as part of a response header and body. You can also allow the client to pass that data back in with a request and have it transformed back into state information available for that request. The public/v1 API provides support for passing the profile and cart state information back and forth to the client. The profile

110 4 Writing Resources and Endpoints data is passed using headers. The cart can grow to be very large, and is therefore passed as extra data in the response body.

Note: When configuring statelessness, your environment should not contain any shareable types. For information on shareable types, refer to the Multisite Administration Guide.

Important: When working with stateless environments, the best performance can be obtained by routing all service requests from a session to the same server, ensuring session affinity. Additionally, data volume for service calls and responses increases when your environment is set to use statelessness. As such, it is best to increase the available network bandwidth with the understanding that your performance results may differ depending on the configuration of your environment.

Passing State Data in the HTTP Header

When a component uses a header to pass state data between the client and the server, the data is comprised of a map of key/value pairs that reconstruct the component on the next request. This encoded and signed data is keyed on the component name. The value is the child map of key/value pairs used to reconstruct the component. The header value is a string representation of this map. For example:

{ /atg/userprofiling/ProfileLoadableService = {securityStatus=0, activePromotions=, userId=1160002} }

To configure a component to pass state information within the headers, add the Nucleus component path to a request-scoped instance of LoadableService to the loadableServicePaths property in the RequestStateManager:

loadableServicePaths=\ /atg/userprofiling/ProfileLoadableService

Passing State Data in the HTTP Body

When a component uses the body of the request or response to pass data between the client and server, the state data is a coded and signed JSON representation of that component.

The body of the request is JSON that contains the input for the endpoint and any state data. All state data contained within the body is encoded JSON that represents the component that is reconstructs. The RequestStateManager uses the validator framework to create the outgoing JSON and validate the incoming JSON that represents the component state.

To configure a component to pass state information within the body of the request or response, add the Nucleus component path to a request-scoped instance of LoadableService to the loadableServicePaths property in the RequestStateManager:

loadableServicePaths=\ /atg/userprofiling/ProfileLoadableService

The RestResource class adds the current instance of the component as a parameter of the request so that the RequestStateManager can retrieve the object and build a representation of it to be returned to the client.

You can also use the StateMessageBodyReader to read state data from a message body or to write state data from the response of a specific media type. The default implementation reads state data in JSON format

4 Writing Resources and Endpoints 111 Loading Components

The LoadableService interface reconstructs components per request. Components can either be loaded from a map contained in the request header or from a JSON-constructed object contained within the request body. Because of this, there are two different LoadableService interfaces.

Components that need to pass state data back and forth in the HTTP headers implement the MapDataLoadableService. Use the getProperties method to allow the component to identify the properties that it needs to reload itself or another component. These properties are returned as a map of key/ value pairs that are stored in the HTTP response header. When another request occurs, the map of key/value pairs is returned in a call to the loadService method.

Components that pass state back and forth in the request and response body implement the ObjectDataLoadableService. Its loadService method takes an object that contains data used to reconstruct a service.

Loading User Profile Components

The ProfileLoadableService is an implementation of LoadableService that loads the / atg/userprofiling/Profile component on each request. The getProperties method of the ProfileLoadableService builds a map that includes the ID of the profile, as well as any other properties of the profile that need to be set. The implementation of loadService uses the data in the map to load the user profile from the repository and then set any of the additional properties contain in the map on the profile. If the profile cannot be loaded, a new transient profile is created and other properties contained in the map will be set on the transient profile.

You can extend the ProfileLoadableService to handle additional properties that must be stored or reset upon each request. For example, an extension of ProfileLoadableService handles the activePromotions property of the profile.

To use the getProperties method, your extension should call the super.getProperties method to get the map created by the super-type. This also allows you to add further properties and not lose properties set by the super-type. The loadService method should be extended to call the super.loadService method to load the profile and handle any properties set by the super-type.

Understanding Oracle Core Commerce-Specific Statelessness

The following section describes Core Commerce-specific modifications made to your configured statelessness framework.

Core Commerce-specific cart endpoints and sub-resource locator methods call the setupCartStateRequestData method of CartRestResource to set up the cart state request data so that it can be added to the body of the HTTP response.

When shopping cart data is added to a request, the framework puts it in the body of the HTTP response, as described above. The CartStateService class adds shopping cart data to a data map, allowing the framework to add to the body of a response using the cartState key.

The RequestStateManager uses the keyToValidatorId to indicate what to look for in the request map. Note that the prefix atg.service.jaxrs is prepended to cartState. The RequestStateManager also contains a key/value pair that points to the OrderLoadableService component that sets up the shopping cart; this is the keyToLoadableServicePath.

keyToValidatorId=\ atg.service.jaxrs.cartState=cart-representation

112 4 Writing Resources and Endpoints keyToLoadableServicePath=\ atg.service.jaxrs.cartState=/atg/commerce/order/OrderLoadableService

When the cart state is passed in a request, the framework uses the cartState-representation validator in the DCS/configlayers/stateless/atg/dynamo/service/payloadSchema.xml to retrieve and reconstruct the order object.

The CommerceProfileLoadableService component saves and reconstructs profile properties for the response. This component overrides the loadService method and returns a map of profile properties needed to reload the profile on subsequent requests.

The OrderLoadableService accepts reconstructed order objects that have been created by the framework and sets them as the current order.

Example of Creating an Endpoint

The following steps show how you might create an endpoint.

1. Create a package called atg.commerce.foo.restresources.

2. In this new package, create a current order resource class, such as CurrentOrderRestResource.

3. Define the annotations for the root resource level:

@RestResource(id=OrderRestConstants.CURRENT_ORDER_ID) @Path("/cart") @Api(value="/cart") public class CurrentOrderRestResource extends GenericService { }

4. Add an endpoint that retrieves a representation of the current order by adding the following:

@GET @Endpoint(id="/cart#GET" filterId="cart-Default") @ApiOperation(value="Gets the current order.") public Object getOrder(JSONObject pJson) throws RestException, CommerceException { }

5. Register the current user resource in the RestResourceRegistry.properties file.

nucleusRestResources+=\ atg/commerce/foo/restresources/CurrentOrderRestResource

6. Build a CurrentOrderRestResource using a separate class loader.

7. If you are adding the resource to a location different than the default, update the /Dynamo/foo/config/ atg/dynamo/service/jaxrs/ JerseyClassLoaderService.properties file to include:

childFirstPrefixes=+\ atg/commerce/foo/restresources

Self Documenting with Swagger

The Swagger-core open source project allows you to create documentation for your REST endpoints. During the installation process, all of the required Swagger libraries are available, allowing you to configure and use Swagger annotations in your endpoint classes.

Swagger produces documentation in JSON or YAML format, and can be accessed through the URL in the format of http://server:port/context/servletpath/swagger.json|yaml. For example, you could access a JSON file from http://localhost:8080/public/v1/swagger.json.

Swagger is initiated on server startup and can be configured to scan specific packages or classes, looking for JAX-RS and Swagger annotation. Swagger has been extended to retrieve a list of classes from the RestResourceRegistry to scan. Swagger has also been extended to generate most of the endpoint request body and response schema information from the PayloadSchemaRegistry configuration, specifically the payloadSchema.xml.

Setting up Context or Versions

Every context (public, admin, and agent) and version (v1, v2, etc.) has a separate swagger.json response. The REST module defines a separate Web application for each context/version pair. For example, the Web application for /public/v1 is defined in RESTJAXRSPublic.version1. The Web application’s web.xml file specifies Jersey servlet initial parameters that supply paths for the appropriate RestResourceRegistry and PayloadSchemaRegistry components. Setting up a new context or version requires new resource and registry components as well as a Web application, but no Swagger-specific configuration.

Using Swagger Annotations

Swagger uses a number of annotations to create and display documentation, with most Swagger annotations being with @API. A list of Swagger annotations can be found at https://github.com/swagger-api/swagger-core/ wiki.

Note: You will only need few of the annotations and their attribute. The following descriptions focus on the Swagger features that are needed for endpoint design and implementation. Key features of the Swagger scan logic are described as they apply to Oracle Commerce REST endpoints.

When creating Swagger annotation, it is best to put the annotations after the JAX-RS and Oracle Commerce annotations. For example:

@Path("/currentUser")

114 4 Writing Resources and Endpoints @Api(value = "currentUser") public class CurrentUserRestResource extends GenericService {

The following is an example of a swagger.json file format:

{ "swagger" : "2.0", "info" : { "title" : "REST API Reference for Oracle Commerce Platform" "version" : "v1" }, "host" : "somehost:8080", "basePath" : "/public/v1", "tags" : [ { "name" : "articles" }, ... ], "schemes" : [ "http" ], "paths" : { "/" : { "get" : { "tags" : [ "version" ], "summary" : "get version", "description" : "Retrieves a singular version resource that pertains to this context.", "operationId" : "getVersion", "parameters" : [ ], "responses" : { "200" : { "description" : "successful operation", "schema" : { "$ref" : "#/definitions/version-Default" } }, "500" : { "description" : "Invalid version resource path." } } } }, "/cart" : { "get" : { "tags" : [ "cart" ], "operationId" : "getCurrentOrder", "responses" : { "200" : { "description" : "successful operation", "schema" : { "$ref" : "#/definitions/cart-Summary" }, "headers" : { } } } }, "delete" : { "tags" : [ "cart" ], "summary" : "Cancels the current order.", "description" : "Cancels the current order.", "operationId" : "cancelCart",

4 Writing Resources and Endpoints 115 "parameters" : [ ], "responses" : { "500" : { "description" : "Could not cancel the order." } } } }, ... }, "definitions" : { "orders.id-Summary" : { "properties" : { "id" : { "type" : "string" }, "totalCommerceItemCount" : { "type" : "integer", "format" : "int64" }, "totalCommerceItemCountWithFraction" : { "type" : "number", "format" : "double" }, "priceInfo" : { "$ref" : "#/definitions/orders.id.orderPriceInfo-Summary" }, "commerceItems" : { "$ref" : "#/definitions/commerceitems-CollectionSummary" } } }, "promotions.id-Default" : { "$ref" : "#/definitions/promotions.id-Summary" }, ... } }

The main Swagger annotation is @Api which marks a class as a Swagger resource or sub-resource. @Api must be used within resource and sub-resource classes for their endpoints to appear in general documentation.

Tags group endpoints, with the scan automatically using the value of the @Api value attribute as a tag for every endpoint in the class; if the value starts with “/”, the slash is removed. You can use the same value for the value property in both @Path and @Api annotations. Sub-resource endpoints are automatically tagged with their own tags and their ancestor resources’ tags. Should you prefer not to use the value attribute, you can specify the tags attribute to add a list of tags.

A method in a resource or sub-resource class is considered to be an endpoint if it contains a JAX-RS @Path annotation. It must also have an HTTP method annotation, which is a JAX-RS @GET, @DELETE, @POST, @PUT, or an Oracle Commerce @PATCH. The @ApiOperation annotation is not required for an endpoint to be included in swagger.json. However, it does provide a place to specify useful information that cannot be determined in other ways. Endpoints should use the @ApiOperation value attribute to specify a summary of the actions that an endpoint performs.

Swagger adds an entry to its paths section for each unique path, building the path identifier from the endpoint @Path, the class @Path, and any ancestor resource path. Each HTTP method corresponds to an operation under the path. Each endpoint is represented in swagger.json with a path and operation pair.

116 4 Writing Resources and Endpoints Adding Swagger Annotation

Every endpoint is represented in the swagger.json file by a path and an operation pair.

The following is a list of the most common swagger.json properties for an endpoint, and the source of their values:

Property Source Value

description (string) The @ApiOperation notes attribute. The notes attribute has some limited support for GFM syntax, for example, ** for bolding and ~~ for strikethrough. You can use the notes attribute to describe anything about the endpoint’s behavior that is not obvious from the value attribute and the endpoint’s input parameters.

operationId (string) The endpoint’s Java method name, which can be overridden by the @ApiOperation nickname attribute.

parameter (array of objects) A parameter array is added for each parameter in the method signature. Refer to the Using Endpoint Parameters (page 117) section for further information.

responses (map keyed by Every endpoint must contain at least one response entry. Refer to the response status codes) Using Endpoint Responses (page 118) for further information.

summary (string) The @ApiOperation value attribute. Can be up to 120 characters.

tags (array of strings) The @APIOperation tags attribute or, if there are no @APIOperation tags, resource tags and ancestor resource tags.

Using Endpoint Parameters

Swagger adds an entry to an endpoint’s parameter array for each parameter in the method signature. The @ApiParam annotation is not required for a parameter to be included in swagger.json. The most common uses of @ApiParam are to supply a description and to flag a parameter as required. The following is a list of the most common swagger.json properties for a parameter and the source of their values:

Property Source Value

description (string) The @ApiParam value attribute.

enum (string) The @ApiParam allowableValues attribute. Supply allowableValues for any non-body parameter that accepts a specific set of values.

in (body, path, query) Uses path if @PathParam is present or query if @QueryParam is present or formData if @FormParam is present. Otherwise uses body. Note that there are additional choices for the in property, however they are not used.

4 Writing Resources and Endpoints 117 Property Source Value

name (string) Uses body for in body, the @PathParam value for in path, or the @QueryParam value for in query or @FormParam value for in formData. It is overridden by the @ApiParam name attribute.

required (true, false) The @ApiParam required attribute, which defaults to false.

schema (string) The @APIOperation value attribute. This string can contain up to 120 characters. This property is required when using in body.

There are additional Swagger properties that could be useful when creating path and query parameters. Unless otherwise noted, these properties come from the @ApiParam annotation:

• defaultValue - @DefaultValue value or @ApiParam defaultValue attribute

• example

Using Endpoint Responses

Swagger requires that every endpoint have at least one entry in the responses map. The Swagger scan usually adds “200” with the “successful operation” description by default.

The Swagger extensions in Core Commerce automatically fill in the following if not specified in the @Endpoint annotation:

• 200 – “successful operation” for endpoints other than DELETE, unless the @Endpoint annotation specifies a different 2xx response

• 204 – “successful operation” for DELETE endpoints, unless the @Endpoint annotation specifies a different 2xx response

• 404 – “resource not found” for GET endpoints

• 500 – “internal server error” for all endpoints

Specify other status codes by using the @ApiResponse and @ApiResponses annotations. It is important to not specify the same status code more than once per endpoint as Swagger cannot hold more than one message per code.

If your endpoint’s normal status code is something other than 200 or 204, use the @ApiOperation annotation with the code attribute set to the appropriate status code.

Using Validator and Filter Definitions

Every endpoint that accepts input in the request body needs a schema definition for the body parameter. Schema definitions are generated automatically with the @Endpoint validatorId attribute. This guarantees that swagger.json will always match what an endpoint actually accepts.

Similarly, every endpoint that generates a response body needs a schema definition associated with any success response code, such as 200 or 201. Response schema definitions are automatically generated with the @Endpoint filter attribute, or the validatorId attribute if the filterId is omitted. The schema is automatically associated with both the 200 and 201 response codes, if present.

118 4 Writing Resources and Endpoints Using both the tags in the payloadSchema.xml file and information that the payload schema framework determines by introspecting referenced repository items and Java objects at start up, a complete schema definition is automatically generated. This includes all property names, data types, required and writable attributes, alternate data models (such as switch/case combinations) and others. In most cases, no additional information is required. If an additional explanation of the schema is needed, the payload schema XML offers a doc tag that can be included as a child of the schema, property and bean-property tags. The doc tag uses PCDATA rather than an attribute for the text, which gets transferred to a description property in swagger.json. Descriptions support rich text using GFM syntax. For additional information on payload schemas, refer to the Working with the Payload Schema (page 121) section.

The following is an example of a schema definition:

... properties ... Provides commentary about the cart's default filter.

... Describes a list of upsell actions.

Use the following instructions to add Swagger annotation to your endpoints.

1. The @Api annotation marks a class as a Swagger resource or sub-resource. Add the annotation to your endpoint and specify a value attribute. The value attribute groups resources, and is used during the construction of Swagger’s tags. The value that you defined for the @Path annotation can be used, without the slash:

@Path("/checkout") @API(value = "/cart") public class CartRestResource extends AbstractOrderRestResource {

2. Add the @ApiOperation annotation to all of the methods in your endpoint. You can add it as the last annotation in the list. Include information on applied filters and any security details:

@Endpoint(id="/cart/checkout/#POST", isSingular = true, validatorId = "cart.checkout", filterId = "cart-Default") @ApiOperation(value = "Checks out the current order in the cart.") public Object login(

3. If your endpoint is returning different codes, you can annotate them and add the corresponding annotation after the @ApiOperation. All responses must be unique. If you create multiple responses with the same code, Swagger will randomly pick a response:

@ApiResponses(value = { @ApiResponse(code = 400, message = "Failure: Invalid ID supplied."), @ApiResponse(code = 404, message = "Failure: Order not found.") })

4. Once the method is annotated, you must annotate all of the incoming parameters. Use the @ApiParam annotation. With this annotation, the value attribute describes incoming parameters. Mark all required parameters with the required=true attribute. The name attribute is optional:

4 Writing Resources and Endpoints 119 The following is an example of Swagger annotation:

@Api(value = "/cart") @POST @Path("/checkout") @Endpoint(id="/cart/checkout/#POST", isSingular = true, validatorId = "cart.checkout", filterId="cart-Default") @ApiOperation(value = "Checkout the current order in the cart.") public RepresentationModel checkout(@QueryParam("allowEmptyOrders") Boolean pAllowEmptyOrders, JSONObject pInputJson) throws RestException, CommerceException, ServletException { … }

120 4 Writing Resources and Endpoints 5 Working with the Payload Schema

The REST JAX-RS API payload schema framework contains a validation framework that handles validation as well as updating target dynamic beans. The payload schema also provides serialization and filtering formats for the generation of Swagger documentation.

You define the input, as well as the validators that check the input. Validators can also apply data to a target dynamic bean or record changes that can be applied later. The payload schema framework can introspect beans or repository items to create default validators for simple properties.

Use the Dynamo Server Admin to view available schemas, validator and validator properties.

The payload schema framework can perform the following:

• Validating input, which may be a hierarchy of any kind of dynamic bean, collection or map

• Transforming input, so that input types can be coerced into primitive types, Maps, Beans or repository items

• Updating the properties of beans or repository items using the validated and transformed values

• Dynamically adding repository properties and repository subtypes

Understanding Validator Components

Validators are configured using an XML-combining XML file. The payloadschema.xml file defines the top-level payload-schemas and child schema tags, giving each schema tag a unique ID. Each schema tag represents a java-bean class or a repository item type and specifies the entity that validation input represents. Note that a validator can be run on inputs of other types, such as a JSONObject, as well as update other types, such as an empty HashMap.

The following table describes a few of the XML attributes from the payloadSchema.xml file that can be used during filtering and validation. For a full list, refer to the ATG Platform API Reference:

XML Attribute Description

hidden This attribute on the schema or bean-property elements identifies if a property is hidden from the output. The default is false. Refer to the Validating Input and Filtering Output (page 95) section for instructions on using this attribute.

5 Working with the Payload Schema 121 XML Attribute Description

id The unique ID of the schema.

include-all-simple This attribute on the schema or bean-property elements allows you to include all simple properties. This flag also includes containers, such as collections and maps, which can be introspected to contain simple properties. Refer to the Validating Input and Filtering Output (page 95) section for instructions on using this attribute.

include-schema-id The ID of the schema from which to inherit.

include-simple-properties- This element allows the simple properties of a sub-property to be from exposed as its own properties.

internal-property-name This attribute on the property element allows a property to be aliased and allows the simple property of a sub-bean to be exposed as a property of its parent. Dot notation is supported.

property-customizer This attribute on the property element allows you to declare a Nucleus component that customizes the output value. The Nucleus component must be a class that implements the atg.service.filter.bean.PropertyCustomizer interface.

switches-first Identifies if switches should be performed before contained property and bean-property validations. May not be needed, for example, if the SwitchingUpdatingValidator subclass creates the target bean.

treat-container-as-bean This attribute on the schema or bean-property elements identifies the container object as a normal bean. For example, if the state of the representation model is a Map, the properties defined for the schema or bean-property will correspond to the Map keys when the treat- container-as-bean property is set to true. The default is false. For additional information on this attribute, refer to the Validating Collections (page 97) section.

writeable Indicates if the schema can be used for updates. If set to false, no validator is created.

In addition to the XML attributes listed above, you can use the embedded XML tag, which determines how embedded resources filter output as part of the root resource. This element has hidden and use-schema- id attributes. The hidden attribute decides if the full embedded resource will be output. If hidden=true, only a self link for the embedded resource will display. The use-schema-id attribute indicates the schema to use when filtering the embedded resource. If an embedded resource exists for a root resource, but no corresponding embedded tag is specified in the payloadSchema.xml, there will be no output for that embedded resource.

The property and bean-property validators are executed in the order in which they appear in the XML file for a given bean. Validators created from the property tag, which represents a simple property, are executed before the validators created from bean-property tags, which represent a property that has a value of a bean that has nested properties itself. Validators that are created for switch tags are executed last, unless the switches-first attribute on the schema or bean-property tag is set to true.

122 5 Working with the Payload Schema Validator Components

This table is a list of validator components, followed by additional information on some of the components:

Component Description

BeanValidator This is the interface for validating and updating an entire bean. The BeanValidator is the core interface and uses two methods:

validateBean – Validates the properties of the source bean, adding any validation errors to the errors property of pContext

updateBean – Validates property values and places them into the target object.

ListUpdatingValidator This class extends the UnorderedCollection’s component UpdatingValidator to add code that updates an order in the case where order is important.

MapUpdatingValidator The class that implements UpdatingValidator and BeanValidator and can update the map with homogeneous values.

PayloadSchemaBuilder This helper class creates validators from the configuration beans.

PayloadSchemaRegistry The class that parses the payload schema XML and builds configuration beans and instantiates validators. This class provides a way to fetch a named validator or its schema configuration. For additional information on the PayloadSchemaRegistry, refer to Using the Payload Schema Registry (page 125) section.

UpdatingValidator This is the interface that extends Validator and allows you to update a single property.

Validator This is the interface for validating a single property value.

The Validator interface, which validates individual properties, uses the following methods:

validateBeanProperty – Retrieves the named property and invokes the validateValue method. This enables simple validators to be written by overriding the validateValue method

validateValue – This method can be overridden when creating simple validators

ValidatorContext This class holds the errors, the current parent property path and other contextual data that is used during validation. For detailed information on the ValidatorContext, refer to Configuring the Validator Context Class (page 124) section.

ValidatorManager The class that implements UpdatingValidator and BeanValidator. It also contains a map from property names to Validator, as well as validates and updates named properties of a dynamic bean.

5 Working with the Payload Schema 123 For additional information on validation classes and components, refer to the ATG Platform API Reference.

Configuring the Validator Context Class

The ValidatorContext represents the current state and setting for the validator. It also contains an attributes map that allows validators to pass or share state, as well as the following properties:

Property Description

allowableUnknown Obtains the names of properties that are not defined in the schema and PropertyName should not cause validation errors.

applyUpdatesToTarget If set to true, the target is updated with the changes in the property value.

attributes Returns any extra property attributes.

create If the validation is for a create call, set this property to true. The default is false.

defaultErrorCode Identifies the default error code.

errorCount This read only property provides a count of the validation errors or exceptions encountered during validation.

errors List of error or exceptions encountered during validation.

fetchValueForCopy If set to true, obtains the value to copy for a property.

filter Returns a list of properties filters to include or exclude.

filterForInclude Identifies if the filter includes or excludes data. The default is false, indicating that the filter excludes data.

modifiedValue Indicates if a value was updated.

nullOutPresent Identifies if target properties should be set to null if a source property is ButNullProperties present in a source map or object.

pagentCount Obtains a count of the number of parents.

parentSrc The source parent stack that is being updated. Note: This property should be modified only by methods of this class.

propertyPath The property path that leads to the current parent.

propertyValueChange Identifies listeners that are notified when properties change. Listeners

repositoryItemHelper Identifies and sets a repository item helper.

124 5 Working with the Payload Schema Property Description

shouldRecurse Indicates if validation should recurse into validators for sub-properties.

sourceUsesExternal Indicates if the validation or update source uses external property names. PropertyNames

treatUnknownProperties Identifies whether to treat unknown properties in the input data as errors. AsErrors

updating Indicates if an update is in progress. If set to false, it indicates that a validation is occurring.

updateMode Controls whether the update mode is:

COMPLETE – All properties should be present. Properties that can be updated but are unset are considered null, and collections and maps are trimmed down to match the input.

SPARSE –Properties that can be are updated. All other properties are left untouched. SPARSE only updates properties that exist in the source.

HYBRID (merged) – Most input can be identified as SPARSE, with the exception of lists and maps, which must contain enough information to identify existing items.

validateExisting Indicates if existing properties should be validated. Properties

validatorListeners Identifies a list of validator listeners.

For additional information on validation classes and components, refer to the ATG Platform API Reference.

Using the Payload Schema Registry

The PayloadSchemaRegistry, which is configured using the payloadSchema.xml file, parses definition files into configuration beans. Once the definition file has been parsed, the PayloadSchemaRegistry resolves Nucleus components.

The following are a few of the PayloadSchemaRegistry properties:

• simpleClassToValidatorClass – If no validator is specified, the registry uses a map from a simple class to the corresponding validator.

• containerClassToValidatorClass – If no validator is specified, the registry uses a map from a container class to a corresponding validator.

• validatorClassPrefixes – An array of prefixes to search when a validator class is specified without a package name. Prefixes are tried in order, and the first two prefixes are atg.service.validator and atg.service.validator.Validators$.

5 Working with the Payload Schema 125 For additional information on PayloadSchemaRegistry properties, refer to the ATG Platform API Reference.

Validating Simple Properties

The PayloadSchemaRegistry can assign validators for simple properties, such as a primitive, a primitive wrapper, a date or a string. If the PayloadSchemaRegistry can determine the class of the property and there is a default validator for that class, it can automatically assign validators for simple properties. The include-all- simple flag indicates if all simple properties should be included when returning values. When the include- all-simple attribute is set to true on the schema or bean-property tag, the PayloadSchemaRegistry tries to create validators for all simple properties. Unless you use the include-all-simple flag, the automatic assigning of validator classes is optional. Note that you can also specify types and validator classes manually.

The default validators for simple properties are as follows. Note that these validators can be overridden by sub- classes that include customization logic to create target items, add additional constraints or perform other actions:

Simple Class Default Validator

Boolean or boolean Validators.BooleanValidator

Date Validators.TimestampValidator

Double or double Validators.DoubleValidator

Float or float Validators.FloatValidator

Integer or int Validators.IntegerValidator

Long or long Validators.LongValidator

Short or short Validators.ShortValidator

String Validators.StringValidator

How to Validate Simple Properties

The property tag validates simple properties. In the following example the PayloadSchemaRegistry reviews stringOne and assigns a default validator for the string. By default, included properties appear in the output and can be updated:

If you want to expose the simple property of a sub-bean as a property of its parent, use the internal- property-name attribute to specify a different internal name. For example, to expose a longDescription property from a bean’s backing repositoryItem property:

126 5 Working with the Payload Schema

Or, if you wanted to expose a map entry as a top-level property from a map, you might do the following:

You can extend the payload schema by using XML-combine and writing custom validators to support new data types or validation behavior. Validators are located in the atg.service.validator.Validator class.

How to Extend Simple Property Validators

The payload schema configuration can be extended using XML-combine, which creates custom validators that can be implemented to support new data types or behaviors. It is best to check for an existing validator before creating a new one.

Simple property validators should extend Validators.RequiredValidator and override the validateValue method. Start with a super.validateValue method to check for a required value. Validators that represent one of a limited number of options should extend Validators.OptionValidator, as it provides error messages that include a list of available options.

Non-updating validators, which are validators that do not implement UpdatingValidator, are used during updates to retrieve the value that will be set on the target item.

The following is an example of a simple property validator:

@Override public Object validateValue(String pPropertyName, Object pPropertyValue, ValidatorContext pContext) { Object value = super.validateValue(pPropertyName, pPropertyValue, pContext);

if (value != null) { if (!isValidValue(value)) { String errorTxt = ValidationConstants.getResource( ValidationConstants.INVALID_VALUE, pContext.getPropertyPath(pPropertyName), value.toString()); pContext.addException(this, errorTxt, pPropertyName, null); value = null; } } return value; }

If the value returned is not null, the example code validates the value. Note that the value might be null because the super.validateValue method may find an error, or because the original value was null. If, instead, the input value is invalid, an error is entered using the ValidatorContext.addException method and returned as null.

You can extend a validator to handle dynamic properties by using the include-all-simple attribute on the schema or bean-property tag. Then use a property tag with writable="true" on the simple properties that should not be accepted as input. Use the Dynamo Server Admin to access the PayloadSchemaRegistry to identify the properties found.

5 Working with the Payload Schema 127 Validating Child Repository Items

To validate child beans or child repository items, use the bean-property tag:

The bean-property tags support the nesting of both the property and bean-property tags. The validator-instance tag allows you to override the default validator class instance and to set properties on the validator instance once it is created. The param value supports both nucleus: and class: prefixes, which allows the tag to use a Nucleus value or a new class instance.

Use the Dynamo Server Admin to access the PayloadSchemaRegistry to introspect the validation configuration and test validation. If introspection fails for a bean property, use a nested bean or item- descriptor tag to override the results of the default introspection and continue with the specified class or repository item type.

You can use the following method to access BeanValidator, which validates a dynamic bean’s sub-properties, by ID:

public BeanValidator getBeanValidatorById(String pId)

Note that the PayloadSchemaRegistry and the framework are not directly exposed as endpoints. The PayloadSchemaRegistry creates the following default validators for tags that can contain property and bean-property tags:

XML Tag Default Validator Class

validator ValidatorManager

bean-validator ValidatorManager

switch SwitchingUpdatingValidator

case ValidatorManager

Note that these validators can be overridden by sub-classes that include customized logic to handle creating target items, adding additional constraints, or other similar actions.

128 5 Working with the Payload Schema Exposing Sub-Properties

You may want to use a schema or bean-property tag to expose the simple properties of a sub-property as its own. For example, you might want the schema for OrderImpl to expose simple properties from its repositoryItem sub-property.

Use the include-simple-properties-from tag to generate property tags with their internal- property-name attribute set. In the following example, the property elements are generated for the simple properties of OrderImpl, following property elements for the simple properties of the order repository item:

How to Validate Dynamic Bean Sub-Properties

The ValidatorManager class validates a dynamic bean’s sub-properties. Note that you do not have to extend the ValidationManager class to implement inter-property validation. The parent source and target beans are available on the ValidatorContext, so a validator can find its parent and check for a given property.

You may also want to update the SwitchingUpdatingValidator to handle creation of per-value target beans or repository items.

Working with Sub-Classes and Repository Sub-Types

The payloadSchema.xml also supports the switch and the case tags. These tags provide support for separate schemas that are based upon a property value, and allow you to work with sub-classes or repository subtypes. For example:

5 Working with the Payload Schema 129 Separating Schemas

You can use the switch tags to define bean or item-descriptor tags, which allows you to specify sub- classes or repository item subtypes. These switch tags inherit the include-all-simple setting from their containing schema or bean-property tag. The following example includes all of the simple properties of TestBean in the top-level validator, and the ‘a’ and ‘b’ cases include all of the additional simple properties of SubClassAOfTestBean and SubClassBOfTestBean:

When the include-all-simple attribute is inherited from the containing schema or bean-property, simple properties that the schema or bean-property do not already mention are included.

In the above example, the simple properties of TestBean would be included at the top level and those simple properties would not be repeated for the two case tags.

When the schema or bean-property tag references a repository and the include-all-simple attribute is set to true, subtypes are automatically generated, supporting automatic validation of dynamically added subtypes and their simple properties. For example:

In preceding example, testItemBase is the base item descriptor and testItemDynType1 and testItemDynType2 are the dynamic subtypes with dynType1Boolean and dynType2StringOne corresponding to dynamic properties.

The switch tag also supports an option-to-subtype-map attribute. This attribute specifies the Nucleus path to a map that maps an option value to a RepositoryItemDescriptor, class or string containing the name of a class. The option-to-subtype-map also creates automatic case tags for subclasses, and can be useful where such configurations already exist in Nucleus. For example:

130 5 Working with the Payload Schema ...

Validating Maps and Collections

There are two ways that the framework allows you to validate maps and collections.

You can represent validations by using explicit pseudo-properties. Maps use the key and value pseudo- properties while collections use the element pseudo-property. An explicit usage where the value of the map entries must be a string no longer than 10 characters may be similar to the following example:

You can also have containers of sub-beans. Note that in this example, you may need a class or item- descriptor tag in the inner bean-property tag if introspection fails:

The implicit approach assumes nesting. For a map, the equivalent implicit XML may resemble:

Note that when using the implicit containment XML, you cannot specify the key validator for maps, and you cannot override the default validator class. As such, it is recommended that you use the explicit form whenever possible.

The following container validators are available, whether using implicit or explicit pseudo-properties:

5 Working with the Payload Schema 131 Container Class Default Validator Class

java.util.Map MapUpdatingValidator

java.util.Collection, arrays UnorderedCollectionUpdatingValidator

Creating Custom Map Validators

The MapUpdatingValidator can be extended using a MapUpdateHelper, configuring it as the default MapUpdatingValidator instance using a param tag. You can do this using the class: or nucleus: prefix, depending on whether the Helper should be a new instance or one found from Nucleus.

The UnorderedCollectionUpdatingValidator and its child, the ListUpdatingValidator, support a CollectionUpdateHelper. These helpers contain methods for creating a target container, finding a corresponding target item or creating a target item. This allows you to update a target repository item or bean container that requires the use of Nucleus-based manager or if you need custom logic to find an existing corresponding item.

Wrapping a Validator

In some instances it may be best to wrap a validator and not create a subclass. The payload schema supports the wrapping-validator-instance attribute that allow you to wrap a validator. It contains the following wrappers that can serve as a base class:

• validatorWrapperImpl – Implements the Validator and ValidatorWrapper interfaces and delegates to the wrapped validator

• UpdatingValidatorWrapperImpl – Extends validatorWrapperImpl and adds support for the UpdatingValidator interface

Note that you should only wrap UpdatingValidator with wrappers that also implement UpdatingValidator. If you do not, the updatedBeanValue method will never be called on the wrapped UpdatingValidator, and will bypass any custom logic that may be contained within the method.

Validating Inter-Related Properties

You can validate properties that are interrelated to ensure that they are consistent. To do this, use the PropertyGatherer validator, which can gather up named properties in a Map and then invokes a configured BeanValidator for inter-property validation. For example, this AllSameValuesValidator will have its validateBean method invoked with the pBean parameter being Map containing entries for StringOne and StringTwo:

132 5 Working with the Payload Schema

The PropertyGatherer has other properties that can be configured using the param tag:

Property Description

continueDespiteIndividualErrors A Boolean property that defaults to false and prevents inter-property validation from occurring if one of the individual property validators flags a validation error

propertiesValidator A BeanValidator property that specifies the BeanValidator to be invoked for inter-property validation. Note that validataeBean is the only bean to be invoked for this BeanValidator.

maxDepth and minDepth Integer properties that represent the maximum and minimum ValidatorContext ancestor stack depth at which property values are collected. If property values are not being collected as expected, turn on loggingDebug on the PropertyGatherers. The default for these properties is set to 1.

remappedPropertyNames A Map property that can be configured to store one encountered property name to a different map key.

saveMultipleValues A Boolean property that saves multiple values for the same property name when set to true. In this case, the map passed to the propertiesValidator BeanValidator is a Map > where the value is a list of values seen for that property name. By default, this property is set to false.

5 Working with the Payload Schema 133 134 5 Working with the Payload Schema Part II. Oracle Commerce Platform REST MVC Web Services

The REST MVC framework leverages existing droplets, form handlers and components, creating an API that can be extended easily. You can build REST services in a modular format by combining model producers. URLs are explicitly defined in a registry, making access to REST URLs secure. Using access controllers defined in your applications, you can restrict who or under what conditions REST URLs can be accessed. All properties that are used in REST calls can be filtered, which reduces the amount of information that must be transferred.

This section describes the Model View Controller (MVC) architecture and framework in detail, and provides examples of possible customizations. It contains the following information:

• Installing and Configuring the REST MVC Server (page 137) provides information on installing the REST server using CIM, and configuring various components, such as debugging and enabling desired services

• The REST MVC Definition Framework (page 139) describes the architecture of the REST MVC API, including the file definitions and components that make up the framework. This section also has instructions on creating a new REST service

• External REST MVC Service Call Examples (page 183) provides detailed information on existing customer-facing REST service calls, with examples and component configuration information

• Internal REST MVC Service Call Examples (page 247) provides detailed information on existing internal, or agent-facing REST service calls. This section is intended for users of Oracle Commerce Service Center to REST services for call center agents

6 Installing and Configuring the REST MVC Server

The following section describes the installation and configuration of the REST server.

Installing the REST MVC Module

The REST MVC framework is contained within the REST module. Install the REST MVC module using the Oracle Commerce Platform Configuration and Installation Manager (CIM). When you run the CIM script, the REST module will be added to your production and agent server instances. For additional information on installing Oracle Commerce Platform modules, refer to the Platform Installation and Configuration Guide.

Enabling REST Services

For security reasons, when you install the REST MVC module, none of the REST services are enabled. To enable a service, you must register the actor-chain in your /localconfig/atg/rest/ registry/ActorChainRestRegistry.properties file. Any actor-chain that will be used must be registered. This includes success and error URL actor-chains. Nested actor-chains that are accessed only through other actors need not be registered. For detailed information on actor-chains, refer to The REST MVC Definition Framework (page 139) section.

Note: Oracle Commerce Reference Store registers a number of REST actors during installation. Refer to the Commerce Reference Store Installation and Configuration Guide.

Note: When you add the actor-chain, you should add it to your /localconfig directory, or to your customization directory.

To register an actor-chain:

1. Create the ActorChainRestRegistry.properties file in your local directory.

2. Add the actor-chain. The following example adds three actor-chains: the login chain, as well as the Success and Error URL chains.

//home/localconfig/atg/rest/registry/ActorChainRestRegistry.properties

6 Installing and Configuring the REST MVC Server 137 registeredUrls+=\ /atg/userprofiling/ProfileActor/login,\ /atg/userprofiling/ProfileActor/login-success,\ /atg/userprofiling/ProfileActor/login-error,\

Note that if you enter only the actor, the default actor-chain will be used.

3. Save the file.

Note: If you do not register the actor-chain, when the actor-chain is used in a REST Web Service, an error will occur.

Using Dynamo Session Confirmation Numbers

When using REST services, you want to prevent the processing of malicious site requests. Oracle Commerce Platform uses a request parameter _dynSessConf, which contains a session confirmation number, to verify that a request is legitimate. For further information on session confirmation numbers, and the warnings that occur if the request is not legitimate, refer to the DAFDropletEventServlet section of the Platform Programming Guide.

For Development Purposes Only: The Dynamo session confirmation numbers are required to ensure that your REST sessions remain secure. During your development process, you may not want to use these numbers because session confirmation numbers must be passed in for all form and component actors that set property values. Should you elect to turn them off for development, you must turn them back on when you put your code into production. To disable the session confirmation numbers, set the enforceSessionConfirmation parameter in your local /atg/dynamo/service /actor/Configuration.properties file to false. For additional information, refer to The Form Element (page 152) and The Component Element (page 145) sections. For information on getting the Dynamo session confirmation number, refer to the Getting the Session Confirmation Number (page 184) section.

138 6 Installing and Configuring the REST MVC Server 7 The REST MVC Definition Framework

REST MVC Web Services allow you to use HTTP requests to work with any Oracle Commerce Platform application. These services provide you with ways to do things such as protect user logins, send data to forms using mobile applications, or retrieve data from search results. Multiple controllers generate a model map that can be filtered, and the output from these controllers is used to generate a JSON or XML response.

The REST MVC API can be extended or customized as needed. The following information describes the components of the API, and provide examples that may be useful when creating custom elements for your environment.

Architecture Overview

When you initiate a REST MVC service, you send a URL. This URL must be explicitly defined and registered with the REST MVC Services. If registered, as outlined in the Enabling REST Services (page 137) section, the URL references controllers, which are known as actors. Each actor, which is configured using XML definition files, interfaces with a resource, such as a JSP page, a form handler, a servlet bean, a Nucleus component or another chain of actors, or actor-chains.

These actors generate a ModelMap, which can be filtered and transformed as necessary. The ModelMap is a map of maps that is populated by actors. The response that is rendered is based on the content that the ModelMap has generated. ModelMap instances are created by the ModelMapFactory.

Each time that an actor is invoked, an ActorContext is passed into the actor. An ActorContext, which is created by an ActorContextFactory, is a map of attributes that are relevant to the context in which an actor is involved.

REST MVC resolves Nucleus components using the ActorChainService, which uses an XML definition file to define both the chains of actors to execute, and the order in which they must be executed.

Once all the actors have generated their model data, bean filters are applied to the data. Then the response generator uses the ModelMap to generate a JSON or XML response.

REST MVC Service Flow Example

To understand how the REST MVC processes work, imagine that a customer would like to add a single item from a catalog to their shopping cart. When the customer, or client REST service, initiates the REST call, the following occurs:

7 The REST MVC Definition Framework 139 1. The REST Service uses a URL that begins with /rest/model and has been registered with the ActorChainRestRegistry service. In this example, the URL is:

/rest/model/atg/commerce/order/purchase/CartModifierActor/addItemToOrder

This URL contains not only the CartModifierActor Nucleus component, but the addItemToOrder actor- chain.

The REST Service also verifies the user’s access using the AccessControllerService.

2. The REST Service initializes the actor context from the REST control parameters and the URL. The actor- context is then passed to the ActorChainService. Because the addItemToOrder actor-chain calls /atg/ commerce/order/purchase/ CartModifierFormHandler, a formActor is invoked. The /atg/commerce/order/ShoppingCart component is invoked by the componentActor. Refer to the XML Definition Elements (page 141) section for information on actors and actor-chains.

3. Once all of the actors have provided the data, the ModelMap is filtered with BeanFilters initiated by the BeanFilterService. This process modifies the data in the ModelMap. Refer to Bean Filtering (page 169) for additional information.

4. After the filters have been applied to the ModelMap, the ResponseGenerator transforms the ModelMap into the response, which is configured to be a JSON or XML response. The response is then sent back to the client. Refer to the Configuring REST MVC Output (page 177) for information on configuring default response formats.

The following diagram shows the flow of the REST MVC Service call:

Actor Types

The REST MVC API’s modular and extensible functionality is based on actors, which uses a number of different types of actors to perform a variety of functions. The atg.service.actor.Actor interface contains the

140 7 The REST MVC Definition Framework following actor types that perform specific actions or provide configurations. For detailed information on any of these classes, refer to the ATG Platform API Reference.

• Component Actor – Use this actor to set component property values or invoke methods on a component, or to read component property values

• Droplet Actor – Use this actor when you want to invoke droplets and output data from the droplet to the ModelMap. Inputs are mapped to the droplet input parameter. Other types of actors can be nested in the oparam parameter of a DropletActor

• Form Actor – Use this actor to set up form handler inputs and submit a form

• JSP Actor – This actor invokes a JSP page and adds the JSP response or JSP-defined variables to the ModelMap

• Nested Actor – These actors allow you to invoke actor-chains from within other actor-chains, helping to define modular units of work that can be combined and extended

• Variable Actor – The VarActor enables you to set variables in the actor context

Request URLs

Oracle Commerce Platform REST MVC requests use a /rest/model URL to process requests against the actor framework. The general format for a REST MVC URL is:

http://host:port/rest/model/actor_chain_component/tail

The format variables are:

• host – The name of the REST server

• port – (Optional) The port from which users access the REST services

• actor_chain_component – The Nucleus path for a Nucleus component that implements the actor-chain interface

• tail – (Optional) Any attribute that can be processed by a URIProcessor. For actors, the tail is usually the chain-id. If the tail is omitted, the default actor-chain defined for the actor_chain_component is used.

A typical request may be similar to the following call that adds an item to a shopping cart:

http://rest.example.com:8280/rest/model/atg/commerce/order/purchase/ CartModifierActor/addItemtoOrder

Refer to the External REST MVC Service Call Examples (page 183) and Internal REST MVC Service Call Examples (page 247) sections to see examples of request URLs in cURL.

XML Definition Elements

The ActorChain.xsd XML schema defines the data structures used within the REST MVC API. The schema defines XML files that contain actor-template definitions that, in turn, point to Nucleus components. Each of the components within the schema identifies and performs a specific action and generates a ModelMap.

7 The REST MVC Definition Framework 141 The schema contains the following objects:

REST XML Schema Diagram

The Actor-Template Element

The actor-template, which is the root element of all actor elements, contains one or more actor-chain elements. This element uses the default-chain-id attribute, which is the default chain that will be executed if there is no chain-id found in the request. If no default-chain is defined the first chain is executed.

The following is an example of an actor-template that contains a single actor-chain:

142 7 The REST MVC Definition Framework

The Actor-Chain Element

The second element defined in the schema is the actor-chain, which identifies a series of actors to execute. The actor-chain can contain one or more actors that include input and/or output elements.

An actor-chain contains the following:

Attribute/Elements Description

id Required. Defines the chain-id. This attribute is used during the XML combination process, and identifies the chain to execute.

transaction Provides transaction demarcation for the chain. For information on the supported transaction demarcation types, refer to the Repository Guide. The default value is TX_SUPPORTS.

Note: If you are creating REST MVC Service calls it is important to note that Profile and Order-related form handlers require that the transaction be TX_SUPPORTS and not TX_REQUIRED, as the transaction must be initiated in the form handler and not be defined prior.

actors An actor-chain can have one or more actors that include input and/or output elements.

You can use the Dynamo Server Admin to review actors, actor-chains and their attributes.

The Actor Element

When necessary, an actor-chain can invoke a child actor-chain. The actor element passes information from that parent actor to a child actor, and executes the child actor-chain. Note that you must explicitly define the values that will be passed from the parent to the child actor-chain.

Actor elements contain the following:

Attribute/Element Description

id Required. The actor ID. This attribute is used for actor ordering.

7 The REST MVC Definition Framework 143 Attribute/Element Description

name Required. The Nucleus path of the actor component to invoke.

return-model-var Provides the variable name of the child actor-chain returned by the ModelMap. The ModelMap that is returned from the child actor-chain can be accessed using this variable name.

chain-id The chain ID of the actor component to be executed. If the chain-id is not specified, the default chain will be executed.

depends This element defines actors that must be executed prior to the execution of the current actor. There can be multiple depends elements associated with an actor.

depends-if- This element defines actors that, if present, must be executed prior to the execution present of the current actor. There can be multiple depends-if-present elements associated with an actor.

input This element defines each actor’s input. Actors can have multiple input elements.

output This element defines each actor’s output. Output elements create a map entry in a ModelMap. Actors can have multiple output elements.

The ActorContext and ModelMap of the parent actor are not passed to the child actor. The following example shows how information can be passed from a child actor-chain to a parent actor-chain. Note that request parameters do not need to be passed in explicitly as inputs; you can pass in their variables:

In the above example, the parent actor-chain contains a quantity ModelMap entry. Map entries are based upon the child actor-chain. For information on working with implicit objects, which can be used in any chain, refer to the Working with Implicit Objects (page 166) section.

To pass the entire child ModelMap back to the parent and not have it nested under another variable name, use the add-map-children="true" in the output element to copy the child ModelMap keys to the parent ModelMap.

144 7 The REST MVC Definition Framework The Component Element

The component element executes a method within a component, or sets properties and outputs values from a component to the output ModelMap.

The component element contains the following:

Attribute/Element Description

name Required. Identifies the Nucleus path of the component.

id Required. This attribute defines the actor ID, and is used for actor ordering.

method Identifies the name of the method to be executed. Use only when invoking a method.

component-var Provides a variable name that accesses the component’s properties.

method-return-var Identifies the variable name that accesses the method invocation’s returned value.

set-property- By default, all set-property values require session confirmation numbers. This requires-session- property is set to true by default. confirmation

invoke-method- By default, all method calls require session confirmation numbers. This property requires-session- is set to true by default. confirmation

depends This element defines actors that must be executed prior to the execution of the current actor. There can be multiple depends elements associated with an actor.

depends-if-present This element defines actors that, if present, must be executed prior to the execution of the current actor. There can be multiple depends-if-present elements associated with an actor

input This element defines each actor’s input. Actors can have multiple input elements.

output This element defines each actor’s output. Output elements create a map entry in a ModelMap. Actors can have multiple output elements.

Example: Resolving a Component

The following example resolves a component that sends output from the properties of the component to a ModelMap. In this example, the component class instance is saved in the shoppingCart variable of the ActorContext.

7 The REST MVC Definition Framework 145

Note that you can reference a component without having to invoke a component actor. The following example shows how you would resolve the orderID component in-line. This works for components that are referenced only once; if you plan to reference the same component multiple times, it is best to define the variable, as in the above example:

Example: Executing a Method

You can also use the component element to execute a method on a Nucleus component. The following example shows how the return value is stored in the orderStatus variable and stores the method return value into the ModelMap under the orderStatus key.

Example: Finding a Method using a String Array

You can also use the component element to find a method by providing a string array. For example, to find a method that contains a string array, such as atg.commerce.order.OrderLookupService. getOrderCount(String,String[]), you must provide the String and String[] class-names. In the following example, the String[] is passed in as [Ljava.lang.String; and passed to the getOrderCount method.

Example: Finding a Method Using an Interface

You can use the component element to find a method if the method has an interface signature. For example, the atg.commerce.pricing.PricingTools.priceOrderSubtotal(Order, Locale, RepositoryItem, Map) method needs the interface class-names:

146 7 The REST MVC Definition Framework value="${nucleus['/atg/userprofiling/Profile']}"/>

Example: Finding a Method using Generics

If you are using a method that contains a generic class or interface, use the component element to provide the necessary type parameters. For example, to find the atg.multisite.SiteGroupManager. filterInactiveSites (Collection) method, you would create the following:

Example: Using Primitives When Executing Methods

The REST MVC framework accepts the use of primitive data types. The following example shows how a Boolean primitive data type is identified using a primitive type name in class-name:

Example: Using Primitive Arrays When Executing Methods

You can use an array of primitive data types to return method information. The following example shows how a Boolean primitive array is used:

Note that the following class-name values are used to identify primitive array types:

Primitive Data Array Type Class-Name Value

char [C For example, class-name="[C"

short [S For example, class-name="[S"

double [D For example, class-name="[D"

long [J For example, class-name="[J"

7 The REST MVC Definition Framework 147 Primitive Data Array Type Class-Name Value

boolean [Z For example, class-name="[Z"

byte [B For example, class-name="[B"

float [F For example, class-name="[F"

int [I For example, class-name="[I"

Example: Passing Multiple Arguments

To pass more than one argument into a method, you must specify the index attribute on the inputs so that the input arguments for the method are ordered. For complex object types, you may need to convert the string value to an object by specifying a PropertyEditor or TagConverter. Any registered property manager can be used to convert inputs into complex object types so that they may pass method parameters. The system attempts to coerce the input value to the correct type of object based on the method’s expected input type. If the method is overloaded, you may need to specify the PropertyEditor to disambiguate between the overloaded methods. Also, it is usually necessary to define a PropertyEditor for collections of complex objects since the type of objects contained in the collection cannot be determined at run time.

Example: Setting Property Values

The following is an example of setting property values on a Nucleus component. The ComponentActor sets the listId property value and outputs the currentList property value:

Example: Disabling Component Actor Dynamo Session Confirmation Numbers

Important: The following information is for use within development environments only. Dynamo session confirmation numbers provide session security and must be enabled in production environments.

148 7 The REST MVC Definition Framework By default ComponentActors use Dynamo session confirmation numbers, _dynSessConf, for method calls and setting property values. However, session confirmation numbers are not required for calls such as outputting properties of a component, a JSPActor or a DropletActor. For detailed information on Dynamo Session Confirmation Numbers, refer to the Platform Programming Guide.

The following example shows how to disable session confirmation numbers for method calls:

The following example shows how to disable set property values:

Note that the /atg/dynamo/service/actor/Configuration.enforceSessionConfirmation flag can be used to disable this requirement during development. It is recommended that this flag is disabled only in your development environment.

The Droplet Element

The droplet element provides meta-data for Oracle Commerce Platform servlet beans. The DropletActor executes the servlet beans and adds object values to the ModelMap based on the meta-data.

The droplet element contains the following:

Attribute/Element Description

name Required. This is the Nucleus path of the Oracle Commerce Platform servlet bean.

id Required. This attribute defines the actor ID, and is used for actor ordering.

var Exposes the current frame of the Dynamo param stack as an attribute.

oparam Droplets may have one-to-many oparams.

depends This element defines actors that must be executed prior to the execution of the current actor. There can be multiple depends elements associated with an actor.

7 The REST MVC Definition Framework 149 Attribute/Element Description

depends-if- This element defines actors that, if present, must be executed prior to the execution present of the current actor. There can be multiple depends-if-present elements associated with an actor.

input This element defines each actor’s input. Actors can have multiple input elements.

output This element defines each actor’s output. output elements create a map entry in a ModelMap. Actors can have multiple output elements.

DropletActors can be nested with all types of actors using the oparam element.

The Oparam Element

The oparam element can be used within the droplet element to identify names of droplet oparams. This element contains the following:

Attribute/Element Description

name Required. The name of the oparam.

actors The oparam element can have one or more actors that include output or set-var elements.

The following is an example of how to access droplet properties:

...

The following is an example of a droplet and oparam element:

150 7 The REST MVC Definition Framework

Example: Nesting Droplet Elements

It is possible to nest droplet elements. For example:

Because each actor-chain has its own ActorContext and ModelMap, you can use the input and output of nested actors to pass inputs into a nested ActorContext and return outputs from nested ModelMaps. In the following example, the add-map-children attribute copies the properties in the nested ModelMap to the outer ModelMap:

Note that you should make your actors accessible from either the client, using the request parameter, or from the nested actor, using the variable. Clients pass actors as param, for example param.orderId. Nested actors pass their variables as ActorContext variables. You must configure your input to look for both param and ActorContex variables. For example:

Example: Evaluating Servlet Beans

When working in a JSP page, you can identify a bean parameter. For example:

7 The REST MVC Definition Framework 151

There is no bean attribute available for DropletActors. Instead, you can retrieve servlet beans using the $nucleus syntax. For example:

Example: Setting a Variable Within an oparam

The set-var element sets a variable as an attribute. For additional information on this element, refer to The Set Variable Element (page 163) section. This example shows how to set a set a variable named sites within an oparam element:

You could then use the variable in the following way:

The Form Element

The form element provides meta-data that the FormActor uses when it executes form handlers and sends output data to the ModelMap.

The form element contains the following:

Attribute/Element Description

name Required. This is the Nucleus path of the form handler.

152 7 The REST MVC Definition Framework Attribute/Element Description

handle Required. The name of the handle method to execute.

id Required. This attribute defines the actor ID, and is used for actor ordering.

var The variable name that can access form handler properties and exceptions.

requires-session- By default, all form handler submissions require session confirmation numbers. confirmation This property is set to true by default.

depends This element defines actors that must be executed prior to the execution of the current actor. There can be multiple depends elements associated with an actor.

depends-if-present This element defines actors that, if present, must be executed prior to the execution of the current actor. There can be multiple depends-if- present elements associated with an actor.

input This element defines each actor’s input. Actors can have multiple input elements. Note that all input data uses the xxsFiltering parameter to prevent XXS attacks. For additional information on xxsFiltering, refer to the Platform Programming Guide.

output This element defines each actor’s output. Output elements create a map entry in a ModelMap. Actors can have multiple output elements.

use-forwards By default, most form handler submissions use forwards. It is recommended that you use forwards instead of redirects. To enable redirects, you must set this attribute to false.

The following is an example of a form element that adds a single item to an order:

By default, all form elements define success and error chains. You can use XML combining to modify the default behavior of the chains. The following example shows what you would create to make a combined file that modifies the addItemToOrder-success chain:

The success or error URL, if present, is generally a REST URL that references another actor that generates the next page. Success and error URL are specified by the actor definition. Your success and error URLs should start with /model/atg if you are forwarding. If you are doing a redirect, start your URLs with /rest/model/atg. The FormActor uses the use-forward attribute. Note that it is better to use forwarding than redirection.

Form Handler Arrays

When using a JSP form, you can set the individual form array elements. For example, if you wanted to review each user and set their input field to be first name and last name:

154 7 The REST MVC Definition Framework When using a FormActor, use the priority attribute to initialize input array size before the array is populated if you are passing input arrays. For example:

To set individual elements, use the [ ] syntax, and pass in array-size attributes for each input array element.

When a form actor processes an input tag that contains [ ] in the name string, the input is treated as an input array. Based upon the array-size, the FormActor adds the index between the brackets, for example, [0] or [Index]. It then adds the form input tag to the form tag. Both the input name and value can use the [ ] syntax, with the index substituted for their attribute values.

In the following example, the first input tag value uses an array property and the second input tag passes in a scalar value:

or

Use tag converters to convert array inputs:

Example: Disabling Form Actor Dynamo Session Confirmation Numbers

Important: The following information is for use within development environments only. Dynamo session confirmation numbers provide session security and must be enabled in production environments.

By default, FormActors use Dynamo Session Confirmation Numbers, _dynSessConf, for method calls and setting property values. However, session confirmation numbers are not required for calls such as outputting properties of a component, a JSPActor, or a DropletActor. For detailed information on Dynamo Session Confirmation Numbers, refer to the Platform Programming Guide.

The following example shows how to disable session confirmation numbers for a FormActor:

7 The REST MVC Definition Framework 155

Note that the /atg/dynamo/service/actor/Configuration.enforceSessionConfirmation flag can also be used to disable this requirement during development. Again, it is recommended that this flag is disabled only in your development environment.

Example: Form Error Handling

When a form handler encounters an error, it typically processes the error by adding a DropletException to the form handler and forwarding to an error URL. The handle method returns false, indicating that a forward or redirect has occurred, and the actor-chain immediately terminates. Success or error URLS can be supplied to the form handler using the input element. If the error URL has been defined to use another actor-chain, a new ModelMap and ActorContext is created to issue the response.

For example, to invoke the cartModifierActor to pass an error URL that will re-render the Add Item to Order page if there is an error:

# /atg/commerce/order/purchase/cartModifierActor

156 7 The REST MVC Definition Framework

If the CartModifierFormHandler encounters an error, the form handler identifies a formError and forwards to the AddItemToOrderErrorURL property in the CartModifierFormHandler.

If there is no error, the detailed view of the order is displayed.

Error Code Response Types

Note that there are two types of error message patterns provided as a response. For Oracle Commerce Core Commerce-based form handlers, the error message response is similar to the following:

{ "formError":true, "formExceptions":[{ "localizedMessage":"There was an error updating this order", "cause":null, }], "concurrentUpdate":false }

For Oracle Commerce Platform-based form handlers, the form handler response is similar to the following:

{"formError":true, "formExceptions":[{"localizedMessage":"The password and login do not match","errorCode":"invalidPassword"}]}

The JSP Element

The jsp element executes a JSP page and sends output object values to the output ModelMap. JSPActors typically write to variables that are mapped by the JSPActor definition.

Note: If possible, use DropletActors instead of JSPActors, as DropletActors are more modular and do not require configuring a WAR file.

The jsp element contains the following:

7 The REST MVC Definition Framework 157 Attribute Description

id Required. This attribute defines the actor ID, and is used for actor ordering.

page Required. This is the absolute path of the JSP URL, excluding the context root.

context Required. The context root of the JSP URL.

response-var The value that is written to the HTTP response by the JSP page. You can reference this attribute in an output element to add the response to the output model. This is useful for returning HTML snippets to render.

depends This element defines actors that must be executed prior to the execution of the current actor. There can be multiple depends elements associated with an actor.

depends-if- This element defines actors that, if present, must be executed prior to the execution present of the current actor. There can be multiple depends-if-present elements associated with an actor.

input This element defines each actor’s input. Actors can have multiple input elements.

output This element defines each actor’s output. Output elements create a map entry in a ModelMap. Actors can have multiple output elements.

The following is an example of a jsp element:

The following is an example of the JSP that the element invokes:

<%-- Return available shipping methods, optionally with prices - Optional parameters: getPrices if true, will return prices with the shipping methods - Model output: shippingMethods currencyCode --%>

158 7 The REST MVC Definition Framework <%-Determine shipping price for the current shipping method --%>

<%-Add the currencyCode if returning prices --%>

Example: HTML Output

JSPActors can output HTML snippets to pass to the client using the response-var property. For example:

7 The REST MVC Definition Framework 159 The Output Element

The output element defines a map entry in a ModelMap. Once the actors are executed, the output values are evaluated and added to the ModelMap based on the name attribute.

The output element contains the following:

Attribute/Element Description

id Required. This attribute defines the actor ID, and is used for actor ordering.

name Defines the name of the map entry. The value of this attribute can be static, or a dynamic EL expression. For additional information on ActorContext variables, refer to the Working with Implicit Objects (page 166) section.

value Defines the value of the map entry. The value of this attribute can be static, or a dynamic EL expression. For additional information on ActorContext variables, refer to the Working with Implicit Objects (page 166) section.

filter-id Defines the bean filter that will be applied when the value object is filtered using the BeanFilterService. Note that the filter-id attribute on a bean filter property will override this filter-id attribute.

embed-for-mime-type Identifies if the value of the object should be embedded within the server response. For example, if the object is a JSON string, and it should be embedded in the JSON response, set the embedded mime attribute to application/ json. If the ResponseGenerator has been set to output as JSON, the string is added to the JSON response. If the EmbeddedMimeType does not match the response mime type, (for example, the response mime type is set to XML), the JSON response will be encoded as a string inside the XML response.

add-map-children This attribute, when set to true, copies the key/value pairs of a map value into the ModelMap. The value must be a map. This attribute is often used to pass the values of a child ModelMap to a parent ModelMap in a nested actor call.

depends This element defines actors that must be executed prior to the execution of the current actor. There can be multiple depends elements associated with an actor.

depends-if-present This element defines actors that, if present, must be executed prior to the execution of the current actor. There can be multiple depends-if-present elements associated with an actor.

message The output tag supports internationalized messages that are added to the ModelMap.

The following is an example of an output element:

160 7 The REST MVC Definition Framework The filter-id identifies the filter for the BeanFilterService to apply. Refer to the Bean Filtering (page 169) section for further information.

The output tag supports localized message tags, which add internationalized messages to the ModelMap. By default, all messages are localized based upon the current user’s locale, however, the locale can be passed in using the message tag.

The message element contains the following:

Attribute/Element Description

id Required. This attribute defines the message ID.

locale-code The locale that will be used to localize the message, for example, en_US. If not available, the system will use the ServletUtil.userLocale setting.

bundle Identifies the resource bundle that contains the resource key.

key The resource key identified by the resource bundle.

message-param If message parameters are required during the resource lookup, you can use the attributes used by this element:

id – The ID of the message param. value – The value to pass.

The following is an example of an output element with a message element. Messages are, by default, localized using the user’s locale, however, you can set the locale using the message tag:

The output from the example above would be:

{"error": { "messageCode" : "PRODUCT_NOT_IN_CURRENT_CATALOG", "localizedMessage" : "Product xprod2099 is not defined in the current catalog" }}

The Input Element

The input element defines actor inputs and is used to pass values to the actors. The input element is used for all actor types.

7 The REST MVC Definition Framework 161 The input element contains the following:

Attribute/Element Description

name Required. Defines the name of the input element.

value Defines the value of the input element.

property-editor In certain actors, a property editor is used to modify the JSON or XML value into a complex object. Refer to The Component Element (page 145) section for information on working with property editors.

tag-converter Use this element to coerce the JSON or XML value into a complex object using the class-name attribute.

priority This attribute determines the order of the actor inputs.

array-size Used only by the FormActor, this attribute is used to support form handler array support. Refer to The Form Element (page 152) section for additional information.

index Used only by the ComponentActor in a method call, this attribute defines the order of the method’s parameters. Refer to The Component Element (page 145) section for additional information on this attribute.

The input element uses the xxsFiltering parameter to filter all input data. By default, this parameter is set to true. For additional information on xxsFiltering, refer to the Filtering Requests to Prevent Cross-Site Attacks section in the Platform Programming Guide.

The following is an example of an input element:

The Depends and Depends-If-Present Element

The depends element defines actors that must be executed before another actor can run. If the actor that must be run first cannot be found, an error will occur, but the current actor will still execute. This element allows you to order actors in an actor-chain when the actors have been XML combined. If you do not specify a depends attribute, actors will be executed in the order in which they appear in the definition file.

The depends-if-present element is similar to the depends element, in that it specifies an actor that must run prior to the current actor’s execution. However, in the depends-if-present element, the specified actor is not required in the actor-chain. This element is best used when an actor in the actor-chain may not be available. The element allows you to identify actor order, but will not generate an error if the requirements are not met.

Both the depends and the depends-if-present elements use the required id attribute, which identifies the ID of the actor that must run before the current actor.

162 7 The REST MVC Definition Framework Ordering Actors

The depends and the depends-if-present elements control actor-chain ordering. If your actors are defined in a single file, the order in which you define your actors is the way they will be executed. However, if you have actors that you have defined in various overriding layers and you want to change their order, you must identify the order using the depends and depends-if-present elements. If actor order is not important, these elements are not required in the actor definition. For example, if you have a base configuration file for shipping groups:

The file that you would create in your local configuration directory to order actors would contain:

In this example, the ShippingGroupDroplet initializes the shipping group information. However, because it must be invoked before running the ApplicableShippingGroups droplet, you must define a depends element, indicating that the ShippingGroupDroplet should be executed first.

The Set Variable Element

The set-var element sets a variable as an attribute in the actor context within the scope of the actor-chain. This element can be used only within the input, output, or oparam elements.

7 The REST MVC Definition Framework 163 This element contains the following:

Attribute/Element Description

id Required. The actor ID. This attribute is used for actor ordering.

name Required. The name of the map entry. This can be a static or dynamic EL expression.

value This attribute defines the value of the map entry, and can be a static or dynamic EL expression.

depends This element defines actors that must be executed prior to the execution of the current actor. There can be multiple depends elements associated with an actor.

depends-if-present This element defines actors that, if present, must be executed prior to the execution of the current actor. There can be multiple depends-if-present elements associated with an actor.

The following is an example of the set-var element:

In this example, the set-var element sets the environmentChangeState variable in the actor context while executing the first output.

Actor XML Definition File Examples

This section provides a few actor definition examples. Note that to create an ActorChainService component, you must create both a Nucleus component and an XML file that contains the actor-template instance definition. Note that when working with actor definitions, it is best to use XML combination to add your customizations.

Example: Creating an Order Confirmation Actor

The following is an example that creates a ComponentActor that adds a component to the ModelMap. This actor will reference a Nucleus component and an XML file that defines the actor-template.

1. Define the OrderConfirmation component to call the ActorChainService, and then set the definitionFile property value to the appropriate XML file:

/custom/atg/commerce/order/purchase/OrderConfirmation.properties

164 7 The REST MVC Definition Framework $class=atg.service.actor.ActorChainService definitionFiles+=/custom/atg/commerce/orderConfirmationActor.xml

2. Create a orderConfirmationActor XML file that contains the following, where the actor-chain defines a ComponentActor:

/custom/atg/commerce/order/purchase/orderConfirmation.xml

Example: Creating a Shipping Address Actor

The following is an example that creates a Nucleus component and an XML file that defines an actor- template instance that allows you to access shipping address data.

1. Define the Nucleus component and identify the XML file that defines the actor-template:

/custom/atg/commerce/ShippingAddressesActor.properties $class=atg.service.actor.ActorChainService definitionFiles+=/custom/atg/commerce/shippingAddressesActor.xml

2. Create the XML file that creates a shippingAddresses actor-chain:

/custom/atg/commerce/shippingAddressesActor.xml

7 The REST MVC Definition Framework 165

Example: Creating a Profile Form Handler Actor

The following example demonstrates how to create an actor-template with multiple chains. This allows you to define multiple chains in the same XML file. However, it is best to define XML files based on a single functional area.

This example creates a ProfileActor, which contains XML chains for its functional areas. This actor contains profile-related functions such as getting, creating, or deleting a profile, profile address, or credit card. It is best to provide the form handler or any single-service function within an actor, as doing so groups related chains together and reduces the number of Nucleus components that must be defined.

1. To create this actor, define the Nucleus component:

/custom/atg/userprofiling/ProfileActor.properties $class=atg.service.actor.ActorChainService definitionFiles+=/custom/atg/userprofiling/profileActor.xml

2. Create the XML file:

/custom/atg/userprofiling/profileActor.xml ...... ... ... ... ... ...

Working with Implicit Objects

Although it is best to explicitly define objects, the REST framework supports the ability to work with the following defined implicit objects:

166 7 The REST MVC Definition Framework Object Description

atgActorModel Maps the current actor-chain’s modelMap. This does not reference the parent chain’s modelMap.

cookie.name Maps a cookie name to a cookie object.

header.name Maps a header name to a single string value.

headerValues.name Maps a header name to an array of string values.

nucleus Maps a Nucleus component.

objectParam.name Maps a request parameter name to an object value.

param.name Maps a request parameter name to a single string value.

paramValues.name Maps a request parameter name to an array of string values.

request This object maps to the current request.

session This object maps to the user’s session.

Accessing Actor Context Variables

Actor context variables and attributes are available only for the duration of the actor-chain. Each nested actor- chain or child actor-chain is given a new ActorContext and ModelMap, and is unable to reference their parent’s ActorContext and ModelMap. However, all actor variables are added to the ActorContext as attributes, which you can access.

To access ActorContext, request or session attributes, you can map the attribute to a value using the ${order.id} syntax or ${commerceItems[0]} array notation.

For example, you could resolve a Nucleus component using the following EL expression:

${nucleus['/atg/commerce/ShoppingCart'].current}

If a variable name does not start one of the implicit objects listed in the Working with Implicit Objects (page 166) section, the system will look up the variable in the attributes of the ActorContext, then in the attributes of the request and finally in the attributes of the session. Note that you should have a separate actor context per actor-chain.

When working with a JSP page and JSPActors, the JSP c:set tag saves the variable in a request or session attribute. The attributes that are set using the c:set tag are accessible in the actor definition and can be referenced in an output element to include in the ModelMap.

Working with Maps

When working with parameters for mapping, use the objectParam.name, param.name or paramValues.name inputs.

For example, the following actor-chain definition uses the completeQuoteParameters map string keys and values to obtain quote information using the objectParam object:

7 The REST MVC Definition Framework 167

The output from this call would be the following, which identifies that the REST class-type is a HashMap:

{ "atg-rest-class-type":\"java.util.HashMap\", "atg-rest-values":{ "agentId": \"agent007\", "providerNote": \"Quote good until 11/11/14\", "externalId": \"external001\", "expirationDate": \"2014-11-11 11:00\", "orderAdjustment": \"5.0\", } }

Combining Actor Definitions

You can use XML combining to customize the elements used in REST. The following attributes are used during the XML combining. For additional information on XML combining, refer to the Platform Programming Guide.

Element Match Attribute

actor id

actor-chain id

component id

depends id

depends-if-present id

droplet id

form id

input name

168 7 The REST MVC Definition Framework Element Match Attribute

jsp id

message id

message-param id

oparam name

output id

Bean Filtering

The BeanFilterService filters the properties of a java bean or repository item and converts beans into a map of properties. The BeanFilterService reads XML definition files that define which properties of a Java class or repository item should be included in the filtered view of the object. The XML definitions include ways to remap property names and transform properties.

By default, the BeanFilterService is applied to the ModelMap by the REST MVC framework before generating a JSON or XML response. However, you can filter objects at any time. For example, you can use the BeanFilterService as a ComponentActor to filter a repository item before adding it to the ModelMap. This converts the repository item into a map of primitive objects:

There are two types of bean filters, those for repository items and those for Java bean classes. By using the ComponentActor, you can add a component to the ModelMap, which can then be filtered by the class that the component implements. For example:

This allows the Profile class to filter the components:

7 The REST MVC Definition Framework 169

Bean filters combine filter definitions from all classes or interfaces for an object using the filter-id property. You can also include other bean filters within a bean filter by using the include-filter attribute.

It is best to define a filter for every object, so that you can control its output. Note that if an object has no filters defined, it will output all properties.

The following XML values are defined by the atg/dtds/beanfilter/beanFiltering_1.0.dtd file:

The Bean Element

The bean element defines a filter for a Java bean class or interface that is in the ModelMap. The filter can be defined at any level of the class and interface hierarchy, and will automatically apply classes and interfaces that have a filter with the same ID. Note that it is best to insert whole objects into the ModelMap and allow bean filtering to control the way that the object is viewed. By defining a filter for every object you can control the output for that object.

The bean element contains the following attributes:

Attribute Description

name The fully qualified package name of the class or interface.

default-filter The ID of the default filter. If no default-filter is defined, the first filter is used.

Available Filters

There are three filters that are primarily used:

• detailed – This filter provides a detailed list

• short – This filter provides a short list

• summary – This filter provides a summary

The following is an example of the ElectronicShippingGroup filter:

170 7 The REST MVC Definition Framework

If the same property is defined in the super and sub-class, the subtype definition overrides the super-type property definition if both reference the same filter ID. If filters are defined on two interfaces that a Java servlet bean implements, but no filter is defined on the classes that the bean implements, the output from both interface filters will be included.

Working with Shared Properties

The bean element allows you to define properties that are shared in one filter and then reference the filter class by super-type. For example, the ElectronicShippingGroup and the HardgoodShippingGroup are similar. However, the ElectronicShippingGroup adds the emailAddress property and does not require the ShippingAddress property. In the following example, the majority of the properties have been moved to the super-type class ShippingGroup. Because the HardgoodShippingGroup contains all of the properties of the based ShippinGroup, it does not need a definition. The ElectronicShippingGroup defines the emailAddress property and hides the unneeded shippingAddress property.

Note: Combining all shipping groups within one filter is not recommended, the following is merely an example. It is best to have a filter defined for each shipping group:

Note that the filter-id attribute of the filter element supersedes any filters that may have been applied in the actor output definition.

Example: Referencing a Filter ID Using an Actor Definition

You can also reference a filter-id by including it within an actor definition. For example, if you wanted to add a summary description to each product contained within a list of product results, apply a specific filter by ID using the actor definition. The following example configures the output element to write to a list of product

172 7 The REST MVC Definition Framework repository item. The shortSummary filter, which was created in the previous example, will output the repository ID, the display name, and thumbnail image.

To avoid having to duplicate property definitions that are shared among different filter descriptions, you can use the include-filter attribute. This includes properties from another filter. For example, the detailed filter could have been written so that the detailed filter includes the summary filter:

In this example, the repositoryId, displayName and thumbnailImage properties are not listed in the detailed filter, but will still be included because the full filter now includes the summary filter using the filter-include attribute. Note that if a property is defined in both of the filters, the detailed filter will override the summary filter when rendering.

The Property Element

The property element identifies which properties of repository items or beans should be included in the response. By default, only properties that are explicitly listed are included.

The property element contains the following attributes:

Attribute Description

name The name that the property will use when sending the response.

7 The REST MVC Definition Framework 173 Attribute Description

target The name of the property that is read from the Java servlet bean or repository. If no target is supplied, the value of the name attribute will be used instead.

property- The Nucleus path of a component that implements the customizer atg.service.filter.bean.PropertyCustomizer interface. Use these attributes to transform properties if needed.

hidden If this property is set to true, the property will be excluded from the response. This property is set to false by default.

filter-id Applies a filter by ID that matches the class of the repository item type of the property value. Note that the filter-id of a bean filter property will override the filter-id attribute of an actor output element. Objects that are properties of this element use this filter-id. For example, if a filter-id is applied to the user repository-item, the same filter-id will be applied to the contact repository-item when filtering the homeAddress property of the user.

Working with Property Customizers

You can transform properties using the property-customizer attribute. For example you could mask a credit card number by creating a maskedCreditCardNumber property:

You can also retrieve other properties using this syntax.

If the target attribute does not start with a $, it will be evaluated as a DynamicBean.getPropertyValue if the object is a DynamicBean. Both item-descriptor and bean elements can use this syntax. Note that you can add to any properties that are returned by default using XML combination.

You can use the RepositoryItemPropertyCustomzier to retrieve repository items or properties of a repository item in a bean filter by looking up the item by ID. The following example retrieves a specific property by specifying the property attribute:

To retrieve the entire repository item, do not specify a property attribute:

174 7 The REST MVC Definition Framework The DottedPropertyNamePropertyCustomizer can be used when you are working with properties that have a dot in their name, such as profile.firstName. For example:

The Attribute Element

The attribute element allows you to identify and pass name and value pair attributes for a property customizer. This element contains the following attributes:

Attribute Description

name The name of the attribute.

value The value of the attribute.

Passing name and value attributes into a property-customizer is similar to passing attributes into a custom repository-descriptor. For example, you can update the maskedCreditCardNumber property that was created in The Property Element (page 173) section to identify the number of digits that are not masked when displaying a credit card number:

By creating this new attribute, when the credit card information is rendered, all but the last four numbers will be masked.

The Repository Element

The repository element defines one or more item-descriptor filters for a repository, and contains the following attributes:

Attribute Description

name The path name to the repository.

item-descriptor The name of the item-descriptor to filter upon. The item-descriptor elements are nested under the repository element so that item-descriptors from the same repository are grouped together in the XML file. If you XML combine any item-descriptor definitions, they are presented together under the repository element in the combined XML.

7 The REST MVC Definition Framework 175 The following is an example of the repository element:

The alias element defines an alternate component path for the repository definition. The name attribute of the alias element defines the path of the repository.

The Item-Descriptor Element

The item-descriptor element filters the properties returned for an item-descriptor placed in the modelMap. It uses the following attributes:

Attribute Description

name The name of the item descriptor.

default-filter The ID of the default filter for this item-descriptor. If you define more than one filter, specify a default filter to avoid errors in the case where no filter is specified in the ModelMap.

The following is an example of the item-descriptor element:

Working with Filters

Use the Dynamo Server Admin to view the filters used in your environment. Select the /atg/dynamo/service/ filter/bean/XmlFilterService to see the filter configuration. Click on a repository or a servlet bean to view filter information:

176 7 The REST MVC Definition Framework Note that you cannot use the Dynamo Server Admin to modify these filters. To make modifications to these filters, modify the beanFilteringConfiguration.xml file. Once you have made the changes, use the Dynamo Server Admin to access /atg/dynamo/service/filter/bean/BeanFilterService and run the reinitialize method to implement your changes.

Configuring REST MVC Output

As described earlier, the ResponseGenerator transforms the information obtained from the actors into a response. This response can be configured as either a JSON or XML response. Output from the ResponseGenerator is configured using values from the /atg/dynamo/service/resonse/output/ Configuration.properties file. The following configuration properties define the settings used for the ResponseGenerator and output customizers:

Property Description

defaultFormat Sets the default output of the response to a specific format, such as JSON or XML. The default for this property is json. Note that this property is case sensitive. This property is overwritten if your REST call contains the atg-rest-output parameter.

defaultTimeZoneId Sets the default time zone used when creating output dates. The default for this property is GMT.

7 The REST MVC Definition Framework 177 Property Description

defaultEnableFormatDateOutput Use this property to configure output dates as formatted data strings. The default is false, indicating that the output will contain all of the properties of the Date object. This property uses the defaultTimeZoneId for time zone output.

defaultMaxNestingDepth This property identifies how many levels the XML or JSON response will contain. Setting this property to -1 sets the depth to unlimited. The default of this property is set to 15.

REST MVC Access Control

Whenever an Oracle Commerce Platform REST MVC call occurs, the system checks the AccessControllerService to determine if access to the URL should be granted for the given user. Access control to REST MVC services is set with access controllers that are defined in the /atg/dynamo/servlet/ dafpipeline/AccessControlServlet.

The access controller recognizes the /rest/model/ syntax and then maps the actor and call to a controller.

Example: External User Access Control

The following is an example of access control for an external user:

# List of mappings between paths and AccessController objects. If a # path refers to a directory, all the documents in that directory and # its subdirectories will be protected by the given AccessController. accessControllers+=\ /rest/model/atg/userprofiling/ProfileActor/logout= /atg/rest/userprofiling/LoggedInAccessController, \ /rest/model/atg/userprofiling/ProfileActor/logout-success= /atg/rest/userprofiling/AllAccessController, \ /rest/model/atg/userprofiling/ProfileActor/logout-error= /atg/rest/userprofiling/AllAccessController, \ /rest/model/atg/rest/SessionConfirmationActor/getSessionConfirmationNumber= /atg/rest/userprofiling/AllAccessController

Example: Internal User Access Control

Access control for an internal user is provided by the InternalProfileActor. The following is an example of access control for an internal user:

# List of mappings between paths and AccessController objects. If a # path refers to a directory, all the documents in that directory and # its subdirectories will be protected by the given AccessController. accessControllers+=\ /rest/model/atg/userprofiling/InternalProfileActor/login=

178 7 The REST MVC Definition Framework /atg/rest/userprofiling/AllAccessController, \ /rest/model/atg/userprofiling/InternalProfileActor/logout= /atg/rest/userprofiling/LoggedInAccessController, \ /rest/model/atg/userprofiling/InternalProfileActor/logout-error= /atg/rest/userprofiling/AllAccessController, \ /rest/model/atg/userprofiling/SecurityConfirmationActor= /atg/rest/userprofiling/AllAccessController, \ /rest/model/atg/rest/SessionConfirmationActor/getSessionConfirmationNumber= /atg/rest/userprofiling/AllAccessController, \ /rest/model=/atg/rest/userprofiling/NonTransientAccessController

accessControllers=+\ /rest/model/atg/userprofiling/ProfileActor/logout= /atg/rest/userprofiling/LoggedInAccessController, \ /rest/model/atg/userprofiling/ProfileActor/logout-success= /atg/rest/userprofiling/AllAccessController, \ /rest/model/atg/userprofiling/ProfileActor/logout-error= /atg/rest/userprofiling/AllAccessController, \ /rest/model/atg/rest/SessionConfirmationActor/getSessionConfirmationNumber =/atg/rest/userprofiling/AllAccessController

The following example of the /atg/rest/userprofiling/LoggedInAccessController shows how to set the access controller using the enabled parameter, as well as which rule to use to determine access. If access is denied, the SecurityStatusActor will identify the error and redirect the user to an error URL:

$class=atg.userprofiling.RuleAccessController enabled=true # Rules used to determine whether access should be allowed ruleSetService=/atg/rest/targeting/LoggedInRuleSetService # URL to redirect to if access is denied deniedAccessURL=/rest/model/atg/userprofiling/SecurityStatusActor/ authenticationRequired

Creating a New REST MVC Call

The following section identifies the steps needed to define a new REST MVC call.

1. Define an actor-chain component.

When you define an actor-chain component, it is recommended that you define it in the same location as the component it references. For example:

/atg/commerce/custsvc/order/CommitOrderActor.properties $class=atg.service.actor.ActorChainService definitionFile=commitOrderActor.xml

2. Define the actor-chain definition XML file.

It is best to define success and error URLs in the actor rather than on the client-side. You should also define a success and error URL per form handler. You can use nested actors to reference a shared error handler.

7 The REST MVC Definition Framework 179

When creating a form handler, it is best to define success and error chains in the base directory, such as /DCS, and then XML combine the success chain in your Web application directory.

Note that when you are creating an actor-chain component in development mode, it is best to disable the Dynamo session confirmation number. To do this, disable the enforceSessionConfirmation parameter in your local /atg/dynamo/service /actor/Configuration.properties file. Once you have finished testing the component, you can set the property back to use session confirmation. Refer to the Using Dynamo Session Confirmation Numbers (page 138) section for further information.

3. If required, create a success chain using XML combination in the Web application directory.

For example, the following example displays an order confirmation after the order has been committed.

180 7 The REST MVC Definition Framework return-model-var="model"/>

4. Register the actor-chains in the ActorChainRestRegistry so that they are enabled for REST access.

By default, no actors are registered. Actor-chains accessed from REST or from success and error URLs must be registered in the application module. Actor-chains that are accessed only from nested actors do not need to be registered. Note that each chain ID should be registered separately. For information on registering actors, refer to the Enabling REST Services (page 137) section.

# /atg/rest/registry/ActorChainRestRegistry.properties registeredUrls+=\ /atg/commerce/custsvc/order/CommitOrderActor/commitOrder, \ /atg/commerce/cstsvc/order/CommitOrderActor/ commitOrder-success, \ /atg/commerce/custsvc/order/CommitOrderActor/ commitOrder-error

5. Define the Java servlet bean filters.

Bean filters are shared across all actor calls. Use a separate filter ID if you need a specific view for a specific actor. It is best to define properties per class, as filtering will be applied to each class or interface in the class hierarchy. You can define filters for both repository items and any wrapper classes that you may have for repository items.

Note that you can enable debugging when creating your filter by setting the loggingDebug attribute to true in the /atg/dynamo/service/filter/

7 The REST MVC Definition Framework 181 bean/BeanFilterService. This will provide a log of what is being filtered.

6. Test your new REST call.

When you have created your new REST call, you can test it using cURL. For information on creating cURL examples, refer to the Using cURL for Examples (page 58) section. It is best to test success and the error conditions, as well as JSON or XML input and output types. For example, you can test the new Commit Order call using the following cURL:

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8280/rest/model/atg/commerce/custsvc/order/ CommitOrderActor/commitOrder {"orderId": {"orderId": "o99520004"}}"

During your development and testing, you may want to disable the Dynamo session confirmation numbers, as discussed in the Using Dynamo Session Confirmation Numbers (page 138) section. To disable the session confirmation numbers, set the enforceSessionConfirmation parameter in your local /atg/dynamo/ service /actor/Configuration.properties file to false. Note that the following type of ambiguous error will occur when session confirmation is disabled:

HTTP Status 409 - Your session expired due to inactivity. type - Status report message - Your session expired due to inactivity. description - The request could not be completed due to a conflict with the current state of the resource.

182 7 The REST MVC Definition Framework 8 External REST MVC Service Call Examples

The following REST MVC services have been made available so that you can begin issuing them immediately upon installation of your REST configuration.

As described in previous sections, REST MVC calls are based on actors that perform specific functions. This section is organized by tasks that each actor performs for external-facing customers. For REST MVC calls for agents, refer to the Internal REST MVC Service Call Examples (page 247) section.

Note that this section contains information on desktop REST MVC calls. For information on REST calls used by mobile applications, refer to the Commerce Reference Store IUA Overview document.

External Service Call Workflow Example

The following diagram shows an example of a typical customer’s workflow that contains various REST service calls:

Each of these service calls performs an action within the Add Item to Cart workflow, starting with a customer logging in to the REST server and ending when the customer logs out of the REST server.

8 External REST MVC Service Call Examples 183 Note: The following examples are provided as guidelines for working with External REST MVC calls. The responses returned by your server may vary based upon your environment’s configuration.

Getting the Session Confirmation Number

The first actor that must be invoked is the Dynamo Session Confirmation actor. As described in the Using Dynamo Session Confirmation Numbers (page 138) section, the session confirmation number is used by the REST Web Services to provide secure access to the REST calls. The Form Element (page 152) and The Component Element (page 145) use _dynSessConf for method calls and setting property values. The SessionConfirmationActor returns the session confirmation number. The path to this actor is /atg/rest and it uses the getSessionConfirmationNumber actor-chain.

Parameters: None

Session Confirmation Number Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" "http://localhost:8280/rest/model/atg/rest/SessionConfirmationActor/ getSessionConfirmationNumber"

The server response may be similar to the following:

{"sessionConfirmationNumber":-5166444348429687167}

Specifying Site Context in a Multisite Environment

Include the pushSite URL query parameter to specify site context when performing an external REST call. Include the site as the value of the pushSite parameter. For detailed information about the pushSite parameter, refer to Multisite Request Processing section of the Platform Programming Guide.

For example, to set the site context to mainStoreUS:

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" "http://localhost:8280/rest/model/atg/rest/ShoppingCartActor/ totalCommerceItemCount?pushSite=mainStoreUS"

Working with Customers

The ProfileActor allows you to access and work with customer profiles. This actor is located at /atg/ userprofiling/ and contains the following actor-chains:

184 8 External REST MVC Service Call Examples Actor-Chain Description

login Allows a customer to log into the site.

logout Allows a customer to log out of a site.

create Creates a customer profile.

update Updates a customer profile.

detailed Views a customer profile using the detailed filter.

summary Views a customer profile using the summary filter.

creditCards Provides the credit cards associated with the customer profile.

currentCatalog Provides the customer’s current catalog.

addresses Provides the addresses associated with this customer profile.

Logging In Customers

The login actor-chain is used to log the customer into the site and verify the appropriate login and password credentials.

Parameter Description

login The customer login, for example, [email protected].

password The customer’s password.

Customer Log In Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" -d "{ \"login\" : \"[email protected]\" , \"password\" : \"password123\" }" "http://localhost:8280/rest/model/atg/userprofiling/ProfileActor/ login"

If the log in information is incorrect, the following exception might occur:

{"formError":true,"formExceptions":[{"localizedMessage":"The password and login do not match","errorCode":"invalidPassword"}]}

Logging Out Customers

The logout actor-chain is used to log the customer out of the application.

8 External REST MVC Service Call Examples 185 Parameters: None

Customer Log Out Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" "http://localhost:8280/rest/model/atg/userprofiling/ProfileActor/ logout"

Creating New Customer Profiles

The create actor-chain is used to create a new customer profile.

Parameter Description

autoLogin Determines if a cookie should be returned upon logging in. This property, if set to true, allows customer to log in automatically.

realmId If your environment is set up to use profile realms, this indicates the ID of the realm. Refer to the Core Commerce Programming Guide for information on profile realms.

firstName The first name of the customer.

middleName The middle name or initial of the customer.

lastName The last name of the customer.

email The customer’s e-mail address.

password The customer’s password.

confirmPassword Re-enter the customer’s password to verify.

login The customer’s log in name.

dateOfBirth The customer’s date of birth.

gender The customer’s gender.

homeAddress.address1 The first address line of the customer’s home address.

homeAddress.address2 The second address line of the customer’s home address.

homeAddress.address3 The third address line of the customer’s home address.

homeAddress.city The city associated with the customer’s home address.

homeAddress.state The state associated with the customer’s home address.

homeAddress.postalCode The postal code associated with the customer’s home address.

homeAddress.country The country associated with the customer’s home address.

186 8 External REST MVC Service Call Examples Parameter Description

homeAddress.phoneNumber The phone number of the customer’s home address.

homeAddress.companyName A company that is associated with the home address.

homeAddress.county A county that it associated with the home address.

homeAddress.jobTitle A job title associated with the customer’s home address.

homeAddress.faxNumber A fax number associated with the customer’s home address.

homeAddress.prefix A prefix used when creating the home address, for example, Mr. or Dr.

homeAddress.suffix A suffix used when creating the user name associated with the home address, for example, Jr.

homeAddress.firstName The first name of the customer associated with the home address.

homeAddress.middleName A middle name or initial of the customer associated with the home address.

homeAddress.lastName The last name of the customer associated with the home address.

daytimeTelephoneNumber Identifies the daytime telephone number on the customer profile.

Create Customer Profile Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" -d "{\"firstName\":\"Joe\", \"middleName\":\"T\", \"lastName\":\"Smith\", \"email\":\"[email protected]\", \"password\":\"tempPassword\", \"confirmPassword\":\"tempPassword\", \"login\":\"joe03\", \"homeAddress\": {\"atg-rest-class-type\":\"java.util.HashMap\", \"atg-rest-values\": {\"address1\":\"111 Main Street\", \"address2\":\"Suite 100\", \"city\":\"Cambridge\", \"state\":\"MA\", \"country\":\"USA\", \"postalCode\":\"00123\", \"phone\": \"555-111-2222\"}} }" "http://localhost:8280/rest/model/atg/userprofiling/ProfileActor/create"

Editing or Updating a Customer Profile

The update actor-chain is used to edit customer profiles.

Parameter Description

autoLogin Determines if a cookie should be used when logging in. Setting this to true allows a customer to log in automatically.

8 External REST MVC Service Call Examples 187 Parameter Description

realmId If your environment is set up to use realms, this indicates the ID of the realm. Refer to the Core Commerce Programming Guide for information on realms.

firstName The first name of the customer.

middleName The middle name or initial of the customer.

lastName The last name of the customer.

email The customer’s e-mail address.

password The customer’s password.

confirmPassword Re-enter the customer’s password to verify.

login The customer’s log in name.

dateOfBirth The customer’s date of birth.

gender The customer’s gender.

homeAddress.address1 The first address line of the customer’s home address.

homeAddress.address2 The second address line of the customer’s home address.

homeAddress.address3 The third address line of the customer’s home address.

homeAddress.city The city associated with the customer’s home address.

homeAddress.state The state associated with the customer’s home address.

homeAddress.postalCode The postal code associated with the customer’s home address.

homeAddress.country The country associated with the customer’s home address.

homeAddress.phoneNumber The phone number of the customer’s home address.

homeAddress.companyName A company that is associated with the home address.

homeAddress.county A county that is associated with the home address.

homeAddress.jobTitle A job title associated with the customer’s home address.

homeAddress.faxNumber A fax number associated with the customer’s home address.

homeAddress.prefix A prefix associated with the customer when creating the home address, for example, Mr. or Dr.

homeAddress.suffix A suffix to display for the customer when displaying the home address, for example, Jr.

homeAddress.firstName The first name of the customer associated with the home address.

188 8 External REST MVC Service Call Examples Parameter Description

homeAddress.middleName A middle name or initial of the customer associated with the home address.

homeAddress.lastName The last name of the customer associated with the home address.

daytimeTelephoneNumber Identifies the daytime telephone number on the customer profile.

Edit Customer Profile Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" -d "{\"firstName\":\"Joe\", \"middleName\":\"B\", \"lastName\":\"Smith\", \"email\":\"[email protected]\", \"daytimeTelephoneNumber\":\"617-637-8687\", \"homeAddress\":{\"atg-rest-class-type\":\"java.util.HashMap\", \"atg-rest-values\": {\"address1\":\"127 Main Street\", \"address2\": \"Suite 100\", \"city\":\"Cambridge\",\"state\":\"MA\", \"country\":\"USA\", \"postalCode\":\"02046\", \"phone\": \"555-111-3333\"}} }" "http://localhost:8280/rest/model/atg/userprofiling/ProfileActor/update"

Viewing a Customer Profile

The detailed actor-chain is used to view customer profiles.

Parameters: None

View Customer Profile Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" http://localhost:8280/rest/model/atg/userprofiling/ProfileActor/detailed"

Viewing the Shopping Cart

The ShoppingCartActor contains two chains, the detailed actor-chain that is used to view or review a cart or order, and the summary actor-chain that provides a summary of the shopping cart. This actor is located at /atg/ commerce/.

Parameters: None

View Shopping Cart Example

The following example shows a detailed request:

curl -v -b customer_cookies.txt -H "Content-Type: application/json" "http://localhost:8280/rest/model/atg/commerce/ShoppingCartActor/detailed"

8 External REST MVC Service Call Examples 189 The server response may be similar to the following:

{"order": { "lastModifiedTime": 1363293103777, "shippingGroupCount": 1, "paymentGroupCount": 1, "shippingGroups": [{ "specialInstructions": {}, "handlingInstructions": [], "state": 0, "locationId": null, "shippingMethod": "Ground", "id": "sg140009", "trackingNumber": null, "priceInfo": null, "description": "sg140009", "actualShipDate": null, "submittedDate": null, "shipOnDate": null, "shippingAddress": { "middleName": null, "lastName": "Smith", "ownerId": null, "state": "MA", "address1": "1 Main Street", "address2": null, "address3": null, "companyName": null, "suffix": null, "city": "Cambridge", "country": "USA", "id": null, "postalCode": "02046", "faxNumber": null, "phoneNumber": "6176378687", "county": null, "email": "[email protected]", "prefix": null, "firstName": "John", "jobTitle": null }, "stateDetail": null }], "commerceItems": [{ "id": "ci11000002", "productDisplayName": "Roseanna Storage Ottoman", "returnedQuantity": 0, "priceInfo": { "amount": 159.2, "quantityDiscounted": 1, "discountable": true, "priceListId": "listPrices", "onSale": false, "rawTotalPrice": 199, "currencyCode": "USD", "amountIsFinal": false, "listPrice": 199, "discounted": true, "currentPriceDetailsSorted": [{

190 8 External REST MVC Service Call Examples "amount": 159.2, "itemPriceInfo": null, "currencyCode": "USD", "tax": 0, "range": { "lowBound": 0, "class": "atg.core.util.Range", "highBound": 0, "size": 1 }, "amountIsFinal": false, "discounted": true, "quantity": 1, "detailedUnitPrice": 159.2 }], "salePrice": 0 }, "catalogId": null, "quantity": 1, "catalogRefId": "xsku2034", "catalogKey": "en_US", "productId": "xprod2034" }], "id": "o140002", "siteId": "homeSite", "taxPriceInfo": null, "priceInfo": { "amount": 149.2, "total": 149.2, "shipping": 0, "currencyCode": "USD", "tax": 0, "amountIsFinal": false, "discounted": true, "manualAdjustmentTotal": 0, "rawSubtotal": 159.2, "discountAmount": 10 }, "paymentGroups": [{ "amount": 0, "currencyCode": null, "expirationMonth": null, "expirationYear": null, "paymentId": "pg140003", "creditCardNumber": null, "expirationDayOfMonth": null, "billingAddress": { "middleName": null, "lastName": "Smith", "ownerId": null, "state": "MA", "address1": "1 Main Street", "address2": null, "address3": null, "companyName": null, "suffix": null, "city": "Cambridge", "country": "USA", "id": null, "postalCode": "02046",

8 External REST MVC Service Call Examples 191 "faxNumber": null, "phoneNumber": "6176378687", "county": null, "email": "[email protected]", "prefix": null, "firstName": "John", "jobTitle": null }, "creditCardType": "Visa", "orderId": null }], "profileId": "230000", "creationTime": 1363291121877, "relationships": [{ "id": "r110006", "amount": 0, "relationshipType": "SHIPPINGQUANTITY", "returnedQuantity": 0, "shippingGroupId": "sg140009", "commerceItemId": "ci11000002", "quantity": 1 }], "totalCommerceItemCount": 1 }}

Working with the Shopping Cart

The CartModifierActor contains several actor-chains that modify the customer’s shopping cart. The path for this actor is /atg/commerce/order/purchase/CartModifierActor.

This actor contains the following actor-chains:

Actor-Chain Description

addItemToOrder Adds items from a catalog, wish/gift list to a shopping cart.

addMultipleItemsToOrder Adds multiple items to a shopping cart.

moveToPurchaseInfo Saves the shopping cart and continues to the next step in the checkout process.

moveToPurchaseInfoByCommerceId Saves the shopping cart and continues to the next step in the checkout process.

moveToPurchaseInfoByRelId Saves the shopping cart and continues to the next step in the checkout process using the shipping group relationship ID.

removeAndAddItemToOrder Removes an item and then adds it to the shopping cart.

192 8 External REST MVC Service Call Examples Actor-Chain Description

removeItemFromOrder Removes an item from the shopping cart using the SKU ID.

removeItemFromOrderByRelationshipId Removes an item from the shopping cart using the relationship ID.

setOrder Updates the shopping cart by SKU ID.

setOrderByCommerceId Updates the shopping cart by commerce ID.

setOrderByRelationshipID Updates the shopping cart by relationship ID.

Adding Multiple Items to the Shopping Cart

The addMultipleItemsToOrder actor-chain is used when adding more than one item to shopping cart.

Parameter Description

addItemCount The number of items being added to the shopping cart. This is different than the quantity of each product being added.

catalogRefId The catalog reference ID.

giftlistId Used only when adding gift or wishlist items to the shopping cart. Identifies the ID of the list.

giftlistItemId Used only when adding gift or wishlist items to the shopping cart. Identifies the ID of the list item.

locationId Used only for in-store pickup. This identifies the location of the store.

productId The ID of the product to add to the shopping cart.

quantity The number of each product being added to the shopping cart. For example, two sweaters or four pairs of shoes.

quantityWith The number of each product being added to the shopping cart, but in fractional Fraction quantities. For example, a half gallon of milk.

Add Multiple Items to Order Example

curl -v -b customer_cookies.txt -H "Content-Type: application/json" -d "{ \"addItemCount\": 3, \"items\": {\"atg-rest-class-type\":\"java.util.ArrayList\", \"atg-rest-values\": [{\"atg-rest-class-type\": \"atg.commerce.order.purchase.AddCommerceItemInfo\", \"catalogRefId\": \"xsku1043\",\"productId\": \"xprod1015\",\"quantity\": 1}, {\"atg-rest-class-type\": \"atg.commerce.order.purchase.AddCommerceItemInfo\", \"catalogRefId\": \"xsku60325\",\"productId\": \"xprod40028\",\"quantity\": 2},

8 External REST MVC Service Call Examples 193 {\"atg-rest-class-type\": \"atg.commerce.order.purchase.AddCommerceItemInfo\", \"catalogRefId\": \"xsku1001\",\"productId\": \"xprod1001\",\"quantity\": 3} ]}}" "http://localhost:8280/rest/model/atg/commerce/order/purchase/CartModifierActor/ addMultipleItemsToOrder"

Adding an Item to a Shopping Cart

The addItemToOrder actor-chain is used to add a single item to a shopping cart. It also is used to add an item from a customer’s gift/wish list to a shopping cart, as well as adding an item to an in-store pickup order:

Parameter Description

addToWishlist Boolean parameter used only for adding wish list items to the shopping cart.

catalogRefIds The catalog reference ID.

giftlistId Used only when adding gift or wishlist items to the shopping cart. Identifies the gift list ID.

giftlistItemId Used only when adding gift or wishlist items to the shopping cart. Identifies the ID of the list item.

locationId Used only for in-store pickup, identifies the location of the store.

productId The ID of the product to add to the shopping cart.

quantity The number of each product being added to the shopping cart. For example, two sweaters or four pairs of shoes.

quantityWith The number of each product being added to the shopping cart, but in a fractional Fraction amount. For example, a half pound of sugar or ¼ gallon of fuel.

Add Item to Order Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" -d "{ \"catalogRefIds\": \"xsku1043\",\"productId\":\"xprod1015\",\"quantity\": 1}" "http://localhost:8280/rest/model/atg/commerce/order/purchase/CartModifierActor/ addItemToOrder"

Add Item to In-Store Pickup Example

Note the use of the locationId to identify the store from where the item will be picked up.

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" -d "{ \"catalogRefIds\": \"sku30029\",\"productId\": \"prod10004\", \"locationId\": \"FashionIsland\", \"quantity\": 1}" "http://localhost:8280/rest/model/atg/ commerce/order/purchase/CartModifierActor/addItemToOrder"

194 8 External REST MVC Service Call Examples Add Item From Gift List Example

Note the use of the giftlistId and the giftlistItemId.

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" -d "{ \"catalogRefIds\" : \"xsku2085\", \"productId\" : \"xprod2085\", \"giftlistId\" : \"gl40007\",\"giftlistItemId\" : \"gi40001\", \"quantity\": 1}" "http://localhost:8280/rest/model/atg/commerce/order/purchase/CartModifierActor/ addItemToOrder"

Add Item From Wish List Example

This example is similar to the Gift List example, however if addToWishlist is true, the system uses Profile.wishlist.repositoryId instead of the giftlistId.

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" -d "{ \"catalogRefIds\" : \"xsku2085\", \"productId\" : \"xprod2085\", \"addToWishlist\" : \"true\",\"giftlistItemId\" : \"gi40001\", \"quantity\": 1}" "http://localhost:8280/rest/model/atg/commerce/order/purchase/CartModifierActor/ addItemToOrder"

Updating the Shopping Cart by SKU ID

The setOrder actor-chain updates the quantity of items within the cart using SKU IDs.

Parameters: None

Update Shopping Cart by SKU ID Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" "http://localhost:8280/rest/model/atg/commerce/order/purchase/CartModifierActor/ setOrder?xsku1043=2"

Updating the Shopping Cart by Commerce ID

The setOrderByCommerceId actor-chain updates the quantities of items within the cart using the commerce ID.

Parameters: None

Update Shopping Cart by Commerce ID Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" "http://localhost:8280/rest/model/atg/commerce/order/purchase/CartModifierActor/ setOrderByCommerceId?ci111000001=3"

8 External REST MVC Service Call Examples 195 Updating the Shopping Cart By Shipping Group Relationship ID

The setOrderByRelationshipId actor-chain is used to update the quantities of items within the cart using the CommerceItem or the shipping group relationship ID.

Parameters: None

Update Shopping Cart by Relationship ID Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" "http://localhost:8280/rest/model/atg/commerce/order/purchase/CartModifierActor/ setOrderByRelationshipId?r99090004=4"

Removing and Adding an Item to the Cart

The removeAndAddItemToOrder actor-chain is used to remove items from the order and then add it back to the order.

Parameter Description

catalogRefIds The catalog reference ID.

productId The ID of the product.

quantity The quantity of the product.

quantityWithFraction The quantity of the product in fractional units.

removalCommerceIds The list of commerce IDs to remove.

Move Item to the Cart Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" -d "{ \"catalogRefIds\":\"xsku1043\",\"productId\": \"xprod1015\",\"quantity\": 1, \"removalCommerceIds\":\"ci116000002\"}" "http://localhost:8280/rest/model/atg/ commerce/order/purchase/CartModifierActor/removeAndAddItemToOrder"

Removing an Item From the Shopping Cart

The removeItemFromOrder actor-chain removes items from the cart using the commerce ID.

Parameters: None

Remove Item From Cart Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json"

196 8 External REST MVC Service Call Examples "http://localhost:8280/rest/model/atg/commerce/order/purchase/CartModifierActor/ removeItemFromOrder?removalCommerceIds=ci115000001"

Removing an Item From the Shopping Cart By Relationship ID

The removeItemFromOrderByRelationshipId actor-chain is used to remove items from the cart using the CommerceItem or the shipping group relationship ID.

Parameters: None

Remove Item by Relationship ID Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" "http://localhost:8280/rest/model/atg/commerce/order/purchase/CartModifierActor/ removeItemFromOrderByRelationshipId?removalRelationshipIds=r99160002"

Starting the Checkout Process

The moveToPurchaseInfoByCommerceId actor-chain starts the checkout process. The current order’s commerce items and quantities must be passed in to initiate the checkout process.

Parameters: None

Continue the Checkout Process Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" -d "http://localhost:8280/rest/model/atg/commerce/order/purchase/CartModifierActor/ moveToPurchaseInfoByCommerceId"

Working with the Shipping Page

The ShippingGroupActor contains several actor-chains that modify the Shipping page. The path for this actor is /atg/commerce/order/purchase/ShippingGroupActor.

This actor contains the following actor-chains:

Actor-Chain Description

getShippingGroups Displays the shipping groups that are available.

specifyDefaultShippingGroup Specifies a default shipping group.

applyDefaultShippingGroup Applies the default shipping group.

8 External REST MVC Service Call Examples 197 Actor-Chain Description

getAllCommerceItemShippingInfos Obtains all of the Commerce Item Shipping Info (CISI).

applyShippingGroups Applies the shipping group.

splitShippingInfos Splits the shipping between specified shipping groups. Supports fractional quantities.

Displaying Shipping Groups

The GetShippingGroups actor-chain displays all of the shipping groups that are available.

Parameter Description

createOneInfoPerUnit A Boolean parameter that controls if one Commerce Item Shipping Info (CISI) is created for each item unit. For example, if you add an item with a quantity of five, you will end up with five CommerceItemShippingInfos, each with a quantity of one.

init If set to true, clears shippingInfos and shippingGroups and reinitializes these values in the /atg/commerce/order/purchase/ ShippingGroupDroplet.

shippingGroupTypes Identifies the shipping group types.

Display Shipping Groups Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" -d "{ \"createOneInfoPerUnit\":\"true\", \"init\":\"true\", \"shippingGroupTypes\": \"hardgoodShippingGroup\" }" "http://localhost:8280/rest/model/ atg/commerce/order/purchase/ShippingGroupActor/getShippingGroups"

The server response may be similar to the following:

{ "shippingGroups": {"Test": { "specialInstructions": {}, "priceInfo": { "amount": 0, "currencyCode": null, "amountIsFinal": false, "discounted": false }, "description": "sg140012", "actualShipDate": null, "submittedDate": null, "state": 0, "locationId": null,

198 8 External REST MVC Service Call Examples "shipOnDate": null, "shippingMethod": "hardgoodShippingGroup", "shippingAddress": { "lastName": "Smith", "postalCode": "02046", "phoneNumber": "6176378687", "email": "[email protected]", "state": "MA", "address1": "1 Main St", "address2": null "firstName": "John", "city": "Cambridge", "country": "USA" }, "stateDetail": null }}, "shippingInfos": {"ci11000002": [{ "handlingInstructionInfos": [], "commerceItemId": "ci11000002" }]} }

Specifying the Default Shipping Group

The specifyDefaultShippingGroup actor-chain identifies the default shipping group for the current order.

Parameter Description

defaultShippingGroupName Identifies the default shipping group name.

Specify Default Shipping Group Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" -d "{ \"defaultShippingGroupName\" : \"Address\"}" "http://localhost:8280/rest/model/ atg/commerce/order/purchase/ShippingGroupActor/specifyDefaultShippingGroup"

Applying the Default Shipping Group

The applyDefaultShippingGroup actor-chain applies shipping of the order to the default shipping group.

Note: You cannot use applyDefaultShippingGroup to set the a shipping method. To set the shipping method, choose the method used in the getCommerceIdentifierShippingInfos and applyShippingGroup parameters.

Parameters: None

Apply Default Shipping Group Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json"

8 External REST MVC Service Call Examples 199 "http://localhost:8280/rest/model/atg/commerce/order/purchase/ShippingGroupActor/ applyDefaultShippingGroup"

Obtaining the Current Shipping Info List

The getAllCommerceItemShippingInfos actor-chain obtains all of the Commerce Item Shipping Info (CISI). Note that you must call this method to initialize the shipping list prior to calling applyShippingGroups.

Parameters: None

Initialize Shipping List Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" "http://localhost:8280/rest/model/atg/commerce/order/purchase/ShippingGroupActor/ getAllCommerceItemShippingInfos"

Applying Shipping Groups and Shipping Methods

The ApplyShippingGroups actor-chain applies single or multiple shipping groups and shipping methods and then continues onto the billing process. This chain is also used to apply multiple shipping groups or methods.

Parameter Description

cisicount Identifies the array size, or number of Commerce Item Shipping Info (CISI) items included in the request.

cisiList.shippingGroupName Identifies the name of the shipping group.

cisiList.shippingMethod Identifies the shipping method used for the shipping group.

Apply Shipping Group and Method Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" -d "{ \"cisicount\" : \"2\", \"cisiList\" :{ \"atg-rest-class-type\" : \"java.util.ArrayList\", \"atg-rest-values\": [{\"atg-rest-class-type\" : \"atg.commerce.order.purchase.CommerceItemShippingInfo\", \"shippingGroupName\" : \"Home\", \"shippingMethod\" : \"Ground\"}, {\"atg-rest-class-type\" : \"atg.commerce.order.purchase.CommerceItemShippingInfo\", \"shippingGroupName\" : \"Work\", \"shippingMethod\" : \"Ground\"}]}}" "http://localhost:8280/rest/model/ atg/commerce/order/purchase/ShippingGroupActor/applyShippingGroups"

Splitting Commerce Items into Different Shipping Groups

The splitShippingInfos actor-chain splits the shipping between shipping groups.

200 8 External REST MVC Service Call Examples Parameter Description

cisiList.quantity The original quantity value that needs to be split.

cisiList.splitQuantity The quantity that should be moved to the other shipping group.

cisiList.shipppingGroupName This is the name of the shipping group in which the item will be available.

cisiList.splitShippingGroupName This is the name of the split shipping group.

Split Commerce Items into Different Shipping Groups Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" -d "{ \"cisicount\" : \"1\", \"cisiList\" :{ \"atg-rest-class-type\": \"java.util.ArrayList\", \"atg-rest-values\": [{ \"atg-rest-class-type\": \"atg.commerce.order.purchase.CommerceItemShippingInfo\", \"quantity\" : \"5\", \"splitQuantity\" : \"2\", \"shippingGroupName\" : \"Address\", \"splitShippingGroupName\" : \"Address##0\"}]}}" "http://localhost:8280/rest/model/atg/commerce/order/purchase/ShippingGroupActor/ splitShippingInfos"

Displaying Available Shipping Methods

The AvailableShippingMethodsActor is used to display the available shipping methods. The path to this actor is: /atg/commerce/pricing/AvailableShippingMethodsActor.

This actor contains the getAvailableShippingMethods actor-chain:

Parameters: None Display Available Shipping Methods Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" "http://localhost:8280/rest/model/atg/commerce/pricing/ AvailableShippingMethodsActor/getAvailableShippingMethods"

Creating a New Hardgood Shipping Group

The CreateHardgoodShippingGroupActor is used to create a new shipping group. The path to this actor is: / atg/commerce/order/purchase/CreateHardgoodShippingGroupActor.

This actor contains the addHardgoodShippingGroup actor-chain.

Parameter Description

hardgoodShippingGroupName The name of the shipping group.

8 External REST MVC Service Call Examples 201 Parameter Description

hardgoodShippingGroupType The shipping group type.

firstName The first name of the customer associated with this shipping group.

middleName The middle name or initial of the customer associated with this shipping group.

lastName The last name of the customer associated with this shipping group.

address1 The first address field associated with this shipping group.

address2 The second address field associated with this shipping group.

city The city of the address associated with this shipping group.

state The state of the address associated with this shipping group.

country The country of the address associated with this shipping group.

postalCode The postal code of the address associated with this shipping group.

phoneNumber The phone number of the customer associated with this shipping group.

Create New Shipping Group Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" -d "{ \"firstName\": \"John\",\"lastName\": \"Doe\", \"address1\": \"1 Main St.\", \"city"\:\"Cambridge\", \"state\": \"MA\", \"country\": \"USA\",\"postalCode\": \"02146\" }""http://localhost:8280/rest/model/atg/commerce/order/purchase/ CreateHardgoodShippingGroupActor/addHardgoodShippingGroup"

Editing a Shipping Group

The UpdateHardgoodShippingGroupActor is used to edit shipping groups. The path to this actor is: /atg/ commerce/order/purchase/UpdateHardgoodShippingGroupActor.

This actor contains the updateHardgoodShippingGroup actor-chain:

Parameter Description

nickname The nickname associated with the shipping group to update.

firstName The first name of the customer associated with this shipping group.

middleName The middle name or initial of the customer associated with this shipping group.

lastName The last name of the customer associated with this shipping group.

202 8 External REST MVC Service Call Examples Parameter Description

address1 The first address field of the address associated with this shipping group.

address2 The second address field of the address associated with this shipping group.

city The city of the address associated with this shipping group.

state The state of the address associated with this shipping group.

country The country of the address associated with this shipping group.

postalCode The postal code of the address associated with this shipping group.

phoneNumber The phone number of the customer associated with this shipping group.

Edit Shipping Group Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" -d "{ \"nickname\": \"Address\",\"firstName\": \"John\",\"lastName\": \"Doe\",\"address1\": \" 2 Main St.\",\"city\": \"Wilmington\",\"state\": \"MA\",\"country\": \"USA\",\"postalCode\": \"01872\" }" "http://localhost:8280/rest/model/atg/commerce/order/purchase/ UpdateHardgoodShippingGroupActor/updateHardgoodShippingGroup"

Working with the Billing Page

The PaymentGroupActor contains several actor-chains that allow the customer to work with the billing page, and to specify payment groups. The path for this actor is /atg/commerce/order/purchase/ PaymentGroupActor.

This actor contains the following actor-chains:

Actor-Chain Description

getPaymentGroups Displays the Billing page.

specifyDefaultPaymentGroup Specifies the default payment group.

applyDefaultPaymentGroup Applies the default payment group.

getCommerceIdentifierPaymentInfos Gets the Commerce Identifier Payment Info (CIPI).

applyMultiplePaymentGroups Applies single or multiple payment groups.

8 External REST MVC Service Call Examples 203 Display the Billing Page

The getPaymentGroups actor-chain is used to display the Billing page.

Parameter Description

init This Boolean parameter, if true, will clear payment group information and the Commerce Identifier Payment Info (CIPI) , and initialize payment groups and the Commerce Item Shipping Info (CISI).

createAllPaymentInfos This parameter will look for all Commerce Identifier Payment Info (CIPI), and returns information from all payment groups.

paymentGroupTypes Identifies the payment group types, such as creditCard or storeCredit.

Display Billing Page Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" –d "{ \"init\" : \"true\", \"paymentGroupTypes\" : \"creditCard,storeCredit\"}" "http://localhost:8280/rest/model/atg/commerce/order/purchase/PaymentGroupActor/ getPaymentGroups"

The server response may be similar to the following:

{"paymentGroups": {"Visa": { "amount": 109.2, "currencyCode": "USD", "expirationMonth": "1", "expirationYear": "2014", "paymentId": "pg140002", "creditCardNumber": "1111", "expirationDayOfMonth": null, "billingAddress": { "lastName": "Smith", "postalCode": "02046", "phoneNumber": "6176378687", "email": "[email protected]", "state": "MA", "address1": "1 Main St", "address2": "", "firstName": "John", "city": "Cambridge", "country": "USA" }, "creditCardType": "Visa", "orderId": null }}}

204 8 External REST MVC Service Call Examples Specifying the Default Payment Group

The specifyDefaultPaymentGroup actor-chain is used to identify the default payment group.

Parameter Description

defaultPaymentGroupName Identifies the default payment group name.

Specify Default Payment Group Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" –d "{\"defaultPaymentGroupName\" : \"visa 1111\"}" "http://localhost:8280/rest/model/ atg/commerce/order/purchase/PaymentGroupActor/specifyDefaultPaymentGroup"

Applying Default Payment Group

The applyDefaultPaymentGroup actor-chain is used to apply the default payment group to the order and continues on to order review.

Parameters: None Apply Default Payment Group Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" "http://localhost:8280/rest/model/atg/commerce/order/purchase/PaymentGroupActor/ applyDefaultPaymentGroup"

The server response may be similar to the following:

{"paymentGroups": {"visa - 1111": {{"paymentGroups": {"visa - 1111": { "amount": 0, "currencyCode": null, "expirationMonth": "1", "expirationYear": "2022", "paymentId": "pg110012", "creditCardNumber": "1111", "expirationDayOfMonth": null, "billingAddress": { "lastName": "Smith", "postalCode": "02046", "phoneNumber": "6176378687", "email": "[email protected]", "state": "MA", "address1": "1 Main Street", "address2": null, "firstName": "John", "city": "Cambridge", "country": "USA" }, "creditCardType": "Visa",

8 External REST MVC Service Call Examples 205 "orderId": null }}}

"orderId": null

Obtaining Current Payment Info Lists

Th getCommerceIdentifierPaymentInfos actor-chain is used to obtain the Commerce Identifier Payment Info (CIPI) list, based on the commerce item-identifier, such as Order ID, or Commerce Item ID.

Parameter Description

listId Identifies the payment list to initialize.

Initialize Payment List Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" –d "{ \"listId\" : \"o60003\"}" "http://localhost:8280/rest/model/atg/commerce/ order/purchase/PaymentGroupActor/getCommerceIdentifierPaymentInfos"

The server response may resemble the following:

{"currentList": [ { "amount": 0, "relationshipType": "ORDERAMOUNTREMAINING", "splitQuantity": 0, "quantity": 0, "amountRemainingType": "ORDERAMOUNTREMAINING", "splitAmount": 0, "commerceIdentifier": { "id": "o60004", "priceInfo": { "amount": 5, "total": 5, "shipping": 0, "currencyCode": "USD", "tax": 0, "amountIsFinal": false, "discounted": false, "manualAdjustmentTotal": 0, "rawSubtotal": 5, "discountAmount": 0, "adjustments": [{ "adjustment": 5, "quantityAdjusted": 1, "totalAdjustment": 5, "manualPricingAdjustment": null, "coupon": null }] },

206 8 External REST MVC Service Call Examples "commerceItems": [{ "id": "ci7000008", "productDisplayName": "Gift Wrap", "returnedQuantity": 0, "priceInfo": { "quantityDiscounted": 0, "quantityAsQualifier": 0, "onSale": false, "currencyCode": "USD", "orderDiscountShare": 0, "adjustments": [{ "adjustment": 5, "quantityAdjusted": 1, "totalAdjustment": 5, "manualPricingAdjustment": null, "coupon": null }], "amount": 5, "discountable": null, "rawTotalPrice": 5, "listPrice": 5, "amountIsFinal": false, "discounted": false, "salePrice": 0 }, "state": 0, "quantity": 1, "catalogRefId": "xsku1043" }], "totalCommerceItemCount": 1 }, "amountType": "ORDERAMOUNT" }, { "amount": 0, "relationshipType": "ORDERAMOUNT", "splitQuantity": 0, "quantity": 0, "amountRemainingType": "ORDERAMOUNTREMAINING", "splitAmount": 0, "commerceIdentifier": { "id": "o60004", "priceInfo": { "amount": 5, "total": 5, "shipping": 0, "currencyCode": "USD", "tax": 0, "amountIsFinal": false, "discounted": false, "manualAdjustmentTotal": 0, "rawSubtotal": 5, "discountAmount": 0, "adjustments": [{ "adjustment": 5, "quantityAdjusted": 1, "totalAdjustment": 5, "manualPricingAdjustment": null, "coupon": null }]

8 External REST MVC Service Call Examples 207 }, "commerceItems": [{ "id": "ci7000008", "productDisplayName": "Gift Wrap", "returnedQuantity": 0, "priceInfo": { "quantityDiscounted": 0, "quantityAsQualifier": 0, "onSale": false, "currencyCode": "USD", "orderDiscountShare": 0, "adjustments": [{ "adjustment": 5, "quantityAdjusted": 1, "totalAdjustment": 5, "manualPricingAdjustment": null, "coupon": null }], "amount": 5, "discountable": null, "rawTotalPrice": 5, "listPrice": 5, "amountIsFinal": false, "discounted": false, "salePrice": 0 }, "state": 0, "quantity": 1, "catalogRefId": "xsku1043" }], "totalCommerceItemCount": 1 }, "paymentMethod": "visa - 1111", "amountType": "ORDERAMOUNT" } ]}

Applying Multiple Payment Groups to an Order

The applyMultiplePaymentGroups actor-chain is used to apply multiple payment groups to an order.

Parameter Description

listId The ID of the commerce identifier.

cipicount The number of Commerce Identifier Payment Info (CIPI) items that are included in the request.

cipiList.amount Amount that is being applied to the payment group.

cipiList.creditCardVerificationNumber The credit card verification number.

208 8 External REST MVC Service Call Examples Apply Multiple Payment Groups Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" –d "{ \"listId\" : \"o50002\", \"cipicount\" : \"1\", \"cipiList\" : { \"atg-rest-class-type\":\"java.util.ArrayList\", \"atg-rest-values\": [{\"atg-rest-class-type\":\"atg.commerce.order.purchase. CommerceIdentifierPaymentInfo\", \"amount\" : \"15.00\", \"creditCardVerificationNumber\" : \"1234\"}]}}" "http://localhost:8280/rest/model/atg/commerce/order/purchase/PaymentGroupActor/ applyMultiplePaymentGroups"

Creating a New Credit Card

The CreateCreditCardActor is used to create a new credit card when working in the Billing page. The path to this actor is: /atg/commerce/order/purchase/CreateCreditCardActor.

This actor contains the newCreditCard actor-chain:

Parameter Description

creditCardType The type of credit card to add.

creditCardNumber The credit card number.

expirationMonth The month that the credit card expires.

expirationYear The year that the credit card expires.

generateNickname Used to generate a nickname for the credit card. This parameter is always set to true.

firstName The first name on the credit card.

middleName The middle name or initial on the credit card.

lastName The last name on the credit card.

address1 The first address field on the credit card.

address2 The second address field on the credit card.

city The city on the credit card.

state The state on the credit card.

country The country on the credit card.

postalCode The postal code on the credit card.

phoneNumber A phone number associated with the credit card.

8 External REST MVC Service Call Examples 209 Create New Credit Card Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" –d "{ \"creditCardType\": \"visa\",\"creditCardNumber\": \"4111111111111111\",\"expirationMonth\": \"1\",\"expirationYear\": \"2020\",\"firstName\": \"John\",\"lastName\": \"Doe\",\"address1\": \"1 Main St.\",\"city\": \"Cambridge\",\"state\": \"MA\",\"country\": \"USA\",\"postalCode\": \"02146\" }" "http://localhost:8280/rest/model/atg/ commerce/order/purchase/CreateCreditCardActor/newCreditCard"

Updating a Credit Card

The UpdateCreditCardActor is used to edit an existing credit card. The path to this actor is: /atg/commerce/ order/purchase/UpdateCreditCardActor.

This actor contains the updateCreditCard actor-chain:

Parameter Description

nickname The nickname of the credit card to update.

creditCardType The type of credit card to update.

creditCardNumber The credit card number to update.

expirationMonth The month that the credit card expires.

expirationYear The year that the credit card expires.

firstName The first name on the credit card.

middleName The middle name or initial on the credit card.

lastName The last name on the credit card.

address1 The first address field on the credit card.

address2 The second address field on the credit card.

city The city on the credit card.

state The state on the credit card.

country The country on the credit card.

postalCode The postal code on the credit card.

phoneNumber A phone number associated with the credit card.

210 8 External REST MVC Service Call Examples Update Credit Card Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" -d "{ \"nickname\" : \"Visa\", \"creditCardType\" : \"Visa\", \"creditCardNumber\" : \"4111111111111111\", \"expirationMonth\" : \"06\", \"expirationYear\" : \"2017\", \"firstName\":\"Joe\", \"middleName\":\"C\", \"lastName\":\"Smith\", \"address1\":\"432 Willow Road\", \"address2\":\"NA\", \"city\":\"Broadbrook\", \"state\":\"MA\", \"country\":\"USA\", \"postalCode\":\"01234\", \"phoneNumber\":\"6176378687\" }" "http://localhost:8280/rest/model/ atg/commerce/order/purchase/UpdateCreditCardActor/updateCreditCard"

Working with Catalogs

The ProductCatalogActor is used to get catalog and product information. The path to this actor is: /atg/ commerce/catalog/ProductCatalogActor.

This actor contains the following actor-chains:

Actor-Chain Description

fractionalQuantityAllowed Boolean identification that indicates if fractional quantities are permitted with the product/SKU combination.

getCurrentCatalogRootCategories Obtains the user’s current catalog and root categories.

getCategory Displays the user’s sub-categories.

getProduct Displays a product by product ID.

getSku Displays a SKU by its ID.

outputProduct Outputs a product, including the prices for its child SKUs.

outputProductSummary Outputs product properties, as well as list and sale price ranges.

Identifying if Fractional Quantities Are Allowed

The fractionalQuantityAllowed actor-chain indicates if fractional quantities are permitted for a product/ SKU combination. This actor-chain is Boolean and returns either true or false. It uses the following parameters:

Parameter Description

productId The ID of the product.

8 External REST MVC Service Call Examples 211 Parameter Description

skuId The ID of the SKU.

Note that when passing in URL parameters that contain quantities, you must ensure that the SKU or product values being passed in match the quantity type. For example, if a SKU uses fractional values, the value passed in must be a fractional value, such as 14.0. If the SKU does not use fractional values, the value passed in should be a whole number. For additional information on working with Fractional Quantities, refer to the Core Commerce Programming Guide.

Identify Fractional Quantities Allowed Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" –d "{ \"productId\" : \"xprod2085\", \"skuId\" : \"sku225\" }" http://localhost:8280/ rest/model/atg/commerce/catalog/ProductCatalogActor/fractionalQuantityAllowed"

Getting the User’s Current Catalog

The getCurrentCatalogRootCategories actor-chain looks at the user’s profile and obtains their current catalog and root categories.

Parameters: None

Get Current Catalog Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" "http://localhost:8280/rest/model/atg/commerce/catalog/ProductCatalogActor/ getCurrentCatalogRootCategories"

A typical server response may be similar to the following:

{"rootCategories": [ { "id": "rootCategory", "description": null, "defaultParentCategory": null, "displayName": "Commerce Root", "type": null }, { "id": "NonNavigableProducts", "description": "", "defaultParentCategory": null, "displayName": "Non Navigable Products", "type": null } ]}

212 8 External REST MVC Service Call Examples Browsing the Catalog By Category ID

The getCatagory actor-chain allows the user to browse the catalog sub-categories. The actor-chain looks for a category using its categoryId. If the category is located, the chain checks whether the category belongs to the user’s catalog in their current profile, and if the item belongs to the current site. If it does, the chain returns the category. If the category is not found using the catalogId, the chain will return an empty response. If the category does not belong to a user’s catalog or current site, the chain will return an error message.

Parameter Description

categoryId The ID of the category.

filterBySite Identifies if the output is filtered by site. Set to true by default.

filterByCatalog Identifies if the output is filtered by catalog. Set to true by default.

Get Catalog By Sub-Categories Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" –d "{ \"categoryId\" : \"cat50056\" }" "http://localhost:8280/rest/model/atg/ commerce/catalog/ProductCatalogActor/getCategory"

The server response might be similar to the following:

{ "childCategories": [ { "id": "cat50056", "description": null, "defaultParentCategory": null, "displayName": "Gift Shop", "type": null }, { "id": "cat50001", "description": "", "defaultParentCategory": null, "displayName": "Women", "type": null }, { "id": "catMen", "description": "", "defaultParentCategory": null, "displayName": "Men", "type": null }, { "id": "cat50097", "description": "", "defaultParentCategory": null,

8 External REST MVC Service Call Examples 213 "displayName": "Shoes", "type": null }, { "id": "cat10016", "description": null, "defaultParentCategory": null, "displayName": "Home Accents", "type": null } ], "category": { "id": "rootCategory", "description": null, "defaultParentCategory": null, "displayName": "Commerce Root", "type": null } }

Browsing the Catalog by Product ID

The getProduct actor-chain allows the user to look up products by their ID.

Parameter Description

productId The ID of the product.

catalogs Used by the CategoryItemLookupDroplet. If filterByCatalog is set to true, this parameter provides the list of acceptable catalogs.

filterBySite Identifies if the output is filtered by site. Set to true by default.

filterByCatalog Identifies if the output is filtered by catalog. Set to true by default.

sites Used by the CategoryItemLookupDroplet. If filterBySite is set to true, this parameter provides the list of acceptable sites.

Get Product by Product ID Example

curl -v -b customer_cookies.txt -H "Content-Type: application/json" -d "{ \"productId\" : \"xprod2085\"}" "http://localhost:8280/rest/model/atg/commerce/ catalog/ProductCatalogActor/getProduct"

The server response may be similar to the following:

{ "product": { "currencyCode": "USD",

214 8 External REST MVC Service Call Examples "highestSalePrice": 19, "lowestSalePrice": 19, "lowestListPrice": 19, "fullImageUrl": "/crsdocroot/content/images/products/full/ HOME_TumblerGlass_full.jpg", "childSKUs": [{ "listPrice": 19, "displayName": "Tumbler Glass", "type": "sku", "repositoryId": "xsku2085" }], "repositoryId": "xprod2085", "highestListPrice": 19, "description": "Tumbler glass great for mixed drinks and other beverages", "largeImageUrl": "/crsdocroot/content/images/products/large/ HOME_TumblerGlass_large.jpg", "longDescription": "Our heavy glass tumblers are a versatile addition to your barware collection. Holds 12 ounces. Dishwasher safe. Made in Poland.", "isNavigableProduct": true, "mediumImageUrl": "/crsdocroot/content/images/products/medium/ HOME_TumblerGlass_medium.jpg", "displayName": "Tumbler Glass", "thumbnailImageUrl": "/crsdocroot/content/images/products/thumb/ HOME_TumblerGlass_thumb.jpg" }}

Browsing the Catalog by SKU ID

The getSku actor-chain allows the user to look up SKUs by their ID.

Parameter Description

skuId The ID of the SKU.

filterBySite Identifies if the output is filtered by site. Set to true by default.

Get SKU by SKU ID Example

curl -v -b customer_cookies.txt -H "Content-Type: application/json" -d "{ \"getSku\" : \"sku1234 \"}" "http://localhost:8280/rest/model/atg/commerce/ catalog/ProductCatalogActor/getSku"

Return Product Prices

The outputProduct actor-chain returns a product as well as the prices for its child SKUs. This actor-chain uses the following parameter:

8 External REST MVC Service Call Examples 215 Parameter Description

product A product repository item.

Get Price Output Example

curl -v -b customer_cookies.txt -H "Content-Type: application/json" -d "{ \"product\" : \"prod215\"}" "http://localhost:8280/rest/model/atg/commerce/ catalog/ProductCatalogActor/outputProduct"

Return Product Summary Prices

The outputProductSummary actor-chain returns product properties, as well as list and sales price ranges within a currency code. This actor-chain uses the following parameter:

Parameter Description

product A product repository item.

Get Price Output Summary Example

curl -v -b customer_cookies.txt -H "Content-Type: application/json" -d "{ \"product\" : \"prod215\"}" "http://localhost:8280/rest/model/atg/commerce/ catalog/ProductCatalogActor/outputProductSummary"

Getting Product Prices

The PricingActor is used to obtain prices for products using product IDs or SKU IDs. The path to this actor is: / atg/commerce/pricing.

This actor contains the following actor-chains:

Actor-Chain Description

productPriceRanges Provides the lowest and highest sale price for a product. These prices are obtained from the user’s profile.

skuPrices Displays either the listPrice and salePrice for a specific SKU if price lists are enabled. If price lists are not enabled, displays both listPrice and salePrice.

216 8 External REST MVC Service Call Examples Getting Lowest and Highest Prices for a Product

The productPriceRanges actor-chain returns the lowest and highest prices for a specific product.

Parameter Description

productId Identifies the product ID to use.

Get Prices by Product ID Example

curl -v -b customer_cookies.txt -H "Content-Type: application/json" -d "{ \"productId\" : \"xprod2085\"}" "http://localhost:8280/rest/model/atg/commerce/ pricing/PricingActor/productPriceRanges"

The server response may be similar to the following:

{"highestSalePrice": 19, "lowestSalePrice": 19, }

Getting List Price and Sale Prices for a SKU

The skuPrices actor-chain returns the list and sale prices for a specific product using its SKU ID:

Parameter Description

productId Identifies the product ID to use. The input is used only for price list pricing. This parameter is optional.

skuId The SKU ID to use.

Get Prices by SKU ID Example

curl -v -b customer_cookies.txt -H "Content-Type: application/json" -d "{ \"skuId\" : \"xsku2085\"}" "http://localhost:8280/rest/model/atg/commerce/ pricing/PricingActor/skuPrices"

The server response may be similar to the following:

{"listPrice": 19, "salePrice": 19,}

If you are not using price list pricing you can pass additional input parameters. This is because SKU-based pricing uses a nested actor chain that calls into getSku in productCatalogActor.xml, which accepts the following input parameters:

8 External REST MVC Service Call Examples 217

Working with Orders

There are a number of REST services that have been created that allow you to work with orders.

Looking Up an Order by Order ID or User ID

The OrderLookupActor is used to look up the current user’s orders by order or user ID. The path to this actor is: /atg/commerce/order/OrderLookupActor.

This actor contains the orderLookup actor-chain:

Parameter Description

orderId Identifies the order ID to use when looking up the order.

Lookup Order By Order ID Example

curl -v -b customer_cookies.txt -H "Content-Type: application/json" -d "{ \"orderId\" : \"o220001\"}" http://localhost:8280/rest/model/atg/commerce/ order/OrderLookupActor/orderLookup

A typical server response may resemble the following:

{"result": { "id": "o120001", "priceInfo": { "amount": 109.2, "total": 109.2, "shipping": 0, "currencyCode": "USD", "tax": 0, "rawSubtotal": 119.2, "discountAmount": 10 }, "commerceItems": [{ "id": "ci11000001", "productDisplayName": "Hubbard Chair", "priceInfo": { "amount": 119.2,

218 8 External REST MVC Service Call Examples "currencyCode": "USD", "currentPriceDetailsSorted": [{ "amount": 119.2, "currencyCode": "USD", "quantity": 1, "detailedUnitPrice": 119.2 }] }, "quantity": 1, "catalogRefId": "xsku2126", "productId": "xprod2126" }], "totalCommerceItemCount": 1 }}

Cancelling or Deleting an Order

The CancelOrderActor is used to cancel or delete the current order. This actor is located in: /atg/commerce/ order/purchase/CancelOrderActor.

This actor contains the following actor-chains:

Actor-Chain Description

cancelCurrentOrder Cancels or deletes the user’s current order.

cancelOrder Cancels or deletes an order.

Cancel or Delete Current Order

The cancelCurrentOrder actor-chain deletes the current order.

Parameters: None

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" "http://localhost:8280/rest/model/atg/commerce/order/purchase/CancelOrderActor/ cancelCurrentOrder"

Cancel or Delete a Specific Order

The cancelOrder actor-chain deletes a specified order.

Parameter Description

orderIdToCancel Provides the ID of the order to cancel.

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" -d

8 External REST MVC Service Call Examples 219 "{\"orderIdToCancel\":\"o99240003\"}" "http://localhost:8280/rest/model/atg/ commerce/order/purchase/CancelOrderActor/cancelOrder"

Saving an Order

The SaveOrderActor saves an order. It is located in: /atg/commerce/order/purchase/ SaveOrderActor.

This actor has the saveOrder actor-chain:

Parameter Description

description A description of why the order was saved.

Save Order Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" -d "{\"description\":\"Customer is returning later\"}" "http://localhost:8280/ rest/model/atg/commerce/order/purchase/SaveOrderActor"

Claiming a Coupon

The CouponActor is used to claim a coupon. It is located in: /atg/commerce/promotion/CouponActor.

This actor has the claimCoupon actor-chain:

Parameter Description

couponClaimCode The coupon code that is being claimed.

Claim Coupon Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" -d "{ \"couponClaimCode\":\"TENSHIP\" }" "http://localhost:8280/rest/model/atg/ commerce/promotion/CouponActor/claimCoupon"

Confirming an Order

The ConfirmOrderActor is used to re-price the order prior to confirming the order. The path to this actor is: / atg/commerce/pricing/ConfirmOrderActor.

This actor contains the confirmOrder actor-chain.

220 8 External REST MVC Service Call Examples Confirm Order Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" -d "{ \"howMany\" : 3 } "http://localhost:8280/rest/model/atg/commerce/order/ purchase/ConfirmOrderActor/confirmOrder"

The server response may be similar to the following:

{"order": { "lastModifiedTime": 1363287004602, "shippingGroupCount": 1, "paymentGroupCount": 1, "shippingGroups": [{ "specialInstructions": {}, "handlingInstructions": [], "state": 0, "locationId": null, "shippingMethod": "Ground", "id": "sg140002", "trackingNumber": null, "priceInfo": { "amount": 6.5, "currencyCode": "USD", "amountIsFinal": false, "discounted": false, "rawShipping": 6.5 }, "description": "sg140002", "actualShipDate": null, "submittedDate": null, "shipOnDate": null, "shippingAddress": { "middleName": null, "lastName": "Smith", "ownerId": null, "state": "MA", "address1": "1 Main St", "address2": "", "address3": null, "companyName": null, "suffix": null, "city": "Cambridge", "country": "USA", "id": null, "postalCode": "02046", "faxNumber": null, "phoneNumber": "6176378687", "county": null, "email": "[email protected]", "prefix": null, "firstName": "John", "jobTitle": null }, "stateDetail": null }], "commerceItems": [{ "id": "ci11000001", "productDisplayName": "Hubbard Chair",

8 External REST MVC Service Call Examples 221 "returnedQuantity": 0, "priceInfo": { "amount": 119.2, "quantityDiscounted": 1, "discountable": true, "priceListId": "listPrices", "onSale": false, "rawTotalPrice": 149, "currencyCode": "USD", "amountIsFinal": false, "listPrice": 149, "discounted": true, "currentPriceDetailsSorted": [{ "amount": 119.2, "itemPriceInfo": null, "currencyCode": "USD", "tax": 0, "range": { "lowBound": 0, "class": "atg.core.util.Range", "highBound": 0, "size": 1 }, "amountIsFinal": false, "discounted": true, "quantity": 1, "detailedUnitPrice": 119.2 }], "salePrice": 0 }, "catalogId": null, "quantity": 1, "catalogRefId": "xsku2126", "catalogKey": "en_US", "productId": "xprod2126" }], "id": "o120001", "siteId": "homeSite", "taxPriceInfo": { "amount": 0, "currencyCode": "USD", "countyTax": 0, "amountIsFinal": false, "countryTax": 0, "discounted": false, "stateTax": 0, "cityTax": 0, "districtTax": 0 }, "priceInfo": { "amount": 109.2, "total": 115.7, "shipping": 6.5, "currencyCode": "USD", "tax": 0, "amountIsFinal": false, "discounted": true, "manualAdjustmentTotal": 0, "rawSubtotal": 119.2, "discountAmount": 10

222 8 External REST MVC Service Call Examples }, "paymentGroups": [{ "amount": 0, "currencyCode": null, "expirationMonth": "1", "expirationYear": "2014", "paymentId": "pg140002", "creditCardNumber": "1111", "expirationDayOfMonth": null, "billingAddress": { "middleName": null, "lastName": "Smith", "ownerId": null, "state": "MA", "address1": "1 Main St", "address2": null, "address3": null, "companyName": null, "suffix": null, "city": "Cambridge", "country": "USA", "id": null, "postalCode": "02046", "faxNumber": null, "phoneNumber": "6176378687", "county": null, "email": "[email protected]", "prefix": null, "firstName": "John", "jobTitle": null }, "creditCardType": "Visa", "orderId": null }], "profileId": "230000", "creationTime": 1363282777057, "relationships": [ { "id": "r110002", "amount": 0, "relationshipType": "SHIPPINGQUANTITY", "returnedQuantity": 0, "shippingGroupId": "sg140002", "commerceItemId": "ci11000001", "quantity": 1 }, { "amount": 0, "id": "r110004", "relationshipType": "ORDERAMOUNTREMAINING", "paymentGroupId": "pg140002", "orderId": "o120001" } ], "totalCommerceItemCount": 1 }}

8 External REST MVC Service Call Examples 223 Committing an Order

The CommitOrderActor is used to commit the order. The path to this actor is: /atg/commerce/order/ purchase/CommitOrderActor.

This actor contains the commitOrder actor-chain.

Parameter Description

allowEmptyOrders If set to false, will return an error if an order is commited that contains no items.

salesChannel The sales channel used to submit the order. The values are “Web”, “Call Center” or Scheduled Orders”, and are defined in the Order repository.

siteId The ID of the site to be recorded in the order.

Commit Order Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" "http://localhost:8280/rest/model/atg/commerce/order/purchase/CommitOrderActor/ commitOrder"

Sending Order Confirmation

The OrderConfirmationActor is referenced by the CommitOrderActor to display confirmation of a successfully committed order. The path to this actor is/atg/commerce/order/purchase/ OrderConfirmationActor.

This actor contains the orderConfirmation actor-chain.

Parameters: None Confirm Order Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" "http://localhost:8280/rest/model/atg/commerce/order/purchase/ OrderConfirmationActor/orderConfirmation"

The server response may be similar to the following:

{orderId: "0132", email: [email protected]}

Obtaining Closeness Qualifiers

The ClosenessQualifierActor enables a customer to see how close their order is to qualifying for a promotion. This actor is located at /atg/commerce/custsvc/promotion/

224 8 External REST MVC Service Call Examples ClosenessQualifierActor, and contains the getClosenessQualifiers actor-chain.

Parameters: None Obtain Closeness Qualifiers Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" "http://localhost:8080/rest/model/atg/commerce/promotion/ClosenessQualifierActor/ getClosenessQualifiers"

Working with Returns and Exchanges

The returns and exchanges process allows a customer to return or exchange an item. For an overview of the process, refer to the Returns and Exchange Process Overview (page 361) section in the Internal REST MVC Service Call Examples (page 247) section.

The ReturnsActor is used to initiate, confirm and cancel returns. The path to this actor is: /atg/commerce/ custsvc/returns/ReturnsActor.

This actor contains the following actor-chains:

Actor-Chain Description

createReturn Initiates a return request.

selectItems Identifies the items to add to the return request.

returnReasons Retrieves possible reasons for the return of an item.

confirmReturn Confirms the return request.

confirmation Displays return details to confirm successful return.

cancelReturnRequest Cancels the return request.

applyRefunds Applies non-default refund values to the order’s refund method types.

modifiableRefundsMethodList Retrieves a list of refund method types.

isCurrentOrderReturnable Identifies if the current order is returnable.

isReturnActive Determines if there is a return in process for this order.

returnsHistory Displays return history for this order.

returns Displays the order’s return request.

nonReturnItemDetails Displays refund adjustments that were applied to non-return items. This chain supports fractional quantities.

8 External REST MVC Service Call Examples 225 Initiating a Return

The createReturn actor-chain initiates and creates a return request. Note that this actor-chain calls the ReturnFormHandler, as opposed to the internal createReturn actor-chain, which calls the StartReturnExchangeProcess form handler. For information on the internal createReturns actor-chain, refer to the Creating a Return (page 363) section. This actor-chain contains the following parameter:

Parameter Description

newOrderId The ID of the order to be returned.

Initiate Returns Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" -d "{\"newOrderId\":\"o2620001\"}" "http://localhost:8181/rest/model/atg/commerce/ custsvc/returns/ReturnsActor/createReturn"

Selecting Items to Return

The selectItems actor-chain identifies the items that will be returned in the current return request. This actor- chain takes the input from an updated JSON-formatted return request and then uses that input to set the server- side shipping group list’s return item values. Note that you must update the shippingGroupList items to set the number of items to be returned or exchanged, and the reason code. Refer to the Obtaining Return Reason Codes section for information on retrieving reason codes.

This actor-chain contains the following parameters:

Parameter Description

processName Identifies if the process is a return or an exchange.

jsonReturnRequest Identifies the updated Jason-formatted return request where the item to be returned or exchanged in the shippingGroupList.itemList has been updated so that either the quantityToReturn property or the quantityToExchange property is greater than 0, and the returnReasoncode is set.

Add Items to Return Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" –d "{\"processName\":\"Return\",\"jsonReturnRequest\":{\"returnRequest\": {\"shippingGroupList\":[{\"itemList\":[{\"id\":\"xcr10101\",\"shippingGroupId\": \"xcsg20080\",\"quantityToReturn\":1,\"returnReason\":\"didNotLike\", \"quantityToExchange\":0},{\"id\":\"xcr10102\",\"shippingGroupId\":\"xcsg20080\",

226 8 External REST MVC Service Call Examples \"quantityToReturn\":1,\"returnReason\":\"defective\",\"quantityToExchange\": 0}]}]}}}" "http://localhost:8181/rest/model/atg/commerce/custsvc/returns/ CSRReturnsActor/selectItems"

The following is an XML-based example:

curl -L -v -b customer_cookies.txt -H "Content-Type: application/xml" –d "{"returnRequest":{"shippingGroupList": [{"itemList":[{"id":"xcr10101","shippingGroupId":"xcsg20080","quantityToReturn":1, "returnReason":"didNotLike","quantityToExchange":0},{"id":"xcr10102", "shippingGroupId":"xcsg20080","quantityToReturn":1,"returnReason":"defective", "quantityToExchange":0}]}]}}Return " "http://localhost:8181/rest/model/atg/commerce/custsvc/returns/ CSRReturnsActor/selectItems"

The server response may be similar to the following:

{ "returnRequest":{ "returnPaymentState":"Refund", "otherRefund":0, "requestId":null, "state":"incomplete", "processName":"Return", "actualShippingRefund":12.62, "replacementOrderId":null, "originatingOrderId":"xco30045", "exchangeProcess":false, "returnAdjustedOrderId":"o350068", "orderCurrencyCode":"USD", "refundMethodList":[ { "refundType":"creditCard", "amount":113.62, "maximumRefundAmount":131.85 }, { "refundType":"storeCredit", "amount":0, "maximumRefundAmount":-1 } ], "returnItemCount":2, "actualTaxRefund":0, "returnItemList":[ { "quantityToExchange":0, "suggestedTaxRefundShare":0, "quantityReceived":0, "itemCurrencyCode":"USD", "returnItemId":"xcr10101", "actualTaxRefundShare":0, "refundAmount":50.52, "shippingGroupId":"xcsg20080", "quantityReturned":0, "quantityShipped":1, "quantityAvailable":1,

8 External REST MVC Service Call Examples 227 "description":"Boyfriend Jeans", "quantityToReturn":1, "actualShippingRefundShare":6.31, "suggestedShippingRefundShare":6.31, "commerceItemId":"xci1000051", "catalogRefId":"xsku2519_2", "suggestedRefundAmount":50.52, "disposition":null, "returnReason":"didNotLike" }, { "quantityToExchange":0, "suggestedTaxRefundShare":0, "quantityReceived":0, "itemCurrencyCode":"USD", "returnItemId":"xcr10102", "actualTaxRefundShare":0, "refundAmount":51.44, "shippingGroupId":"xcsg20080", "quantityReturned":0, "quantityShipped":1, "quantityAvailable":1, "description":"Corduroy Cargo Pants", "quantityToReturn":1, "actualShippingRefundShare":6.31, "suggestedShippingRefundShare":6.31, "commerceItemId":"xci1000052", "catalogRefId":"xsku2512_2", "suggestedRefundAmount":51.44, "disposition":null, "returnReason":"defective" } ], "processImmediately":false, "rma":null, "returnFee":0, "orderId":"xco30045", "profile":{ "middleName":null, "lastName":"Smith", "id":"se-570085", "login":"[email protected]", "firstName":"Joe" } } }

Getting Return Reason Codes

The returnReasons actor-chain displays a list of all reason codes. Reason codes can be used in the selectItems actor-chain as outlined in Selecting Items to Return (page 226).

Parameters: None

Obtain Return Reason Codes Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json"

228 8 External REST MVC Service Call Examples "http://localhost:8181/rest/model/atg/commerce/custsvc/returns/ReturnsActor/ returnReasons"

The server may return a response similar to the following:

{ "reasons": { "incorrectSize": "Incorrect Size", "incorrectColor": "Incorrect Color", "didNotMeetExpectations": "Did Not Meet Expectations", "didNotLike": "Did Not Like", "defective": "Defective", "incorrectItem": "IncorrectItem" } }

Confirming a Return

The confirmReturn actor-chain submits and processes a return request, and displays confirmation detail if a submission is successful.

Parameters: None

Confirm a Return Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" "http://localhost:8181/rest/model/atg/commerce/custsvc/returns/ReturnsActor/ confirmReturn"

Displaying Return Confirmation Details

The confirmation is an informational actor-chain used to display return details confirming that the return was successful. You can use this actor-chain to display return data as part of the confirmReturn actor-chain output. This actor-chain outputs the confirmation e-mail address. To display other information, such as the exchange order ID, you must customize this call to hold a reference to the return request. Refer to the ATG Platform API Reference for information on customizing this actor-chain.

Note that this actor is invoked by the confirmReturn actor-chain. Calling this actor directly will display no results.

Canceling a Return

The cancelReturnRequest actor-chain cancels the return request at any point during the returns process.

Parameters: None

Cancel a Return Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json"

8 External REST MVC Service Call Examples 229 "http://localhost:8181/rest/model/atg/commerce/custsvc/returns/ReturnsActor/ cancelReturnRequest"

Returning Refund Methods

The modifiableRefundsMethodList actor-chain retrieves the list of all credit and payment methods to which a refund can be applied, and the default values for the item to be returned. Note that this call should be run after running the selectItems actor-chain.

Parameters: None

Refund Methods Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" http://localhost:8180/rest/model/atg/commerce/custsvc/returns/ReturnsActor/ modifiableRefundsMethodList"

The server response may be similar to the following:

{ "modifiableRefundMethodList": [{ "refundType": "creditCard", "amount": 51.31 }] }

Applying Non-Default Refund Values

The applyRefunds actor-chain is used to apply a non-default refund type and value to the order.

Parameter Description

returnMethodListSize The array size to retrieve from the JSP. The array size corresponds to the number of refund methods available.

Non-Default Refund Values Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" –d "{\"items\":{\"atg-rest-class-type\":\"java.util.ArrayList\", \"atg-rest-values\":[{\"atg-rest-class-type\": \"atg.commerce.csr.returns.RefundMethod\", \"refundType\":\"creditCard\", \"amount\":\"46.31\"}, {\"atg-rest-class-type\": \"atg.commerce.csr.returns.RefundMethod\", \"refundType\":\"storeCredit\", \"amount\":\"5.00\"}]}, \"returnMethodListSize\" : \"2\"}" "http://localhost:8180/rest/model/atg/commerce/custsvc/returns/ReturnsActor/

230 8 External REST MVC Service Call Examples applyRefunds"

Identifying Returnable Orders

The isCurrentOrderReturnable actor chain looks at the current order to see if it is a returnable order. It provides a true or false server response.

Parameters: None

Is Order Returnable Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" "http://localhost:8180/rest/model/atg/commerce/custsvc/order/ReturnsActor/ isCurrentOrderReturnable"

Viewing Details of Returned Items

The returns actor-chain provides details of returned items in the current order.

Parameter Description

orderId The ID of the order.

Does Order Contain Active Return Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" –d "{\"orderId\" : \"xco30049\"}" "http://localhost:8180/rest/model/atg/ commerce/custsvc/returns/ReturnsActor/returns"

Reviewing Return History

The returnsHistory actor-chain is used to view returns history.

Parameter Description

orderId The ID of the order to be returned.

Returns History Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" -d

8 External REST MVC Service Call Examples 231 "{\"orderId\":\"o2620001\"}" "http://localhost:8280/rest/model/atg/commerce/ custsvc/returns/ReturnsActor/returnsHistory"

Showing Non-Return Items

The nonReturnItemDetails actor-chain displays any non-returned items that have been affected by the return. When working on a current working order, when a return is completed, the system displays the refund details with non-returnable items, as well as the refund types and any additional notes. The return is then submitted for completion. Note that this call will produce information only after selectItems is called, and if the items being returned affect non-returned items.

Parameters: None

Complete Return Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" –d "http://localhost:8180/rest/model/atg/commerce/custsvc/returns/ ReturnsActor/nonReturnItemDetails"

Identifying if an Order is Part of an Active Return

The isReturnActive actor-chain looks at the current order to see if it is associated with an active return. It provides a true or false server response.

Parameters: None

Is Order Part of an Active Return Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" "http://localhost:8180/rest/model/atg/commerce/custsvc/order/ ReturnsActor/isReturnActive"

Updating Credit Cards for a Returns

The UpdateCreditCardActor is used to edit an existing credit card for a return. The path to this actor is: /atg/ commerce/order/purchase/UpdateCreditCardActor.

This actor contains the updateCreditCardForReturns actor-chain. This actor-chain depends on the ReturnsActor createReturn actor-chain to obtain the correct information.

Parameter Description

creditCardType The type of credit card.

creditCardNumber The credit card number.

232 8 External REST MVC Service Call Examples Parameter Description

expirationMonth The month that the credit card expires.

expirationYear The year that the credit card expires.

firstName The first name on the credit card.

middleName The middle name or initial on the credit card.

lastName The last name on the credit card.

address1 The first address field on the credit card.

address2 The second address field on the credit card.

city The city on the credit card.

state The state on the credit card.

country The country on the credit card.

postalCode The postal code on the credit card.

phoneNumber A phone number associated with the credit card.

Update Credit Card Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" -d "{\"paymentGroupId\":\"pg3980014\",\"creditCardType\":\"visa\", \"creditCardNumber\": \"4111111111111111\",\"expirationMonth\":\"1\", \"expirationYear\": \"2017\"}" "http://localhost:8181/rest/model/atg/commerce/ custsvc/order/UpdateCreditCardActor/updateCreditCardForReturns"

Displaying Lost Promotions

The LostPromotionsActor displays a list of promotions that a customer loses during the return or exchange process. Note that this data is not saved and can only be displayed during the return and exchange process. This actor is located at /atg/commerce/custsvc/returns/lostPromotionsActor. It contains the promotionsLost actor-chain.

Parameters: None

Display Lost Promotions Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" "http://localhost:8180/rest/model/atg/commerce/custsvc/returns/ LostPromotionsActor/promotionsLost"

The response may be similar to the following:

8 External REST MVC Service Call Examples 233 {"promotionsLost":"promo50012"}

Working with Gift Lists

The following actors are used with gift lists. For adding items to a cart, see Add Item From Wish List Example (page 195) and Add Item From Gift List Example (page 195).

The GiftlistActor contains several actor-chains that initiate gift list actions. The path for this actor is /atg/ commerce/gifts/GiftlistActor.

This actor contains the following actor-chains:

Actor-Chain Description

createGiftlist Creates a gift list.

updateGiftlist Updates a gift list.

addItemToGiflList Adds an item to a gift list. Supports fractional quantities.

removeItemFromGiftlist Removes an item from a gift list.

addItemToWishlist Adds an item to a wish list. Supports fractional quantities.

removeItemFromWishlist Removes an item from a wish list.

moveItemsFromCart Removes a gift or wish list item from the Shopping Cart. Supports fractional quantities.

deleteGiftlist Deletes a gift list.

profileGiftlists Views the current profile’s list of gift lists.

Creating a Gift List

The createGiftlist actor-chain creates a gift list.

Parameter Description

isPublished Identifies if the list has been published.

eventName The name of the gift list event.

eventDate The date of the gift list event.

234 8 External REST MVC Service Call Examples Parameter Description

eventType The type of the gift list event.

description A description of the gift list.

comments Any comments that are included with the list.

shippingAddressId The ID of the shipping address.

instructions Any instructions that are included with the list.

Create Gift List Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" -d "{\"eventName\" : \"Birthday\", \"eventType\" : \"Birthday\", "eventDate" : \"AUG 30, 2013\"}" "http://localhost:8280/rest/model/atg/commerce/gifts/ GiftlistActor/createGiftlist"

Updating a Gift List

The updateGiftlist actor-chain edits a gift list.

Parameter Description

giftlistId The ID of the gift list.

isPublished Identifies if the list is published.

eventName The name of the gift list event.

eventDate The date of the gift list event.

eventType The type of the gift list event.

description A description associated with the list.

shippingAddressId The Shipping Address ID associated with the list.

instructions Any instructions that are associated with the list.

Update Gift List Example

curl -v -b customer_cookies.txt -H "Content-Type: application/json" -d "{ \"giftlistId\": \"gl20002\", \"eventName\" : \"updated Birthday\", \"eventType\" : \"Birthday\", \"eventDate\" : \"AUG 30, 2013\"}" "http://localhost:8280/rest/

8 External REST MVC Service Call Examples 235 model/atg/commerce/gifts/GiftlistActor/updateGiftlist"

Adding Items to a Gift List

The addItemToGiftlist actor-chain adds an item to a gift list.

Parameter Description

giftlistId The ID of the gift list.

quantity The quantity of the products to add to the gift list.

productId The product ID of the product to add to the gift list.

catalogRefIds The catalog reference ID of the product being added to the gift list.

Add Item to Gift List Example

curl -v -b customer_cookies.txt -H "Content-Type: application/json" -d "{ \"giftlistId\": \"gl230009\", \"productId\": \"xprod1015\", \"catalogRefIds\" : \"xsku1043\", \"quantity\": \"2\" }" "http://localhost:8280/rest/model/atg/ commerce/gifts/GiftlistActor/addItemToGiftlist"

Adding Items to a Wish List

The addItemToWishlist actor-chain adds an item to a wish list.

Parameter Description

quantity The quantity of the products to add to the wish list.

productId The product ID of the product to add to the wish list.

catalogRefIds The catalog reference ID of the product being added to the wish list.

Add Item to Wish List Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" -d "{ \"productId\": \"prod10004\", \"catalogRefIds\" : \"sku30029\", \"quantity\": \"2\" }" "http://localhost:8280/rest/model/atg/commerce/gifts/GiftlistActor/ addItemToWishlist"

236 8 External REST MVC Service Call Examples Removing Items from a Gift List

The removeItemFromGiftlist actor-chain removes an item from a gift list.

Parameter Description

giftlistId The ID of the gift list from which the items will be removed.

removeGiftitemIds The ID of the items to remove from the gift list.

Remove Item from Gift List Example

curl -v -b customer_cookies.txt -H "Content-Type: application/json" -d "{ \"giftlistId\": \"gl20002\", \"removeGiftitemIds\": \"gi10001\" }" "http://localhost:8280/rest/model/atg/commerce/gifts/GiftlistActor/ removeItemFromGiftlist"

Removing Items from a Wish List

The removeItemFromWishlist actor-chain removes an item from a wish list.

Parameter Description

removeGiftitemIds The ID of the items to be reomved from the gift list.

Remove Item from Wish List Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" -d "{ \"removeGiftitemIds\": \"gi20001\" }" "http://localhost:8280/rest/model/atg/ commerce/gifts/GiftlistActor/removeItemFromWishlist"

Moving Items to a Gift or Wish List from a Shopping Cart

The moveItemsFromCart actor-chain takes an item from a shopping cart and moves it into the specified gift or wish list. You can specify a default quantity for an item, or specify the quantity for a specific item.

Parameter Description

giftlistId The ID of the gift or wish list to which the items will be moved.

itemIds The IDs of the items to move to the list.

8 External REST MVC Service Call Examples 237 Parameter Description

quantity The quantity of the items to move to the list.

Move Item to Gift or Wish List from Cart Example

The following example shows how you would specify the default quantity for the items within the cart:

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" -d "{ \"giftlistId\": \"gl20002\", \"itemIds\": \"ci10000003\", \"quantity\": 1}" "http://localhost:8280/rest/model/atg/commerce/gifts/GiftlistActor/ moveItemsFromCart"

The following example shows how you would specify the quantity for a particular item within the cart:

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" -d "{ \"giftlistId\": \"gl20002\", \"itemIds\": \"ci10000003\"}" "http://localhost:8280/ rest/model/atg/commerce/gifts/GiftlistActor/moveItemsFromCart?ci10000003=1"

Deleting a Gift List

The deleteGiftlist actor-chain deletes a specific gift.

Parameter Description

giftlistId The ID of the gift list to delete.

Delete a Gift List Example

curl -v -b customer_cookies.txt -H "Content-Type: application/json" -d "{ \"giftlistId\": \"gl20002\"}" "http://localhost:8280/rest/model/atg/commerce/ gifts/GiftlistActor/deleteGiftlist"

Viewing the Current Profile’s List of Gift Lists

The profileGiftlist actor-chain views the current profile’s list of gift lists.

Parameters: None View Current Profile’s List of Gift List Example

curl -v -b customer_cookies.txt -H "Content-Type: application/json" "http://localhost:8280/rest/model/atg/commerce/gifts/GiftlistActor/ profileGiftlists"

238 8 External REST MVC Service Call Examples The server response may be similar to the following:

{"giftlists": [ { "name": "Birthday", "repositoryId": "xgl20004" }, { "name": "Anniversary", "repositoryId": "gl430003" } ]}

Viewing a Gift List

The GiftlistLookupActor is used to view a customer’s gift list. This actor is located at: /atg/commerce/ gifts/GiftlistLookupActor, and contains the info actor-chain.

Parameter Description

giftlistId The ID of the gift list to view.

View Gift List Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" -d "{ \"giftlistId\" : \"gl430003\"}" "http://localhost:8280/rest/model/atg/commerce/ gifts/GiftlistLookupActor/info"

The server response may be similar to the following:

{"giftlist": { "giftlistItems": [], "instructions": "", "description": "Upcoming birthday gifts.", "name": "Birthday", "public": true, "date": {"time": 1386521853000}, "type": "Birthday", "repositoryId": "xgl20004", "addressId": "se-980030" }

Viewing a Gift List’s Items

The GiftlistLookupActor is used to view the items within a customer’s gift list. This actor is located at: /atg/ commerce/gifts/GiftlistLookupActor, and contains the items actor-chain.

8 External REST MVC Service Call Examples 239 Parameter Description

giftlistId The ID of the gift list to view.

View Gift List Item Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" -d "{ \"giftlistId\" : \"gl430003\"}" "http://localhost:8280/rest/model/atg/commerce/ gifts/GiftlistLookupActor/items?giftlistId=xgl10002"

The server response may be similar to the following:

{"giftlistItems":[ { "repositoryId":"xgi10001", "productId":"xprod1001", "siteId":"storeSiteUS", "skuId":"xsku1003", "quantity":1 }, { "repositoryId":"xgi10002", "productId":"xprod1007", "siteId":"storeSiteUS", "skuId":"xsku1026", "quantity":1 }, { "repositoryId":"xgi10003", "productId":"xprod1014", "siteId":"storeSiteUS", "skuId":"xsku1042", "quantity":1 }, { "repositoryId":"xgi10004", "productId":"xprod1047", "siteId":"storeSiteUS", "skuId":"xsku1244", "quantity":1 }, { "repositoryId":"xgi10005", "productId":"xprod2032", "siteId":"storeSiteUS", "skuId":"xsku2032", "quantity":1 }, { "repositoryId":"xgi10006", "productId":"xprod2071", "siteId":"homeSite", "skuId":"xsku2071", "quantity":1 },

240 8 External REST MVC Service Call Examples { "repositoryId":"xgi10007", "productId":"xprod2116", "siteId":"homeSite", "skuId":"xsku2116", "quantity":1 }, { "repositoryId":"xgi10008", "productId":"xprod2138", "siteId":"homeSite", "skuId":"xsku2138", "quantity":1 } ]}

Viewing a Wish List

The GiftlistLookupActor is used to view a customer’s wish list. This actor is located at: /atg/commerce/ gifts/GiftlistLookupActor, and contains the viewWishlist actor-chain.

Parameters: None

View Wish List Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" "http://localhost:8280/rest/model/atg/commerce/gifts/GiftlistLookupActor/ viewWishlist"

The server response may be similar to the following:

{"giftlistItems":[ { "repositoryId":"xgi10001", "productId":"xprod1001", "siteId":"storeSiteUS", "skuId":"xsku1003", "quantity":1 }, { "repositoryId":"xgi10002", "productId":"xprod1007", "siteId":"storeSiteUS", "skuId":"xsku1026", "quantity":1 }, { "repositoryId":"xgi10003", "productId":"xprod1014", "siteId":"storeSiteUS", "skuId":"xsku1042", "quantity":1 }, {

8 External REST MVC Service Call Examples 241 "repositoryId":"xgi10004", "productId":"xprod1047", "siteId":"storeSiteUS", "skuId":"xsku1244", "quantity":1 }, { "repositoryId":"xgi10005", "productId":"xprod2032", "siteId":"storeSiteUS", "skuId":"xsku2032", "quantity":1 }, { "repositoryId":"xgi10006", "productId":"xprod2071", "siteId":"homeSite", "skuId":"xsku2071", "quantity":1 }, { "repositoryId":"xgi10007", "productId":"xprod2116", "siteId":"homeSite", "skuId":"xsku2116", "quantity":1 }, { "repositoryId":"xgi10008", "productId":"xprod2138", "siteId":"homeSite", "skuId":"xsku2138", "quantity":1 } ]}

Searching for a Gift List

The GiftlistSearchActor is used to find a customer’s gift list. This actor is located at: /atg/commerce/ gifts/GiftlistSearchActor, and contains the search actor-chain.

Parameter Description

currentPage Sets the current page.

searchInput Looks for matching strings in owner.firstName or owner.lastName.

firstName The first name of the customer.

lastName The last name of the customer.

eventType The list event type.

eventDate The list event date.

242 8 External REST MVC Service Call Examples Parameter Description

resultsPerPage Sets the number of results to display per page.

state The state or province of the billing address.

Search for Gift List Example

curl -v -b customer_cookies.txt -H "Content-Type: application/json" -d "{ \"firstName\" : \"Stuart\", \"lastName\" : \"Schmidt\", \"eventType\": \"Other\", \"eventDate\" : \"AUG 30, 2013\"} "http://localhost:8280/rest/model/atg/commerce/ gifts/GiftlistSearchActor/search"

The server response may be similar to the following:

{"giftlists": [ { "giftlistItems": [], "instructions": null, "description": null, "name": "Birthday", "public": true, "date": {"time": 1377837000000}, "type": "Other", "repositoryId": "gl140010", "addressId": null }, { "giftlistItems": [{ "siteId": "storeSiteUS", "skuId": "xsku1043", "quantity": 2, "repositoryId": "gi50001", "productId": "xprod1015" }], "instructions": null, "description": null, "name": "updated test", "public": true, "date": {"time": 1377837000000}, "type": "Other", "repositoryId": "gl120010", "addressId": null }, { "giftlistItems": [], "instructions": null, "description": null, "name": "Anniversary", "public": true, "date": {"time": 1377837000000}, "type": "Other", "repositoryId": "gl120011", "addressId": null }

8 External REST MVC Service Call Examples 243 ]}

Working with In-Store Pickup

The StoreLocatorActor contains two actor-chains that are used for in-store pickup. The path for this actor is / atg/commerce/locations/StoreLocatorActor. For information on adding an item to the shopping cart for in-store pickup, refer to the Add Item to In-Store Pickup Example (page 194).

This actor contains the following actor-chains:

Actor-Chain Description

locateItems Used for searching for an item within stores.

currentResultPageNum Used to display search result paging.

Searching for a Store

The locateItems actor-chain is used to find stores that have the specified item.

Parameter Description

skuId The SKU ID of the item to find in the store.

countryCode Used to specify a country.

state Used to specify a state.

city Used to specify a city.

postalCode Used to specify a postal code.

distance Used to identify a distance (in meters).

maxResultsPerPage The maximum number of results to display on the page.

Search for Store Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" -d "{ \"distance\" : \"10\", \"skuId\" : \"sku30029\"}" "http://localhost:8280/ rest/model/atg/commerce/locations/StoreLocatorActor/locateItems"

244 8 External REST MVC Service Call Examples The server response may be similar to the following:

{ "FashionIsland": { "distance": 0, "postalCode": "92660", "phoneNumber": "555-555-2006", "name": "Fashion Island", "state": "CA", "address1": "401 Newport Center Drive", "stockLevel": 0, "city": "Newport", "country": "USA" }, "BiltmoreFashionPark": { "distance": 0, "postalCode": "85016", "phoneNumber": "(555) 555-1963", "name": "Biltmore Fashion Park", "state": "AZ", "address1": "2404 East Camelback Road", "stockLevel": 0, "city": "", "country": "USA" } }

Displaying Search Results for In-Store Pickup

The currentResultPageNum actor-chain is used to display stores that contain the specified item.

Parameter Description

pageNum Identifies which page of the results set is being viewed. The default value is 1, with the base value of this parameter set to1 instead of 0 for usability.

maxResultsPerPage The maximum number of results to display on the page.

Display In-Store Search Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" -d "{ \"pageNum\":\"2\", \"maxResultsPerPage\":\"2\" }" "http://localhost:8280/ rest/model/atg/commerce/locations/StoreLocatorActor/currentResultPageNum"

Identifying a State

The StateListActor is used to identify the state of a user’s profile locale. The path of this actor is /atg/ commerce/util, and it contains the states actor-chain.

8 External REST MVC Service Call Examples 245 Parameter Description

countryCode Identifies the country code of a specific customer.

State Identification Example

curl -L -v -b customer_cookies.txt -H "Content-Type: application/json" -d "{ \"countryCode\":\"US\" }" "http://localhost:8280/rest/model/atg/commerce/ util/StateListActor/states"

The server response may be similar to the following:

{"states":[ { "code":"AK", "displayName":"AK - Alaska" }, { "code":"AL", "displayName":"AL - Alabama" }, { "code":"AR", "displayName":"AR - Arkansas" },

...

} ]}

246 8 External REST MVC Service Call Examples 9 Internal REST MVC Service Call Examples

The following REST MVC services enable Call Center agents to assist customers. The following REST MVC calls examples are specific to internal users, such as those used by Oracle Commerce Service Center, and are intended for the creation of REST MVC calls for Commerce Service Center Call Center agent actions.

As described in previous sections, REST MVC calls are based on actors that perform specific functions. This section is organized by tasks that agents perform on behalf of customers. These agent-specific REST MVC calls are different than external user REST MVC calls in that they use the agent_cookies.txt file to store cookie information, and are located in the DCS-CSR modules. For REST MVC calls for external customers, refer to the External REST MVC Service Call Examples (page 183) section.

Internal REST MVC Service Calls Workflow Example

The following diagram shows an example of an agent’s workflow when adding an item to a cart. Each of the REST MVC calls performs an action that propels the agent through the workflow. Note that depending on the actions required, the process may flow differently.

9 Internal REST MVC Service Call Examples 247 This example begins with the agent logging in to the REST server, and ends when the customer is sent an order confirmation e-mail.

Note: The following examples are provided as guidelines for working with Internal REST MVC calls. The responses returned by your server may vary based upon your environment’s configuration.

Getting the Internal Session Confirmation Number

The first actor that must be invoked is the Dynamo Session Confirmation actor. As described in the Using Dynamo Session Confirmation Numbers (page 138) section, the session confirmation number is used by the REST Web Services to provide secure access to the REST calls. The Form Element (page 152) and The Component Element (page 145) use _dynSessConf for method calls and setting property values. The SessionConfirmationActor returns the session confirmation number. The path to this actor is /atg/rest and it uses the getSessionConfirmationNumber actor-chain.

Parameters: None

Session Confirmation Number Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8280/rest/model/atg/rest/SessionConfirmationActor/ getSessionConfirmationNumber"

The server response may be similar to the following:

{"sessionConfirmationNumber":-5166444348429687167}

248 9 Internal REST MVC Service Call Examples Logging Agents In and Out

The AgentProfileActor is located at /atg/agent/userprofiling/ and contains the following actor- chains:

Actor-Chain Description

login Allows an agent to log into the site.

logout Allows an agent to log out of a site.

Logging In Agents

The login actor-chain is used to log the agent into the site and verify the appropriate login and password credentials.

Parameter Description

login The login of the agent.

password The agent’s password.

Agent Log In Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"login\" : \"ServiceAdmin\" , \"password\" : \"service123\" }" "http://localhost:8280/rest/model/atg/agent/userprofiling/AgentProfileActor/ login"

If the log in information proves to be correct, the following success server response occurs:

{"userId": "svcUserAdmin>}

If the log in information proved to be incorrect, the following exception would occur:

{"formError": true, "formExceptions":[{"localizedMessage":"The password and login combination is incorrect.","errorCode":"invalidPassword"}]}

Logging Out Agents

The logout actor-chain is used to log the agent out of the site.

Parameters: None

9 Internal REST MVC Service Call Examples 249 Agent Log Out Example

curl -L -v -c agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8280/rest/model/atg/agent/userprofiling/AgentProfileActor/ logout"

Confirming Log Out

The ConfirmLogoutActor, which uses the confirmLogout actor-chain, allows you to check confirmation before logging the agent out. This actor is located at /atg/svc/ui/ formhandlers/ConfirmLogoutActor.

Parameter Description

TryLogout When set to true, performs a confirmation before logging the agent out.

Confirm Logout Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"TryLogout\": \"true\" }" "http://localhost:8181/rest/model/atg/svc/ui/ formhandlers/ConfirmLogoutActor/confirmLogout"

Changing Agents Passwords

The ChangePasswordActor, which uses the changePassword actor-chain, is used to change the password of the agent. This actor is located at /atg/svc/ui/formhandlers/ChangePasswordActor.

Parameter Description

newPassword The new password of the agent.

oldPassword The agent’s old password.

confirmPassword Confirmation of the new password to be set for the agent.

Change Agent Password Example

curl -L -v -c agent_cookies.txt -H "Content-Type: application/json" -d "{ \"oldPassword\" : \"passwordOne\" , \"newPassword\" : \"passwordTwo\", \"confirmPassword\" : \"passwordTwo\" }" "http://localhost:8181/rest/model/ atg/svc/ui/formhandlers/ChangePasswordActor/changePassword"

250 9 Internal REST MVC Service Call Examples Setting Default Login Page

You can set the default page the agent will access when logging in. The DefaultLoginPageActor, which uses the defaultLoginOption actor-chain, allows you to set the default login page. The actor is located at /atg/ svc/ui/formhandlers/DefaultLoginPageActor.

Parameter Description

agentUserDefaultHomeTab The default login page for the agent.

Set Default Login Page Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"agentUserDefaultHomeTab\": \"ticketsTab\" }" "http://localhost:8181/rest/ model/atg/svc/ui/formhandlers/DefaultLoginPageActor/defaultLoginOption"

Restoring Defaults

You can restore the defaults for agent preferences using the RestoreDefaultAgentOptionsActor, which uses the restoreDefaults actor-chain. The actor is located at /atg/svc/ui/formhandlers/ RestoreDefaultAgentOptionsActor.

Parameters: None

Restore Agent Preferences Options Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8181/rest/model/atg/svc/ui/formhandlers/ RestoreDefaultAgentOptionsActor/restoreDefaults"

Working with Calls

The following actors are used to make calls, end calls, and add call notes.

Starting a Call

The /atg/svc/agent/ui/formhandlers/StartNewCallActor contains the startNewCall actor-chain, which is used to initiate a new call in Commerce Service Center:

9 Internal REST MVC Service Call Examples 251 Parameter Description

doWarnings Determines if ticket disposition warnings will be generated for changes.

doTicketDispositionPrompt Determines if ticket disposition prompts will be generated for changes.

dispositionOption The ticket disposition option to use.

reasonCode The reason code for the ticket.

ticketNote Creates a note stored in the ticket.

publicNote Makes the note available for public viewing.

Start Call Example

This example confirms the ticket disposition settings when starting a call.

curl -L -v -b agent_cookies.txt -d "{ \"doWarnings\":true, \"doTicketDispositionPrompt\":true, \"dispositionOption\":\"save\" }" "http://localhost:8280/rest/model/atg/svc/agent/ui/formhandlers/StartNewCallActor/ startNewCall"

The server response confirmation warning may be similar to the following:

{ "isDiscardable": true, "allWarnings": ["The current working order has items in it and has not been saved. If you continue, the order will be lost."], "activeTicketDisposition": true }

This example shows how changes are made in the ticket disposition settings when starting a call.

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"doWarnings\":false, \"doTicketDispositionPrompt\":false, \"ticketNote"\: \"Junk mail\",\"reasonCode\":\"spam\", \"dispositionOption\":\"close\" }" "http://localhost:8280/rest/model/atg/svc/agent/ui/formhandlers/StartNewCallActor/ startNewCall"

Ending a Call

The /atg/svc/agent/ui/formhandlers/EndCallActor contains the endCall actor-chain, which is used to end a call in Commerce Service Center:

252 9 Internal REST MVC Service Call Examples Parameter Description

doWarnings Determines if ticket disposition warnings will be generated for changes.

doTicketDispositionPrompt Determines if ticket disposition prompts will be generated for changes.

dispositionOption Provides the ticket disposition option to use.

reasonCode The reason code for the ticket.

ticketNote Creates a note stored in the ticket.

publicNote Makes the note available for public viewing.

End Call Example

This example confirms the ticket disposition settings when ending a call.

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"doWarnings\":true, \"doTicketDispositionPrompt\":true, \"dispositionOption\": \"save\" }" "http://localhost:8280/rest/model/atg/svc/agent/ui/ formhandlers/EndCallActor/endCall"

The server response confirmation warning may be similar to the following:

{ "isDiscardable": true, "allWarnings": ["The current working order has items in it and has not been saved. If you continue, the order will be lost."], "activeTicketDisposition": true }

This example shows how changes are made in the ticket disposition settings when ending a call.

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"doWarnings\":false, \"doTicketDispositionPrompt\":false, \"ticketNote\": \"Junk mail\",\"reasonCode\":\"spam\", \"dispositionOption\":\"close\" }" "http://localhost:8280/rest/model/atg/svc/agent/ui/formhandlers/EndCallActor/ endCall"

Adding a Call Note

The /atg/svc/ui/formhandlers/TicketingActor contains the addNote actor-chain, which is used to add a call note to a ticket in Commerce Service Center:

9 Internal REST MVC Service Call Examples 253 Parameter Description

noteText The text of the note.

share Identifies if the note should be shared with the customer.

inbound Marks the note as either being “inbound”, which is a note that was initiated by the customer, or “outbound”, which is a note initiated by the agent.

noteType The type of note, which, in this case, is call.

Add Call Note Example

curl -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"noteType"\ : \"call\", \"noteText\" : \"The user would like to be notified if we get more inventory in for this product.\", \"share\": \"false\", \"inbound\": \"true\" }" "http://localhost:8180/rest/model/atg/svc/ui/formhandlers/ TicketingActor/addNote"

Working with Tickets

The TicketActor allows an agent to work with a specific ticket. This actor is located at /atg/svc/agent/ui/ formhandlers/TicketActor.

Note: The TicketActor is different than the TicketingActor. Refer to the Adding a Call Note (page 253) example for information on the TicketingActor.

The TicketActor contains the following actor-chains:

Actor-Chain Description

workTicket Used by an agent to access a specific ticket.

createNewTicket Used to create a new ticket.

saveTicket Saves the current ticket.

associateTicket Associates a ticket.

escalateTicket Escalates a ticket.

closeTicket Closes a ticket.

releaseTicket Releases the ticket.

deferTicket Allows an agent to defer a ticket.

254 9 Internal REST MVC Service Call Examples Actor-Chain Description

reassignTicket Allows the agent to reassign a ticket.

sendToGroup Enables an agent to send a ticket to a predefined group.

closeAsDuplicate Closes a ticket as a duplicate ticket.

beginEdit Allows an agent to begin editing a ticket.

endEdit Completes the editing of a ticket.

viewActiveTicket Provides a list of all active tickets.

Selecting a Ticket to Work On

The workTicket actor-chain, allows an agent to specify a ticket to work on.

Parameter Description

ticketId The ID of the ticket to work on.

doTicketDispositionPrompt If set to true, will present ticket disposition prompts to the agent.

dispositionOption Provides a ticket disposition option.

reasonCode Provides a ticket disposition reason code.

ticketNote Provides a note associated with the ticket.

publicNote Identifies if the ticket note is public.

subStatus Provides a sub-status for the ticket.

Select a Ticket Example

curl -v -b agent_cookies.txt -H "Content-Type: application/json" –d "{ \"ticketId\":\"2203\"}""http://localhost:8180/rest/model/atg/svc/agent/ ui/formhandlers/TicketActor/workTicket"

Creating a New Ticket

The createNewTicket actor-chain allows an agent to create a new ticket, making it the current ticket.

9 Internal REST MVC Service Call Examples 255 Parameter Description

dispositionOption Identifies a ticket disposition used for this ticket.

reasonCode Adds a reason code to the ticket.

ticketNote Adds a ticket note to the new ticket.

subStatus Provides a sub-status for the ticket.

publicNote Identifies if the ticket note is public.

doDispositionPrompt If set to true, will present ticket disposition prompts to the agent.

Create New Ticket Example

curl -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8180/rest/model/atg/svc/agent/ui/formhandlers/TicketActor/ createNewTicket"

Saving a Ticket

The saveTicket actor-chain allows an agent to save a ticket.

Parameter Description

ticketId The ID of the ticket to save.

Save Ticket Example

curl -v -b agent_cookies.txt -H "Content-Type: application/json" –d "{\"ticketId\" : \"2203\"}" "http://localhost:8180/rest/model/atg/svc/agent/ ui/formhandlers/TicketActor/saveTicket"

Associating a Ticket

The associateTicket actor-chain allows an agent to associate a ticket.

Parameter Description

ticketId The ID of the ticket to associate.

associatedTicketId The ID of the associated ticket.

256 9 Internal REST MVC Service Call Examples Parameter Description

doTicketDispositionPrompt If set to true, will present ticket disposition prompts to the agent.

dispositionOption Provides a ticket disposition option.

reasonCode Provides a disposition reason code.

ticketNote Provides a note associated with the ticket.

subStatus Provides a sub-status for the ticket.

Associate Ticket Example

curl -v -b agent_cookies.txt -H "Content-Type: application/json" –d "{\"ticketId\" : \"2203\", \"associatedTicketId\" : \"2200\"}" "http://localhost:8180/rest/model/atg/svc/agent/ui/formhandlers/TicketActor/ associateTicket"

Escalating a Ticket

The escalateTicket actor-chain allows an agent to escalate a ticket.

Parameter Description

ticketId The ID of the ticket to escalate.

escalationLevel The level to which the ticket should be escalated.

group The group to which the ticket should be escalated.

doTicketDispositionPrompt If set to true, will present ticket disposition prompts to the agent.

dispositionOption Identifies a ticket disposition used for this ticket.

reasonCode Adds a reason code to the ticket.

ticketNote Adds a ticket note to the new ticket.

publicNote Identifies if the ticket note is public.

subStatus Provides a sub-status for the ticket.

Escalate Ticket Example

curl -v -b agent_cookies.txt -H "Content-Type: application/json" –d

9 Internal REST MVC Service Call Examples 257 "{\"ticketId\" : \"2203\" \"escalationLevel\" : \"Tier2\" }" "http://localhost:8180/rest/model/atg/svc/agent/ui/formhandlers/TicketActor/ escalateTicket"

Closing a Ticket

The closeTicket actor-chain allows an agent to close a ticket.

Parameter Description

ticketId The ID of the ticket to close.

doTicketDispositionPrompt If set to true, will present ticket disposition prompts to the agent.

dispositionOption Identifies a ticket disposition used for this ticket.

reasonCode Adds a reason code to the ticket.

ticketNote Adds a ticket note to the new ticket.

publicNote Identifies if the ticket note is public.

subStatus Provides a sub-status for the ticket.

Close Ticket Example

curl –L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{\"ticketId\" : \"2203\" }" "http://localhost:8180/rest/model/atg/svc/ agent/ui/formhandlers/TicketActor/closeTicket"

Releasing a Ticket

The releaseTicket actor-chain allows an agent to release a ticket.

Parameter Description

ticketId The ID of the ticket to release.

doTicketDispositionPrompt If set to true, will present ticket disposition prompts to the agent.

dispositionOption Identifies a ticket disposition used for this ticket.

reasonCode Adds a reason code to the ticket.

ticketNote Adds a ticket note to the new ticket.

258 9 Internal REST MVC Service Call Examples Parameter Description

publicNote Identifies if the ticket note is public.

subStatus Provides a sub-status for the ticket.

Release Ticket Example

curl –L -v -b agent_cookies.txt -H "Content-Type: application/json" –d "{\"ticketId\" : \"2203\" }" "http://localhost:8180/rest/model/atg/svc/ agent/ui/formhandlers/TicketActor/releaseTicket"

Deferring a Ticket

The deferTicket actor-chain allows an agent to defer a ticket.

Parameter Description

ticketId The ID of the ticket to defer.

date The date to which to defer the ticket.

retain Boolean option to retain the ticket or not.

share Identifies if the ticket should be shared or not.

doTicketDispositionPrompt If set to true, will present ticket disposition prompts to the agent.

dispositionOption Identifies a ticket disposition used for this ticket.

reasonCode Adds a reason code to the ticket.

ticketNote Adds a ticket note to the new ticket.

publicNote Identifies if the ticket note is public.

subStatus Provides a sub-status for the ticket.

Defer Ticket Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" –d "{\"ticketId\" : \"10603\", \"retain\" : \"true\", \"reasonCode\" : \"NeedHelp\"}" "http://localhost:8181/rest/model/atg/svc/agent/ui/formhandlers/TicketActor/ deferTicket"

9 Internal REST MVC Service Call Examples 259 Reassigning a Ticket

The reassignTicket actor-chain allows an agent to reassign a ticket.

Parameter Description

ticketId The ID of the ticket to reassign.

doTicketDispositionPrompt If set to true, will present ticket disposition prompts to the agent.

reassignAgent The agent to which the ticket should be assigned.

dispositionOption Identifies a ticket disposition used for this ticket.

reasonCode Adds a reason code to the ticket.

ticketNote Adds a ticket note to the new ticket.

publicNote Identifies if the ticket note is public.

subStatus Provides a sub-status for the ticket.

Reassign Ticket Example

curl –L -v -b agent_cookies.txt -H "Content-Type: application/json" –d "{\"ticketId\" : \"2203\", \"reassignAgent\" : \"agent007\" }" "http://localhost:8180/rest/model/atg/svc/agent/ui/formhandlers/TicketActor/ reassignTicket"

Sending a Ticket to a Group

The sendToGroup actor-chain allows an agent to send a ticket to a specific group.

Parameter Description

ticketId The ID of the ticket to send.

group The group to which the ticket should be sent.

doTicketDispositionPrompt If set to true, will present ticket disposition prompts to the agent.

dispositionOption Identifies a ticket disposition used for this ticket.

reasonCode Adds a reason code to the ticket.

ticketNote Adds a ticket note to the new ticket.

260 9 Internal REST MVC Service Call Examples Parameter Description

publicNote Identifies if the ticket note is public.

subStatus Provides a sub-status for the ticket.

Send Ticket to Group Example

curl –L -v -b agent_cookies.txt -H "Content-Type: application/json" –d "{\"ticketId\" : \"2203\" \"group\" : \"MyTicketQueue\" }" "http://localhost:8180/rest/model/atg/svc/agent/ui/formhandlers/TicketActor/ sendToGroup"

Closing a Ticket as Duplicate

The closeAsDuplicate actor-chain allows an agent to close a ticket that has been identified as a duplicate.

Parameter Description

ticketId The ID of the ticket to close.

duplicateTicketId The ID of the duplicated ticket.

doTicketDispositionPrompt If set to true, will present ticket disposition prompts to the agent.

dispositionOption Identifies a ticket disposition used for this ticket.

reasonCode Adds a reason code to the ticket.

ticketNote Adds a ticket note to the new ticket.

publicNote Identifies if the ticket note is public.

subStatus Provides a sub-status for the ticket.

Close Ticket as Duplicate Example

curl –L -v -b agent_cookies.txt -H "Content-Type: application/json" –d "{\"ticketId\" : \"458514\" \"duplicateTicketId\" : \"2200\" }" "http://localhost:8180/rest/model/atg/svc/agent/ui/formhandlers/TicketActor/ closeAsDuplicate"

Editing a Ticket

The beginEdit actor-chain allows an agent to begin editing a ticket.

9 Internal REST MVC Service Call Examples 261 Parameter Description

ticketId The ID of the ticket to edit.

doTicketDispositionPrompt If set to true, will present ticket disposition prompts to the agent.

dispositionOption Identifies a ticket disposition used for this ticket.

reasonCode Adds a reason code to the ticket.

ticketNote Adds a ticket note to the new ticket.

subStatus Provides a sub-status for the ticket.

Edit Ticket Example

curl –L -v -b agent_cookies.txt -H "Content-Type: application/json" –d "{\"ticketId\" : \"458514\" }" "http://localhost:8180/rest/model/atg/svc/agent/ ui/formhandlers/TicketActor/beginEdit"

End Editing a Ticket

The endEdit actor-chain allows an agent to end editing a ticket, saving the information added during the edit. The endEdit actor-chain also implicitly calls the beginEdit actor-chain, which sets the current ticket to “isEditable”.

Parameter Description

ticketId The ID of the ticket to edit.

doTicketDispositionPrompt If set to true, will present ticket disposition prompts to the agent.

dispositionOption Identifies a ticket disposition used for this ticket.

reasonCode Adds a reason code to the ticket.

ticketNote Adds a ticket note to the new ticket.

subStatus Provides a sub-status for the ticket.

parameterMap.priority The ticket priority.

parameterMap.ticketQueue The ticket queue of the ticket.

parameterMap.customerDetails_firstName The first name of the customer associated with the ticket.

262 9 Internal REST MVC Service Call Examples Parameter Description

parameterMap.customerDetails_lastName The last name of the customer associated with the ticket.

parameterMap.customerDetails_phone The phone number of the customer associated with the ticket.

parameterMap.customerDetails_email The email of the customer associated with the ticket.

parameterMap.customerDetails_address The address of the customer associated with the ticket.

parameterMap.customerDetails_city The city of the customer associated with the ticket.

parameterMap.customerDetails_state The state where the customer who is associated with the ticket resides.

parameterMap.customerDetails_country The country of the customer associated with the ticket.

parameterMap.customerDetails_postalCode The postal code of the customer associated with the ticket.

End Editing Ticket Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" –d "{\"parameterMap\":{\"atg-rest-class-type\":\"java.util.HashMap\", \"atg-rest-values\":{\"priority\":\"3\",\"ticketQueue\":\"myTicketQueue\", \"customerDetails_firstName\":\"John\",\"customerDetails_lastName\":\"Smith\", \"customerDetails_phone\":\"07876788144\",\"customerDetails_email\": \"[email protected]\",\"customerDetails_address\":\"1 Main Street\" ,\"customerDetails_city\":\"Berlin\",\"customerDetails_state\": \"MA\",\"customerDetails_country\":\"US\",\"customerDetails_postalCode\": \"01580\"}}, \"ticketId\" : \"458514\"}" "http://localhost:8080/rest/model/atg/ svc/agent/ui/formhandlers/TicketActor/endEdit?atg-rest-output=json"

Viewing Active Tickets

The viewActiveTickets actor-chain displays a list of all active ticket. It contains the following parameter:

Parameter Description

sortDirection The way in which you want to sort the list.

sortField The field used to sort the list.

9 Internal REST MVC Service Call Examples 263 Parameter Description

currentPage The paging results of the search to display.

resultsPerPage The number of results to display per page.

View Active Tickets Example

curl –L -v -b agent_cookies.txt -H "Content-Type: application/json" –d "{\"sortField\" : \"id\" \"sortDirection\" : \"desc\", \"currentPage\" : \"0\", \"resultsPerPage\" : \"3\" }" "http://localhost:8180/rest/model/atg/svc/agent/ui/ formhandlers/TicketActor/viewActiveTickets"

Looking Up a Ticket

The TicketLookupActor allows an agent to look up a ticket. This service calls the TicketLookupDroplet to provide search parameters. The TicketLookupActor is located at /atg/ticketing/droplet/.

This actor uses the lookup actor-chain.

Parameter Description

searchProperty The name of the ticketing property to search on when performing the lookup.

value The value of the property.

includes Looks up tickets whose searchProperty includes the value provided if set to true. If set to false, searches using a straight comparison.

ticketId The ID of the ticket.

startIndex The first ticket to return. This property is used to break large query results into smaller pieces.

numTickets The number of tickets to return.

Lookup Ticket Examples

The following example looks for tickets that were created on the telephone. The server will respond with a list of all tickets and the corresponding ticket information that meet the criteria.

curl –L -v -b agent_cookies.txt -H "Content-Type: application/json" –d "{\"searchProperty\" : \"creationChannel\" , \"value\" : \"telephony\" }" "http://localhost:8180/rest/model/atg/ticketing/droplet/TicketLookupActor/lookup"

This example looks for a specific ticket, which is identified by its ticket ID.

264 9 Internal REST MVC Service Call Examples curl –L -v -b agent_cookies.txt -H "Content-Type: application/json" –d "{\"ticketId\" : \"22003\" }" "http://localhost:8180/rest/model/atg/ticketing/ droplet/TicketLookupActor/lookup"

The server response to this example might be similar to the following:

{ "tickets": { "creationChannel": "telephony", "hasPendingOwnership": false, "relatedTickets": [], "escalationCount": 1, "externalTicketSystem": null, "escalationLevel": "Tier3", "pendingTime": null, "activitiesByDate": [{ "abstract": null, "previousSubStatus": { "subStatusName": "Closed", "parentStatus": "Closed" }, "application": "Agent", "textContent": null, "newSubStatus": { "subStatusName": "ReOpened", "parentStatus": "Open" }, "reason": null, "inProgress": null, "type": "statusChange", "id": "1700003", "activityData": null, "userName": null, "creationTime": { "time": 1375785034000 }, "public": false, "heading": null }, { "abstract": null, "application": "Agent", "textContent": null, "reason": null, "inProgress": null, "type": "agentAssignment", "id": "1700004", "activityData": null, "userName": null, "creationTime": { "time": 1375785034000 }, "public": false, "heading": null }, { "abstract": null, "application": "Agent",

9 Internal REST MVC Service Call Examples 265 "textContent": null, "reason": null, "inProgress": null, "type": "agentAssignment", "id": "1600009", "activityData": null, "userName": null, "creationTime": { "time": 1375716548000 }, "public": false, "heading": null }, { "abstract": null, "previousSubStatus": { "subStatusName": "Closed", "parentStatus": "Closed" }, "application": "Agent", "textContent": null, "newSubStatus": { "subStatusName": "ReOpened", "parentStatus": "Open" }, "reason": null, "inProgress": null, "type": "statusChange", "id": "1600008", "activityData": null, "userName": null, "creationTime": { "time": 1375716548000 }, "public": false, "heading": null }, { "abstract": null, "previousSubStatus": { "subStatusName": "ReOpened", "parentStatus": "Open" }, "application": "Agent", "textContent": null, "newSubStatus": { "subStatusName": "Closed", "parentStatus": "Closed" }, "reason": null, "inProgress": null, "type": "statusChange", "id": "1600010", "activityData": null, "userName": null, "creationTime": { "time": 1375716548000 }, "public": false, "heading": null

266 9 Internal REST MVC Service Call Examples }, { "abstract": null, "previousSubStatus": { "subStatusName": "Open", "parentStatus": "Open" }, "application": "Agent", "textContent": null, "newSubStatus": { "subStatusName": "Closed", "parentStatus": "Closed" }, "reason": null, "inProgress": null, "type": "statusChange", "id": "1600005", "activityData": null, "userName": null, "creationTime": { "time": 1375716201000 }, "public": false, "heading": null }, { "abstract": null, "application": "Agent", "textContent": null, "reason": null, "inProgress": null, "type": "agentAssignment", "id": "999999", "activityData": null, "userName": null, "creationTime": { "time": 1375276229000 }, "public": false, "heading": null }], "id": "2200", "duplicateOfTicketId": null, "loadedTimestamp": null, "slaBaseTimestamp": { "time": 1374054964000 }, "description": null, "priority": 0, "lastModifiedInDays": 0, "customerDetails": null, "creationTime": { "time": 1374054650000 }, "application": "Agent", "lastModified": { "time": 1376639939000 }, "originatingTicketId": null, "ageInDays": 30,

9 Internal REST MVC Service Call Examples 267 "mergeable": true, "externalReferences": [], "inProgressActivity": null, "loaded": false, "externalTicketId": null, "inboundChannelAddress": null, "subStatus": { "subStatusName": "Open", "parentStatus": "Open" }, "pushable": false, "due": null, "releaseTime": null, "defaultOutboundChannel": "unknown", "user": null, "displayId": "2200", "ticketQueue": null } }

Searching for a Ticket

The TicketSearchActor allows an agent to search for ticket. This service uses the searchTicketFormHandler when working with search parameters. The TicketSearchActor is located at / atg/svc/ui/formhandlers/.

This actor uses the findTicket actor-chain.

Parameter Description

currentPage The paging results of the search to display.

resultsPerPage The number of results to display per page.

sortDirection The way in which you want to sort the list.

sortField The field used to sort the list.

parameterMap.id The ID of the ticket to find.

parameterMap.subStatus_subStatusName The name of the sub-status of the ticket.

parameterMap.ticketQueue_id The ticket queue ID of the ticket.

parameterMap.escalationLevel The escalation level of the ticket.

parameterMap.customerDetails_firstName The first name of the customer associated with the ticket.

parameterMap.customerDetails_lastName The last name of the customer associated with the ticket.

268 9 Internal REST MVC Service Call Examples Parameter Description

parameterMap.customerDetails_phone The phone number of the customer associated with the ticket.

parameterMap.customerDetails_email The email address of the customer associated with the ticket.

parameterMap.description The ticket description.

parameterMap.owningAgentId The agent ID who owns the ticket.

parameterMap.dates_byCreatedDate The created by date.

parameterMap.dates_pastOrFromTo A date range from which to retrieve tickets.

parameterMap.dates_past A date after which tickets will be retrieved. For example, tickets created after December 1, 2013.

parameterMap.dates_past2 A secondary date after which tickets will be retrieved.

parameterMap.dates_fromDate A date from which tickets will be retrieved. Use in tandem with dates_toDate to set a date range.

parameterMap.dates_toDate A date to which tickets will be retrieved. Use in tandem with dates_fromDate to set a date range.

parameterMap.dates_pastOrFromTo2 An optional additional past or from date criteria.

parameterMap.dates_byLastModified Search for tickets by the date of the last modification.

parameterMap.dates_modifiedFrom Search for tickets modified from a specific date.

parameterMap.dates_modifiedTo Search for a ticket modified up to a specific date.

Search Tickets Examples

The following example searches for a specific ticket using the ticket ID.

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" –d "{\"parameterMap\":{\"atg-rest-class-type\":\"java.util.HashMap\", \"atg-rest-values\":{\"id\":\"460916\"}}}" "http://localhost:8080/rest/ model/atg/svc/ui/formhandlers/TicketSearchActor/findTickets"

The following example will return a list of all open tickets:

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" –d "{\"sortField\" : \"id\" ,\"sortDirection\" : \"desc\",\"parameterMap\": {\"atg-rest-class-type\":\"java.util.HashMap\", \"atg-rest-values\":{\"id\":\"\" , \"subStatus_subStatusName\":\"Open\", \"ticketQueue_id\":\"\", \"escalationLevel\":\"\",\"customerDetails_firstName\":\"\", \"customerDetails_lastName\":\"\",\"customerDetails_phone\":\"\", \"customerDetails_email\":\"\", \"description\":\"\",

9 Internal REST MVC Service Call Examples 269 \"owningAgentId\":\"\", \"dates_byCreatedDate\":\"\", \"dates_pastOrFromTo\":\"\", \"dates_past\":\"\", \"dates_past2\":\"\", \"dates_fromDate\":\"\", \"dates_toDate\":\"\",\"dates_pastOrFromTo2\":\"\", \"dates_byLastModified\":\"\", \"dates_modifiedFrom\":\"\", \"dates_modifiedTo\":\"\"}}}" "http://localhost:8080/ rest/model/atg/svc/ui/formhandlers/TicketSearchActor/findTickets"

Reviewing a Ticket Status

The TicketStatusDescriptionActor allows an agent to look up a ticket’s status. This actor is located at / atg/ticketing/TicketStatusDescriptorActor.

This actor uses the statusDescription actor-chain.

Parameter Description

descriptionId The ID of the ticket description.

baseName The name of the ticket status.

elementName The element name of the ticket status.

Ticket Status Description Example

The following example looks for tickets that have a status of CLOSED.

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" –d "{\"baseName\" : \"STATUS\", \"elementName\" : \"element\", \"descriptionId\" : \"Closed\"}" "http://localhost:8080/rest/model/atg/ticketing/ TicketStatusDescriptionActor/statusDescription"

Viewing a Customer

The /atg/svc/agent/ui/formhandlers/ServiceUIProfileActor contains the viewCustomer actor- chain:

Parameter Description

customerId The ID of the customer to view.

View Customer Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{

270 9 Internal REST MVC Service Call Examples \"customerId\" : \"se-570050\"}" "http://localhost:8280/rest/model/atg/svc/agent/ ui/formhandlers/ServiceUIProfileActor/viewCustomer"

Working with Customer Profiles

The /atg/svc/agent/ui/formhandlers/CustomerProfileActor contains the following actor-chains:

Actor-Chain Description

create Creates a new customer profile.

update Updates an existing customer profile.

addNote Adds a note to a customer profile.

Creating a New Customer Profile

The create actor-chain is used to create a new customer profile. This actor-chain is also used to create a new Commerce Service Center account when the orderId and saveCreditCards parameters are used.

Parameter Description

firstName The first name of the new customer.

middleName The middle name or initial of the new customer.

lastName The last name of the new customer.

email The e-mail address of the new customer.

login The customer’s login.

password The customer’s password.

dateOfBirth The customer’s date of birth.

orderId Used when creating an account. Indicates the order ID. If this property is set, and saveCreditCards is set to true, copies the credit card information from the order to the user’s profile. Used with Commerce Service Center only.

saveCreditCards Used when creating an account. Indicates if the credit card information for the customer should be saved. Used with Commerce Service Center only.

address.address1 The first address field associated with the customer’s address.

9 Internal REST MVC Service Call Examples 271 Parameter Description

address.address2 The second address field associated with the customer’s address.

address.city The city associated with the customer’s address.

address.companyName A company name associated with the customer’s address.

address.country A country associated with the customer’s address.

address.county A county associated with the customer’s address.

address.jobTitle A job title associated with the customer’s address.

address.postalCode The postal code associated with the customer’s address.

address.faxNumber A fax number associated with the customer’s address.

address.firstName The first name of the customer associated with the address.

address.middleName The middle name or initial of the customer associated with the address.

address.lastName The last name of the customer associated with the address.

address.phoneNumber The phone number associated with the customer’s address.

address.prefix A prefix associated with the customer, such as Mr. or Dr.

address.state The state associated with the customer’s address.

address.suffix A suffix associated with the customer, such as Jr.

Create New Customer Profile Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{\"firstName\":\"Bill\", \"middleName\":\"T\", \"lastName\":\"Hitchock\", \"email\":\"[email protected]\", \"login\":\"bill18\", \"password\": \"tempPassword\", \"dateOfBirth\":\"AUG 30, 1970\", \"address\": {\"atg-rest-class-type\": \"java.util.HashMap\", \"atg-rest-values\": {\"phoneNumber\":\"555-111-2222\"}} }" "http://localhost:8280/rest/ model/atg/svc/agent/ui/formhandlers/CustomerProfileActor/create"

Create New Customer Account Example

The following example shows how you can create a new C account based upon a customer profile by including the orderId and the saveCreditCards parameters. This service is used specifically on the Commerce Service Center Order Completion page, once you have created and completed an order. You could use this service to create a new user, and then copy the payment information from the order into the user’s profile:

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{\"orderId\":\"o99720003\", \"saveCreditCards\":true, \"firstName\":\"Bill\", \"middleName\":\"T\", \"lastName\":\"Hitchock\", \"email\":\"[email protected]\", \"login\":\"bill14\", \"password\":\"tempPassword\", \"dateOfBirth\":

272 9 Internal REST MVC Service Call Examples \"AUG 30, 1970\", \"address\":{\"atg-rest-class-type\":\"java.util.HashMap\", \"atg-rest-values\": {\"phoneNumber\":\"555-111-2222\"}} }" "http://localhost:8280/rest/model/atg/svc/agent/ui/formhandlers/ CustomerProfileActor/create"

Updating an Existing Customer Profile

The update actor-chain is used to update a customer profile.

Parameter Description

firstName The first name of the customer.

middleName The middle name or initial of the customer.

lastName The last name of the customer.

email The e-mail address of the customer.

dateOfBirth The customer’s date of birth.

address.address1 The first address field associated with the customer’s address.

address.address2 The second address field associated with the customer’s address.

address.city The city associated with the customer’s address.

address.companyName A company name associated with the customer’s address.

address.country A country associated with the customer’s address.

address.county A county associated with the customer’s address.

address.jobTitle A job title associated with the customer’s address.

address.postalCode The postal code associated with the customer’s address.

address.faxNumber A fax number associated with the customer’s address.

address.firstName The first name of the customer associated with the address.

address.middleName The middle name or initial of the customer associated with the address.

address.lastName The last name of the customer associated with the address.

address.phoneNumber The phone number associated with the customer’s address.

address.prefix A prefix associated with the customer, such as Mr. or Dr.

address.state The state associated with the customer’s address.

address.suffix A suffix associated with the customer, such as Jr.

9 Internal REST MVC Service Call Examples 273 Update Customer Profile Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{\"firstName\":\"Bill\", \"middleName\":\"Theodore\", \"lastName\":\"Hitchock\", \"email\":\"[email protected]\", \"dateOfBirth\":\"AUG 30, 1972\", \"address\":{\"atg-rest-class-type\":\"java.util.HashMap\", \"atg-rest-values\": {\"address1\":\"333 Main Street\", \"address2\":\"Suite 900\", \"city\":\"Tacoma\",\"state\":\"WA\", \"country\":\"USA\", \"postalCode\": \"00123\", \"phoneNumber\":\"555-111-2225\"}} }" "http://localhost:8280/rest/ model/atg/svc/agent/ui/formhandlers/CustomerProfileActor/update"

Adding a Note to a Customer Profile

The addNote actor-chain is used to create a note that is included in the customer profile.

Parameter Description

comment The text of the note that is attached to the customer profile.

Add Customer Profile Note Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{\"comment\":\"Customer has many loyalty points that they should use.\" }" "http://localhost:8180/rest/model/atg/svc/agent/ui/formhandlers/ CustomerProfileActor/addNote"

Searching for a Customer Profile

The atg/svc/agent/ui/formhandlers/CustomerSearchTreeQueryActor contains actor-chains that perform the following:

Actor-Chain Description

search Searches for a customer profile.

clearForm Clears the saved session search request.

The search actor-chain is used to search for customer profiles. It identifies the way that the results will display, including the paging and sort order.

274 9 Internal REST MVC Service Call Examples Parameter Description

fieldCount The array size of the fields returned.

pageSize The number of results per page. The default is set to 10.

pageNum The page number within the pages of results This parameter is zero-based, with the default set to 0.

maxResults The maximum number of results to display. The default is set to 100.

docProps Which properties should be returned for each result. The default is set to all.

docSort Type of sorting used to display the results. The default is strprop. For number fields, use numprop sorting.

docSortOrder Sets the sort order as ascending or descending. The default is set to ascending.

docSortProp The field used to sort the results on. The default is lastName.

saveRequest Identifies if the request should be saved within the session. The default is true.

fields[].name The order property name.

fields[].op The operation, which should be set to starts.

field[].value The value that is used for searching this field.

Search Customer Profile Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"pageNum\":0, \"pageSize\":2, \"fieldCount\":\"1\", \"fields\": {\"atg-rest-class-type\":\"java.util.ArrayList\", "atg-rest-class-descriptor\" : { \"atg-rest-values\" : {\"container-class\" : \"java.util.ArrayList\", \"element-class\":\"atg.textsearch.client.Field\"}}, \"atg-rest-values\": [{\"atg-rest-class-type\":\"atg.textsearch.client.Field\", \"name\": \"lastName\",\"op\": \"starts\",\"value\": \"t\"} ]}}" "http://localhost:8280/ rest/model/atg/svc/agent/ui/formhandlers/CustomerSearchTreeQueryActor/ search"

The server response may be similar to the following:

{ "searchResponse": {"items": [ { "lastName": "Taylor", "postalCode": "89501", "phoneNumber": "2125558105", "email": "[email protected]", "profileId": "se-570105", "login": "[email protected]", "firstName": "Chuck" },

9 Internal REST MVC Service Call Examples 275 { "lastName": "Thomas", "postalCode": "59101", "phoneNumber": "2125558855", "email": "[email protected]", "profileId": "se-570056", "login": "[email protected]", "firstName": "Juan" } ]}, "pagesAvailable": 2 }

Clearing a Customer Search Session

The clearForm actor-chain is used to clear the saved session search request.

Properties: None

Clear Customer Search Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8280/rest/model/atg/svc/agent/ui/formhandlers/ CustomerSearchTreeQueryActor/clearForm"

Selecting a Customer to Work On

The ChangeCurrentCustomerActor allows an agent to select a customer and make them the current customer in the Commerce Service Center global context area. This enables an agent to work on the customer and any associated tickets. This actor uses the selectCustomer actor-chain to obtain customer information.

Additionally, this actor can be configured to present ticket disposition information. This actor is located at: / atg/svc/agent/ui/formhandlers/ChangeCurrentCustomerActor.

Parameter Description

customerId The ID of the customer to select.

doWarnings If set to true, will present a warning to the agent when proceeding to the new site.

doTicketDispositionPrompt If set to true, will present ticket disposition prompts to the agent.

dispositionOption If doTicketDispositionPrompt is selected, this provides a ticket disposition option.

reasonCode If doTicketDispositionPrompt is selected, this provides a ticket disposition reason code.

276 9 Internal REST MVC Service Call Examples Parameter Description

ticketNote Used to provide a note associated with the ticket.

publicNote Identifies if the ticket note is public.

Select Customer to Work On Example

This example confirms the ticket disposition.

curl -x 127.0.0.1:8888 -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"customerId\" : \"480010\", \"doWarnings\":true, \"doTicketDispositionPrompt\":true, \"dispositionOption\":\"save\" }" "http://localhost:8280/rest/model/atg/svc/agent/ui/formhandlers/ ChangeCurrentCustomerActor/selectCustomer"

This example makes changes to the ticket disposition.

curl -x 127.0.0.1:8888 -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"customerId\" : \"480010\", \"doWarnings\":false, \"doTicketDispositionPrompt\":false, \"ticketNote\":\"Junk mail\", \"reasonCode\":\"spam\", \"dispositionOption\":\"close\" }" "http://localhost:8280/rest/model/atg/svc/agent/ui/formhandlers/ ChangeCurrentCustomerActor/selectCustomer"

The server response may be similar to this:

{ "isDiscardable": false, "allWarnings": [], "activeTicketDisposition": true }

Working with Customer Profile Addresses

The /atg/svc/agent/ui/profile/AddressBookActor contains the following actor-chains:

Actor-Chain Description

addAddress Adds an address to a customer profile.

updateAddress Updates an address in a customer profile.

9 Internal REST MVC Service Call Examples 277 Actor-Chain Description

deleteAddress Deletes an address from a customer profile.

Adding an Address to a Customer Profile

The addAddress actor-chain is used to create a new address in a customer profile.

Parameter Description

firstName The first name of the customer associated with this address.

middleName The middle name or initial of the customer associated with this address.

lastName The last name of the customer associated with this address.

address1 The first address field of the address.

address2 The second address field of the address.

city The city of the address.

state The state or province of the address.

postalCode The postal code of the address.

country The country of the address.

phoneNumber The phone number associated with this address.

setBillingAddress Boolean value that sets the address as the default billing address.

setShippingAddress Boolean value that sets the address as the default shipping address

Add Address to Customer Profile Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ "\firstName\" : "\Jack\", "\lastName\" : "\Dill\", "\address1\" : \"123 Main St\", "\city\" : "\\", "\state\" : "\CA\", "\postalCode\" : "\99021\", "\phoneNumber\" : "\123-123-1234\", "\country\" : "\US\" }" "http://localhost:8280/rest/model/atg/svc/agent/profile/AddressBookActor/ addAddress"

The server response would be:

{"addressId" : "270015"}

278 9 Internal REST MVC Service Call Examples Editing an Address in a Customer Profile

The updateAddress actor-chain is used to edit or update an existing address in a customer profile.

Parameter Description

addressId Identifies the address to edit.

firstName The first name of the customer associated with this address.

middleName The middle name or initial of the customer associated with this address.

lastName The last name of the customer associated with this address.

address1 The first address field of the address.

address2 The second address field of the address.

city The city of the address.

state The state or province of the address.

postalCode The postal code of the address.

country The country of the address.

phoneNumber The phone number associated with this address.

setBillingAddress Boolean value that sets the address as the default billing address.

setShippingAddress Boolean value that sets the address as the default shipping address.

Edit Customer Profile Address Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"addressId\": \"270015\", \"firstName\":\"Jack\", \"lastName\":\"Dill\", \"address1\":\"124 Main St\", \"city\":\"Seaside\", \"state\":\"CA\", \"postalCode\":\"99022\",\"phoneNumber\":\"555-123-1234\", \"country\":\"US\" }" "http://localhost:8280/rest/model/atg/svc/agent/profile/AddressBookActor/ updateAddress"

Deleting an Address from a Customer Profile

The deleteAddress actor-chain is used to delete an existing address from a customer profile. Note that you cannot delete an address that has been identifies as a default billing or shipping address.

9 Internal REST MVC Service Call Examples 279 Parameter Description

addressId Identifies the address to delete.

Delete Customer Profile Address Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"addressId\": \"270015\" }" "http://localhost:8280/rest/model/atg/svc/agent/ profile/AddressBookActor/deleteAddress"

Working with Credit Cards Within a Customer Profile

The /atg/commerce/custsvc/repository/CreditCardActor contains actor-chains that perform the following:

Actor-Chain Description

addCreditCard Adds a new credit card to a customer profile.

updateCreditCard Updates credit card information in a customer’s profile.

deleteCreditCard Deletes a credit card from a customer’s profile.

Adding a Credit Card to a Customer Profile

The addCreditCard actor-chain is used to add a new credit card within a customer profile.

Parameter Description

creditCardType The type of credit card to add.

creditCardNumber The credit card number.

expirationMonth The month the credit card expires.

expirationYear The year the credit card expires.

billingAddressRepositoryId The ID of the billing address repository.

firstName The first name of the customer associated with this billing address.

280 9 Internal REST MVC Service Call Examples Parameter Description

middleName The middle name or initial of the customer associated with this billing address.

lastName The last name of the customer associated with this billing address.

address1 The first address field of the billing address.

address2 The second address field of the billing address.

city The city of the billing address.

state The state or province of the billing address.

postalCode The postal code of the billing address.

country The country of the billing address.

phoneNumber The phone number associated with this billing address.

setBillingAddress Boolean value that sets the address as the default billing address.

setShippingAddress Boolean value that sets the address as the default shipping address.

defaultCreditCardSetDefault If this property is set to true, this becomes the default credit card.

Add Credit Card to Customer Profile Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"billingAddressRepositoryId\" : \"690024\", \"creditCardType\" : \"Visa\", \"creditCardNumber\" : \"4111111111111111\", \"expirationMonth\" : \"01\", \"expirationYear\" : \"2016\", \"firstName\" : \"Jack\", \"lastName\" : \"Dill\", \"address1\" : \"321 Willow Dr\", \"city\" : \"Beachside\", \"state\" : \"CA\", \"postalCode\" : \"99023\", \"phoneNumber\" : \"617-634-8687\", \"country\" : \"US\", \"createNewAddress\" : \"true\" }" "http://localhost:8280/rest/model/ atg/commerce/custsvc/repository/CreditCardActor/addCreditCard"

The server response may be similar to the following:

{"creditCardId" : "0012"}

Editing a Credit Card in a Customer Profile

The updateCreditCard actor-chain is used to add a new credit card within a customer profile. This chain can be used to add a credit card to an existing customer address, or associated it with a new address.

9 Internal REST MVC Service Call Examples 281 Parameter Description

createNewAddress Identifies if a new address will be created in the customer profile.

creditCardId The ID of the credit card to edit.

creditCardType The type of credit card to edit.

creditCardNumber The credit card number.

expirationMonth The month the credit card expires.

expirationYear The year the credit card expires.

billingAddressRepositoryId The ID of the billing address repository.

firstName The first name of the customer associated with this billing address.

middleName The middle name or initial of the customer associated with this billing address.

lastName The last name of the customer associated with this billing address.

address1 The first address field of the billing address.

address2 The second address field of the billing address.

city The city of the billing address.

state The state or province of the billing address.

postalCode The postal code of the billing address.

country The country of the billing address.

phoneNumber The phone number associated with this billing address.

setBillingAddress Boolean value that sets the address as the default billing address.

setShippingAddress Boolean value that sets the address as the default shipping address.

defaultCreditCardSetDefault If set to true, this becomes the default credit card.

Update Credit Card in Customer Profile Example

The following example shows how to update a credit card with an existing address. The createNewAddress parameter is set to false, indicating that the call should not create a new address.

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{

282 9 Internal REST MVC Service Call Examples \"createNewAddress\":\"false\", \"creditCardId\":\"usercc99050003\", \"billingAddressRepositoryId\":\"380016\", \"creditCardType\":\"Visa\", \"creditCardNumber\":\"4111111111111111\", \"expirationMonth\":\"1\", \"expirationYear\":\"2022\" }" "http://localhost:8280/rest/model/atg/commerce/ custsvc/repository/CreditCardActor/updateCreditCard"

The following example shows how to update a credit card with a new address. The createNewAddress parameter is set to true, indicating that the call should create a new address.

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"createNewAddress\":\"true\", \"creditCardId\":\"usercc99050003\", \"billingAddressRepositoryId\":\"380016\", \"creditCardType\": \"visa\",\"creditCardNumber\": \"4111111111111111\",\"expirationMonth\": \"1\",\"expirationYear\": \"2023\", \"firstName\":\"John\", \"lastName\":\"Smith\",\"address1\": \"1 Main Street\", \"city\":\"Cambridge\", \ "state\":\"MA\", \"country\":\"USA\",\"postalCode\": \"12468\" }" "http://localhost:8280/rest/model/atg/commerce/custsvc/repository/CreditCardActor/ updateCreditCard"

Deleting a Credit Card from a Customer Profile

The deleteCreditCard actor-chain is used to delete an existing credit card from a customer profile.

Parameter Description

creditCardId Identifies the credit card to delete.

Delete Credit Card From Customer Profile Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"creditCardId\":\"usercc99020006\" }" "http://localhost:8280/rest/model/ atg/commerce/custsvc/repository/CreditCardActor/deleteCreditCard"

Viewing a Customer’s Shopping Cart

The /atg/commerce/custsvc/order/ShoppingCartActor contains a single detailed actor-chain, which is used to view or review a customer’s cart or order, and the summary actor-chain, which provides a summary of the shopping cart.

Parameters: None View Customer Cart Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8280/rest/model/atg/commerce/custsvc/order/ShoppingCartActor/

9 Internal REST MVC Service Call Examples 283 detailed"

The server response may be similar to the following:

{"order": { "lastModifiedTime": 1363200675886, "shippingGroupCount": 1, "paymentGroupCount": 0, "shippingGroups": [{ "specialInstructions": {}, "handlingInstructions": [], "state": 0, "locationId": null, "shippingMethod": "hardgoodShippingGroup "id": "sg110004", "trackingNumber": null, "priceInfo": { "amount": 0, "currencyCode": "USD", "amountIsFinal": false, "discounted": true, "rawShipping": 0 }, "description": "sg110004", "actualShipDate": null, "submittedDate": null, "shipOnDate": null, "shippingAddress": { "middleName": null, "lastName": "Smith", "ownerId": 02443221, "state": "MA", "address1": "One Main Street", "address2": null, "address3": null, "companyName": null, "suffix": null, "city": "Cambridge", "country": "USA", "id": null, "postalCode": "02046", "faxNumber": null, "phoneNumber": "6176378687", "county": null, "email": "[email protected]", "prefix": null, "firstName": "John", "jobTitle": null }, "stateDetail": null }], "commerceItems": [{ "id": "ci10000001", "productDisplayName": "Tumbler Glass", "returnedQuantity": 0, "priceInfo": { "amount": 19, "quantityDiscounted": 0, "discountable": true, "priceListId": "listPrices",

284 9 Internal REST MVC Service Call Examples "onSale": false, "rawTotalPrice": 19, "currencyCode": "USD", "amountIsFinal": false, "listPrice": 19, "discounted": false, "currentPriceDetailsSorted": [{ "amount": 19, "itemPriceInfo": null, "currencyCode": "USD", "tax": 0, "range": { "lowBound": 0, "class": "atg.core.util.Range", "highBound": 0, "size": 1 }, "amountIsFinal": false, "discounted": false, "quantity": 1, "detailedUnitPrice": 19 }], "salePrice": 0 }, "catalogId": null, "quantity": 1, "catalogRefId": "xsku2085", "catalogKey": "en_US", "productId": "xprod2085" }], "id": "o110001", "siteId": "homeSite", "taxPriceInfo": { "amount": 0, "currencyCode": "USD", "countyTax": 0, "amountIsFinal": false, "countryTax": 0, "discounted": false, "stateTax": 0, "cityTax": 0, "districtTax": 0 }, "priceInfo": { "amount": 19, "total": 19, "shipping": 0, "currencyCode": "USD", "tax": 0, "amountIsFinal": false, "discounted": false, "manualAdjustmentTotal": 0, "rawSubtotal": 19, "discountAmount": 0 }, "paymentGroups": [], "profileId": "220008", "creationTime": 1363200429849, "relationships": [{ "id": "r100001",

9 Internal REST MVC Service Call Examples 285 "amount": 0, "relationshipType": "SHIPPINGQUANTITY", "returnedQuantity": 0, "shippingGroupId": "sg110004", "commerceItemId": "ci10000001", "quantity": 1 }], "totalCommerceItemCount": 1 }}

Working with a Customer’s Shopping Cart

The CartModifierActor contains several actor-chains that modify the customer’s shopping cart. The path for this actor is /atg/commerce/custsvc/order/CartModifierActor.

This actor contains the following actor-chains:

Actor-Chain Description

addMultipleItemsToOrder Adds multiple items to a shopping cart.

addItemToOrder Adds items from a catalog, wish/gift list to a shopping cart by SKUI ID.

setOrder Updates the shopping cart by SKU ID.

setOrderByCommerceId Updates the shopping cart by commerce ID.

setOrderByRelationshipID Updates the shopping cart by shipping group relationship ID.

removeAndAddItemToOrder Removes and item and then adds it to the shopping cart.

removeItemFromOrder Removes an item from the shopping cart using the SKU.

removeItemFromOrderByRelationshipId Removes an item from the shopping cart using the Relationship ID.

moveToPurchaseInfo Checks out the order from the shopping cart page using the SKU.

moveToPurchaseInfoByCommerceId Saves the shopping cart and continues to the next step in the checkout process using the commerce ID.

moveToPurchaseInfoByRelId Saves the shopping cart and continues to the next step in the checkout process using the shipping group relationship ID.

286 9 Internal REST MVC Service Call Examples Actor-Chain Description

changeSKUs Changes the SKU of one or more commerce items in the current order.

Adding Multiple Items to a Customer’s Shopping Cart

The addMultipleItemsToOrder actor-chain is used when adding more than one item to the customer’s shopping cart.

Parameter Description

addItemCount The number of items being added to the shopping cart. This is different than the quantity of each product being added, this is the items array size.

items.catalogRefId The catalog reference ID.

items.productId The ID of the product to add to the shopping cart.

items.quantity The number of each product being added to the shopping cart. For example, two sweaters or four pairs of shoes.

items.locationId Used only for in-store pickup. This identifies the location of the store.

items.siteId Identifies the site associated with the product.

items.giftlistId Used only when adding gift or wishlist items to the shopping cart. Identifies the ID of the list.

items.giftlistItemId Used only when adding gift or wishlist items to the shopping cart. Identifies the ID of the list item.

Add Multiple Items to Customer Order Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"addItemCount\": 3, \"items\": {\"atg-rest-class-type\":\"java.util.ArrayList\", \"atg-rest-values\": [{\"atg-rest-class-type\": \"atg.commerce.order.purchase.AddCommerceItemInfo\", \"catalogRefId\": \"xsku1043\",\"productId\": \"xprod1015\",\"quantity\": 1}, {\"atg-rest-class-type\":\"atg.commerce.order.purchase.AddCommerceItemInfo\" ,\"catalogRefId\":\"xsku60325\",\"productId\": \"xprod40028\",\"quantity\": 2},{\"atg-rest-class-type\":\"atg.commerce.order.purchase.AddCommerceItemInfo"\, \"catalogRefId\":\"xsku1001\",\"productId\": \"xprod1001\",\"quantity\": 3} ]}}" "http://localhost:8280/rest/model/atg/commerce/custsvc/order/CartModifierActor/ addMultipleItemsToOrder"

9 Internal REST MVC Service Call Examples 287 Adding Items to a Customer’s Shopping Cart

The addItemToOrder actor-chain is used to add a single item to a customer’s shopping cart. It also is used to add an item from a customer’s gift/wish list to a shopping cart, as well as adding an item to an in-store pickup order:

Parameter Description

catalogRefIds The catalog reference ID.

productId The ID of the product to add to the shopping cart.

quantity The number of each product being added to the shopping cart. For example, two sweaters or four pairs of shoes.

siteId Identifies the site associated with the product.

locationId Used only for in-store pickup, identifies the location of the store.

addToWishlist This Boolean parameter is used only for adding wish list items to the shopping cart.

giftlistItemId Used only for adding gift/wish list items. Identifies the list item ID.

giftlistId The ID of the gift list.

Add Item to Customer’s Order Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"catalogRefIds\": \"xsku1043\",\"productId\": \"xprod1015\",\"quantity\": 1}" "http://localhost:8280/rest/model/atg/commerce/custsvc/order/CartModifierActor/ addItemToOrder"

Add Item to Customer’s In-Store Pickup Example

Note the use of the locationId to identify the store from where the item will be picked up.

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"catalogRefIds\" : \"xsku2085\", \"productId\" : \"prod10004\", \"locationId\" : \"AventuraMall\", \"quantity\": 8}" "http://localhost:8280/rest/model/atg/ commerce/custsvc/order/CartModifierActor/addItemToOrder"

Add Item From Customer’s Gift List Example

Note the use of the giftlistId and the giftlistItemId.

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"catalogRefIds\" : \"xsku2085\", \"productId\" : \"xprod2085\", \"giftlistId\" : \"gl40007\", \"giftlistItemId\" : \"gi40001\", \"quantity\": 1}" "http://localhost:8280/rest/model/atg/commerce/custsvc/order/CartModifierActor/

288 9 Internal REST MVC Service Call Examples addItemToOrder"

Add Item From Customer’s Wish List Example

This example is similar to the Gift List example, however it uses the addToWishlist instead of the giftlistId.

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"addToWishlist\" : \"true\", \"catalogRefIds\" : \"xsku2085\", \"productId\" : \"xprod2085\", \"giftlistItemId\" : \"gi40001\", \"quantity\": 1}" "http://localhost:8280/rest/model/atg/commerce/custsvc/order/CartModifierActor/ addItemToOrder"

Updating the Customer’s Shopping Cart by SKU ID

The setOrder actor-chain updates the quantity of items within the customer’s shopping cart using SKU IDs.

Parameter Description

removalCatalogRefIds The optional list of catalog reference IDs (SKU ID) to remove from the order.

Update Customer’s Shopping Cart by SKU ID Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8280/rest/model/atg/commerce/custsvc/order/CartModifierActor/ setOrder?xsku1043=2"

Updating the Customer’s Shopping Cart by Commerce ID

The setOrderByCommerceId actor-chain updates the quantities of items within the customer’s shopping cart using the commerce ID. Note that this actor-chain is also used to perform a price override. Refer to the Adjusting a Customer’s Order (page 333) section for information on price overrides.

Parameter Description

removalCommerceIds The optional list of commerce item IDs to remove from the order.

Update Customer’s Shopping Cart by Commerce ID Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8280/rest/model/atg/commerce/custsvc/order/CartModifierActor/ setOrderByCommerceId?ci111000001=3"

9 Internal REST MVC Service Call Examples 289 Updating the Customer’s Shopping Cart By Shipping Group Relationship ID

The setOrderByRelationshipId actor-chain is used to update the quantities of items within the customer’s shopping cart using the CommerceItem or the shipping group relationship ID.

Parameter Description

removalRelationshipIds The list of relationship IDs to remove from the order.

Update Customer’s Shopping Cart by Relationship ID Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8280/rest/model/atg/commerce/custsvc/order/CartModifierActor/ setOrderByRelationshipId?r99090004=4"

Removing and Adding an Item to the Customer’s Shopping Cart

The removeAndAddItemToOrder actor-chain is used to removes items from the order and then adds it to the order.

Parameter Description

catalogRefIds The catalog reference ID.

productId The ID of the product.

quantity The quantity of the product.

removalCommerceIds The ID given to the item, or to a list of commerce items, that should be removed from the order.

Move an Item to the Customer’s Cart Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"catalogRefIds\":\"xsku1043\",\"productId\": \"xprod1015\",\"quantity\": 1, \"removalCommerceIds\":\"ci116000002\"}" "http://localhost:8280/rest/model/atg/ commerce/custsvc/order/CartModifierActor/removeAndAddItemToOrder"

Removing an Item From the Customer’s Shopping Cart

The removeItemFromOrder actor-chain removes items from the customer’s shopping cart using the commerce ID.

290 9 Internal REST MVC Service Call Examples Parameter Description

removalCommerceIds The list of commerce item IDs to remove from the order.

Remove Item From Customer’s Cart Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8280/rest/model/atg/commerce/custsvc/order/CartModifierActor/ removeItemFromOrder?removalCommerceIds=ci115000001"

Removing an Item From a Customer’s Shopping Cart By Relationship ID

The removeItemFromOrderByRelationshipId actor-chain is used to remove items from the customer’s shopping cart using the commerceItem or the shipping group relationship ID.

Parameter Description

removalRelationshipIds The list of relationship IDs to remove from the order.

Remove Item From Customer’s Cart by Relationship ID Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8280/rest/model/atg/commerce/custsvc/order/CartModifierActor/ removeItemFromOrderByRelationshipId?removalRelationshipIds=r99160002"

Starting the Checkout Process with SKU ID

The moveToPurchaseInfo actor-chain starts the checkout process by verifying for changes in the order. The current order’s SKU quantities are passed in to initiate the checkout process.

Parameters: None

Continue the Checkout Process with SKU ID Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8280/rest/model/atg/commerce/custsvc/order/CartModifierActor/ moveToPurchaseInfo?sku40051=1"

Starting the Checkout Process with Commerce ID

The moveToPurchaseInfoByCommerceId actor-chain starts the checkout process. The current order’s commerce ID quantities are passed in to initiate the checkout process.

9 Internal REST MVC Service Call Examples 291 Parameters: None

Continue the Checkout Process with Commerce ID Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8280/rest/model/atg/commerce/custsvc/order/CartModifierActor/ moveToPurchaseInfoByCommerceId?ci4000006=1"

Starting the Checkout Process with Relationship ID

The moveToPurchaseInfoByRelId actor-chain starts the checkout process. The current order’s relationship ID quantities are passed in to initiate the checkout process.

Parameters: None

Continue the Checkout Process with Relationship ID Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8280/rest/model/atg/commerce/custsvc/order/CartModifierActor/ moveToPurchaseInfoByRelId?r99290001=1"

Changing the SKU of an Item

The changeSkus actor-chain changes the SKU of one or more commerce items in the current order.

Parameters: To modify the SKU of an item, pass the commerce ID prefixed by SKUCNG with the new SKU ID as the value: SKUCNG:{CommerceItem ID}={SKU ID}

Change SKU Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8280/rest/model/atg/commerce/custsvc/order/CartModifierActor/ changeSkus?SKUCNG:ci115000001=2"

Assisting the Customer with the Shipping Page

The ShippingGroupActor contains several actor-chains that modify the Shipping page. The path for this actor is /atg/commerce/custsvc/order/ShippingGroupActor.

Actor-Chain Description

getShippingGroups Initializes and retrieves avilable shipping groups.

292 9 Internal REST MVC Service Call Examples Actor-Chain Description

applySingleShippingGroup Used to select a single shipping group.

applyMultipleShippingGroups Used to set multipe shipping groups.

applyShippingMethods Applies shipping methods to both single and multiple shipping groups.

splitShippingInfos Splits the shipping between specified shipping groups.

getAllCommerceItemShippingInfos Obtains all of the Commerce Item Shipping Info (CISI).

Displaying Available Shipping Groups

The getShippingGroups actor-chain displays all of the shipping groups that are available.

Parameter Description

init Clears the shipping group infos on the ShippingGroupDroplet and relitializes the properties.

Display Available Shipping Groups Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d " { \"init\" : \"true\"}" "http://localhost:8280/rest/model/atg/commerce/ custsvc/order/ShippingGroupActor/getShippingGroups"

The server response may be similar to the following:

{ "ci10000002": { "shippingGroups": {}, "allShippingGroupTypes": ["hardgoodShippingGroup"] }, "shippingGroups": {}, "shippingInfos": {"ci10000002": [{ "handlingInstructionInfos": [], "commerceItemId": "ci10000002" }]}, "allShippingGroupTypes": ["hardgoodShippingGroup"], "commonShippingGroupTypes": ["hardgoodShippingGroup"] }

Specifying a Single Shipping Group

The applySingleShippingGroup actor-chain identifies a single shipping group for the current order.

9 Internal REST MVC Service Call Examples 293 Parameter Description

shipToAddressNickname Identifies the nickname of the shipping group.

Specify Single Shipping Group Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"shipToAddressNickname\" : \"HomeAddress\"}" "http://localhost:8280/rest/model/ atg/commerce/custsvc/order/ShippingGroupActor/applySingleShippingGroup"

Specifying Multiple Shipping Groups

The ApplyMultipleShippingGroups actor-chain identifies one or more shipping groups for the current order. Note that shippingGroupNames must be configured in the Commerce Item Shipping Info(CISI) list. Refer to the Core Commerce Programming Guide for further information.

Parameter Description

cisicount Identifies the array size of the cisiList.

cisiList.shippingGroupName The name of the shipping group in the Commerce Item Shipping Info (CISI) list.

cisiList.shippingMethod The name of the shipping method in the Commerce Item Shipping Info (CISI) list.

Specify Multiple Shipping Groups Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"cisicount\" : \"2\", \"cisiList\" :{ \"atg-rest-class-type\": \"java.util.ArrayList\", \"atg-rest-values\": [{ "atg-rest-class-type": \"atg.commerce.order.purchase.CommerceItemShippingInfo\", \"shippingGroupName\" : \"Address\"}, { \"atg-rest-class-type\": \"atg.commerce.order.purchase.CommerceItemShippingInfo\",\"shippingGroupName\" : \"Address##0\"}]}}" "http://localhost:8280/rest/model/atg/commerce/ custsvc/order/ShippingGroupActor/applyMultipleShippingGroups"

Splitting Items into Different Shipping Groups

The splitShippingInfos actor-chain splits the shipping between shipping groups.

294 9 Internal REST MVC Service Call Examples Parameter Description

cisicount Identifies the array size of the cisiList.

cisiList.quantity The original quantity value that needs to be split.

cisiList.splitQuantity The quantity that should be moved to the other shipping group.

cisiList.shipppingGroupName This is the name of the shipping group in which the item will be available.

cisiList.splitShippingGroupName This is the name of the split shipping group.

Split Items into Different Shipping Groups Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"cisicount\" : \"1\", \"cisiList\" :{ \"atg-rest-class-type\": \"java.util.ArrayList\", \"atg-rest-values\": [ { \"atg-rest-class-type\": \"atg.commerce.order.purchase.CommerceItemShippingInfo\", \"quantity\" : \"5\", \"splitQuantity\" : \"2\", \"shippingGroupName\" : \"Address\", \"splitShippingGroupName\" : \"Address##0\"}]}}" "http://localhost:8280/rest /model/atg/commerce/custsvc/order/ShippingGroupActor/splitShippingInfos"

Applying Shipping Methods

The applyShippingMethods actor-chain applies shipping methods to shipping groups and then continues onto the billing process.

Parameter Description

shippingGroupscount Identifies the array size of the shipping groups.

shippingGroups.shippingMethod Identifies the shipping methods for each shipping group.

Apply Shipping Method Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"shippingGroupscount\" : \"1\", \"shippingGroups\" : {\"atg-rest-class-type\": \"java.util.ArrayList\", \"atg-rest-values\": [{\"atg-rest-class-type\": \"atg.commerce.order.purchase.CommerceItemShippingInfo\", \"shippingMethod\" : \"Ground\"}]}}" "http://localhost:8280/rest/model/atg/commerce/custsvc/order/ ShippingGroupActor/applyShippingMethods"

9 Internal REST MVC Service Call Examples 295 Displaying All Available Shipping Methods

The AvailablePricedShippingMethodsActor is used to display the available shipping methods. The path to this actor is: /atg/commerce/custsvc/pricing/AvailablePricedShippingMethodsActor.

This actor contains the getAvailablePricedShippingMethods actor-chain:

Parameters: None

Display All Available Shipping Methods Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8280/rest/model/atg/commerce/custsvc/pricing/ AvailablePricedShippingMethodsActor/getAvailablePricedShippingMethods"

The server response might be:

{"sg70004": { "Next Day": { "amount": 18.95, "currencyCode": "USD", "rawShipping": 18.95 }, "Two Day": { "amount": 9.5, "currencyCode": "USD", "rawShipping": 9.5 }, "Ground": { "amount": 4.75, "currencyCode": "USD", "rawShipping": 4.75 } }}

Creating New Hardgood Shipping Groups

The CreateHardgoodShippingGroupActor is used to create a new hardgood shipping group. The path to this actor is: /atg/commerce/custsvc/order/CreateHardgoodShippingGroupActor.

This actor contains the addHardgoodShippingGroup actor-chain:

Parameter Description

firstName The first name of the customer associated with this shipping group.

middleName The middle name or initial of the customer associated with this shipping group.

lastName The last name of the customer associated with this shipping group.

address1 The first address field associated with this shipping group.

296 9 Internal REST MVC Service Call Examples Parameter Description

address2 The second address field associated with this shipping group.

city The city of the address associated with this shipping group.

state The state of the address associated with this shipping group.

country The country of the address associated with this shipping group.

postalCode The postal code of the address associated with this shipping group.

phoneNumber The phone number of the customer associated with this shipping group.

Create New Hardgood Shipping Group Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"firstName\": \"Joe\",\"lastName\": \"Smith\",\"address1\": \"1 Main St\",\"city\": \"Cambridge\",\"state\": \"MA\",\"country\": \"USA\", \"postalCode\": \"02146\" }" "http://localhost:8280/rest/model/atg/commerce/ custsvc/order/CreateHardgoodShippingGroupActor/newHardgoodShippingGroup"

Editing a Hardgood Shipping Group

The UpdateHardgoodShippingGroupActor is used to edit shipping groups. The path to this actor is: /atg/ commerce/custsvc/order/UpdateHardgoodShippingGroupActor.

This actor contains the updateHardgoodShippingGroup actor-chain:

Parameter Description

nickname The nickname associated with the shipping group to update.

firstName The first name of the customer associated with this shipping group.

middleName The middle name or initial of the customer associated with this shipping group.

lastName The last name of the customer associated with this shipping group.

address1 The first address field of the address associated with this shipping group.

address2 The second address field of the address associated with this shipping group.

city The city of the address associated with this shipping group.

state The state of the address associated with this shipping group.

country The country of the address associated with this shipping group.

postalCode The postal code of the address associated with this shipping group.

9 Internal REST MVC Service Call Examples 297 Parameter Description

phoneNumber The phone number of the customer associated with this shipping group.

Edit Hardgood Shipping Group Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"nickname\": \"Address\",\"firstName\": \"Jane\",\"lastName\": \"Doe\",\"address1\": \"2 Main St\",\"city\": \"Wilmington\",\"state\": \"MA\",\"country\": \"USA\",\"postalCode\": \"01887\" }" "http://localhost:8280/ rest/model/atg/commerce/custsvc/order/UpdateHardgoodShippingGroupActor/ updateHardgoodShippingGroup"

Obtaining the Customer’s Current Shipping Info List

The getAllCommerceItemShippingInfos actor-chain obtains all of the Commerce Item Shipping Info (CISI). Note that you must call this method to initialize the shipping list prior to calling applyShippingGroups.

Parameters: None

Initialize Shipping List Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8280/rest/model/atg/commerce/custsvc/order/ShippingGroupActor/ getAllCommerceItemShippingInfos"

Assisting the Customer with the Billing Page

The PaymentGroupActor contains several actor-chains that allow the agent to assist the customer when working with the billing page. The path for this actor is /atg/commerce/custsvc/order/ PaymentGroupActor.

Actor-Chain Description

getPaymentGroups Displays the customer’s billing information.

getCommerceIdentifierPaymentInfos Gets the Commerce Identifier Payment Info (CIPI).

applyMultiplePaymentGroups Applies multiple payment groups.

claimItem Used to claim store credit or a gift card.

298 9 Internal REST MVC Service Call Examples Display the Customer’s Payment Groups

The getPaymentGroups actor-chain is used to display the customer’s payment groups.

Parameter Description

init This parameter will initialize initPaymentGroups, initBasedOnOrder and initOrderPayment groups.

Display Customer Payment Groups Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"init\": \"true\"}" "http://localhost:8280/rest/model/atg/commerce/custsvc/ order/PaymentGroupActor/getPaymentGroups"

The server response may be similar to the following:

{"paymentGroups": {"visa - 1111": { "amount": 0, "currencyCode": null, "expirationMonth": "1", "expirationYear": "2022", "paymentId": "pg110012", "creditCardNumber": "1111", "expirationDayOfMonth": null, "billingAddress": { "lastName": "Smith", "postalCode": "02046", "phoneNumber": "6176378687", "email": "[email protected]", "state": "MA", "address1": "One Main Street", "address2": null, "firstName": "John", "city": "Cambridge", "country": "USA" }, "creditCardType": "Visa", "orderId": null }}}

Getting Available Payment Information

The getCommerceIdentifierPaymentInfos actor-chain is used initializes payment lists and obtains the current payment list.

9 Internal REST MVC Service Call Examples 299 Parameter Description

listId Identifies the payment list to initialize.

Get Available Payment Information Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"listId\" : \"o40001\"}" "http://localhost:8280/rest/model/atg/commerce/custsvc/ order/PaymentGroupActor/getCommerceIdentifierPaymentInfos"

The server resopnse may be similar to the following:

{"currentList":[ { "splitPaymentMethod":null," "splitQuantity":0, "splitAmount":0, "commerceIdentifier":{ "commerceItems":[{ "productDisplayName":"Corduroy Pants", "productId":"prod20003", "id":"ci103000003", "priceInfo":{ "currencyCode":"USD", "amount":67, "currentPriceDetailsSorted":[{ "currencyCode":"USD", "detailedUnitPrice":67, "amount":67,"quantity":1 } ]}, "quantity":1, "catalogRefId":"sku40051" }], "id":"o99060003", "priceInfo":{ "total":60.3, "currencyCode":"USD", "discountAmount":6.700000000000003, "amount":60.3, "shipping":0, "tax":0, "rawSubtotal":67 }, "totalCommerceItemCount":1 }, "amount":60.3, "creditCardVerificationNumber":null, "relationshipType":"ORDERAMOUNTREMAINING", "amountRemainingType":"ORDERAMOUNTREMAINING", "quantity":0, "paymentMethod":null, "amountType":"ORDERAMOUNT" }, {

300 9 Internal REST MVC Service Call Examples "splitPaymentMethod":null, "splitQuantity":0, "splitAmount":0, "commerceIdentifier":{ "commerceItems":[{ "productDisplayName":"Corduroy Pants", "productId":"prod20003", "id":"ci103000003", "priceInfo":{ "currencyCode":"USD", "amount":67, "currentPriceDetailsSorted":[{ "currencyCode":"USD", "detailedUnitPrice":67, "amount":67, "quantity":1 } ]}, "quantity":1, "catalogRefId":"sku40051" }], "id":"o99060003", "priceInfo":{ "total":60.3, "currencyCode":"USD", "discountAmount":6.700000000000003, "amount":60.3, "shipping":0, "tax":0,"rawSubtotal":67 }, "totalCommerceItemCount":1 }, "amount":0, "creditCardVerificationNumber":null, "relationshipType":"ORDERAMOUNT", "amountRemainingType":"ORDERAMOUNTREMAINING", "quantity":0, "paymentMethod":"visa - 1111", "amountType":"ORDERAMOUNT" } ]}

Claiming Store Credit or a Gift Certificate

The claimItem actor-chain is used for the customer to claim either store credit, or a gift certificate.

Parameter Description

claimCode The claim code being used by the customer.

Claim Store Credit or Gift Card Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{

9 Internal REST MVC Service Call Examples 301 \"claimCode\": \"sc36b60\" }" "http://localhost:8280/rest/model/atg/commerce/ custsvc/order/PaymentGroupActor/claimItem"

Claiming a Customer’s Coupon

The CouponActor is used by a customer to claim a coupon. It is located in: /atg/commerce/ custsvc/promotion/CouponActor.

This actor has the claimCoupon actor-chain:

Parameter Description

couponClaimCode The coupon code that is being provided by the customer.

Claim Customer’s Coupon Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"couponClaimCode\":\"TENSHIP\" }" "http://localhost:8280/rest/model/atg/ commerce/custsvc/promotion/CouponActor/claimCoupon"

Applying Multiple Payment Groups

The applyMultiplePaymentGroups actor-chain is used to apply multiple payment groups to a customer’s order. Once the payment groups are applied, the process continues on to Order Review.

Parameter Description

listId The ID of the order.

cipicount The size of the cipiList array.

cipiList.amount Amount that is being applied to the payment group.

cipiList.creditCardVerificationNumber The credit card verification number.

Apply Multiple Payment Groups Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"listId\" : \"o40003\", \"cipicount\" : \"2\", \"cipiList\" : { \"atg-rest-class-type\":\"java.util.ArrayList\", \"atg-rest-values\": [{\"atg-rest-class-type\" :\"atg.commerce.order.purchase.CommerceIdentifierPaymentInfo\", \"amount\" : \"0.00\",\"creditCardVerificationNumber\" : \"1234\"}, {\"atg-rest-class-type\":

302 9 Internal REST MVC Service Call Examples \"atg.commerce.order.purchase.CommerceIdentifierPaymentInfo\", \"amount\" : \"5.00\", \"creditCardVerificationNumber\" : \"1234\"}]}}" "http://localhost:8280/rest/model/atg/commerce/custsvc/order/PaymentGroupActor/ applyMultiplePaymentGroups"

Working with Credit Cards Within an Order

The /atg/commerce/custsvc/order/CreateCreditCardActor contains actor-chains that allow an agent to work with the customer’s credit card information while working on an order:

Actor-Chain Description

getExistingAddresses Initializes the existing addresses in an order.

newCreditCardWithExistingAddress Creates a new credit card payment group with an existing address in an order.

newCreditCardWithNewAddress Creates a new credit card payment group with a new address in an order.

Getting a Customer’s Existing Address

The getExistingAddress actor-chain is used to initialize the existing address of the customer. This actor-chain must be run prior to using the newCreditCardWithExistingAddress actor-chain.

Properties: None

Initialize Customer Existing Address Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8280/rest/model/atg/commerce/custsvc/order/ CreateCreditCardActor/getExistingAddresses"

Adding a Credit Card to an Existing Address in an Order

The newCreditCardWithExistingAddress actor-chain is used to create a new credit card payment group with an existing address in an order. Note that the getExistingAddress actor-chain must be run prior to running this call.

Parameter Description

creditCardType Identifies the address to delete.

9 Internal REST MVC Service Call Examples 303 Parameter Description

creditCardNumber Adds the new credit card number.

expirationMonth Adds the new credit card’s expiration month.

expirationYear Adds the new credit card’s expiration year.

addressIndex Identifies the address associated with this new credit card.

Add Credit Card to Existing Address in Order Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"addressIndex\": \"0\", \"creditCardType\": \"visa\",\"creditCardNumber\": \"4111111111111111\",\"expirationMonth\": \"1\",\"expirationYear\": \"2020\" }" "http://localhost:8280/rest/model/atg/commerce/custsvc/order/ CreateCreditCardActor/newCreditCardWithExistingAddress"

Adding a Credit Card to a New Address in an Order

The newCreditCardWithNewAddress actor-chain is used to create a new credit card payment group with an existing address in an order.

Parameter Description

creditCardType Identifies the address to delete.

creditCardNumber Adds the new credit card number.

expirationMonth Adds the new credit card’s expiration month.

expirationYear Adds the new credit card’s expiration year.

firstName Identifies the first name of the customer associated with this billing address.

middleName The middle name or initial of the customer associated with this billing address.

lastName The last name of the customer associated with this billing address.

address1 The first address field of the billing address.

address2 The second address field of the billing address.

city The city of the billing address.

state The state or province of the billing address.

country The country of the billing address.

postalCode The postal code of the billing address.

304 9 Internal REST MVC Service Call Examples Parameter Description

phoneNumber The phone number of the billing address.

Add Credit Card to New Address in Order Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"creditCardType\": \"visa\",\"creditCardNumber\": \"4111111111111111\",\"expirationMonth\": \"1\",\"expirationYear\": \"2020\",\"firstName\": \"John\",\"lastName\": \"Smith\",\"address1\": \"1 Main Street\",\"city\": \"cambridge\",\"state\": \"MA\",\"country\": \"USA\",\"postalCode\": \"02146\" }" "http://localhost:8280/rest/model/atg/ commerce/custsvc/order/CreateCreditCardActor/newCreditCardWithNewAddress"

Updating a Credit Card in an Order

The UpdateCreditCardActor is used to edit an existing credit card within an order. The path to this actor is: / atg/commerce/custsvc/order/UpdateCreditCardActor.

This actor contains the updateCreditCard actor-chain:

Parameter Description

nickname The nickname of the credit card to update.

creditCardType The type of credit card to update.

creditCardNumber The credit card number to update.

expirationMonth The month that the credit card expires.

expirationYear The year that the credit card expires.

firstName The first name on the credit card.

middleName The middle name or initial on the credit card.

lastName The last name on the credit card.

address1 The first address field on the credit card.

address2 The second address field on the credit card.

city The city on the credit card.

state The state on the credit card.

country The country on the credit card.

postalCode The postal code on the credit card.

9 Internal REST MVC Service Call Examples 305 Parameter Description

phoneNumber A phone number associated with the credit card.

Update Credit Card in Order Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"nickname\" : \"visa 1111\", \"creditCardType\" : \"Visa\", \"creditCardNumber\" : \"4111111111111111\", \"expirationMonth\" : \"06\", \"expirationYear\" : \"2017\",\"firstName\":\"Charles\", \"middleName\":\"J\", \"lastName\":\"Smythe\",\"address1\":\"123 Main Street\", \"address2\": \"Suite 100\", \"city\":\"Cambridge\",\"state\":\"MA\", \"country\":\"USA\", \"postalCode\":\"02146\",\"phoneNumber\": \"617-637-8687\" }" "http://localhost:8280/rest/model/atg/commerce/custsvc/order/ UpdateCreditCardActor/updateCreditCard"

Assisting Customers with Orders

There are a number of REST services that have been created that allow agents to assist customers with orders.

Creating New Orders

The CreateNewOrderActor allows an agent to create a new order when working within a ticket. This actor is located at /atg/commerce/custsvc/environment/CreateNewOrderActor, and contains the createNewOrder actor-chain.

Parameter Description

doWarnings If set to true, will present a warning to the agent when leaving the order they are currently working on and proceeding to the new order.

doTicketDispositionPrompt If set to true, will present ticket disposition prompts to the agent.

dispositionOption If doTicketDispositionPrompt is selected, this provides a ticket disposition option.

reasonCode If doTicketDispositionPrompt is selected, this provides a ticket disposition reason code.

ticketNote Used to provide a note associated with the ticket.

publicNote Identifies if the ticket note is public.

306 9 Internal REST MVC Service Call Examples New Order Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8280/rest/model/atg/commerce/custsvc/environment/ CreateNewOrderActor/createNewOrder"

The server response may be similar to the following:

{"currentOrder" : "02350008"}

Viewing the Current or Active Customer

The ActiveCustomerProfileActor is used to view the current, or active, customer. The path to this actor is: / atg/userprofiling/ActiveCustomerProfileActor.

This actor contains the detailed actor-chain, which is used to view detailed information, and the summary actor-chain, which is used to view summary information.

Parameters: None View Current Customer Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8280/rest/model/atg/userprofiling/ActiveCustomerProfileActor/ detailed"

Viewing the Customer Order History

The ServiceCustomerProfileActor is used to view the customer order history. The path to this actor is: / atg/userprofiling/ServiceCustomerProfileActor.

This actor contains the detailed actor-chain.

Parameters: None View Current Customer Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8280/rest/model/atg/userprofiling/ServiceCustomerProfileActor/ detailed"

The server response may be similar to the following:

{"profile": { "middleName": null, "lastName": "Smith", "expressCheckout": false, "defaultCreditCard": null, "orderPriceLimit": null, "locale": null,

9 Internal REST MVC Service Call Examples 307 "currentLocation": "unknown", "id": "220022", "registrationDate": {"time": 1363218368049}, "email": "[email protected]", "homeAddress": { "middleName": null, "lastName": "Smith", "item-id": null, "state": "MA", "address1": "1 Main Street", "address2": null, "address3": null, "companyName": null, "suffix": null, "repositoryId": "230024", "country": "USA", "city": "Cambridge", "faxNumber": null, "postalCode": "02046", "phoneNumber": "6176378687", "county": null, "prefix": null, "firstName": "John" }, "favoriteStores": [], "daytimeTelephoneNumber": null, "billingAddress": null, "login": null, "secondaryAddresses": {}, "purchaseLists": [], "firstName": "John", "shippingAddress": null, "allowPartialShipment": false, "creditCards": {"visa - 1111": { "id": "usercc10001", "expirationYear": "2022", "expirationMonth": "1", "creditCardNumber": "1111", "billingAddress": { "middleName": null, "lastName": "Smith", "item-id": null, "state": "MA", "address1": "One Main Street", "address2": null, "address3": null, "companyName": null, "suffix": null, "repositoryId": "230038", "country": "USA", "city": "Cambridge", "faxNumber": null, "postalCode": "02046", "phoneNumber": "6176378687", "county": null, "prefix": null, "firstName": "John" }, "creditCardType": "visa" }}

308 9 Internal REST MVC Service Call Examples }}

Searching and Clearing Searches for an Order

The OrderSearchTreeQueryActor is used to search for orders. The path to this actor is: /atg/commerce/ custsvc/order/OrderSearchTreeQueryActor.

This actor contains the following actor-chains:

Actor-Chain Description

clearForm Clears the search session.

search Used to search for orders. It also indicates the way that the results will display, including the paging and sort order.

The clearForm actor-chain allows you to clear the saved session search request.

Parameters: None Clear Order Search Sessions Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8280/rest/model/atg/commerce/custsvc/order/ OrderSearchTreeQueryActor/clearForm"

The search actor-chain searches for orders and configures the result display.

Parameter Description

fieldCount Indicates the size of the fields array, or the number of items in the field.

pageSize The number of orders per page. The default is set to 10.

pageNum Indicates which page of results to return. The default is set to 0.

maxResults The total number of search results to return. The default is set to 100.

docProps Identifies the properties of the order to return in each search result. The default is set to all.

docSort The type of sort property to use. The default is strprop. Use numpropr if you are doing a number property sort.

docSortOrder Sort the results in ascending or descending order. The default is descending.

docSortProp The property to sort on. The default is id.

9 Internal REST MVC Service Call Examples 309 Parameter Description

saveRequest Keeps the request in session.

fields[].name The name of the order property to search.

fields[].op The operation, which should be set to starts.

field[].value The value that is used for searching this field.

Search for Orders Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" –d "{ \"pageNum\":1, \"pageSize\":3, \"fieldCount\":\"1\", \"fields\": {\"atg-rest-class-type\":\"java.util.ArrayList\", \"atg-rest-class-descriptor\" : { \"atg-rest-values\" : {\"container-class\" : \"java.util.ArrayList\", \"element-class\":\"atg.textsearch.client.Field\"}}, \"atg-rest-values\": [{\"atg-rest-class-type\":\"atg.textsearch.client.Field\", \"name\": "id",\"op\": \"starts\",\"value\": \"x\"} ]}}" "http://localhost:8280/rest/model/ atg/commerce/custsvc/order/OrderSearchTreeQueryActor/search"

The server response may be similar to the following:

{ "searchResponse": {"items": [ { "total": 715.2, "customerId": "se-570040", "returnedQuantity": 2, "status": "no_pending_action", "originOfOrder": "default", "submittedDate": "1340638926", "quantity": 4, "orderId": "xco20042" }, { "total": 316.7, "lastName": "Schmidt", "returnedQuantity": 5, "status": "no_pending_action", "originOfOrder": "default", "submittedDate": "1340638855", "quantity": 0, "firstName": "Stuart", "orderId": "xco20040" }, { "total": 88, "customerId": "se-570042", "returnedQuantity": 0, "status": "processing", "originOfOrder": "default", "submittedDate": "1340636993", "quantity": 2, "orderId": "xco20031"

310 9 Internal REST MVC Service Call Examples } ]}, "pagesAvailable": 7 }

Finding an Order by Order ID

The ViewOrderActor is used to find orders by ID. This actor also changes the currently viewed order. The path to this actor is: atg/commerce/custsvc/order/ViewOrderActor.

This actor contains the changeViewOrder actor-chain:

Parameter Description

viewOrderId Identifies the order ID to use when finding the order.

Find Order By Order ID Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"viewOrderId\" : \"o99520001\" }" "http://localhost:8280/rest/model/atg/commerce/ custsvc/order/ViewOrderActor/changeViewOrder"

Selecting an Order to Work On

The ChangeOrderActor allows an agent to select an order and make it the current order in the Commerce Service Center global context area. This enables an agent to work on the order and any associated tickets. This actor uses the changeOrder actor-chain to obtain customer information. Additionally, this actor can be configured to present ticket disposition information. This actor is located at: /atg/commerce/custsvc/ environment/ChangeOrderActor.

Parameter Description

customerId The ID of the customer to select.

doWarnings If set to true, will present a warning to the agent when leaving the order they are currently working on and proceeding to the new order.

doTicketDispositionPrompt If set to true, will present ticket disposition prompts to the agent.

dispositionOption If doTicketDispositionPrompt is selected, this provides a ticket disposition option.

reasonCode If doTicketDispositionPrompt is selected, this provides a ticket disposition reason code.

ticketNote Used to provide a note associated with the ticket.

9 Internal REST MVC Service Call Examples 311 Parameter Description

publicNote Identifies if the ticket note is public.

Select Order to Work On Example

This example confirms the ticket disposition, and displays any existing warnings.

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"newOrderId\":\"o99810006\" \"doWarnings\":true, \"doTicketDispositionPrompt\": true, \"dispositionOption\":\"save\" }" "http://localhost:8280/rest/model/atg/ commerce/custsvc/environment/ChangeOrderActor/changeOrder"

This example makes the changes to the order ticket disposition.

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"newOrderId\":\"o99810006\" \"doWarnings\":false, \"doTicketDispositionPrompt\": false, \"doWarnings\":false, \"doTicketDispositionPrompt\":false, \"ticketNote\": \"Junk mail\", \"reasonCode\":\"spam\", \"dispositionOption\": \"close\"}" "http://localhost:8280/rest/model/atg/commerce/custsvc/environment/ ChangeOrderActor/changeOrder"

The following may be response may occur from the server:

{ "allWarnings":["The current working order has items in it and has not been saved. If you continue, the order will be lost."}, "activeTIcketDisposition":false, "isDiscardable":true }

Cancelling or Deleting the Current Order

The CancelOrderActor is used to cancel or delete the current order. This actor is located in: /atg/commerce/ custsvc/order/CancelOrderActor.

This actor contains the cancelCurrentOrder actor-chain:

Parameter Description

orderIdToCancel The ID of the order to cancel.

Cancel Current Order Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{

312 9 Internal REST MVC Service Call Examples \"orderIdToCancel\": \"o640001\" }" "http://localhost:8280/rest/model/atg/ commerce/custsvc/order/CancelOrderActor/cancelOrder"

Viewing Cross Sell Items in a Shopping Cart

The CSRCrossSellActor displays cross sell items in a shopping cart. It is located in: /atg/commerce/ custsvc/order/CSRCrossSellActor.

The crossSellItems actor-chain displays the products.

Parameters: None:

View Cross Sells Example

curl -v -b agent_cookies.txt "http://localhost:8180/rest/model/atg/commerce/ custsvc/order/CSRCrossSellActor/crossSellItems"

The server response may be similar to the following:

{"crossSellItems": [ { "description": "Bring a little chateau to your palace", "largeImageUrl": "/crsdocroot/content/images/products/large/ ST_CamelotChair_large.jpg", "longDescription": "Feel like royalty with this dramatic accent chair. Constructed of solid oak with a rich finish, engraved designs and upholstered leather seat. Brass tack detailing adds to the overall design.", "isNavigableProduct": null, "mediumImageUrl": "/crsdocroot/content/images/products/medium/ ST_CamelotChair_medium.jpg", "fullImageUrl": "/crsdocroot/content/images/products/full/ ST_CamelotChair_full.jpg", "displayName": "Camelot Chair", "repositoryId": "xprod2037", "thumbnailImageUrl": "/crsdocroot/content/images/products/thumb/ ST_CamelotChair_thumb.jpg" }, { "description": "Tumbler glass great for mixed drinks and other beverages", "largeImageUrl": "/crsdocroot/content/images/products/large/ HOME_TumblerGlass_large.jpg", "longDescription": "Our heavy glass tumblers are a versatile addition to your barware collection. Holds 12 ounces. Dishwasher safe. Made in Poland.", "isNavigableProduct": null, "mediumImageUrl": "/crsdocroot/content/images/products/medium/ HOME_TumblerGlass_medium.jpg", "fullImageUrl": "/crsdocroot/content/images/products/full/ HOME_TumblerGlass_full.jpg", "displayName": "Tumbler Glass", "repositoryId": "xprod2085", "thumbnailImageUrl": "/crsdocroot/content/images/products/thumb/ HOME_TumblerGlass_thumb.jpg" },

9 Internal REST MVC Service Call Examples 313 { "description": "Fine crystal tumbler for highballs and other beverages", "largeImageUrl": "/crsdocroot/content/images/products/large/ HOME_JackJillGlass_large.jpg", "longDescription": "This sturdy, sophisticated crystal glass adds an elegant touch. Perfect for entertaining and holiday use.", "isNavigableProduct": null, "mediumImageUrl": "/crsdocroot/content/images/products/medium/ HOME_JackJillGlass_medium.jpg", "fullImageUrl": "/crsdocroot/content/images/products/full/ HOME_JackJillGlass_full.jpg", "displayName": "Jack and Jill Glass Tumbler", "repositoryId": "xprod2074", "thumbnailImageUrl": "/crsdocroot/content/images/products/thumb/ HOME_JackJillGlass_thumb.jpg" } ] }

Saving or Committing an Order

The CommitOrderActor saves or persists an order. It is located in: /atg/commerce/custsvc/ order/CommitOrderActor.

The CommitOrderActor has the following actor-chains:

Actor-Chain Description

persistOrder Saves the order..

commitOrder Commits the order.

sendConfirmationMessage Sends a confirmation message to an e-mail address. For information on this actor-chain, refer to the Working with Scheduled Orders (page 321) section.

validateTemplateOrder Validates a scheduled order template order. For information on this actor- chain, refer to the Working with Scheduled Orders (page 321) section.

The persistOrder actor-chain saves the order

Parameters: None:

Save or Persist Order Example

curl -x 127.0.0.1:8888 -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8280/rest/model/atg/commerce/custsvc/ order/CommitOrderActor/persistOrder"

The commitOrder actor-chain commits an order and contains the following parameters:

314 9 Internal REST MVC Service Call Examples Parameter Description

allowEmptyOrders This parameter allows you to commit empty orders.

salesChannel Identifies the sales channel used for this order.

siteId Identifies the site ID used for this order.

createTemplateFromSubmittedOrder Allows you to create a template from this submitted order. Used for Scheduled Orders. Refer to the Working with Scheduled Orders (page 321) section.

Commit Customer’s Order Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8280/rest/model/atg/commerce/custsvc/order/CommitOrderActor/ commitOrder"

Confirming a Customer’s Order

The ConfirmOrderActor is used to confirm a customer’s order. As it does this, it re-prices the order one last time before the agent commits the order to ensure that all pricing is up to date. The path to this actor is: /atg/ commerce/pricing/ConfirmOrderActor.

This actor contains the confirmOrder actor-chain.

Parameters: None

Confirm Customer’s Order Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8280/rest/model/atg/commerce/custsvc/order/ConfirmOrderActor/ confirmOrder"

The server response may be similar to the following:

{"order": { "lastModifiedTime": 1363214893776, "shippingGroupCount": 1, "paymentGroupCount": 0, "shippingGroups": [{ "specialInstructions": {}, "handlingInstructions": [], "state": 0, "locationId": null, "shippingMethod": "hardgoodShippingGroup", "id": "sg110016", "trackingNumber": null, "priceInfo": { "amount": 0, "currencyCode": "USD",

9 Internal REST MVC Service Call Examples 315 "amountIsFinal": false, "discounted": true, "rawShipping": 0 }, "description": "sg110016", "actualShipDate": null, "submittedDate": null, "shipOnDate": null, "shippingAddress": { "middleName": null, "lastName": null, "ownerId": null, "state": null, "address1": null, "address2": null, "address3": null, "companyName": null, "suffix": null, "city": null, "country": null, "id": null, "postalCode": null, "faxNumber": null, "phoneNumber": null, "county": null, "email": null, "prefix": null, "firstName": null, "jobTitle": null }, "stateDetail": null }], "commerceItems": [{ "id": "ci10000002", "productDisplayName": "Swiss Detail Clock", "returnedQuantity": 0, "priceInfo": { "amount": 99, "quantityDiscounted": 0, "discountable": true, "priceListId": "listPrices", "onSale": false, "rawTotalPrice": 99, "currencyCode": "USD", "amountIsFinal": false, "listPrice": 99, "discounted": false, "currentPriceDetailsSorted": [{ "amount": 99, "itemPriceInfo": null, "currencyCode": "USD", "tax": 0, "range": { "lowBound": 0, "class": "atg.core.util.Range", "highBound": 0, "size": 1 }, "amountIsFinal": false, "discounted": false,

316 9 Internal REST MVC Service Call Examples "quantity": 1, "detailedUnitPrice": 99 }], "salePrice": 0 }, "catalogId": null, "quantity": 1, "catalogRefId": "xsku2011", "catalogKey": "en_US", "productId": "xprod2011" }], "id": "o110003", "siteId": "homeSite", "taxPriceInfo": { "amount": 0, "currencyCode": "USD", "countyTax": 0, "amountIsFinal": false, "countryTax": 0, "discounted": false, "stateTax": 0, "cityTax": 0, "districtTax": 0 }, "priceInfo": { "amount": 99, "total": 99, "shipping": 0, "currencyCode": "USD", "tax": 0, "amountIsFinal": false, "discounted": false, "manualAdjustmentTotal": 0, "rawSubtotal": 99, "discountAmount": 0 }, "paymentGroups": [], "profileId": "220022", "creationTime": 1363213904193, "relationships": [{ "id": "r100004", "amount": 0, "relationshipType": "SHIPPINGQUANTITY", "returnedQuantity": 0, "shippingGroupId": "sg110016", "commerceItemId": "ci10000002", "quantity": 1 }], "totalCommerceItemCount": 1 }}

Sending a Customer Order Confirmation

The OrderConfirmationActor is referenced by the CommitOrderActor to display confirmation of a successfully committed order. The path to this actor is/atg/commerce/order/purchase/ OrderConfirmationActor.

This actor contains the orderConfirmation actor-chain.

9 Internal REST MVC Service Call Examples 317 Parameters: None Confirm Customer Order Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8280/rest/model/atg/commerce/order/purchase/ OrderConfirmationActor/orderConfirmation"

The server response may be similar to the following:

{orderId: "0132", email: [email protected]}

Modifying a Submitted Order

The ModifyOrderActor allows an agent to make a modification to a submitted order. The path to this actor is: /atg/commerce/custsvc/environment/ModifyOrderActor.

This actor contains the modifySubmittedOrder actor-chain.

Parameter Description

orderID The ID of the order to be modified.

Modify a Submitted Order Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"orderID\" : \"o250005\"}" "http://localhost:8180/rest/model/atg/commerce/ custsvc/environment/ModifyOrderActor/modifySubmittedOrder"

Submitting a Modified Order

The SubmitModifiedOrderActor enables an agent to re-submit an order that has been edited. The path to this actor is: /atg/commerce/custsvc/environment/SubmitModifiedOrderActor.

This actor contains the submitModifiedOrder actor-chain.

Parameter Description

orderID The ID of the order to re-submit.

Submit a Modified Order Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d

318 9 Internal REST MVC Service Call Examples "{ \"orderID\" : \"o250005\"}" "http://localhost:8180/rest/model/atg/commerce/ custsvc/environment/SubmitModifiedOrderActor/submitModifiedOrder"

Duplicating an Order

The DuplicateOrderActor allows you to duplicate an existing order. When you duplicate the order, you can duplicate the ticket disposition of the order. For additional information on working with ticket dispositions, refer to the Working with Ticket Disposition Warnings and Messages (page 384) section. This actor is located at / atg/commerce/custsvc/order/DuplicateOrderActor.

This actor uses the duplicateOrder actor-chain, which contains the following parameters:

Parameter Description

orderToDuplicate The ID of the scheduled order or scheduled order item.

doWarnings If set to true, will present a warning to the agent when proceeding to the new site.

doTicketDispositionPrompt If set to true, will present ticket disposition prompts to the agent.

ticketDispositionOptions.dispositionOption If doTicketDispositionPrompt is enabled, this provides a ticket disposition option.

ticketDispositionOptions.reasonCode If doTicketDispositionPrompt is selected, this provides a ticket disposition reason code.

ticketDispositionOptions.ticketNote If doTicketDispositionPrompt is selected,provides a note associated with the ticket.

ticketDispositionOptions.publicNote If doTicketDispositionPrompt is selected, identifies if the ticket note is public.

Duplicate an Order Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"orderToDuplicate\":\"xco30012\", \"doWarnings\":false, \"doTicketDispositionPrompt\":true, "dispositionOption":\"save\" }" "http://localhost:8080/rest/model/atg/commerce/custsvc/order/DuplicateOrderActor/ duplicateOrder"

Adding a Note to a Customer’s Current Order

The OrderNoteActor is used to add a note to a customer’s current order. The path to this actor is: /atg/ commerce/custsvc/order/.

9 Internal REST MVC Service Call Examples 319 This actor contains the addOrderNote actor-chain.

Parameter Description

comment The text of the note to add to the order.

Add Note to Current Order Example

curl -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"comment\":\"Customer would like this in pink if it becomes available\" }" "http://localhost:8180/rest/model/atg/commerce/custsvc/order/OrderNoteActor/ addOrderNote"

Adding a Note to a Customer’s Original Order

The OriginalOrderNoteActor is used to add a note to a customer’s original order. The path to this actor is: / atg/commerce/custsvc/order/OriginalOrderNoteActor.

This actor contains the addOrderNote actor-chain.

Parameter Description

comment The text of the note to add to the order.

Add Note to Original Order Example

curl -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"comment\":\"Customer is ordering two different sizes and may return one\" }" "http://localhost:8180/rest/model/atg/commerce/custsvc/order/ OriginalOrderNoteActor/addOrderNote"

Creating a Quote for a Customer’s Order

The QuoteActor is used to submit a quote to a Business-to-Business customer. For information on integrating with a third-party quoting system, refer to the Core Commerce Programming Guide. The path to this actor is: / atg/commerce/order/purchase/QuoteActor.

This actor contains the completeQuote actor-chain.

320 9 Internal REST MVC Service Call Examples Parameter Description

completeQuoteParameters This identifies the map and its string keys and values that provides quote information.

Submitting a Quote Example

curl –L -v -b agent_cookies.txt -H "Content-Type: application/json" –d "{"orderId":"o10005", "completeQuoteParameters":{"atg-rest-class-type": "atg-rest-values":{"agentId":\"agent007\", "providerNote":\"Quote good until 11/11/14\", "externalId":\"external001\", "expirationDate":\"2014-11-11 11:00\", "orderAdjustment":\"5.0\"}}}" "http://localhost:8180/rest/model/atg/commerce/ order/purchase/QuoteActor/completeQuote"

Working with Scheduled Orders

The following REST services allow agents to create and work with scheduled orders. For information on working with scheduled orders, refer to the Core Commerce Programming Guide and the Commerce Service Center Installation and Programming Guide. Note that before you can use these services, the active customer and order must be set. To set the active customer, refer to the Viewing a Customer (page 270) section. To set the current order, refer to the Selecting an Order to Work On (page 311) section. To commit and validate the order, refer to the Saving or Committing an Order (page 314) section.

The CSRScheduledOrderActor is used to add scheduled orders. The path to this actor is: /atg/commerce/ custsvc/order/scheduled/CSRScheduledOrderActor.

This actor contains the following actor-chains:

Actor-Chain Description

createCSRScheduledOrder Used to create a new scheduled order.

updateCSRScheduledOrder Used to update a scheduled order.

Creating a Scheduled Order

The createCSRScheduledOrder actor-chain is used to create a scheduled order using the scheduled order template.

Parameter Description

name The name of the scheduled order.

9 Internal REST MVC Service Call Examples 321 Parameter Description

scheduleType The type of scheduled order. Values can be either calendar or interval.

startDate The start date used for the order.

endDateOption Options that can be set for the end date of the scheduled order. The options include none, afterOccurrences or endBy.

numberOfOccurances This parameter is used with the afterOccurances option to calculate the end date of the scheduled order.

endDate The end date of the scheduled order. Used with the endBy parameter.

daysOption This calendar property sets the delivery days of the scheduled order. The options for this property are allDays, selectedDays and selectedDates.

selectedDays An integer array of selected days, for example, “2,4” indicates Monday and Wednesday. Values start at 1, indicating Sunday, and end with 7, indicating Saturday.

selectedDates An integer array of values between 1 and 31.

occurrencesOption Identifies the occurrence of the scheduled order. Options are allOccurrences or selectedOccurrences. Occurrences are configurable when using selectedDays.

selectedOccurrences An integer array for occurrences of the scheduled order. Options are:

1 – First 2 – Second 3 – Third 4 – Fourth 5 – Last

Use this parameter with selectedDays to identify specific occurrences within a month.

monthsOption Allows you to select specific months, selectedMonths, or to use all months, allMonths, for the scheduled order.

selectedMonths Sets the delivery months of the scheduled orders. Values are 0 – 11, which indicate January – December.

selectedHours Identifies the selected hours in an integer array. Values are 0 – 23, where 0 indicates 12:00, and 23 indicates 23:00 or 11:00 p.m.

selectedMinutes Identifies the selected minutes in an integer array. Values are 0 – 59.

selectedInterval Identifies the interval option for the schedule. Selected intervals are used when creating a periodic schedule. When daysOption parameters reference this parameter, it is used for creating calendar schedules.

322 9 Internal REST MVC Service Call Examples Parameter Description

intervalOption Indicates the interval option, which is either weeks or days. Selected intervals are used when creating a periodic schedule. When daysOption parameters reference this parameter, it is used for creating calendar schedules.

Create Scheduled Order Examples

The following example shows how you would create a schedule that runs every day, all month at a specific hour and minute and then ends on a specific day:

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"name\": \"Test endBy, allDays, allMonths\" , \"scheduleType\" : \"Calendar\" , \"startDate\" : \"03/10/2012\" , \"endDateOption\" : \"endBy\" , \"numberOfOccurrances\" : 0 , \"endDate\" : \"03/12/2016\" , \"daysOption\" : \"allDays\" , \"selectedDays\" : \"0\" , \"selectedDates\" : \"0\" , \"occurrencesOption\" : \"allOccurrences\" , \"selectedOccurrences\" : \"0\" , \"monthsOption\" : \"allMonths\" , \"selectedMonths\" : \"0\", \"selectedHours\" : \"1,2,\" , \"selectedMinutes\" : \"0\" }" "http://localhost:8181/rest/model/atg/ commerce/custsvc/order/scheduled/CSRScheduledOrderActor/createCSRScheduledOrder"

The following example shows how you could create a schedule that runs on selected dates in selected months at a specific hour and time. This schedule is also set to end after 345 occurrences:

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"name\" : \"T1 endA, selDatesMonths\" , \"scheduleType\" : \"Calendar\" , \"startDate\" : \"03/10/2012\" , \"endDateOption\" : \"afterOccurrences\" , \"numberOfOccurrances\" : 345 , \"endDate\" : \"03/12/2016\" , \"daysOption\" : \"selectedDates\" , \"selectedDates\" : \"1,3,28\" , \"monthsOption\" : \"selectedMonths\" , \"selectedMonths\" : \"1,3,11\", \"selectedHours\" : \"3,4,5,22\" , \"selectedMinutes\" : \"5,11,59\" }" "http://localhost:8181/rest/ model/atg/commerce/custsvc/order/scheduled/CSRScheduledOrderActor/ createCSRScheduledOrder"

The following example shows how you could create a schedule that runs on selected days within a specific month at a specific hour and minute. This schedule has no end date:

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"name\" : \"T2 endNo, selDaysMonths, allO\" , \"scheduleType\" : \"Calendar\" , \"startDate\" : \"03/10/2012\" , \"endDateOption\" : \"none\" , \"numberOfOccurrances\" : 0 , \"endDate\" : \"03/12/2016\" , \"daysOption\" : \"selectedDays\" , \"selectedDays\" : \"1,2,3,5,6,7\" , \"occurrencesOption\" : \"allOccurrences\" , \"monthsOption\" : \"selectedMonths\" , \"selectedMonths\" : \"4,5,6\", \"selectedHours\" : \"0,23\" , \"selectedMinutes\" : \"59\" }" "http://localhost:8181/rest/model/atg/commerce/custsvc/order/scheduled/ CSRScheduledOrderActor/createCSRScheduledOrder"

The following example shows how you could create a schedule that runs on the second and third Wednesdays and the first, third and twenty-eight day of February at a specific hour and minute:

9 Internal REST MVC Service Call Examples 323 curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"name\" : \"T3 endNo, selDaysMonths, 2n3rdWe\" , \"scheduleType\" : \"Calendar\" , \"startDate\" : \"03/10/2012\" , \"endDateOption\" : \"none\" , \"daysOption\" : \"selectedDays\" , \"selectedDays\" : \"4\" , \"selectedDates\" : \"1,3,28\" , \"occurrencesOption\" : \"selectedOccurrences\" , \"selectedOccurrences\" : \"2,3\" , \"monthsOption\" : \"selectedMonths\" , \"selectedMonths\" : \"2\", \"selectedHours\" : \"12\" , \"selectedMinutes\" : \"0\" }" "http://localhost:8181/rest/model/atg/commerce/custsvc/order/scheduled/ CSRScheduledOrderActor/createCSRScheduledOrder"

Updating a Scheduled Order

The updateCSRScheduledOrder actor-chain is used to update a scheduled order using a scheduled order template.

Parameter Description

scheduledOrderId The repository ID of the scheduled order. Note, this is not the ID of the scheduled order template, but the ID of the scheduled order item.

name The name of the scheduled order.

scheduleType The type of scheduled order. Values can be either calendar or interval.

startDate The start date used for the order.

endDateOption Options that can be set for the end date of the scheduled order. The options include none, afterOccurrences or endBy.

numberOfOccurances This parameter is used with the afterOccurances option to calculate the end date of the scheduled order.

endDate The end date of the scheduled order. Used with the endBy parameter.

daysOption This calendar property sets the delivery days of the scheduled order. The options for this property are allDays, selectedDays and selectedDates.

selectedDays An integer array of selected days, for example, “2,4” indicate Monday and Wednesday. Values start at 1, indicating Sunday, and end with 7, indicating Saturday.

selectedDates An integer array of values between 1 and 31.

occurrencesOption Identifies the occurrence of the scheduled order. Options are allOccurrences or selectedOccurrences. Occurrences are configurable when using selectedDays.

324 9 Internal REST MVC Service Call Examples Parameter Description

selectedOccurrences An integer array for occurrences of the scheduled order. Options are:

1 – First 2 – Second 3 – Third 4 – Fourth 5 – Last

Use this parameter with selectedDays to identify specific occurrences within a month.

monthsOption Allows you to select specific months, selectedMonths, or to use all months, allMonths, for the scheduled order.

selectedMonths Sets the delivery months of the scheduled orders. Values are 0 – 11, which indicate January – December.

selectedHours Identifies the selected hours in an integer array. Values are 0 – 23, where 0 indicates 12:00, and 23 indicates 23:00 or 11:00 p.m.

selectedMinutes Identifies the selected minutes in an integer array. Values are 0 – 59.

selectedInterval Identifies the interval option for the schedule. Selected intervals are used when creating a periodic schedule. When daysOption parameters reference this parameter, it is used for creating calendar schedules.

intervalOption Indicates the interval option, which is either weeks or days. Selected intervals are used when creating a periodic schedule. When daysOption parameters reference this parameter, it is used for creating calendar schedules.

Update Scheduled Order Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"scheduledOrderId\" : \"sco100002\" , \"name\" : \"Modified Company Schedule\" , \"selectedHours\" : \"12, 16, 20\" , \"selectedMinutes\" : \"05\" }" "http://localhost:8181/rest/model/atg/commerce/custsvc/order/scheduled/ CSRScheduledOrderActor/updateCSRScheduledOrder"

Submitting a Scheduled Order

The DuplicateAndSumbitActor is used to duplicate the scheduled order and immediately submit the order. This actor is located at /atg/commerce/custsvc/order/scheduled/ DuplicateAndSubmitActor. Note that before you can submit a scheduled order, the active customer and order must be set. To set the active customer, refer to the Viewing a Customer (page 270) section. To set the current order, refer to the Selecting an Order to Work On (page 311) section.

This actor uses the duplicateAndSumbit actor-chain to identify the template of the scheduled order and then submit it.

9 Internal REST MVC Service Call Examples 325 Parameter Description

orderToDuplicate The ID of the template scheduled order to immediately submit.

Submitting Scheduled Order Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"orderToDuplicate\":\"o100008\"}" "http://localhost:8181/rest/model/atg/ commerce/custsvc/order/scheduled/DuplicateAndSubmitActor"

Activating a Scheduled Order

The ActivateScheduleActoris used to activate a scheduled order and initiate its schedule. This actor is located at /atg/commerce/custsvc/order/scheduled/ activateScheduleActor.

This actor uses the activateSchedule actor-chain to identify and activate both the scheduled order and its template.

Parameter Description

scheduledOrderId The ID of the scheduled order to activate.

orderId The ID of the template order with which the scheduled order is associated.

Activate Scheduled Order Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"orderId\":\"o100008\", \"scheduledOrderId\" : \"sco100002\"}" "http://localhost:8181/rest/model/atg/commerce/custsvc/order/scheduled/ ActivateScheduleActor/activateSchedule"

Deactivating a Scheduled Order

The DeactivateScheduleActor is used to deactivate a scheduled order and terminate its schedule. This actor is located at /atg/commerce/custsvc/order/scheduled/ DeactivateScheduleActor.

This actor uses the deactivateSchedule actor-chain to identify and activate both the scheduled order and its template.

326 9 Internal REST MVC Service Call Examples Parameter Description

scheduledOrderId The ID of the scheduled order to deactivate.

orderId The ID of the template order with which the scheduled order is associated.

Deactivate Scheduled Order Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"orderId\":\"o100008\", \"scheduledOrderId\" : \"sco100002\"}" "http://localhost:8181/rest/model/atg/commerce/custsvc/order/scheduled/ DeactivateScheduleActor/deactivateSchedule"

Displaying Scheduled Order Details

The CSRScheduledOrderInfoActor is used to display the details of a scheduled order once a scheduled order action has occurred. This actor is located at /atg/commerce/custsvc/order/scheduled/ CSRScheduledOrderInfoActor.

Note: The CSRScheduledOrderInfoActor must be used alongside other Commerce Service Center scheduled order actions. Calling this actor directly produces no results.

The CSRScheduledOrderInfoActor contains the following actor-chains:

Actor-Chain Description

getReadableSchedule Used to display the readable details of a scheduled order.

getAllScheduledOrderInfo Used to display all information of a scheduled order.

The getReadableSchedule actor-chain displays the scheduled order details. This actor-chain is used by other actors and actor-chains to obtain data regarding scheduled orders. It has the following parameters:

Parameter Description

scheduledOrderId The ID of the scheduled order or scheduled order item.

scheduledOrder The ID of the template order with which the scheduled order is associated.

locale The locale used to display the output.

Display Readable Scheduled Order Detail Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d

9 Internal REST MVC Service Call Examples 327 "{ \"locale\" : \"en_GB\" , \"scheduledOrderId\" : \"sco90002\" }" http://localhost:8181/rest/model/atg/commerce/custsvc/order/scheduled/ CSRScheduledOrderInfoActor/getReadableSchedule"

The getAllScheduleInfo actor-chain displays the scheduled order details. This actor-chain is used by other actors and actor-chains and returns only the scheduled object.

Parameter Description

scheduledOrderId The ID of the scheduled order or scheduled order item.

scheduledOrder The ID of the template order with which the scheduled order is associated.

locale The locale used to display the output.

Display All Scheduled Order Detail Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"locale\" : \"en_GB\" , \"scheduledOrderId\" : \"sco90002\" }" http://localhost:8181/rest/model/atg/commerce/custsvc/order/scheduled/ CSRScheduledOrderInfoActor/getAllScheduleInfo"

Displaying Scheduled Order Confirmation

The CSRScheduledOrderConfirmationActor is referenced by the CSRScheduledOrderActor, ActiveScheduleActor and DeactivateScheduleActor to display information once a scheduled order action has occurred. Note that this actor is invoked by other actors working on the current order. Calling this actor directly will display no results.

The CSRScheduledOrderConfirmationActor contains the scheduledOrderConfirmation actor-chain, which provides the scheduled order details that confirm success of a specific action, such as creating or activating a scheduled order.

Parameters: None Display Scheduled Order Confirmation Example

curl –L –v -b agent_cookies.txt -H "Content-Type: application/json" http://localhost:8181/rest/model/atg/commerce/custsvc/order/scheduled/ CSRScheduledOrderConfirmationActor/scheduledOrderConfirmation"

Working with Scheduled Order Templates

The CommitOrderActor is used to work with scheduled order templates. The path to this actor is: /atg/ commerce/custsvc/order/CommitOrderActor.

328 9 Internal REST MVC Service Call Examples This actor contains the following actor-chains for working with template orders:

Actor-Chain Description

commitOrder Commits a scheduled order template from a submitted order.

validateTemplateOrder Validates the scheduled order template.

sendCOnfirmationMessage Allows you to send an order confirmation e-mail.

Creating a Template from a Scheduled Order

The commitOrder actor-chain is used to create a template order from a submitted scheduled order. This service call requires that the order has been successfully submit.

Parameter Description

allowEmptyOrders Indicates if empty orders will be permitted in the order.

salesChannel Identifies the sales channel for this order.

siteId Identifies the site ID for this order.

createTemplateFromSubmittedOrder Indicates if a scheduled order template should be created from this submitted order.

Create Template from Order Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{\"createTemplateFromSubmittedOrder\" : \"true\"}" "http://localhost:8080/rest/ model/atg/commerce/custsvc/order/CommitOrderActor/commitOrder"

Validating a Scheduled Order Template

The validateTemplateOrder actor-chain is a service call that validates a template order.

Parameters: None

Validate Scheduled Order Template Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8080/rest/model/atg/commerce/custsvc/order/CommitOrderActor/ validateTemplateOrder"

9 Internal REST MVC Service Call Examples 329 Sending E-Mail Confirmation for a Scheduled Order Template

The sendConfirmationMessage actor-chain allows you to manually send a confirmation e-mail for a specific scheduled order template.

Parameter Description

email The e-mail address, obtained from the customer’s profile. If an e-mail parameter is not passed in, the e-mail address of the current customer will be used by default.

templateName The name of the template. If no template name is provided, the template name that is set on the confirmation object is used.

Send Manual E-Mail Confirmation Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{\"templateName" : \"NEW_ORDER\",\"email\" : \"[email protected]\" }" "http://localhost:8080/rest/model/atg/commerce/custsvc/order/CommitOrderActor/ sendConfirmationMessage"

Identifying a Template Order

The IsScheduledOrderTemplateActor is a service call that identifies if a schedule order is a scheduled order template. This actor is located at /atg/commerce/custsvc/order/scheduled/ and contains the isCurrentOrderScheduledOrderTemplate actor-chain.

Parameters: None

Create Template from Order Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8080/rest/model/atg/commerce/custsvc/order/scheduled/ IsScheduledOrderTemplateActor/isCurrentOrderScheduledOrderTemplate"

Reviewing a Template

The ScheduledOrderLookupActor allows you to iterate through a list of scheduled orders for a specific customer, or other parameter. This actor is located at /atg/commerce/order/scheduled/ ScheduledOrderLookup and uses the scheduledOrderLookup actor-chain.

This actor-chain contains the following parameters. Note that you need to provide only one parameter as the system cycles through all available parameters. If you include more than one parameter, the extra parameters will be ignored. :

330 9 Internal REST MVC Service Call Examples Parameter Description

itemId The ID of the of the item.

templateId The ID of the template.

profileId The ID of the user’s profile.

siteIds The IDs of the sites used in this scheduled order.

siteScope The site scope used in this scheduled order.

Review a Template’s Schedule Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{\"profileId" : \"se-570098\" }" "http://localhost:8080/rest/model/atg/commerce/ order/scheduled/ScheduledOrderLookupActor/scheduledOrderLookup"

Viewing a Template Order List of Submitted Orders

The SubmittedOrderTableActor allows you to view a list of the submitted orders applied to a template order. Note that this call requires the orderID of a submitted order. It is located at /atg/commerce/order/ scheduled/SubmittedOrderTableActor.

This actor uses the list actor-chain:

Parameter Description

orderId The ID of the of the submitted order.

sortDirection The way in which you want to sort the list.

sortField The field used to sort the list.

currentPage The paging results of the search to display.

resultsPerPage The number of results to display per page.

View a Template’s List of Submitted Orders Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{\"orderId" : \"o1233241\" }" "http://localhost:8080/rest/model/atg/commerce/ order/scheduled/SubmittedOrderTableActor/list"

The results may be similar to the following:

9 Internal REST MVC Service Call Examples 331 { "searchResults": [{ "id": "o500035" }, { "id": "o500030" }, { "id": "o500001" }, { "id": "o490001" }, { "id": "o480006" }, { "id": "o480001" }, { "id": "o120006" }, { "id": "o110003" }, { "id": "o90007" }, { "id": "o90003" }], "resultsPerPage": 10, "totalItemCount": 10, "currentPage": 0 }

Viewing a User’s List of Template Orders

The ScheduledOrderTableActor allows you to view a list of the submitted orders for a specific user. It is located at /atg/commerce/order/scheduled/ScheduledOrderTableActor.

This actor uses the list actor-chain:

Parameter Description

profileId The ID of the of the user’s profile.

sortDirection The way in which you want to sort the list.

sortField The field used to sort the list.

currentPage The paging results of the search to display.

resultsPerPage The number of results to display per page.

332 9 Internal REST MVC Service Call Examples View a User’s List of Scheduled Orders Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{\"orderId" : \"o1233241\" }" "http://localhost:8080/rest/model/atg/commerce/ order/scheduled/ScheduledOrderTableActor/list"

The results may be similar to the following:

{ "searchResults": [{ "id": "o120008" }], "resultsPerPage": 10, "totalItemCount": 1, "currentPage": 0 }

Adjusting Customer’s Orders

The following REST services allow an agent to make manual price adjustments to an order, and to initiate a price override.

The ManualAdjustmentsActor is used to make a price adjustment to a customer’s order. The path to this actor is: /atg/commerce/custsvc/order/ManualAdjustmentsActor.

This actor contains the following actor-chains:

Actor-Chain Description

addAdjustment Used to issue a manual adjustment to an order.

deleteAdjustment Used to delete an adjustment from an order.

viewAdjustmentLimits Used to view the adjustment limits for an order.

viewReasonCodes Used to return the reason for an adjustment.

Adjusting a Customer’s Order

The addAdjustment actor-chain is used to issue an adjustment to a customer’s order.

Parameter Description

adjustmentAmount The amount of the adjustment.

9 Internal REST MVC Service Call Examples 333 Parameter Description

adjustmentNote A note to provide a description for the adjustment.

adjustmentReasonCode The adjustment reason code used for this adjustment.

adjustmentType The type of adjustment.

Adjust Order Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"adjustmentAmount\" : \"10\", \"adjustmentReasonCode\" : \"Appeasement\", \"adjustmentNote\" : \"Customer ordered 10 of these last week\", \"adjustmentType\" : \"amountOff\" }" "http://localhost:8280/rest/model/ atg/commerce/custsvc/order/ManualAdjustmentsActor/addAdjustment"

Deleting an Adjustment from a Customer’s Order

This actor contains the deleteAdjustment actor-chain. It is used to delete an existing adjustment from an order.

Parameter Description

adjustmentId The ID of the adjustment.

adjustmentReasonCode The adjustment reason code used for this adjustment.

Delete Order Adjustment Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"adjustmentId\" : \"700001\" }" "http://localhost:8280/rest/model/atg/commerce/ custsvc/order/ManualAdjustmentsActor/deleteAdjustment"

Overriding an Item’s Price in the Customer’s Order

The CartModifierActor contains the setOrderByCommerceId actor-chain that allows an agent to override the price of an item within an order.

To override a price, add the following to the URL:

IPO:commerceItemId=newPrice

334 9 Internal REST MVC Service Call Examples Override Price Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8280/rest/model/atg/commerce/custsvc/order/CartModifierActor/ setOrderByCommerceId?ci172000006=1&IPO:ci172000006=19.99"

Viewing the Adjustment Limits

This actor contains the viewAdjustmentLimits actor-chain. It is used to view the adjustment limits for an order.

Parameters: None

View Adjustment Limits Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" http:// localhost:8080/rest/model/atg/commerce/custsvc/order/ManualAdjustmentsActor/ viewAdjustmentLimits?atg-rest-output=json"

Viewing the Reason Code for an Adjustment

This actor contains the viewReasonCodes actor-chain. It is used to view the reason for which an adjustment was applied.

Parameters: None

View Reason Codes Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" http:// localhost:8080/rest/model/atg/commerce/custsvc/order/ManualAdjustmentsActor/ viewReasonCodes?atg-rest-output=json"

Assisting Customers with Catalogs

The ProductCatalogActor is used to get catalog and product information. The path to this actor is: /atg/commerce/custsvc/catalog/ProductCatalogActor.

This actor contains the following actor-chains:

Actor-Chain Description

getCurrentCatalogRootCategories Obtains the user’s current catalog and root categories.

9 Internal REST MVC Service Call Examples 335 Actor-Chain Description

getCategory Displays the user’s sub-categories.

getProduct Views a product by Product ID.

Getting the Customer’s Current Catalog

The getCurrentCatalogRootCategories actor-chain obtains the current catalog.

Parameters: None

Get Current Catalog Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8280/rest/model/atg/commerce/custsvc/catalog/ ProductCatalogActor/getCurrentCatalogRootCategories"

The server response might be:

{"rootCategories": [ { "id": "homeStoreNonNavigableProducts", "description": "", "defaultParentCategory": null, "displayName": "Non Navigable Products", "type": null }, { "id": "homeStoreRootCategory", "description": null, "defaultParentCategory": null, "displayName": "Home Store Root", "type": null } ]}

Browsing the Customer’s Catalog By Category ID

The getCatagory actor-chain allows the agent to browse the customer’s current catalog by category ID.

Parameter Description

categoryId The ID of the category.

filterBySite Identifies if the product is contained in the current site, and if so filters by site.

filterByCatalog Identifies if the product is contained in the current site, and if so filters by catalog.

336 9 Internal REST MVC Service Call Examples Browse by Catalog ID Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"categoryId\" : \"cat50056\" }" "http://localhost:8280/rest/model/atg/commerce/ custsvc/catalog/ProductCatalogActor/getCategory"

Browsing the Customer’s Catalog By Product ID

The getProduct actor-chain allows the agent to browse the customer’s current catalog and to look up products by their ID.

Parameter Description

productId The ID of the product.

filterBySite Identifies if the product is contained in the current site, and if so filters by site.

filterByCatalog Identifies if the product is contained in the current site, and if so filters by catalog.

siteIds The site associated with the catalog.

catalogs Identifies the catalogs to browse.

Get Product by Product ID Example

curl -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"productId\" : \"xprod1047\"}" "http://localhost:8280/rest/model/atg/commerce/ custsvc/catalog/ProductCatalogActor/getProduct"

Searching for Catalogs with Criteria

The MoreCatalogsSearchActor allows an agent to search for specific catalogs. This actor uses the catalogSearch actor-chain, and is located at /atg/commerce/custsvc/catalog/ MoreCatalogsSearchActor.

The catalogSearch actor-chain uses the following parameters:

Parameter Description

resultSetSize Sets the number of results that are displayed per page. The default is 10.

keyword The keyeword used to search the catalogs.

startDate Optional. The start date used to search the catalogs. For example, YYYY-MM-DD HH:MM:SS format, or, 2010-08-11 00:00:00.

9 Internal REST MVC Service Call Examples 337 Parameter Description

endDate Optional. The end date used to search the catalogs. For example, YYYY-MM-DD HH:MM:SS format, or, 2010-08-11 00:00:00.

allowEmptySearch When this parameter is set to true, if there is no search criteria, all catalogs will be searched.

Search Catalog Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{\"keyword\" : \"Store\", \"startDate\" : \"2009-09-28 00:00:00\", \"endDate\" : \"2013-03-12 15:39:59\"}" "http://localhost:8080/rest/model/atg/ commerce/custsvc/catalog/MoreCatalogsSearchActor/catalogSearch"

Working with the Current Catalog

The EnvironmentChangeActor allows an agent to work with the current catalog. The path to this actor is: / atg/commerce/custsvc/environment/EnvironmentChangeActor.

This actor contains the following catalog actor-chains:

Actor-Chain Description

setCurrentCatalog Selects a catalog and makes it the current catalog.

getCurrentCatalog Retrieves the user’s current catalog.

setDefaultCatalog Resets the user’s default catalog

Selecting a Current Catalog

The setCurrentCatalog actor-chain allows an agent to select a catalog and make it the current catalog.

Parameter Description

catalogId The ID of the catalog to find.

Select Catalog Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{\"catalogId\" : \"homeStoreCatalog\"}" "http://localhost:8080/rest/model/

338 9 Internal REST MVC Service Call Examples atg/commerce/custsvc/environment/EnvironmentChangeActor/setCurrentCatalog"

Retrieving the Current Catalog

The getCurrentCatalog actor-chain retrieves the user’s current catalog.

Parameters: None

Retrieve Current Catalog Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8080/rest/model/atg/commerce/custsvc/environment/ EnvironmentChangeActor/getCurrentCatalog"

Resetting the Current Catalog

The setDefaultCatalog actor-chain resets the user’s current default catalog.

Parameters: None

Reset Current Catalog Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8080/rest/model/atg/commerce/custsvc/environment/ EnvironmentChangeActor/setDefaultCatalog"

Obtaining Product Prices

The PricingActor is used to obtain prices for products using product IDs or SKU IDs. The path to this actor is: / atg/commerce/pricing.

This actor contains the following actor-chains:

Actor-Chain Description

productPriceRanges Provides the lowest and highest sale price for a product. These prices are obtained from the user’s profile.

skuPrices Displays either the listPrice and salePrice for a specific SKU if price lists are enabled. If price lists are not enabled, displays both listPrice and salePrice.

Getting Price Ranges for a Product

The productPriceRanges actor-chain returns the lowest and highest prices for a specific product. It uses the following parameters:

9 Internal REST MVC Service Call Examples 339 Parameter Description

productId Identifies the product ID to use.

Get Prices by Range ID Example

curl -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"productId\" : \"xprod2085\"}" "http://localhost:8280/rest/model/atg/commerce/ pricing/PricingActor/productPriceRanges"

The server response may be similar to the following:

{"highestSalePrice": 19, "lowestSalePrice": 19, }

Obtaining List Price and Sale Prices for a Product by SKU

The skuPrices actor-chain returns the list and sale prices for a specific product using its SKU ID. It uses the following parameters:

Parameter Description

productId Identifies the product ID to use.

skuId The SKU ID to use.

Obtain Prices by Product ID Example

curl -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"skuId\" : \"xsku2085\"}" "http://localhost:8280/rest/model/atg/commerce/ pricing/PricingActor/skuPrices"

The server response may be similar to the following:

{"listPrice": 19, "salePrice": 19,}

Working with Customer’s Price Lists

The EnvironmentChangeActor also allows an agent to work with the current price lists. The path to this actor is: /atg/commerce/custsvc/environment/EnvironmentChangeActor.

340 9 Internal REST MVC Service Call Examples This actor contains the following price list actor-chains:

Actor-Chain Description

setCurrentPriceList Selects a price list and makes it the current price list.

getCurrentPriceList Retrieves the user’s current price list.

setDefaultPriceList Resets the user’s default price list.

Selecting a Current Price List

The setCurrentPriceList actor-chain allows an agent to select a price list and make it the current price list.

Parameter Description

priceListId The ID of the price list to find.

Select Price List Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{\"priceListId\" : \"salePrices\"}" "http://localhost:8080/rest/model/ atg/commerce/custsvc/environment/EnvironmentChangeActor/setCurrentPriceList"

Retrieving the Current Price List

The getCurrentPriceList actor-chain retrieves the user’s current price list.

Parameters: None

Retrieve Current Price List Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8080/rest/model/atg/commerce/custsvc/environment/ EnvironmentChangeActor/getCurrentPriceList"

Resetting the Current Price List

The setDefaultPriceList actor-chain resets the user’s current default price list.

Parameters: None

9 Internal REST MVC Service Call Examples 341 Reset Current Price List Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8080/rest/model/atg/commerce/custsvc/environment/ EnvironmentChangeActor/setDefaultPriceList"

Searching for a Price List

The PriceListSearchActor allows an agent to search for a price list. It is located at /atg/commerce/ custsvc/pricing/pricelists/PriceListSearchActor and uses the priceListSearch actor-chain.

Parameter Description

resultSetSize Allows you to set the number of the results displayed on the page. The default is 10.

keyword The keyword used to search

startDate Specifies the start date of a search date range. For example, YYYY-MM-DD HH:MM:SS format, or, 2010-08-11 00:00:00.

endDate Specifies the end date of a search date range. For example, YYYY-MM-DD HH:MM:SS format, or, 2010-08-11 00:00:00.

allowEmptySearch When set to true, this parameter allows you to search without using a search criteria.

Search Price List Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{\"keyword\" : \"sale\", \"startDate\" : \"2000-09-28 00:00:00\", \"endDate\" : \"2013-03-12 15:39:59\"}" "http://localhost:8180/rest/model/atg/commerce/custsvc/ pricing/priceLists/PriceListSearchActor/priceListSearch"

Working with Customer’s Promotions

The PromotionWalletActor is used to work with customer’s promotion information. The path to this actor is: /atg/commerce/custsvc/promotion/PromotionWalletActor.

This actor contains the following actor-chains:

342 9 Internal REST MVC Service Call Examples Actor-Chain Description

getAvailablePromotions Obtains the available promotions.

updatePrice Updates the price of the order.

grantPromotion Add a promotion.

unGrantPromotion This chain allows an agent to remove an agent-granted promotion.

includePromotionInOrder This chain is used to add promotions that are presented by the promotions wallet.

excludePromotionFromOrder This chain is used to ignore promotions that are presented by the promotions wallet.

saveWallet Saves the promotion wallet.

revertWallet Reverts the order before promotions were included.

Getting Available Promotions

The getAvailablePromotions actor-chain returns a list of promotions that can be used.

Parameter Description

resultsPerPage Identifies the number of promotions that will be displayed on the page.

Get Available Promotions Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"resultSetSize\" : 20 }" "http://localhost:8080/rest/model/atg/ commerce/custsvc/promotion/PromotionWalletActor/getAvailablePromotions"

The response may be similar to the following:

{"availablePromotions":[ { "ignored":false, "agentGranted":false, "closenessQualifiers":[], "close":false, "considered":false, "discount":0, "promotionId":"promo10003", "usable":true, "promotionName":"CRS Home - Free Shipping", "applied":true, "active":false,

9 Internal REST MVC Service Call Examples 343 "promotionStateId":"80" }, { "ignored":false, "agentGranted":false, "closenessQualifiers":[ { "id":"se-200005", "name":"Save $10 on all orders over $100" } ], "close":true, "considered":false, "discount":0, "promotionId":"promo50012", "usable":true, "promotionName":"$10 off Orders over $100", "applied":false, "active":false, "promotionStateId":"82" } ]}

Updating Prices After Promotions

The updatePrice actor-chain returns an updated price of the customer’s order.

Parameters: None

Update Order with Promotions Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8080/rest/model/atg/commerce/custsvc/promotion/ PromotionWalletActor/updatePrice"

Adding a Promotion

The grantPromotion actor-chain adds a promotion to the order. This actor-chain has the following parameters:

Parameter Description

promotionId The ID of the promotion to be granted.

Add Promotions Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"promotionId\": \"promoto20010\" }" "http://localhost:8080/rest/model/atg/ commerce/custsvc/promotion/PromotionWalletActor/unGrantPromotion"

344 9 Internal REST MVC Service Call Examples Removing a Promotion

The unGrantPromotion actor-chain removes a promotion from the order. In Commerce Service Center, only agent-granted promotions can be removed by agents. This actor-chain has the following parameters:

Parameter Description

promotionStateId The ID of the state of promotion to be granted.

Remove Promotions Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"promotionStateId\": \"92\" }" "http://localhost:8080/rest/model/atg/commerce/ custsvc/promotion/PromotionWalletActor/unGrantPromotion"

Include Promotions from Wallet

The includePromotionInOrder actor-chain adds a promotion from the promotions wallet. This actor-chain has the following parameters:

Parameter Description

promotionId The ID of promotion to be added.

Include Promotion Wallet Promotions Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"promotionId\": \"promo20010\" }" "http://localhost:8080/rest/model/atg/ commerce/custsvc/promotion/PromotionWalletActor/includePromotionInOrder"

Ignoring Promotions from Wallet

The excludePromotionFromOrder actor-chain excludes promotions that may be added to the order from the promotions wallet. This actor-chain has the following parameters:

Parameter Description

promotionId The ID of promotion to be ignored.

9 Internal REST MVC Service Call Examples 345 Ignore Promotion Wallet Promotions Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"promotionId\": \"promo20010\" }" "http://localhost:8080/rest/model/atg/ commerce/custsvc/promotion/PromotionWalletActor/excludePromotionInOrder"

Saving the Promotions Wallet

The saveWallet actor-chain saves the promotions wallet.

Parameters: None Save Promotions Wallet Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8080/rest/model/atg/commerce/custsvc/promotion/ PromotionWalletActor/saveWallet"

Reverting the Promotions Wallet

The revertWallet actor-chain reverts to the last saved version of the promotions wallet.

Parameters: None Revert Promotions Wallet Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8080/rest/model/atg/commerce/custsvc/promotion/ PromotionWalletActor/revertWallet"

Obtaining Closeness Qualifiers

The ClosenessQualifierActor enables an agent to view how close a customer is to qualifying for a promotion. This actor is located at /atg/commerce/custsvc/promotion/ ClosenessQualifierActor, and contains the getClosenessQualifiers actor-chain.

Parameters: None Obtain Closeness Qualifiers Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8080/rest/model/atg/commerce/custsvc/promotion/ ClosenessQualifierActor/getClosenessQualifiers"

The response may be similar to the following:

{"closenessQualifiers":[ {"id":"se-200005",

346 9 Internal REST MVC Service Call Examples "name":"Save $10 on all orders over $100"} ]}

Searching for Promotions

The PromotionsSearchActor enables an agent to search for a promotion. This actor is located at /atg/ commerce/custsvc/promotion/PromotionSearchActor, and contains the searchPromotions actor- chain.

Parameter Description

keyword The keyword used to search for promotions.

dateOption The date to search for the promotion. This parameter can take the following values: Today, Start in Next 7 Days, End in Last 7 Days, All Future, or All Expired.

type The type of promotion to search for. This parameter can take the following values: " empty, which gets all types, Item Discount, Order Discount, or Shipping Discount.

hideGlobal To hide global discounts, set this parameter to true.

site Which sites to search for promotions. This parameter can take the following values: " empty, which gets all sites or site name.

resultsSetSize The number of promotion results to display.

Search Promotions Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"keyword\" : \"10\", \"dateOption\" : \"Today\", \"type\" : \"\" , \"hideGlobal\" : \"true\", \"site\" : \"\", \"resultSetSize\" : 20}" "http://localhost:8080/rest/model/atg/commerce/custsvc/promotion/ PromotionSearchActor/searchPromotions"

The response may be similar to the following:

{"searchResults":[ { "id":"abandonedOrderDiscount", "displayName":"10% off Order" }, { "id":"promo20011", "displayName":"TENSHIP Coupon - 10% Off Order" } ]}

9 Internal REST MVC Service Call Examples 347 Adding Store Credit

The AddStoreCreditActor allows an agent to add store credit to a profile. The profile must be active before the agent can issue a credit. Refer to Selecting a Customer to Work On (page 276). This actor is located at / atg/commerce/custsvc/profile/AddStoreCreditActor and uses the addStoreCredit actor-chain with the following parameters:

Parameter Description

amount The amount of the credit.

comments Any comments regarding the credit.

Store Credit Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"amount\" : \"10\", \"comments\" : \"Loyalty Customer – Added $10 credit\" }" "http://localhost:8180/rest/model/atg/commerce/custsvc/profile/ AddStoreCreditActor/addStoreCredit"

Displaying Lost Promotions

The LostPromotionsActor displays a list of promotions that a customer loses during the returns and exchanges process. Note that this data is not saved and can only be retrieved during the return and exchange process. This actor is located at /atg/commerce/custsvc/returns/LostPromotionsActor. It contains the promotionsLost actor-chain.

Parameters: None

Display Lost Promotions Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8180/rest/model/atg/commerce/custsvc/returns/ LostPromotionsActor/promotionsLost"

The response may be similar to the following:

{"promotionsLost":"promo50012"}

Displaying Changed Promotions

The CSRReturnsActor uses the changePromotions actor-chain to display a list of promotions that change when items are returned or exchanged from a shipped order. This call returns a list of promotion IDs and display names. The path to this actor is: /atg/commerce/custsvc/returns/ CSRReturnsActor.

348 9 Internal REST MVC Service Call Examples Parameters: None

Display Changed Promotions Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8180/rest/model/atg/commerce/custsvc/catalogs/ CSRReturnsActor/changedPromotions"

The response may be similar to the following:

{\"ChangedPromotions\": { \"id\" : \"promo50012\", \"displayName\" : \"10 off orders over $100\" }

Working with Customer’s Gift Lists

The following actors are used to work with a customer’s gift or wish list. For information on adding a gift or wish list item to a shopping cart, refer to Add Item From Customer’s Gift List Example (page 288) and Add Item From Customer’s Wish List Example (page 289).

The CSRGiftlistActor contains several actor-chains that initiate gift list actions. The path for this actor is / atg/commerce/custsvc/gifts/.

This actor contains the following actor-chains:

Actor-Chain Description

createGiftlist Creates a gift or wish list.

updateGiftlist Updates a gift or wish list.

addItemToGiftlist Adds an item to a gift list.

removeItemFromGiftlist Removes an item from a gift list.

addItemToWishlist Adds an item to a wish list.

removeItemFromWishlist Removes an item from a wish list.

moveItemsFromCart Removes a gift or wish list item from the Shopping Cart.

deleteGiftlist Deletes a gift or wish list.

Creating a Customer’s Gift or Wish List

The createGiftlist actor-chain creates a gift list or a wish list.

9 Internal REST MVC Service Call Examples 349 Note: The following parameters are all optional, unless stated otherwise.

Parameter Description

isPublished Identifies if the list has been published.

siteId The ID of the site.

eventName Required. The name of the gift list event.

eventDate Required. The date of the gift list event.

eventType Required. The type of the gift list event.

description A description of the gift list.

comments Any comments that are included with the list.

shippingAddressId The ID of the shipping address.

instructions Any instructions that are included with the list.

isNewAddress Identifies if the address included in this list is new.

firstName The first name of the customer.

middleName The middle name or initial of the customer.

lastName The last name of the customer.

address1 The first address field of the customer.

address2 The second address field of the customer.

city The city of the customer’s address.

state The state or province of the customer’s address.

postalCode The postal code of the customer’s address.

country The country of the customer’s address.

phoneNumber The phone number associated with the customer.

Basic Create Gift List Example

This example uses only the required parameters.

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"eventName\" : \"Wedding\", \"eventType\": \"Wedding\", \"eventDate\" : \"AUG 30, 2013\" }" "http://localhost:8180/rest/model/atg/commerce/custsvc/ gifts/CSRGiftlistActor/createGiftlist"

350 9 Internal REST MVC Service Call Examples Create Gift List with Existing Address Example

This example uses an existing customer address. The address is identified by the shippingAddressId parameter.

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"eventName\" : \"Birthday\", \"eventType\": \"Birthday\", \"eventDate\" : \"NOV 10, 2013\",\"shippingAddressId\" : \"270015\" }" "http://localhost:8180/ rest/model/atg/commerce/custsvc/gifts/CSRGiftlistActor/createGiftlist"

Create Gift List with New Address Example

This example creates a new customer address.

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"eventName\" : \"Valentines\", \"eventType\": \"Other\", \"eventDate\" : \"FEB 14, 2014\",\"isNewAddress\" : \"true\", \"firstName\":\"Tara\", \"lastName\":\"Hammond\", \"middleName\":\"C\", \"address1\":"\101 First St\", \"address2\":null, \"city\":\"Cambridge\",\"state\":\"MA\",\"country\":\"USA\", \"postalCode\": \"02146\", \"phoneNumber\":\"617-637-8687\" }" "http://localhost:8180/rest/model/atg/commerce/custsvc/gifts/CSRGiftlistActor/ createGiftlist"

Updating a Customer’s Gift or Wish List

The updateGiftlist actor-chain allows an agent to edit a customer’s gift or wish list.

Note: The following parameters are all optional, unless stated otherwise.

Parameter Description

isPublished Identifies if the list has been published.

siteId The ID of the site.

eventName Required. The name of the gift list event.

eventDate Required. The date of the gift list event.

eventType Required. The type of the gift list event.

description A description of the gift list.

comments Any comments that are included with the list.

shippingAddressId The ID of the shipping address.

instructions Any instructions that are included with the list.

isNewAddress Identifies if the address included in this list is new.

firstName The first name of the customer.

9 Internal REST MVC Service Call Examples 351 Parameter Description

middleName The middle name or initial of the customer.

lastName The last name of the customer.

address1 The first address field of the customer.

address2 The second address field of the customer.

city The city of the customer’s address.

state The state or province of the customer’s address.

postalCode The postal code of the customer’s address.

country The country of the customer’s address.

phoneNumber The phone number associated with the customer.

Update Customer Gift List Example

curl -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"giftlistId\": \"gl240010\", \"eventName\" : \"St Patricks Day\", \"eventType\": \"Other\",\"description\": \"Things needed for St Patrick's Day\", \"eventDate\" : \"MAR 17, 2013\"}" "http://localhost:8180/rest/model/atg/commerce/custsvc/gifts/ CSRGiftlistActor/updateGiftlist"

Adding Items to a Customer’s Gift List

The addItemToGiftlist actor-chain allows an agent to add an item to a customer’s gift list.

Parameter Description

giftlistId The ID of the gift list.

quantity The quantity of the products to add to the gift list.

productId The product ID of the product to add to the gift list.

catalogRefIds The catalog reference ID of the product being added to the gift list.

siteId The ID of the site.

Add Item to Customer Gift List Example

curl -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{

352 9 Internal REST MVC Service Call Examples \"giftlistId\": \"gl380011\", \"productId\": \"xprod1015\", \"catalogRefIds\" : \"xsku1043\",\"quantity\": \"2\", \"siteId\": \"homeSite\"}" "http://localhost:8180/rest/model/atg/commerce/custsvc/gifts/CSRGiftlistActor/ addItemToGiftlist"

Adding Items to a Customer’s Wish List

The addItemToWishlist actor-chain allows an agent to add an item to the active customer’s wish list.

Parameter Description

siteId The ID of the site.

quantity The quantity of the products to add to the wish list.

productId The product ID of the product to add to the wish list.

catalogRefIds The catalog reference ID of the product being added to the wish list.

Add Item to Customer’s Wish List Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"productId\": \"xprod2085\", \"catalogRefId\" : \"xsku2085\", \"quantity\": \"1\", \"siteId\":\"homeSite\" }" "http://localhost:8280/rest/model/atg/ commerce/custsvc/gifts/CSRGiftlistActor/addItemToWishlist"

Removing Items from a Customer’s Gift List

The removeItemFromGiftlist actor-chain allows an agent to remove an item from a customer’s gift list.

Parameter Description

giftlistId The ID of the gift list from which the items will be removed.

giftitemId The ID of the item to remove from the gift list.

Remove Item from Customer’s Gift List Example

curl -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"giftlistId\": \"gl380011\", \"giftItemId\" : \"gi30002\"}" "http://localhost:8180/rest/model/atg/commerce/custsvc/gifts/CSRGiftlistActor/ removeItemFromGiftlist"

9 Internal REST MVC Service Call Examples 353 Removing Items from a Customer’s Wish List

The removeItemFromWishlist actor-chain enables an agent to remove an item from a customer’s wish list.

Parameter Description

giftitemId The ID of the items to be removed from the wish list.

Remove Item from Customer’s Wish List Example

curl -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"giftItemId\" : \"gi30001\" }" "http://localhost:8280/rest/model/atg/commerce/ custsvc/gifts/CSRGiftlistActor/removeItemFromWishlist"

Moving Items to a Gift or Wish List from a Customer’s Shopping Cart

The moveItemsFromCart actor-chain allows an agent to take an item from a shopping cart and move it into the specified gift or wish list. You can specify a default quantity for an item, or specify the quantity for a specific item.

Parameter Description

giftlistId The ID of the gift or wish list to which the items will be moved.

itemIds The IDs of the items to move to the list.

quantity The quantity of the items to move to the list.

Move Item to Gift or Wish List from Customer’s Cart Example

curl -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"giftlistId\" : \"gl620010\", \"itemIds\": \"ci42000001\"}" "http://localhost:8180/rest/model/atg/commerce/custsvc/gifts/CSRGiftlistActor/ moveItemsFromCart?ci42000001=6"

Deleting a Customer’s Gift List

The deleteGiftlist actor-chain allows an agent to delete a specific gift list.

Parameter Description

giftlistId The ID of the gift or wish list to delete.

354 9 Internal REST MVC Service Call Examples Delete a Customer’s Gift List Example

curl -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"giftlistId\": \"gl220010\" }" "http://localhost:8180/rest/model/atg/commerce/ custsvc/gifts/CSRGiftlistActor/deleteGiftlist"

Viewing a Customer’s Gift List

The GiftlistLookupActor enables an agent to view a customer’s gift or wish list. This actor is located at: / atg/commerce/gifts/GiftlistLookupActor, and contains the following actor-chains.

Actor-Chain Description

view Views the ID of the customer’s gift or wish list.

giftlistItems Displays the items within the gift list.

The view actor-chain contains the following parameter:

Parameter Description

giftlistId The ID of the gift or wish list to view.

View Gift List Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"giftListId\" : \"gl430003\"}" "http://localhost:8280/rest/model/atg/commerce/ gifts/GiftlistLookupActor/view"

The server response may be similar to the following:

{"giftlist": { "giftlistItems": [], "instructions": null, "description": null, "name": "Valentines", "public": true, "date": {"time": 1360816200000}, "type": "Other", "repositoryId": "gl130271", "addressId": "230324", } }

9 Internal REST MVC Service Call Examples 355 The giftlistItems actor-chain contains the following parameter:

Parameter Description

giftlistId The ID of the gift or wish list to view.

View Gift List Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"giftListId\" : \"gl430003\"}" "http://localhost:8280/rest/model/atg/commerce/ gifts/GiftlistLookupActor/giftlistItems"

Viewing a Customer’s Wish List

The ServiceCustomerProfileActor enables an agent to view a customer’s gift or wish list. This actor is located at /atg/userprofiling/ServiceCustomerProfileActor, and contains the viewWishlist actor- chain.

Parameters: None

View Gift or Wish List Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8280/rest/model/atg/userprofiling/ServiceCustomerProfileActor/ viewWishlist"

Searching for a Customer’s Gift List

The CSRGgiftlistSearchActor is used to find a customer’s gift list. This actor is located at /atg/commerce/ gifts/ and contains the search actor-chain.

Parameter Description

firstName The first name of the customer.

lastName The last name of the customer.

eventType The list event type.

eventDate The list event date.

sortField Indicates the field used to sort the results.

sortDirection Indicates the direction that the results are sorted.

356 9 Internal REST MVC Service Call Examples Parameter Description

resultsPerPage The number of results that are displayed per page.

currentPage The paging results of the search to display.

Search for Customer Gift List Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"firstName\" : \"Stuart\", \"lastName\" : \"Schmidt\", \"eventType\": \"Other\", \"eventDate\" : \"AUG 30, 2013\", \"sortDirection\": \"desc\", \"sortField\" : \"eventName\",\"currentPage\": 1, \"resultsPerPage\": 5 }" "http://localhost:8180/ rest/model/atg/commerce/gifts/CSRGiftlistSearchActor/search"

The server response may be similar to the following:

{"giftlists": [ { "giftlistItems": [], "instructions": null, "description": null, "name": "Birthday", "public": true, "date": {"time": 1377837000000}, "type": "Other", "repositoryId": "gl140010", "addressId": null }, { "giftlistItems": [{ "siteId": "storeSiteUS", "skuId": "xsku1043", "quantity": 2, "repositoryId": "gi50001", "productId": "xprod1015" }], "instructions": null, "description": null, "name": "updated test", "public": true, "date": {"time": 1377837000000}, "type": "Other", "repositoryId": "gl120010", "addressId": null }, { "giftlistItems": [], "instructions": null, "description": null, "name": "Anniversary", "public": true, "date": {"time": 1377837000000}, "type": "Other", "repositoryId": "gl120011", "addressId": null

9 Internal REST MVC Service Call Examples 357 } ] }

Viewing a List of Customer’s Gift or Wish Lists

The GiftlistTableActor allows an agent to display a list of all of the customer’s gift or wish lists. This actor is located at /atg/commerce/custsvc/gifts/GiftlistTableActor, and contains the list actor-chain.

Parameter Description

doOwnerSearch This Boolean parameter, if set to true, restricts search results to the current customer.

doSiteFilterSearch Filter sites when searching.

includeDisabledSites Include disabled sites in the view.

sortDirection Indicates the direction that the results are sorted.

sortField Indicates the field used to sort the results.

resultsPerPage The number of results that are displayed per page.

currentPage The paging results of the search to display.

View Customer List of Gift List Example

curl -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"doOwnerSearch\" : false, \"doSiteFilterSearch\": false, \"includeDisabledSites\" : false, \"sortDirection\": \"desc\", \"sortField\" : \"eventName\", \"currentPage\": 1, \"resultsPerPage\": 5 }" "http://localhost:8180/rest/model/atg/commerce/custsvc/gifts/GiftlistTableActor/ list"

A possible server response might be:

{ "resultsPerPage": 10, "totalItemCount": 1, "currentPage": 0, "giftlists": [{ "giftlistItems": [], "instructions": null, "description": null, "name": null, "public": true, "date": {"time": 1364308351415}, "type": null,

358 9 Internal REST MVC Service Call Examples "repositoryId": "gl130274" "addressId": "230327" }] }

Assisting Customers with In-Store Pickup

The REST MVC service calls that agents use to assist customer with in-store pickup are similar to the external- based REST calls. Refer to the Working with In-Store Pickup (page 244) section for actor-chains and parameters.

When agents initiate these REST calls, their session will use the agent_cookies.txt file.

Agent Search for Store Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"distance\" : \"10\", \"skuId\" : \"sku30029\"}" "http://localhost:8280/rest/ model/atg/commerce/locations/StoreLocatorActor/locateItems"

Agent Display In-Store Search Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"pageNum\" : \"2\"}" "http://localhost:8280/rest/model/atg/commerce/locations/ StoreLocatorActor/currentResultPageNum"

For information on adding an item to an in-store pickup, refer to Adding Items to a Customer’s Shopping Cart (page 288).

Working with Approvals

The REST MVC Web service calls allow agents or supervisors to view, approve or reject order modifications. For information on approvals in Commerce Service Center, refer to the Commerce Service Center User Guide

Finding Pending Approvals

The ViewAllPendingApprovalsActor allows an agent or supervisor to find orders that are waiting for approval before fulfillment. This actor contains the viewAllPendingApprovals actor-chain. This actor is located at /atg/commerce/custsvc/approvals/ViewAllPendingApprovalsActor.

Parameters: None

Find Pending Approvals Example

curl \-L \-v \-c agent_cookies.txt \-H "Content-Type: application/json"

9 Internal REST MVC Service Call Examples 359 "http://localhost:8180/rest/model/atg/commerce/custsvc/approvals/ ViewAllPendingApprovalsActor/viewAllPendingApprovals"

The response may be similar to the following:

"pendingApprovals": { "creationDate": { "time": 1364378657000 }, "customerId": "210006", "orderTotal": 13.75, "appeasementTotal": -12, "agentId": "a10001", "customerEmail": "[email protected]", "orderId": "o1200001" }, { "creationDate": { "time": 1364378689000 }, "customerId": "210006", "orderTotal": 18.75, "appeasementTotal": -12, "agentId": "a10001", "customerEmail": "[email protected]", "orderId": "o1200002" }

Approving or Rejecting a Pending Order

The ApproveOrderActor is used to approve or reject any order that is waiting for authorization. This actor is located at /atg/commerce/custsvc/approvals/order/ApproveOrderActor, and contains the following actor-chains:

Actor-Chain Description

approveOrder Approves a pending order.

rejectOrder Rejects a pending order.

The approveOrder actor-chain allows an agent or supervisor to approve a pending order.

Parameter Description

approvalId The ID of the approval.

360 9 Internal REST MVC Service Call Examples Parameter Description

newOrderId The ID of the order that has been approved.

Approve Order Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{\"newOrderId\": \"o650008\",\"approvalId\": \"400003\"}" "http://localhost:8180 /rest/model/atg/commerce/custsvc/approvals/order/ApproveOrderActor/approveOrder"

The rejectOrder actor-chain allows an agent or supervisor to reject a pending order.

Parameter Description

approvalId The ID of the approval.

newOrderId The ID of the order that has been rejected.

Reject Order Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"newOrderId\": \"o650008\",\"approvalId\": \"400003\"}" "http://localhost:8180 /rest/model/atg/commerce/custsvc/approbals/order/ApproveOrderActor/rejectOrder"

Assisting the Customer with Returns and Exchanges

The returns and exchange process allows an agent to assist a customer when returning and/or exchanging an item.

Returns and Exchange Process Overview

When an agent initiates a return and exchange process, the workflow process may be similar to the following:

1. The return or exchange process is initiated by calling the createReturn actor-chain. This actor-chain generates a shippinGroupsList itemList as a list of all of the possible items that can be returned from an order.

2. Return codes for items to be returned and/or exchanged are obtained by calling the returnReasons actor chain.

3. The process continues by calling the selectItems actor chain, which passes in the updated shippingGroupList and return reason codes.

9 Internal REST MVC Service Call Examples 361 4. From this point, there are a number of actions that can be performed, depending on the requirements of the returns and exchange process.

• Obtain the list of refund methods that can be used to provide the customer with a refund by calling the modifiableRefundsMethodList actor-chain. By default, this amount is credited back to the original credit card.

• Modify the default amounts that are credited to the refund methods by calling the applyRefunds actor- chain.

• Modify the default refund amounts by calling the ModifyRefundValuesActor.

• Display any promotions that are lost as part of a return or an exchange by calling the LostPromotionsActor. Note that this data is calculated when the actor is called, but the data is not saved.

• Display any promotions that have been changed as part of the return or exchange process by calling the changePromotions actor-chain.

5. To complete the return or exchange process, use the confirmReturn actor-chain to confirm that the item should be returned or exchanged. The confirmation chain can be customized to display different confirmation details.

6. Once the return or exchange process is complete, you can process items when they have been received back from the customer by calling the receiveReturnItems actor-chain, and display return history for a specific order by calling the returnsHistory actor-chain.

The CSRReturnsActor is used when working with returns and exchanges. This actor, along with the ModifyRefundValuesActor, and the LostPromotionsActor, comprise the agent-based returns and exchanges functionality. The path to this actor is: atg/commerce/custsvc/returns/ CSRReturnsActor.

This actor contains the following actor-chains:

Actor-Chain Description

createReturn Initiates the return request.

selectItems Adds items to the return request.

confirmReturn Displays confirmation of the return request.

confirmation Displays the return/exchange details to confirm that the return was successful.

cancelReturnRequest Cancels the return request.

returnReasons Obtains the return reason codes for the request.

receiveReturnItems Displays the details of the items selected for return.

modifiableRefundsMethodList Retrieves a list of all methods to which a refund can be applied.

applyRefunds Applies a refund type and value to the order.

362 9 Internal REST MVC Service Call Examples Actor-Chain Description

isCurrentOrderReturnable Identifies if the current order is returnable

isItemReturnable Identifies if items within the order are returnable.

isReturnActive Determines if there is a return in process for this order.

returnsHistory Displays the return history of this order

returns Displays the order’s return request.

nonReturnItemDetails Displays refund adjustments that were applied to non-return items.

changedPromotions Identifies promotions that have changed during the return process. For information on this actor-chain, refer to the Displaying Changed Promotions (page 348) section.

Creating a Return

The createReturn actor-chain initiates a return request specific to the order ID passed in and sets the Commerce Service Center environment settings, such as price lists. Note that this actor-chain calls the StartReturnExchangeProcess form handler. The external createReturn actor-chain uses the ReturnFormHandler. For information on the external createReturn actor-chain, refer to the Initiating a Return (page 226) section. Subsequent Return REST calls use this return request for the order specific return details. It contains the following parameters:

Parameter Description

newOrderId The ID of the order to be returned.

Initiate Returns and Exchanges Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{\"newOrderId\":\"xco30045\"}" "http://localhost:8181/rest/model/atg/commerce/ custsvc/returns/CSRReturnsActor/createReturn"

The server response may be similar to the following:

{ "returnRequest":{ "shippingGroupList":[ { "shippingPriceRaw":18.95, "shippingMethod":"Next Day", "shippingGroupId":"xcsg20080", "itemList":[ {

9 Internal REST MVC Service Call Examples 363 "returnItemId":"xcr10101", "quantityShipped":1, "quantityReturned":0, "quantityAvailable":1, "description":"Boyfriend Jeans", "commerceItemId":"xci1000051", "catalogRefId":"xsku2519_2" }, { "returnItemId":"xcr10102", "quantityShipped":1, "quantityReturned":0, "quantityAvailable":1, "description":"Corduroy Cargo Pants", "commerceItemId":"xci1000052", "catalogRefId":"xsku2512_2" }, { "returnItemId":"xcr10103", "quantityShipped":1, "quantityReturned":0, "quantityAvailable":1, "description":"Huey Martini Glass", "commerceItemId":"xci1000053", "catalogRefId":"xsku2076" } ], "shippingAddress":{ "lastName":"Robinson", "state":"NY", "address1":"604 Red Mountain Road", "address2":null, "country":"US", "city":"Rochester", "postalCode":"14603", "phoneNumber":"212-555-8885", "email":null, "firstName":"Adrian" } } ], "orderCurrencyCode":"USD", "orderId":"xco30045" } }

Adding Items to a Return Request

The selectItems actor-chain identifies the items that will be returned in the current return request. This actor-chain, which requires that the createReturn actor-chain is called first, takes the input from an updated JSON-formatted return request and then uses that input to set the server-side shipping group list’s return item values. Note that you must update the shippingGroupList items to set the number of items to be returned or exchanged, and the reason code. Refer to the Obtaining Return Reason Codes (page 367) section for information on retrieving reason codes.

This actor-chain contains the following parameters:

364 9 Internal REST MVC Service Call Examples Parameter Description

processName Identifies if the process is a return or an exchange.

jsonReturnRequest Identifies the updated JSON-formatted return request where the item to be returned or exchanged in the shippingGroupList.itemList has been updated so that either the quantityToReturn property or the quantityToExchange property is greater than 0, and the returnReasoncode is set.

Add Items to Return Example

The following is a JSON-based example:

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" –d "{\"processName\":\"Return\",\"jsonReturnRequest\":{\"returnRequest\": {\"shippingGroupList\":[{\"itemList\":[{\"id\":\"xcr10101\",\"shippingGroupId\": \"xcsg20080\",\"quantityToReturn\":1,\"returnReason\":\"didNotLike\", \"quantityToExchange\":0},{\"id\":\"xcr10102\",\"shippingGroupId\":\"xcsg20080\", \"quantityToReturn\":1,\"returnReason\":\"defective\",\"quantityToExchange\": 0}]}]}}}" "http://localhost:8181/rest/model/atg/commerce/custsvc/returns/ CSRReturnsActor/selectItems"

The following is an XML-based example:

curl -L -v -b agent_cookies.txt -H "Content-Type: application/xml" –d "{"returnRequest":{"shippingGroupList": [{"itemList":[{"id":"xcr10101","shippingGroupId":"xcsg20080","quantityToReturn":1, "returnReason":"didNotLike","quantityToExchange":0},{"id":"xcr10102", "shippingGroupId":"xcsg20080","quantityToReturn":1,"returnReason":"defective", "quantityToExchange":0}]}]}}Return " "http://localhost:8181/rest/model/atg/commerce/custsvc/returns/ CSRReturnsActor/selectItems"

The server response may be similar to the following:

{ "returnRequest":{ "returnPaymentState":"Refund", "otherRefund":0, "requestId":null, "state":"incomplete", "processName":"Return", "actualShippingRefund":12.62, "replacementOrderId":null, "originatingOrderId":"xco30045", "exchangeProcess":false, "returnAdjustedOrderId":"o350068", "orderCurrencyCode":"USD", "refundMethodList":[ { "refundType":"creditCard",

9 Internal REST MVC Service Call Examples 365 "amount":113.62, "maximumRefundAmount":131.85 }, { "refundType":"storeCredit", "amount":0, "maximumRefundAmount":-1 } ], "returnItemCount":2, "actualTaxRefund":0, "returnItemList":[ { "quantityToExchange":0, "suggestedTaxRefundShare":0, "quantityReceived":0, "itemCurrencyCode":"USD", "returnItemId":"xcr10101", "actualTaxRefundShare":0, "refundAmount":50.52, "shippingGroupId":"xcsg20080", "quantityReturned":0, "quantityShipped":1, "quantityAvailable":1, "description":"Boyfriend Jeans", "quantityToReturn":1, "actualShippingRefundShare":6.31, "suggestedShippingRefundShare":6.31, "commerceItemId":"xci1000051", "catalogRefId":"xsku2519_2", "suggestedRefundAmount":50.52, "disposition":null, "returnReason":"didNotLike" }, { "quantityToExchange":0, "suggestedTaxRefundShare":0, "quantityReceived":0, "itemCurrencyCode":"USD", "returnItemId":"xcr10102", "actualTaxRefundShare":0, "refundAmount":51.44, "shippingGroupId":"xcsg20080", "quantityReturned":0, "quantityShipped":1, "quantityAvailable":1, "description":"Corduroy Cargo Pants", "quantityToReturn":1, "actualShippingRefundShare":6.31, "suggestedShippingRefundShare":6.31, "commerceItemId":"xci1000052", "catalogRefId":"xsku2512_2", "suggestedRefundAmount":51.44, "disposition":null, "returnReason":"defective" } ], "processImmediately":false, "rma":null, "returnFee":0,

366 9 Internal REST MVC Service Call Examples "orderId":"xco30045", "profile":{ "middleName":null, "lastName":"Smith", "id":"se-570085", "login":"[email protected]", "firstName":"Joe" } } }

Obtaining Return Reason Codes

The returnReasons actor-chain displays a list of all reason codes. Reason codes can be used in the selectItem actor-chain as outlined in Adding Items to a Return Request (page 364).

Parameters: None

Obtain Return Reason Codes Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8181/rest/model/atg/commerce/custsvc/returns/CSRReturnsActor/ returnReasons"

The server may return a response similar to the following:

{ "reasons": { "incorrectSize": "Incorrect Size", "incorrectColor": "Incorrect Color", "didNotMeetExpectations": "Did Not Meet Expectations", "didNotLike": "Did Not Like", "defective": "Defective", "incorrectItem": "Incorrect Item" } }

Confirming a Return Request

The confirmReturn actor-chain allows you to submit and process a return request, and displays confirmation detail if a submission is successful.

Parameters: None

Confirm Return Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8181/rest/model/atg/commerce/custsvc/returns/ReturnActor/ confirmReturn"

9 Internal REST MVC Service Call Examples 367 Displaying Return Request Confirmation Details

The confirmation actor-chain is an informational actor-chain used to display return details confirming that the return was successful. You can use this actor-chain to display return data as part of the confirmReturn actor- chain output. This actor-chain outputs the confirmation e-mail address. To display other information, such as the exchange order ID, you must customize this call to hold a reference to the return request. Refer to the ATG Platform API Reference for information on customizing this actor-chain.

Note that this actor is invoked by the confirmReturn actor-chain. Calling this actor directly will display no results.

Cancelling a Return Request

The cancelReturnRequest actor-chain cancels a return request at any point during the returns process.

Parameters: None

Cancel Return Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8181/rest/model/atg/commerce/custsvc/returns/CSRReturnsActor/ cancelReturnRequest"

Receiving Return Items

The receiveReturnItems actor-chain is used to get information about the items that have been selected to be returned and to process the items that have been returned as received. This actor-chain uses the following parameters:

Parameter Description

returnItemsRequest The received item’s return request, where the key is the return item ID and the value is the return request ID.

returnItemDispositions The item disposition information contained within the return request.

receiveItemQuantities The quantity of the return items received.

Receive Return Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" –d "{\"returnItemsRequests\":{\"atg-rest-class-type\":\"java.util.HashMap\", \"atg-rest-values\": {\"xc4400016\":\"xc4400011\"}}, \"returnItemDispositions\": {\"atg-rest-class-type\":\"java.util.HashMap\",\"atg-rest-values\": {\"xc4400016\":\"defective\"}}, \"receiveItemQuantities\": {\"atg-rest-class-type\":\"java.util.HashMap\",\"atg-rest-values\"

368 9 Internal REST MVC Service Call Examples :{\"xc4400016\":1}}}" "http://localhost:8181/rest/model/atg/commerce/custsvc/ returns/CSRReturnsActor/receiveReturnItems"

Retrieving Available Refund Methods

The modifiableRefundsMethodList actor-chain retrieves the sorted list of all credit and payment methods to which a refund can be applied, and the default values for the item to be returned. This does not display any extra store credit that might be displayed due to an exchange. Note that this call should be run after running the selectItems actor-chain.

Parameters: None

Refund Methods Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8181/rest/model/atg/commerce/custsvc/returns/CSRReturnsActor/ modifiableRefundsMethodList"

The server response may be similar to the following:

{ "modifiableRefundMethodList": [{ "refundType": "creditCard", "amount": 51.31 }] }

Applying Refunds

The applyRefunds actor-chain is used to apply refund type and value to the order. The server-side sortedRefundMethodList is updated by the UI with the values of the amounts passed in, in the order in which they are passed in. As such, the inputs for the applyRefund actor-chain should match the sortedRefundMethodList.

Parameter Description

returnMethodListSize The array size to retrieve from the JSP. The array size corresponds to the number of refund methods available.

Applying Refund Values Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" –d "{\"items\":{\"atg-rest-class-type\":\"java.util.ArrayList\", \"atg-rest-values\":[{\"atg-rest-class-type\": \"atg.commerce.csr.returns.RefundMethod\",\"amount\":\"46.31\"}, {\"atg-rest-class-type\":

9 Internal REST MVC Service Call Examples 369 \"atg.commerce.csr.returns.RefundMethod\",\"amount\":\"5.00\"}]}, \"returnMethodListSize\" : \"2\"}" "http://localhost:8180/rest/model/atg/ commerce/custsvc/returns/CSRReturnsActor/applyRefunds"

Displaying Return History

The returnHistory actor-chain displays the return history and contains the following parameters:

Parameter Description

orderId The ID of the order to be returned.

Customer Return History Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{\"orderId\":\"o2620001\"}" "http://localhost:8280/rest/model/atg/commerce/ custsvc/returns/CSRReturnsActor/returnHistory"

Identifying if the Order is Returnable

The isCurrentOrderReturnable actor chain looks at the current order to see if it is a returnable order. It provides a true or false server response.

Parameters: None

Is Order Returnable Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8180/rest/model/atg/commerce/custsvc/order/ CSRReturnsActor/isCurrentOrderReturnable"

Identifying if an Item is Returnable

The isItemReturnable actor-chain looks at an item within a current order to see if it is returnable. If the item is returnable, the returnable state is ITEM_RETURNABLE. If the returnable state contains anything else, the item is not returnable.

This actor-chain uses the following parameter:

Parameter Description

commerceItemId The ID of the item.

370 9 Internal REST MVC Service Call Examples Is Item Returnable Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" –d "{\"commerceItemId\":\"xci1000070\"}" "http://localhost:8181/rest/model/ atg/commerce/custsvc/order/CSRReturnsActor/isItemReturnable"

Identifying if the Order Contains an Active Return

The isReturnActive actor-chain determines if you are in the middle of a return process by looking at the current order to see if it is associated with an active return. It provides a true or false server response.

Parameters: None

Does Order Contain Active Return Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8180/rest/model/atg/commerce/custsvc/order/ CSRReturnsActor/isReturnActive"

Reviewing Details of Returned Items

The returns actor-chain provides details of returned items in the current order and contains the following parameters:

Parameter Description

orderId The ID of the order.

Does Order Contain Active Return Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" –d "{\"orderId\" : \"xco20040\"}""http://localhost:8180/rest/model/ atg/commerce/custsvc/returns/CSRReturnsActor/returns"

The server output may resemble the following:

{ "itemReturnSummary":{ "xci1000071":2, "xci1000070":1, "xci1000073":1, "xci1000072":1 }, "resultName":[

9 Internal REST MVC Service Call Examples 371 { "methods":[ { "methodType":"creditCard" } ], "requestId":"xc100005", "replacementOrderId":null, "items":[ { "requestId":"xc100005", "returnItemId":"xc100007" }, { "requestId":"xc100005", "returnItemId":"xc100008" }, { "requestId":"xc100005", "returnItemId":"xc100010" }, { "requestId":"xc100005", "returnItemId":"xc100009" } ], "rma":"xc100005", "createdDateTime":1340764006000, "orderId":"xco20040" } ] }

Displaying Non-Return Items

The nonReturnItemDetails actor-chain displays any non-returned items that have been affected by the return. When working on a current order, when a return is completed, the system displays the refund details with non-returnable items, as well as the refund types and any additional notes. The return is then submitted for completion. Note that this call will produce information only after selectItems is called, and if the items being returned affect non-returned items.

Parameters: None

Complete Return Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" –d "http://localhost:8180/rest/model/atg/commerce/custsvc/returns/ CSRReturnsActor/nonReturnItemDetails"

Updating a Credit Card for a Returns

The UpdateCreditCardActor is used to edit an existing credit card for a return. The path to this actor is: /atg/ commerce/order/purchase/UpdateCreditCardActor.

372 9 Internal REST MVC Service Call Examples This actor contains the updateCreditCardForReturns actor-chain. This actor-chain depends on the ReturnsActor createReturn actor-chain to obtain the correct information.

Parameter Description

creditCardType The type of credit card.

creditCardNumber The credit card number.

expirationMonth The month that the credit card expires.

expirationYear The year that the credit card expires.

firstName The first name on the credit card.

middleName The middle name or initial on the credit card.

lastName The last name on the credit card.

address1 The first address field on the credit card.

address2 The second address field on the credit card.

city The city on the credit card.

state The state on the credit card.

country The country on the credit card.

postalCode The postal code on the credit card.

phoneNumber A phone number associated with the credit card.

Update Credit Card Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{\"paymentGroupId\":\"pg3980014\",\"creditCardType\":\"visa\", \"creditCardNumber\": \"4111111111111111\",\"expirationMonth\":\"1\", \"expirationYear\": \"2017\"}" "http://localhost:8181/rest/model/atg/commerce/ custsvc/order/UpdateCreditCardActor/updateCreditCardForReturns"

Applying Appeasements to a Customer’s Order

An appeasement is a goodwill credit that can be applied to a fulfilled order where a customer has experienced difficulties but does not wish to return or exchange the items. When you issue an appeasement to a customer you can issue it against the cost of the items in the order, or against the cost of shipping associated with the order.

9 Internal REST MVC Service Call Examples 373 Initiating an Appeasement

The initiateAppeasement actor-chain initiates a return request specific to the order ID passed in and sets the Commerce Service Center environment settings, such as price lists. Note that this actor-chain calls the InitiateAppeasementFormHandler form handler.

Parameter Description

newOrderId The ID of the order to which the appeasement applies.

Initiate Appeasement Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"newOrderId \" : \"xco30076\"}" http://localhost:8080/rest/model/atg/commerce/custsvc/appeasement/ AppeasementActor/initiateAppeasement?atg-rest-output=json"

Applying an Appeasement

The applyAppeasementRefunds actor-chain is used to apply appeasement type and value to the order. Note that this actor-chain calls the AppeasementFormHandler form handler.

Parameter Description

appeasementType This is the type of appeasement.

appeasementAmount This is the value of the appeasement.

reasonCode This is the reason for the appeasement.

appeasementNotes This is any notes by the agent to support the appeasement.

Apply Appeasement Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"appeasementType\" : \"items\", \"appeasementAmount\" : \"5\", \"reasonCode \" : \"orderArrivedLate\", \"appeasementNotes\" : \"test notes value\", }" http:// localhost:8080/rest/model/atg/commerce/custsvc/appeasement/AppeasementActor/ applyAppeasementRefunds?atg-rest-output=json"

Validating an Appeasement

The ValidateAppeasementValues actor-chain is used to validate the refund total and the refund amounts allocated to different payment options. Note that this actor-chain calls the AppeasementFormHandler form handler.

374 9 Internal REST MVC Service Call Examples Parameters: None

Validate Appeasement Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" http:// localhost:8080/rest/model/atg/commerce/custsvc/appeasement/AppeasementActor/ validateAppeasementValues?atg-rest-output=json"

Submitting an Appeasement

The submitAppeasement actor-chain is used to submit the appeasement. Note that this actor-chain calls the AppeasementFormHandler form handler.

Parameters: None

Submit Appeasement Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" http:// localhost:8080/rest/model/atg/commerce/custsvc/appeasement/AppeasementActor/ submitAppeasement?atg-rest-output=json"

Cancelling an Appeasement

The cancelAppeasement actor-chain is used to cancel the appeasement. Note that this actor-chain calls the AppeasementFormHandler form handler.

Parameters: None

Cancel Appeasement Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" http:// localhost:8080/rest/model/atg/commerce/custsvc/appeasement/AppeasementActor/ cancelAppeasement?atg-rest-output=json"

Sending a Confirmation Message for an Appeasement

The sendConfirmationMessage actor-chain is used to send a confirmation message regarding the appeasement indicating whether it was successfully completed, or if it is awaiting approval. Note that this actor- chain calls the AppeasementFormHandler form handler.

Parameters: None

Send Confirmation Message Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" http:// localhost:8080/rest/model/atg/commerce/custsvc/appeasement/AppeasementActor/ sendConfirmationMessage?atg-rest-output=json"

9 Internal REST MVC Service Call Examples 375 Approving an Appeasement

The approveAppeasement actor-chain is used to approve an appeasement where the value of the appeasement exceeds the agent’s authorized limit. Note that this actor-chain calls the AppeasementApprovalFormHandler form handler.

Parameter Description

approvalId The ID of the approval request.

Approve Appeasement Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"approvalId \" : \"200001\"}" http://localhost:8080/rest/model/atg/commerce/custsvc/approvals/ appeasement/AppeasementApprovalsActor/approveAppeasement?atg-rest-output=json"

Rejecting an Appeasement

The RejectAppeasement actor-chain is used to reject an appeasement where the value of the appeasement exceeds the agent’s authorized limit. Note that this actor-chain calls the AppeasementApprovalFormHandler form handler.

Parameter Description

approvalId The ID of the approval request.

Initiate Appeasement Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"rejectApprovalId\" : \"200001\"}" http://localhost:8080/rest/model/atg/commerce/ custsvc/approvals/appeasement/AppeasementApprovalsActor/rejectAppeasement?atg-rest- output=json"

Modifying Refund Values

The ModifyRefundValuesActor is used to edit the values of refunded items. This actor is dependent on the createReturn and selectItems actor-chains, which should be called first. This actor produces no output, but can be customized as needed. The path to this actor is /atg/commerce/custsvc/returns. This actor contains the following actor-chains:

376 9 Internal REST MVC Service Call Examples Actor-Chain Description

modifyRefundValues This service allows you to edit the values of a refunded item within an array.

resetRefundValues This service call clears and resets all refund values. You can use this property to edit the default refund value for a returned item, shipping cost or other adjustment.

Modify a Refund Value

The modifyRefundValues actor-chain allows you to edit the values of a refund item.

Parameter Description

returnItemRefunds A map of the returned items and their corresopnding refunds.

shippingAdjustment Identifies shipping adjustments made for the refund.

otherAdjustment Identifies any other adjustments made for the refund.

Modify Refund Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" –d "{\"returnItemRefunds\":{\"atg-rest-class-type\":\"java.util.HashMap\", \"atg-rest-values\":{\"0\":\"-50.52\"}}, \"shippingAdjustment\" : \"-6.31\", \"otherAdjustment\" : \"0\" }" http://localhost:8180/rest/model/atg/commerce/ custsvc/returns/ModifyRefundValuesActor/modifyRefundValues"

Resetting a Refund Value

The resetRefundValues actor-chain allows you to clear and reset all of the values of a refund item to their default values.

Parameters: None

Reset Refund Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8180/rest/model/atg/commerce/custsvc/returns /ModifyRefundValuesActor/resetRefundValues"

9 Internal REST MVC Service Call Examples 377 Responding to Customers

There are two actors that allow an agent to use the tasks found on the Respond Tab in the UI. These tasks enable agents to respond to customers using e-mail.

The RespondEmailActor is used by agents to respond to e-mail from a customer. This actor is located at /atg/ svc/agent/ui/formhandlers/RespondEmailActor, and contains the following actor-chains:

Actor-Chain Description

sendEmail Allows an agent to send e-mail using the Send Email form on the Respond Tab.

addAttachment Allows an agent to add an attachment to the e-mail.

discardEmail Enables an agent to discard e-mail.

Sending a Customer E-Mail

The sendEmail actor-chain allows an agent to send an e-mail.

Parameter Description

to This required parameter identifies the customer e-mail address.

cc Identifies any addresses to be added to the cc field.

bcc Identifies any addresses to be added to the bcc field.

subject This required parameter provides the subject of the e-mail.

htmlBody Identifies the HTML body of the e-mail.

textBody Identifies the text body of the e-mail.

Send E-Mail Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"to\" : \"[email protected]\", \"subject\" : \"We got your request\", \"textBody\" : \"The text for the email\", \"htmlBody\" : \"The HTML body of the email\" }" "http://localhost:8180/rest/model/atg/svc/agent/ui/formhandlers /RespondEmailActor/sendEmail"

Adding an Attachment to an E-Mail

The addAttachment actor-chain allows an agent to add an attachment to an e-mail.

378 9 Internal REST MVC Service Call Examples Parameter Description

windowId The window ID of the attachment.

fileAsString The file conversion string.

contentType The content type of the file to attach.

fileSize The size of the file to attach.

fileName The name of the file to attach.

tempDir The location of the temporary directory where the attachment is stored.

attachmentDisplayName The name that will be displayed for the attachment.

Add Attachment Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"windowId\" : \"1\", \"fileAsString\" : \"LS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tL S0xMDU3MDczMDI5NjAxNTY2MTEzNjkyMDY4MTQNCkNvbnRlbnQtRGlzcG9zaXRpb246IGZvcm0tZGF0YTs gbmFtZT0iX2R5bmNoYXJzZXQiDQoNClVURi04DQotLSS0tLS0tLS0tLS0tMTA1NzA3MzAyOTYwMTU2NjEx MzY5MjA2ODE0LS0NCg==\", \"contentType\" : \"multipart/form-data; boundary=------105707302960156611369206814\", \"fileSize\" : \"40\", \"fileName\" : \"copyofinvoice\",\"tempDir\" : \"/home/order/invoice/\", "attachmentDisplayName" : \"Copy of Invoice\" }" "http://localhost:8180/rest/ model/atg/svc/agent/ui/formhandlers/RespondEmailActor/addAttachment"

Discarding an E-Mail

The discardAttachment actor-chain allows an agent to discard an e-mail.

Parameters: None

Discard E-Mail Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8180/rest/model/atg/svc/agent/ui/formhandlers/RespondEmailActor/ discardEmail"

Sending Customer E-Mail and Closing Ticket

The SendAndCloseTicketActor allows an agent to send an e-mail and close the corresponding ticket. It is located at /atg/svc/agent/ui/formhandlers/SendAndClosetTicketActor, and contains the sendAndCloseTicket actor-chains.

9 Internal REST MVC Service Call Examples 379 Parameter Description

to This required parameter identifies the customer e-mail address.

cc Identifies any addresses to be added to the cc field.

bcc Identifies any addresses to be added to the bcc field.

subject This required parameter provides the subject of the e-mail.

htmlBody Identifies the HTML body of the e-mail.

textBody Identifies the text body of the e-mail.

doWarnings If set to true, will present a warning to the agent when proceeding to the new site.

doTicketDispositionPrompt If set to true, will present ticket disposition prompts to the agent.

ticketDispositionOptions.dispositionOptionIf doTicketDispositionPrompt is enabled, this provides a ticket disposition option.

ticketDispositionOptions.reasonCodeIf doTicketDispositionPrompt is selected, this provides a ticket disposition reason code.

ticketDispositionOptions.ticketNoteIf doTicketDispositionPrompt is selected, provides a note associated with the ticket.

ticketDispositionOptions.publicNoteIf doTicketDispositionPrompt is selected, identifies if the ticket note is public.

Send E-Mail and Close Ticket Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"to\" : \"[email protected]\", \"subject\" : \"We're glad you're happy! \", \"textBody\" : \"Body of the email goes here\", \"htmlBody\" : \"Body of the HTML goes here\" }" "http://localhost:8180/rest/model/atg/svc/agent/ui/formhandlers/ SendAndCloseTicketActor/sendAndCloseTicket"

Working with the Commerce Service Center Environment

There are a number of actors that enable an agent to work with the Commerce Service Center UI and environment.

380 9 Internal REST MVC Service Call Examples Obtaining Global Session Information

The GlobalInfoActor contains the globalInfo actor-chain that obtains environment information including agent profile information, environment tools and current session values. The path for this actor is /atg/ commerce/custsvc/GlobalInfoActor.

Parameters: None.

Global Information Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8280/rest/model/atg/commerce/custsvc/environment/ GlobalInfoActor/globalInfo"

This REST service call returns a server response similar to the following, providing current session values:

{ "currentSite": { "id": "storeSiteUS", "name": "CRS Home" }, "currentSalePriceList": { "id": "salePrices", "displayName": "Sale Prices" }, "currentAgent": { "id": "Call Center Agent", "lastName": "Agent", "login": "Call Center Agent", "firstName": "Call Center" }, "currentLocale": { "language": "en", "displayName": "English (United States)", "country": "US" }, "currentCustomer": { "middleName": C, "id": "830013", "lastName": "Smith", "login": null, "firstName": "John" }, "currentCatalog": { "id": "homeStoreCatalog", "status": "other", "displayName": "Home Store Catalog" }, "currentCallState": { "startTime": null, "callActive": false }, "currentOrder": {"id": "o99660003", "currentPriceList": { "id": "listPrices", "displayName": "List Prices" },

9 Internal REST MVC Service Call Examples 381 "currentTicket": {"id": "5501"} }

Listing Available Sites

The SiteGroupsActor contains the getSites actor-chain that obtains a list of grouped and ungrouped sites. For information on site groups, refer to the Multisite Administration Guide. The path for this actor is /atg/ dynamo/droplet/multisite/SiteGroupsActor.

Parameters: None.

List Available Sites Example

curl -x 127.0.0.1:8888 -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http://localhost:8280/rest/model/atg/dynamo/droplet/multisite/ SiteGroupsActor/getSites"

This REST service call returns a server response similar to the following, providing a list of sites:

{ "groupedSites": [ { "id": "storeSiteUS", "name": "CRS Store" }, { "id": "homeSite", "name": "CRS Home" }, ], "ungroupedSites": [] }

Selecting a Site

The ChangeSiteActor contains the selectSite actor-chain that allows an agent to select a specific site. This actor can be configured to present ticket disposition warnings and prompts. The path for this actor is /atg/ svc/agent/environment/ChangeSiteActor.

Parameter Description

siteId The ID of the site to select.

doWarnings If set to true, will present a warning to the agent when proceeding to the new site.

doTicketDispositionPrompt If set to true, will present ticket disposition prompts to the agent.

382 9 Internal REST MVC Service Call Examples Parameter Description

dispositionOption If doTicketDispositionPrompt is selected, this provides a ticket disposition option.

reasonCode If doTicketDispositionPrompt is selected, this provides a ticket disposition reason code.

ticketNote Used to provide a note associated with the ticket.

publicNote Identifies if the ticket note is public.

Select Site Example

curl -x 127.0.0.1:8888 -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d "{ \"siteId\" : \"mobileStoreSiteUS\" }" "http://localhost:8280/rest/model/atg/svc/agent/environment/ChangeSiteActor/ selectSite"

A server response similar to the following may occur:

{ "allWarnings":["You are changing sites. Please ensure that all work is saved."}, "activeTIcketDisposition":false, "isDiscardable":true }

Viewing Messages

The MessageToolsActor contains the messages actor-chain that allows an agent to see messages. Once a message has been read from the message queue by the messages actor-chain, the message is removed from the message queue. The path for this actor is /atg/web/messaging/MessageToolsActor.

Parameters: None

Display Messages Example

curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" "http:// localhost:8280/rest/model/atg/web/messaging/MessageToolsActor/messages"

The server response may be something similar to the following:

{"messages":[ { "summary":"No default site has been configured.", "params":null, "type":"warning", "requestUrl":"/rest/model/atg/userprofiling/InternalProfileActor/

9 Internal REST MVC Service Call Examples 383 login-success?atg-rest-output=json&_requestid=63", "messageDetails":[], "timestamp":{"time":1364498690397}, "priority":-5, "messageGroup":null, "datetime":{"time":1364498690397}, "identifier":null }, { "summary":"First valid active site has been chosen.", "params":null, "type":"information", "requestUrl":"/rest/model/atg/userprofiling/InternalProfileActor/ login-success?atg-rest-output=json&_requestid=63", "messageDetails":[], "timestamp":{"time":1364498690486}, "priority":-10, "messageGroup":null, "datetime":{"time":1364498690486}, "identifier":null } ]}

Working with Ticket Disposition Warnings and Messages

Actions that agents perform in Commerce Service Center are linked to ticket actions. Whenever an agent performs an action, it is possible that there will be an environment change made. Whenever an environment changes, a warning or a ticket disposition message may occur.

By default, ticket dispositions may occur with the following REST MVC calls:

• Logging Out – The logout actor-chain

• Start New Call – The startNewCall actor-chain

• End Call – The endCall actor-chain

• Change Current Customer – The selectCustomer actor-chain

• Change Order - The changeOrder actor-chain

• Change Site – The selectSite actor-chain

When these warnings or messages occur, the data that can be returned is:

• Error – An error message is displayed

• Success – A success message is displayed

• Confirm – There are three confirmation chains that are presented:

• allWarnings – Identifies all warning messages

• isActiveTicketDisposition – Identifies if an open ticket must be processed

384 9 Internal REST MVC Service Call Examples • isDiscardable – Indicates that the current ticket can be discarded

The following is an example of what the confirm chain returns as data:

{ "allWarnings":["The current working order has items in it and has not been saved. If you continue, the order will be lost."}, "activeTIcketDisposition":false, "isDiscardable":true }

If you create an actor that requires a disposition message or error, it must provide information for the environmentChangeState service. The following example shows how the changeOrderActor includes the parameters referenced by the environmentChangeState service and defines the confirm actor-chain.

Note: The three environmentChangeState modifications are identified by comments in this example:

9 Internal REST MVC Service Call Examples 385

386 9 Internal REST MVC Service Call Examples DeactivateScheduleActor, Internal, 326 Index DefaultLoginPageActor, Internal, 251 DuplicateAndSubmitActor, Internal, 325 DuplicateOrderActor, Internal, 319 EndCallActor, Internal, 252 EnvironmentChangeActor, Internal, 338 GiftlistActor, External, 234 GiftlistLookupActor, External, 239 GiftlistLookupActor, Internal, 355 GiftlistSearchActor, External, 242 GiftListTableActor, Internal, 358 GlobalInfoActor, Internal, 381 IsScheduledOrderTemplateActor, Internal, 330 A LostPromotionsActor, External, 233 ActivateScheduleActor, 326 LostPromotionsActor, Internal, 348 ActiveCustomerProfileActor, 307 ManualAdjustmentsActor, Internal, 333 Actor MessageToolsActor, Internal, 383 ActivateScheduleActor, Internal, 326 ModifyOrderActor, Internal, 318 ActiveCustomerProfileActor, Internal, 307 ModifyRefundValuesActor, Internal, 376 AddressBookActor, Internal, 277 MoreCatalogsSearchActor, Internal, 337 AddStoreCreditActor, Internal, 348 OrderConfirmationActor, External, 224 AvailablePricedShippingMethodsActor, Internal, 296 OrderConfirmationActor, Internal, 317 AvailableShippingMethodsActor, External, 201 OrderLookupActor, External, 218 CancelOrderActor, External, 219 OrderNoteActor, Internal, 319 CancelOrderActor, Internal, 312 OrderSearchTreeQueryActor, Internal, 309 CartModifierActor, External, 192 OriginalOrderNoteActor, Internal, 320 CartModifierActor, Internal, 286 PaymentGroupActor, External, 203 ChangeCurrentCustomer, Internal, 276 PaymentGroupActor, Internal, 298 ChangeOrderActor, Internal, 311 PriceListSearchActor, Internal, 342 ChangePasswordActor, Internal, 250 PricingActor, External, 216 ChangeSiteActor, Internal, 382 PricingActor, Internal, 339 ClosenessQualifierActor, External, 224 ProductCatalogActor, External, 211 ClosenessQualifierActor, Internal, 346 ProductCatalogActor, Internal, 335 CommitOrderActor, External, 224 ProfileActor, External, 184 CommitOrderActor, Internal, 314 PromotionsSearchActor, Internal, 347 ConfirmLogoutActor, Internal, 250 PromotionWalletActor, Internal, 342 ConfirmOrderActor, External, 220 QuoteActor, Internal, 320 ConfirmOrderActor, Internal, 315 RespondEmailActor, Internal, 378 CouponActor, External, 220 RestoreDefaultAgentOptionsActor, Internal, 251 CouponActor, Internal, 302 ReturnsActor, External, 225 CreateCreditCardActor, External, 209 SaveOrderActor, External, 220 CreateCreditCardActor, Internal, 303 ScheduledOrderLookupActor, Internal, 330 CreateHardgoodShippingGroupActor, External, 201 ScheduledOrderTableActor, Internal, 332 CreateHardgoodShippingGroupActor, Internal, 296 SendAndCloseTicketActor, Internal, 379 CreditCardActor, Internal, 280 ServiceCustomerProfileActor, Internal, 307, 356 CSRCrossSellActor, Internal, 313 ServiceUIProfileActor, Internal, 270 CSRGiftlistActor, Internal, 349 SessionConfirmationActor, External, 184 CSRGiftlistSearchActor, Internal, 356 SessionConfirmationActor, Internal, 248 CSRReturnsActor, Internal, 362 ShippingGroupActor, External, 197 CSRScheduledOrderActor, Internal, 321 ShippingGroupActor, Internal, 292 CSRScheduledOrderConfirmationActor, Internal, 328 ShoppingCartActor, External, 189 CSRScheduledOrderInfoActor, Internal, 327 ShoppingCartActor, Internal, 283 CustomerProfileActor, Internal, 271 SiteGroupsActor, Internal, 382 CustomerSearchTreeQueryActor, Internal, 274

Index 387 StartNewCallActor, Internal, 251 ConfirmLogoutActor, 250 StateListActor, External, 245 ConfirmOrderActor StoreLocatorActor, External, 244 External, 220 StoreLocatorActor, Internal, 359 Internal, 315 SubmitModifiedOrderActor, Internal, 318 CouponActor TicketActor, Internal, 254 External, 220 TicketingActor, Internal, 253 Internal, 302 TicketLookupActor, Internal, 264 CreateCreditCardActor TicketSearchActor, Internal, 268 External, 209 TicketStatusDescriptionActor, Internal, 270 Internal, 303 UpdateCreditCardActor, External, 210, 232 CreateHardgoodShippingGroupActor UpdateCreditCardActor, Internal, 305, 372 External, 201 UpdateHardgoodShippingGroupActor, External, 202 Internal, 296 UpdateHardgoodShippingGroupActor, Internal, 297 CreditCardActor, 280 ViewAllPendingApprovalsActor, Internal, 359 CSRCrossSellActor, 313 ViewOrderActor, Internal, 311 CSRGiftlistActor, 349 actor-chains, 139 CSRGiftlistSearchActor, 356 registering, 137 CSRReturnsActor, 362 actors, 139 CSRScheduledOrderActor, 321 execution order, 162 CSRScheduledOrderConfirmationActor, 328 passing params, 151 CSRScheduledOrderInfoActor, 327 types, 140 cURL, 58 AddressBookActor, 277 command components, 60 AddStoreCreditActor, 348 CustomerProfileActor, 271 Apache Axis, 35 CustomerSearchTreeQueryActor, 274 ATGWS.dll, 45 installing, 46 D AvailablePricedShippingMethodsActor DeactivateScheduleActor, 326 Internal, 296 DefaultLoginPageActor, 251 AvailableShippingMethodsActor DuplicateAndSubmitActor , 325 External, 201 DuplicateOrderActor, 319 dynSessConf, 138, 149, 155 C caching with REST JAX-RS, 72 E configuring client, 107 EndCallActor, 252 configuring server, 107 endpoints in REST JAX-RS, 73 responses, 71 and media types, 81 CancelOrderActor annotation, 81 External, 219 associating schema, 99 Internal, 312 documenting with Swagger, 114 CartModifierActor entry path, 74 External, 192 example of, 113 Internal, 286 exceptions, 94 ChangeCurrentCustomerActor, 276 including sub-resources, 77 ChangeOrderActor, 311 invoking methods, 91 ChangePasswordActor, 250 links, 87 ChangeSiteActor, 382 locales, 108 ClosenessQualifierActor media types, 75 External, 224 metadata, 80 Internal, 346 responding to a representation, 75 CommitOrderActor security, 104 External, 224 transactional, 92 Internal, 314 versioning, 75

388 Index wrapping, 70 media type in REST JAX-RS, 80 EnvironmentChangeActor, 338 output, 58 Etags in REST JAX-RS, 71, 108 L F links in REST JAX-RS, 84 filters building, 75 associating with an endpoint, 99 HATEOAS, 88 bean classes, in REST MVC, 169 relation, 85 defining in REST MVC, 170 self, 85 modifying in REST MVC, 177 self, customizing, 87 output in REST JAX-RS, 98 LinkUtils in REST JAX-RS, 75 repository items, in REST MVC, 169 generating links, 90 requests in REST JAX-RS, 70 locking in REST JAX-RS, 72, 93 form handlers with REST JAX-RS, 109 LostPromotionsActor External, 233 G Internal, 348 GiftlistActor, 234 GiftlistLookupActor M External, 239 ManualAdjustmentsActor, 333 Internal, 355 media types in REST JAX-RS, 80, 82 GiftlistSearchActor, 242 message sink, 18 GiftListTableActor, 358 MessageToolsActor, 383 GlobalInfoActor, 381 methods builder in REST JAX-RS, 82 H executing with REST MVC, 145 HAL media type in REST JAX-RS, 80 overloaded, specifying in REST MVC, 148 HATEOAS in REST JAX-RS, 71, 75, 88 ModelMap, 139, 141 link relations, 85 and filtering, 169 HTTP and hierarchy, 144, 167 and endpoints in REST JAX-RS, 73 and output elements, 160 requests, 56, 61 ModifyOrderActor, 318 requests and REST JAX-RS, 68 ModifyRefundValuesActor, 376 security in REST JAX-RS, 70 MoreCatalogsSearchActor, 337 specifying methods in REST JAX-RS, 70 status codes, 57 N Hypermedia as the Engine of Application State (see naming standards in REST JAX-RS, 73, 82 HATEOAS) O I OAUTH in REST JAX-RS, 69 IsScheduledOrderTemplateActor, 330 OrderConfirmationActor External, 224 J Internal, 317 JAX-RPC, 4, 9, 11 OrderLookupActor, 218 and WSDL, 8 OrderNoteActor, 319 JAX-RS, 67 OrderSearchTreeQueryActor, 309 annotation in REST JAX-RS, 73 OriginalOrderNoteActor, 320 Jersey, 70 and REST JAX-RS, 68 P JMS Messages, 16 Patch Bay, 15, 17 Patch Bay, 16 PaymentGroupActor type, 16 External, 203 JSON Internal, 298

Index 389 PriceListSearchActor, 342 Etags, 71 PricingActor filters, 99 External, 216 framework, 67 Internal, 339 HAL media type, 80 ProductCatalogActor HATEOAS, 71 External, 211 HTTP security, 70 Internal, 335 media types, 80 ProfileActor, 184 metadata, 80 PromotionsSearchActor, 347 naming standards, 73 PromotionWalletActor, 342 OAUTH, 69 pushSite, 184 query parameters, 89 resources, 73 Q responses, 71 RestResourceRegistry, 68 query parameters in REST JAX-RS, 88, 89, 90, 103 security, 104 QuoteActor, 320 statelessness, 110 sub-resources, 76 R tunneling, 70 repository URIs, 77 data binding Web Services, 21 validating, 121 delete item, 34 versions, 70 filtering in REST MVC, 176 web.xml, 68 items from XML, 29 with REST MVC, 110 match properties, 33 REST MVC modify item, 32 cURL example, 59 resources in REST JAX-RS, 73 examples, external user, 183 and Etags, 108 examples, internal users, 247 collection, 75, 88, 102 executing methods, 145 embedded, 76 filtering, 169 global, 79 framework, 56, 139 metadata, 80 installing, 137 registering Nucleus, 79 registering services, 137 registry, 77, 79 schema, 141 representation, 75 security, 178 representing, 82 URLs, 141 resolving Non-Nucleus, 80 URLS, error and success, 154 root, 81 with REST JAX-RS, 110 sub-resources, 76 RestoreDefaultAgentOptionsActor, 251 validating, 74, 95 RestResourceRegistry in REST JAX-RS, 68 version, 108 RestUtils in REST JAX-RS, 74 RespondEmailActor, 378 and returning sub-resources, 76 responses in REST JAX-RS, 71 ReturnsActor, 225 codes, 75 REST, 55 S cURL examples, 58 HTTP status codes, 57 SaveOrderActor, 220 output, 58 Scenario Actions, 16 URLs, 56 Scenario Manager, 18 URLs, adding parameters, 62 ScheduledOrderLookupActor, 330 REST JAX-RS, 68 ScheduledOrderTableActor, 332 and form handlers, 109 security and HTTP requests, 68 HTTP in REST JAX-RS, 70 endpoints, 73 REST JAX-RS endpoints, 104 entry point, 74 REST JAX-RS server, 103

390 Index REST MVC, 178 External, 202 Web Services, 12 Internal, 297 SendAndCloseTicketActor, 379 URIs in REST JAX-RS, 77 Service Endpoint Interface (SEI), 8 adding resources, 76 mapping to WSDL, 11 embedding, 76 ServiceCustomerProfileActor, 307, 356 naming, 85 ServiceUIProfileActor, 270 security, 70 servlet beans versions, 70 filtering in REST MVC, 171 URLs, 56 filtering individual properties in REST JAX-RS, 103 adding REST parameters, 62 retrieving in REST MVC, 152 and WSDL, 9 state builder method in REST JAX-RS, 82 control parameters, 61 validating in REST JAX-RS, 95, 97, 121 URLs in REST MVC, 141 session confirmation number, 138, 184, 248 forwarding, 154 disabing in Form actors, 155 success and error, 154 disabling in Component actor, 149 SessionConfirmationActor V External, 184 validating in REST JAX-RS Internal, 248 requests, 72 ShippingGroupActor simple properties, 126 External, 197 validators, 121 Internal, 292 ViewAllPendingApprovalsActor, 359 ShoppingCartActor ViewOrderActor, 311 External, 189 Internal, 283 site context, external, 184 W SiteGroupsActor, 382 Web Services SOAP, 4, 8, 9 .Net, 44, 47 and WSDL, 8 abstract data types, 5 StartNewCallActor, 251 cookies, 5, 37 statelessness in REST JAX-RS, 110 DAS, 2 StateListActor, 245 DCS, 2 StoreLocatorActor deploying, 13 External, 244 deserializer in .Net, 45, 49 Internal, 359 deserializer in Java, 36, 42 sub-resources in REST JAX-RS, 76 DPS, 2 locator methods, 76 dynamic, 39, 41 SubmitModifiedOrderActor, 318 exposing methods, 8 Swagger, 114 Java client, 35 JMS Messages, 15 T JMS Type, 16 naming conflict, 5, 7 TicketActor, 254 NucleusSecurityManager, 12 TicketingActor, 253 NucleusSecurityRepository, 13 TicketLookupActor, 264 primitive data types, 5, 8 TicketSearchActor, 268 Registry, 8, 11, 14 TicketStatusDescriptionActor, 270 repository, for, 18 tunneling in REST JAX-RS, 70 rollback a call, 35 scenario actions, 16 U security, 4, 12 UpdateCreditCardActor serializer in .Net, 45, 49 External, 210, 232 serializer in Java, 36, 42 Internal, 305, 372 session sharing, 36, 45 UpdateHardgoodShippingGroupActor static, 39, 39

Index 391 wizard, 5 WSDL, 8, 10 XML file, 9 Web Services Description Language (WSDL) (see Also Web Services) mapping to SEI, 11 web.xml in REST JAX-RS, 68 WebServicesGenerator, 6 X XML data binding, 21 data binding in REST MVC, 168 delete repository item, 34 generating schemas, 43 mapping in Web Services, 22 mapping Web Services DTD, 23 output, REST, 58 payloadSchema in REST JAX-RS, 125 repository items, 29 schema mapping, 42 schemas, 27 validating, 32

392 Index