idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
13,800
public List < String > getNotifierSpecs ( Long taskId , Long processInstanceId , String outcome ) throws ObserverException { String noticesAttr = null ; EventServices eventManager = ServiceLocator . getEventServices ( ) ; try { if ( processInstanceId != null ) { Process process = eventManager . findProcessByProcessInstanceId ( processInstanceId ) ; if ( process != null && process . getActivities ( ) != null ) { TaskTemplate taskVO = TaskTemplateCache . getTaskTemplate ( taskId ) ; for ( Activity activity : process . getActivities ( ) ) { if ( taskVO . getLogicalId ( ) . equals ( activity . getAttribute ( TaskAttributeConstant . TASK_LOGICAL_ID ) ) ) { noticesAttr = activity . getAttribute ( TaskAttributeConstant . NOTICES ) ; break ; } } } } if ( ! StringHelper . isEmpty ( noticesAttr ) ) { return parseNoticiesAttr ( noticesAttr , outcome ) ; } return getNotifierSpecs ( taskId , outcome ) ; // For compatibility } catch ( Exception ex ) { logger . severeException ( ex . getMessage ( ) , ex ) ; return null ; } }
Return a list of notifier class name and template name and version pairs Get the template name and notifier class names based on the process activity attributes to get the relevant values for in flight and new processes
260
40
13,801
private List < String > parseNoticiesAttr ( String noticesAttr , String outcome ) { List < String > notifiers = new ArrayList < String > ( ) ; int columnCount = 4 ; int colon = noticesAttr . indexOf ( ";" ) ; if ( colon != - 1 ) { columnCount = StringHelper . delimiterColumnCount ( noticesAttr . substring ( 0 , colon ) , "," , "\\," ) + 1 ; } int notifierClassColIndex = columnCount > 3 ? 3 : 2 ; List < String [ ] > rows = StringHelper . parseTable ( noticesAttr , ' ' , ' ' , columnCount ) ; for ( String [ ] row : rows ) { if ( ! StringHelper . isEmpty ( row [ 1 ] ) && row [ 0 ] . equals ( outcome ) ) { StringTokenizer st = new StringTokenizer ( row [ notifierClassColIndex ] , "," ) ; boolean hasCustomClass = false ; String templateVerSpec = columnCount > 3 ? ":" + row [ 2 ] : "" ; while ( st . hasMoreTokens ( ) ) { String className = st . nextToken ( ) ; className = getNotifierClassName ( className ) ; notifiers . add ( className + ":" + row [ 1 ] + templateVerSpec ) ; hasCustomClass = true ; } if ( ! hasCustomClass ) { notifiers . add ( NOTIFIER_PACKAGE + ".TaskEmailNotifier:" + ":" + row [ 1 ] + templateVerSpec ) ; } } } return notifiers ; }
To parse notices attribute
341
4
13,802
public static void assertEquals ( String message , XmlCursor expected , XmlCursor actual ) { for ( int child = 0 ; true ; child ++ ) { boolean child1 = expected . toChild ( child ) ; boolean child2 = actual . toChild ( child ) ; if ( child1 != child2 ) { fail ( message , "Different XML structure near " + QNameHelper . pretty ( expected . getName ( ) ) ) ; } else if ( expected . getName ( ) != null && ! expected . getName ( ) . equals ( actual . getName ( ) ) ) { fail ( message , "Expected element: '" + expected . getName ( ) + "' differs from actual element: '" + actual . getName ( ) + "'" ) ; } else if ( child == 0 && ! child1 ) { if ( ! ( expected . getTextValue ( ) . equals ( actual . getTextValue ( ) ) ) ) { fail ( message , "Expected value for element " + QNameHelper . pretty ( expected . getName ( ) ) + " -> '" + expected . getTextValue ( ) + "' differs from actual value '" + actual . getTextValue ( ) + "'" ) ; } break ; } else if ( child1 ) { assertEquals ( message , expected , actual ) ; expected . toParent ( ) ; actual . toParent ( ) ; } else { break ; } } assertAttributesEqual ( message , expected , actual ) ; }
Uses cursors to compare two XML documents ignoring whitespace and ordering of attributes . Fails the JUnit test if they re different .
319
28
13,803
private static void assertAttributesEqual ( String message , XmlCursor expected , XmlCursor actual ) { Map < QName , String > map1 = new HashMap < QName , String > ( ) ; Map < QName , String > map2 = new HashMap < QName , String > ( ) ; boolean attr1 = expected . toFirstAttribute ( ) ; boolean attr2 = actual . toFirstAttribute ( ) ; if ( attr1 != attr2 ) { if ( expected . isAttr ( ) || actual . isAttr ( ) ) { expected . toParent ( ) ; } fail ( message , "Differing number of attributes for element: '" + QNameHelper . pretty ( expected . getName ( ) ) + "'" ) ; } else if ( ! attr1 ) { return ; } else { map1 . put ( expected . getName ( ) , expected . getTextValue ( ) ) ; map2 . put ( actual . getName ( ) , actual . getTextValue ( ) ) ; } while ( true ) { attr1 = expected . toNextAttribute ( ) ; attr2 = actual . toNextAttribute ( ) ; if ( attr1 != attr2 ) { if ( expected . isAttr ( ) || actual . isAttr ( ) ) { expected . toParent ( ) ; } fail ( message , "Differing number of attributes for element: '" + QNameHelper . pretty ( expected . getName ( ) ) + "'" ) ; } else if ( ! attr1 ) { break ; } else { map1 . put ( expected . getName ( ) , expected . getTextValue ( ) ) ; map2 . put ( actual . getName ( ) , actual . getTextValue ( ) ) ; } } expected . toParent ( ) ; actual . toParent ( ) ; // check that attribute maps match, neglecting order Iterator < QName > iter = map1 . keySet ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { QName name = iter . next ( ) ; String value1 = map1 . get ( name ) ; String value2 = map2 . get ( name ) ; if ( value2 == null ) { fail ( message , "Expected attribute value missing for element: " + QNameHelper . pretty ( expected . getName ( ) ) + "--> '" + name + "'" ) ; } else if ( ! value2 . equals ( value1 ) ) { fail ( message , "Attribute values for element '" + QNameHelper . pretty ( expected . getName ( ) ) + "': Expected '" + value1 + "', Actual '" + value2 + "'" ) ; } } }
Compares the attributes of the elements at the current position of two XmlCursors . The ordering of the attributes is ignored in the comparison . Fails the JUnit test case if the attributes or their values are different .
587
46
13,804
private String getMainPropertyFileName ( ) throws StartupException { String configLoc = getConfigLocation ( ) ; File file = new File ( configLoc == null ? MDW_PROPERTIES_FILE_NAME : ( configLoc + MDW_PROPERTIES_FILE_NAME ) ) ; if ( file . exists ( ) ) return MDW_PROPERTIES_FILE_NAME ; URL url = this . getClass ( ) . getClassLoader ( ) . getResource ( MDW_PROPERTIES_FILE_NAME ) ; if ( url != null ) return MDW_PROPERTIES_FILE_NAME ; return null ; }
Null means not found .
140
5
13,805
public File getCompiled ( AssetInfo asset , File starter ) throws IOException , ServiceException { File file ; synchronized ( WebpackCache . class ) { file = webpackAssets . get ( asset ) ; if ( file == null || ! file . exists ( ) || file . lastModified ( ) < asset . getFile ( ) . lastModified ( ) || ( starter != null && file . lastModified ( ) < starter . lastModified ( ) ) ) { file = getOutput ( asset ) ; compile ( asset , starter , file ) ; return file ; } } return file ; }
Starter file will be compiled but asset used to compute output path .
127
14
13,806
private void compile ( AssetInfo asset , File source , File target ) throws ServiceException { File watched = watchedAssets . get ( asset ) ; if ( watched == null ) { if ( isDevMode ( ) ) { new Thread ( ( ) -> { try { // avoid recursive compiles if ( isDevMode ( ) ) watchedAssets . put ( asset , target ) ; doCompile ( asset , source , target ) ; } catch ( Exception ex ) { logger . severeException ( ex . getMessage ( ) , ex ) ; } } ) . start ( ) ; } else { doCompile ( asset , source , target ) ; } } }
Returns null except in dev mode .
137
7
13,807
public List < ServiceMonitor > getServiceMonitors ( ) { List < ServiceMonitor > serviceMonitors = new ArrayList <> ( ) ; serviceMonitors . addAll ( getDynamicServices ( ServiceMonitor . class ) ) ; return serviceMonitors ; }
Returns all service monitors .
54
5
13,808
protected TaskInstance createTaskInstance ( ) throws ActivityException { try { String taskTemplate = getAttributeValue ( ATTRIBUTE_TASK_TEMPLATE ) ; if ( taskTemplate == null ) throw new ActivityException ( "Missing attribute: " + ATTRIBUTE_TASK_TEMPLATE ) ; String templateVersion = getAttributeValue ( ATTRIBUTE_TASK_TEMPLATE_VERSION ) ; AssetVersionSpec spec = new AssetVersionSpec ( taskTemplate , templateVersion == null ? "0" : templateVersion ) ; TaskTemplate template = TaskTemplateCache . getTaskTemplate ( spec ) ; if ( template == null ) throw new ActivityException ( "Task template not found: " + spec ) ; String taskName = template . getTaskName ( ) ; String title = null ; if ( ActivityRuntimeContext . isExpression ( taskName ) ) { title = getRuntimeContext ( ) . evaluateToString ( taskName ) ; } String comments = null ; Exception exception = ( Exception ) getVariableValue ( "exception" ) ; if ( exception != null ) { comments = exception . toString ( ) ; if ( exception instanceof ActivityException ) { ActivityRuntimeContext rc = ( ( ActivityException ) exception ) . getRuntimeContext ( ) ; if ( rc != null && rc . getProcess ( ) != null ) { comments = rc . getProcess ( ) . getFullLabel ( ) + "\n" + comments ; } } } return createTaskInstance ( spec , getMasterRequestId ( ) , getProcessInstanceId ( ) , getActivityInstanceId ( ) , getWorkTransitionInstanceId ( ) , title , comments ) ; } catch ( Exception ex ) { throw new ActivityException ( ex . getMessage ( ) , ex ) ; } }
Creates a new task instance based on the configured template for this activity .
378
15
13,809
@ Override public Map < String , String > getRequestHeaders ( ) { Map < String , String > requestHeaders = super . getRequestHeaders ( ) ; if ( requestHeaders == null ) requestHeaders = new HashMap <> ( ) ; try { requestHeaders . put ( Request . REQUEST_ID , getMasterRequestId ( ) ) ; String httpMethod = getHttpMethod ( ) ; if ( "GET" . equals ( httpMethod ) ) requestHeaders . put ( "Accept" , "application/json" ) ; else requestHeaders . put ( "Content-Type" , "application/json" ) ; } catch ( ActivityException ex ) { logexception ( ex . getMessage ( ) , ex ) ; } return requestHeaders ; }
Overridden to append JSON headers .
167
7
13,810
public Long getRequestId ( ) throws ActivityException { if ( requestId != null ) return requestId ; String requestIdVarName = getAttribute ( "requestIdVariable" , "requestId" ) ; Variable requestIdVar = getProcessDefinition ( ) . getVariable ( requestIdVarName ) ; if ( requestIdVar == null && ! "GET" . equals ( getHttpMethod ( ) ) ) throw new ActivityException ( "Request ID variable not defined: " + requestIdVarName ) ; Object requestIdObj = getVariableValue ( requestIdVarName ) ; if ( requestIdObj == null ) return null ; if ( requestIdObj instanceof Long ) { return ( Long ) requestIdObj ; } else { try { return Long . valueOf ( requestIdObj . toString ( ) ) ; } catch ( NumberFormatException ex ) { throw new ActivityException ( "Invalid value for " + requestIdVarName + ": " + requestIdObj ) ; } } }
Returns the requestId that we will use to populate the serviceSummary
207
13
13,811
@ Override public JSONObject handleEvent ( SlackEvent event ) throws ServiceException { if ( event . getCallbackId ( ) != null && event . getCallbackId ( ) . indexOf ( ' ' ) > 0 && event . getCallbackId ( ) . indexOf ( ' ' ) > 0 && event . getTs ( ) != null ) { Long instanceId = Long . parseLong ( event . getCallbackId ( ) . substring ( event . getCallbackId ( ) . lastIndexOf ( ' ' ) + 1 ) ) ; new Thread ( ( ) -> { Map < String , String > indexes = new HashMap <> ( ) ; logger . debug ( "Saving slack:message_ts=" + event . getTs ( ) + " for task " + instanceId ) ; indexes . put ( "slack:message_ts" , event . getTs ( ) ) ; try { ServiceLocator . getTaskServices ( ) . updateIndexes ( instanceId , indexes ) ; } catch ( Exception ex ) { logger . severeException ( "Error updating indexes for task " + instanceId + ": " + ex , ex ) ; } } ) . start ( ) ; } else if ( event . getThreadTs ( ) != null && event . getUser ( ) != null ) { new Thread ( ( ) -> { try { TaskServices taskServices = ServiceLocator . getTaskServices ( ) ; Query query = new Query ( ) ; query . setFilter ( "index" , "slack:message_ts=" + event . getThreadTs ( ) ) ; List < TaskInstance > instances = taskServices . getTasks ( query ) . getTasks ( ) ; for ( TaskInstance instance : instances ) { // add a corresponding note Comment comment = new Comment ( ) ; comment . setCreated ( Date . from ( Instant . now ( ) ) ) ; // TODO: lookup (or cache) users comment . setCreateUser ( event . getUser ( ) . equals ( "U4V5SG5PU" ) ? "Donald Oakes" : event . getUser ( ) ) ; comment . setContent ( event . getText ( ) ) ; comment . setOwnerType ( OwnerType . TASK_INSTANCE ) ; comment . setOwnerId ( instance . getTaskInstanceId ( ) ) ; comment . setName ( "slack_message" ) ; ServiceLocator . getCollaborationServices ( ) . createComment ( comment ) ; } } catch ( Exception ex ) { logger . severeException ( ex . getMessage ( ) , ex ) ; } } ) . start ( ) ; } return null ; }
Messages posted on the tasks channel .
557
8
13,812
public static void writeToFile ( String pFileName , String pContents , boolean pAppend ) throws IOException { FileWriter writer = null ; writer = new FileWriter ( pFileName , pAppend ) ; writer . write ( pContents ) ; writer . flush ( ) ; writer . close ( ) ; }
Method that writes the file contents
67
6
13,813
public static InputStream openConfigurationFile ( String filepath , ClassLoader classLoader ) throws FileNotFoundException { File file = getConfigurationFile ( filepath ) ; if ( file . exists ( ) ) { logger . info ( "Located configuration file: " + file . getAbsolutePath ( ) ) ; return new FileInputStream ( file ) ; } // last resort is classLoader classpath InputStream is = classLoader . getResourceAsStream ( filepath ) ; if ( is == null ) { if ( ApplicationContext . getDeployPath ( ) != null ) { // try META-INF/mdw String deployPath = ApplicationContext . getDeployPath ( ) ; if ( ! deployPath . endsWith ( "/" ) ) deployPath += "/" ; file = new File ( deployPath + "META-INF/mdw/" + filepath ) ; if ( file . exists ( ) ) { logger . info ( "Located configuration file: " + file . getAbsolutePath ( ) ) ; is = new FileInputStream ( file ) ; } } if ( is == null ) throw new FileNotFoundException ( filepath ) ; // give up } return is ; }
Open configuration file . If Java system property mdw . config . location is defined and the file exists in that directory it will load the file . Otherwise it loads through the class path .
251
37
13,814
protected KieBase getKnowledgeBase ( String name , String modifier ) throws StrategyException { KnowledgeBaseAsset kbrs = DroolsKnowledgeBaseCache . getKnowledgeBaseAsset ( name , modifier , null , getClassLoader ( ) ) ; if ( kbrs == null ) { return null ; } else { return kbrs . getKnowledgeBase ( ) ; } }
Returns the latest version .
81
5
13,815
protected List < Attribute > getAttributes1 ( String ownerType , Long ownerId ) throws SQLException { List < Attribute > attrs = getAttributes0 ( ownerType , ownerId ) ; if ( attrs == null ) return null ; ResultSet rs ; String query = "select RULE_SET_DETAILS from RULE_SET where RULE_SET_ID=?" ; for ( Attribute attr : attrs ) { String v = attr . getAttributeValue ( ) ; if ( v != null && v . startsWith ( Asset . ATTRIBUTE_OVERFLOW ) ) { Long assetId = new Long ( v . substring ( Asset . ATTRIBUTE_OVERFLOW . length ( ) + 1 ) ) ; rs = db . runSelect ( query , assetId ) ; if ( rs . next ( ) ) { attr . setAttributeValue ( rs . getString ( 1 ) ) ; } } } return attrs ; }
Same as getAttribute1 but handles overflow values
209
9
13,816
public Document getDocument ( Long documentId ) throws DataAccessException { try { db . openConnection ( ) ; return this . getDocument ( documentId , false ) ; } catch ( SQLException ex ) { throw new DataAccessException ( "Failed to load document: " + documentId , ex ) ; } finally { db . closeConnection ( ) ; } }
Not for update . Opens a new connection .
78
10
13,817
@ SuppressWarnings ( "unchecked" ) public boolean evaluate ( List < String > completedActivities , List < VariableInstance > variableInstances ) throws SynchronizationException { if ( syncedActivityIds == null || syncedActivityIds . length == 0 ) return true ; try { Expression e = ExpressionFactory . createExpression ( syncExpression ) ; // create a context JexlContext jc = JexlHelper . createContext ( ) ; if ( syncedActivityIds != null && completedActivities != null ) { // set the sync values for ( String syncedActivityId : syncedActivityIds ) { Boolean isCompleted = completedActivities . contains ( syncedActivityId ) ; jc . getVars ( ) . put ( syncedActivityId , isCompleted ) ; // the following is for backward compatibility where escaped activity names are used String escapedName = idToEscapedName . get ( syncedActivityId ) ; if ( escapedName != null ) jc . getVars ( ) . put ( escapedName , isCompleted ) ; } } if ( variableInstances != null ) { // set the variables for ( VariableInstance variableInstance : variableInstances ) { jc . getVars ( ) . put ( variableInstance . getName ( ) , variableInstance . getData ( ) ) ; } } // evaluate the expression Boolean b = ( Boolean ) e . evaluate ( jc ) ; return b . booleanValue ( ) ; } catch ( Exception ex ) { logger . severeException ( ex . getMessage ( ) , ex ) ; throw new SynchronizationException ( ex . getMessage ( ) , ex ) ; } }
Checks whether the synchronization criteria can be considered to be met by evaluating the expression versus the list of completed activities .
353
23
13,818
public String getDefaultSyncExpression ( ) { String syncExpression = "" ; for ( int i = 0 ; i < syncedActivityIds . length ; i ++ ) { if ( i > 0 ) syncExpression += " && " ; syncExpression += syncedActivityIds [ i ] ; } return syncExpression ; }
Create the default sync expression based on the synced activity logical IDs .
72
14
13,819
public static RoutingStrategy getRoutingStrategy ( String attributeValue ) throws StrategyException { TaskInstanceStrategyFactory factory = getInstance ( ) ; String className = factory . getStrategyClassName ( attributeValue , StrategyType . RoutingStrategy ) ; RoutingStrategy strategy = ( RoutingStrategy ) factory . getStrategyInstance ( RoutingStrategy . class , className , null ) ; return strategy ; }
Returns a workgroup routing strategy instance based on an attribute value which can consist of either the routing strategy logical name or an xml document .
92
27
13,820
public static RoutingStrategy getRoutingStrategy ( String attributeValue , Long processInstanceId ) throws StrategyException { Package packageVO = processInstanceId == null ? null : getPackage ( processInstanceId ) ; TaskInstanceStrategyFactory factory = getInstance ( ) ; String className = factory . getStrategyClassName ( attributeValue , StrategyType . RoutingStrategy ) ; RoutingStrategy strategy = ( RoutingStrategy ) factory . getStrategyInstance ( RoutingStrategy . class , className , packageVO ) ; return strategy ; }
Returns a workgroup routing strategy instance based on an attribute value and bundle spec which can consist of either the routing strategy logical name or an xml document .
118
30
13,821
public static SubTaskStrategy getSubTaskStrategy ( String attributeValue ) throws StrategyException { TaskInstanceStrategyFactory factory = getInstance ( ) ; String className = factory . getStrategyClassName ( attributeValue , StrategyType . SubTaskStrategy ) ; SubTaskStrategy strategy = ( SubTaskStrategy ) factory . getStrategyInstance ( SubTaskStrategy . class , className , null ) ; return strategy ; }
Returns a subtask strategy instance based on an attribute value which can consist of either the subtask strategy logical name or an xml document .
92
27
13,822
public static SubTaskStrategy getSubTaskStrategy ( String attributeValue , Long processInstanceId ) throws StrategyException { Package packageVO = processInstanceId == null ? null : getPackage ( processInstanceId ) ; TaskInstanceStrategyFactory factory = getInstance ( ) ; String className = factory . getStrategyClassName ( attributeValue , StrategyType . SubTaskStrategy ) ; SubTaskStrategy strategy = ( SubTaskStrategy ) factory . getStrategyInstance ( SubTaskStrategy . class , className , packageVO ) ; return strategy ; }
Returns a subtask strategy instance based on an attribute value and bundle spec which can consist of either the subtask strategy logical name or an xml document .
118
30
13,823
public static PrioritizationStrategy getPrioritizationStrategy ( String attributeValue ) throws StrategyException { TaskInstanceStrategyFactory factory = getInstance ( ) ; String className = factory . getStrategyClassName ( attributeValue , StrategyType . PrioritizationStrategy ) ; PrioritizationStrategy strategy = ( PrioritizationStrategy ) factory . getStrategyInstance ( PrioritizationStrategy . class , className , null ) ; return strategy ; }
Returns a Prioritization routing strategy instance based on an attribute value which can consist of either the routing strategy logical name or an xml document .
98
28
13,824
public static PrioritizationStrategy getPrioritizationStrategy ( String attributeValue , Long processInstanceId ) throws StrategyException { Package packageVO = processInstanceId == null ? null : getPackage ( processInstanceId ) ; TaskInstanceStrategyFactory factory = getInstance ( ) ; String className = factory . getStrategyClassName ( attributeValue , StrategyType . PrioritizationStrategy ) ; PrioritizationStrategy strategy = ( PrioritizationStrategy ) factory . getStrategyInstance ( PrioritizationStrategy . class , className , packageVO ) ; return strategy ; }
Returns a Prioritization routing strategy instance based on an attribute value and bundle spec which can consist of either the routing strategy logical name or an xml document .
124
31
13,825
public static AutoAssignStrategy getAutoAssignStrategy ( String logicalName ) throws StrategyException { TaskInstanceStrategyFactory factory = getInstance ( ) ; String className = factory . getStrategyClassName ( logicalName , StrategyType . AutoAssignStrategy ) ; return ( AutoAssignStrategy ) factory . getStrategyInstance ( AutoAssignStrategy . class , className , null ) ; }
Returns an auto - assign strategy instance based on the logical name .
89
13
13,826
public static AutoAssignStrategy getAutoAssignStrategy ( String logicalName , Long processInstanceId ) throws StrategyException { Package packageVO = processInstanceId == null ? null : getPackage ( processInstanceId ) ; TaskInstanceStrategyFactory factory = getInstance ( ) ; String className = factory . getStrategyClassName ( logicalName , StrategyType . AutoAssignStrategy ) ; return ( AutoAssignStrategy ) factory . getStrategyInstance ( AutoAssignStrategy . class , className , packageVO ) ; }
Returns an auto - assign strategy instance based on the logical name and bundle spec .
115
16
13,827
public JavaFileObject getJavaFileForOutput ( Location location , String className , Kind kind , FileObject sibling ) throws IOException { if ( logger . isMdwDebugEnabled ( ) ) logger . mdwDebug ( "Loading Dynamic Java byte code from: " + ( sibling == null ? null : sibling . toUri ( ) ) ) ; try { JavaFileObject jfo = new ByteArrayJavaFileObject ( className , kind ) ; jfoCache . putIfAbsent ( className , jfo ) ; return jfo ; } catch ( Exception ex ) { logger . severeException ( ex . getMessage ( ) , ex ) ; throw new IOException ( ex . getMessage ( ) , ex ) ; } }
Create a new Java file object which will be used by the compiler to store the generated byte code . Also add a reference to the object to the cache so it can be accessed by other parts of the application .
154
42
13,828
protected ServiceSummary getServiceSummary ( ) throws ActivityException { ServiceSummary serviceSummary = ( ServiceSummary ) getVariableValue ( "serviceSummary" ) ; if ( serviceSummary == null ) throw new ActivityException ( "Missing variable: serviceSummary" ) ; return serviceSummary ; }
If you really must name the variable something other than serviceSummary you can override this method to retrieve its value .
57
22
13,829
@ Override protected Object openConnection ( ) throws ConnectionException { try { String dataSource = getDataSource ( ) ; if ( dataSource == null ) throw new ConnectionException ( "Missing attribute: " + JDBC_DATASOURCE ) ; DatabaseAccess dbAccess = new DatabaseAccess ( dataSource ) ; dbAccess . openConnection ( ) ; return dbAccess ; } catch ( Exception ex ) { throw new ConnectionException ( ConnectionException . CONNECTION_DOWN , ex . getMessage ( ) , ex ) ; } }
Returns a db connection based on the configured jdbc url or datasource which includes the resource path . Override for HTTPS or other connection type .
110
30
13,830
public Object invoke ( Object conn , Object requestData ) throws AdapterException { try { DatabaseAccess dbAccess = ( DatabaseAccess ) conn ; if ( requestData == null ) throw new AdapterException ( "Missing SQL Query" ) ; String query = ( String ) requestData ; QueryType queryType = getQueryType ( ) ; Object queryParams = getQueryParameters ( ) ; if ( queryParams instanceof List < ? > ) { if ( queryType == QueryType . Select ) return dbAccess . runSelect ( query , ( ( List < ? > ) queryParams ) . toArray ( ) ) ; else if ( queryType == QueryType . Update ) { Integer ret = new Integer ( dbAccess . runUpdate ( query , ( ( List < ? > ) queryParams ) . toArray ( ) ) ) ; dbAccess . commit ( ) ; return ret ; } else throw new AdapterException ( "Unsupported query type: " + queryType ) ; } else { if ( queryType == QueryType . Select ) return dbAccess . runSelect ( query , queryParams ) ; else if ( queryType == QueryType . Update ) { Integer ret = new Integer ( dbAccess . runUpdate ( query , queryParams ) ) ; dbAccess . commit ( ) ; return ret ; } else throw new AdapterException ( "Unsupported query type: " + queryType ) ; } } catch ( SQLException ex ) { AdapterException adapEx = new AdapterException ( - 1 , ex . getMessage ( ) , ex ) ; if ( isRetryable ( ex ) ) adapEx . setRetryable ( true ) ; throw adapEx ; } catch ( Exception ex ) { throw new AdapterException ( - 1 , ex . getMessage ( ) , ex ) ; } }
Invokes the JDBC Query . If QueryType is Select returns a java . sql . ResultSet . If QueryType is Update returns an Integer with the number of rows updated .
378
36
13,831
@ Override protected Object getRequestData ( ) throws ActivityException { try { return executePreScript ( getSqlQuery ( ) ) ; } catch ( Exception ex ) { throw new ActivityException ( ex . getMessage ( ) , ex ) ; } }
Returns the parameterized SQL query to execute .
53
9
13,832
@ SuppressWarnings ( "unchecked" ) @ Override public String getMasterRequestId ( Message request ) { List < SoapHeader > headers = ( List < SoapHeader > ) ( ( CxfPayload < ? > ) request . getBody ( ) ) . getHeaders ( ) ; for ( SoapHeader header : headers ) { if ( header . getName ( ) . getLocalPart ( ) . equals ( "MasterRequestID" ) ) { Node headerNode = ( Node ) header . getObject ( ) ; return headerNode . getTextContent ( ) ; } } return null ; }
Assumes a MasterRequestID SOAP header element . Override for something different .
131
17
13,833
private boolean validate ( DefinitionsDocument defdoc ) { List < XmlError > errorList = new ArrayList <> ( ) ; XmlOptions options = new XmlOptions ( ) . setSavePrettyPrint ( ) . setSavePrettyPrintIndent ( 2 ) . setSaveAggressiveNamespaces ( ) ; options . setErrorListener ( errorList ) ; System . out . println ( "!--toString---" ) ; System . out . println ( defdoc . toString ( ) ) ; boolean valid = defdoc . validate ( options ) ; System . out . println ( "Document is " + ( valid ? "valid" : "invalid" ) ) ; if ( ! valid ) { for ( int i = 0 ; i < errorList . size ( ) ; i ++ ) { XmlError error = errorList . get ( i ) ; System . out . println ( "\n" ) ; System . out . println ( "Message: " + error . getMessage ( ) + "\n" ) ; System . out . println ( "Location of invalid XML: " + error . getCursorLocation ( ) . xmlText ( ) + "\n" ) ; } } return valid ; }
Validates the xml after creation
252
6
13,834
public static boolean verifyClass ( String className ) { try { Class < ? > cl = Class . forName ( className ) ; cl . newInstance ( ) ; return true ; } catch ( Exception ex ) { logger . severeException ( "ApplicationContext: verifyClass(): General Exception occurred: " + ex . getMessage ( ) , ex ) ; return false ; } }
Verifies a class
78
4
13,835
public static String getAppId ( ) { if ( appId != null ) return appId ; appId = PropertyManager . getProperty ( PropertyNames . MDW_APP_ID ) ; if ( appId == null ) // try legacy property appId = PropertyManager . getProperty ( "mdw.application.name" ) ; if ( appId == null ) return "Unknown" ; return appId ; }
Returns the application name
87
4
13,836
public static String getAppVersion ( ) { if ( appVersion != null ) return appVersion ; String appName = getAppId ( ) ; if ( "mdw" . equalsIgnoreCase ( appName ) ) { appVersion = getMdwVersion ( ) ; } else { appVersion = "Unknown" ; try { InputStream stream = ApplicationContext . class . getClassLoader ( ) . getResourceAsStream ( BUILD_VERSION_FILE ) ; if ( stream != null ) { appVersion = "" ; int i ; while ( ( i = stream . read ( ) ) != - 1 ) { appVersion += ( char ) i ; } stream . close ( ) ; } } catch ( Exception ex ) { logger . severeException ( ex . getMessage ( ) , ex ) ; } } return appVersion ; }
Returns the application version read from the build version file
174
10
13,837
public static String getServicesUrl ( ) { String servicesUrl = PropertyManager . getProperty ( PropertyNames . MDW_SERVICES_URL ) ; if ( servicesUrl == null ) { servicesUrl = getMdwHubUrl ( ) ; } if ( servicesUrl . endsWith ( "/" ) ) servicesUrl = servicesUrl . substring ( 0 , servicesUrl . length ( ) - 1 ) ; return servicesUrl ; }
Returns the web services URL
91
5
13,838
public static String getCentralServicesUrl ( ) { String centralServicesUrl = getMdwCentralUrl ( ) ; if ( centralServicesUrl != null && centralServicesUrl . endsWith ( "/central" ) ) centralServicesUrl = centralServicesUrl . substring ( 0 , centralServicesUrl . length ( ) - 8 ) ; return centralServicesUrl ; }
Compatibility for disparities in mdw - central hosting mechanism .
74
12
13,839
public static String substitute ( String sql , Object ... params ) { try { if ( params == null || params . length == 0 ) return sql ; String subst = sql ; int start = 0 ; int q ; for ( int i = 0 ; start < subst . length ( ) && ( q = subst . indexOf ( ' ' , start ) ) >= 0 ; i ++ ) { Object param = params [ i ] ; String p = String . valueOf ( param ) ; if ( param != null && ! ( param instanceof Integer ) && ! ( param instanceof Long ) ) p = "'" + p + "'" ; subst = subst . substring ( 0 , q ) + p + subst . substring ( q + 1 ) ; start = q + p . length ( ) ; } return subst ; } catch ( Throwable t ) { logger . severeException ( t . getMessage ( ) , t ) ; return sql ; } }
Utility method for showing parameterized query result
196
9
13,840
public static List < ExternalEvent > getPathExternalEvents ( String bucket ) { if ( myPathCache . get ( bucket ) != null ) return myPathCache . get ( bucket ) ; else if ( bucket . indexOf ( ' ' ) > 0 ) { // We could have a sub-path return getPathExternalEvents ( bucket . substring ( 0 , bucket . lastIndexOf ( ' ' ) ) ) ; } return null ; }
returns the cached path - based external event
92
9
13,841
@ Override public JSONObject get ( String path , Map < String , String > headers ) throws ServiceException , JSONException { Asset rules = getRulesAsset ( path ) ; Operand input = new Operand ( ) ; input . setContext ( getContext ( path ) ) ; Query query = getQuery ( path , headers ) ; input . setParams ( query . getFilters ( ) ) ; input . setMeta ( headers ) ; JSONObject response = invokeRules ( rules , input , getExecutor ( headers ) ) ; Status status = input . getStatus ( ) ; if ( status != null ) { headers . put ( Listener . METAINFO_HTTP_STATUS_CODE , String . valueOf ( status . getCode ( ) ) ) ; if ( response == null ) return status . getJson ( ) ; } return response ; }
Apply rules designated in asset path against incoming request parameters .
181
11
13,842
@ Override @ Path ( "/{assetPath}" ) @ ApiOperation ( value = "Apply rules identified by assetPath." , notes = "Query may contain runtime values" ) @ ApiImplicitParams ( { @ ApiImplicitParam ( name = "FactsObject" , paramType = "body" , required = true , value = "Input to apply rules against" ) , @ ApiImplicitParam ( name = "assetPath" , paramType = "path" , required = true , value = "Identifies a .drl or .xlsx asset" ) , @ ApiImplicitParam ( name = "rules-executor" , paramType = "header" , required = false , value = "Default is Drools" ) } ) public JSONObject post ( String path , JSONObject content , Map < String , String > headers ) throws ServiceException , JSONException { Asset rules = getRulesAsset ( path ) ; Operand input = new Operand ( content ) ; input . setContext ( getContext ( path ) ) ; Query query = getQuery ( path , headers ) ; input . setParams ( query . getFilters ( ) ) ; input . setMeta ( headers ) ; JSONObject response = invokeRules ( rules , input , getExecutor ( headers ) ) ; Status status = input . getStatus ( ) ; if ( status != null ) { headers . put ( Listener . METAINFO_HTTP_STATUS_CODE , String . valueOf ( status . getCode ( ) ) ) ; if ( response == null ) return status . getJson ( ) ; } return response ; }
Apply rules designated in asset path against incoming JSONObject .
350
11
13,843
public void execute ( ) throws ActivityException { try { String language = getLanguage ( ) ; String script = getScript ( ) ; Object retObj = executeScript ( script , language , null , null ) ; if ( retObj != null ) setReturnCode ( retObj . toString ( ) ) ; } catch ( ActivityException ex ) { throw ex ; } catch ( Exception ex ) { logger . severeException ( ex . getMessage ( ) , ex ) ; throw new ActivityException ( - 1 , ex . getMessage ( ) , ex ) ; } }
Execute scripts in supported languages .
116
7
13,844
@ SuppressWarnings ( "deprecation" ) protected Date getEndDate ( Query query ) { Instant instant = query . getInstantFilter ( "Ending" ) ; if ( instant == null ) return null ; else { Date end = new Date ( Date . from ( instant ) . getTime ( ) + DatabaseAccess . getDbTimeDiff ( ) ) ; if ( end . getHours ( ) == 0 ) { end = new Date ( end . getTime ( ) + DAY_MS ) ; // end of day } return end ; } }
This is not completion date . It s ending start date .
117
12
13,845
public void removeEventWaitForActivityInstance ( Long activityInstanceId , String reason ) throws SQLException { String query = "delete from EVENT_WAIT_INSTANCE where EVENT_WAIT_INSTANCE_OWNER_ID=?" ; db . runUpdate ( query , activityInstanceId ) ; this . recordEventHistory ( "All Events" , EventLog . SUBCAT_DEREGISTER , OwnerType . ACTIVITY_INSTANCE , activityInstanceId , reason ) ; if ( db . isMySQL ( ) ) //Commit since JMS message to resume activity was already sent, in case next activity to notify causes deadlock db . commit ( ) ; }
remove other wait instances when an activity receives one event
143
10
13,846
private void removeEventWait ( String eventName ) throws SQLException { String query = "delete from EVENT_WAIT_INSTANCE where EVENT_NAME=?" ; db . runUpdate ( query , eventName ) ; this . recordEventHistory ( eventName , EventLog . SUBCAT_DEREGISTER , "N/A" , 0L , "Deregister all existing waiters" ) ; }
remove existing waiters when a new waiter is registered for the same event
89
14
13,847
public List < ScheduledEvent > getScheduledEventList ( Date cutofftime ) throws SQLException { StringBuffer query = new StringBuffer ( ) ; query . append ( "select EVENT_NAME,CREATE_DT,CONSUME_DT,AUXDATA,REFERENCE,COMMENTS " ) ; query . append ( "from EVENT_INSTANCE " ) ; query . append ( "where STATUS_CD in (" ) ; query . append ( EventInstance . STATUS_SCHEDULED_JOB ) . append ( "," ) ; query . append ( EventInstance . STATUS_INTERNAL_EVENT ) . append ( ")" ) ; ResultSet rs ; if ( cutofftime == null ) { query . append ( " and CONSUME_DT is null" ) ; rs = db . runSelect ( query . toString ( ) ) ; } else { query . append ( " and CONSUME_DT < ?" ) ; rs = db . runSelect ( query . toString ( ) , cutofftime ) ; } List < ScheduledEvent > ret = new ArrayList < ScheduledEvent > ( ) ; while ( rs . next ( ) ) { ScheduledEvent de = new ScheduledEvent ( ) ; de . setName ( rs . getString ( 1 ) ) ; de . setCreateTime ( rs . getTimestamp ( 2 ) ) ; de . setScheduledTime ( rs . getTimestamp ( 3 ) ) ; de . setMessage ( rs . getString ( 4 ) ) ; de . setReference ( rs . getString ( 5 ) ) ; if ( de . getMessage ( ) == null ) de . setMessage ( rs . getString ( 6 ) ) ; ret . add ( de ) ; } return ret ; }
Load all internal event and scheduled jobs before cutoff time . If cutoff time is null load only unscheduled events
377
22
13,848
public List < UnscheduledEvent > getUnscheduledEventList ( Date cutoffTime , int maxRows ) throws SQLException { StringBuffer query = new StringBuffer ( ) ; query . append ( "select EVENT_NAME,CREATE_DT,AUXDATA,REFERENCE,COMMENTS " ) ; query . append ( "from EVENT_INSTANCE " ) ; query . append ( "where STATUS_CD = " + EventInstance . STATUS_INTERNAL_EVENT + " " ) ; query . append ( "and CREATE_DT < ? " ) ; query . append ( "and CONSUME_DT is null " ) ; if ( ! db . isMySQL ( ) ) query . append ( "and ROWNUM <= " + maxRows + " " ) ; query . append ( "order by CREATE_DT" ) ; if ( db . isMySQL ( ) ) query . append ( " LIMIT " + maxRows + " " ) ; List < UnscheduledEvent > ret = new ArrayList < UnscheduledEvent > ( ) ; ResultSet rs = db . runSelect ( query . toString ( ) , cutoffTime ) ; while ( rs . next ( ) ) { UnscheduledEvent ue = new UnscheduledEvent ( ) ; ue . setName ( rs . getString ( "EVENT_NAME" ) ) ; ue . setCreateTime ( rs . getTimestamp ( "CREATE_DT" ) ) ; ue . setMessage ( rs . getString ( "AUXDATA" ) ) ; ue . setReference ( rs . getString ( "REFERENCE" ) ) ; if ( ue . getMessage ( ) == null ) ue . setMessage ( rs . getString ( "COMMENTS" ) ) ; ret . add ( ue ) ; } return ret ; }
Load all internal events start at the specified age and scheduled jobs before cutoff time . If cutoff time is null load only unscheduled events
407
27
13,849
public String getVariableNameForTaskInstance ( Long taskInstId , String name ) throws SQLException { String query = "select v.VARIABLE_NAME " + "from VARIABLE v, VARIABLE_MAPPING vm, TASK t, TASK_INSTANCE ti " + "where ti.TASK_INSTANCE_ID = ?" + " and ti.TASK_ID = t.TASK_ID" + " and vm.MAPPING_OWNER = 'TASK'" + " and vm.MAPPING_OWNER_ID = t.TASK_ID" + " and v.VARIABLE_ID = vm.VARIABLE_ID" + " and (v.VARIABLE_NAME = ? or vm.VAR_REFERRED_AS = ?)" ; Object [ ] args = new Object [ 3 ] ; args [ 0 ] = taskInstId ; args [ 1 ] = name ; args [ 2 ] = name ; ResultSet rs = db . runSelect ( query , args ) ; if ( rs . next ( ) ) { /*if (rs.isLast())*/ return rs . getString ( 1 ) ; //else throw new SQLException("getVariableNameForTaskInstance returns non-unique result"); } else throw new SQLException ( "getVariableNameForTaskInstance returns no result" ) ; }
Get the variable name for a task instance with Referred as name
312
12
13,850
private static void initializeLogging ( ) { try { String mdwLogLevel = LoggerUtil . initializeLogging ( ) ; if ( mdwLogLevel != null ) { LoggerContext loggerContext = ( LoggerContext ) LoggerFactory . getILoggerFactory ( ) ; loggerContext . getLogger ( "com.centurylink.mdw" ) . setLevel ( Level . toLevel ( mdwLogLevel . toLowerCase ( ) ) ) ; } } catch ( IOException ex ) { ex . printStackTrace ( ) ; } }
Make zero - config logback logging honor mdw . logging . level in mdw . yaml .
120
21
13,851
protected synchronized List < String > getActiveWorkerInstances ( ) { List < String > localList = new ArrayList < String > ( ) ; int activeServerInterval = PropertyManager . getIntegerProperty ( PropertyNames . MDW_ROUTING_ACTIVE_SERVER_INTERVAL , 15 ) ; // Represents how many seconds between checks if ( lastCheck == 0 || ( ( System . currentTimeMillis ( ) - lastCheck ) / 1000 ) > activeServerInterval ) { lastCheck = System . currentTimeMillis ( ) ; activeServerList . clear ( ) ; for ( String server : getWorkerInstances ( ) ) { try { HttpHelper helper = new HttpHelper ( new URL ( "http://" + server + "/" + ApplicationContext . getServicesContextRoot ( ) + "/Services/SystemInfo?type=threadDumpCount&format=text" ) ) ; helper . setConnectTimeout ( 1000 ) ; // Timeout after 1 second helper . setReadTimeout ( 1000 ) ; String response = helper . get ( ) ; if ( ! StringHelper . isEmpty ( response ) && Integer . parseInt ( response ) > 0 && ! activeServerList . contains ( server ) ) activeServerList . add ( server ) ; } catch ( Exception ex ) { if ( activeServerList . contains ( server ) ) activeServerList . remove ( server ) ; logger . info ( "MDW Server instance " + server + " is not responding" ) ; } } lastCheck = System . currentTimeMillis ( ) ; } // If all worker instances are non-responsive, still try to send it to one of them - Don't want routing instance to process request // Could be they just did a cache refresh or initial startup and couldn't respond in < 1 second - First request if ( activeServerList . isEmpty ( ) ) { for ( String server : getWorkerInstances ( ) ) activeServerList . ( server ) ; } for ( String server : activeServerList ) localList . ( server ) ; return localList ; }
Override this to modify how active instances are determined
436
9
13,852
protected URL buildURL ( Map < String , String > headers , String instanceHostPort ) throws MalformedURLException { String origUrl = headers . get ( Listener . METAINFO_REQUEST_URL ) ; if ( origUrl == null || ! origUrl . startsWith ( "http" ) ) { // other protocol: forward to standard services url return new URL ( "http://" + instanceHostPort + "/" + getServicesRoot ( ) + "/Services" ) ; } else { URL origHttpUrl = new URL ( origUrl ) ; String path = origHttpUrl . getPath ( ) ; // Re-route from SOAP to REST since MDW only cares about message Payload, plus we no longer have the SOAP Envelope in the request if ( path != null && ( path . contains ( "/SOAP" ) || path . contains ( "/MDWWebService" ) ) ) path = "/" + getServicesRoot ( ) + "/Services" ; String destUrl = origHttpUrl . getProtocol ( ) + "://" + instanceHostPort + path ; if ( ! StringHelper . isEmpty ( headers . get ( Listener . METAINFO_REQUEST_QUERY_STRING ) ) ) destUrl += "?" + headers . get ( Listener . METAINFO_REQUEST_QUERY_STRING ) ; return new URL ( destUrl ) ; } }
Override this to build the destination URL differently .
300
9
13,853
public Object toObject ( String pStr ) { String decoded = null ; try { decoded = decoder . decode ( pStr ) ; } catch ( DecoderException ex ) { ex . printStackTrace ( ) ; throw new TranslationException ( ex . getMessage ( ) ) ; } return decoded ; }
converts the passed in String to an equivalent object
66
10
13,854
protected void runScript ( String mapperScript , Slurper slurper , Builder builder ) throws ActivityException , TransformerException { CompilerConfiguration compilerConfig = new CompilerConfiguration ( ) ; compilerConfig . setScriptBaseClass ( CrossmapScript . class . getName ( ) ) ; Binding binding = new Binding ( ) ; binding . setVariable ( "runtimeContext" , getRuntimeContext ( ) ) ; binding . setVariable ( slurper . getName ( ) , slurper . getInput ( ) ) ; binding . setVariable ( builder . getName ( ) , builder ) ; GroovyShell shell = new GroovyShell ( getPackage ( ) . getCloudClassLoader ( ) , binding , compilerConfig ) ; Script gScript = shell . parse ( mapperScript ) ; gScript . run ( ) ; }
Invokes the builder object for creating new output variable value .
171
12
13,855
public Map < String , String > getDocRefs ( ) { return new HashMap < String , String > ( ) { @ Override public String get ( Object varName ) { VariableInstance varInst = processInstance . getVariable ( ( String ) varName ) ; if ( varInst != null && varInst . getData ( ) instanceof DocumentReference ) return varInst . getData ( ) . toString ( ) ; return null ; } } ; }
For read - only access .
96
6
13,856
public Object getValue ( String key ) { if ( isExpression ( key ) ) return evaluate ( key ) ; else return getVariables ( ) . get ( key ) ; }
Returns a variable value . Key can be a var name or an expression .
38
15
13,857
@ ApiModelProperty ( hidden = true ) public AssetFile getAssetFile ( File file , AssetRevision rev ) throws IOException { AssetFile assetFile ; if ( rev == null ) { rev = versionControl . getRevision ( file ) ; if ( rev == null ) { // presumably dropped-in asset rev = new AssetRevision ( ) ; rev . setVersion ( 0 ) ; rev . setModDate ( new Date ( ) ) ; } assetFile = new AssetFile ( this , file . getName ( ) , rev ) ; assetFile . setRevision ( rev ) ; } else { versionControl . setRevision ( file , rev ) ; assetFile = new AssetFile ( this , file . getName ( ) , rev ) ; versionControl . clearId ( assetFile ) ; } assetFile . setId ( versionControl . getId ( assetFile . getLogicalFile ( ) ) ) ; assetFiles . put ( assetFile . getLogicalFile ( ) , assetFile ) ; return assetFile ; }
Called during initial load the file param is a standard file .
218
13
13,858
private void storeAttribute ( Attr attribute ) { // examine the attributes in namespace xmlns if ( attribute . getNamespaceURI ( ) != null && attribute . getNamespaceURI ( ) . equals ( XMLConstants . XMLNS_ATTRIBUTE_NS_URI ) ) { // Default namespace xmlns="uri goes here" if ( attribute . getNodeName ( ) . equals ( XMLConstants . XMLNS_ATTRIBUTE ) ) { putInCache ( DEFAULT_NS , attribute . getNodeValue ( ) ) ; } else { // Here are the defined prefixes stored putInCache ( attribute . getLocalName ( ) , attribute . getNodeValue ( ) ) ; } } }
This method looks at an attribute and stores it if it is a namespace attribute .
149
16
13,859
public String getNamespaceURI ( String prefix ) { if ( prefix == null || prefix . equals ( XMLConstants . DEFAULT_NS_PREFIX ) ) { return prefix2Uri . get ( DEFAULT_NS ) ; } else { return prefix2Uri . get ( prefix ) ; } }
This method is called by XPath . It returns the default namespace if the prefix is null or .
66
20
13,860
public Object getObject ( String type , Package pkg ) { if ( type == null || type . equals ( documentType ) ) { if ( object == null && content != null ) { object = VariableTranslator . realToObject ( pkg , documentType , content ) ; } } else { if ( content != null ) { documentType = type ; object = VariableTranslator . realToObject ( pkg , documentType , content ) ; } else if ( object != null ) { content = VariableTranslator . realToString ( pkg , documentType , object ) ; documentType = type ; object = VariableTranslator . realToObject ( pkg , documentType , content ) ; } } return object ; }
content in object format
151
4
13,861
public boolean isGroupMapped ( String pGroupName ) { List < String > userGroups = this . getUserGroups ( ) ; for ( String g : userGroups ) { if ( g . equals ( pGroupName ) ) return true ; } return false ; }
Checked if the passed in GroupIName is mapped to the task
59
14
13,862
public boolean isVariableMapped ( String pVarName ) { if ( variables == null ) { return false ; } for ( Variable vo : variables ) { if ( vo . getName ( ) . equals ( pVarName ) ) { return true ; } } return false ; }
Checked if the passed in Var Name is mapped to the task
58
13
13,863
protected SOAPMessage createSoapRequest ( Object requestObj ) throws ActivityException { try { MessageFactory messageFactory = getSoapMessageFactory ( ) ; SOAPMessage soapMessage = messageFactory . createMessage ( ) ; Map < Name , String > soapReqHeaders = getSoapRequestHeaders ( ) ; if ( soapReqHeaders != null ) { SOAPHeader header = soapMessage . getSOAPHeader ( ) ; for ( Name name : soapReqHeaders . keySet ( ) ) { header . addHeaderElement ( name ) . setTextContent ( soapReqHeaders . get ( name ) ) ; } } SOAPBody soapBody = soapMessage . getSOAPBody ( ) ; Document requestDoc = null ; if ( requestObj instanceof String ) { requestDoc = DomHelper . toDomDocument ( ( String ) requestObj ) ; soapBody . addDocument ( requestDoc ) ; } else { Variable reqVar = getProcessDefinition ( ) . getVariable ( getAttributeValue ( REQUEST_VARIABLE ) ) ; XmlDocumentTranslator docRefTrans = ( XmlDocumentTranslator ) VariableTranslator . getTranslator ( getPackage ( ) , reqVar . getType ( ) ) ; requestDoc = docRefTrans . toDomDocument ( requestObj ) ; Document copiedDocument = DomHelper . copyDomDocument ( requestDoc ) ; soapBody . addDocument ( copiedDocument ) ; } return soapMessage ; } catch ( Exception ex ) { throw new ActivityException ( ex . getMessage ( ) , ex ) ; } }
Create the SOAP request object based on the document variable value .
332
13
13,864
public void removeAttribute ( String name ) { if ( getAttributes ( ) != null ) { List < Attribute > toRemove = new ArrayList < Attribute > ( ) ; for ( Attribute attr : getAttributes ( ) ) { if ( attr . getAttributeName ( ) . equals ( name ) ) toRemove . add ( attr ) ; } for ( Attribute attr : toRemove ) getAttributes ( ) . remove ( attr ) ; } }
Takes care of multiples .
99
7
13,865
public static int parseVersionSpec ( String versionString ) throws NumberFormatException { if ( versionString == null ) return 0 ; int dot = versionString . indexOf ( ' ' ) ; int major , minor ; if ( dot > 0 ) { major = Integer . parseInt ( versionString . substring ( 0 , dot ) ) ; minor = Integer . parseInt ( versionString . substring ( dot + 1 ) ) ; } else { major = Integer . parseInt ( versionString ) ; minor = 0 ; } return major * 1000 + minor ; }
single digit without decimal means a major version not minor
116
10
13,866
public static String getFormat ( String fileName ) { int lastDot = fileName . lastIndexOf ( ' ' ) ; if ( lastDot == - 1 ) return null ; return getLanguage ( fileName . substring ( lastDot ) ) ; }
Takes into account special rules due to multiple languages per extension .
56
13
13,867
public VariableTranslator getDynamicVariableTranslator ( String className , ClassLoader parentLoader ) { try { Class < ? > clazz = CompiledJavaCache . getClassFromAssetName ( parentLoader , className ) ; if ( clazz != null ) return ( VariableTranslator ) ( clazz ) . newInstance ( ) ; } catch ( Exception ex ) { logger . trace ( "Dynamic VariableTranslatorProvider not found: " + className ) ; } return null ; }
To get dynamic java variable translator
101
6
13,868
public void onShutdown ( ) { if ( instance == null ) return ; try { this . camelContext . stop ( ) ; } catch ( Exception ex ) { logger . severeException ( ex . getMessage ( ) , ex ) ; } }
Method can be invoked when the server shuts down
51
9
13,869
public static String evaluate ( XmlObject xmlbean , String path ) { XmlCursor cursor = xmlbean . newCursor ( ) ; String value ; // 1.2.3. use XQuery or selectPath // // cursor.toFirstChild(); // String defaultNamespace = cursor.namespaceForPrefix(""); // String namespaceDecl = "declare default element namespace '" + defaultNamespace + "';"; // Map<String,String> namespaces = new HashMap<String,String>(); // cursor.getAllNamespaces(namespaces); // for (String prefix : namespaces.keySet()) // { // namespaceDecl += "declare namespace " + prefix + "='" + namespaces.get(prefix) + "';"; // } // 1. use XQuery // XmlCursor results = cursor.execQuery(namespaceDecl + path); // value = (results==null)?null:results.getTextValue(); // 2. use selectPath on XmlObject // XmlObject[] result = xmlbean.selectPath(namespaceDecl + path); // 3. use selectPath on XmlCursor // cursor.toParent(); // XmlOptions options = new XmlOptions(); // options.put(Path.PATH_DELEGATE_INTERFACE,"org.apache.xmlbeans.impl.xpath.saxon.XBeansXPath"); // cursor.selectPath(namespaceDecl + path, options); // if (cursor.getSelectionCount()>0) { // cursor.toNextSelection(); // value = cursor.getTextValue(); // } else value = null; // 4. use our own implementation try { XmlPath matcher = new XmlPath ( path ) ; value = matcher . evaluate_segment ( cursor , matcher . path_seg ) ; } catch ( XmlException e ) { value = null ; // xpath syntax error - treated as no match } cursor . dispose ( ) ; return value ; }
Using XPath or XQuery . NOTE!!!! To use this code need to include xbean_xpath . jar saxon9 . jar saxon9 - dom . jar in CLASSPATH in startWebLogic . cmd
430
47
13,870
protected void parseGroupMap ( Map < String , Object > groupMap , Map < String , String > resultMap , String prefix ) { Object obj ; for ( String groupKey : groupMap . keySet ( ) ) { obj = groupMap . get ( groupKey ) ; String key = prefix == null ? groupKey : prefix + "." + groupKey ; if ( obj instanceof Map ) parseGroupMap ( loader . getMap ( groupKey , groupMap ) , resultMap , key ) ; // Parse inner map else resultMap . put ( key , decryptValue ( obj . toString ( ) ) ) ; // String, Boolean and List values } }
Flattens the group map
138
6
13,871
protected Integer notifyProcesses ( String eventName , Long eventInstId , String message , int delay ) { Integer status ; try { EventServices eventManager = ServiceLocator . getEventServices ( ) ; status = eventManager . notifyProcess ( eventName , eventInstId , // document ID message , delay ) ; } catch ( Exception e ) { logger . severeException ( e . getMessage ( ) , e ) ; status = EventInstance . RESUME_STATUS_FAILURE ; } return status ; }
This method is used to wake up existing process instances .
107
11
13,872
protected DocumentReference createDocument ( String docType , Object document , String ownerType , Long ownerId , Long processInstanceId , String searchKey1 , String searchKey2 ) throws EventHandlerException { ListenerHelper helper = new ListenerHelper ( ) ; return helper . createDocument ( docType , document , getPackage ( ) , ownerType , ownerId ) ; }
This method is used to create a document from external messages . The document reference returned can be sent as parameters to start or inform processes .
77
27
13,873
protected Object getRequestData ( ) throws ActivityException { String varname = getAttributeValue ( REQUEST_VARIABLE ) ; Object request = varname == null ? null : getParameterValue ( varname ) ; if ( ! StringHelper . isEmpty ( getPreScript ( ) ) ) { Object returnVal = executePreScript ( request ) ; if ( returnVal == null ) { // nothing returned; requestVar may have been assigned by script request = getParameterValue ( varname ) ; } else { request = returnVal ; } } return request ; }
Override this method if need to translate data from variable or need to get data elsewhere . The default method assumes the data is in the variable REQUEST_VARIABLE
118
34
13,874
protected Response getStubbedResponse ( Object requestObject ) { // compatibility String resp = getStubResponse ( externalRequestToString ( requestObject ) ) ; if ( resp != null ) { Response oldStubbed = new Response ( ) ; oldStubbed . setObject ( resp ) ; oldStubbed . setContent ( externalResponseToString ( resp ) ) ; return oldStubbed ; } List < SimulationResponse > responses = new ArrayList <> ( ) ; for ( Attribute attr : this . getAttributes ( ) ) { if ( attr . getAttributeName ( ) . startsWith ( WorkAttributeConstant . SIMULATION_RESPONSE ) ) { SimulationResponse r = new SimulationResponse ( attr . getAttributeValue ( ) ) ; responses . add ( r ) ; } } String unfilteredResponse = null ; String returnCode = null ; if ( responses . size ( ) == 0 ) { unfilteredResponse = null ; } else if ( responses . size ( ) == 1 ) { unfilteredResponse = responses . get ( 0 ) . getResponse ( ) ; returnCode = responses . get ( 0 ) . getReturnCode ( ) ; } else { // randomly pick a response based on chances int total_chances = 0 ; for ( SimulationResponse r : responses ) { total_chances += r . getChance ( ) . intValue ( ) ; } if ( random == null ) random = new Random ( ) ; int ran = random . nextInt ( total_chances ) ; int k = 0 ; for ( SimulationResponse r : responses ) { if ( ran >= k && ran < k + r . getChance ( ) . intValue ( ) ) { unfilteredResponse = r . getResponse ( ) ; break ; } k += r . getChance ( ) . intValue ( ) ; } } Response response = new Response ( ) ; String filtered = filter ( unfilteredResponse , requestObject ) ; response . setObject ( filtered ) ; response . setContent ( filtered ) ; if ( returnCode != null ) { try { response . setStatusCode ( Integer . parseInt ( returnCode ) ) ; } catch ( NumberFormatException ex ) { } } return response ; }
Return stubbed response from external system .
471
8
13,875
protected Map < String , Object > getPreScriptBindings ( Object request ) throws ActivityException { Map < String , Object > binding = new HashMap < String , Object > ( ) ; String requestVar = this . getAttributeValue ( REQUEST_VARIABLE ) ; if ( requestVar != null && request instanceof String ) { binding . put ( "request" , getVariableValue ( requestVar ) ) ; } else { binding . put ( "request" , request ) ; } return binding ; }
Extra bindings for pre - script beyond process variable values .
107
11
13,876
protected Map < String , Object > getPostScriptBindings ( Object response ) throws ActivityException { Map < String , Object > binding = new HashMap < String , Object > ( ) ; String varname = this . getAttributeValue ( RESPONSE_VARIABLE ) ; if ( varname != null && response instanceof String ) { binding . put ( "response" , getVariableValue ( varname ) ) ; } else { binding . put ( "response" , response ) ; } return binding ; }
Extra bindings for post - script beyond process variable values .
108
11
13,877
private void preloadDynamicCaches ( ) { List < CacheService > dynamicCacheServices = CacheRegistry . getInstance ( ) . getDynamicCacheServices ( ) ; for ( CacheService dynamicCacheService : dynamicCacheServices ) { if ( dynamicCacheService instanceof PreloadableCache ) { try { PreloadableCache preloadableCache = ( PreloadableCache ) dynamicCacheService ; RegisteredService regServ = preloadableCache . getClass ( ) . getAnnotation ( RegisteredService . class ) ; Map < String , String > params = new HashMap <> ( ) ; Parameter [ ] parameters = regServ . parameters ( ) ; if ( parameters != null ) { for ( Parameter parameter : parameters ) { if ( parameter . name ( ) . length ( ) > 0 ) params . put ( parameter . name ( ) , parameter . value ( ) ) ; } } preloadableCache . initialize ( params ) ; preloadableCache . loadCache ( ) ; } catch ( Exception ex ) { logger . severeException ( "Failed to preload " + dynamicCacheService . getClass ( ) , ex ) ; } } synchronized ( allCaches ) { allCaches . put ( dynamicCacheService . getClass ( ) . getName ( ) , dynamicCacheService ) ; } } }
Load caches registered as dynamic java services .
274
8
13,878
public void onShutdown ( ) { CacheRegistry . getInstance ( ) . clearDynamicServices ( ) ; // clear dynamic cache services synchronized ( allCaches ) { for ( String cacheName : allCaches . keySet ( ) ) { CacheService cachingObj = allCaches . get ( cacheName ) ; cachingObj . clearCache ( ) ; } } }
Method that gets invoked when the server shuts down
77
9
13,879
public void refreshCache ( String cacheName , List < String > excludedFormats ) { CacheService cache = allCaches . get ( cacheName ) ; if ( cache != null ) { if ( excludedFormats != null && cache instanceof ExcludableCache && excludedFormats . contains ( ( ( ExcludableCache ) cache ) . getFormat ( ) ) ) { logger . debug ( " - omitting cache " + cacheName ) ; } else { logger . info ( " - refresh cache " + cacheName ) ; try { cache . refreshCache ( ) ; } catch ( Exception e ) { logger . severeException ( "failed to refresh cache" , e ) ; } } } }
Refreshes a particular cache by name .
145
9
13,880
public static String getActivityImplementor ( String className ) throws IOException { if ( getActivityImplementors ( ) != null ) { String newImpl = getActivityImplementors ( ) . get ( className ) ; if ( newImpl != null ) return newImpl ; } return className ; }
If the className argument needs to be mapped to a new implementor class returns the new class name ; otherwise returns the unmodified argument .
65
28
13,881
public static String getEventHandler ( String className ) throws IOException { if ( getEventHandlers ( ) != null ) { String newHandler = getEventHandlers ( ) . get ( className ) ; if ( newHandler != null ) return newHandler ; } return className ; }
If the className argument needs to be mapped to a new event handler class returns the new class name ; otherwise returns the unmodified argument .
61
28
13,882
public static String getVariableTranslator ( String className ) throws IOException { if ( getVariableTranslators ( ) != null ) { String newTranslator = getVariableTranslators ( ) . get ( className ) ; if ( newTranslator != null ) return newTranslator ; } return className ; }
If the className argument needs to be mapped to a new variable translator class returns the new class name ; otherwise returns the unmodified argument .
67
28
13,883
public static String getVariableType ( String type ) throws IOException { if ( getVariableTypes ( ) != null ) { String newType = getVariableTypes ( ) . get ( type ) ; if ( newType != null ) return newType ; } return type ; }
If the type argument needs to be mapped to a new variable type class returns the new class name ; otherwise returns the unmodified argument .
56
27
13,884
protected RoutesDefinition getRoutesDefinition ( String name , String version ) throws AdapterException { String modifier = "" ; Map < String , String > params = getHandlerParameters ( ) ; if ( params != null ) { for ( String paramName : params . keySet ( ) ) { if ( modifier . length ( ) == 0 ) modifier += "?" ; else modifier += "&amp;" ; modifier += paramName + "=" + params . get ( paramName ) ; } } Map < String , String > customAttrs = null ; String customAttrString = getAttributeValue ( CUSTOM_ATTRIBUTES ) ; if ( ! StringHelper . isEmpty ( customAttrString ) ) { customAttrs = StringHelper . parseMap ( customAttrString ) ; } RoutesDefinitionRuleSet rdrs ; if ( version == null ) rdrs = CamelRouteCache . getRoutesDefinitionRuleSet ( name , modifier , customAttrs ) ; else rdrs = CamelRouteCache . getRoutesDefinitionRuleSet ( new AssetVersionSpec ( name , version ) , modifier , customAttrs ) ; if ( rdrs == null ) { throw new AdapterException ( "Unable to load Camel route: " + name + modifier ) ; } else { super . logdebug ( "Using RoutesDefinition: " + rdrs . getRuleSet ( ) . getLabel ( ) ) ; return rdrs . getRoutesDefinition ( ) ; } }
Returns the latest version whose attributes match the custom attribute criteria specified via CustomAttributes . Override to apply additional or non - standard conditions .
317
27
13,885
ProcessInstance createProcessInstance ( Long processId , String ownerType , Long ownerId , String secondaryOwnerType , Long secondaryOwnerId , String masterRequestId , Map < String , String > parameters , String label , String template ) throws ProcessException , DataAccessException { ProcessInstance pi = null ; try { Process processVO ; if ( OwnerType . MAIN_PROCESS_INSTANCE . equals ( ownerType ) ) { ProcessInstance parentPi = getDataAccess ( ) . getProcessInstance ( ownerId ) ; Process parentProcdef = ProcessCache . getProcess ( parentPi . getProcessId ( ) ) ; processVO = parentProcdef . getSubProcessVO ( processId ) ; pi = new ProcessInstance ( parentPi . getProcessId ( ) , processVO . getName ( ) ) ; String comment = processId . toString ( ) ; if ( parentPi . getProcessInstDefId ( ) > 0L ) // Indicates instance definition comment += "|HasInstanceDef|" + parentPi . getProcessInstDefId ( ) ; pi . setComment ( comment ) ; } else { if ( uniqueMasterRequestId && ! ( OwnerType . PROCESS_INSTANCE . equals ( ownerType ) || OwnerType . ERROR . equals ( ownerType ) ) ) { // Check for uniqueness of master request id before creating top level process instance, if enabled List < ProcessInstance > list = edao . getProcessInstancesByMasterRequestId ( masterRequestId ) ; if ( list != null && list . size ( ) > 0 ) { String msg = "Could not launch process instance for " + ( label != null ? label : template ) + " because Master Request ID " + masterRequestId + " is not unique" ; logger . error ( msg ) ; throw new ProcessException ( msg ) ; } } processVO = ProcessCache . getProcess ( processId ) ; pi = new ProcessInstance ( processId , processVO . getName ( ) ) ; } pi . setOwner ( ownerType ) ; pi . setOwnerId ( ownerId ) ; pi . setSecondaryOwner ( secondaryOwnerType ) ; pi . setSecondaryOwnerId ( secondaryOwnerId ) ; pi . setMasterRequestId ( masterRequestId ) ; pi . setStatusCode ( WorkStatus . STATUS_PENDING_PROCESS ) ; if ( label != null ) pi . setComment ( label ) ; if ( template != null ) pi . setTemplate ( template ) ; edao . createProcessInstance ( pi ) ; createVariableInstancesFromEventMessage ( pi , parameters ) ; } catch ( SQLException e ) { if ( pi != null && pi . getId ( ) != null && pi . getId ( ) > 0L ) try { edao . setProcessInstanceStatus ( pi . getId ( ) , WorkStatus . STATUS_FAILED ) ; } catch ( SQLException ex ) { logger . severeException ( "Exception while updating process status to 'Failed'" , ex ) ; } throw new DataAccessException ( - 1 , e . getMessage ( ) , e ) ; } return pi ; }
Create a process instance . The status is PENDING_PROCESS
662
15
13,886
void createTransitionInstances ( ProcessInstance processInstanceVO , List < Transition > transitions , Long fromActInstId ) throws ProcessException , DataAccessException { TransitionInstance transInst ; for ( Transition transition : transitions ) { try { if ( tooManyMaxTransitionInstances ( transition , processInstanceVO . getId ( ) ) ) { // Look for a error transition at this time // In case we find it, raise the error event // Otherwise do not do anything handleWorkTransitionError ( processInstanceVO , transition . getId ( ) , fromActInstId ) ; } else { transInst = createTransitionInstance ( transition , processInstanceVO . getId ( ) ) ; String tag = logtag ( processInstanceVO . getProcessId ( ) , processInstanceVO . getId ( ) , transInst ) ; logger . info ( tag , "Transition initiated from " + transition . getFromId ( ) + " to " + transition . getToId ( ) ) ; InternalEvent jmsmsg ; int delay = 0 ; jmsmsg = InternalEvent . createActivityStartMessage ( transition . getToId ( ) , processInstanceVO . getId ( ) , transInst . getTransitionInstanceID ( ) , processInstanceVO . getMasterRequestId ( ) , transition . getLabel ( ) ) ; delay = transition . getTransitionDelay ( ) ; String msgid = ScheduledEvent . INTERNAL_EVENT_PREFIX + processInstanceVO . getId ( ) + "start" + transition . getToId ( ) + "by" + transInst . getTransitionInstanceID ( ) ; if ( delay > 0 ) this . sendDelayedInternalEvent ( jmsmsg , delay , msgid , false ) ; else sendInternalEvent ( jmsmsg ) ; } } catch ( SQLException ex ) { throw new ProcessException ( - 1 , ex . getMessage ( ) , ex ) ; } catch ( MdwException ex ) { throw new ProcessException ( - 1 , ex . getMessage ( ) , ex ) ; } } }
Handles the work Transitions for the passed in collection of Items
438
13
13,887
void startProcessInstance ( ProcessInstance processInstanceVO , int delay ) throws ProcessException { try { Process process = getProcessDefinition ( processInstanceVO ) ; edao . setProcessInstanceStatus ( processInstanceVO . getId ( ) , WorkStatus . STATUS_PENDING_PROCESS ) ; // setProcessInstanceStatus will really set to STATUS_IN_PROGRESS - hint to set START_DT as well if ( logger . isInfoEnabled ( ) ) { logger . info ( logtag ( processInstanceVO . getProcessId ( ) , processInstanceVO . getId ( ) , processInstanceVO . getMasterRequestId ( ) ) , WorkStatus . LOGMSG_PROC_START + " - " + process . getQualifiedName ( ) + ( processInstanceVO . isEmbedded ( ) ? ( " (embedded process " + process . getId ( ) + ")" ) : ( "/" + process . getVersionString ( ) ) ) ) ; } notifyMonitors ( processInstanceVO , WorkStatus . LOGMSG_PROC_START ) ; // get start activity ID Long startActivityId ; if ( processInstanceVO . isEmbedded ( ) ) { edao . setProcessInstanceStatus ( processInstanceVO . getId ( ) , WorkStatus . STATUS_PENDING_PROCESS ) ; startActivityId = process . getStartActivity ( ) . getId ( ) ; } else { Activity startActivity = process . getStartActivity ( ) ; if ( startActivity == null ) { throw new ProcessException ( "Transition has not been defined for START event! ProcessID = " + process . getId ( ) ) ; } startActivityId = startActivity . getId ( ) ; } InternalEvent event = InternalEvent . createActivityStartMessage ( startActivityId , processInstanceVO . getId ( ) , null , processInstanceVO . getMasterRequestId ( ) , EventType . EVENTNAME_START + ":" ) ; if ( delay > 0 ) { String msgid = ScheduledEvent . INTERNAL_EVENT_PREFIX + processInstanceVO . getId ( ) + "start" + startActivityId ; this . sendDelayedInternalEvent ( event , delay , msgid , false ) ; } else sendInternalEvent ( event ) ; } catch ( Exception ex ) { logger . severeException ( ex . getMessage ( ) , ex ) ; throw new ProcessException ( ex . getMessage ( ) ) ; } }
Starting a process instance which has been created already . The method sets the status to In Progress find the start activity and sends an internal message to start the activity
529
31
13,888
void failActivityInstance ( InternalEvent event , ProcessInstance processInst , Long activityId , Long activityInstId , BaseActivity activity , Throwable cause ) throws DataAccessException , MdwException , SQLException { String tag = logtag ( processInst . getProcessId ( ) , processInst . getId ( ) , activityId , activityInstId ) ; logger . severeException ( "Failed to execute activity - " + cause . getClass ( ) . getName ( ) , cause ) ; String compCode = null ; String statusMsg = buildStatusMessage ( cause ) ; try { ActivityInstance actInstVO = null ; if ( activity != null && activityInstId != null ) { activity . setReturnMessage ( statusMsg ) ; actInstVO = edao . getActivityInstance ( activityInstId ) ; failActivityInstance ( actInstVO , statusMsg , processInst , tag , cause . getClass ( ) . getName ( ) ) ; compCode = activity . getReturnCode ( ) ; } if ( ! AdapterActivity . COMPCODE_AUTO_RETRY . equals ( compCode ) ) { DocumentReference docRef = createActivityExceptionDocument ( processInst , actInstVO , activity , cause ) ; InternalEvent outgoingMsg = InternalEvent . createActivityErrorMessage ( activityId , activityInstId , processInst . getId ( ) , compCode , event . getMasterRequestId ( ) , statusMsg . length ( ) > 2000 ? statusMsg . substring ( 0 , 1999 ) : statusMsg , docRef . getDocumentId ( ) ) ; sendInternalEvent ( outgoingMsg ) ; } } catch ( Exception ex ) { logger . severeException ( "Exception thrown during failActivityInstance" , ex ) ; throw ex ; } }
Reports the error status of the activity instance to the activity manager
368
12
13,889
private Transition findTaskActionWorkTransition ( ProcessInstance parentInstance , ActivityInstance activityInstance , String taskAction ) { if ( taskAction == null ) return null ; Process processVO = getProcessDefinition ( parentInstance ) ; Transition workTransVO = processVO . getTransition ( activityInstance . getActivityId ( ) , EventType . RESUME , taskAction ) ; if ( workTransVO == null ) { // try upper case workTransVO = processVO . getTransition ( activityInstance . getActivityId ( ) , EventType . RESUME , taskAction . toUpperCase ( ) ) ; } if ( workTransVO == null ) { workTransVO = processVO . getTransition ( activityInstance . getActivityId ( ) , EventType . FINISH , taskAction ) ; } return workTransVO ; }
Look up the appropriate work transition for an embedded exception handling subprocess .
174
14
13,890
private void cancelProcessInstanceTree ( ProcessInstance pi ) throws Exception { if ( pi . getStatusCode ( ) . equals ( WorkStatus . STATUS_COMPLETED ) || pi . getStatusCode ( ) . equals ( WorkStatus . STATUS_CANCELLED ) ) { throw new ProcessException ( "ProcessInstance is not in a cancellable state" ) ; } List < ProcessInstance > childInstances = edao . getChildProcessInstances ( pi . getId ( ) ) ; for ( ProcessInstance child : childInstances ) { if ( ! child . getStatusCode ( ) . equals ( WorkStatus . STATUS_COMPLETED ) && ! child . getStatusCode ( ) . equals ( WorkStatus . STATUS_CANCELLED ) ) { this . cancelProcessInstanceTree ( child ) ; } else { logger . info ( "Descendent ProcessInstance in not in a cancellable state. ProcessInstanceId=" + child . getId ( ) ) ; } } this . cancelProcessInstance ( pi ) ; }
Cancels the process instance as well as all descendant process instances . Deregisters associated event wait instances .
218
23
13,891
private void cancelProcessInstance ( ProcessInstance pProcessInst ) throws Exception { edao . cancelTransitionInstances ( pProcessInst . getId ( ) , "ProcessInstance has been cancelled." , null ) ; edao . setProcessInstanceStatus ( pProcessInst . getId ( ) , WorkStatus . STATUS_CANCELLED ) ; edao . removeEventWaitForProcessInstance ( pProcessInst . getId ( ) ) ; this . cancelTasksOfProcessInstance ( pProcessInst ) ; }
Cancels a single process instance . It cancels all active transition instances all event wait instances and sets the process instance into canceled status .
108
28
13,892
private void resumeActivityInstance ( ActivityInstance actInst , String pCompletionCode , Long documentId , String message , int delay ) throws MdwException , SQLException { ProcessInstance pi = edao . getProcessInstance ( actInst . getProcessInstanceId ( ) ) ; if ( ! this . isProcessInstanceResumable ( pi ) ) { logger . info ( "ProcessInstance in NOT resumable. ProcessInstanceId:" + pi . getId ( ) ) ; } InternalEvent outgoingMsg = InternalEvent . createActivityNotifyMessage ( actInst , EventType . RESUME , pi . getMasterRequestId ( ) , pCompletionCode ) ; if ( documentId != null ) { // should be always true outgoingMsg . setSecondaryOwnerType ( OwnerType . DOCUMENT ) ; outgoingMsg . setSecondaryOwnerId ( documentId ) ; } if ( message != null && message . length ( ) < 2500 ) { outgoingMsg . addParameter ( "ExternalEventMessage" , message ) ; } if ( this . isProcessInstanceProgressable ( pi ) ) { edao . setProcessInstanceStatus ( pi . getId ( ) , WorkStatus . STATUS_IN_PROGRESS ) ; } if ( delay > 0 ) { this . sendDelayedInternalEvent ( outgoingMsg , delay , ScheduledEvent . INTERNAL_EVENT_PREFIX + actInst . getId ( ) , false ) ; } else { this . sendInternalEvent ( outgoingMsg ) ; } }
Sends a RESUME internal event to resume the activity instance .
319
13
13,893
protected VelocityContext createVelocityContext ( ) throws ActivityException { try { VelocityContext context = null ; String toolboxFile = getAttributeValueSmart ( VELOCITY_TOOLBOX_FILE ) ; if ( toolboxFile != null && FileHelper . fileExistsOnClasspath ( toolboxFile ) ) { throw new ActivityException ( "TODO: Velocity Toolbox Support" ) ; // XMLToolboxManager toolboxManager = new XMLToolboxManager(); // toolboxManager.load(FileHelper.fileInputStreamFromClasspath(toolboxFile)); // context = new VelocityContext(toolboxManager.getToolbox(toolboxFile)); } else { context = new VelocityContext ( ) ; } Process processVO = getMainProcessDefinition ( ) ; List < Variable > varVOs = processVO . getVariables ( ) ; for ( Variable variableVO : varVOs ) { String variableName = variableVO . getName ( ) ; Object variableValue = getVariableValue ( variableName ) ; context . put ( variableName , variableValue ) ; } return context ; } catch ( Exception ex ) { throw new ActivityException ( - 1 , ex . getMessage ( ) , ex ) ; } }
Creates the velocity context adding process variables as parameters .
256
11
13,894
protected Map < String , Object > getAdditionalScriptBindings ( ) { Map < String , Object > addlBindings = new HashMap < String , Object > ( 1 ) ; addlBindings . put ( VELOCITY_OUTPUT , velocityOutput ) ; return addlBindings ; }
Gets additional bindings for script execution adding the velocity output string as a special bind value .
65
18
13,895
public String handleEventMessage ( String message , Object messageObj , Map < String , String > metaInfo ) throws EventHandlerException { return null ; }
This is for non - Camel style event handlers . It is not used here . Overriding has no effect in the context of a Camel route .
31
30
13,896
public void scheduleInternalEvent ( String name , Date time , String message , String reference ) { schedule ( name , time , message , reference ) ; }
Schedule a timer task or a delayed event
31
9
13,897
@ Override @ Path ( "/{dataType}" ) public JSONObject get ( String path , Map < String , String > headers ) throws ServiceException , JSONException { String dataType = getSegment ( path , 1 ) ; if ( dataType == null ) throw new ServiceException ( "Missing path segment: {dataType}" ) ; try { BaselineData baselineData = DataAccess . getBaselineData ( ) ; if ( dataType . equals ( "VariableTypes" ) ) { List < VariableType > variableTypes = baselineData . getVariableTypes ( ) ; JSONArray jsonArray = new JSONArray ( ) ; for ( VariableType variableType : variableTypes ) jsonArray . put ( variableType . getJson ( ) ) ; return new JsonArray ( jsonArray ) . getJson ( ) ; } else if ( dataType . equals ( "TaskCategories" ) ) { List < TaskCategory > taskCats = new ArrayList < TaskCategory > ( ) ; taskCats . addAll ( baselineData . getTaskCategories ( ) . values ( ) ) ; Collections . sort ( taskCats ) ; JSONArray jsonArray = new JSONArray ( ) ; for ( TaskCategory taskCat : taskCats ) jsonArray . put ( taskCat . getJson ( ) ) ; return new JsonArray ( jsonArray ) . getJson ( ) ; } else { throw new ServiceException ( "Unsupported dataType: " + dataType ) ; } } catch ( Exception ex ) { throw new ServiceException ( ex . getMessage ( ) , ex ) ; } }
Retrieve variableTypes or taskCategories .
337
9
13,898
private ProcessInstance getProcInstFromDB ( Long procInstId ) throws DataAccessException { TransactionWrapper transaction = null ; EngineDataAccessDB edao = new EngineDataAccessDB ( ) ; try { transaction = edao . startTransaction ( ) ; return edao . getProcessInstance ( procInstId ) ; } catch ( SQLException e ) { logger . severe ( "InvokeSubProcessActivity -> Failed to load process instance for " + procInstId ) ; return null ; } finally { edao . stopTransaction ( transaction ) ; } }
Method to get the Process Instance from the database
118
10
13,899
public List < String > getRecipients ( String workgroupsAttr , String expressionAttr ) throws DataAccessException , ParseException { List < String > recipients = new ArrayList <> ( ) ; if ( workgroupsAttr != null ) { String workgroups = context . getAttribute ( workgroupsAttr ) ; if ( workgroups != null && ! workgroups . isEmpty ( ) ) { for ( String groupEmail : getGroupEmails ( StringHelper . parseList ( workgroups ) ) ) { if ( ! recipients . contains ( groupEmail ) ) recipients . add ( groupEmail ) ; } } } if ( expressionAttr != null ) { String expression = context . getAttribute ( expressionAttr ) ; if ( expression != null && ! expression . isEmpty ( ) ) { List < String > expressionEmails ; if ( expression . indexOf ( "${" ) >= 0 ) expressionEmails = getRecipientsFromExpression ( expression ) ; else expressionEmails = Arrays . asList ( expression . split ( "," ) ) ; for ( String expressionEmail : expressionEmails ) { if ( ! recipients . contains ( expressionEmail ) ) recipients . add ( expressionEmail ) ; } } } return recipients ; }
Default behavior returns the UNION of addresses specified via the expression attribute along with those specified by the designated workgroups attribute .
261
24