/*
@see org.cafesip.sipunit.MessageListener#processEvent(java.util.EventObject)
334082
public void processEvent(EventObject event) // for asynchronous
  // (nonblocking) response
  // handling
  {
    synchronized (this) {
    } // wail til message sending has finished (transaction attribute set)

    if (event instanceof ResponseEvent) {
      processResponse((ResponseEvent) event);
    } else if (event instanceof TimeoutEvent) {
      processTimeout((TimeoutEvent) event);
    }

    // note, requests don't come through here, they are handled via the
    // listen/waitFor methods.
  }
699900
public void processTimeout(final TimeoutEvent timeoutEvent) {
		Transaction eventTransaction = null;
		if(timeoutEvent.isServerTransaction()) {
			eventTransaction = timeoutEvent.getServerTransaction();
		} else {
			eventTransaction = timeoutEvent.getClientTransaction();
		}
		final Transaction transaction = eventTransaction;
		if(logger.isDebugEnabled()) {
			logger.debug("transaction " + transaction + " timed out => " + transaction.getRequest().toString());
		}

		final TransactionApplicationData tad = (TransactionApplicationData) transaction.getApplicationData();
		if(tad != null && tad.getSipServletMessage() != null) {
			// https://github.com/RestComm/sip-servlets/issues/107 guard against NPEon concurrent cleanup
			final SipServletMessageImpl sipServletMessage = tad.getSipServletMessage();
			final MobicentsSipSessionKey sipSessionKey = sipServletMessage.getSipSessionKey();
			final MobicentsSipSession sipSession = sipServletMessage.getSipSession();
			getAsynchronousExecutor().execute(new Runnable() {
				public void run() {
					try {
						if(logger.isDebugEnabled()) {
							logger.debug("transaction " + transaction + " timed out => " + transaction.getRequest().toString());
						}
						boolean appNotifiedOfPrackNotReceived = false;
						// session can be null if a message was sent outside of the container by the container itself during Initial request dispatching
						// but the external host doesn't send any response so we call out to the application only if the session is not null
						if(logger.isDebugEnabled()) {
                            logger.debug("time out happened on sipSession " + sipSession);
                        }
						if(sipSession != null) {
							SipContext sipContext = findSipApplication(sipSessionKey.getApplicationName());
							//the context can be null if the server is being shutdown
							if(sipContext != null) {
								MobicentsSipApplicationSession sipApplicationSession = sipSession.getSipApplicationSession();
								try {
									sipContext.enterSipApp(sipApplicationSession, sipSession, false, true);
									MobicentsB2BUAHelper b2buaHelperImpl = sipSession.getB2buaHelper();

									if(b2buaHelperImpl != null && tad.getSipServletMessage() instanceof SipServletRequestImpl) {
										b2buaHelperImpl.unlinkRequestInternal((SipServletRequestImpl)tad.getSipServletMessage(), false);
									}
									// naoki : Fix for Issue 1618 http://code.google.com/p/mobicents/issues/detail?id=1618 on Timeout don't do the 408 processing for Server Transactions
									if(logger.isDebugEnabled()) {
			                            logger.debug("time out happened on server tx ? " + timeoutEvent.isServerTransaction() + " and message " + sipServletMessage);
			                        }
									if(sipServletMessage instanceof SipServletRequestImpl && !timeoutEvent.isServerTransaction()) {
										try {
											ProxyBranchImpl proxyBranchImpl = tad.getProxyBranch();
											if(proxyBranchImpl != null) {
												ProxyImpl proxy = (ProxyImpl) proxyBranchImpl.getProxy();
												if(proxy.getFinalBranchForSubsequentRequests() != null) {
													tad.cleanUp();
													transaction.setApplicationData(null);
													return;
												}
											}
											SipServletRequestImpl sipServletRequestImpl = (SipServletRequestImpl) sipServletMessage;
											if(sipServletRequestImpl.visitNextHop()) {
												return;
											}
											sipServletMessage.setTransaction(transaction);
											SipServletResponseImpl response = (SipServletResponseImpl) sipServletRequestImpl.createResponse(408, null, false, true);
											// Fix for Issue 1734
											sipServletRequestImpl.setResponse(response);
											MessageDispatcher.callServlet(response);
											if(tad.getProxyBranch() != null) {
												tad.getProxyBranch().setResponse(response);
												tad.getProxyBranch().onResponse(response, response.getStatus());
											}
											sipSession.updateStateOnResponse(response, true);
										} catch (Throwable t) {
											logger.error("Failed to deliver 408 response on transaction timeout" + transaction, t);
										}
									}
									// Guard only invite tx should check that, otherwise proxy might become null http://code.google.com/p/mobicents/issues/detail?id=2350
									// Should check only Server Tx for ack or prack not received http://code.google.com/p/mobicents/issues/detail?id=2525
									if(Request.INVITE.equals(sipServletMessage.getMethod()) && timeoutEvent.isServerTransaction()) {
										checkForAckNotReceived(sipServletMessage);
										appNotifiedOfPrackNotReceived = checkForPrackNotReceived(sipServletMessage);
									}
								} finally {
									sipSession.removeOngoingTransaction(transaction);
									sipSession.setRequestsPending(0);
									sipContext.exitSipApp(sipApplicationSession, sipSession);
								}
								// don't invalidate here because if the application sends a final response on the noPrack received
								// the ACK to this final response won't be able to get routed since the sip session would have been invalidated
								if(!appNotifiedOfPrackNotReceived) {
									tryToInvalidateSession(sipSessionKey, false);
								}
							}
						}
						// don't clean up for the same reason we don't invalidate the sip session right above
						tad.cleanUp();
						transaction.setApplicationData(null);
					} catch (Exception e) {
						logger.error("Problem handling timeout", e);
					}
				}
			});
		}
	}
367417
@Override
    public void processListener(FacesListener listener) {
        UIComponent c = getComponent();
        UIComponent cFromStack;
        boolean didPush = false;
        FacesContext context = FacesContext.getCurrentInstance();
        cFromStack = UIComponent.getCurrentComponent(context);
        if (null == cFromStack) {
            didPush = true;
            c.pushComponentToEL(context, null);
        }
        try {
            if (listener instanceof SystemEventListener) {
                super.processListener(listener);
            } else if (listener instanceof ComponentSystemEventListener) {
                ((ComponentSystemEventListener)listener).processEvent(this);
            }
        } finally {
            if (didPush) {
                c.popComponentFromEL(context);
            }
        }
    }
1035380
public void processTimeout(TimeoutEvent arg0) {
    synchronized (listeners) {
      Iterator<SipListener> iter = listeners.iterator();
      while (iter.hasNext() == true) {
        SipListener listener = (SipListener) iter.next();
        listener.processTimeout(arg0);
      }
    }
  }
677644
@Override
	public boolean process(ContentEvent event) {
		if (event instanceof InstanceContentEvent) {
			this.processInstanceEvent((InstanceContentEvent) event);
		}
		else if (event instanceof PredicateContentEvent) {
			PredicateContentEvent pce = (PredicateContentEvent) event;
			if (pce.getRuleSplitNode() == null) {
				this.updateLearningNode(pce);
			}
			else {
				this.updateRuleSplitNode(pce);
			}
		}
		else if (event instanceof RuleContentEvent) {
			RuleContentEvent rce = (RuleContentEvent) event;
			if (rce.isRemoving()) {
				this.removeRule(rce.getRuleNumberID());
			}
			else {
				addRule(rce.getRule());
			}
		}
		return true;
	}
575858
public void processTimeout(TimeoutEvent timeout) {
    ClientTransaction trans = timeout.getClientTransaction();
    if (trans == null) {
      return;
    }

    SipTransaction sip_trans = null;
    synchronized (respTransactions) {
      sip_trans = (SipTransaction) respTransactions.get(trans);
    }

    if (sip_trans == null) {
      return;
    }

    if (trans.getState().getValue() == TransactionState._TERMINATED) {
      synchronized (respTransactions) {
        respTransactions.remove(trans);
      }
    }

    // check for listener handling
    MessageListener listener = sip_trans.getClientListener();
    if (listener != null) {
      listener.processEvent(timeout);
      return;
    }

    // if no listener, use the default blocking mechanism
    synchronized (sip_trans.getBlock()) {
      sip_trans.getEvents().addLast(timeout);
      sip_trans.getBlock().notifyEvent();
    }
  }
515245
public void processTransactionTerminated(final TransactionTerminatedEvent transactionTerminatedEvent) {
		Transaction eventTransaction = null;
		if(transactionTerminatedEvent.isServerTransaction()) {
			eventTransaction = transactionTerminatedEvent.getServerTransaction();
		} else {
			eventTransaction = transactionTerminatedEvent.getClientTransaction();
		}
		final Transaction transaction = eventTransaction;
		if(logger.isDebugEnabled()) {
			logger.info("transaction " + transaction + " terminated => " + transaction.getRequest());
		}

		final TransactionApplicationData tad = (TransactionApplicationData) transaction.getApplicationData();
		final String branchId = transaction.getBranchId();
		if(tad != null && tad.getSipServletMessage() != null) {
			// https://github.com/RestComm/sip-servlets/issues/107 guard against NPEon concurrent cleanup
			final SipServletMessageImpl sipServletMessageImpl = tad.getSipServletMessage();
			final MobicentsSipSessionKey sipSessionKey = sipServletMessageImpl.getSipSessionKey();
			final MobicentsSipSession sipSession = sipServletMessageImpl.getSipSession();
			getAsynchronousExecutor().execute(new Runnable() {
				public void run() {
					try {
						if(logger.isDebugEnabled()) {
							logger.info("transaction " + transaction + " terminated => " + sipServletMessageImpl);
						}

						MobicentsB2BUAHelper b2buaHelperImpl = null;
						if(sipSession != null) {
							b2buaHelperImpl = sipSession.getB2buaHelper();
						}
						if(sipSessionKey == null) {
							if(logger.isDebugEnabled()) {
								logger.debug("no sip session were returned for this key " + sipServletMessageImpl.getSipSessionKey() + " and message " + sipServletMessageImpl);
							}
						}
						ProxyBranchImpl proxyBranch = tad.getProxyBranch();
						if(proxyBranch != null) {
							proxyBranch.removeTransaction(branchId);
						}

						// Issue 1333 : B2buaHelper.getPendingMessages(linkedSession, UAMode.UAC) returns empty list
						// don't remove the transaction on terminated state for INVITE Tx because it won't be possible
						// to create the ACK on second leg for B2BUA apps
						if(sipSession != null) {
							boolean removeTx = true;
							if(b2buaHelperImpl != null && (transaction == null || transaction instanceof ClientTransaction)
									&& Request.INVITE.equals(sipServletMessageImpl.getMethod())) {
								removeTx = false;
							}
							SipContext sipContext = findSipApplication(sipSessionKey.getApplicationName());
							//the context can be null if the server is being shutdown
							if(sipContext != null) {
								MobicentsSipApplicationSession sipApplicationSession = sipSession.getSipApplicationSession();
								try {
									sipContext.enterSipApp(sipApplicationSession, sipSession, false, true);

									if(removeTx) {
										if(b2buaHelperImpl != null && tad.getSipServletMessage() instanceof SipServletRequestImpl) {
											b2buaHelperImpl.unlinkRequestInternal((SipServletRequestImpl)tad.getSipServletMessage(), false);
										}
										sipSession.removeOngoingTransaction(transaction);
										// Issue 1468 : to handle forking, we shouldn't cleanup the app data since it is needed for the forked responses
										boolean nullifyAppData = true;
										if(((SipStackImpl)((SipProvider)transactionTerminatedEvent.getSource()).getSipStack()).getMaxForkTime() > 0 && Request.INVITE.equals(sipServletMessageImpl.getMethod())) {
											nullifyAppData = false;
										}
										if(nullifyAppData) {
											tad.cleanUp();
											if(b2buaHelperImpl == null && tad.getSipServletMessage() instanceof SipServletRequestImpl) {
												sipSession.cleanDialogInformation(false);
											}
											transaction.setApplicationData(null);
										}
									} else {
										if(logger.isDebugEnabled()) {
											logger.debug("Transaction " + transaction + " not removed from session " + sipSessionKey + " because the B2BUA might still need it to create the ACK");
										}
									}
								} finally {
									sipContext.exitSipApp(sipApplicationSession, sipSession);
								}
							}

							// If it is a client transaction, do not kill the proxy session http://code.google.com/p/mobicents/issues/detail?id=1024
							tryToInvalidateSession(sipSessionKey, transactionTerminatedEvent.isServerTransaction());

						}
					} catch (Exception e) {
						logger.error("Problem handling transaction termination", e);
					}
				}
			});
		} else {
			if(logger.isDebugEnabled()) {
				logger.debug("TransactionApplicationData not available on the following request " + transaction.getRequest());
			}
			if(tad != null) {
				tad.cleanUp();
			}
			transaction.setApplicationData(null);
		}

	}
532025
public boolean process(MessageEnvelope envelope) {
		if (this.event == null) {
			return false;
		}

		boolean triggered = this.event.verifyEventCondition(envelope);
		if (triggered) {
			beforeReply(envelope);
			if (this.reply != null) {
				this.reply.reply(envelope);
			}
			afterReply(envelope);
		}
		return triggered;
	}
707006
public void processResponseEvent(HttpClientNIOResponseEvent event, HttpClientNIORequestActivityImpl activity) {

        HttpClientNIORequestActivityHandle ah = new HttpClientNIORequestActivityHandle(activity.getId());

        if (tracer.isFineEnabled())
            tracer.fine("==== FIRING ResponseEvent EVENT TO LOCAL SLEE, Event: " + event + " ====");

        try {
            resourceAdaptorContext.getSleeEndpoint().fireEvent(ah, fireableEventType, event, null, null, EVENT_FLAGS);
        } catch (Throwable e) {
            tracer.severe(e.getMessage(), e);
        }
    }
403723
private QYBaseRespMsg processEventHandle(QYBaseEvent event){
        if(CollectionUtil.isEmpty(eventHandles)){
            synchronized (LOCK){
                eventHandles = this.initEventHandles();
            }
        }
        if(CollectionUtil.isNotEmpty(eventHandles)){
            for(QYEventHandle eventHandle : eventHandles){
                QYBaseRespMsg resultMsg = null;
                boolean result;
                try{
                    result = eventHandle.beforeHandle(event);
                }catch (Exception e){
                    result = false;
                }
                if(result){
                    resultMsg = eventHandle.handle(event);
                }
                if(BeanUtil.nonNull(resultMsg)){
                    return resultMsg;
                }
            }
        }
        return null;
    }
328831
@SuppressWarnings("PMD.DataflowAnomalyAnalysis")
    public void invoke(EventBase<?> event) throws Throwable {
        // ADAPT VERBOSEHANDLERREFERENCE TO ANY CHANGES MADE HERE
        switch (method.type().parameterCount()) {
        case 0:
            // No parameters
            method.invoke();
            break;

        case 1:
            // Event parameter
            method.invoke(event);
            break;

        case 2:
            // Event and channel
            Class<?> channelParam = method.type().parameterType(1);
            for (Channel channel : event.channels()) {
                if (channelParam.isAssignableFrom(channel.getClass())) {
                    method.invoke(event, channel);
                }
            }
            break;

        default:
            throw new IllegalStateException("Handle not usable");
        }
    }
786188
public void processEvent(QueryBatch batch) {
    if ( ! (batch.getClient() instanceof DatabaseClientImpl) ) {
      throw new IllegalStateException("DatabaseClient must be instanceof DatabaseClientImpl");
    }
    StringHandle uris = new StringHandle(String.join("\n", batch.getItems()))
      .withMimetype("text/uri-list");
    RESTServices services = ((DatabaseClientImpl) batch.getClient()).getServices();
    try {
      RequestParameters params = new RequestParameters();
      if ( transform != null ) transform.merge(params);
      params.add("result", applyResult.toString().toLowerCase());
      List<String> responseUris = new BufferedReader(
        services.postResource(null, "internal/apply-transform", null, params, uris, new ReaderHandle()).get()
      ).lines().collect(Collectors.toList());
      QueryBatchImpl processedBatch = new QueryBatchImpl()
        .withClient( batch.getClient() )
        .withItems( responseUris.toArray(new String[responseUris.size()]) )
        .withTimestamp( batch.getTimestamp() )
        .withJobBatchNumber( batch.getJobBatchNumber() )
        .withJobResultsSoFar( batch.getJobResultsSoFar() )
        .withForestBatchNumber( batch.getForestBatchNumber() )
        .withForestResultsSoFar( batch.getForestResultsSoFar() )
        .withForest( batch.getForest() )
        .withServerTimestamp( batch.getServerTimestamp() )
        .withJobTicket( batch.getJobTicket() );
      for ( QueryBatchListener listener : successListeners ) {
        try {
          listener.processEvent(processedBatch);
        } catch (Throwable t) {
          logger.error("Exception thrown by an onSuccess listener", t);
        }
      }

      List<String> skippedRequestUris = new ArrayList<>(Arrays.asList(batch.getItems()));
      skippedRequestUris.removeAll( responseUris );
      if ( skippedRequestUris.size() > 0 ) {
        QueryBatchImpl skippedBatch = processedBatch
          .withItems( skippedRequestUris.toArray(new String[0]) );
        for ( QueryBatchListener listener : skippedListeners ) {
          try {
            listener.processEvent(skippedBatch);
          } catch (Throwable t) {
            logger.error("Exception thrown by an onSkipped listener", t);
          }
        }
      }
    } catch (Throwable t) {
      for ( BatchFailureListener<Batch<String>> listener : failureListeners ) {
        try {
          listener.processFailure(batch, t);
        } catch (Throwable t2) {
          logger.error("Exception thrown by an onBatchFailure listener", t2);
        }
      }
      for ( BatchFailureListener<QueryBatch> queryBatchFailureListener : queryBatchFailureListeners ) {
        try {
          queryBatchFailureListener.processFailure(batch, t);
        } catch (Throwable t2) {
          logger.error("Exception thrown by an onFailure listener", t2);
        }
      }
      logger.warn("Error: {} in batch with urs ({})", t.toString(),
        Arrays.asList(batch.getItems()));
    }
  }
1324478
def _ProcessEvent(self, mediator, event):
    
    try:
      self._analysis_plugin.ExamineEvent(mediator, event)

    except Exception as exception:  # pylint: disable=broad-except
      self.SignalAbort()

      # TODO: write analysis error.

      if self._debug_output:
        logger.warning('Unhandled exception while processing event object.')
        logger.exception(exception)
283136
@Override
	public void processEvent(SystemEvent event) throws AbortProcessingException {
		if (!FacesContext.getCurrentInstance().isPostback()) {
			// if (!(getParent() instanceof Column)) {
			insertLabelBeforeThisInputField();
			insertMessageBehindThisInputField();
		}
		// }
	}
929713
public <T> void handleEvent(final T event) throws EventException {
		final Class<?> type = event.getClass();
		if (!this.cachedListeners.containsKey(event.getClass())) {
			this.cachedListeners.put(type, new LinkedList<ListenerInstancePair<?>>());
			for (final ListenerInstancePair<?> listener : this.listeners) {
				final Type observableType = GenericsUtil.getEntityGenericType(listener.listener.getClass(), 0, Listener.class);
				final Class<?> observable = GenericsUtil.guessClazz(observableType);
				if (observable.isAssignableFrom(type)) {
					this.cachedListeners.get(type).add(listener);
				}
			}
		}
		@SuppressWarnings("unchecked")
		final List<ListenerInstancePair<T>> resolvedListeners = List.class.cast(this.cachedListeners.get(event.getClass()));
		for (final ListenerInstancePair<T> listener : resolvedListeners) {
			listener.handleEvent(event, null);
		}
	}
188459
public void processDialogTimeout(final DialogTimeoutEvent timeoutEvent) {
		final Dialog dialog = timeoutEvent.getDialog();
		if(logger.isDebugEnabled()) {
			logger.info("dialog timeout " + dialog + " reason => " + timeoutEvent.getReason());
		}
		if(timeoutEvent.getReason() == Reason.AckNotReceived) {
			final TransactionApplicationData tad = (TransactionApplicationData) dialog.getApplicationData();
			if(tad != null && tad.getSipServletMessage() != null) {
				// https://github.com/RestComm/sip-servlets/issues/107 guard against NPEon concurrent cleanup
				final SipServletMessageImpl sipServletMessage = tad.getSipServletMessage();
				final MobicentsSipSessionKey sipSessionKey = sipServletMessage.getSipSessionKey();
				final MobicentsSipSession sipSession = sipServletMessage.getSipSession();
				getAsynchronousExecutor().execute(new Runnable() {
					public void run() {
						if(logger.isDebugEnabled()) {
							logger.info("Running process dialog timeout " + dialog + " reason => " + timeoutEvent.getReason());
						}
						try {
							if(sipSession != null) {
								SipContext sipContext = findSipApplication(sipSessionKey.getApplicationName());
								//the context can be null if the server is being shutdown
								if(sipContext != null) {
									MobicentsSipApplicationSession sipApplicationSession = sipSession.getSipApplicationSession();
									try {
										sipContext.enterSipApp(sipApplicationSession, sipSession, false, true);
										checkForAckNotReceived(sipServletMessage);
										checkForPrackNotReceived(sipServletMessage);
									} finally {
										sipContext.exitSipApp(sipApplicationSession, sipSession);
									}
									// Issue 1822 http://code.google.com/p/mobicents/issues/detail?id=1822
									// don't delete the dialog so that the app can send the BYE even after the noAckReceived has been called
									//								dialog.delete();
									tryToInvalidateSession(sipSessionKey, false);
								}
							}
							tad.cleanUp();
							tad.cleanUpMessage();
							dialog.setApplicationData(null);
						} catch (Exception e) {
							logger.error("Problem handling dialog timeout", e);
						}
					}
				});
			} else{
				dialog.setApplicationData(null);
			}
		} else {
			dialog.setApplicationData(null);
		}
	}
58397
@Override
  public void parseProcess(Element processElement, ProcessDefinitionEntity processDefinition) {
    addStartEventListener(processDefinition);
    addEndEventListener(processDefinition);
  }