/*
(non-Javadoc)

@see com.ibm.ws.sib.processor.impl.interfaces.ControllableResource#dereferenceControlAdapter()
509893
@Override
    public void dereferenceControlAdapter()
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(tc, "dereferenceControlAdapter");

        if (controlAdapter != null)
        {
            controlAdapter.dereferenceControllable();
            controlAdapter = null;
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "dereferenceControlAdapter");
    }
676414
@Override
    public void registerCommandHandler(String key, CommandHandler handler)
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(tc, "registerCommandHandler",
                        new Object[] { key, handler });

        // Table of keys and non-tx handlers is managed at ME level
        _messageProcessor.registerCommandHandler(key, handler);

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "registerCommandHandler");
    }
686750
@Override
    public void foundGuaranteedNullDeref(@Nonnull
            Set<Location> assignedNullLocationSet, @Nonnull
            Set<Location> derefLocationSet, SortedSet<Location> doomedLocations, ValueNumberDataflow vna, ValueNumber refValue,
            @CheckForNull
            BugAnnotation variableAnnotation, NullValueUnconditionalDeref deref, boolean npeIfStatementCovered) {
        if (refValue.hasFlag(ValueNumber.CONSTANT_CLASS_OBJECT)) {
            return;
        }

        if (DEBUG) {
            System.out.println("Found guaranteed null deref in " + method.getName());
            for (Location loc : doomedLocations) {
                System.out.println("Doomed at " + loc);
            }
        }

        String bugType;

        int priority = npeIfStatementCovered ? HIGH_PRIORITY : NORMAL_PRIORITY;

        if (deref.isMethodReturnValue()) {
            if (deref.isReadlineValue()) {
                bugType = "NP_DEREFERENCE_OF_READLINE_VALUE";
            } else {
                bugType = "NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE";
            }
        } else if (derefLocationSet.size() > 1) {
            if (!deref.isAlwaysOnExceptionPath()) {
                bugType = "NP_GUARANTEED_DEREF";
            } else {
                bugType = "NP_GUARANTEED_DEREF_ON_EXCEPTION_PATH";
            }
        } else if (!deref.isAlwaysOnExceptionPath()) {
            bugType = "NP_NULL_ON_SOME_PATH";
        } else {
            bugType = "NP_NULL_ON_SOME_PATH_EXCEPTION";
        }

        boolean allCallToAssertionMethod = !doomedLocations.isEmpty();
        for (Location loc : doomedLocations) {
            if (!callToAssertionMethod(loc)) {
                allCallToAssertionMethod = false;
            }
        }
        if (allCallToAssertionMethod) {
            return;
        }

        // Add Locations in the set of locations at least one of which
        // is guaranteed to be dereferenced

        SortedSet<Location> sourceLocations;
        if (doomedLocations.isEmpty() || doomedLocations.size() > 3 && doomedLocations.size() > assignedNullLocationSet.size()) {
            sourceLocations = new TreeSet<>(assignedNullLocationSet);
        } else {
            sourceLocations = doomedLocations;
        }

        if (doomedLocations.isEmpty() || derefLocationSet.isEmpty()) {
            return;
        }

        WarningPropertySet<WarningProperty> propertySet = new WarningPropertySet<>();

        addPropertiesForDereferenceLocations(propertySet, derefLocationSet, false);

        int minDereferencePC = minPC(derefLocationSet);
        int distance1 = minDereferencePC - maxPC(assignedNullLocationSet);
        int distance2 = minDereferencePC - maxPC(doomedLocations);
        int distance = Math.max(distance1, distance2);
        /*
        if (false) {
            System.out.printf("%9d %9d %9d RANGE %s.%s%s\n", distance, distance1, distance2, classContext.getClassDescriptor()
                    .toDottedClassName(), method.getName(), method.getSignature());
        }
         */

        // Create BugInstance

        BitSet knownNull = new BitSet();

        SortedSet<SourceLineAnnotation> knownNullLocations = new TreeSet<>();
        for (Location loc : sourceLocations) {
            SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstruction(classContext, method, loc);
            if (sourceLineAnnotation == null) {
                continue;
            }
            int startLine = sourceLineAnnotation.getStartLine();
            if (startLine == -1) {
                knownNullLocations.add(sourceLineAnnotation);
            } else if (!knownNull.get(startLine)) {
                knownNull.set(startLine);
                knownNullLocations.add(sourceLineAnnotation);
            }
        }

        FieldAnnotation storedField = null;
        MethodAnnotation invokedMethod = null;
        XMethod invokedXMethod = null;
        int parameterNumber = -1;
        if (derefLocationSet.size() == 1) {

            Location loc = derefLocationSet.iterator().next();

            PointerUsageRequiringNonNullValue pu = null;
            try {
                UsagesRequiringNonNullValues usages = classContext.getUsagesRequiringNonNullValues(method);
                pu = usages.get(loc, refValue, vnaDataflow);
            } catch (DataflowAnalysisException e) {
                AnalysisContext.logError("Error getting UsagesRequiringNonNullValues for " + method, e);
            } catch (CFGBuilderException e) {
                AnalysisContext.logError("Error getting UsagesRequiringNonNullValues for " + method, e);
            }

            if (pu == null) {
                assert true; // nothing to do
            } else if (deref.isReadlineValue()) {
                bugType = "NP_DEREFERENCE_OF_READLINE_VALUE";
                priority = NORMAL_PRIORITY;
            } else if (deref.isMethodReturnValue() && !deref.isReadlineValue()) {
                bugType = "NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE";
                priority = NORMAL_PRIORITY;
            } else if (pu.isReturnFromNonNullMethod()) {
                bugType = "NP_NONNULL_RETURN_VIOLATION";
                String methodName = method.getName();
                String methodSig = method.getSignature();
                if ("clone".equals(methodName) && "()Ljava/lang/Object;".equals(methodSig)) {
                    bugType = "NP_CLONE_COULD_RETURN_NULL";
                    priority = NORMAL_PRIORITY;
                } else if ("toString".equals(methodName) && "()Ljava/lang/String;".equals(methodSig)) {
                    bugType = "NP_TOSTRING_COULD_RETURN_NULL";
                    priority = NORMAL_PRIORITY;
                }

            } else {
                XField f = pu.getNonNullField();
                if (f != null) {
                    storedField = FieldAnnotation.fromXField(f);
                    bugType = "NP_STORE_INTO_NONNULL_FIELD";
                } else {
                    XMethodParameter mp = pu.getNonNullParameter();
                    if (mp != null) {
                        invokedXMethod = mp.getMethod();
                        for (Location derefLoc : derefLocationSet) {
                            if (safeCallToPrimateParseMethod(invokedXMethod, derefLoc)) {
                                return;
                            }
                        }
                        invokedMethod = MethodAnnotation.fromXMethod(mp.getMethod());
                        if (mp.getParameterNumber() == 0
                                && TypeQualifierNullnessAnnotationDatabase.assertsFirstParameterIsNonnull(invokedXMethod)) {
                            return;
                        }
                        parameterNumber = mp.getParameterNumber();
                        bugType = "NP_NULL_PARAM_DEREF";
                    }
                }
            }
        }

        boolean hasManyNullTests = true;
        for (SourceLineAnnotation sourceLineAnnotation : knownNullLocations) {
            if (!hasManyPreceedingNullTests(sourceLineAnnotation.getStartBytecode())) {
                hasManyNullTests = false;
            }
        }
        if (hasManyNullTests) {
            if ("NP_NULL_ON_SOME_PATH".equals(bugType) || "NP_GUARANTEED_DEREF".equals(bugType)) {
                bugType = "NP_NULL_ON_SOME_PATH_MIGHT_BE_INFEASIBLE";
            } else {
                priority++;
            }
        }

        BugInstance bugInstance = new BugInstance(this, bugType, priority).addClassAndMethod(classContext.getJavaClass(), method);
        if (invokedMethod != null) {
            assert invokedXMethod != null;
            XMethod i = invokedXMethod.resolveAccessMethodForMethod();
            if (i != invokedXMethod) {
                bugInstance.addMethod(i).describe(MethodAnnotation.METHOD_CALLED);
            } else {
                bugInstance.addMethod(invokedMethod).describe(MethodAnnotation.METHOD_CALLED)
                .addParameterAnnotation(parameterNumber, "INT_MAYBE_NULL_ARG");
            }
        }
        if (storedField != null) {
            bugInstance.addField(storedField).describe("FIELD_STORED");
        }
        bugInstance.addOptionalAnnotation(variableAnnotation);
        if (variableAnnotation instanceof FieldAnnotation) {
            bugInstance.describe("FIELD_CONTAINS_VALUE");
        }

        addPropertiesForDereferenceLocations(propertySet, derefLocationSet, false);

        if (deref.isAlwaysOnExceptionPath()) {
            propertySet.addProperty(NullDerefProperty.ALWAYS_ON_EXCEPTION_PATH);
        }

        if (!assignedNullLocationSet.isEmpty() && distance > 100) {
            propertySet.addProperty(NullDerefProperty.LONG_RANGE_NULL_SOURCE);
        }

        propertySet.decorateBugInstance(bugInstance);

        if ("NP_DEREFERENCE_OF_READLINE_VALUE".equals(bugType)) {

            int source = -9999;
            if (knownNullLocations.size() == 1) {
                source = knownNullLocations.iterator().next().getEndBytecode();
            }
            for (Location loc : derefLocationSet) {
                int pos = loc.getHandle().getPosition();
                if (pos != source + 3) {
                    // another detector
                    bugAccumulator.accumulateBug(bugInstance,
                            SourceLineAnnotation.fromVisitedInstruction(classContext, method, loc));
                }
            }

        } else {
            for (Location loc : derefLocationSet) {
                bugInstance.addSourceLine(classContext, method, loc).describe(getDescription(loc, refValue));
            }

            if (sourceLocations == doomedLocations && assignedNullLocationSet.size() == 1) {
                Location assignedNull = assignedNullLocationSet.iterator().next();
                SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstruction(classContext, method,
                        assignedNull);
                if (sourceLineAnnotation != null) {
                    int startLine = sourceLineAnnotation.getStartLine();
                    if (startLine > 0 && !knownNull.get(startLine)) {
                        bugInstance.add(sourceLineAnnotation).describe("SOURCE_LINE_NULL_VALUE");
                    }
                }

            }
            for (SourceLineAnnotation sourceLineAnnotation : knownNullLocations) {
                bugInstance.add(sourceLineAnnotation).describe("SOURCE_LINE_KNOWN_NULL");
            }

            // Report it
            bugReporter.reportBug(bugInstance);
        }
    }
