/*
(non-Javadoc)

@see org.restcomm.protocols.ss7.map.api.service.supplementary. MAPServiceSupplementaryListener
#onProcessUnstructuredSSResponseIndication( org.restcomm.protocols.ss7.map
.api.service.supplementary.ProcessUnstructuredSSResponseIndication)
323949
@Override
    public void onProcessUnstructuredSSResponse(ProcessUnstructuredSSResponse procUnstrResInd) {
        // Server shouldn't be getting ProcessUnstructuredSSResponseIndication
        logger.error(String.format("onProcessUnstructuredSSResponseIndication for Dialog=%d and invokeId=%d", procUnstrResInd
                .getMAPDialog().getLocalDialogId(), procUnstrResInd.getInvokeId()));
    }
421210
@Override
    public void onUnstructuredSSResponse(UnstructuredSSResponse unstrResInd) {
        if (logger.isDebugEnabled()) {
            logger.debug(String.format("onUnstructuredSSResponseIndication for DialogId=%d", unstrResInd.getMAPDialog()
                    .getLocalDialogId()));
        }
        try {
            USSDString ussdStrObj = this.mapProvider.getMAPParameterFactory().createUSSDString("Your balance is 500");
            CBSDataCodingScheme ussdDataCodingScheme = new CBSDataCodingSchemeImpl(0x0F);
            MAPDialogSupplementary dialog = unstrResInd.getMAPDialog();

            AddressString msisdn = this.mapProvider.getMAPParameterFactory().createAddressString(
                    AddressNature.international_number, NumberingPlan.ISDN, "31628838002");

            dialog.addProcessUnstructuredSSResponse(((Long) dialog.getUserObject()).longValue(), ussdDataCodingScheme,
                    ussdStrObj);
            dialog.close(false);
        } catch (MAPException e) {
            logger.error("Error while sending UnstructuredSSRequest ", e);
        }
    }
318721
public void send(TCResponseRequest event) throws TCAPSendException {

        if (this.previewMode)
            return;

        if (!this.isStructured()) {
            throw new TCAPSendException("Unstructured dialogs do not use Response");
        }

        try {
            dialogLock.lock();
            TCResponseMessageImpl tcbm = null;

            if (state == TRPseudoState.InitialReceived) {
                // TC-END request primitive issued in response to a TC-BEGIN
                // indication primitive
                this.idleTimerActionTaken = true;
                stopIdleTimer();
                tcbm = (TCResponseMessageImpl) TcapFactory.createTCResponseMessage();
                tcbm.setDestinationTransactionId(this.remoteTransactionId);
                // local address may change, lets check it;
                if (event.getOriginatingAddress() != null && !event.getOriginatingAddress().equals(this.localAddress)) {
                    this.localAddress = event.getOriginatingAddress();
                }

                if (event.getApplicationContextName() != null || event.getConfidentiality() != null
                        || event.getSecurityContext() != null || event.getUserInformation() != null) {
                    // set dialog portion
                    DialogPortion dp = TcapFactory.createDialogPortion();
                    dp.setProtocolVersion(TcapFactory.createProtocolVersionFull());
                    dp.setApplicationContext(event.getApplicationContextName());
                    dp.setUserInformation(event.getUserInformation());
                    dp.setSecurityContext(event.getSecurityContext());
                    dp.setConfidentiality(event.getConfidentiality());

                    tcbm.setDialogPortion(dp);
                }
                if (this.scheduledComponentList.size() > 0) {
                    Component[] componentsToSend = new Component[this.scheduledComponentList.size()];
                    this.prepareComponents(componentsToSend);
                    tcbm.setComponent(componentsToSend);
                }

            } else if (state == TRPseudoState.Active) {
                restartIdleTimer();
                tcbm = (TCResponseMessageImpl) TcapFactory.createTCResponseMessage();

                tcbm.setDestinationTransactionId(this.remoteTransactionId);
                if (this.scheduledComponentList.size() > 0) {
                    Component[] componentsToSend = new Component[this.scheduledComponentList.size()];
                    this.prepareComponents(componentsToSend);
                    tcbm.setComponent(componentsToSend);
                }

            } else {
                throw new TCAPSendException(String.format("State is not %s or %s: it is %s", TRPseudoState.Active,
                        TRPseudoState.InitialReceived, this.state));
            }

            AsnOutputStream aos = new AsnOutputStream();
            try {
                tcbm.encode(aos);
                if (this.provider.getStack().getStatisticsEnabled()) {
                    this.provider.getStack().getCounterProviderImpl().updateTcResponseSentCount(this);
                }
                this.provider.send(aos.toByteArray(), event.getReturnMessageOnError(), this.remoteAddress, this.localAddress,
                        this.seqControl, this.getNetworkId(), this.localSsn);

                this.scheduledComponentList.clear();
            } catch (Exception e) {
                // FIXME: remove freshly added invokes to free invoke ID??
                if (logger.isEnabledFor(Level.ERROR)) {
                    logger.error("Failed to send message: ", e);
                }
                throw new TCAPSendException("Failed to send TC-Response message: " + e.getMessage(), e);
            } finally {
                // FIXME: is this proper place - should we not release in case
                // of error ?
                release();
            }
        } finally {
            dialogLock.unlock();
        }
    }
1048268
@Override
    public void onDeploy(DeploymentEvent event) {
        AbstractRuntimeManager runtimeManager = (AbstractRuntimeManager) event.getDeployedUnit().getRuntimeManager();        
        KieBase kieBase = runtimeManager.getEnvironment().getKieBase();
        Collection<Process> processes = kieBase.getProcesses(); 
        
        Map<String, DeployedAsset> mapProcessById = event.getDeployedUnit().getDeployedAssets()
                                                                            .stream()
                                                                            .collect(toMap(DeployedAsset::getId, asset -> asset));        
        for( Process process : processes ) {
            if( ((WorkflowProcess)process).isDynamic()) {
                String caseIdPrefix = collectCaseIdPrefix(process);
                Collection<CaseMilestone> caseMilestones = collectMilestoness(process);
                Collection<CaseStage> caseStages = collectCaseStages(event.getDeploymentId(), process.getId(), ((WorkflowProcess)process));                
                Collection<CaseRole> caseRoles = collectCaseRoles(process);
                Collection<AdHocFragment> adHocFragments = collectAdHocFragments((WorkflowProcess)process);
                Map<String, List<String>> dataAccessRestrictions = collectDataAccessRestrictions(process);
                
                CaseDefinitionImpl caseDef = new CaseDefinitionImpl((ProcessAssetDesc) mapProcessById.get(process.getId()), caseIdPrefix, caseStages, caseMilestones, caseRoles, adHocFragments, dataAccessRestrictions);
                
                availableCases.add(caseDef);
                caseIdGenerator.register(caseIdPrefix);
            }
        }
        
        // collect role information
        Collection<DeployedAsset> assets = event.getDeployedUnit().getDeployedAssets();
        List<String> roles = null;
        for( DeployedAsset asset : assets ) {
            if( asset instanceof ProcessAssetDesc ) {  
                // if it's not dynamic it's considered as not case definition
                if (!((ProcessAssetDesc) asset).isDynamic()) {
                    availableProcesses.add((ProcessAssetDesc) asset);
                }
                if (roles == null) {
                    roles = ((ProcessAssetDesc) asset).getRoles();
                }
            }
        }
        if (roles == null) {
            roles = Collections.emptyList();
        }
        deploymentRolesManager.addRolesForDeployment(event.getDeploymentId(), roles);

    }
393365
@Override
    void processModelNode(OperationContext context, String containerName, ModelNode cache, ConfigurationBuilder builder, List<Dependency<?>> dependencies)
            throws OperationFailedException {

        // process the basic clustered configuration
        super.processModelNode(context, containerName, cache, builder, dependencies);

        final int owners = DistributedCacheConfigurationResource.OWNERS.resolveModelAttribute(context, cache).asInt();
        final int segments = DistributedCacheConfigurationResource.SEGMENTS.resolveModelAttribute(context, cache).asInt();
        final float capacityFactor = (float) DistributedCacheConfigurationResource.CAPACITY_FACTOR.resolveModelAttribute(context,
              cache).asDouble();
        final long lifespan = DistributedCacheConfigurationResource.L1_LIFESPAN.resolveModelAttribute(context, cache).asLong();

        // process the additional distributed attributes and elements
        builder.clustering().hash()
            .numOwners(owners)
            .numSegments(segments)
            .capacityFactor(capacityFactor)
        ;

        if (lifespan > 0) {
            // is disabled by default in L1ConfigurationBuilder
            builder.clustering().l1().enable().lifespan(lifespan);
        } else {
            builder.clustering().l1().disable();
        }
    }
1026972
public void onResponse(final MobicentsSipServletResponse response, final int status) throws DispatcherException
	{
		// If we are canceled but still receiving provisional responses try to cancel them
		if(canceled && status < 200) {
			if(logger.isDebugEnabled()) {
				logger.debug("ProxyBranch " + this + " with outgoing request " + outgoingRequest + " cancelled and still receiving provisional response, trying to cancel them");
			}
			try {
				final SipServletRequest cancelRequest = outgoingRequest.createCancel();
				cancelRequest.send();
			} catch (Exception e) {
				if(logger.isDebugEnabled()) {
					logger.debug("Failed to cancel again a provisional response " + response.toString()
							, e);
				}
			}
		}

		// We have already sent TRYING, don't send another one
		if(status == 100) {
			if(logger.isDebugEnabled() && proxyBranch1xxTimerStarted) {
				logger.debug("1xx received, cancelling 1xx timer ");
			}
			cancel1xxTimer();
			return;
		}
		
		// Send informational responses back immediately
		if((status > 100 && status < 200) || (status == 200 &&
				(Request.PRACK.equals(response.getMethod()) || Request.UPDATE.equals(response.getMethod()))))
		{
			// Deterimine if the response is reliable. We just look at RSeq, because
			// every such response is required to have it.
			if(response.getHeader("RSeq") != null) {
				this.setWaitingForPrack(true); // this branch is expecting a PRACK now
			}
			
			final SipServletResponseImpl proxiedResponse = 
				ProxyUtils.createProxiedResponse(response, this);
			
			if(proxiedResponse == null) {
				if(logger.isDebugEnabled())
					logger.debug("Response dropped because it was addressed to this machine.");
				return; // this response was addressed to this proxy
			}
			
			try {
				String branch = ((Via)proxiedResponse.getMessage().getHeader(Via.NAME)).getBranch();
				synchronized(this.ongoingTransactions) {
					for(TransactionRequest tr : this.ongoingTransactions) {
						if(tr.branchId.equals(branch)) {
							((SipServletResponseImpl)proxiedResponse).setTransaction(tr.request.getTransaction());
							((SipServletResponseImpl)proxiedResponse).setOriginalRequest(tr.request);
							break;
						}
					}
				}

				proxiedResponse.send();
				if(logger.isDebugEnabled())
					logger.debug("Proxy response sent out sucessfully");
			} catch (Exception e) {
				logger.error("A problem occured while proxying a response", e);
			}
			if(logger.isDebugEnabled())
				logger.debug("SipSession state " + response.getSipSession().getState());
			if(status == 200 &&
				(Request.PRACK.equals(response.getMethod()) || Request.UPDATE.equals(response.getMethod()))
				// Added for http://code.google.com/p/sipservlets/issues/detail?id=41
				&& State.EARLY.equals(response.getSipSession().getState())) {
				
				updateTimer(true, response.getSipApplicationSession(false));
			}
			
			if(logger.isDebugEnabled())
					logger.debug("About to return from onResponse");
			
			return;
		}
		
		// Non-provisional responses must also cancel the timer, otherwise it will timeout
		// and return multiple responses for a single transaction.
		cancelTimer();
		
		if(status >= 600) // Cancel all 10.2.4
			this.proxy.cancelAllExcept(this, null, null, null, false);
		
		// FYI: ACK is sent automatically by jsip when needed
		
		boolean recursed = false;
		if(status >= 300 && status < 400 && recurse) {
			String contact = response.getHeader("Contact");
			if(contact != null) {
				//javax.sip.address.SipURI uri = SipFactoryImpl.addressFactory.createAddress(contact);
				try {
					if(logger.isDebugEnabled())
						logger.debug("Processing recursed response");
					int start = contact.indexOf('<');
					int end = contact.indexOf('>');
					contact = contact.substring(start + 1, end);
					URI uri = proxy.getSipFactoryImpl().createURI(contact);
					ArrayList<SipURI> list = new ArrayList<SipURI>();
					list.add((SipURI)uri);
					List<ProxyBranch> pblist = proxy.createProxyBranches(list);
					ProxyBranchImpl pbi = (ProxyBranchImpl)pblist.get(0);
					this.addRecursedBranch(pbi);
					pbi.start();
					recursed = true;
				} catch (ServletParseException e) {
					throw new IllegalArgumentException("Can not parse contact header", e);
				}
			}
		}		
		if(status >= 200 && !recursed)
		{
			
			if(proxy.getFinalBranchForSubsequentRequests() == null ||
					(outgoingRequest != null && outgoingRequest.isInitial())) {
				if(logger.isDebugEnabled())
					logger.debug("Handling final response for initial request");
				this.proxy.onFinalResponse(this);
			} else {
				if(logger.isDebugEnabled())
					logger.debug("Handling final response for non-initial request");				
				this.proxy.sendFinalResponse(response, this);
			}
		}
		
	}
601450
public void onSuccessRespEvent(ResponseEvent event, ActivityContextInterface aci) {
		
		if (tracer.isFineEnabled())
			tracer.fine("Received 2xx (SUCCESS) response:\n"+event.getResponse());
		
		final SbbLocalObject sbbLocalObject = sbbContext.getSbbLocalObject();
		aci.detach(sbbLocalObject);
		
		final Response response = event.getResponse();
		final SIPETagHeader sipeTagHeader = (SIPETagHeader) response.getHeader(SIPETagHeader.NAME);
		if(sipeTagHeader != null) {
			this.setETagCMP(sipeTagHeader.getETag());
		}
				
		final PublishRequestType type = getPublishRequestTypeCMP();
		
		if (type != PublishRequestType.REMOVE) {
			final ExpiresHeader expiresHeader = (ExpiresHeader) response.getHeader(ExpiresHeader.NAME);
			if(expiresHeader!=null && expiresHeader.getExpires() != 0) {
				//update expires time.
				setExpiresCMP(expiresHeader.getExpires());
				startExpiresTimer();
			}
		}
		
		PostponedRequest postponedRequest = null;
		setPublishRequestTypeCMP(null);

		try{
			switch (type) {
			case NEW:
				postponedRequest = getPostponedRequestCMP();
				getParent().newPublicationSucceed((PublicationClientChildSbbLocalObject) sbbLocalObject);
				break;
			case REFRESH:
				postponedRequest = getPostponedRequestCMP();
				break;
			case UPDATE:
				postponedRequest = getPostponedRequestCMP();
				getParent().modifyPublicationSucceed((PublicationClientChildSbbLocalObject) sbbLocalObject);
				break;
			case REMOVE:
				getParent().removePublicationSucceed((PublicationClientChildSbbLocalObject) sbbLocalObject);
				break;
			}
		}
		catch(Exception e) {
			if(tracer.isSevereEnabled()) {
				tracer.severe("Exception in publication parent!", e);
			}
		}

		if (postponedRequest != null) {
			// refresh may be concurrent with another request, if there is a
			// postponed request resume it now
			postponedRequest.resume(this);
		}
		
	}
1128680
public void eventProcessingSuccessful(ActivityHandle ah,
			FireableEventType arg1, Object arg2, Address ad,
			ReceivableService arg4, int arg5) {
				
	}
81726
public void processResponse(ResponseEvent response) {
    ClientTransaction trans = response.getClientTransaction();
    if (trans == null) {
      return;
    }

    SipTransaction sip_trans = null;

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

    if (sip_trans == null) {
      return;
    }

    if (response.getResponse().getStatusCode() > 199) {
      synchronized (respTransactions) {
        respTransactions.remove(trans);
      }
    }

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

    // if no listener, use the default blocking mechanism
    synchronized (sip_trans.getBlock()) {
      sip_trans.getEvents().addLast(response);
      sip_trans.getBlock().notifyEvent();
    }
  }
872326
private JsonNode processCallbackResponse(final JsonNode resp) {
        if (this.callbackHandler == null) {
            throw new JsiiException("Cannot process callback since callbackHandler was not set");
        }

        Callback callback = JsiiObjectMapper.treeToValue(resp.get("callback"), Callback.class);

        JsonNode result = null;
        String error = null;
        try {
            result = this.callbackHandler.handleCallback(callback);
        } catch (Exception e) {
            if (e.getCause() instanceof InvocationTargetException) {
                error = e.getCause().getCause().getMessage();
            } else {
                error = e.getMessage();
            }
        }

        ObjectNode completeResponse = JsonNodeFactory.instance.objectNode();
        completeResponse.put("cbid", callback.getCbid());
        if (error != null) {
            completeResponse.put("err", error);
        }
        if (result != null) {
            completeResponse.set("result", result);
        }

        ObjectNode req = JsonNodeFactory.instance.objectNode();
        req.set("complete", completeResponse);

        return requestResponse(req);
    }
881297
public void processResponse(ResponseEvent responseEvent) {
    	BalancerAppContent content=(BalancerAppContent)responseEvent.getSource();
    	boolean isIpv6 = content.isIpv6();
        SipProvider sipProvider = content.getProvider();
        
        Response originalResponse = responseEvent.getResponse();
        if(logger.isDebugEnabled()) {
            logger.debug("got response :\n" + originalResponse);
        }

        updateStats(originalResponse);

        final Response response = (Response) originalResponse; 
        Node senderNode = getSenderNode(response);
        if(senderNode != null) {
        	if(logger.isDebugEnabled()) {
    			logger.debug("Updating Timestamp of sendernode: " + senderNode);
    		}
            senderNode.updateTimerStamp();
        }

        // Topmost via headers is me. As it is response to external request
        ViaHeader viaHeader = (ViaHeader) response.getHeader(ViaHeader.NAME);

        String branch = viaHeader.getBranch();
        int versionDelimiter = branch.lastIndexOf('_');
        String version = branch.substring(versionDelimiter + 1);

        InvocationContext ctx = balancerRunner.getInvocationContext(version);

        if(viaHeader!=null && !isHeaderExternal(viaHeader.getHost(), viaHeader.getPort(), viaHeader.getTransport(),isIpv6)) {
            response.removeFirst(ViaHeader.NAME);
        }
        
        viaHeader = (ViaHeader) response.getHeader(ViaHeader.NAME);
        String transport=viaHeader.getTransport();
        
        if(viaHeader!=null && !isHeaderExternal(viaHeader.getHost(), viaHeader.getPort(), viaHeader.getTransport(),isIpv6)) {
            response.removeFirst(ViaHeader.NAME);
        }
        
       
        
        boolean fromServer = false;
        if(balancerRunner.balancerContext.isTwoEntrypoints()) {
        	if(!isIpv6)
        		fromServer = sipProvider.equals(balancerRunner.balancerContext.internalSipProvider);
        	else
        		fromServer = sipProvider.equals(balancerRunner.balancerContext.internalIpv6SipProvider);
            if(logger.isDebugEnabled()) {
            	if(!isIpv6)
            		logger.debug("fromServer : "+ fromServer + ", sipProvider " + sipProvider + ", internalSipProvider " + balancerRunner.balancerContext.internalSipProvider);
            	else
            		logger.debug("fromServer : "+ fromServer + ", sipProvider " + sipProvider + ", internalIpv6SipProvider " + balancerRunner.balancerContext.internalIpv6SipProvider);
            		
    		}
        } else {
            fromServer = senderNode == null;
            if(logger.isDebugEnabled()) {
    			logger.debug("fromServer : "+ fromServer + ", senderNode " + senderNode);
    		}
        }
        //removes rport and received from last Via header because of NEXMO patches it
        //only for external responses
        if(balancerRunner.balancerContext.isUseWithNexmo&&!fromServer)
        {
        	viaHeader = (ViaHeader) response.getHeader(ViaHeader.NAME);
        	if(viaHeader!=null) 
        	{
        		if(logger.isDebugEnabled())
        			logger.debug("We are going to remove rport and received parametres from :" + viaHeader + " from external response");
        		response.removeFirst(ViaHeader.NAME);
        		viaHeader.removeParameter("rport");
        		viaHeader.removeParameter("received");
			
        		try {
        			response.addFirst(viaHeader);
        		} catch (NullPointerException | SipException e) {
        			e.printStackTrace();
        		}
        		if(logger.isDebugEnabled())
        			logger.debug("After removing :" + response);
        	}
        }

        if(fromServer) {
        	if(senderNode!=null&&senderNode.getIp()!=null)
        	{
        		
        		if(balancerRunner.balancerContext.maxRequestNumberWithoutResponse!=null
      			&& balancerRunner.balancerContext.maxResponseTime!=null)
        		{
        	    	KeySip keySip = new KeySip(senderNode,isIpv6);
        	    	// adding null check for https://github.com/RestComm/load-balancer/issues/83
        	    	Node currNode = ctx.sipNodeMap(isIpv6).get(keySip);
        	    	if(currNode!=null)
        	    	{
        	    		if(logger.isDebugEnabled())
        	    			logger.debug("We are going to reset counters of health check" + currNode.getRequestNumberWithoutResponse()+ " : "+currNode.getLastTimeResponse());
        	    		currNode.setLastTimeResponse(System.currentTimeMillis());
        	    		currNode.setRequestNumberWithoutResponse(0);
        	    		if(logger.isDebugEnabled())
        	    			logger.debug("Counter of request without responses is : " + currNode.getRequestNumberWithoutResponse()+ " : "+currNode.getLastTimeResponse());
        	    	}
        	    	else
        	    	{
        	    		logger.warn("Node is null, we will not reset counters");
        	    	}
        		}
        		mediaFailureDetection(response, ctx, senderNode);
        	}
            /*
			if("true".equals(balancerRunner.balancerContext.properties.getProperty("removeNodesOn500Response")) && response.getStatusCode() == 500) {
				// If the server is broken remove it from the list and try another one with the next retransmission
				if(!(sourceNode instanceof ExtraServerNode)) {
					if(balancerRunner.balancerContext.nodes.size()>1) {
						balancerRunner.balancerContext.nodes.remove(sourceNode);
						balancerRunner.balancerContext.balancerAlgorithm.nodeRemoved(sourceNode);
					}
				}
			} 
        	*/
        	String publicIp = null;
        	if(!isIpv6)
        		publicIp = balancerRunner.balancerContext.publicIP;
        	else
        		publicIp = balancerRunner.balancerContext.publicIPv6;
        	if(publicIp != null && publicIp.trim().length() > 0) {
        		if(logger.isDebugEnabled()) {
        			logger.debug("Will add Record-Route header to response with public IP Address: "+publicIp);
        		}
                patchSipMessageForNAT(response, isIpv6);
            }
            // https://github.com/RestComm/load-balancer/issues/45 Adding sender node for the algorithm to be available
        	((ResponseExt)response).setApplicationData(senderNode);
        	
            ctx.balancerAlgorithm.processInternalResponse(response,isIpv6);
            try {	
                if(logger.isDebugEnabled()) {
                    logger.debug("from server sending response externally " + response);
                }
                if(!isIpv6)
                	balancerRunner.balancerContext.externalSipProvider.sendResponse(response);
                else
                	balancerRunner.balancerContext.externalIpv6SipProvider.sendResponse(response);

            } catch (Exception ex) {
                logger.error("Unexpected exception while forwarding the response \n" + response, ex);
            }
        } else {
        	try {
                SIPMessage message = (SIPMessage)response;

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

                Header remoteAddrHeader = null;
                Header remotePortHeader = null;
                try {
                	HeaderFactory hf=SipFactory.getInstance().createHeaderFactory();
                    remoteAddrHeader = hf.createHeader("X-Sip-Balancer-InitialRemoteAddr", initialRemoteAddr);
                    remotePortHeader = hf.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)
                    response.addHeader(remoteAddrHeader);
                if (remotePortHeader != null)
                    response.addHeader(remotePortHeader);
                                
                if(balancerRunner.balancerContext.isTwoEntrypoints()) {
            	    ctx.balancerAlgorithm.processExternalResponse(response,isIpv6);
                   
                    if(logger.isDebugEnabled()) {
                        logger.debug("two entry points: from external sending response " + response);
                    }
                    if(!isIpv6)
                    	balancerRunner.balancerContext.internalSipProvider.sendResponse(response);
                    else
                    	balancerRunner.balancerContext.internalIpv6SipProvider.sendResponse(response);
                } else {
                	if(!comesFromInternalNode(response,ctx,initialRemoteAddr,message.getPeerPacketSourcePort(),transport,isIpv6))
                		ctx.balancerAlgorithm.processExternalResponse(response,isIpv6);
                	else
                		ctx.balancerAlgorithm.processInternalResponse(response,isIpv6);
                	
                    if(logger.isDebugEnabled()) {
                        logger.debug("one entry point: from external sending response " + response);
                    }
                    if(!isIpv6)
                    	balancerRunner.balancerContext.externalSipProvider.sendResponse(response);
                    else
                    	balancerRunner.balancerContext.externalIpv6SipProvider.sendResponse(response);
                }
            } catch (Exception ex) {
                logger.error("Unexpected exception while forwarding the response \n" + response, ex);
            }
        }
    }
