/*
@see org.cafesip.sipunit.MessageListener#processEvent(java.util.EventObject)
195039
public void processEvent(EventObject event) {
    if (event instanceof RequestEvent) {
      processRequest((RequestEvent) event);
    } else if (event instanceof ResponseEvent) {
      processResponse((ResponseEvent) event);
    } else if (event instanceof TimeoutEvent) {
      processTimeout((TimeoutEvent) event);
    } else {
      LOG.error("invalid event type received: {}: {}", event.getClass().getName(), event.toString());
    }
  }
1126843
@Override
    public void onInteractionEvent(final InteractionEvent event) {
        QName id = event.getId();
        QName source = (QName)event.getSource();

        final Set<Procedure> collection = procedures.get(id);
        Procedure execution = null;

        if(collection!=null)
        {
            for(Procedure consumer : collection) {

                // TODO: This isn't optimal (creation of new resource with every comparison)
                Resource<ResourceType> resource = new Resource<ResourceType>(id, ResourceType.Interaction);
                resource.setSource(source);

                boolean justified = consumer.getJustification() == null
                        || source.equals(consumer.getJustification());

                if(consumer.doesConsume(resource) && justified)
                {
                    execution = consumer;
                    break;
                }
            }
        }

        if(null==execution)
        {
            Window.alert("No procedure for " + event);
            Log.warn("No procedure for " + event);
        }
        else if(execution.getPrecondition().isMet(getStatementContext(source)))   // guarded
        {
            try {
                execution.getCommand().execute(InteractionCoordinator.this.dialog, event.getPayload());
            } catch (Throwable e) {
                Log.error("Failed to execute procedure "+execution, e);
            }
        }

    }
173714
public void processThisMessage()
    {
        Utility.getLogger().info("On message called in receiving process");
        try {
            BaseMessage messageIn = this.getMessage();
            if (messageIn != null)
            {
                BaseMessage messageReply = this.createReplyMessage(messageIn);
                this.moveScreenParamsToMessage(messageReply);
                // Step 2 - Get the body part of the message
                this.getTransport().setupReplyMessage(messageReply, messageIn, MessageInfoTypeModel.REPLY, MessageTypeModel.MESSAGE_IN);
            
                this.getTransport().processIncomingMessage(messageReply, null);
            }
        } catch(Exception ex) {
            ex.printStackTrace();
            Debug.print(ex, "Error in processing or replying to a message");
        }
    }
538911
@Override
  public synchronized void handleEvent(final Event event) {
    if (event.getType() == EventType.FLOW_FINISHED) {
      final FlowRunner runner = (FlowRunner) event.getRunner();
      if (runner != null && runner.getExecutableFlow().getStatus().equals(Status.FAILED)) {
        this.value = this.value + 1;
      }
    }
  }
1369434
public void onInviteEvent(javax.sip.RequestEvent requestEvent,
			ActivityContextInterface aci) {

		final ServerTransaction serverTransaction = requestEvent
				.getServerTransaction();

		try {
			// send "trying" response
			Response response = messageFactory.createResponse(Response.TRYING,
					requestEvent.getRequest());
			serverTransaction.sendResponse(response);
			// get local object
			final SbbLocalObject sbbLocalObject = this.sbbContext
					.getSbbLocalObject();
			
			// send 180
			response = messageFactory.createResponse(Response.RINGING,
					requestEvent.getRequest());
			serverTransaction.sendResponse(response);

			setFinalReplySent(false);
			// set timer of 1 secs on the dialog aci to send 200 OK after that
			timerFacility.setTimer(aci, null,
					System.currentTimeMillis() + 1000L, getTimerOptions());			
						
		} catch (Exception e) {
			getTracer().severe("failure while processing initial invite", e);
		}
	}
1281371
@Override
	public void receiveEvent(Tree message) {

		// Verify protocol version
		if (checkVersion) {
			String ver = message.get("ver", "unknown");
			if (!ServiceBroker.PROTOCOL_VERSION.equals(ver)) {
				logger.warn("Invalid protocol version (" + ver + ")!");
				return;
			}
		}

		// Get event property
		String name = message.get("event", (String) null);
		if (name == null || name.isEmpty()) {
			logger.warn("Missing \"event\" property!");
			return;
		}

		// Get data
		Tree payload = message.get("data");

		// Process events in Moleculer V2 style
		Tree groupArray = message.get("groups");
		Groups groups = null;
		if (groupArray != null) {
			int size = groupArray.size();
			if (size > 0) {
				String[] array = new String[groupArray.size()];
				int i = 0;
				for (Tree group : groupArray) {
					array[i++] = group.asString();
				}
				groups = Groups.of(array);
			}
		}

		// Emit or broadcast?
		if (message.get("broadcast", true)) {

			// Broadcast
			broadcast(name, payload, groups, true);

		} else {

			// Emit
			emit(name, payload, groups, true);
		}
	}
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);
		}

	}
750080
public void eventReceived (DEvent event)
    {
        if (event instanceof InvocationResponseEvent) {
            InvocationResponseEvent ire = (InvocationResponseEvent)event;
            handleInvocationResponse(ire.getRequestId(), ire.getMethodId(), ire.getArgs());

        } else if (event instanceof InvocationNotificationEvent) {
            InvocationNotificationEvent ine = (InvocationNotificationEvent)event;
            handleInvocationNotification(ine.getReceiverId(), ine.getMethodId(), ine.getArgs());

        } else if (event instanceof MessageEvent) {
            MessageEvent mevt = (MessageEvent)event;
            if (mevt.getName().equals(ClientObject.CLOBJ_CHANGED)) {
                handleClientObjectChanged(((Integer)mevt.getArgs()[0]).intValue());
            }
        }
    }
1073743
protected final Event processEvent() throws IOException {
    while (true) {
      String line;
      try {
        line = readLine();
      } catch (final EOFException ex) {
        if (doneOnce) {
          throw ex;
        }
        doneOnce = true;
        line = "";
      }

      // If the line is empty (a blank line), Dispatch the event, as defined below.
      if (line.isEmpty()) {
        // If the data buffer is an empty string, set the data buffer and the event name buffer to
        // the empty string and abort these steps.
        if (dataBuffer.length() == 0) {
          eventName = "";
          continue;
        }

        // If the event name buffer is not the empty string but is also not a valid NCName,
        // set the data buffer and the event name buffer to the empty string and abort these steps.
        // NOT IMPLEMENTED

        final Event.Builder eventBuilder = new Event.Builder();
        eventBuilder.withEventName(eventName.isEmpty() ? Event.MESSAGE_EVENT : eventName);
        eventBuilder.withData(dataBuffer.toString());

        // Set the data buffer and the event name buffer to the empty string.
        dataBuffer = new StringBuilder();
        eventName = "";

        return eventBuilder.build();
        // If the line starts with a U+003A COLON character (':')
      } else if (line.startsWith(":")) {
        // ignore the line
        // If the line contains a U+003A COLON character (':') character
      } else if (line.contains(":")) {
        // Collect the characters on the line before the first U+003A COLON character (':'),
        // and let field be that string.
        final int colonIdx = line.indexOf(":");
        final String field = line.substring(0, colonIdx);

        // Collect the characters on the line after the first U+003A COLON character (':'),
        // and let value be that string.
        // If value starts with a single U+0020 SPACE character, remove it from value.
        String value = line.substring(colonIdx + 1);
        value = value.startsWith(" ") ? value.substring(1) : value;

        processField(field, value);
      // Otherwise, the string is not empty but does not contain a U+003A COLON character (':')
      // character
      } else {
        processField(line, "");
      }
    }
  }
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();
    }
  }
1256314
@Override
    public void processEvent(ListenerEvent event, SequenceVectors<T> sequenceVectors, long argument) {
        try {
            locker.acquire();

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

            StringBuilder builder = new StringBuilder(targetFolder.getAbsolutePath());
            builder.append("/").append(modelPrefix).append("_").append(sdf.format(new Date())).append(".seqvec");
            File targetFile = new File(builder.toString());

            if (useBinarySerialization) {
                SerializationUtils.saveObject(sequenceVectors, targetFile);
            } else {
                throw new UnsupportedOperationException("Not implemented yet");
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            locker.release();
        }
    }
54137
@Override
  public synchronized void handleEvent(final Event event) {
    if (event.getType() == EventType.JOB_STARTED) {
      this.value = this.value + 1;
    } else if (event.getType() == EventType.JOB_FINISHED) {
      this.value = this.value - 1;
    }
  }
63096
public void processRequest(RequestEvent requestEvent) {
        // This will be invoked only by external endpoint
    	BalancerAppContent content=(BalancerAppContent)requestEvent.getSource();
    	boolean isIpv6 = content.isIpv6();
        final SipProvider sipProvider = content.getProvider();
        final Request request = requestEvent.getRequest();
        final String requestMethod = request.getMethod();

        if(logger.isDebugEnabled()) {
            logger.debug("got request:\n"+request);
        }
        
        if((requestMethod.equals(Request.OPTIONS) ||
                requestMethod.equals(Request.INFO)) &&
                request.getHeader("Mobicents-Heartbeat") != null &&
                sipProvider == balancerRunner.balancerContext.internalSipProvider) {
            byte[] bytes = (byte[]) request.getContent();
            Properties prop = new Properties();
            try {
                prop.load(new ByteArrayInputStream(bytes, 0, bytes.length));
                Node node = new Node(prop.getProperty("hostname"), prop.getProperty("ip"));
                for(String id : prop.stringPropertyNames()) {
                    node.getProperties().put(id, prop.getProperty(id));
                }
                ArrayList<Node> list = new ArrayList<Node>();
                list.add(node);
                this.register.handlePingInRegister(list);
                Response response = balancerRunner.balancerContext.messageFactory.createResponse(Response.OK, request);			
                sipProvider.sendResponse(response);	
                return;
            } catch (Exception e) {
                logger.error("Failure parsing heartbeat properties from this request " + request, e);
            }
        }
        //Issue 10: https://telestax.atlassian.net/browse/LB-10
        if (request.getContent() != null || (requestMethod.equals(Request.REGISTER) && sipProvider != balancerRunner.balancerContext.internalSipProvider)) {
            SIPMessage message = (SIPMessage)request;            

            String initialRemoteAddr = message.getPeerPacketSourceAddress().getHostAddress();
            String initialRemotePort = String.valueOf(message.getPeerPacketSourcePort());

            Header remoteAddrHeader = null;
            Header remotePortHeader = null;
            try {
                remoteAddrHeader = SipFactory.getInstance().createHeaderFactory().createHeader("X-Sip-Balancer-InitialRemoteAddr", initialRemoteAddr);
                remotePortHeader = SipFactory.getInstance().createHeaderFactory().createHeader("X-Sip-Balancer-InitialRemotePort", initialRemotePort);
            } catch (PeerUnavailableException e) {
                logger.error("Unexpected exception while creating custom headers for REGISTER message ", e);
            } catch (ParseException e) {
                logger.error("Unexpected exception while creating custom headers for REGISTER message ", e);
            }
            if (remoteAddrHeader != null)
                request.addHeader(remoteAddrHeader);
            if (remotePortHeader != null)
                request.addHeader(remotePortHeader);
        } 
        try {	
            updateStats(request);
            forwardRequest(sipProvider,request, isIpv6);          						
        } catch (Throwable throwable) {
            logger.error("Unexpected exception while forwarding the request " + request, throwable);
            if(!Request.ACK.equalsIgnoreCase(requestMethod)) {
                try {
                    Response response = balancerRunner.balancerContext.messageFactory.createResponse(Response.SERVER_INTERNAL_ERROR, request);			
                    sipProvider.sendResponse(response);	
                } catch (Exception e) {
                    logger.error("Unexpected exception while trying to send the error response for this " + request, e);
                }
            }
        }
    }
1018946
@Override
	public boolean process(ContentEvent event) {

    	InstanceContentEvent inEvent = (InstanceContentEvent) event;
		Instance instance = inEvent.getInstance();

		if (inEvent.getInstanceIndex() < 0) {
			//end learning
			ResultContentEvent outContentEvent = new ResultContentEvent(-1, instance, 0,
					new double[0], inEvent.isLastEvent());
			outContentEvent.setClassifierIndex(this.modelId);
			outContentEvent.setEvaluationIndex(inEvent.getEvaluationIndex());
			outputStream.put(outContentEvent);
			return false;
		}
		
		if (inEvent.isTesting()){
			double[] dist = model.getVotesForInstance(instance);
			ResultContentEvent outContentEvent = new ResultContentEvent(inEvent.getInstanceIndex(),
					instance, inEvent.getClassId(), dist, inEvent.isLastEvent());
			outContentEvent.setClassifierIndex(this.modelId);
			outContentEvent.setEvaluationIndex(inEvent.getEvaluationIndex());
			logger.trace(inEvent.getInstanceIndex() + " {} {}", modelId, dist);
			outputStream.put(outContentEvent);
		}
		
		if (inEvent.isTraining()) {
			updateStats(inEvent);
		} 
		return false;
	}
366345
@Override
    protected void processMouseMotionEvent (MouseEvent event)
    {
        event.translatePoint(_vbounds.x, _vbounds.y);
        super.processMouseMotionEvent(event);
    }
150688
@MainThread
    private void handleEventResult(Event event, EventResult result) {
        if (!activeEvents.contains(event)) {
            Utils.logE(event.getKey(), "Cannot send result of finished event");
            return;
        }

        scheduleResultCallbacks(event, result);
        executeTasks(false);
    }
964812
@Override
    public void configurationEvent(ConfigurationEvent event) {
        if (event.getType() == ConfigurationEvent.CM_UPDATED && event.getPid().equals(pid)) {
            processProperties();
            initializeInterceptor();
        }

    }