624456
@Override
    public void createControlAdapter() {
        if (TraceComponent.isAnyTracingEnabled()
            && tc.isEntryEnabled())
            SibTr.entry(tc, "createControlAdapter");
        _controlAdapter = new MessageProcessorControl(this);
        if (TraceComponent.isAnyTracingEnabled()
            && tc.isEntryEnabled())
            SibTr.exit(tc, "createControlAdapter");
    }
1297638
public synchronized Object ensureControl()
    {
        if (_control == null)
        {
            //
            // See if the property map specifies an implementation class for the control; 
            // if not, use default binding.
            //

            String implBinding = null;
            BaseProperties bp = _properties.getPropertySet( BaseProperties.class );
            if ( bp != null )
                implBinding = bp.controlImplementation();
            else
                implBinding = ControlUtils.getDefaultControlBinding(_controlIntf);

            try
            {
                _implClass = _controlIntf.getClassLoader().loadClass(implBinding);

                //
                // Validate that the specified implementation class has an @ControlImplementation
                // annotation, else downstream requirements (such as having a valid control init
                // class) will not be met.
                //
                if (_implClass.getAnnotation(ControlImplementation.class) == null)
                {
                    throw new ControlException("@" + ControlImplementation.class.getName() + " annotation is missing from control implementation class: " + _implClass.getName());
                }
            }
            catch (ClassNotFoundException cnfe)
            {
                throw new ControlException("Unable to load control implementation: "  + implBinding, cnfe);
            }

            //
            // Cache the threading policy associated with the impl
            //
            Threading thr = (Threading)_implClass.getAnnotation(Threading.class);
            if ( thr != null )
                _threadingPolicy = thr.value();
            else
                _threadingPolicy = ThreadingPolicy.SINGLE_THREADED;    // default to single-threaded

            ensureThreadingBehaviour();

            try
            {
                //
                // Create and initialize the new instance
                //
                _control = _implClass.newInstance();

                try
                {
                    /*
                    Run the ImplInitializer.  This class is code generated based on metadata from a control
                    implementation.  If a Control implementation declares event handlers for the
                    ControlBeanContext or for the ResourceContext, executing this code generated class
                    will add the appropriate LifeCycle and / or Resource event listeners.
                     */
                    getImplInitializer().initialize(this, _control);
                    _hasServices = true;
                }
                catch (Exception e)
                {
                    throw new ControlException("Control initialization failure", e);
                }

                //
                // Once the control is initialized, then allow the associated context
                // to do any initialization.
                //
                ControlBeanContext cbcs = getBeanContextProxy();

                /*
                Implementation note: this call will run the LifeCycleListener(s) that have
                been wired-up to the ControlBeanContext object associated with this ControlBean.
                */
                cbcs.initializeControl();
            }
            catch (RuntimeException re) {
                // never mask RuntimeExceptions
                throw re;
            }
            catch (Exception e)
            {
                throw new ControlException("Unable to create control instance", e);
            }
        }

        //
        // If the implementation instance does not currently have contextual services, they
        // are lazily restored here.
        //
        if (!_hasServices)
        {
            getImplInitializer().initServices(this, _control);
            _hasServices = true;
        }

        return _control;
    }