262952
function ProcessManagement(options) {
  EventEmitter.call(this);

  options = options || {};

  if (!options.sagaPath && options.sagaPath !== '') {
    var err = new Error('Please provide sagaPath in options');
    debug(err);
    throw err;
  }

  var defaults = {
    commandRejectedEventName: 'commandRejected'
  };

  _.defaults(options, defaults);

  this.structureLoader = createStructureLoader(options.structureLoader);
  this.sagaStore = sagastore.create(options.sagaStore);

  options.retryOnConcurrencyTimeout = options.retryOnConcurrencyTimeout || 800;

  var defaultRevOpt = {
    queueTimeout: 1000,
    queueTimeoutMaxLoops: 3//,
    // startRevisionNumber: 1
  };

  if (options.revisionGuard !== false) {
    options.revisionGuard = options.revisionGuard || {};
    _.defaults(options.revisionGuard, defaultRevOpt);
    this.revisionGuardStore = revisionGuardStore.create(options.revisionGuard);
  }

  this.options = options;

  this.definitions = {
    command: {
      id: 'id'
////      name: 'name',                   // optional
////      aggregateId: 'aggregate.id',    // optional
////      context: 'context.name',        // optional
////      aggregate: 'aggregate.name',    // optional
////      payload: 'payload',             // optional
////      revision: 'revision',           // optional
////      version: 'version',             // optional
//      meta: 'meta'                    // optional (will be passed directly to corresponding event(s))
    },
    event: {
////      correlationId: 'correlationId', // optional
////      id: 'id',                       //optional
      name: 'name'
////      aggregateId: 'aggregate.id',    // optional
//      context: 'context.name',        // optional
//      aggregate: 'aggregate.name',    // optional
////      payload: 'payload',             // optional
////      revision: 'revision'            // optional
//      version: 'version',             // optional
//      meta: 'meta'                    // optional (will be passed directly from corresponding command)
    }
  };

  this.idGenerator(function () {
    return uuid().toString();
  });

  // DO not register a "dummy" onCommand handler because of getTimeoutedSagas handling
  // this.onCommand(function (cmd) {
  //   debug('emit:', cmd);
  // });

  this.onEventMissing(function (info, evt) {
    debug('missing events: ', info, evt);
  });
}
676076
@Override
	public Object postProcessAfterInitialization(final Object bean, final String beanName) throws BeansException {
		if (subscribers.containsKey(beanName)) {
			Subscribe annotation = subscribers.get(beanName);
			EventBus eventBus = getEventBus(annotation.eventBus(), beanName);
			LOG.debug("Subscribing the event listener '{}' to event bus '{}' with topic '{}", beanName,
					annotation.eventBus(), annotation.topic());
			eventBus.subscribe(annotation.topic(), (EventSubscriber) bean);
		}
		return bean;
	}
