/*
(non-Javadoc)

@see
javax.slee.resource.ResourceAdaptor#eventUnreferenced(javax.slee.resource
.ActivityHandle, javax.slee.resource.FireableEventType, java.lang.Object,
javax.slee.Address, javax.slee.resource.ReceivableService, int)
176422
public void eventUnreferenced(ActivityHandle arg0, FireableEventType arg1, Object arg2, Address arg3,
            ReceivableService arg4, int arg5) {
        if (tracer.isFineEnabled()) {
            tracer.fine(String.format("Event=%s unreferenced", arg2));
        }

        if (arg2 instanceof ResponseEvent) {
            ResponseEvent event = (ResponseEvent) arg2;
            HttpResponse response = event.getHttpResponse();

            // May be this event is carrying Exception and not actual Response
            // in which case
            // skip housekeeping
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException e) {
                    this.tracer.severe("Exception while housekeeping. Event unreferenced", e);
                }
            }
        }
    }
964948
private void lockEvent(EventId eventId) {
		Lockable<V> eventWrapper = sharedBuffer.getEvent(eventId);
		checkState(
			eventWrapper != null,
			"Referring to non existent event with id %s",
			eventId);
		eventWrapper.lock();
		sharedBuffer.upsertEvent(eventId, eventWrapper);
	}
852918
@Override protected void handleEvents(final String EVENT_TYPE) {
        super.handleEvents(EVENT_TYPE);

        if ("VISIBILITY".equals(EVENT_TYPE)) {
            Helper.enableNode(titleText, !tile.getTitle().isEmpty());
            Helper.enableNode(valueText, tile.isValueVisible());
            Helper.enableNode(unitText, !tile.getUnit().isEmpty());
        }
    }
358981
public void eventRestored() throws SevereMessageStoreException {
    super.eventRestored();
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "eventRestored");
    try {
      NonLockingCursor cursor = newNonLockingItemCursor(null);
      AbstractItem item = cursor.next();
      while (item != null) {
        if (item instanceof SchemaStoreItem) {
          addToIndex((SchemaStoreItem)item);
          if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "JSchema found in store: " + ((SchemaStoreItem)item).getSchema().getID());
        }
        item = cursor.next();
      }
    } catch (MessageStoreException e) {
      FFDCFilter.processException(e, "eventRestored", "108", this);
    }
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "eventRestored");
  }
677755
public void markUnresolvable(EObject referenced) {
		if (!referenced.eIsProxy()) {
			throw new IllegalArgumentException("Cannot mark an instance as unresolvable if it is already resolved");
		}
		URI proxyURI = ((InternalEObject)referenced).eProxyURI();
		getUnresolvableURIFragments().add(proxyURI.fragment());
	}
297954
@Override
    public void serviceChanged(ServiceEvent serviceEvent) {
        final String topic = getTopic(serviceEvent);

        // Bail quickly if the event is one that should be ignored
        if (topic == null) {
            return;
        }

        // Event properties
        Map<String, Object> eventProperties = new HashMap<String, Object>();

        // "event" --> the original event object
        eventProperties.put(EventConstants.EVENT, serviceEvent);

        // "service" --> result of getServiceReference
        // "service.id" --> the service's ID
        // "service.pid" --> the service's persistent ID if not null
        // "service.objectClass" --> the services object class
        ServiceReference serviceReference = serviceEvent.getServiceReference();
        if (serviceReference != null) {
            eventProperties.put(EventConstants.SERVICE, serviceReference);

            Long serviceId = (Long) serviceReference.getProperty(Constants.SERVICE_ID);
            eventProperties.put(EventConstants.SERVICE_ID, serviceId);

            Object servicePersistentId = serviceReference.getProperty(Constants.SERVICE_PID);
            if (servicePersistentId != null) {
                // String[] must be coerced into Collection<String>
                if (servicePersistentId instanceof String[]) {
                    servicePersistentId = Arrays.asList((String[]) servicePersistentId);
                }
                eventProperties.put(EventConstants.SERVICE_PID, servicePersistentId);
            }

            String[] objectClass = (String[]) serviceReference.getProperty(Constants.OBJECTCLASS);
            if (objectClass != null) {
                eventProperties.put(EventConstants.SERVICE_OBJECTCLASS, objectClass);
            }
        }

        // Construct and fire the event
        Event event = new Event(topic, eventProperties);
        eventAdmin.postEvent(event);
    }
571348
public void eventProcessingSuccessful(ActivityHandle activityHandle, FireableEventType fireableEventType,
            Object object, Address address, ReceivableService receivableService, int integer) {
        // not used
    }
1332364
@Override
    public void updateDefinition(BaseDestinationDefinition destinationDefinition)
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(
                        tc,
                        "updateDefinition",
                        new Object[] { destinationDefinition });

        DestinationDefinition oldDefinition = definition;
        DestinationDefinition newDefinition = (DestinationDefinition) destinationDefinition;

        super.updateDefinition(destinationDefinition);

        _maxFailedDeliveries = definition.getMaxFailedDeliveries();

        // at runtime the blockedretryinterval was not getting updated
        // since this piece of code was missing
        _blockedRetryInterval = definition.getBlockedRetryTimeout();

        //update TRM if necessary
        registerDestination();

        // Convert array of names to list of jsDestinationAddresses
        QualifiedDestinationName[] names = definition.getForwardRoutingPath();

        if (names != null)
        {
            ArrayList newFRP = new ArrayList(names.length);
            for (int name = 0; name < names.length; name++)
            {
                newFRP.add(SIMPUtils.createJsDestinationAddress(
                                                                names[name].getDestination(),
                                                                null,
                                                                names[name].getBus()));
            }
            _forwardRoutingPath = newFRP;
        }
        else
        {
            _forwardRoutingPath = null;
        }

        _replyDestination = null;
        _replySet = false;

        // Check whether send allowed has changed
        if (oldDefinition != null &&
            (oldDefinition.isSendAllowed() != newDefinition.isSendAllowed()))
        {
            fireSendAllowedStateChangeEvent(newDefinition.isSendAllowed());
        }

        if (oldDefinition != null &&
            (oldDefinition.isReceiveAllowed() != newDefinition.isReceiveAllowed()))
        {
            fireReceiveAllowedStateChangeEvent(newDefinition.isReceiveAllowed());
        }

        if (!_reconciled)
            setIsOrdered(definition.isOrderingRequired());

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "updateDefinition");
    }
201037
protected void eventPreUnlocked(SIMPMessage msg, TransactionCommon tran)
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(tc, "eventPreUnlocked", new Object[] { msg, msg.guessRedeliveredCount() });

        /*
         * 166955.4
         * Check whether the retryCount has been exceeded. If it has then this is a poison msg
         * and needs to be sent to the exception destination rather than to a valid consumer
         * again
         */
        // But only check for messages that are not persistently locked (messages involved in RemoteGet)
        // Otherwise the remote get protocols dont work

        if ((msg.guessRedeliveredCount() + 1) >= _baseDestHandler.getMaxFailedDeliveries())
        {
            /*
             * Message has been delivered a greater number of times than allowed.
             * Route message on to the exception destination associated with this
             * destination.
             */

            // Deregister rollback callbacks to avoid recursive event callbacks
            msg.deregisterMessageEventListener(MessageEvents.POST_ROLLBACK_REMOVE, this);
            msg.deregisterMessageEventListener(MessageEvents.POST_ROLLBACK_ADD, this);

            UndeliverableReturnCode rc = null;
            try
            {
                if (_isPubSub)
                {
                    // F001333-14610
                    // Pass the subscription ID to the destination handler
                    // so that it can be set on the exceptioned message.
                    rc = _baseDestHandler.handleUndeliverableMessage(msg,
                                                                     SIRCConstants.SIRC0035_BACKOUT_THRESHOLD_ERROR,
                                                                     new String[] { _baseDestHandler.getName(),
                                                                                   _messageProcessor.getMessagingEngineName() },
                                                                     tran,
                                                                     dispatcherState.getSubscriberID());
                }
                else
                {
                    // Not pub sub so no subscription ID to pass
                    rc = _baseDestHandler.handleUndeliverableMessage(msg,
                                                                     SIRCConstants.SIRC0035_BACKOUT_THRESHOLD_ERROR,
                                                                     new String[] { _baseDestHandler.getName(),
                                                                                   _messageProcessor.getMessagingEngineName() },
                                                                     tran);
                }
            } catch (SIResourceException e)
            {
                // No FFDC code needed
                // Exception had already been handled
            }

            // re-register the callbacks
            msg.registerMessageEventListener(MessageEvents.POST_ROLLBACK_REMOVE, this);
            msg.registerMessageEventListener(MessageEvents.POST_ROLLBACK_ADD, this);

            if (rc == null || rc == UndeliverableReturnCode.ERROR)
            {
                // Spin of a new alarm
                _messageProcessor.getAlarmManager().
                                create(SIMPConstants.EXCEPTION_RETRY_TIMEOUT,
                                       new ExceptionDestinationRetryHandler(msg, this));
            }

            if (rc == UndeliverableReturnCode.BLOCK)
            {
                // PK03344 - Handle retry count when no exception destination available
                // When the retry count is reached and we have nowhere to send the message
                // we suspend the consumer for a period of time to avoid 100% cpu usage
                // due to continuous message retry.

                // MDBs will only have one consumer (PK03344 handles the MDB case).
                // For multiple consumers we suspend them all.

                // Pause the consumers for the specified time
                pauseConsumers(msg, _baseDestHandler.getBlockedRetryInterval());
            }

            if (rc != UndeliverableReturnCode.BLOCK)
                msg.setRedeliveryCountReached();

        } // End of 165955.4

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "eventPreUnlocked");
    }