187828
private static ObjectType dereferenced(@Nullable JSType type) {
    return type == null ? null : type.dereference();
  }
185197
@Override
	public void initDownstream()
	{
		for (Controller controller : ctrl.getController())
		{
			if (controller instanceof Pathway) continue;

			PhysicalEntity pe = (PhysicalEntity) controller;
			bindDownstream(pe);
		}

		for (Control control : ctrl.getControlledOf())
		{
			bindDownstream(control);
		}

		for (Process prc : ctrl.getControlled())
		{
			if (prc instanceof Interaction)
			{
				bindDownstream(prc);
			}
		}
	}
183721
public void dereferenceControllable()
  {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.entry(tc, "dereferenceControllable");
      
    _issueTime = 0;
    _timeout = 0;
    _selectionCriterias = null;
    _ackingDME = 0;  
    
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.exit(tc, "dereferenceControllable");
  }
617347
public void createControlAdapter()
  {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) 
      SibTr.entry(tc, "createControlAdapter");
    controlAdapter = new ForeignBus(messageProcessor, this);
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) 
      SibTr.exit(tc, "createControlAdapter", controlAdapter);
  }
483028
private void delRef(final int root) {
    if (root < 2)
      return;
    if (root >= this.nodesize)
      throw new IllegalStateException("Cannot dereference a variable > varnum");
    if (this.low(root) == -1)
      throw new IllegalStateException("Cannot dereference variable -1");
    if (!this.hasref(root))
      throw new IllegalStateException("Cannot dereference a variable which has no reference");
    this.decRef(root);
  }
