/*
(non-Javadoc)

@see org.activiti.engine.impl.history.HistoryManagerInterface# recordProcessDefinitionChange(java.lang.String, java.lang.String)
10578
@Override
  public void recordProcessDefinitionChange(String processInstanceId, String processDefinitionId) {
    if (isHistoryLevelAtLeast(HistoryLevel.ACTIVITY)) {
      HistoricProcessInstanceEntity historicProcessInstance = getHistoricProcessInstanceEntityManager().findById(processInstanceId);
      if (historicProcessInstance != null) {
        historicProcessInstance.setProcessDefinitionId(processDefinitionId);
      }
    }
  }
101423
protected void ensureProcessDefinitionInitialized() {
    if ((processDefinition == null) && (processDefinitionId != null)) {
      ProcessDefinitionEntity deployedProcessDefinition = Context.getProcessEngineConfiguration().getDeploymentCache()
          .findDeployedProcessDefinitionById(processDefinitionId);
      setProcessDefinition(deployedProcessDefinition);
    }
  }
660608
@Deprecated
  public void startProcessInstanceByIdForm(String processDefinitionId, String callbackUrl) {
    this.url = callbackUrl;
    this.processDefinitionId = processDefinitionId;
    beginConversation();
  }
340809
protected void processChangeTrackerChange(final Map<String, Object> change) {
        // Process each change from the feed:
        String docID = (String) change.get("id");
        if (docID == null || !Document.isValidDocumentId(docID))
            return;

        String lastSequence = change.get("seq").toString();
        boolean deleted = (change.containsKey("deleted") &&
                change.get("deleted").equals(Boolean.TRUE));
        List<Map<String, Object>> changes = (List<Map<String, Object>>) change.get("changes");
        for (Map<String, Object> changeDict : changes) {
            String revID = (String) changeDict.get("rev");
            if (revID == null) {
                continue;
            }

            PulledRevision rev = new PulledRevision(docID, revID, deleted);

            // Remember its remote sequence ID (opaque), and make up a numeric sequence
            // based on the order in which it appeared in the _changes feed:
            rev.setRemoteSequenceID(lastSequence);

            if (changes.size() > 1)
                rev.setConflicted(true);

            Log.d(TAG, "%s: adding rev to inbox %s", this, rev);

            Log.v(TAG,
                    "%s: changeTrackerReceivedChange() incrementing changesCount by 1", this);

            // this is purposefully done slightly different than the ios version
            addToChangesCount(1);

            addToInbox(rev);
        }

        pauseOrResume();
    }
1345327
public void registerProcessEngine(ProcessEngine processEngine) {

    if(processEngine == null) {
      throw new ProcessEngineException("Cannot register process engine with Msc Runtime Container: process engine is 'null'");
    }

    ServiceName serviceName = ServiceNames.forManagedProcessEngine(processEngine.getName());

    if(serviceContainer.getService(serviceName) == null) {
      MscManagedProcessEngine processEngineRegistration = new MscManagedProcessEngine(processEngine);

      // install the service asynchronously.
      childTarget.addService(serviceName, processEngineRegistration)
        .setInitialMode(Mode.ACTIVE)
        .addDependency(ServiceNames.forMscRuntimeContainerDelegate(), MscRuntimeContainerDelegate.class, processEngineRegistration.getRuntimeContainerDelegateInjector())
        .install();
    }

  }
5310
@Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        registerObject(bean);
        return bean;
    }
641128
@Override
	public void setReference(Record reference) {
		for (int i = 0; i < this.keyFields1.length; i++) {
			if (!reference.getFieldInto(this.keyFields1[i], this.keyHolders1[i])) {
				throw new NullKeyFieldException(this.keyFields1[i]);
			}
		}
	}
873937
public void updateProcessDefinitionSuspensionStateById(String processDefinitionId, SuspensionState suspensionState) {
    Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("processDefinitionId", processDefinitionId);
    parameters.put("suspensionState", suspensionState.getStateCode());
    getDbEntityManager().update(ProcessDefinitionEntity.class, "updateProcessDefinitionSuspensionStateByParameters", configureParameterizedQuery(parameters));
  }
643336
@Override
  public void addChange(DiffEntry change) {
    Path path = new Path(change.getNewPath());
    if (path.depth() == NODE_FILE_DEPTH) {
      addDataNode(change);
    } else if (path.depth() == EDGE_FILE_DEPTH) {
      addFlowEdge(change);
    }
  }
876718
protected void logRegistration(Set<String> deploymentIds, ProcessApplicationReference reference) {

    if (!LOG.isInfoEnabled()) {
      // building the log message is expensive (db queries) so we avoid it if we can
      return;
    }

    try {
      StringBuilder builder = new StringBuilder();
      builder.append("ProcessApplication '");
      builder.append(reference.getName());
      builder.append("' registered for DB deployments ");
      builder.append(deploymentIds);
      builder.append(". ");

      List<ProcessDefinition> processDefinitions = new ArrayList<ProcessDefinition>();
      List<CaseDefinition> caseDefinitions = new ArrayList<CaseDefinition>();

      CommandContext commandContext = Context.getCommandContext();
      ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration();
      boolean cmmnEnabled = processEngineConfiguration.isCmmnEnabled();

      for (String deploymentId : deploymentIds) {

        DeploymentEntity deployment = commandContext
          .getDbEntityManager()
          .selectById(DeploymentEntity.class, deploymentId);

        if(deployment != null) {

          processDefinitions.addAll(getDeployedProcessDefinitionArtifacts(deployment));

          if (cmmnEnabled) {
            caseDefinitions.addAll(getDeployedCaseDefinitionArtifacts(deployment));
          }

        }
      }

      logProcessDefinitionRegistrations(builder, processDefinitions);

      if (cmmnEnabled) {
        logCaseDefinitionRegistrations(builder, caseDefinitions);
      }

      LOG.registrationSummary(builder.toString());

    }
    catch(Throwable e) {
      LOG.exceptionWhileLoggingRegistrationSummary(e);
    }
  }
1367939
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());
        }
    }
681464
@Override
  public void recordActivityStart(ExecutionEntity executionEntity) {
    if (isHistoryLevelAtLeast(HistoryLevel.ACTIVITY)) {
      if (executionEntity.getActivityId() != null && executionEntity.getCurrentFlowElement() != null) {
        
        HistoricActivityInstanceEntity historicActivityInstanceEntity = null;
        
        // Historic activity instance could have been created (but only in cache, never persisted)
        // for example when submitting form properties
        HistoricActivityInstanceEntity historicActivityInstanceEntityFromCache = 
            getHistoricActivityInstanceFromCache(executionEntity.getId(), executionEntity.getActivityId(), true);
        if (historicActivityInstanceEntityFromCache != null) {
          historicActivityInstanceEntity = historicActivityInstanceEntityFromCache;
        } else {
          historicActivityInstanceEntity = createHistoricActivityInstanceEntity(executionEntity);
        }
        
        // Fire event
        ActivitiEventDispatcher activitiEventDispatcher = getEventDispatcher();
        if (activitiEventDispatcher != null && activitiEventDispatcher.isEnabled()) {
          activitiEventDispatcher.dispatchEvent(
              ActivitiEventBuilder.createEntityEvent(ActivitiEventType.HISTORIC_ACTIVITY_INSTANCE_CREATED, historicActivityInstanceEntity));
        }
        
      }
    }
  }
799407
public void onSelectionChanged(SelectionEvent event) {
		Record record = event.getRecord();
		String featureId = record.getAttribute(FIELD_NAME_FEATURE_ID);

		// Check if selection and deselection are really necessary, to avoid useless events.
		if (event.getState()) {
			// Only select a feature if it is not yet selected:
			if (!layer.isFeatureSelected(featureId)) {
				layer.getFeatureStore().getFeature(featureId, GeomajasConstant.FEATURE_INCLUDE_ALL,
						new LazyLoadCallback() {

							public void execute(List<Feature> response) {
								layer.selectFeature(response.get(0));
							}
						});
			}
		} else {
			// Only deselect a feature if it is not yet deselected:
			if (layer.isFeatureSelected(featureId)) {
				layer.getFeatureStore().getFeature(featureId, GeomajasConstant.FEATURE_INCLUDE_ALL,
						new LazyLoadCallback() {

							public void execute(List<Feature> response) {
								layer.deselectFeature(response.get(0));
							}
						});
			}
		}
	}
760024
public void registerInitialProcesses()
    {
        MessageProcessInfo recMessageProcessInfo = new MessageProcessInfo(this);
        try   {
             // Always register this generic processing queue.
            this.registerProcessForMessage(new BaseMessageFilter(MessageConstants.TRX_SEND_QUEUE, MessageConstants.INTERNET_QUEUE, null, null), null, null);
            recMessageProcessInfo.close();
            while (recMessageProcessInfo.hasNext())
            {
                recMessageProcessInfo.next();
                String strQueueName = recMessageProcessInfo.getQueueName(true);
                String strQueueType = recMessageProcessInfo.getQueueType(true);
                String strProcessClass = recMessageProcessInfo.getField(MessageProcessInfo.PROCESSOR_CLASS).toString();
                Map<String,Object> properties = ((PropertiesField)recMessageProcessInfo.getField(MessageProcessInfo.PROPERTIES)).getProperties();
                Record recMessageType = ((ReferenceField)recMessageProcessInfo.getField(MessageProcessInfo.MESSAGE_TYPE_ID)).getReference();
                if (recMessageType != null)
                {   // Start all processes that handle INcoming REQUESTs.
                    String strMessageType = recMessageType.getField(MessageType.CODE).toString();
                    Record recMessageInfo = ((ReferenceField)recMessageProcessInfo.getField(MessageProcessInfo.MESSAGE_INFO_ID)).getReference();
                    if (recMessageInfo != null)
                    {
                        Record recMessageInfoType = ((ReferenceField)recMessageInfo.getField(MessageInfo.MESSAGE_INFO_TYPE_ID)).getReference();
                        if (recMessageInfoType != null)
                        {
                            String strMessageInfoType = recMessageInfoType.getField(MessageInfoType.CODE).toString();
                            if (MessageInfoType.REQUEST.equals(strMessageInfoType))
                                if (MessageType.MESSAGE_IN.equals(strMessageType))
                                    if ((strQueueName != null) && (strQueueName.length() > 0))
                                        this.registerProcessForMessage(new BaseMessageFilter(strQueueName, strQueueType, null, null), strProcessClass, properties);
                        }
                    }
                }
            }
            recMessageProcessInfo.close();
        } catch (DBException ex)    {
            ex.printStackTrace();
        } finally {
            recMessageProcessInfo.free();
        }
    }
1139848
@Override
    public Collection<ProcessDefinition> getProcessDefinitions(QueryContext queryContext) {
        Collection<ProcessDefinition> cases = availableProcesses.stream()
                .filter(caseDef -> caseDef.isActive())
                .sorted(new ProcessDefinitionComparator(queryContext.getOrderBy(), queryContext.isAscending()))
                .skip(queryContext.getOffset())
                .limit(queryContext.getCount())
                .collect(toList());
        return cases;
    }
83835
@Override
	public ProcessDefinition getProcessDefinition(String name) {
		for (ProcessDefinition pd: m_allProcesses) {
			if (pd.getName().equals(name)) {
				return pd;
			}
		}
		return null;
	}
701663
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry definitionRegistry)
      throws BeansException {
    // 自动注册
    BindRegistry registry = new SpringBindRegistry(definitionRegistry);
    Map<String, BeanDefinition> newDefinitions = registerModules(registry);
    // should register after all beans
    registerBuildins(registry);
    // 再配置
    reconfig(definitionRegistry, registry);
    lifecycle(registry, definitionRegistry);
    autowire(newDefinitions, registry);
  }