Transcript
  • DEVELOPMENT STANDARDS 2.5

    Oracle Workflow 2.5

    Oracle Workflow

  • IntroductionWFDEVSTD.doc(v25)

    2

    Development Standards - Oracle Workflow 2.5

    Copyright 2000, Oracle Corporation. All rights reserved.

    Author: Tim Roveda

    The Programs (which include both the software and documentation) contain proprietary information of OracleCorporation; they are provided under a license agreement containing restrictions on use and disclosure and are alsoprotected by copyright, patent and other intellectual property law. Reverse engineering of the Programs is prohibited.

    Program Documentation is licensed for use solely to support the deployment of the Programs and not for any otherpurpose.

    The information contained in this document is subject to change without notice. If you find any problems in thedocumentation, please report them to us in writing. Oracle Corporation does not warrant that this document is errorfree. Except as may be expressly permitted in your license agreement for these Programs, no part of these Programsmay be reproduced or transmitted in any form or by any means, electronic or mechanical, for any purpose, without theexpress written permission of Oracle Corporation.

    If the Programs are delivered to the US Government or anyone licensing or using the Programs on behalf of the USGovernment, the following notice is applicable:

    RESTRICTED RIGHTS LEGEND

    Programs delivered subject to the DOD FAR Supplement are 'commercial computer software' and use, duplication anddisclosure of the Programs including documentation, shall be subject to the licensing restrictions set forth in theapplicable Oracle license agreement. Otherwise, Programs delivered subject to the Federal Acquisition Regulations are'restricted computer software' and use, duplication and disclosure of the Programs shall be subject to the restrictions inFAR 52.227-19, Commercial Computer Software - Restricted Rights (June, 1987). Oracle Corporation, 500 OracleParkway, Redwood City, CA 94065.

    The Programs are not intended for use in any nuclear, aviation, mass transit, medical, or other inherently dangerousapplications. It shall be licensee's responsibility to take all appropriate fail-safe, back up, redundancy and othermeasures to ensure the safe use of such applications if the Programs are used for such purposes, and Oracle disclaimsliability for any damages caused by such use of the Programs.

    Oracle is a registered trademark and ConText, Enabling the Information Age, Oracle7, Oracle8, Oracle8 i, Oracle Access,Oracle Application Object Library, Oracle Financials, Oracle Discoverer, Oracle Web Customers, Oracle WebEmployees, Oracle Workflow, Oracle Work in Process, PL/SQL, Pro*C, SmartClient, SQL*, SQL*Forms, SQL*Loader,SQL*Menu, SQL*Net, SQL*Plus, and SQL*Report are trademarks or registered trademarks of Oracle Corporation.Other names may be trademarks of their respective owners.

  • IntroductionWFDEVSTD.doc(v25)

    3

    Contents

    Introduction .................................................................................................................................................................7Objective.............................................................................................................................................................................7Oracle Workflow and Applications.....................................................................................................................................7

    Workflow Basics ..........................................................................................................................................................8Workflow Engine................................................................................................................................................................8Background Engine.............................................................................................................................................................8Synchronous vs. Asynchronous flows.................................................................................................................................8The Standard Item type .......................................................................................................................................................9

    Getting Started ..........................................................................................................................................................10Should I use Workflow?............................................................................................................................................................10Do I model a Synchronous Workflow?.....................................................................................................................................10Starting a Workflow..................................................................................................................................................................10Getting started with Oracle Workflow Builder .........................................................................................................................11Creating a new process or a new item? .....................................................................................................................................11Calling a non-Workflow API ....................................................................................................................................................12

    Coding Techniques ....................................................................................................................................................13Parallel Threads ........................................................................................................................................................................13

    What are parallel threads?.................................................................................................................................................13Working with Parallel threads...........................................................................................................................................13Parallel vs. Sequential .......................................................................................................................................................13Hanging Activities ............................................................................................................................................................14Racing Parallel Threads. ...................................................................................................................................................15Forced Synchronous Processes .........................................................................................................................................15

    External Function Calls.............................................................................................................................................................16Blocks and Waits ......................................................................................................................................................................16

    Coupling with non-Oracle Workflow systems. ................................................................................................................16Timeouts ...................................................................................................................................................................................17

    How it works.....................................................................................................................................................................17Timeouts and Notifications ...................................................................................................................................................18Timeouts and Functions ........................................................................................................................................................18

    How they work..................................................................................................................................................................18Common uses....................................................................................................................................................................18

    Timeouts and Processes ........................................................................................................................................................19Caution..............................................................................................................................................................................19

    Dynamic timeouts and dynamic timeout constructs..............................................................................................................19Timeouts on business days only............................................................................................................................................20

    Subprocesses .............................................................................................................................................................................20Limitations ........................................................................................................................................................................21

    Customizing Hooks...................................................................................................................................................................22Embedding null processes.................................................................................................................................................22Using Item Attributes........................................................................................................................................................22

    Loop Structures .........................................................................................................................................................................22Processing within loops.........................................................................................................................................................22

    On-revisit Reset option .....................................................................................................................................................23

  • IntroductionWFDEVSTD.doc(v25)

    4

    On-revisit Loop option......................................................................................................................................................23On-revisit Ignore option and OR-joins..............................................................................................................................23Pivot Activity ....................................................................................................................................................................24Common problems............................................................................................................................................................24Notifications in loops ........................................................................................................................................................24

    Exception Handling...................................................................................................................................................................24The Default branch - Catching unexpected outcomes.......................................................................................................24The Default vs. Any transition. .........................................................................................................................................24Using notifications ............................................................................................................................................................24Workflow Error Handling .................................................................................................................................................25

    Master Detail Flows ..................................................................................................................................................................26Starting from the same process. ........................................................................................................................................26Starting the children from a separate process....................................................................................................................27

    Selector/callback function.........................................................................................................................................................28What is it? .........................................................................................................................................................................28When to use ......................................................................................................................................................................28Restrictions .......................................................................................................................................................................28

    Notifications..............................................................................................................................................................................29FYI Notifications ..............................................................................................................................................................29Expand roles .....................................................................................................................................................................29Response Notifications .....................................................................................................................................................29PL/SQL Documents ..........................................................................................................................................................29PLSQLCLOB Documents (Available in 2.6/11.5.1).........................................................................................................30Notifications and URL or Document type attributes.........................................................................................................31In-line vs. Attachment.......................................................................................................................................................32Notifications with a Single URL Response Attribute........................................................................................................33

    Post-Notification Function ........................................................................................................................................................33Example Uses....................................................................................................................................................................33How it works.....................................................................................................................................................................33Post-notification function vs. Notification followed by a function. ..................................................................................34

    Voting .......................................................................................................................................................................................34What is it? .........................................................................................................................................................................34

    Lookups ....................................................................................................................................................................................36Attributes...................................................................................................................................................................................36

    Item vs. Activity attributes................................................................................................................................................36Item Attributes ..................................................................................................................................................................36Changing Activity attributes at runtime ............................................................................................................................36

    Start Activities...........................................................................................................................................................................37When are start activities really Start Activities? ...............................................................................................................37Multiple starts for a process ..............................................................................................................................................37Starting a process half way through ..................................................................................................................................37

    End Activities............................................................................................................................................................................37When are end activities really End activities?...................................................................................................................37

    Stuck processes .........................................................................................................................................................................38Background engine ...................................................................................................................................................................38

    What is it? .........................................................................................................................................................................38Deferring to the background .............................................................................................................................................38Parameters.........................................................................................................................................................................39How often should it run?...................................................................................................................................................39

    Commits....................................................................................................................................................................................39No commits in Workflow..................................................................................................................................................39Can you commit in a workflow process? ..........................................................................................................................39Autonomous Commit........................................................................................................................................................40

    How to write re-usable activities...............................................................................................................................................41How to write re-usable processes..............................................................................................................................................41

    APPENDIX A: Naming Standards ..........................................................................................................................44General Naming Standards........................................................................................................................................................44

    General Standards for all Objects .........................................................................................................................................44Internal Names ..................................................................................................................................................................44

  • IntroductionWFDEVSTD.doc(v25)

    5

    Display Names ..................................................................................................................................................................44Object Naming Standards .........................................................................................................................................................44

    Item Types ............................................................................................................................................................................44Internal Name....................................................................................................................................................................44Display Name....................................................................................................................................................................45

    Item Attributes ......................................................................................................................................................................45Internal Name....................................................................................................................................................................45Display name.....................................................................................................................................................................45

    Lookup types.........................................................................................................................................................................45Internal Name....................................................................................................................................................................45Display name.....................................................................................................................................................................46

    Lookup Codes .......................................................................................................................................................................46Internal Name....................................................................................................................................................................46Display name.....................................................................................................................................................................46

    Messages ...............................................................................................................................................................................46Internal Name....................................................................................................................................................................46Display name.....................................................................................................................................................................46

    Message Attributes................................................................................................................................................................47Internal Name....................................................................................................................................................................47Display name.....................................................................................................................................................................47Description........................................................................................................................................................................47

    Activities ...............................................................................................................................................................................47Internal Name....................................................................................................................................................................47Display name.....................................................................................................................................................................47Label .................................................................................................................................................................................47

    Activity Attributes.................................................................................................................................................................48Internal Name....................................................................................................................................................................48Display name.....................................................................................................................................................................48

    APPENDIX B: Diagramming Standards ................................................................................................................49Keep to a grid structure .....................................................................................................................................................49Use the appropriate icons ..................................................................................................................................................49Position your icons logically.............................................................................................................................................50Avoid excessive scrolling .................................................................................................................................................50Simplify your Diagram......................................................................................................................................................50

    APPENDIX C: Notification Standards. ..................................................................................................................51Subject Line ..........................................................................................................................................................................51Message Body.......................................................................................................................................................................51

    Send Section of Message ..................................................................................................................................................51Layout ...............................................................................................................................................................................51Response Section of Message ...........................................................................................................................................52

    APPENDIX D: Standards Checklist........................................................................................................................53APPENDIX E: Glossary ...........................................................................................................................................54

    Database Process /Session.....................................................................................................................................................54Workflow Process .................................................................................................................................................................54Activity..................................................................................................................................................................................54Item type ...............................................................................................................................................................................54Item Attribute........................................................................................................................................................................54Item .......................................................................................................................................................................................54Worklist ................................................................................................................................................................................54Subprocess ............................................................................................................................................................................54Thread ...................................................................................................................................................................................54

    APPENDIX F: API STANDARDS ..........................................................................................................................55

  • IntroductionWFDEVSTD.doc(v25)

    6

  • IntroductionWFDEVSTD.doc(v25)

    7

    Introduction

    ObjectiveThis document shows how to use Oracle Workflow to create effective results for your workflowneeds. It explains principles essential for understanding and developing with Oracle Workflow aswell as providing a framework for development standards. For specific details of the componentsof Oracle Workflow, please refer to the Oracle Workflow Guide.

    Oracle Workflow and ApplicationsMany application product groups have been using Oracle Workflow with ever greater popularity.This rapid proliferation in use is principally due to its ability to control the execution of atransaction from start to finish and still provide an easy interface for customization.

    With its increase in use we have found a strong need to introduce development standards. Therehas been an equally strong need to share more practical information regarding development whichis not found elsewhere. This document aims at filling this need and providing the requiredguidance.

  • Workflow BasicsWFDEVSTD.doc(v25)

    8

    Workflow Basics

    Workflow EngineThe Engine is only an engine as a metaphor. In reality it is a PL/SQL package procedure that mustbe called by every workflow instance. Each workflow is a series of activities strung together witheach activitys outcome determining the next activity to perform. It is the Workflow Engine thatexamines the outcomes and controls the activities to execute. Therefore, its primary responsibilityis to control the workflow process from start to finish, governing when to branch or rendezvous theprocess flow.

    Background EngineAnother metaphor, the Background Engine is a PL/SQL package that checks the workflow tablesfor any activities that require processing such as timed-out or deferred activities. It is called background because it is set up to execute at regular intervals by a system admin job (e.g. batch,concurrent program or cron jobs) rather than in-line from the application. On detecting an activityto process, the Background Engine invokes the correct Engine API to complete the activity. Youmay have more than one Background Engine running at any one time, in which case the work loadwill be shared between them.

    NOTE: As a developer, you should not be writing logic to check that a background engine isset up or running effectively. It is a requirement for Oracle Workflow installs to set up abackground engine and part of the DBA responsibility to check it is running effectively. If youhave a significant dependency on it, you may want to recommend in your documentation thata background engine is specifically set up for your item type. Otherwise you can safelyassume that it is working and do not need to program logic around it.

    Synchronous vs. Asynchronous flowsThe concepts of synchronous and asynchronous flows are essential to designing effective workflowsolutions. A synchronous flow is one that goes uninterrupted from start to finish. With such a flow,you can immediately check for your results written to Item Attributes or directly to the database.This solution is only effective if the workflow does not take long to execute; otherwise the userwill be left waiting with an application that appears to hang. In this case you should change it to anasynchronous flow. A good example is Oracle Applications FlexBuilder code in which a series offunctions are called to construct an intelligent/concatenated key.

    CreateProcess() -- register a new instanceSetIemAttr() -- set as many item attributes as necessaryStartProcess() -- execute the process -- workflow is complete: control is returnedGetItemAttr() - get the result as an Item Attributes

    Code Example of a Synchronous flow where the result is retrieved from an item attribute

    An asynchronous flow is one in which the Engine cannot go to completion immediately because itcontains activities that interrupt the flow. Rather than waiting indefinitely, the engine sets the audittables appropriately and returns control to the calling module that initiated the workflow (usingStartProcess or CompleteProcess). The workflow is left in an unfinished state until it is startedagain, usually by the notification system or the Background Engine. Examples of activities thatforce an asynchronous flow are deferred activities, notifications with responses, blocking and waitactivities.

    Deferred activities

    This is the most effective way to improve the users response time. At design time you can setan activitys cost above the default threshold cost (a PL/SQL package variable set to 50 bydefault) for all activities you dont want the user to wait for. At runtime the engine defers anythread to the background as soon as it comes across such an activity. Control is immediately

  • Workflow BasicsWFDEVSTD.doc(v25)

    9

    returned to the user who remains unaware that processing is still taking place rendering afaster execution time. It is the background engine which identifies the process as deferred andcontinues its execution.

    Notifications

    A notification that requires a response will stop the synchronous flow as it waits for a user toinput a reply. While it is waiting, the activity status is set to NOTIFIED. The notificationsystem, on receiving the response, starts the process through the callback function,WF_ENGINE.CB.

    Blocking activities

    You can explicitly force the flow to halt by using a block activity. Internally this is similar to anotification in that the activity status is set to NOTIFIED. This is commonly used tosynchronize with an external event, so that the next activities are assured that an event hasoccurred. It is up to the external event to restart the activity by calling the Workflow EngineCompleteActivity API.

    Wait activities

    This is an activity that is deferred until a relative or absolute time. A Background Enginedetects when it is valid to restart.

    The Standard Item typeOracle Workflow comes with an item type called Standard (wfstd.wft). Though this is notnecessary for developing a workflow process it provides useful activities that will greatly enhancethe ease of programming. Consequently we assume you will be using it much like a library ofcommon routines so will refer to its activities and components throughout this document.

    Use the QuickStart Wizard to automatically copy the Standard item type into your new item type. Alternatively, make a copy of the Standard item type in each of your workflow processes (you willhave to open the file, wfstd.wft, and drag the item type into your data store).

  • Getting StartedWFDEVSTD.doc(v25)

    10

    Getting StartedThis section reviews some questions you should confront before starting a workflow project orduring its early design phase.

    Should I use Workflow?

    Workflow controls the execution of a predefined series of activities. The need for sophisticatedbranching logic, modeling constructs and the ability to include human responses throughnotifications makes it a suitable choice for modeling your business process.

    Workflow gives extra flexibility to your business process but it does add the extra level ofcomplexity by introducing another layer of software (even though Oracle Workflow is verylightweight). If you need to model human responses such as notifications then Workflow isdefinitely for you. If you want to push a transaction from beginning to end and execute complexbusiness logic, then again Workflow is a good fit. So when making your decision you mustdetermine if what you are modeling is suited to Workflow and whether the benefits justify the costsof another software layer.

    Do I model a Synchronous Workflow?

    If you design a synchronous workflow (one which goes from start to finish as the user is waiting)and rely on it for an immediate result, you must guarantee that future enhancements orcustomization will not introduce any activities that force it to become asynchronous. Without suchactivities, a synchronous workflow is a series of function activities and as such can be modeled asan API. Therefore you should question if an API with customizable hooks is not an easier andsafer way to model this. The only advantage of modeling a synchronous process in workflow is thegraphic front end. Will the user make use of this? How much customization will the end user makeand can you ensure it remains synchronous? Oracle Applications FlexBuilder is a good exampleof a synchronous process that relies on customization and consequently needs the very flexiblefront end provided by Oracle Workflow.

    Starting a Workflow

    Once your workflow process has been saved to the database, you start the process by calling theWorkflow Engine APIs. These are well documented in the Oracle Workflow Guide and are listedbelow. Where you put these is up to you (ex: Forms on-insert/update/delete triggers, data loaderroutines etc) but generally you will have to add them to a calling application. CreateProcess: this is a mandatory procedure required to set up the item information in the

    workflow tables.

    SetItemAttribute: this is optional and may be called multiple times to define any itemattributes which will be referenced in the process flow much like setting up global variable ina programming language.

    TECHNICAL NOTE: the SetItemAttribute APIs are not overloaded, meaning you must use aparticular API for each data type you want to set. If they were overloaded, a programmer maymistakenly define an attribute as the wrong data type. Then, when retrieving a value, no errorwould be raised but a null value will be returned (when setting it, the value will be stored inthe wrong data type so it will never be retrieved). This type of error is very difficult to debug.By not overloading the functions we reduce this type of programming problems.

    SetItemUserKey: though optional, we request you always use this to set a user-friendly itemkey. This gets displayed in the monitor and can be used by the user to identify the process.

    SetItemOwner: also optional, but again we request you always use this to define the owner of

  • Getting StartedWFDEVSTD.doc(v25)

    11

    the process. Only when it is defined does the process become visible in the find-processscreen. If instead it is not set then only users in the WF_ADMIN_ROLE can query the processin the find-process web page. That users cannot find a process is a common problem andeasily resolved by setting the owner. Note that the owner can be a role of multiple users.

    SetItemParent: only required if you are defining this process as a child to a parent process.

    StartProcess: is mandatory. It is responsible for starting the process.

    When integrating a workflow into your application, make sure you create a separate package tocreate and start the item. This will make your code more modular and provide excellentdocumentation regarding what is required to initiate your workflow item.

    When integrating with Oracle Applications, look up the owners role using the directory serviceAPIs before calling SetItemOwner.

    wf_directory.GetRoleName(Orig_System, User_ID, role_name, role_displayname);

    /****Orig_System is a constant that depends on the sourceof the role information as defined in WF_ROLES view:

    For HR people/users, Orig_System = PERFor RA Customer Contacts, Orig_System = CUST_CONTFor HR Positions, Orig_System = POSFor Engineering ECN Approval Lists, Orig_System = ENG_LISTUser_ID is the corresponding table ID value.Role_name and role_display_name are OUT parameters

    Please use the wf_directory.GetRoleName API to get the role namerather than retrieving the information directly from any applicationtables. All AOL usernames are replicated in the directory serviceviews however to protect yourself from any changes in the directoryservices implementation you should use the workflow API.****/-- go ahead and call engine API to set the owner.wf_engine.SetItemOwner(ItemType, ItemKey, role_name);

    Code example to set item owner in a workflow for Oracle Application

    Getting started with Oracle Workflow Builder

    When you first open the Builder you get a blank hierarchy editor. If you are not editing an existingfile launch the QuickStart Wizard to automatically set up the editor with a copy of the Standarditem type.

    Creating a new process or a new item?

    If you have two different business flows for the same business item then you could set up twodifferent workflows (two Oracle Workflow item types) or have one workflow with two processes(one item type with two processes). Which is best? This is an implementation decision commonly,if your business items share the same item attributes and activities then they should be part of thesame workflow item type.

  • Getting StartedWFDEVSTD.doc(v25)

    12

    Calling a non-Workflow API

    A benefit of Oracle Workflow is that you can use existing APIs to create the function activities foryour process. However these usually do not have the 5 necessary arguments to integrate directlywith workflow. Instead you must create a simple wrapper API which accepts the Oracle Workflowarguments and then calls your existing API. It is in the wrapper that you set up all the necessaryarguments before calling your API. You can either compute these directly or retrieve them fromitem attributes using the Workflow Engine APIs, GetItemAttribute.

  • Coding TechniquesWFDEVSTD.doc(v25)

    13

    Coding Techniques

    Parallel Threads

    What are parallel threads?When a node in a process leads to more than one node for the same outcome, then the process flowis split and we have parallel threads to execute.

    Internally, the engine loops through each node to process, executing each thread until it cantproceed any further. Only then does it move on to the next thread. The order in which it processeseach thread is totally arbitrary.

    Working with Parallel threadsWhen working with parallel threads you must be careful with any thread that can execute an ENDactivity. When an END is executed, the engine returns Completion status and disregards any otherthreads for that process. Therefore, if you have multiple threads in parallel and one includes anEND, the others are effectively killed when the END is executed. This may not be what you wantin which case your workflow will behave very differently to what you intended. The only way toguarantee that all parallel threads complete are by forcing them to rendezvous with an ANDfunction.

    Note however, that this can be used to your advantage if you purposely want to pit parallel threadsagainst each other so as to create a race for the end result (see Racing Parallel threads).

    Parallel vs. Sequential

    Diagram 1a: Shows a simple process flow executed in sequence

    Consider Diagram 1a. Assume Setup transportation and Make Pizza are labor intensive jobsrequiring a lot of time to execute. To improve efficiency, you will want to execute them off-line bydeferring them to the background engine. If they have no dependencies on each other such thattheir ordering does not matter, you can place them in parallel as in Diagram 1b. Then, because theyare deferred, a separate background process may execute each activity resulting in true parallelprocessing with faster turn around. The AND operator ensures that the flow only continues whenboth activities are complete.

    Diagram 1b: Shows the same process flow but two activities have been placed in parallel.

  • Coding TechniquesWFDEVSTD.doc(v25)

    14

    Diagram 1c: Similar to diagram 1b but without the AND-operator.

    Diagram 1c is similar to 1b but without the AND-operator. Now the threads do not need torendezvous. Therefore the first thread to arrive at Party invite, an FYI notification, sends thenotification and immediately progresses to the END so terminating the other thread. If Make Pizzaand Setup transportation are subprocesses or notifications requiring responses, terminating eitherone before it is really complete seriously changes the process flow from what we had before. Inthis case you could end up with a party with no pizza or no transportation to get to it! Thishighlights the importance of the AND-operator as the only way to guarantee that all threads areexecuted.

    Hanging Activities

    When the sequence of events is not important, it is tempting to hang a series of activities off asingle parent activity creating parallel threads. FYI notifications are often treated in this way, as ifadded as an after thought. This is very dangerous because there is no guarantee that all activitieswill complete. It is far better to place the activities in sequence.

    Diagram 2: Example of an FYI notification hanging off an activity. In this example , NotifyDirect Manager FYI is probably sent because the engine must wait further downstream for anapproval. However, if Request Approval was replaced with a synchronous activity, such as afunction or an FYI, then the process would terminate and the FYI would not be sent. Placing thisFYI into the main flow is better practice and also makes it easier to read.

  • Coding TechniquesWFDEVSTD.doc(v25)

    15

    Racing Parallel Threads.The fact that the engine terminates any open activities on completion of the process can work toyour advantage. Sometimes we purposely pit two threads against each other and start a race to seewhich thread ends first. This happens when we are dealing with an EITHER-OR case where by wecan accept a final result from either thread. An example of this is a dynamic timeout constructwhere one thread waits to timeout while the other performs some activities (see section on dynamictimeouts).

    Forced Synchronous ProcessesWhen you use workflow in a totally synchronous mode in which you are only concerned in acalculated end result, it can be more efficient to run the process in forced synchronous mode. This accelerates the execution speed by not writing any information to the workflow database tables. Asevere limitation in this mode is that no auditing takes place and any error must be raised to thecalling program and handled immediately without the fall back of the error process. Examples ofsuch a use are the Flexfield generators in Oracle Applications.

    To execute in forced synchronous mode, simply specify the itemkey as #SYNCH. Whenever theengine detects this value for the itemkey it will not write anything to the database.

    No Deferred Activities No Notifications or Blocking Activities No Error Processes No Loop Reset (loops are allowed, but no reset processing will occur) No Master / Detail flow control No parallel splits (transitions from activity must have distinct results) Not permitted to use the "Any" transition (would cause a parallel split) No WF_Engine calls for any item besides the current synchronous item. No Monitoring / Auditing Disallowed Standard Activities

    And Block Wait Notifications / Voting Continue Flow / Wait for Flow Role Resolution Compare Execution Time Notify Defer Thread

    No WF_Engine API calls besides the following WF_Engine.StartProcess(itemtype, itemkey) WF_Engine.GetItemAttr WF_Engine.SetItemAttr WF_Engine.GetActivityAttr

    Table of restrictions when using Forced Synchronous Process (#SYNCH)

    To debug a process in forced synchronous mode, run it in regular mode by setting a uniqueitemkey. This way all the auditing and errors stacks will be written to the database. Then debug itas normal.

  • Coding TechniquesWFDEVSTD.doc(v25)

    16

    External Function Calls

    Workflow 2.5 permits you to define activity functions which do not call PL/SQL packageprocedures in the local database. Simply set the functions activity type to EXTERNAL andworkflow places an entry onto a special Advanced Queue, called the Outbound Queue, and sets theactivity to a blocked state (status = NOTIFIED). The activity will remain in this state until thequeued event is processed and the result is placed back onto the inbound queue. The backgroundengine always checks for any entries in the Inbound queue and updates the activity accordingly.

    By using the combination of outbound and inbound queues, Workflow provides a standardinterface for integrating external applications. However the actual processing of the event is stillthe application coders responsibility. You must set up a queue processor that polls the outboundqueue for your specific event type, processes it and writes the answer onto the inbound queue. Allthe information for processing the activity is written on the outbound queue event and there are aseries of Workflow Queue APIs for this. The queue processor can be written in C, Java or PL/SQLand can reside on the server or client (the former makes more sense): it all depends on yourimplementation.

    Blocks and Waits

    Among the many functions provided in the WF_STANDARD item type (wfstd.wft), two areparticularly useful for interrupting your process: Block and Wait. In the following examples, weshow how you can use these to couple with other applications as an alternative method to advancedqueues.

    Coupling with non-Oracle Workflow systems.The block activity stops your flow from proceeding any further by setting the activity status toNOTIFIED. In this state, the engine treats the activity like a notification and ignores it until anexternal activity restarts the process by calling CompleteActivity. This is the easiest way tosynchronize with another application as long as you have access to customize the other system.Usually it is used to synchronize between processes within the same application groups codebecause the code that releases the block must know of the item type, key and label name.

    NOTE: see master/detail coordination for more complex synchronization between workflowprocesses.

    Diagram 3 shows the use of a block activity to call out to an external application. The Get SalaryAuthorization function communicates with the application and the process is blocked until theexternal application gives the go-ahead to continue (using CompleteActivity).

    The wait activity pauses the process for a time interval which can be defined in absolute or relativetime. A background engine detects when it is time to proceed again. This can also be used tointerface with an external system but in this case the communication is one-way, in that OracleWorkflow constantly polls for an event and only proceeds when the event is satisfied. This is notas efficient as a Block because it places extra load on the background engine which picks up thewait and performs the check.

  • Coding TechniquesWFDEVSTD.doc(v25)

    17

    Diagram 4.This does the same functionality as the block activity. Use this implementation whenyou do not have update access to the external event/application so that it cannot be modified torestart the process. Instead an API and wait function are added that check the outcome at regularintervals and only continue when a condition is met. The advantage is that you dont need toupdate external events and your workflow remains independent. The disadvantage is that the waitmay cause an unnecessary delay in processing time and add overhead to the background engine.

    Timeouts

    Timeouts are a mechanism for setting a time limit on an activity after which the activity iscompleted automatically and control is routed along a timeout thread. Use this to constructnotification reminders.

    Diagram 5: The Activity Detail Screen showing a timeout of 5 minutes. Note the drop box fortimeout is shown expanded displaying all 3 timeout options.

    How it worksTimeouts are defined in the Workflow Builder on the activitys property page. You may eitherselect relative and enter the days, hours and minutes in the appropriate UI fields, or choose ItemAttribute and reference an item attribute. The item attribute can be numeric, signifying the numberof minutes, or a date value specifying the absolute date to wait for. A Background Engine willprocess this when it checks for timeout events as specified by its PROCESS_TIMEOUT parameter. Specifically, it checks if the timeout interval is exceeded since its start time for any activity with astatus of WAITING, SUSPENDED, NOTIFIED, DEFERRED or ACTIVE when it is a process. If the timeoutinterval has been exceeded, the status of the activity is forced to COMPLETE:#TIMEOUT. Fornotification activities, it cancels any outstanding notifications (those that require a response) bysetting their status to CANCEL. For processes, it kills any child processes by forcing their status toCOMPLETE:#FORCE. Once timed-out, the engine progresses down a timeout path. Notice thattimeouts are processed by setting the status flags to complete and no activity is actually interrupted

  • Coding TechniquesWFDEVSTD.doc(v25)

    18

    or killed during execution. This makes for cleaner processing, though any database changes from asubprocess that was timed-out are not rolled back.

    For timeouts to work correctly, it is essential that the background engine is properly configured.(refer to Background Engine).

    Timeouts and Notifications

    Every notification that requires a response must have a timeout event; otherwise your workflowmay appear to hang if someone ignores, forgets or otherwise does not respond.

    Diagram 6: The Notify Approver process from the Oracle Workflow Demonstration

    Diagram 6 shows a complete subprocess for approving a notification. Note how the two timeoutsare being used: the first notification times-out to give a polite reminder which in turn timeouts andkeeps repeating until the recipient responds. Another example would be to include a loop counterwithin the reminder loop that sets a limit on the number of times to repeat. The limit could be setdynamically (perhaps as a user attribute) or hard coded in the design. Alternatively the loop couldincrement the priority of the message.

    Timeouts and Functions

    All functions can have a timeout defined on the activity detail sheet but at runtime only functionswith a status of WAITING, SUSPENDED, NOTIFIED or DEFERRED are processed as timeouts. Thereforesynchronous functions that remain ACTIVE throughout their duration are never timed-out but cometo normal completion.

    How they workThe Workflow Engine and Background Engine are two different database processes. Thebackground engine cannot see the data generated by the Workflow Engine until the WorkflowEngine completes processing and the calling application performs a commit. Therefore functions,or processes, that execute synchronously from start to finish cannot be timed-out. The only way totimeout a synchronous function is to model it as an asynchronous subprocess.

    Common uses

    The most common use for timeouts with functions are expirations on blocking activities. Forexample, your blocking activity may be waiting for an external event but it will timeout if thatevent doesnt happen within the set time. This ensures that your process does not remain waitingforever.

  • Coding TechniquesWFDEVSTD.doc(v25)

    19

    Timeouts and Processes

    Processes are activities so they can also have a specified timeout period. You can use this as auseful maximum time limit on a process which may save you effort programming a limit on theamount of looping that may happen inside the process itself (see diagram 7).

    Diagram 7: Example of a process for a typical notification that uses timeouts to generatereminders . The loop counter is set to 9 and the timeout on the notification is one day. Thereforeup to 10 notifications may be sent (the original and 9 reminders) before the process ends with atimeout result.

    Diagram 8: with the loop counter removed, this process will keep sending notifications foreveruntil a response is made. However it will perform the same as diagram 1a if the process itself hasa timeout period of 10 days.

    Caution

    For the same reasons as functions, a synchronous process (one that has at least one uninterruptedpath from start to end) cannot be timed out. If you want to force a process to timeout, interrupt thesynchronous flow by deferring the first function (raise its cost above the threshold cost). Howeverif the process is already deferred, insert a wait activity with a minimum wait (example, one secondwait) to interrupt the thread.

    Dynamic timeouts and dynamic timeout constructs

    To set a timeout dynamically, Workflow 2.5 permits you to set the timeout to an item typeattribute, the value of which can be populated at runtime. This is the easiest and most reliable way.However, you can create a construct that has the effect of a timeout by racing two parallel threadsagainst each other. This is more complicated and you must ensure that both parallel threads areasynchronous. Therefore it is not advised; however it is backward compatible with previousversions of Workflow, so it is included here purely for reference.

  • Coding TechniquesWFDEVSTD.doc(v25)

    20

    Diagram 9: A dynamic timeout construct.

    In diagram 9, a user defined function is used to lookup or calculate the timeout interval which isthen stored to an item attribute. The process flow then splits in to two threads, starting a race between the notification and the wait activity (which accesses the timeout interval through the itemattribute). Whichever thread completes first returns the result value to the calling process (seeracing parallel threads).

    Timeouts on business days only

    Currently there is no support to limit the timeout duration to business days because these may varybetween users, companies and countries. If you wish to limit your timeout duration to workinghours only, you must create an API to validate the timeout period against your calendar and usethis value in a dynamic timeout.

    NOTE: Consultants can implement a database trigger on WF_ITEM_ACTIVITY_STATUSES tocheck the value of the timeout, stored in DUE_DATE, and modify it accordingly if necessary. Thiswould result in a system wide change. It may also impact performance.

    Subprocesses

    Always use subprocesses to group a series of activities that perform one logical unit of work. Thiswill drastically simplify your process flow and make it easy to read and maintain. For example,consider a notification with several reminders and multiple outcomes. Rather than repeating yourentire flow for each reminder, encapsulate the notification/reminder process in a subprocess.

    Diagram 10 shows the same activity repeated three times, once for the initial notification andtwice for reminders. In each case the same notification has 4 outcomes, each of which is repeated.This can become very complex if each outcome leads to a very long thread.

  • Coding TechniquesWFDEVSTD.doc(v25)

    21

    Diagram 11 shows the same process flow but the notification has been dropped into its ownsubprocess (see diagram 12) making the diagram far easier to read (and draw!). Notice that thenumber of outcomes in the lookup list has been increased to include the No_Response option.Alternatively, use the option to catch all unmodeled responses and process this resultwithout modifying the lookup.

    Diagram 12 shows the subprocess Approve Notification. Notice we use a loop counter to simplifysending notifications. By including the loop-counter value dynamically in the notification body orsubject, we can indicate this is the n-th reminder.

    Limitations

    Subprocesses are an excellent way to package common functionality. However at present, the samesubprocess cannot be used more than once in a single process (a subprocess in a loop is a singleoccurrence). Using the subprocess in mutually exclusive processes is not problematic at runtime(because the process will only be called once in the same hierarchy tree) however it will causeproblems if using the expedite button on the monitor. As a workaround, please copy and renamethe subprocess.

  • Coding TechniquesWFDEVSTD.doc(v25)

    22

    Customizing Hooks

    All workflow processes can be easily customized. However, there are steps you can take to guideand facilitate where a user should place their customization and in this way preserve your processflow. Essentially, the main technique is to embed clearly labeled null functions or processes that auser can swap for their own API.

    Embedding null processesEmbedding null processes in your flow makes it very clear where a user can add customization. Ifyou drop parts of your process into subprocesses then you can further abstract your process,rendering a very simple top level flow in which the points for customization are easilydistinguishable. Embedding null processes is more flexible than null functions because a user canadd as much as they like within that subprocess.

    Diagram 13: Example of a top level process flow where null processes have been inserted ashooks for user customization and the main flow has been dropped into a subprocess.

    Using Item AttributesUse item attributes when you have activity attributes that need customization. Rather than makingthe user navigate to each activity instance, they simply modify one item attribute. This isparticularly useful when setting the performer role for multiple notifications that could be scatteredthroughout your process or nested in different sub processes.

    NOTE: When setting up an item attribute to store the performer role as described above,remember to define the item attribute as type ROLE which will give you all the benefits of role-attributes: even if you do not need these, your customer may want them when they customize.

    Loop Structures

    A loop is a simple construct in which an activity, or series of activities is repeated. Most workflowproducts offer such a construct but Oracle Workflow additionally offers the ability to undo orunwind what has previously been executed in a loop of activities.

    Processing within loops

    The Workflow Engine automatically detects when it enters a loop. It makes use of its extensiveauditing trail to check if the activity has already been executed. At design time you have the optionto respond to this in three different ways determined by the On-revisit flag.

  • Coding TechniquesWFDEVSTD.doc(v25)

    23

    Diagram 14: Details tab of an Activity Property Sheet. Note the on-revisit option, with the dropbox showing all three possible values.

    On-revisit Reset option

    This is the default option. It means that when the engine detects it is in a loop, it looks up all thechild activities in the loop (i.e. everything that follows this activity which has already been run)and runs them again in CANCEL mode (it reruns then in order of first to last). This enables you towrite appropriate logic in your APIs to undo any events that may have taken place the first timearound. In this way, you have the ability to rewind a process so you can re-execute it. This isparticularly useful when you must undo any updates to the database from a previous round so thatthe same event happens on re-execution of the loop. If you do not have any changes to undo thenprogram a null event.

    If (funcmode = CANCEL) then do cancel mode processing else if (funcmode = RUN) then do regular run time processing else if (funcmode = TIMEOUT) then only valid for vote functions else -- there shouldnt be any other modes null;end if;

    Example of coding an API to handle the different modes of funcmode.

    On-revisit Loop option

    The loop option was introduced to improve efficiency by not calling already-executed activities inCANCEL mode. It otherwise functions exactly the same as the Reset option and permits the loop tocontinue.

    On-revisit Ignore option and OR-joinsThe only reason to use the Ignore option is when programming OR-joins, which is not a real loop.When using an OR-join you only want the activity and the thread after it, to execute the first timearound. All subsequent executions will ignore the rest of the thread and terminate. This type of aconstruct is not of much use in a true loop scenario.

  • Coding TechniquesWFDEVSTD.doc(v25)

    24

    Pivot Activity

    This is the first activity that gets detected as a re-executed activity. It marks the beginning of there-executed loop and governs which rewind technique is used to process this loop. Therefore thevalue of on-revisit is only important on the first activity in the loop - the pivot activity.

    Common problemsIf you find that a process is starting but never finishing and it includes a loop, check the On-revisitoption on the pivot activity. If on-revisit is set to ignore it will make the process hang in what lookslike a normal state. A background engine will detect this only if there are no other active threads inthe process and only then set its status to ERROR with a result of STUCK.

    Notifications in loopsNotifications that occur within a loop will be canceled automatically. This is to enable anotification to be sent a second time with corrected information or a different performer but still bethe same logical business event. If instead you do not want the notification to be canceled then nestthe notification into a function, such as the NOTIFY standard activity.

    Exception Handling

    One of the major advantages of Oracle Workflow over conventional systems is the ability toidentify and correct data errors without interrupting the process flow or creating extensive log filesor reports which have to be checked by an individual on a routine and regular basis. Thereforecorrect implementation of error handling can greatly enhance your process flow.

    The Default branch - Catching unexpected outcomes.If your function API is programmed to return multiple outcomes (e.g. multiple values from lookupcodes or a variety of error codes), then use the default branch to handle all the remainingconditions. For example, an API returns Yes or No or one of multiple error codes that could occurat runtime. Use the default branch to catch all exceptions.

    Diagram 15: In this case, all unexpected return values from the function Is Document Completeare caught by the default branch and logged by the Document Manager Failed function. Note: inthis way, every possible outcome does not have to be in the lookup for the return values.

    The Default vs. Any transition.The builder will always offer Default and Any transitions when the activity has an associated resulttype. Default will only be executed if no other transition fits the result where as Any is alwaysexecuted irrespective of the result.

    Using notificationsNotifications are integral to error handling. Use a notification to inform the System Administrator

  • Coding TechniquesWFDEVSTD.doc(v25)

    25

    or, better still, the responsible person, that an error has been detected and needs correcting. Includeon the notification a response request to signify when the data has been corrected and is OK tocontinue.

    For example, during a requisition approval, the Select Manager function finds that there is nomanager defined in the HR tables which causes a No Data Found error. Rather than terminate theprocess, send a notification request to the HR representative to fix the data and respond when thedata is fixed. You can enhance this construct by incorporating a timeout to force the API to repeatin case the data problem is corrected in the system. If it is not corrected, another notification is sentmuch like a reminder, but if it is corrected, the process can continue without waiting for aresponse.

    Diagram 16 shows how a notification can be used to handle missing data. The continue branch isthe only valid response and it permits the process to try again. The timeout branch tries it againirrespective of a response in case the data error has been corrected by a different source (or theuser corrected it but forgot to respond to the notification).

    Workflow Error HandlingOracle Workflow provides error handling mechanisms for all errors that force the process instanceinto ERROR status and so prevent it from completing. Examples of errors are:

    unhandled branch results detected by the background engine

    any system error such as an inability to set savepoints, perform rollback etc.

    engine or notification errors due to invalid data

    data errors such as too many rows selected, no data found, divide by zero etc.

    On detection of an error, the engine sets the activity status to ERROR which terminates processingon that item. If an error process was defined, either for this activity or anywhere up the parentactivity hierarchy, it will be launched and specific item attributes set as defined in the manual. Ifyou can foresee an error then model a process around it. The error process should be a last resortto catch non-function-specific errors. The Default Error supplied by Oracle Workflow should besufficiently general to cope with all errors. If however you need to write your own error handler,make sure you use the same item attributes as defined in the Default Error because this is the onlyway to cross reference the original process in error.

    We recommend you use the DEFAULT_ERROR process in WF_ERROR item type. By default,this sends a notification to the system administrator informing them of the error and requesting aresponse. The administrator has the option to retry or abort the process or access the monitor andperform more complex tasks such as skipping the activity with a specific result. The error processwill automatically terminate once the error is resolved or the administrator has responded.Additionally, defining an item attribute WF_ADMINISTRATOR in your process will override thesystem administrator as the recipient of the error message. This way you can enforce that a rolewho knows and understands your specific item type is informed of any errors rather than having

  • Coding TechniquesWFDEVSTD.doc(v25)

    26

    every single error in the system going to one role.

    Diagram 17: The SYSTEM:Error (from wferror.wft) generic error message. This is sent to thesystem administrator when an error occurs. Note, all the notification attributes refer to itemattributes that were defined by the error handling function in the process in error prior to callingthis error handling process. These item attributes are always set regardless of which error processis called.

    Master Detail Flows

    Oracle Workflows Standard item type includes two function activities, WaitForFlow andContinueFlow, that ensure coordination between master-detail relationships. See the OracleWorkflow Guide for information regarding how to use them. The Oracle Workflow ProductSurvey Demo (wfsrv.wft) has an example of a master/detail implementation: the survey is themaster process and each participants questionnaire is the detail flow.

    There are two ways to initiate a master/detail process which have subtle differences:

    Starting from the same process.

    Diagram 18a: Parent and Child Processes: note the parent process includes an activity to spawnthe child processes.

  • Coding TechniquesWFDEVSTD.doc(v25)

    27

    In this example the master process includes an activity to spawn the child processes and onlyprogresses to the next activity once it has completed spawning all the children. Note that becauseOracle Workflow is a series of package procedures, the parent process waits for each child tocomplete or for its thread to be interrupted. If there are no dependencies between the children youshould defer them to improve throughput.

    Note that if your children are synchronous processes (at least up to the ContinueFlow activity),then they will be executed in succession. This is no different to running a subprocess in linemultiple times.

    Starting the children from a separate process.

    Diagram 18b: Parent and Child processes started from separate procedure.

    When a separate procedure starts the children it is important how and when you define yourparent-child relationship. Code Example 1 shows a simple loop in which each child is created andstarted individually. With such a set up, the first child is also the last child (because the next childhas not been created or spawned yet) so if it executes a ContinueFlow then it will succeed inrestarting the parent prematurely. To overcome this, define your relationships before starting thechildren as shown in Code example 2 below.

    --set up and start the parent flowWF_ENGINE.CreateProcess(order_header, header_id, process_name);WF_ENGINE.StartProcess(order_header, header_id);--set up child flowsFor each detail_line loop WF_ENGINE.CreateProcess(order_lines, detail_line.line_id); WF_ITEM.SetItemParent(order_lines, detail_line.line_id, order_header, header_id); WF_ENGINE.StartProcess(order_lines, detail_line.line_id));End loop

    Example 1: Creating and Starting each detail line individually.

    --set up and start the parent flowWF_ENGINE.CreateProcess(order_header, header_id, process_name);WF_ENGINE.StartProcess(order_header, header_id);--set up child flowsFor each detail_line loop WF_ENGINE.CreateProcess(order_lines, detail_line.line_id); WF_ITEM.SetItemParent(order_lines, detail_line.line_id, order_header, header_id);End loop--now the relationship is established, start the childrenFor each detail_line loop WF_ENGINE.StartProcess(order_lines, detail_line.line_id));End loop

    Example 2: Creating all detail lines first and then starting them.

  • Coding TechniquesWFDEVSTD.doc(v25)

    28

    Selector/callback function

    What is it?The selector/callback function is a hook to your custom API which is used to initialize data foreach process instance. There are three types of data it can initialize depending on the mode inwhich it is called.

    RUN mode: in this mode, the engine expects the name of the starting process to be returned.This is only ever called if the CreateProcess API was called without specifying the processname.

    SET_CTX mode: in this mode the selector/callback function initializes any PL/SQL variables.It is called in this mode once for every SQL session prior to executing the first functionactivity.

    TEST_CTX mode: in this mode the selector/callback function returns TRUE or FALSE if aspecific context has been set. This is only ever called from the Notification Viewer form inOracle Workflow embedded in Applications.

    When to useUse the RUN mode when you want to put your decision logic into a common shared API. Youwant to do this when you have more than one option for the initial start process such that hardcoding the process name is not feasible. For completeness, always create a Selector/callbackfunction to return a default start process name. This ensures against errors in case a user startsa workflow without specifying a process name, provides useful documentation and enhances theengine performance.

    Use the SET_CTX mode to set up all your PL/SQL variables. This ensures that PL/SQL variablesare always set for asynchronous processes when execution is restarted. Examples may be setting abind variable so that specific views are correct or setting global variables. In Applications, youwant this to set your org-context and the who-columns.

    Use the TEST_CTX when you want to check that the user context is correct before permitting auser to open a form from the Notification Viewer form (hence it is only available to Workflowembedded in Applications and not part of Standalone). Use this mode to check that theorganization is correctly set in a multi-organization environment.

    Restrictions

    You cannot use a selector/callback function when initiating a process across a distributed databaseor from a database trigger. This is because savepoints/rollbacks cannot be performed during theseactions but are necessary for the engine to issue when starting the selector/callback function. Wheninitiating a process across distributed databases you have to explicitly state the process to invoke.A workaround is to make your selector/callback function independent and call it directly outside ofOracle Workflow.

  • Coding TechniquesWFDEVSTD.doc(v25)

    29

    Notifications

    FYI NotificationsFYI (for your information) notifications are those that require no response from the user. In thedatabase, they are defined as any notification not having respond attributes. To work effectively,these notifications must have the Expand Role attribute checked.

    select notification_id, message_name, message_typefrom wf_notifications nwhere not exists (select respond attributes exist

    from wf_message_attributeswhere message_name=n.message_nameand message_type=n.message_typeand subtype='RESPOND')

    Example of select statement for distinguishing FYI notifications

    Expand rolesThe Expand Role attribute ensures that every user in the role gets an individual copy of thenotification. In this way, each user may review the notification at leisure. This is not the case ifExpand Roles is not checked (the default). When not checked, the notification is shared betweenusers. This means that the first person to complete the notification closes it and so prevents otherusers from reviewing it. This is what you want if the notification does require a single response butnot if it is an FYI, or a vote that requires responses from more than one user. Therefore it isessential for FYI notifications and voting activities, to ensure expand roles is checked.

    NOTE: The implementation of Expand Roles with the Notification Mailer changed betweenreleases. As explained, Expand Roles unchecked signifies that the notification is shared betweenthe users in the role. Prior to release 2.0.3 the Notification Mailer sent one email to a roles emailaddress (WF_ROLES.email_address). This required the email directory services to duplicateWorkflows directory services. With release 2.0.3 the Notification Mailer expands the roleinternally, sending one email to each participant, but still treats it as the same shared notification.

    Response NotificationsNotifications that require responses store each response in notification attributes. If you want tobranch your workflow based on a response, then you must define a result for the message. Thisautomatically creates an attribute with the reserved name of RESULT. At runtime, all notificationattributes are copied to item attributes. Therefore you can retrieve these responses in functionactivities further downstream with the simple GetItemAttribute APIs. However, be careful whenusing the same attribute names in multiple notifications. When you do this, you may not be surewhich response value you are retrieving, so its best to keep your respond message attributesunique.

    Note: The Workflow Builder modifies the icons for response messages and response attributeswith a red mark in the navigator tree.

    PL/SQL DocumentsThe PL/SQL Document is a special message attribute. When defined, workflow looks to substitutethe attribute not with a constant or item attribute value but the output of a custom PL/SQL packageprocedure. This is especially useful when you have multiple lines to substitute and the exactnumber is determined at run time. For example, a Purchase Order has n line items - the exactnumber varies for each PO. Rather than limiting your message to a fixed number (&LINE1,&LINE2 &LINE-N) insert a single attribute which returns all the lines (&PLSQL-DOC).

    When writing Application workflows, never use the &LINE1.&LINE-N construct describedabove, use the PL/SQL document instead. This is described in the Oracle Workflow Guide. A

  • Coding TechniquesWFDEVSTD.doc(v25)

    30

    working example is provided in the workflow demonstration, wfdemo.wft.

    NOTE: PL/SQL Documents are not supported by the Apps Notification Viewer Form. Users mustuse the web notification page.

    PLSQLCLOB Documents (Available in 2.6/11.5.1)Whereas PLSQL Documents are limited to 32K messages (because of the inherent limitation ofstrings in PL/SQL), PLSQLCLOB Documents can create unlimited messages as they are based oncharacter long objects.

    These operate in exactly the same manner as PLSQL documents but the package procedure theycall must accept a CLOB instead of a string. They have slight overheads (because of the CLOBdatatype) and they do not support further substitutions of message attribute tokens. What is writtento the CLOB is printed in the message body. Therefore you cannot add tokens and must performall formatting (for plain text or html).

    Name Attribute DataType

    Attribute Values Signature

    PLSQL DOCUMENT PLSQL:package_name.procedure/argument_string

    procedure (document_id in varchar2,display_type in varchar2,document in out varchar2,document_type in outvarchar2)

    PLSQLCLOB DOCUMENT PLSQLCLOB:package_name.procedure/argument_string

    procedure (document_id in varchar2,display_type in varchar2,document in out clob,document_type in outvarchar2)

    Table showing difference between PLSQL and PLSQLCLOB Document types.

    The notification system will pass a predefined CLOB to your package procedure to which youappend your document. Use the API WF_NOTIFICATIONS.WriteToClob for this. It isrecommended that you build large strings (up to the 32K limit) and then call this API to store thestring to the CLOB so as to reduce the number of calls to this API.

    procedure Example_package (document_id in varchar2, display_type in varchar2, document in out clob, document_type in out varchar2) is

    build_string varchar2(4000);open_td varchar2(5):= ;close_td varchar2(5):=;open_rw varchar2(5):=;close_rw varchar2(5):=;

    cursor data_stream (ordernumber number) is select c.catalog_number, c.catalog_description from parts_catalog c, customer_order_line co where co.catalog_number = c.catalog_number and co.order_number = ordernumber;

  • Coding TechniquesWFDEVSTD.doc(v25)

    31

    begin build_string := ; for data_rec(to_number(document_id)) in data_stream loop

    build_string :=build_string|| open_tr|| open_td||to_char(data_rec.catalog_number)||close_td|| open_td||data_rec.catalog_description||close_td|| close_tr;

    WF_NOTIFICATIONS.WriteToClob(document,build_string);

    build_string :=null; end loop;

    -- if string is null, then it must have been written to document -- so we must add the close table tag. if build_string is null then WF_NOTIFICATIONS.WriteToClob(document,); end if;end;

    Code example for writing a PLSQLCLOB.

    Notifications and URL or Document type attributes.Message attributes of type URL or Document have two extra properties: Frame-Target andAttach-Content. Use Frame-target to specify in which frame or window you want the URL contentto be displayed: generally stick with the default which uses the same window. Use Attach-Contentto specify if the content of the URL or Document should be included as an attachment.

    Diagram 19a: Defining the Frame Target and Attach content for a URL type message attribute.

  • Coding TechniquesWFDEVSTD.doc(v25)

    32

    Diagram 19b: A notification with URL attributes BOTH inline of the message and as attachments.

    In-line vs. Attachment.This depends on your UI but as a guideline, display attachments if the data is not essential to thebody of the message and the attachment is html (either an html file or a package procedure thatreturns html).

    Be aware that the mailer handles attachments in a special way. Depending on the users e-mailnotification preference, the mailer may create HTML-style email or plain text. For plain text, theattachment is included as the full URL path. For HTML style mail, it assumes all attachments arehtml and includes them into the mail as a physical copy. This has serious consequences:

    Security: because its a physical copy, the recipient may see something that is behind afirewall. This may be beneficial or it could be a security hazard depending on the nature ofthe message.

    Relative links: again, because its a physical copy, any relative links will lose their contextand hence not work. Either make sure the links are absolute or dont include as anattachment. This goes for any referenced images as well.

    Non-HTML files: these will also be physically copied, but they will be read in the resultingHTML formatted e-mail as if its HTML. Therefore txt files, which are plain text, will losetheir formatting as browsers cannot read line feeds.

  • Coding TechniquesWFDEVSTD.doc(v25)

    33

    Notifications with a Single URL Response Attribute.These notifications will automatically display the URL in the response frame. It then becomes theresponsibility of the displayed web page to signal back to the workflow engine any responses andcomplete the notification. To do this you must pass the notification Id as a parameter to your webpage. There is a special automatic attribute for this called #NID

    Attribute Type: URLAttribute Value: us.oracle.com/my_web_page?nid=-NID-

    Example for passing notification id to a single URL response attribute

    Once you have the notification Id, you can look up the item values (note: wf_notifications.contextstores the item_type , item_key and actid as a single concatenated , colon delimited, string ). Youcan set any notification attributes with wf_notifications.SetAttr APIs, including the RESULT valuenecessary for branching, and finally complete the notification with wf_notification.respond(nid).

    Wf_Notification.SetAttrText(nid,RESULT.Y);Wf_Notification.SetAttrText(nid,ATTRIBUTE1,My response);Wf_Notification.Respond(nid,my_response_comment,responder_name );

    Example code for responding to a notification

    Post-Notification Function

    A user defined function that is executed after a notification changes state. This provides theworkflow developer a low level of granularity to manipulate the results of notifications.

    Prior to Oracle Workflow 2.5, post-notification functions were reserved for Voting stylenotifications (response notifications sent to multi


Top Related