702709
public void initIdGenerator() {
    if (idGenerator == null) {
      CommandExecutor idGeneratorCommandExecutor = null;
      if (idGeneratorDataSource != null) {
        ProcessEngineConfigurationImpl processEngineConfiguration = new StandaloneProcessEngineConfiguration();
        processEngineConfiguration.setDataSource(idGeneratorDataSource);
        processEngineConfiguration.setDatabaseSchemaUpdate(DB_SCHEMA_UPDATE_FALSE);
        processEngineConfiguration.init();
        idGeneratorCommandExecutor = processEngineConfiguration.getCommandExecutor();
      } else if (idGeneratorDataSourceJndiName != null) {
        ProcessEngineConfigurationImpl processEngineConfiguration = new StandaloneProcessEngineConfiguration();
        processEngineConfiguration.setDataSourceJndiName(idGeneratorDataSourceJndiName);
        processEngineConfiguration.setDatabaseSchemaUpdate(DB_SCHEMA_UPDATE_FALSE);
        processEngineConfiguration.init();
        idGeneratorCommandExecutor = processEngineConfiguration.getCommandExecutor();
      } else {
        idGeneratorCommandExecutor = getCommandExecutor();
      }

      DbIdGenerator dbIdGenerator = new DbIdGenerator();
      dbIdGenerator.setIdBlockSize(idBlockSize);
      dbIdGenerator.setCommandExecutor(idGeneratorCommandExecutor);
      dbIdGenerator.setCommandConfig(getDefaultCommandConfig().transactionRequiresNew());
      idGenerator = dbIdGenerator;
    }
  }