226827
public void valueUnbound( HttpSessionBindingEvent event )
    {
        //
        // We may have lost our transient ServletContext reference.  Try to get the ServletContext reference from the
        // HttpSession object if necessary.
        //
        ServletContext servletContext = getServletContext();
        HttpSession session = event.getSession();

        if ( servletContext == null && session != null )
        {
            servletContext = session.getServletContext();
        }

        if ( servletContext != null )
        {
            if ( !_isDestroyed && Handlers.get( servletContext ).getStorageHandler().allowBindingEvent( event ) )
            {
                destroy( session );
                _isDestroyed = true;
            }
        }
    }
1167070
@Override protected void handleEvents(final String EVENT_TYPE) {
        super.handleEvents(EVENT_TYPE);
        if ("RECALC".equals(EVENT_TYPE)) {
            referenceValue = tile.getReferenceValue() < maxValue ? maxValue : tile.getReferenceValue();
            angleStep      = ANGLE_RANGE / range;
            sum            = dataList.stream().mapToDouble(ChartData::getValue).sum();
            sections       = tile.getSections();
            redraw();
            setBar(tile.getCurrentValue());
        } else if ("VISIBILITY".equals(EVENT_TYPE)) {
            enableNode(titleText, !tile.getTitle().isEmpty());
            enableNode(text, tile.isTextVisible());
            enableNode(unitText, !tile.getUnit().isEmpty());
            enableNode(descriptionText, tile.isValueVisible());
        }
    }
