idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
17,300
private Set < CacheKey > getCacheKeys ( ) { Set < CacheKey > cacheKeys = new HashSet < CacheKey > ( ) ; Applications apps = registry . getApplicationsFromLocalRegionOnly ( ) ; for ( Application app : apps . getRegisteredApplications ( ) ) { for ( InstanceInfo instanceInfo : app . getInstances ( ) ) { String localAccountId = getAccountId ( instanceInfo , accountId ) ; String asgName = instanceInfo . getASGName ( ) ; if ( asgName != null ) { CacheKey key = new CacheKey ( localAccountId , asgName ) ; cacheKeys . add ( key ) ; } } } return cacheKeys ; }
Get the cacheKeys of all the ASG to which query AWS for .
17,301
private static boolean maybeReadTimeOut ( Throwable e ) { do { if ( IOException . class . isInstance ( e ) ) { String message = e . getMessage ( ) . toLowerCase ( ) ; Matcher matcher = READ_TIME_OUT_PATTERN . matcher ( message ) ; if ( matcher . find ( ) ) { return true ; } } e = e . getCause ( ) ; } while ( e != null ) ; return false ; }
Check if the exception is socket read time out exception
17,302
public synchronized void setInstanceStatus ( InstanceStatus status ) { InstanceStatus next = instanceStatusMapper . map ( status ) ; if ( next == null ) { return ; } InstanceStatus prev = instanceInfo . setStatus ( next ) ; if ( prev != null ) { for ( StatusChangeListener listener : listeners . values ( ) ) { try { listener . notify ( new StatusChangeEvent ( prev , next ) ) ; } catch ( Exception e ) { logger . warn ( "failed to notify listener: {}" , listener . getId ( ) , e ) ; } } } }
Set the status of this instance . Application can use this to indicate whether it is ready to receive traffic . Setting the status here also notifies all registered listeners of a status change event .
17,303
public void bind ( ) throws MalformedURLException { InstanceInfo myInfo = ApplicationInfoManager . getInstance ( ) . getInfo ( ) ; String myInstanceId = ( ( AmazonInfo ) myInfo . getDataCenterInfo ( ) ) . get ( AmazonInfo . MetaDataKey . instanceId ) ; String myZone = ( ( AmazonInfo ) myInfo . getDataCenterInfo ( ) ) . get ( AmazonInfo . MetaDataKey . availabilityZone ) ; final List < String > ips = getCandidateIps ( ) ; Ordering < NetworkInterface > ipsOrder = Ordering . natural ( ) . onResultOf ( new Function < NetworkInterface , Integer > ( ) { public Integer apply ( NetworkInterface networkInterface ) { return ips . indexOf ( networkInterface . getPrivateIpAddress ( ) ) ; } } ) ; AmazonEC2 ec2Service = getEC2Service ( ) ; String subnetId = instanceData ( myInstanceId , ec2Service ) . getSubnetId ( ) ; DescribeNetworkInterfacesResult result = ec2Service . describeNetworkInterfaces ( new DescribeNetworkInterfacesRequest ( ) . withFilters ( new Filter ( "private-ip-address" , ips ) ) . withFilters ( new Filter ( "status" , Lists . newArrayList ( "available" ) ) ) . withFilters ( new Filter ( "subnet-id" , Lists . newArrayList ( subnetId ) ) ) ) ; if ( result . getNetworkInterfaces ( ) . isEmpty ( ) ) { logger . info ( "No ip is free to be associated with this instance. Candidate ips are: {} for zone: {}" , ips , myZone ) ; } else { NetworkInterface selected = ipsOrder . min ( result . getNetworkInterfaces ( ) ) ; ec2Service . attachNetworkInterface ( new AttachNetworkInterfaceRequest ( ) . withNetworkInterfaceId ( selected . getNetworkInterfaceId ( ) ) . withDeviceIndex ( 1 ) . withInstanceId ( myInstanceId ) ) ; } }
Binds an ENI to the instance .
17,304
public void unbind ( ) throws Exception { InstanceInfo myInfo = applicationInfoManager . getInfo ( ) ; String myInstanceId = ( ( AmazonInfo ) myInfo . getDataCenterInfo ( ) ) . get ( AmazonInfo . MetaDataKey . instanceId ) ; AmazonEC2 ec2 = getEC2Service ( ) ; List < InstanceNetworkInterface > result = instanceData ( myInstanceId , ec2 ) . getNetworkInterfaces ( ) ; List < String > ips = getCandidateIps ( ) ; for ( InstanceNetworkInterface networkInterface : result ) { if ( ips . contains ( networkInterface . getPrivateIpAddress ( ) ) ) { String attachmentId = networkInterface . getAttachment ( ) . getAttachmentId ( ) ; ec2 . detachNetworkInterface ( new DetachNetworkInterfaceRequest ( ) . withAttachmentId ( attachmentId ) ) ; break ; } } }
Unbind the IP that this instance is associated with .
17,305
public List < String > getCandidateIps ( ) throws MalformedURLException { InstanceInfo myInfo = applicationInfoManager . getInfo ( ) ; String myZone = ( ( AmazonInfo ) myInfo . getDataCenterInfo ( ) ) . get ( AmazonInfo . MetaDataKey . availabilityZone ) ; Collection < String > candidates = clientConfig . shouldUseDnsForFetchingServiceUrls ( ) ? getIPsForZoneFromDNS ( myZone ) : getIPsForZoneFromConfig ( myZone ) ; if ( candidates == null || candidates . size ( ) == 0 ) { throw new RuntimeException ( "Could not get any ips from the pool for zone :" + myZone ) ; } List < String > ips = Lists . newArrayList ( ) ; for ( String candidate : candidates ) { String host = new URL ( candidate ) . getHost ( ) ; if ( InetAddresses . isInetAddress ( host ) ) { ips . add ( host ) ; } else { String firstPartOfHost = Splitter . on ( "." ) . splitToList ( host ) . get ( 0 ) ; List < String > noIpPrefix = Splitter . on ( "-" ) . splitToList ( firstPartOfHost ) . subList ( 1 , 5 ) ; String ip = Joiner . on ( "." ) . join ( noIpPrefix ) ; if ( InetAddresses . isInetAddress ( ip ) ) { ips . add ( ip ) ; } else { throw new IllegalArgumentException ( "Illegal internal hostname " + host + " translated to '" + ip + "'" ) ; } } } return ips ; }
Based on shouldUseDnsForFetchingServiceUrls configuration either retrieves candidates from dns records or from configuration properties .
17,306
public void populateInstanceCountMap ( Map < String , AtomicInteger > instanceCountMap ) { for ( Application app : this . getRegisteredApplications ( ) ) { for ( InstanceInfo info : app . getInstancesAsIsFromEureka ( ) ) { AtomicInteger instanceCount = instanceCountMap . computeIfAbsent ( info . getStatus ( ) . name ( ) , k -> new AtomicInteger ( 0 ) ) ; instanceCount . incrementAndGet ( ) ; } } }
Populates the provided instance count map . The instance count map is used as part of the general app list synchronization mechanism .
17,307
public static String getReconcileHashCode ( Map < String , AtomicInteger > instanceCountMap ) { StringBuilder reconcileHashCode = new StringBuilder ( 75 ) ; for ( Map . Entry < String , AtomicInteger > mapEntry : instanceCountMap . entrySet ( ) ) { reconcileHashCode . append ( mapEntry . getKey ( ) ) . append ( STATUS_DELIMITER ) . append ( mapEntry . getValue ( ) . get ( ) ) . append ( STATUS_DELIMITER ) ; } return reconcileHashCode . toString ( ) ; }
Gets the reconciliation hashcode . The hashcode is used to determine whether the applications list has changed since the last time it was acquired .
17,308
public void shuffleAndIndexInstances ( Map < String , Applications > remoteRegionsRegistry , EurekaClientConfig clientConfig , InstanceRegionChecker instanceRegionChecker ) { shuffleInstances ( clientConfig . shouldFilterOnlyUpInstances ( ) , true , remoteRegionsRegistry , clientConfig , instanceRegionChecker ) ; }
Shuffles a whole region so that the instances will not always be returned in the same order .
17,309
public AtomicLong getNextIndex ( String virtualHostname , boolean secure ) { Map < String , VipIndexSupport > index = ( secure ) ? secureVirtualHostNameAppMap : virtualHostNameAppMap ; return Optional . ofNullable ( index . get ( virtualHostname . toUpperCase ( Locale . ROOT ) ) ) . map ( VipIndexSupport :: getRoundRobinIndex ) . orElse ( null ) ; }
Gets the next round - robin index for the given virtual host name . This index is reset after every registry fetch cycle .
17,310
private void addInstanceToMap ( InstanceInfo info , String vipAddresses , Map < String , VipIndexSupport > vipMap ) { if ( vipAddresses != null ) { String [ ] vipAddressArray = vipAddresses . toUpperCase ( Locale . ROOT ) . split ( "," ) ; for ( String vipAddress : vipAddressArray ) { VipIndexSupport vis = vipMap . computeIfAbsent ( vipAddress , k -> new VipIndexSupport ( ) ) ; vis . instances . add ( info ) ; } } }
Add the instance to the given map based if the vip address matches with that of the instance . Note that an instance can be mapped to multiple vip addresses .
17,311
private void addInstancesToVIPMaps ( Application app , Map < String , VipIndexSupport > virtualHostNameAppMap , Map < String , VipIndexSupport > secureVirtualHostNameAppMap ) { for ( InstanceInfo info : app . getInstances ( ) ) { String vipAddresses = info . getVIPAddress ( ) ; if ( vipAddresses != null ) { addInstanceToMap ( info , vipAddresses , virtualHostNameAppMap ) ; } String secureVipAddresses = info . getSecureVipAddress ( ) ; if ( secureVipAddresses != null ) { addInstanceToMap ( info , secureVipAddresses , secureVirtualHostNameAppMap ) ; } } }
Adds the instances to the internal vip address map .
17,312
public void destroyResources ( ) { if ( eurekaConnCleaner != null ) { eurekaConnCleaner . execute ( connectionCleanerTask ) ; eurekaConnCleaner . shutdown ( ) ; } if ( apacheHttpClient != null ) { apacheHttpClient . close ( ) ; } }
Clean up resources .
17,313
public Set < String > getHealthCheckUrls ( ) { Set < String > healthCheckUrlSet = new LinkedHashSet < String > ( ) ; if ( this . isUnsecurePortEnabled && healthCheckUrl != null && ! healthCheckUrl . isEmpty ( ) ) { healthCheckUrlSet . add ( healthCheckUrl ) ; } if ( this . isSecurePortEnabled && secureHealthCheckUrl != null && ! secureHealthCheckUrl . isEmpty ( ) ) { healthCheckUrlSet . add ( secureHealthCheckUrl ) ; } return healthCheckUrlSet ; }
Gets the absolute URLs for the health check page for both secure and non - secure protocols . If the port is not enabled then the URL is excluded .
17,314
public synchronized InstanceStatus setStatus ( InstanceStatus status ) { if ( this . status != status ) { InstanceStatus prev = this . status ; this . status = status ; setIsDirty ( ) ; return prev ; } return null ; }
Set the status for this instance .
17,315
public static String getZone ( String [ ] availZones , InstanceInfo myInfo ) { String instanceZone = ( ( availZones == null || availZones . length == 0 ) ? "default" : availZones [ 0 ] ) ; if ( myInfo != null && myInfo . getDataCenterInfo ( ) . getName ( ) == DataCenterInfo . Name . Amazon ) { String awsInstanceZone = ( ( AmazonInfo ) myInfo . getDataCenterInfo ( ) ) . get ( AmazonInfo . MetaDataKey . availabilityZone ) ; if ( awsInstanceZone != null ) { instanceZone = awsInstanceZone ; } } return instanceZone ; }
Get the zone that a particular instance is in . Note that for AWS deployments myInfo should contain AWS dataCenterInfo which should contain the AWS zone of the instance and availZones is ignored .
17,316
public static synchronized DecoderWrapper resolveDecoder ( String name , String eurekaAccept ) { EurekaAccept accept = EurekaAccept . fromString ( eurekaAccept ) ; switch ( accept ) { case compact : return getDecoder ( JacksonJsonMini . class ) ; case full : default : return getDecoder ( name ) ; } }
Resolve the decoder to use based on the specified decoder name as well as the specified eurekaAccept . The eurekAccept trumps the decoder name if the decoder specified is one that is not valid for use for the specified eurekaAccept .
17,317
public static Map < String , Object > map ( Object ... objects ) { if ( objects . length % 2 != 0 ) { throw new ActivitiIllegalArgumentException ( "The input should always be even since we expect a list of key-value pairs!" ) ; } Map < String , Object > map = new HashMap < String , Object > ( ) ; for ( int i = 0 ; i < objects . length ; i += 2 ) { map . put ( ( String ) objects [ i ] , objects [ i + 1 ] ) ; } return map ; }
Helper method to easily create a map .
17,318
protected ProcessDefinition findProcessDefinition ( String processDefinitionKey , String tenantId ) { if ( tenantId == null || ProcessEngineConfiguration . NO_TENANT_ID . equals ( tenantId ) ) { return Context . getProcessEngineConfiguration ( ) . getDeploymentManager ( ) . findDeployedLatestProcessDefinitionByKey ( processDefinitionKey ) ; } else { return Context . getProcessEngineConfiguration ( ) . getDeploymentManager ( ) . findDeployedLatestProcessDefinitionByKeyAndTenantId ( processDefinitionKey , tenantId ) ; } }
Allow subclass to determine which version of a process to start .
17,319
protected void initializeVariables ( ExecutionEntity subProcessInstance , Map < String , Object > variables ) { subProcessInstance . setVariables ( variables ) ; }
Allow a subclass to override how variables are initialized .
17,320
protected void parseChildElements ( String elementName , BaseElement parentElement , BpmnModel model , XMLStreamReader xtr ) throws Exception { parseChildElements ( elementName , parentElement , null , model , xtr ) ; }
To BpmnModel converter convenience methods
17,321
protected void createVariableLocal ( String variableName , Object value , ExecutionEntity sourceActivityExecution ) { ensureVariableInstancesInitialized ( ) ; if ( variableInstances . containsKey ( variableName ) ) { throw new ActivitiException ( "variable '" + variableName + "' already exists. Use setVariableLocal if you want to overwrite the value" ) ; } createVariableInstance ( variableName , value , sourceActivityExecution ) ; }
only called when a new variable is created on this variable scope . This method is also responsible for propagating the creation of this variable to the history .
17,322
public ExecutionEntity createChildExecution ( ExecutionEntity parentExecutionEntity ) { ExecutionEntity childExecution = executionDataManager . create ( ) ; inheritCommonProperties ( parentExecutionEntity , childExecution ) ; childExecution . setParent ( parentExecutionEntity ) ; childExecution . setProcessDefinitionId ( parentExecutionEntity . getProcessDefinitionId ( ) ) ; childExecution . setProcessDefinitionKey ( parentExecutionEntity . getProcessDefinitionKey ( ) ) ; childExecution . setProcessInstanceId ( parentExecutionEntity . getProcessInstanceId ( ) != null ? parentExecutionEntity . getProcessInstanceId ( ) : parentExecutionEntity . getId ( ) ) ; childExecution . setParentProcessInstanceId ( parentExecutionEntity . getParentProcessInstanceId ( ) ) ; childExecution . setScope ( false ) ; parentExecutionEntity . addChildExecution ( childExecution ) ; insert ( childExecution , false ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Child execution {} created with parent {}" , childExecution , parentExecutionEntity . getId ( ) ) ; } if ( getEventDispatcher ( ) . isEnabled ( ) ) { getEventDispatcher ( ) . dispatchEvent ( ActivitiEventBuilder . createEntityEvent ( ActivitiEventType . ENTITY_CREATED , childExecution ) ) ; getEventDispatcher ( ) . dispatchEvent ( ActivitiEventBuilder . createEntityEvent ( ActivitiEventType . ENTITY_INITIALIZED , childExecution ) ) ; } return childExecution ; }
Creates a new execution . properties processDefinition processInstance and activity will be initialized .
17,323
protected void ensureSequenceFlowIdSet ( SequenceFlow sequenceFlow ) { if ( sequenceFlow . getId ( ) == null ) { sequenceFlow . setId ( "sequenceFlow-" + UUID . randomUUID ( ) . toString ( ) ) ; } }
BPMN element handling
17,324
protected void createEventVertex ( FlowElement flowElement ) { if ( ! graph . getStylesheet ( ) . getStyles ( ) . containsKey ( STYLE_EVENT ) ) { Hashtable < String , Object > eventStyle = new Hashtable < String , Object > ( ) ; eventStyle . put ( mxConstants . STYLE_SHAPE , mxConstants . SHAPE_ELLIPSE ) ; graph . getStylesheet ( ) . putCellStyle ( STYLE_EVENT , eventStyle ) ; } Object eventVertex = graph . insertVertex ( cellParent , flowElement . getId ( ) , "" , 0 , 0 , eventSize , eventSize , STYLE_EVENT ) ; generatedVertices . put ( flowElement . getId ( ) , eventVertex ) ; }
Graph cell creation
17,325
protected List < mxPoint > optimizeEdgePoints ( List < mxPoint > unoptimizedPointsList ) { List < mxPoint > optimizedPointsList = new ArrayList < mxPoint > ( ) ; for ( int i = 0 ; i < unoptimizedPointsList . size ( ) ; i ++ ) { boolean keepPoint = true ; mxPoint currentPoint = unoptimizedPointsList . get ( i ) ; if ( i > 0 && i != unoptimizedPointsList . size ( ) - 1 ) { mxPoint previousPoint = unoptimizedPointsList . get ( i - 1 ) ; mxPoint nextPoint = unoptimizedPointsList . get ( i + 1 ) ; if ( currentPoint . getX ( ) >= previousPoint . getX ( ) && currentPoint . getX ( ) <= nextPoint . getX ( ) && currentPoint . getY ( ) == previousPoint . getY ( ) && currentPoint . getY ( ) == nextPoint . getY ( ) ) { keepPoint = false ; } else if ( currentPoint . getY ( ) >= previousPoint . getY ( ) && currentPoint . getY ( ) <= nextPoint . getY ( ) && currentPoint . getX ( ) == previousPoint . getX ( ) && currentPoint . getX ( ) == nextPoint . getX ( ) ) { keepPoint = false ; } } if ( keepPoint ) { optimizedPointsList . add ( currentPoint ) ; } } return optimizedPointsList ; }
This method will remove any such points .
17,326
protected EventLoggerEventHandler getEventHandler ( ActivitiEvent event ) { Class < ? extends EventLoggerEventHandler > eventHandlerClass = null ; if ( event . getType ( ) . equals ( ActivitiEventType . ENTITY_INITIALIZED ) ) { Object entity = ( ( ActivitiEntityEvent ) event ) . getEntity ( ) ; if ( entity instanceof ExecutionEntity ) { ExecutionEntity executionEntity = ( ExecutionEntity ) entity ; if ( executionEntity . getProcessInstanceId ( ) . equals ( executionEntity . getId ( ) ) ) { eventHandlerClass = ProcessInstanceStartedEventHandler . class ; } } } else if ( event . getType ( ) . equals ( ActivitiEventType . ENTITY_DELETED ) ) { Object entity = ( ( ActivitiEntityEvent ) event ) . getEntity ( ) ; if ( entity instanceof ExecutionEntity ) { ExecutionEntity executionEntity = ( ExecutionEntity ) entity ; if ( executionEntity . getProcessInstanceId ( ) . equals ( executionEntity . getId ( ) ) ) { eventHandlerClass = ProcessInstanceEndedEventHandler . class ; } } } else { eventHandlerClass = eventHandlers . get ( event . getType ( ) ) ; } if ( eventHandlerClass != null ) { return instantiateEventHandler ( event , eventHandlerClass ) ; } return null ; }
Subclasses can override this if defaults are not ok
17,327
public void start ( ) { if ( isActive ) { return ; } log . info ( "Starting up the default async job executor [{}]." , getClass ( ) . getName ( ) ) ; if ( timerJobRunnable == null ) { timerJobRunnable = new AcquireTimerJobsRunnable ( this , processEngineConfiguration . getJobManager ( ) ) ; } if ( resetExpiredJobsRunnable == null ) { resetExpiredJobsRunnable = new ResetExpiredJobsRunnable ( this ) ; } if ( ! isMessageQueueMode && asyncJobsDueRunnable == null ) { asyncJobsDueRunnable = new AcquireAsyncJobsDueRunnable ( this ) ; } if ( ! isMessageQueueMode ) { initAsyncJobExecutionThreadPool ( ) ; startJobAcquisitionThread ( ) ; } startTimerAcquisitionThread ( ) ; startResetExpiredJobsThread ( ) ; isActive = true ; executeTemporaryJobs ( ) ; }
Starts the async executor
17,328
public synchronized void shutdown ( ) { if ( ! isActive ) { return ; } log . info ( "Shutting down the default async job executor [{}]." , getClass ( ) . getName ( ) ) ; if ( timerJobRunnable != null ) { timerJobRunnable . stop ( ) ; } if ( asyncJobsDueRunnable != null ) { asyncJobsDueRunnable . stop ( ) ; } if ( resetExpiredJobsRunnable != null ) { resetExpiredJobsRunnable . stop ( ) ; } stopResetExpiredJobsThread ( ) ; stopTimerAcquisitionThread ( ) ; stopJobAcquisitionThread ( ) ; stopExecutingAsyncJobs ( ) ; timerJobRunnable = null ; asyncJobsDueRunnable = null ; resetExpiredJobsRunnable = null ; isActive = false ; }
Shuts down the whole job executor
17,329
protected void stopJobAcquisitionThread ( ) { if ( asyncJobAcquisitionThread != null ) { try { asyncJobAcquisitionThread . join ( ) ; } catch ( InterruptedException e ) { log . warn ( "Interrupted while waiting for the async job acquisition thread to terminate" , e ) ; } asyncJobAcquisitionThread = null ; } }
Stops the acquisition thread
17,330
protected void stopResetExpiredJobsThread ( ) { if ( resetExpiredJobThread != null ) { try { resetExpiredJobThread . join ( ) ; } catch ( InterruptedException e ) { log . warn ( "Interrupted while waiting for the reset expired jobs thread to terminate" , e ) ; } resetExpiredJobThread = null ; } }
Stops the reset expired jobs thread
17,331
protected InputStream getDefaultDiagram ( String diagramImageFileName ) { String imageFileName = diagramImageFileName != null ? diagramImageFileName : getDefaultDiagramImageFileName ( ) ; InputStream imageStream = getClass ( ) . getResourceAsStream ( imageFileName ) ; if ( imageStream == null ) { throw new ActivitiImageException ( "Error occurred while getting default diagram image from file: " + imageFileName ) ; } return imageStream ; }
Get default diagram image as bytes array
17,332
public FlowElement getCurrentFlowElement ( ) { if ( currentFlowElement == null ) { String processDefinitionId = getProcessDefinitionId ( ) ; if ( processDefinitionId != null ) { org . activiti . bpmn . model . Process process = ProcessDefinitionUtil . getProcess ( processDefinitionId ) ; currentFlowElement = process . getFlowElement ( getCurrentActivityId ( ) , true ) ; } } return currentFlowElement ; }
The current flow element will be filled during operation execution
17,333
public ProcessEngineConfiguration addWsEndpointAddress ( QName endpointName , URL address ) { this . wsOverridenEndpointAddresses . put ( endpointName , address ) ; return this ; }
Add or replace the address of the given web - service endpoint with the given value
17,334
public void eventCancelledByEventGateway ( DelegateExecution execution ) { Context . getCommandContext ( ) . getExecutionEntityManager ( ) . deleteExecutionAndRelatedData ( ( ExecutionEntity ) execution , DeleteReason . EVENT_BASED_GATEWAY_CANCEL , false ) ; }
Should be subclassed by the more specific types . For an intermediate catch without type it s simply leaving the event .
17,335
public static void noSpace ( String string ) throws JSONException { int i , length = string . length ( ) ; if ( length == 0 ) { throw new JSONException ( "Empty string." ) ; } for ( i = 0 ; i < length ; i += 1 ) { if ( Character . isWhitespace ( string . charAt ( i ) ) ) { throw new JSONException ( "'" + string + "' contains a space character." ) ; } } }
Throw an exception if the string contains whitespace . Whitespace is not allowed in tagNames and attributes .
17,336
public static int setBit ( int value , int bitNumber , boolean bitValue ) { if ( bitValue ) { return setBitOn ( value , bitNumber ) ; } else { return setBitOff ( value , bitNumber ) ; } }
Set bit to 0 or 1 in the given int .
17,337
protected boolean lockJobIfNeeded ( ) { try { if ( job . isExclusive ( ) ) { processEngineConfiguration . getCommandExecutor ( ) . execute ( new LockExclusiveJobCmd ( job ) ) ; } } catch ( Throwable lockException ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "Could not lock exclusive job. Unlocking job so it can be acquired again. Catched exception: " + lockException . getMessage ( ) ) ; } unacquireJob ( ) ; return false ; } return true ; }
Returns true if lock succeeded or no lock was needed . Returns false if locking was unsuccessfull .
17,338
protected void dispatchJobCanceledEvents ( ExecutionEntity activityExecution ) { if ( activityExecution != null ) { List < JobEntity > jobs = activityExecution . getJobs ( ) ; for ( JobEntity job : jobs ) { if ( Context . getProcessEngineConfiguration ( ) . getEventDispatcher ( ) . isEnabled ( ) ) { Context . getProcessEngineConfiguration ( ) . getEventDispatcher ( ) . dispatchEvent ( ActivitiEventBuilder . createEntityEvent ( ActivitiEventType . JOB_CANCELED , job ) ) ; } } List < TimerJobEntity > timerJobs = activityExecution . getTimerJobs ( ) ; for ( TimerJobEntity job : timerJobs ) { if ( Context . getProcessEngineConfiguration ( ) . getEventDispatcher ( ) . isEnabled ( ) ) { Context . getProcessEngineConfiguration ( ) . getEventDispatcher ( ) . dispatchEvent ( ActivitiEventBuilder . createEntityEvent ( ActivitiEventType . JOB_CANCELED , job ) ) ; } } } }
dispatch job canceled event for job associated with given execution entity
17,339
protected void callActivityEndListeners ( DelegateExecution execution ) { Context . getCommandContext ( ) . getProcessEngineConfiguration ( ) . getListenerNotificationHelper ( ) . executeExecutionListeners ( activity , execution , ExecutionListener . EVENTNAME_END ) ; }
Since no transitions are followed when leaving the inner activity it is needed to call the end listeners yourself .
17,340
private ProcessExtensionModel convertJsonVariables ( ProcessExtensionModel processExtensionModel ) { if ( processExtensionModel != null && processExtensionModel . getExtensions ( ) != null && processExtensionModel . getExtensions ( ) . getProperties ( ) != null ) { for ( VariableDefinition variableDefinition : processExtensionModel . getExtensions ( ) . getProperties ( ) . values ( ) ) { if ( ! variableTypeMap . keySet ( ) . contains ( variableDefinition . getType ( ) ) || variableDefinition . getType ( ) . equals ( "json" ) ) { variableDefinition . setValue ( objectMapper . convertValue ( variableDefinition . getValue ( ) , JsonNode . class ) ) ; } } } return processExtensionModel ; }
Json variables need to be represented as JsonNode for engine to handle as Json Do this for any var marked as json or whose type is not recognised from the extension file
17,341
protected FlowElement getCurrentFlowElement ( final ExecutionEntity execution ) { if ( execution . getCurrentFlowElement ( ) != null ) { return execution . getCurrentFlowElement ( ) ; } else if ( execution . getCurrentActivityId ( ) != null ) { String processDefinitionId = execution . getProcessDefinitionId ( ) ; org . activiti . bpmn . model . Process process = ProcessDefinitionUtil . getProcess ( processDefinitionId ) ; String activityId = execution . getCurrentActivityId ( ) ; FlowElement currentFlowElement = process . getFlowElement ( activityId , true ) ; return currentFlowElement ; } return null ; }
Helper method to match the activityId of an execution with a FlowElement of the process definition referenced by the execution .
17,342
protected ExecutionEntity findFirstParentScopeExecution ( ExecutionEntity executionEntity ) { ExecutionEntityManager executionEntityManager = commandContext . getExecutionEntityManager ( ) ; ExecutionEntity parentScopeExecution = null ; ExecutionEntity currentlyExaminedExecution = executionEntityManager . findById ( executionEntity . getParentId ( ) ) ; while ( currentlyExaminedExecution != null && parentScopeExecution == null ) { if ( currentlyExaminedExecution . isScope ( ) ) { parentScopeExecution = currentlyExaminedExecution ; } else { currentlyExaminedExecution = executionEntityManager . findById ( currentlyExaminedExecution . getParentId ( ) ) ; } } return parentScopeExecution ; }
Returns the first parent execution of the provided execution that is a scope .
17,343
public static List < String > splitCommas ( String st ) { List < String > result = new ArrayList < String > ( ) ; int offset = 0 ; boolean inExpression = false ; for ( int i = 0 ; i < st . length ( ) ; i ++ ) { if ( ! inExpression && st . charAt ( i ) == ',' ) { if ( ( i - offset ) > 1 ) { result . add ( st . substring ( offset , i ) ) ; } offset = i + 1 ; } else if ( ( st . charAt ( i ) == '$' || st . charAt ( i ) == '#' ) && st . charAt ( i + 1 ) == '{' ) { inExpression = true ; } else if ( st . charAt ( i ) == '}' ) { inExpression = false ; } } if ( ( st . length ( ) - offset ) > 1 ) { result . add ( st . substring ( offset ) ) ; } return result ; }
split the given spring using commas if they are not inside an expression
17,344
public static List < ExecutionEntity > orderFromRootToLeaf ( Collection < ExecutionEntity > executions ) { List < ExecutionEntity > orderedList = new ArrayList < ExecutionEntity > ( executions . size ( ) ) ; HashSet < String > previousIds = new HashSet < String > ( ) ; for ( ExecutionEntity execution : executions ) { if ( execution . getParentId ( ) == null ) { orderedList . add ( execution ) ; previousIds . add ( execution . getId ( ) ) ; } } while ( orderedList . size ( ) < executions . size ( ) ) { for ( ExecutionEntity execution : executions ) { if ( ! previousIds . contains ( execution . getId ( ) ) && previousIds . contains ( execution . getParentId ( ) ) ) { orderedList . add ( execution ) ; previousIds . add ( execution . getId ( ) ) ; } } } return orderedList ; }
Takes in a collection of executions belonging to the same process instance . Orders the executions in a list first elements are the leaf last element is the root elements .
17,345
public static boolean isReachable ( String processDefinitionId , String sourceElementId , String targetElementId ) { Process process = ProcessDefinitionUtil . getProcess ( processDefinitionId ) ; FlowElement sourceFlowElement = process . getFlowElement ( sourceElementId , true ) ; FlowNode sourceElement = null ; if ( sourceFlowElement instanceof FlowNode ) { sourceElement = ( FlowNode ) sourceFlowElement ; } else if ( sourceFlowElement instanceof SequenceFlow ) { sourceElement = ( FlowNode ) ( ( SequenceFlow ) sourceFlowElement ) . getTargetFlowElement ( ) ; } FlowElement targetFlowElement = process . getFlowElement ( targetElementId , true ) ; FlowNode targetElement = null ; if ( targetFlowElement instanceof FlowNode ) { targetElement = ( FlowNode ) targetFlowElement ; } else if ( targetFlowElement instanceof SequenceFlow ) { targetElement = ( FlowNode ) ( ( SequenceFlow ) targetFlowElement ) . getTargetFlowElement ( ) ; } if ( sourceElement == null ) { throw new ActivitiException ( "Invalid sourceElementId '" + sourceElementId + "': no element found for this id n process definition '" + processDefinitionId + "'" ) ; } if ( targetElement == null ) { throw new ActivitiException ( "Invalid targetElementId '" + targetElementId + "': no element found for this id n process definition '" + processDefinitionId + "'" ) ; } Set < String > visitedElements = new HashSet < String > ( ) ; return isReachable ( process , sourceElement , targetElement , visitedElements ) ; }
Verifies if the element with the given source identifier can reach the element with the target identifier through following sequence flow .
17,346
protected BpmnModel extractBpmnModelFromEvent ( ActivitiEvent event ) { BpmnModel result = null ; if ( result == null && event . getProcessDefinitionId ( ) != null ) { ProcessDefinition processDefinition = ProcessDefinitionUtil . getProcessDefinition ( event . getProcessDefinitionId ( ) , true ) ; if ( processDefinition != null ) { result = Context . getProcessEngineConfiguration ( ) . getDeploymentManager ( ) . resolveProcessDefinition ( processDefinition ) . getBpmnModel ( ) ; } } return result ; }
In case no process - context is active this method attempts to extract a process - definition based on the event . In case it s an event related to an entity this can be deducted by inspecting the entity without additional queries to the database .
17,347
public void verifyProcessDefinitionsDoNotShareKeys ( Collection < ProcessDefinitionEntity > processDefinitions ) { Set < String > keySet = new LinkedHashSet < String > ( ) ; for ( ProcessDefinitionEntity processDefinition : processDefinitions ) { if ( keySet . contains ( processDefinition . getKey ( ) ) ) { throw new ActivitiException ( "The deployment contains process definitions with the same key (process id attribute), this is not allowed" ) ; } keySet . add ( processDefinition . getKey ( ) ) ; } }
Verifies that no two process definitions share the same key to prevent database unique index violation .
17,348
public void copyDeploymentValuesToProcessDefinitions ( DeploymentEntity deployment , List < ProcessDefinitionEntity > processDefinitions ) { String engineVersion = deployment . getEngineVersion ( ) ; String tenantId = deployment . getTenantId ( ) ; String deploymentId = deployment . getId ( ) ; for ( ProcessDefinitionEntity processDefinition : processDefinitions ) { if ( engineVersion != null ) { processDefinition . setEngineVersion ( engineVersion ) ; } if ( tenantId != null ) { processDefinition . setTenantId ( tenantId ) ; } processDefinition . setDeploymentId ( deploymentId ) ; } }
Updates all the process definition entities to match the deployment s values for tenant engine version and deployment id .
17,349
public void setResourceNamesOnProcessDefinitions ( ParsedDeployment parsedDeployment ) { for ( ProcessDefinitionEntity processDefinition : parsedDeployment . getAllProcessDefinitions ( ) ) { String resourceName = parsedDeployment . getResourceForProcessDefinition ( processDefinition ) . getName ( ) ; processDefinition . setResourceName ( resourceName ) ; } }
Updates all the process definition entities to have the correct resource names .
17,350
public ProcessDefinitionEntity getMostRecentVersionOfProcessDefinition ( ProcessDefinitionEntity processDefinition ) { String key = processDefinition . getKey ( ) ; String tenantId = processDefinition . getTenantId ( ) ; ProcessDefinitionEntityManager processDefinitionManager = Context . getCommandContext ( ) . getProcessEngineConfiguration ( ) . getProcessDefinitionEntityManager ( ) ; ProcessDefinitionEntity existingDefinition = null ; if ( tenantId != null && ! tenantId . equals ( ProcessEngineConfiguration . NO_TENANT_ID ) ) { existingDefinition = processDefinitionManager . findLatestProcessDefinitionByKeyAndTenantId ( key , tenantId ) ; } else { existingDefinition = processDefinitionManager . findLatestProcessDefinitionByKey ( key ) ; } return existingDefinition ; }
Gets the most recent persisted process definition that matches this one for tenant and key . If none is found returns null . This method assumes that the tenant and key are properly set on the process definition entity .
17,351
public void updateTimersAndEvents ( ProcessDefinitionEntity processDefinition , ProcessDefinitionEntity previousProcessDefinition , ParsedDeployment parsedDeployment ) { Process process = parsedDeployment . getProcessModelForProcessDefinition ( processDefinition ) ; BpmnModel bpmnModel = parsedDeployment . getBpmnModelForProcessDefinition ( processDefinition ) ; eventSubscriptionManager . removeObsoleteMessageEventSubscriptions ( previousProcessDefinition ) ; eventSubscriptionManager . addMessageEventSubscriptions ( processDefinition , process , bpmnModel ) ; eventSubscriptionManager . removeObsoleteSignalEventSubScription ( previousProcessDefinition ) ; eventSubscriptionManager . addSignalEventSubscriptions ( Context . getCommandContext ( ) , processDefinition , process , bpmnModel ) ; timerManager . removeObsoleteTimers ( processDefinition ) ; timerManager . scheduleTimers ( processDefinition , process ) ; }
Updates all timers and events for the process definition . This removes obsolete message and signal subscriptions and timers and adds new ones .
17,352
public static void createCopyOfSubProcessExecutionForCompensation ( ExecutionEntity subProcessExecution ) { EventSubscriptionEntityManager eventSubscriptionEntityManager = Context . getCommandContext ( ) . getEventSubscriptionEntityManager ( ) ; List < EventSubscriptionEntity > eventSubscriptions = eventSubscriptionEntityManager . findEventSubscriptionsByExecutionAndType ( subProcessExecution . getId ( ) , "compensate" ) ; List < CompensateEventSubscriptionEntity > compensateEventSubscriptions = new ArrayList < CompensateEventSubscriptionEntity > ( ) ; for ( EventSubscriptionEntity event : eventSubscriptions ) { if ( event instanceof CompensateEventSubscriptionEntity ) { compensateEventSubscriptions . add ( ( CompensateEventSubscriptionEntity ) event ) ; } } if ( CollectionUtil . isNotEmpty ( compensateEventSubscriptions ) ) { ExecutionEntity processInstanceExecutionEntity = subProcessExecution . getProcessInstance ( ) ; ExecutionEntity eventScopeExecution = Context . getCommandContext ( ) . getExecutionEntityManager ( ) . createChildExecution ( processInstanceExecutionEntity ) ; eventScopeExecution . setActive ( false ) ; eventScopeExecution . setEventScope ( true ) ; eventScopeExecution . setCurrentFlowElement ( subProcessExecution . getCurrentFlowElement ( ) ) ; new SubProcessVariableSnapshotter ( ) . setVariablesSnapshots ( subProcessExecution , eventScopeExecution ) ; for ( CompensateEventSubscriptionEntity eventSubscriptionEntity : compensateEventSubscriptions ) { eventSubscriptionEntityManager . delete ( eventSubscriptionEntity ) ; CompensateEventSubscriptionEntity newSubscription = eventSubscriptionEntityManager . insertCompensationEvent ( eventScopeExecution , eventSubscriptionEntity . getActivityId ( ) ) ; newSubscription . setConfiguration ( eventSubscriptionEntity . getConfiguration ( ) ) ; newSubscription . setCreated ( eventSubscriptionEntity . getCreated ( ) ) ; } CompensateEventSubscriptionEntity eventSubscription = eventSubscriptionEntityManager . insertCompensationEvent ( processInstanceExecutionEntity , eventScopeExecution . getCurrentFlowElement ( ) . getId ( ) ) ; eventSubscription . setConfiguration ( eventScopeExecution . getId ( ) ) ; } }
Creates a new event scope execution and moves existing event subscriptions to this new execution
17,353
protected String determineResourceName ( final Resource resource ) { String resourceName = null ; if ( resource instanceof ContextResource ) { resourceName = ( ( ContextResource ) resource ) . getPathWithinContext ( ) ; } else if ( resource instanceof ByteArrayResource ) { resourceName = resource . getDescription ( ) ; } else { try { resourceName = resource . getFile ( ) . getAbsolutePath ( ) ; } catch ( IOException e ) { resourceName = resource . getFilename ( ) ; } } return resourceName ; }
Determines the name to be used for the provided resource .
17,354
public JSONArray getJSONArray ( int index ) throws JSONException { Object o = get ( index ) ; if ( o instanceof JSONArray ) { return ( JSONArray ) o ; } throw new JSONException ( "JSONArray[" + index + "] is not a JSONArray." ) ; }
Get the JSONArray associated with an index .
17,355
public synchronized static void destroy ( ) { if ( isInitialized ( ) ) { Map < String , ProcessEngine > engines = new HashMap < String , ProcessEngine > ( processEngines ) ; processEngines = new HashMap < String , ProcessEngine > ( ) ; for ( String processEngineName : engines . keySet ( ) ) { ProcessEngine processEngine = engines . get ( processEngineName ) ; try { processEngine . close ( ) ; } catch ( Exception e ) { log . error ( "exception while closing {}" , ( processEngineName == null ? "the default process engine" : "process engine " + processEngineName ) , e ) ; } } processEngineInfosByName . clear ( ) ; processEngineInfosByResourceUrl . clear ( ) ; processEngineInfos . clear ( ) ; setInitialized ( false ) ; } }
closes all process engines . This method should be called when the server shuts down .
17,356
public void setIndentStep ( int indentStep ) { StringBuilder s = new StringBuilder ( ) ; for ( ; indentStep > 0 ; indentStep -- ) s . append ( ' ' ) ; setIndentStep ( s . toString ( ) ) ; }
Set the current indent step .
17,357
protected void setProcessDefinitionDiagramNames ( ParsedDeployment parsedDeployment ) { Map < String , ResourceEntity > resources = parsedDeployment . getDeployment ( ) . getResources ( ) ; for ( ProcessDefinitionEntity processDefinition : parsedDeployment . getAllProcessDefinitions ( ) ) { String diagramResourceName = ResourceNameUtil . getProcessDiagramResourceNameFromDeployment ( processDefinition , resources ) ; processDefinition . setDiagramResourceName ( diagramResourceName ) ; } }
Updates all the process definition entities to have the correct diagram resource name . Must be called after createAndPersistNewDiagramsAsNeeded to ensure that any newly - created diagrams already have their resources attached to the deployment .
17,358
protected Map < ProcessDefinitionEntity , ProcessDefinitionEntity > getPreviousVersionsOfProcessDefinitions ( ParsedDeployment parsedDeployment ) { Map < ProcessDefinitionEntity , ProcessDefinitionEntity > result = new LinkedHashMap < ProcessDefinitionEntity , ProcessDefinitionEntity > ( ) ; for ( ProcessDefinitionEntity newDefinition : parsedDeployment . getAllProcessDefinitions ( ) ) { ProcessDefinitionEntity existingDefinition = bpmnDeploymentHelper . getMostRecentVersionOfProcessDefinition ( newDefinition ) ; if ( existingDefinition != null ) { result . put ( newDefinition , existingDefinition ) ; } } return result ; }
Constructs a map from new ProcessDefinitionEntities to the previous version by key and tenant . If no previous version exists no map entry is created .
17,359
protected void setProcessDefinitionVersionsAndIds ( ParsedDeployment parsedDeployment , Map < ProcessDefinitionEntity , ProcessDefinitionEntity > mapNewToOldProcessDefinitions ) { CommandContext commandContext = Context . getCommandContext ( ) ; for ( ProcessDefinitionEntity processDefinition : parsedDeployment . getAllProcessDefinitions ( ) ) { int version = 1 ; ProcessDefinitionEntity latest = mapNewToOldProcessDefinitions . get ( processDefinition ) ; if ( latest != null ) { version = latest . getVersion ( ) + 1 ; } processDefinition . setVersion ( version ) ; processDefinition . setId ( getIdForNewProcessDefinition ( processDefinition ) ) ; if ( commandContext . getProcessEngineConfiguration ( ) . getEventDispatcher ( ) . isEnabled ( ) ) { commandContext . getProcessEngineConfiguration ( ) . getEventDispatcher ( ) . dispatchEvent ( ActivitiEventBuilder . createEntityEvent ( ActivitiEventType . ENTITY_CREATED , processDefinition ) ) ; } } }
Sets the version on each process definition entity and the identifier . If the map contains an older version for a process definition then the version is set to that older entity s version plus one ; otherwise it is set to 1 . Also dispatches an ENTITY_CREATED event .
17,360
protected void persistProcessDefinitionsAndAuthorizations ( ParsedDeployment parsedDeployment ) { CommandContext commandContext = Context . getCommandContext ( ) ; ProcessDefinitionEntityManager processDefinitionManager = commandContext . getProcessDefinitionEntityManager ( ) ; for ( ProcessDefinitionEntity processDefinition : parsedDeployment . getAllProcessDefinitions ( ) ) { processDefinitionManager . insert ( processDefinition , false ) ; bpmnDeploymentHelper . addAuthorizationsForNewProcessDefinition ( parsedDeployment . getProcessModelForProcessDefinition ( processDefinition ) , processDefinition ) ; } }
Saves each process definition . It is assumed that the deployment is new the definitions have never been saved before and that they have all their values properly set up .
17,361
protected void makeProcessDefinitionsConsistentWithPersistedVersions ( ParsedDeployment parsedDeployment ) { for ( ProcessDefinitionEntity processDefinition : parsedDeployment . getAllProcessDefinitions ( ) ) { ProcessDefinitionEntity persistedProcessDefinition = bpmnDeploymentHelper . getPersistedInstanceOfProcessDefinition ( processDefinition ) ; if ( persistedProcessDefinition != null ) { processDefinition . setId ( persistedProcessDefinition . getId ( ) ) ; processDefinition . setVersion ( persistedProcessDefinition . getVersion ( ) ) ; processDefinition . setSuspensionState ( persistedProcessDefinition . getSuspensionState ( ) ) ; } } }
Loads the persisted version of each process definition and set values on the in - memory version to be consistent .
17,362
public static Field getField ( String fieldName , Object object ) { return getField ( fieldName , object . getClass ( ) ) ; }
Returns the field of the given object or null if it doesn t exist .
17,363
public static Field getField ( String fieldName , Class < ? > clazz ) { Field field = null ; try { field = clazz . getDeclaredField ( fieldName ) ; } catch ( SecurityException e ) { throw new ActivitiException ( "not allowed to access field " + field + " on class " + clazz . getCanonicalName ( ) ) ; } catch ( NoSuchFieldException e ) { Class < ? > superClass = clazz . getSuperclass ( ) ; if ( superClass != null ) { return getField ( fieldName , superClass ) ; } } return field ; }
Returns the field of the given class or null if it doesn t exist .
17,364
private static String getValue ( JSONTokener x ) throws JSONException { char c ; char q ; StringBuffer sb ; do { c = x . next ( ) ; } while ( c == ' ' || c == '\t' ) ; switch ( c ) { case 0 : return null ; case '"' : case '\'' : q = c ; sb = new StringBuffer ( ) ; for ( ; ; ) { c = x . next ( ) ; if ( c == q ) { break ; } if ( c == 0 || c == '\n' || c == '\r' ) { throw x . syntaxError ( "Missing close quote '" + q + "'." ) ; } sb . append ( c ) ; } return sb . toString ( ) ; case ',' : x . back ( ) ; return "" ; default : x . back ( ) ; return x . nextTo ( ',' ) ; } }
Get the next value . The value can be wrapped in quotes . The value can be empty .
17,365
public static JSONArray rowToJSONArray ( JSONTokener x ) throws JSONException { JSONArray ja = new JSONArray ( ) ; for ( ; ; ) { String value = getValue ( x ) ; char c = x . next ( ) ; if ( value == null || ( ja . length ( ) == 0 && value . length ( ) == 0 && c != ',' ) ) { return null ; } ja . put ( value ) ; for ( ; ; ) { if ( c == ',' ) { break ; } if ( c != ' ' ) { if ( c == '\n' || c == '\r' || c == 0 ) { return ja ; } throw x . syntaxError ( "Bad character '" + c + "' (" + ( int ) c + ")." ) ; } c = x . next ( ) ; } } }
Produce a JSONArray of strings from a row of comma delimited values .
17,366
public static JSONObject rowToJSONObject ( JSONArray names , JSONTokener x ) throws JSONException { JSONArray ja = rowToJSONArray ( x ) ; return ja != null ? ja . toJSONObject ( names ) : null ; }
Produce a JSONObject from a row of comma delimited text using a parallel JSONArray of strings to provides the names of the elements .
17,367
public IdentityLinkEntity involveUser ( ExecutionEntity executionEntity , String userId , String type ) { for ( IdentityLinkEntity identityLink : executionEntity . getIdentityLinks ( ) ) { if ( identityLink . isUser ( ) && identityLink . getUserId ( ) . equals ( userId ) ) { return identityLink ; } } return addIdentityLink ( executionEntity , userId , null , type ) ; }
Adds an IdentityLink for the given user id with the specified type but only if the user is not associated with the execution entity yet .
17,368
private static Shape createShape ( SHAPE_TYPE shapeType , GraphicInfo graphicInfo ) { if ( SHAPE_TYPE . Rectangle . equals ( shapeType ) ) { return new Rectangle2D . Double ( graphicInfo . getX ( ) , graphicInfo . getY ( ) , graphicInfo . getWidth ( ) , graphicInfo . getHeight ( ) ) ; } else if ( SHAPE_TYPE . Rhombus . equals ( shapeType ) ) { Path2D . Double rhombus = new Path2D . Double ( ) ; rhombus . moveTo ( graphicInfo . getX ( ) , graphicInfo . getY ( ) + graphicInfo . getHeight ( ) / 2 ) ; rhombus . lineTo ( graphicInfo . getX ( ) + graphicInfo . getWidth ( ) / 2 , graphicInfo . getY ( ) + graphicInfo . getHeight ( ) ) ; rhombus . lineTo ( graphicInfo . getX ( ) + graphicInfo . getWidth ( ) , graphicInfo . getY ( ) + graphicInfo . getHeight ( ) / 2 ) ; rhombus . lineTo ( graphicInfo . getX ( ) + graphicInfo . getWidth ( ) / 2 , graphicInfo . getY ( ) ) ; rhombus . lineTo ( graphicInfo . getX ( ) , graphicInfo . getY ( ) + graphicInfo . getHeight ( ) / 2 ) ; rhombus . closePath ( ) ; return rhombus ; } else if ( SHAPE_TYPE . Ellipse . equals ( shapeType ) ) { return new Ellipse2D . Double ( graphicInfo . getX ( ) , graphicInfo . getY ( ) , graphicInfo . getWidth ( ) , graphicInfo . getHeight ( ) ) ; } return null ; }
This method creates shape by type and coordinates .
17,369
private static Point getIntersection ( Shape shape , Line2D . Double line ) { if ( shape instanceof Ellipse2D ) { return getEllipseIntersection ( shape , line ) ; } else if ( shape instanceof Rectangle2D || shape instanceof Path2D ) { return getShapeIntersection ( shape , line ) ; } else { return null ; } }
This method returns intersection point of shape border and line .
17,370
private static Point getEllipseIntersection ( Shape shape , Line2D . Double line ) { double angle = Math . atan2 ( line . y2 - line . y1 , line . x2 - line . x1 ) ; double x = shape . getBounds2D ( ) . getWidth ( ) / 2 * Math . cos ( angle ) + shape . getBounds2D ( ) . getCenterX ( ) ; double y = shape . getBounds2D ( ) . getHeight ( ) / 2 * Math . sin ( angle ) + shape . getBounds2D ( ) . getCenterY ( ) ; Point p = new Point ( ) ; p . setLocation ( x , y ) ; return p ; }
This method calculates ellipse intersection with line
17,371
private static Point getShapeIntersection ( Shape shape , Line2D . Double line ) { PathIterator it = shape . getPathIterator ( null ) ; double [ ] coords = new double [ 6 ] ; double [ ] pos = new double [ 2 ] ; Line2D . Double l = new Line2D . Double ( ) ; while ( ! it . isDone ( ) ) { int type = it . currentSegment ( coords ) ; switch ( type ) { case PathIterator . SEG_MOVETO : pos [ 0 ] = coords [ 0 ] ; pos [ 1 ] = coords [ 1 ] ; break ; case PathIterator . SEG_LINETO : l = new Line2D . Double ( pos [ 0 ] , pos [ 1 ] , coords [ 0 ] , coords [ 1 ] ) ; if ( line . intersectsLine ( l ) ) { return getLinesIntersection ( line , l ) ; } pos [ 0 ] = coords [ 0 ] ; pos [ 1 ] = coords [ 1 ] ; break ; case PathIterator . SEG_CLOSE : break ; default : } it . next ( ) ; } return null ; }
This method calculates shape intersection with line .
17,372
private static Point getLinesIntersection ( Line2D a , Line2D b ) { double d = ( a . getX1 ( ) - a . getX2 ( ) ) * ( b . getY2 ( ) - b . getY1 ( ) ) - ( a . getY1 ( ) - a . getY2 ( ) ) * ( b . getX2 ( ) - b . getX1 ( ) ) ; double da = ( a . getX1 ( ) - b . getX1 ( ) ) * ( b . getY2 ( ) - b . getY1 ( ) ) - ( a . getY1 ( ) - b . getY1 ( ) ) * ( b . getX2 ( ) - b . getX1 ( ) ) ; double ta = da / d ; Point p = new Point ( ) ; p . setLocation ( a . getX1 ( ) + ta * ( a . getX2 ( ) - a . getX1 ( ) ) , a . getY1 ( ) + ta * ( a . getY2 ( ) - a . getY1 ( ) ) ) ; return p ; }
This method calculates intersections of two lines .
17,373
protected int createInstances ( DelegateExecution multiInstanceExecution ) { int nrOfInstances = resolveNrOfInstances ( multiInstanceExecution ) ; if ( nrOfInstances == 0 ) { return nrOfInstances ; } else if ( nrOfInstances < 0 ) { throw new ActivitiIllegalArgumentException ( "Invalid number of instances: must be a non-negative integer value" + ", but was " + nrOfInstances ) ; } ExecutionEntity childExecution = Context . getCommandContext ( ) . getExecutionEntityManager ( ) . createChildExecution ( ( ExecutionEntity ) multiInstanceExecution ) ; childExecution . setCurrentFlowElement ( multiInstanceExecution . getCurrentFlowElement ( ) ) ; multiInstanceExecution . setMultiInstanceRoot ( true ) ; multiInstanceExecution . setActive ( false ) ; setLoopVariable ( multiInstanceExecution , NUMBER_OF_INSTANCES , nrOfInstances ) ; setLoopVariable ( multiInstanceExecution , NUMBER_OF_COMPLETED_INSTANCES , 0 ) ; setLoopVariable ( multiInstanceExecution , NUMBER_OF_ACTIVE_INSTANCES , 1 ) ; setLoopVariable ( childExecution , getCollectionElementIndexVariable ( ) , 0 ) ; logLoopDetails ( multiInstanceExecution , "initialized" , 0 , 0 , 1 , nrOfInstances ) ; if ( nrOfInstances > 0 ) { executeOriginalBehavior ( childExecution , 0 ) ; } return nrOfInstances ; }
Handles the sequential case of spawning the instances . Will only create one instance since at most one instance can be active .
17,374
public void execute ( DelegateExecution execution ) { ActionDefinition actionDefinition = findRelatedActionDefinition ( execution ) ; Connector connector = getConnector ( getImplementation ( execution ) ) ; IntegrationContext integrationContext = connector . apply ( integrationContextBuilder . from ( execution , actionDefinition ) ) ; execution . setVariables ( outboundVariablesProvider . calculateVariables ( integrationContext , actionDefinition ) ) ; leave ( execution ) ; }
We have two different implementation strategy that can be executed in according if we have a connector action definition match or not .
17,375
protected void moveNode ( TreeNode node , double dx , double dy ) { node . x += dx ; node . y += dy ; apply ( node , null ) ; TreeNode child = node . child ; while ( child != null ) { moveNode ( child , dx , dy ) ; child = child . next ; } }
Moves the specified node and all of its children by the given amount .
17,376
protected TreeNode dfs ( Object cell , Object parent , Set < Object > visited ) { if ( visited == null ) { visited = new HashSet < Object > ( ) ; } TreeNode node = null ; mxIGraphModel model = graph . getModel ( ) ; if ( cell != null && ! visited . contains ( cell ) && ( ! isVertexIgnored ( cell ) || isBoundaryEvent ( cell ) ) ) { visited . add ( cell ) ; node = createNode ( cell ) ; TreeNode prev = null ; Object [ ] out = graph . getEdges ( cell , parent , invert , ! invert , false ) ; for ( int i = 0 ; i < out . length ; i ++ ) { Object edge = out [ i ] ; if ( ! isEdgeIgnored ( edge ) ) { if ( resetEdges ) { setEdgePoints ( edge , null ) ; } Object target = graph . getView ( ) . getVisibleTerminal ( edge , invert ) ; TreeNode tmp = dfs ( target , parent , visited ) ; if ( tmp != null && model . getGeometry ( target ) != null ) { if ( prev == null ) { node . child = tmp ; } else { prev . next = tmp ; } prev = tmp ; } } } } return node ; }
Does a depth first search starting at the specified cell . Makes sure the specified swimlane is never left by the algorithm .
17,377
protected void layout ( TreeNode node ) { if ( node != null ) { TreeNode child = node . child ; while ( child != null ) { layout ( child ) ; child = child . next ; } if ( node . child != null ) { attachParent ( node , join ( node ) ) ; } else { layoutLeaf ( node ) ; } } }
Starts the actual compact tree layout algorithm at the given node .
17,378
protected int createInstances ( DelegateExecution execution ) { int nrOfInstances = resolveNrOfInstances ( execution ) ; if ( nrOfInstances < 0 ) { throw new ActivitiIllegalArgumentException ( "Invalid number of instances: must be non-negative integer value" + ", but was " + nrOfInstances ) ; } execution . setMultiInstanceRoot ( true ) ; setLoopVariable ( execution , NUMBER_OF_INSTANCES , nrOfInstances ) ; setLoopVariable ( execution , NUMBER_OF_COMPLETED_INSTANCES , 0 ) ; setLoopVariable ( execution , NUMBER_OF_ACTIVE_INSTANCES , nrOfInstances ) ; List < DelegateExecution > concurrentExecutions = new ArrayList < DelegateExecution > ( ) ; for ( int loopCounter = 0 ; loopCounter < nrOfInstances ; loopCounter ++ ) { DelegateExecution concurrentExecution = Context . getCommandContext ( ) . getExecutionEntityManager ( ) . createChildExecution ( ( ExecutionEntity ) execution ) ; concurrentExecution . setCurrentFlowElement ( activity ) ; concurrentExecution . setActive ( true ) ; concurrentExecution . setScope ( false ) ; concurrentExecutions . add ( concurrentExecution ) ; logLoopDetails ( concurrentExecution , "initialized" , loopCounter , 0 , nrOfInstances , nrOfInstances ) ; } for ( int loopCounter = 0 ; loopCounter < nrOfInstances ; loopCounter ++ ) { DelegateExecution concurrentExecution = concurrentExecutions . get ( loopCounter ) ; if ( concurrentExecution . isActive ( ) && ! concurrentExecution . isEnded ( ) && concurrentExecution . getParent ( ) . isActive ( ) && ! concurrentExecution . getParent ( ) . isEnded ( ) ) { setLoopVariable ( concurrentExecution , getCollectionElementIndexVariable ( ) , loopCounter ) ; executeOriginalBehavior ( concurrentExecution , loopCounter ) ; } } if ( ! concurrentExecutions . isEmpty ( ) ) { ExecutionEntity executionEntity = ( ExecutionEntity ) execution ; executionEntity . setActive ( false ) ; } return nrOfInstances ; }
Handles the parallel case of spawning the instances . Will create child executions accordingly for every instance needed .
17,379
public void updateCachingAndArtifacts ( ParsedDeployment parsedDeployment ) { CommandContext commandContext = Context . getCommandContext ( ) ; final ProcessEngineConfigurationImpl processEngineConfiguration = Context . getProcessEngineConfiguration ( ) ; DeploymentCache < ProcessDefinitionCacheEntry > processDefinitionCache = processEngineConfiguration . getDeploymentManager ( ) . getProcessDefinitionCache ( ) ; DeploymentEntity deployment = parsedDeployment . getDeployment ( ) ; for ( ProcessDefinitionEntity processDefinition : parsedDeployment . getAllProcessDefinitions ( ) ) { BpmnModel bpmnModel = parsedDeployment . getBpmnModelForProcessDefinition ( processDefinition ) ; Process process = parsedDeployment . getProcessModelForProcessDefinition ( processDefinition ) ; ProcessDefinitionCacheEntry cacheEntry = new ProcessDefinitionCacheEntry ( processDefinition , bpmnModel , process ) ; processDefinitionCache . add ( processDefinition . getId ( ) , cacheEntry ) ; addDefinitionInfoToCache ( processDefinition , processEngineConfiguration , commandContext ) ; deployment . addDeployedArtifact ( processDefinition ) ; } }
Ensures that the process definition is cached in the appropriate places including the deployment s collection of deployed artifacts and the deployment manager s cache as well as caching any ProcessDefinitionInfos .
17,380
public void info ( CharSequence info ) { if ( StringUtils . isNotEmpty ( info ) ) { msg . printMessage ( Diagnostic . Kind . NOTE , Consts . PREFIX_OF_LOGGER + info ) ; } }
Print info log .
17,381
private static boolean isVMMultidexCapable ( ) { boolean isMultidexCapable = false ; String vmName = null ; try { if ( isYunOS ( ) ) { vmName = "'YunOS'" ; isMultidexCapable = Integer . valueOf ( System . getProperty ( "ro.build.version.sdk" ) ) >= 21 ; } else { vmName = "'Android'" ; String versionString = System . getProperty ( "java.vm.version" ) ; if ( versionString != null ) { Matcher matcher = Pattern . compile ( "(\\d+)\\.(\\d+)(\\.\\d+)?" ) . matcher ( versionString ) ; if ( matcher . matches ( ) ) { try { int major = Integer . parseInt ( matcher . group ( 1 ) ) ; int minor = Integer . parseInt ( matcher . group ( 2 ) ) ; isMultidexCapable = ( major > VM_WITH_MULTIDEX_VERSION_MAJOR ) || ( ( major == VM_WITH_MULTIDEX_VERSION_MAJOR ) && ( minor >= VM_WITH_MULTIDEX_VERSION_MINOR ) ) ; } catch ( NumberFormatException ignore ) { } } } } } catch ( Exception ignore ) { } Log . i ( Consts . TAG , "VM with name " + vmName + ( isMultidexCapable ? " has multidex support" : " does not have multidex support" ) ) ; return isMultidexCapable ; }
Identifies if the current VM has a native support for multidex meaning there is no need for additional installation by this library .
17,382
static synchronized void destroy ( ) { if ( debuggable ( ) ) { hasInit = false ; LogisticsCenter . suspend ( ) ; logger . info ( Consts . TAG , "ARouter destroy success!" ) ; } else { logger . error ( Consts . TAG , "Destroy can be used in debug mode only!" ) ; } }
Destroy arouter it can be used only in debug mode .
17,383
protected Postcard build ( String path ) { if ( TextUtils . isEmpty ( path ) ) { throw new HandlerException ( Consts . TAG + "Parameter is invalid!" ) ; } else { PathReplaceService pService = ARouter . getInstance ( ) . navigation ( PathReplaceService . class ) ; if ( null != pService ) { path = pService . forString ( path ) ; } return build ( path , extractGroup ( path ) ) ; } }
Build postcard by path and default group
17,384
protected Postcard build ( Uri uri ) { if ( null == uri || TextUtils . isEmpty ( uri . toString ( ) ) ) { throw new HandlerException ( Consts . TAG + "Parameter invalid!" ) ; } else { PathReplaceService pService = ARouter . getInstance ( ) . navigation ( PathReplaceService . class ) ; if ( null != pService ) { uri = pService . forUri ( uri ) ; } return new Postcard ( uri . getPath ( ) , extractGroup ( uri . getPath ( ) ) , uri , null ) ; } }
Build postcard by uri
17,385
protected Postcard build ( String path , String group ) { if ( TextUtils . isEmpty ( path ) || TextUtils . isEmpty ( group ) ) { throw new HandlerException ( Consts . TAG + "Parameter is invalid!" ) ; } else { PathReplaceService pService = ARouter . getInstance ( ) . navigation ( PathReplaceService . class ) ; if ( null != pService ) { path = pService . forString ( path ) ; } return new Postcard ( path , group ) ; } }
Build postcard by path and group
17,386
private String extractGroup ( String path ) { if ( TextUtils . isEmpty ( path ) || ! path . startsWith ( "/" ) ) { throw new HandlerException ( Consts . TAG + "Extract the default group failed, the path must be start with '/' and contain more than 2 '/'!" ) ; } try { String defaultGroup = path . substring ( 1 , path . indexOf ( "/" , 1 ) ) ; if ( TextUtils . isEmpty ( defaultGroup ) ) { throw new HandlerException ( Consts . TAG + "Extract the default group failed! There's nothing between 2 '/'!" ) ; } else { return defaultGroup ; } } catch ( Exception e ) { logger . warning ( Consts . TAG , "Failed to extract default group! " + e . getMessage ( ) ) ; return null ; } }
Extract the default group from path .
17,387
protected Object navigation ( final Context context , final Postcard postcard , final int requestCode , final NavigationCallback callback ) { try { LogisticsCenter . completion ( postcard ) ; } catch ( NoRouteFoundException ex ) { logger . warning ( Consts . TAG , ex . getMessage ( ) ) ; if ( debuggable ( ) ) { runInMainThread ( new Runnable ( ) { public void run ( ) { Toast . makeText ( mContext , "There's no route matched!\n" + " Path = [" + postcard . getPath ( ) + "]\n" + " Group = [" + postcard . getGroup ( ) + "]" , Toast . LENGTH_LONG ) . show ( ) ; } } ) ; } if ( null != callback ) { callback . onLost ( postcard ) ; } else { DegradeService degradeService = ARouter . getInstance ( ) . navigation ( DegradeService . class ) ; if ( null != degradeService ) { degradeService . onLost ( context , postcard ) ; } } return null ; } if ( null != callback ) { callback . onFound ( postcard ) ; } if ( ! postcard . isGreenChannel ( ) ) { interceptorService . doInterceptions ( postcard , new InterceptorCallback ( ) { public void onContinue ( Postcard postcard ) { _navigation ( context , postcard , requestCode , callback ) ; } public void onInterrupt ( Throwable exception ) { if ( null != callback ) { callback . onInterrupt ( postcard ) ; } logger . info ( Consts . TAG , "Navigation failed, termination by interceptor : " + exception . getMessage ( ) ) ; } } ) ; } else { return _navigation ( context , postcard , requestCode , callback ) ; } return null ; }
Use router navigation .
17,388
private void runInMainThread ( Runnable runnable ) { if ( Looper . getMainLooper ( ) . getThread ( ) != Thread . currentThread ( ) ) { mHandler . post ( runnable ) ; } else { runnable . run ( ) ; } }
Be sure execute in main thread .
17,389
private void parseInterceptors ( Set < ? extends Element > elements ) throws IOException { if ( CollectionUtils . isNotEmpty ( elements ) ) { logger . info ( ">>> Found interceptors, size is " + elements . size ( ) + " <<<" ) ; for ( Element element : elements ) { if ( verify ( element ) ) { logger . info ( "A interceptor verify over, its " + element . asType ( ) ) ; Interceptor interceptor = element . getAnnotation ( Interceptor . class ) ; Element lastInterceptor = interceptors . get ( interceptor . priority ( ) ) ; if ( null != lastInterceptor ) { throw new IllegalArgumentException ( String . format ( Locale . getDefault ( ) , "More than one interceptors use same priority [%d], They are [%s] and [%s]." , interceptor . priority ( ) , lastInterceptor . getSimpleName ( ) , element . getSimpleName ( ) ) ) ; } interceptors . put ( interceptor . priority ( ) , element ) ; } else { logger . error ( "A interceptor verify failed, its " + element . asType ( ) ) ; } } TypeElement type_ITollgate = elementUtils . getTypeElement ( IINTERCEPTOR ) ; TypeElement type_ITollgateGroup = elementUtils . getTypeElement ( IINTERCEPTOR_GROUP ) ; ParameterizedTypeName inputMapTypeOfTollgate = ParameterizedTypeName . get ( ClassName . get ( Map . class ) , ClassName . get ( Integer . class ) , ParameterizedTypeName . get ( ClassName . get ( Class . class ) , WildcardTypeName . subtypeOf ( ClassName . get ( type_ITollgate ) ) ) ) ; ParameterSpec tollgateParamSpec = ParameterSpec . builder ( inputMapTypeOfTollgate , "interceptors" ) . build ( ) ; MethodSpec . Builder loadIntoMethodOfTollgateBuilder = MethodSpec . methodBuilder ( METHOD_LOAD_INTO ) . addAnnotation ( Override . class ) . addModifiers ( PUBLIC ) . addParameter ( tollgateParamSpec ) ; if ( null != interceptors && interceptors . size ( ) > 0 ) { for ( Map . Entry < Integer , Element > entry : interceptors . entrySet ( ) ) { loadIntoMethodOfTollgateBuilder . addStatement ( "interceptors.put(" + entry . getKey ( ) + ", $T.class)" , ClassName . get ( ( TypeElement ) entry . getValue ( ) ) ) ; } } JavaFile . builder ( PACKAGE_OF_GENERATE_FILE , TypeSpec . classBuilder ( NAME_OF_INTERCEPTOR + SEPARATOR + moduleName ) . addModifiers ( PUBLIC ) . addJavadoc ( WARNING_TIPS ) . addMethod ( loadIntoMethodOfTollgateBuilder . build ( ) ) . addSuperinterface ( ClassName . get ( type_ITollgateGroup ) ) . build ( ) ) . build ( ) . writeTo ( mFiler ) ; logger . info ( ">>> Interceptor group write over. <<<" ) ; } }
Parse tollgate .
17,390
private boolean verify ( Element element ) { Interceptor interceptor = element . getAnnotation ( Interceptor . class ) ; return null != interceptor && ( ( TypeElement ) element ) . getInterfaces ( ) . contains ( iInterceptor ) ; }
Verify inteceptor meta
17,391
public synchronized void init ( ProcessingEnvironment processingEnv ) { super . init ( processingEnv ) ; if ( generateDoc ) { try { docWriter = mFiler . createResource ( StandardLocation . SOURCE_OUTPUT , PACKAGE_OF_GENERATE_DOCS , "arouter-map-of-" + moduleName + ".json" ) . openWriter ( ) ; } catch ( IOException e ) { logger . error ( "Create doc writer failed, because " + e . getMessage ( ) ) ; } } iProvider = elementUtils . getTypeElement ( Consts . IPROVIDER ) . asType ( ) ; logger . info ( ">>> RouteProcessor init. <<<" ) ; }
Writer used for write doc
17,392
private RouteDoc extractDocInfo ( RouteMeta routeMeta ) { RouteDoc routeDoc = new RouteDoc ( ) ; routeDoc . setGroup ( routeMeta . getGroup ( ) ) ; routeDoc . setPath ( routeMeta . getPath ( ) ) ; routeDoc . setDescription ( routeMeta . getName ( ) ) ; routeDoc . setType ( routeMeta . getType ( ) . name ( ) . toLowerCase ( ) ) ; routeDoc . setMark ( routeMeta . getExtra ( ) ) ; return routeDoc ; }
Extra doc info from route meta
17,393
private void categories ( RouteMeta routeMete ) { if ( routeVerify ( routeMete ) ) { logger . info ( ">>> Start categories, group = " + routeMete . getGroup ( ) + ", path = " + routeMete . getPath ( ) + " <<<" ) ; Set < RouteMeta > routeMetas = groupMap . get ( routeMete . getGroup ( ) ) ; if ( CollectionUtils . isEmpty ( routeMetas ) ) { Set < RouteMeta > routeMetaSet = new TreeSet < > ( new Comparator < RouteMeta > ( ) { public int compare ( RouteMeta r1 , RouteMeta r2 ) { try { return r1 . getPath ( ) . compareTo ( r2 . getPath ( ) ) ; } catch ( NullPointerException npe ) { logger . error ( npe . getMessage ( ) ) ; return 0 ; } } } ) ; routeMetaSet . add ( routeMete ) ; groupMap . put ( routeMete . getGroup ( ) , routeMetaSet ) ; } else { routeMetas . add ( routeMete ) ; } } else { logger . warning ( ">>> Route meta verify error, group is " + routeMete . getGroup ( ) + " <<<" ) ; } }
Sort metas in group .
17,394
private boolean routeVerify ( RouteMeta meta ) { String path = meta . getPath ( ) ; if ( StringUtils . isEmpty ( path ) || ! path . startsWith ( "/" ) ) { return false ; } if ( StringUtils . isEmpty ( meta . getGroup ( ) ) ) { try { String defaultGroup = path . substring ( 1 , path . indexOf ( "/" , 1 ) ) ; if ( StringUtils . isEmpty ( defaultGroup ) ) { return false ; } meta . setGroup ( defaultGroup ) ; return true ; } catch ( Exception e ) { logger . error ( "Failed to extract default group! " + e . getMessage ( ) ) ; return false ; } } return true ; }
Verify the route meta
17,395
@ RequiresApi ( 16 ) public Postcard withOptionsCompat ( ActivityOptionsCompat compat ) { if ( null != compat ) { this . optionsCompat = compat . toBundle ( ) ; } return this ; }
Set options compat
17,396
public static void init ( Application application ) { if ( ! hasInit ) { logger = _ARouter . logger ; _ARouter . logger . info ( Consts . TAG , "ARouter init start." ) ; hasInit = _ARouter . init ( application ) ; if ( hasInit ) { _ARouter . afterInit ( ) ; } _ARouter . logger . info ( Consts . TAG , "ARouter init over." ) ; } }
Init it must be call before used router .
17,397
public static ARouter getInstance ( ) { if ( ! hasInit ) { throw new InitException ( "ARouter::Init::Invoke init(context) first!" ) ; } else { if ( instance == null ) { synchronized ( ARouter . class ) { if ( instance == null ) { instance = new ARouter ( ) ; } } } return instance ; } }
Get instance of router . A All feature U use will be starts here .
17,398
public Postcard build ( String path , String group ) { return _ARouter . getInstance ( ) . build ( path , group ) ; }
Build the roadmap draw a postcard .
17,399
public < T > T navigation ( Class < ? extends T > service ) { return _ARouter . getInstance ( ) . navigation ( service ) ; }
Launch the navigation by type