480277
public void deregisterMonitor(ConnectionImpl connection,
                                ConsumerSetChangeCallback callback)
  throws SINotPossibleInCurrentConfigurationException
  {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
        SibTr.entry(
          tc,
          "deregisterMonitor",
          new Object[] { connection, callback});

    // Retrieve the callback from the index
    TopicRecord tRecord = retrieveCallbackFromConnectionIndex(connection, callback);

    if(tRecord != null)
    {
      // Have found the callback in the index, now remove the callback from
      // the appropriate registered monitors table.
      if(tRecord.isWildcarded)
      {
        removeCallbackFromRegisteredMonitors(callback,
                                             tRecord.topicExpression,
                                             true, // isWildcarded
                                             _registeredWildcardConsumerMonitors);
      }
      else
      {
        // Handle the non-wildcard case
        removeCallbackFromRegisteredMonitors(callback,
                                             tRecord.topicExpression,
                                             false, // isWildcarded
                                             _registeredExactConsumerMonitors);
      }
    }
    else
    {
      // Failed to find any reference to callback
      // Build the message for the Exception
      if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
        SibTr.exit(tc, "deregisterMonitor", callback);

      SibTr.error(tc, "INTERNAL_MESSAGING_ERROR_CWSIP0005",
        new Object[] {
          "com.ibm.ws.sib.processor.matching.ConsumerMonitorRegistrar",
          "1:237:1.10",
          callback });
      throw new SINotPossibleInCurrentConfigurationException(
        nls.getFormattedMessage(
          "INTERNAL_MESSAGING_ERROR_CWSIP0005",
          new Object[] {
            "com.ibm.ws.sib.processor.matching.ConsumerMonitorRegistrar",
            "1:244:1.10",
            callback },
          null));

    }

    // Now remove the callback from the index
    removeCallbackFromConnectionIndex(connection, callback);

    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.exit(tc, "deregisterMonitor");
  }
234650
@Override
    public void setDTDHandler(DTDHandler handler) {
        if (handler == null) {
            handler = base;
        }
        this.dtdHandler = handler;
    }
246612
@Override
    public void createControlAdapter()
    {
        if (tc.isEntryEnabled())
            SibTr.entry(tc, "createControlAdapter");
        controlAdapter = new ForeignDestination(messageProcessor, this);
        if (tc.isEntryEnabled())
            SibTr.exit(tc, "createControlAdapter", controlAdapter);
    }
297221
public static Pattern controlsDegradationIndirectly()
	{
		Pattern p = controlsStateChange();
		p.add(new Size(new ParticipatesInConv(RelType.INPUT), 1, Size.Type.EQUAL), "output PE");
		p.add(new Empty(peToControl()), "output PE");
		p.add(new ParticipatesInConv(RelType.INPUT), "output PE", "degrading Conv");
		p.add(new NOT(type(ComplexAssembly.class)), "degrading Conv");
		p.add(new Size(participant(), 1, Size.Type.EQUAL), "degrading Conv");
		p.add(new Empty(new Participant(RelType.OUTPUT)), "degrading Conv");
		p.add(new Empty(convToControl()), "degrading Conv");
		p.add(equal(false), "degrading Conv", "Conversion");
		return p;
	}
441502
private MetadataReferenceDao getMetadataReferenceDao() throws SQLException {
		if (metadataReferenceDao == null) {
			metadataReferenceDao = DaoManager.createDao(connectionSource,
					MetadataReference.class);
		}
		return metadataReferenceDao;
	}
183502
public void createControlAdapter()
  {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) 
      SibTr.entry(tc, "createControlAdapter");
    
    controlAdapter = new MQLinkQueuePoint(destinationHandler.getMessageProcessor(), this);
    
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) 
      SibTr.exit(tc, "createControlAdapter");
  }