1175903
private JsonNode processErrorResponse(final JsonNode resp) {
        String errorMessage = resp.get("error").asText();
        if (resp.has("stack")) {
            errorMessage += "\n" + resp.get("stack").asText();
        }

        throw new JsiiException(errorMessage);
    }
352179
private void deleteResource(final CmsUUID structureId) {

        CmsRpcAction<Void> action = new CmsRpcAction<Void>() {

            /**
             * @see org.opencms.gwt.client.rpc.CmsRpcAction#execute()
             */
            @Override
            public void execute() {

                CmsCoreProvider.getVfsService().deleteResource(structureId, this);

            }

            /**
             * @see org.opencms.gwt.client.rpc.CmsRpcAction#onResponse(java.lang.Object)
             */
            @Override
            protected void onResponse(Void result) {

                onAfterDeletion();
            }
        };
        action.execute();
    }
385681
@Override
    public void onUnstructuredSSRequest(UnstructuredSSRequest unstrReqInd) {
        if (logger.isDebugEnabled()) {
            logger.debug(String.format("Rx UnstructuredSSRequestIndication. USSD String=%s ", unstrReqInd.getUSSDString()));
        }
        MAPDialogSupplementary mapDialog = unstrReqInd.getMAPDialog();

        try {
            CBSDataCodingScheme ussdDataCodingScheme = new CBSDataCodingSchemeImpl(0x0f);

            USSDString ussdString = this.mapProvider.getMAPParameterFactory().createUSSDString("1", null, null);

            AddressString msisdn = this.mapProvider.getMAPParameterFactory()
                    .createAddressString(AddressNature.international_number, NumberingPlan.ISDN, "31628838002");

            mapDialog.addUnstructuredSSResponse(unstrReqInd.getInvokeId(), ussdDataCodingScheme, ussdString);
            mapDialog.send();

        } catch (MAPException e) {
            logger.error(
                    String.format("Error while sending UnstructuredSSResponse for Dialog=%d", mapDialog.getLocalDialogId()));
        }
    }
660608
@Deprecated
  public void startProcessInstanceByIdForm(String processDefinitionId, String callbackUrl) {
    this.url = callbackUrl;
    this.processDefinitionId = processDefinitionId;
    beginConversation();
  }