979281
@Override
    public final void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt == Http2ConnectionPrefaceAndSettingsFrameWrittenEvent.INSTANCE) {
            // The user event implies that we are on the client.
            tryExpandConnectionFlowControlWindow(connection());
        } else if (evt instanceof UpgradeEvent) {
            UpgradeEvent upgrade = (UpgradeEvent) evt;
            try {
                onUpgradeEvent(ctx, upgrade.retain());
                Http2Stream stream = connection().stream(HTTP_UPGRADE_STREAM_ID);
                if (stream.getProperty(streamKey) == null) {
                    // TODO: improve handler/stream lifecycle so that stream isn't active before handler added.
                    // The stream was already made active, but ctx may have been null so it wasn't initialized.
                    // https://github.com/netty/netty/issues/4942
                    onStreamActive0(stream);
                }
                upgrade.upgradeRequest().headers().setInt(
                        HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), HTTP_UPGRADE_STREAM_ID);
                stream.setProperty(upgradeKey, true);
                InboundHttpToHttp2Adapter.handle(
                        ctx, connection(), decoder().frameListener(), upgrade.upgradeRequest().retain());
            } finally {
                upgrade.release();
            }
            return;
        }
        super.userEventTriggered(ctx, evt);
    }
593192
@Override
    public <P> void pojoDaoCreated(PojoDaoFactoryEvent<P> event) {
        String tableName = event.getTableName();
        Schema schema = new Schema();
        event.getPojoBinding().describe(schema.createTable(tableName), schema);

        schema.items().forEach(schemaItem -> {
            final String key = schemaItem.getKey();
            final String claimId = UUID.randomUUID().toString();
            session.execute(insertStatement.bind(key, claimId));
            Row row = session.execute(selectStatement.bind(key)).one();
            if (StringUtils.equals(claimId, row.getString(0))) {
                final SchemaStatement statement = schemaItem.createStatement();
                LOGGER.info("Creating table(s) to support \"{}\":\n\t{}\n", event.getPojoBinding().getPojoType().getSimpleName(), statement);
                session.execute(statement);
            }
        });
    }
