/*
(non-Javadoc)

@see org.restcomm.protocols.ss7.map.api.service.supplementary. MAPServiceSupplementaryListener
#onProcessUnstructuredSSRequestIndication(org .mobicents.protocols.ss7.map.
api.service.supplementary.ProcessUnstructuredSSRequestIndication)
542734
@Override
    public void onProcessUnstructuredSSRequest(ProcessUnstructuredSSRequest procUnstrReqInd) {
//        NetworkIdState networkIdState = this.mapStack.getMAPProvider().getNetworkIdState(0);
//        if (!(networkIdState == null || networkIdState.isAvailavle() && networkIdState.getCongLevel() == 0)) {
//            // congestion or unavailable
//            logger.warn("onProcessUnstructuredSSRequest Congestion - onUnstructuredSSRequest: networkIdState=" + networkIdState);
//            try {
//                Thread.sleep(1000);
//            } catch (InterruptedException e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            }
//        }

        if (logger.isDebugEnabled()) {
            logger.debug(String.format("onProcessUnstructuredSSRequestIndication for DialogId=%d", procUnstrReqInd
                    .getMAPDialog().getLocalDialogId()));
        }
        try {
            long invokeId = procUnstrReqInd.getInvokeId();

            USSDString ussdStrObj = this.mapProvider.getMAPParameterFactory().createUSSDString(
                    "USSD String : Hello World <CR> 1. Balance <CR> 2. Texts Remaining");
            CBSDataCodingScheme ussdDataCodingScheme = new CBSDataCodingSchemeImpl(0x0F);
            MAPDialogSupplementary dialog = procUnstrReqInd.getMAPDialog();

            dialog.setUserObject(invokeId);

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

            dialog.addUnstructuredSSRequest(ussdDataCodingScheme, ussdStrObj, null, msisdn);
            dialog.send();
        } catch (MAPException e) {
            logger.error("Error while sending UnstructuredSSRequest ", e);
        }
    }
239132
public void doProcess(HttpServletRequest req, HttpServletResponse res) 
        throws ServletException, IOException
    {
        Utility.getLogger().info("doProcess called in xmlws servlet");
        XMLMessageTransport xmlMessageTransport = null;
        ServletTask servletTask = null;
        BaseMessage msgReplyInternal = null;
        try {
            Map<String,Object> properties = m_initProperties;
        	String strDomain = BaseHttpTask.getParam(req, DBParams.DOMAIN);
        	if (strDomain != null)
        	{
		        properties = new HashMap<String,Object>();
		        if (m_initProperties != null)
		        	properties.putAll(m_initProperties);
				properties.put(DBParams.DOMAIN, strDomain);
        	}
            servletTask = new ServletTask(this, BasicServlet.SERVLET_TYPE.XML);
            servletTask.setProperties(properties);
            Environment env = null;
            if (servletTask.getApplication() != null)
                env = ((BaseApplication)servletTask.getApplication()).getEnvironment();
            if (env == null)
                env = Environment.getEnvironment(null);
            App app = env.getMessageApplication(true, properties);
            servletTask.setApplication(app);

            xmlMessageTransport = new XMLMessageTransport(servletTask);
            InputStream inStream = req.getInputStream();	// .getReader();
            Reader in = new InputStreamReader(inStream);
            String message = Utility.transferURLStream(null, null, in, null);
            try   {
                message = URLDecoder.decode(message, DBConstants.URL_ENCODING);
            } catch (java.io.UnsupportedEncodingException ex) {
                ex.printStackTrace();
            }
            //xMap<String,Object> properties = PropertiesField.stringToProperties(message);
            if (message.startsWith("xml="))	// Always
                message = message.substring(4);
            Map<String, Object> propMessage = null;
            if (message.length() == 0)
            {
            	Enumeration<?> names = req.getParameterNames();
            	while (names.hasMoreElements())
            	{
            		String key = names.nextElement().toString();
            		if ("xml".equalsIgnoreCase(key))
            			message = (String)req.getParameter(key);
            		else
            		{
            			if (propMessage == null)
            				propMessage = new HashMap<String, Object>();
            			propMessage.put(key, req.getParameter(key));	// RESTful params
            		}
            	}
            }

            BaseMessage messageIn = new TreeMessage(null, null);
            new XmlTrxMessageIn(messageIn, message);
            if (propMessage != null)
            {
            	for (String key : propMessage.keySet())
            	{
            		messageIn.put(key, propMessage.get(key));
            	}
            }

            msgReplyInternal = xmlMessageTransport.processIncomingMessage(messageIn, null);
            Utility.getLogger().info("msgReplyInternal: " + msgReplyInternal);

            int iErrorCode = xmlMessageTransport.convertToExternal(msgReplyInternal, null);
            Utility.getLogger().info("externalMessageReply: " + msgReplyInternal);

            if (iErrorCode == DBConstants.NORMAL_RETURN)
            {
            	if (msgReplyInternal.getExternalMessage() != null)
            	{	// Always
	                String strReply = msgReplyInternal.getExternalMessage().toString();
    	            res.getWriter().print(strReply);
        	        String strTrxID = (String)msgReplyInternal.getMessageHeader().get(TrxMessageHeader.LOG_TRX_ID);
            	    xmlMessageTransport.logMessage(strTrxID, msgReplyInternal, MessageInfoTypeModel.REPLY, MessageTypeModel.MESSAGE_OUT, MessageStatusModel.SENTOK, null, null);    // Sent (no reply required)
            	}
            }
        } catch (Throwable ex)  {
            ex.printStackTrace();
            String strError = "Error in processing or replying to a message";
            Utility.getLogger().warning(strError);
            if ((msgReplyInternal != null) && (xmlMessageTransport != null))
            {
                String strTrxID = (String)msgReplyInternal.getMessageHeader().get(TrxMessageHeader.LOG_TRX_ID);
                xmlMessageTransport.logMessage(strTrxID, msgReplyInternal, MessageInfoTypeModel.REPLY, MessageTypeModel.MESSAGE_OUT, MessageStatusModel.ERROR, strError, null);
            }
            return; // Error
        } finally   {
            if (xmlMessageTransport != null)
            {
                xmlMessageTransport.free();
                xmlMessageTransport = null;
            }
            if (servletTask != null)
                servletTask.free();
        }
    }
252269
@Override
    void processModelNode(OperationContext context, String containerName, ModelNode cache, ConfigurationBuilder builder, List<Dependency<?>> dependencies)
            throws OperationFailedException {

        // process cache attributes and elements
        super.processModelNode(context, containerName, cache, builder, dependencies);

        // adjust the cache mode used based on the value of clustered attribute MODE
        ModelNode modeModel = ClusteredCacheConfigurationResource.MODE.resolveModelAttribute(context, cache);
        CacheMode cacheMode = modeModel.isDefined() ? Mode.valueOf(modeModel.asString()).apply(this.mode) : this.mode;
        builder.clustering().cacheMode(cacheMode);

        final long remoteTimeout = ClusteredCacheConfigurationResource.REMOTE_TIMEOUT.resolveModelAttribute(context, cache).asLong();
        // process clustered cache attributes and elements
        if (cacheMode.isSynchronous()) {
            builder.clustering().remoteTimeout(remoteTimeout);
        }
    }
66691
@Override
    protected Long logRequest(Request request) {
        requestId = super.logRequest(request);
        try {
            Variable requestIdVar = getProcessDefinition().getVariable("requestId");
            if (requestIdVar != null && Long.class.getName().equals(requestIdVar.getType()))
                setParameterValue("requestId", requestId);
        }
        catch (ActivityException ex) {
            logexception(ex.getMessage(), ex);
        }
        try { // Add microservice, or Update microservice if it has id=0 (when executing in parallel from OrchestratorActivity)
            updateServiceSummary(null, null);
        }
        catch (ActivityException | SQLException ex) {
            logexception(ex.getMessage(), ex);
        }
        return requestId;
    }
1241518
protected void processServiceClass(ClassDoc service,
			Configuration configuration) {
		Tag[] serviceTagArray = service.tags(WRTagTaglet.NAME);
		for (int i = 0; i < serviceTagArray.length; i++) {
			Set<String> serviceTags = WRTagTaglet.getTagSet(serviceTagArray[i]
					.text());
			for (Iterator<String> iter = serviceTags.iterator(); iter.hasNext();) {
				String tag = iter.next();
				if (!this.taggedOpenAPIMethods.containsKey(tag)) {
					this.taggedOpenAPIMethods
							.put(tag, new HashSet<MethodDoc>());
				}
				// all method of this service should be processed later.
				for (int j = 0; j < service.methods().length; j++) {
					if (configuration.nodeprecated
							&& Util.isDeprecated(service.methods()[j])) {
						continue;
					}
					this.taggedOpenAPIMethods.get(tag)
							.add(service.methods()[j]);
				}
			}

			this.wrDoc.getWRTags().addAll(serviceTags);
		}
	}
657435
protected void processRequest(String requestedPath, HttpServletRequest request, HttpServletResponse response,
			BundleHashcodeType bundleHashcodeType) throws IOException {

		boolean writeResponseHeader = false;
		boolean validBundle = true;
		if (!jawrConfig.isDebugModeOn() && jawrConfig.isStrictMode()
				&& bundleHashcodeType.equals(BundleHashcodeType.INVALID_HASHCODE)) {
			validBundle = false;
		}

		if (this.jawrConfig.isDebugModeOn() && null != request.getParameter(GENERATION_PARAM))
			requestedPath = request.getParameter(GENERATION_PARAM);

		// If debug mode is off, check for If-Modified-Since and If-none-match
		// headers and set response caching headers.
		if (!this.jawrConfig.isDebugModeOn()) {
			// If a browser checks for changes, always respond 'no changes'.
			if (validBundle && (null != request.getHeader(IF_MODIFIED_SINCE_HEADER)
					|| null != request.getHeader(IF_NONE_MATCH_HEADER))) {
				response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
				if (LOGGER.isDebugEnabled())
					LOGGER.debug("Returning 'not modified' header. ");
				return;
			}

			if (validBundle) {
				// Add caching headers
				setResponseHeaders(response);
			} else {

				writeResponseHeader = illegalBundleRequestHandler.writeResponseHeader(requestedPath, request, response);
				if (!writeResponseHeader) {
					// Add caching headers
					setResponseHeaders(response);
				}
			}
		}

		try {
			if (validBundle || illegalBundleRequestHandler.canWriteContent(requestedPath, request)) {

				// By setting content type, the response writer will use
				// appropriate encoding
				response.setContentType(getContentType(requestedPath, request));
				writeContent(requestedPath, request, response);
				if (LOGGER.isDebugEnabled())
					LOGGER.debug("request succesfully attended");
			} else {
				if (!writeResponseHeader) {
					logBundleNotFound(requestedPath);
					response.sendError(HttpServletResponse.SC_NOT_FOUND);
				}
			}

		} catch (EOFException eofex) {
			LOGGER.info("Browser cut off response", eofex);
		} catch (IOException e) {
			if (ClientAbortExceptionResolver.isClientAbortException(e)) {
				LOGGER.debug("Browser cut off response", e);
			} else {
				throw e;
			}
		} catch (ResourceNotFoundException e) {
			logBundleNotFound(requestedPath);
			response.setStatus(HttpServletResponse.SC_NOT_FOUND);
		}
	}
439549
private void acknowledgeAlreadyProcessedOperation(SegmentOperation operation) throws DataCorruptionException {
        if (operation instanceof MergeSegmentOperation) {
            // Only MergeSegmentOperations need special handling. Others, such as StreamSegmentSealOperation, are not
            // needed since they're handled in the initialize() method. Ensure that the DataSource is aware of this
            // (since after recovery, it may not know that a merge has been properly completed).
            MergeSegmentOperation mergeOp = (MergeSegmentOperation) operation;
            try {
                updateMetadataForTransactionPostMerger(this.dataSource.getStreamSegmentMetadata(mergeOp.getSourceSegmentId()), mergeOp.getStreamSegmentId());
            } catch (Throwable ex) {
                // Something really weird must have happened if we ended up in here. To prevent any (further) damage, we need
                // to stop the Segment Container right away.
                throw new DataCorruptionException(String.format("Unable to acknowledge already processed operation '%s'.", operation), ex);
            }
        }
    }
866765
protected void processJawrServlets(String destDirPath,
			List<ServletDefinition> jawrServletDefinitions,
			boolean keepUrlMapping) throws Exception {

		String appRootDir = "";
		String jsServletMapping = "";
		String cssServletMapping = "";
		String binaryServletMapping = "";

		for (Iterator<ServletDefinition> iterator = jawrServletDefinitions
				.iterator(); iterator.hasNext();) {

			ServletDefinition servletDef = (ServletDefinition) iterator.next();
			ServletConfig servletConfig = servletDef.getServletConfig();

			// Force the production mode, and remove config listener parameters
			Map<?, ?> initParameters = ((MockServletConfig) servletConfig)
					.getInitParameters();
			initParameters.remove("jawr.config.reload.interval");

			String jawrServletMapping = servletConfig
					.getInitParameter(JawrConstant.SERVLET_MAPPING_PROPERTY_NAME);
			String servletMapping = servletConfig
					.getInitParameter(JawrConstant.SPRING_SERVLET_MAPPING_PROPERTY_NAME);
			if (servletMapping == null) {
				servletMapping = jawrServletMapping;
			}

			ResourceBundlesHandler bundleHandler = null;
			BinaryResourcesHandler binaryRsHandler = null;

			// Retrieve the bundle Handler
			ServletContext servletContext = servletConfig.getServletContext();
			String type = servletConfig.getInitParameter(TYPE_INIT_PARAMETER);
			if (type == null || type.equals(JawrConstant.JS_TYPE)) {
				bundleHandler = (ResourceBundlesHandler) servletContext
						.getAttribute(JawrConstant.JS_CONTEXT_ATTRIBUTE);
				String contextPathOverride = bundleHandler.getConfig()
						.getContextPathOverride();
				if (StringUtils.isNotEmpty(contextPathOverride)) {
					int idx = contextPathOverride.indexOf("//");
					if (idx != -1) {
						idx = contextPathOverride.indexOf("/", idx + 2);
						if (idx != -1) {
							appRootDir = PathNormalizer
									.asPath(contextPathOverride.substring(idx));
						}
					}
				}

				if (jawrServletMapping != null) {
					jsServletMapping = PathNormalizer
							.asPath(jawrServletMapping);
				}

			} else if (type.equals(JawrConstant.CSS_TYPE)) {
				bundleHandler = (ResourceBundlesHandler) servletContext
						.getAttribute(JawrConstant.CSS_CONTEXT_ATTRIBUTE);
				if (jawrServletMapping != null) {
					cssServletMapping = PathNormalizer
							.asPath(jawrServletMapping);
				}
			} else if (type.equals(JawrConstant.BINARY_TYPE)) {
				binaryRsHandler = (BinaryResourcesHandler) servletContext
						.getAttribute(JawrConstant.BINARY_CONTEXT_ATTRIBUTE);
				if (jawrServletMapping != null) {
					binaryServletMapping = PathNormalizer
							.asPath(jawrServletMapping);
				}
			}

			if (bundleHandler != null) {
				createBundles(servletDef.getServlet(), bundleHandler,
						destDirPath, servletMapping, keepUrlMapping);
			} else if (binaryRsHandler != null) {
				createBinaryBundle(servletDef.getServlet(), binaryRsHandler,
						destDirPath, servletConfig, keepUrlMapping);
			}
		}

		// Create the apache rewrite config file.
		createApacheRewriteConfigFile(destDirPath, appRootDir,
				jsServletMapping, cssServletMapping, binaryServletMapping);

	}
735104
@SuppressWarnings({ "PMD.DataflowAnomalyAnalysis", "PMD.EmptyCatchBlock" })
    @RequestHandler(priority = 990, dynamic = true)
    public void onRequest(Request.In event) {
        @SuppressWarnings("PMD.AccessorClassGeneration")
        final Selection selection = event.associated(Session.class)
            .map(session -> (Selection) session.computeIfAbsent(
                Selection.class, newKey -> new Selection(cookieName, path)))
            .orElseGet(() -> new Selection(cookieName, path));
        selection.setCurrentEvent(event);
        event.setAssociated(Selection.class, selection);
        if (selection.isExplicitlySet()) {
            return;
        }

        // Try to get locale from cookies
        final HttpRequest request = event.httpRequest();
        Optional<String> localeNames = request.findValue(
            HttpField.COOKIE, Converters.COOKIE_LIST)
            .flatMap(cookieList -> cookieList.valueForName(cookieName));
        if (localeNames.isPresent()) {
            try {
                List<Locale> cookieLocales = LOCALE_LIST
                    .fromFieldValue(localeNames.get());
                if (!cookieLocales.isEmpty()) {
                    Collections.reverse(cookieLocales);
                    cookieLocales.stream()
                        .forEach(locale -> selection.prefer(locale));
                    return;
                }
            } catch (ParseException e) {
                // Unusable
            }
        }

        // Last resport: Accept-Language header field
        Optional<List<ParameterizedValue<Locale>>> accepted = request.findValue(
            HttpField.ACCEPT_LANGUAGE, Converters.LANGUAGE_LIST);
        if (accepted.isPresent()) {
            Locale[] locales = accepted.get().stream()
                .sorted(ParameterizedValue.WEIGHT_COMPARATOR)
                .map(value -> value.value()).toArray(Locale[]::new);
            selection.updateFallbacks(locales);
        }
    }
669875
@Override
    protected boolean isIndexing(CmsResource res) {

        if ((res != null) && (getSources() != null)) {
            I_CmsDocumentFactory documentFactory = OpenCms.getSearchManager().getDocumentFactory(res);
            for (CmsSearchIndexSource source : getSources()) {
                if (source.isIndexing(res.getRootPath(), CmsSolrDocumentContainerPage.TYPE_CONTAINERPAGE_SOLR)
                    || source.isIndexing(res.getRootPath(), CmsSolrDocumentXmlContent.TYPE_XMLCONTENT_SOLR)
                    || ((documentFactory != null) && source.isIndexing(res.getRootPath(), documentFactory.getName()))) {
                    return true;
                }
            }
        }
        return false;
    }
744554
@Override
    public void processPartial(PhaseId phaseId)
    {
        assertNotReleased();

        UIViewRoot viewRoot = _facesContext.getViewRoot();

        if (phaseId == PhaseId.APPLY_REQUEST_VALUES
                || phaseId == PhaseId.PROCESS_VALIDATIONS
                || phaseId == PhaseId.UPDATE_MODEL_VALUES)
        {
            processPartialExecute(viewRoot, phaseId);
        }
        else if (phaseId == PhaseId.RENDER_RESPONSE)
        {
            processPartialRendering(viewRoot, phaseId);
        }
    }
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()));
    }
159304
public void processRequest(RequestEvent req) {
		
		if (tracer.isInfoEnabled()) {
			tracer.info("Received Request:\n"+req.getRequest());
		}

		// Restcomm Statistics
		final String method = req.getRequest().getMethod();
		if (Request.INVITE.equalsIgnoreCase(method)) {
			this.defaultUsageParameters.incrementCalls(1);
		}
		if (Request.MESSAGE.equalsIgnoreCase(method)) {
			this.defaultUsageParameters.incrementMessages(1);
		}

		// get dialog wrapper
		final Dialog d = req.getDialog();
		final DialogWrapper dw = getDialogWrapper(d);
		if (dw != null && req.getServerTransaction() == null) {
			if (tracer.isInfoEnabled()) {
				tracer.info("No server tx found, for in dialog request, assuming it as retransmission and dropping...");
			}
			return;
		}
		
		if (req.getRequest().getMethod().equals(Request.CANCEL)) {
			processCancelRequest(req,dw);
		} else {
			processNotCancelRequest(req,dw);
		}
	}
256964
@Override
  public final void process(final Map<String, Object> pAddParam,
    final IRequestData pRequestData) throws Exception {
    String itemType = pRequestData.getParameter("itemType");
    if (InvItem.class.getSimpleName().equals(itemType)) {
      makeIt(pAddParam, pRequestData, InvItem.class);
    } else if (ServiceToSale.class.getSimpleName().equals(itemType)) {
      makeIt(pAddParam, pRequestData, ServiceToSale.class);
    } else {
      throw new Exception("NYI: " + itemType);
    }
  }
1049090
public BaseMethodBinding<?> determineResourceMethod(RequestDetails requestDetails, String requestPath) {
		RequestTypeEnum requestType = requestDetails.getRequestType();

		ResourceBinding resourceBinding = null;
		BaseMethodBinding<?> resourceMethod = null;
		String resourceName = requestDetails.getResourceName();
		if (myServerConformanceMethod.incomingServerRequestMatchesMethod(requestDetails)) {
			resourceMethod = myServerConformanceMethod;
		} else if (resourceName == null) {
			resourceBinding = myServerBinding;
		} else {
			resourceBinding = myResourceNameToBinding.get(resourceName);
			if (resourceBinding == null) {
				throwUnknownResourceTypeException(resourceName);
			}
		}

		if (resourceMethod == null) {
			if (resourceBinding != null) {
				resourceMethod = resourceBinding.getMethod(requestDetails);
			}
			if (resourceMethod == null) {
				resourceMethod = myGlobalBinding.getMethod(requestDetails);
			}
		}
		if (resourceMethod == null) {
			if (isBlank(requestPath)) {
				throw new InvalidRequestException(myFhirContext.getLocalizer().getMessage(RestfulServer.class, "rootRequest"));
			}
			throwUnknownFhirOperationException(requestDetails, requestPath, requestType);
		}
		return resourceMethod;
	}
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();
    }
539536
protected void notifyRequestListeners(RequestNotifierAction action, HttpServletRequest req, HttpServletResponse resp) throws IOException {
		// notify any listeners that the config has been updated
		IServiceReference[] refs = null;
		try {
			refs = getPlatformServices().getServiceReferences(IRequestListener.class.getName(),  "(name="+getName()+")"); //$NON-NLS-1$ //$NON-NLS-2$
		} catch (PlatformServicesException e) {
			if (log.isLoggable(Level.SEVERE)) {
				log.log(Level.SEVERE, e.getMessage(), e);
			}
		}
		if (refs != null) {
			for (IServiceReference ref : refs) {
				IRequestListener listener = (IRequestListener)getPlatformServices().getService(ref);
				try {
					if (action == RequestNotifierAction.start) {
						listener.startRequest(req, resp);
					} else {
						listener.endRequest(req, resp);
					}
				} finally {
					getPlatformServices().ungetService(ref);
				}
			}
		}
	}