310223
@Override protected void handleEvents(final String EVENT_TYPE) {
        super.handleEvents(EVENT_TYPE);

        if ("VISIBILITY".equals(EVENT_TYPE)) {
            Helper.enableNode(titleText, !tile.getTitle().isEmpty());
            Helper.enableNode(text, tile.isTextVisible());
            webView.setMaxSize(size * 0.9, tile.isTextVisible() ? size * 0.68 : size * 0.795);
            webView.setPrefSize(size * 0.9, tile.isTextVisible() ? size * 0.68 : size * 0.795);
        } else if ("LOCATION".equals(EVENT_TYPE)) {
            tile.getCurrentLocation().addLocationEventListener(locationListener);
            updateLocation();
        } else if ("TRACK".equals(EVENT_TYPE)) {
            addTrack(tile.getTrack());
        } else if ("MAP_PROVIDER".equals(EVENT_TYPE)) {
            changeMapProvider(tile.getMapProvider());
        }
    }
1112308
@Override
    public void onEvent(InteractionEvent event) {
        switch (event.getType()) {
        case BEFORE_WAIT:
            onBeforeWaitEvent((BeforeWaitInteractionEvent) event);
            break;
        case BEFORE:
            onBeforeEvent((BeforeInteractionEvent) event);
            break;
        case AFTER_SUCCESS:
            onAfterSuccessEvent((AfterSuccessInteractionEvent) event);
            onAfterEvent((AfterInteractionEvent) event);
            break;
        case AFTER_FAIL:
            onAfterFailEvent((AfterFailInteractionEvent) event);
            onAfterEvent((AfterInteractionEvent) event);
            break;
        }
    }
752805
@SuppressWarnings("PMD.SwitchStmtsShouldHaveDefault")
  public void dispatch(@NonNull JCacheEntryEvent<K, V> event) {
    try {
      if (event.getSource().isClosed()) {
        return;
      }
      switch (event.getEventType()) {
        case CREATED:
          onCreated(event);
          return;
        case UPDATED:
          onUpdated(event);
          return;
        case REMOVED:
          onRemoved(event);
          return;
        case EXPIRED:
          onExpired(event);
          return;
      }
      throw new IllegalStateException("Unknown event type: " + event.getEventType());
    } catch (Exception e) {
      logger.log(Level.WARNING, null, e);
    } catch (Throwable t) {
      logger.log(Level.SEVERE, null, t);
    }
  }
276464
protected void handleAdapterInvocationError(Throwable errorCause)
        throws ActivityException {
        logger.severeException(getAdapterInvocationErrorMessage(), errorCause);
        boolean isErrorRetryable;
        int errorCode;
        if (errorCause instanceof AdapterException) {
            AdapterException adEx = (AdapterException) errorCause;
            isErrorRetryable = adEx.isRetryable();
            if (adEx.getCode() != 0) {
                errorCode = adEx.getCode();
            }
            else {
                errorCode = ServiceException.INTERNAL_ERROR;
            }
        }
        else if (errorCause instanceof ConnectionException) {
            errorCode = ((ConnectionException)errorCause).getCode();
            // if process is invoked sync style, no need to retry due to connection failure
            Process procVO = getProcessDefinition();
            if (procVO.getProcessType().equals(ProcessVisibilityConstant.SERVICE)) {
                super.setReturnCode("ERROR:");
                return;
            }
            isErrorRetryable = true;
        }
        else {
            errorCode = ServiceException.INTERNAL_ERROR;
            isErrorRetryable = false;
        }

        if (isErrorRetryable) {
            super.setReturnCode(ActivityResultCodeConstant.RESULT_RETRY);
        }

        this.handleAdapterFailure(errorCode, errorCause);
    }