Dispatch a request outside the container
@param sipServletRequest request
@throws DispatcherException problem occured when dispatching the request outside the container
323677
private void dispatchOutsideContainer(SipServletRequestImpl sipServletRequest) throws DispatcherException {
		final Request request = (Request) sipServletRequest.getMessage();
		if(logger.isInfoEnabled()) {
			logger.info("Dispatching the request event outside the container");
		}
		//check if the request point to another domain
		if(request.getRequestURI() instanceof TelURL ||
				// https://github.com/RestComm/sip-servlets/issues/108
				!(request.getRequestURI() instanceof javax.sip.address.SipURI)) {
			throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "cannot dispatch a request with a tel url or generic request uri outside the container ");
		}
		javax.sip.address.SipURI sipRequestUri = (javax.sip.address.SipURI)request.getRequestURI();
		
		String host = sipRequestUri.getHost();
		int port = sipRequestUri.getPort();
		String transport = JainSipUtils.findTransport(request);
		boolean isAnotherDomain = sipApplicationDispatcher.isExternal(host, port, transport);			
		ListIterator<String> routeHeaders = sipServletRequest.getHeaders(RouteHeader.NAME);				
		if(isAnotherDomain || routeHeaders.hasNext()) {
			try {
				forwardRequestStatefully(sipServletRequest, SipSessionRoutingType.PREVIOUS_SESSION, SipRouteModifier.NO_ROUTE);
			} catch (Exception e) {
				throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "Unexpected Exception while trying to forward statefully the following initial request " + request, e);
			}
		} else {
			// the Request-URI does not point to another domain, and there is no Route header, 
			// the container should not send the request as it will cause a loop. 
			// Instead, the container must reject the request with 404 Not Found final response with no Retry-After header.
			throw new DispatcherException(Response.NOT_FOUND, "the Request-URI does not point to another domain, and there is no Route header," + 
					"the container should not send the request as it will cause a loop. " +
					"Instead, the container must reject the request with 404 Not Found final response with no Retry-After header. You may want to check your dar configuration file to see if the request can be handled or make sure you use the correct Application Router jar.");				
		}
	}
1224159
public void doGet (HttpServletRequest request,
            	   HttpServletResponse response)
    throws ServletException, IOException
    {
    	String access = request.getParameter("access");
    	String callAuthCode = getServletContext().getInitParameter("call.code");
    	if (callAuthCode.equals(access)) {

			String toAddr = "sip:+" + request.getParameter("to").trim() + "@"
					+ getServletContext().getInitParameter("domain.name");

			String fromAddr = "sip:"
					+ getServletContext().getInitParameter("user1") + "@"
					+ getServletContext().getInitParameter("domain.name");

			String secondParty = "sip:+" + request.getParameter("from").trim()
					+ "@" + getServletContext().getInitParameter("domain.name");

			URI to = toAddr == null ? null : sipFactory.createAddress(toAddr)
					.getURI();
			URI from = fromAddr == null ? null : sipFactory.createAddress(
					fromAddr).getURI();

			// Create app session and request
			SipApplicationSession appSession =
			// ((ConvergedHttpSession)request.getSession()).getApplicationSession();
			sipFactory.createApplicationSession();

			SipServletRequest req = sipFactory.createRequest(appSession,
					"INVITE", from, to);

			// Set some attribute
			req.getSession().setAttribute("SecondPartyAddress",
					sipFactory.createAddress(secondParty));
			req.getSession().setAttribute("FromAddr",
					sipFactory.createAddress(fromAddr));
			req.getSession().setAttribute("user",
					getServletContext().getInitParameter("user1"));
			req.getSession().setAttribute("pass",
					getServletContext().getInitParameter("pass1"));

			logger.info("Sending request" + req);
			// Send the INVITE request
			req.send();

		}
        // Write the output html
    	PrintWriter	out;
        response.setContentType("text/html");
        out = response.getWriter();
        
        // Just redirect to the index
        out.println("<HTML><META HTTP-EQUIV=\"Refresh\"CONTENT=\"0; URL=index.jsp\"><HEAD><TITLE></HTML>");
        out.close();
    }
898682
@Override
	public void handleRequest(final Request request) {
		// Check if this link was the AJAX Trigger
		AjaxOperation operation = AjaxHelper.getCurrentOperation();
		boolean pressed = (operation != null && getId().equals(operation.getTriggerId()));

		// Protect against client-side tampering of disabled/read-only fields.
		if (isDisabled() && pressed) {
			LOG.warn("A disabled link has been triggered. " + getText() + ". " + getId());
			return;
		}

		// If an action has been supplied then execute it, but only after
		// handle request has been performed on the entire component tree.
		final Action action = getAction();

		if (pressed && action != null) {
			final ActionEvent event = new ActionEvent(this, getActionCommand(), getActionObject());

			Runnable later = new Runnable() {
				@Override
				public void run() {
					action.execute(event);
				}
			};

			invokeLater(later);
		}
	}
365554
public boolean dispatch(String dispatch, String[] parameters)// throws IOException
	{
		String dispatchURL = dispatch;
		HttpServletRequest servletRequest = httpRequest.get();
		HttpServletResponse servletResponse = httpResponse.get();
		//set content type, because otherwise the response
		//  may be interpreted as text/plain
		servletResponse.setContentType("text/html; charset=UTF-8");
		try
		{
			//pass set attributes as new servlet parameters (a hack to get rid of)
			Request request = requestRegistry.getCurrentRequest();
			if(request != null) {
				for (Object name : request.getAttributeMap().keySet())
				{
					Object o = request.getAttributeMap().get(name);
					servletRequest.setAttribute(name.toString(), o);
				}
			}
			//servlet-include, servlet-forward, service-invocation
            switch(this.dispatchMode)
			{
				case FORWARD:
				{
					ServletSupport.forward(dispatchURL, servletRequest, servletResponse);
				}
				default://INCLUDE
				{
					ServletSupport.include(dispatchURL, servletRequest, servletResponse);
				}
			}
		}
		catch (ServletException e)
		{
			throw new ResourceException("failed to dispatch servlet request to " + dispatchURL, e);
		}
		catch (IOException e)
		{
			throw new ResourceException("failed to dispatch servlet request to " + dispatchURL, e);
		}
		return true;
	}
39396
public static ServletRequest getOuterServletRequest( ServletRequest request )
    {
        ScopedRequest scopedRequest = unwrapRequest( request );
        return scopedRequest != null ? scopedRequest.getOuterRequest() : request;
    }
1231609
public synchronized void setRequest(HttpServletRequest request) {

        if (perThreadRequest == null) {
            perThreadRequest = new ThreadLocal<HttpServletRequest>();
        }
        perThreadRequest.set(request);
    }
1060546
private void dispatchRequest(final CouchbaseRequest request) {
        RingBufferMonitor.instance().removeRequest(request);

        ClusterConfig config = configuration;

        //prevent non-bootstrap requests to go through if bucket not part of config
        if (!(request instanceof BootstrapMessage)) {
            BucketConfig bucketConfig = config == null ? null : config.bucketConfig(request.bucket());
            if (config == null || (request.bucket() != null  && bucketConfig == null)) {
                failSafe(environment.scheduler(), true, request.observable(),
                        new BucketClosedException(request.bucket() + " has been closed"));
                return;
            }

            //short-circuit some kind of requests for which we know there won't be any handler to respond.
            try {
                checkFeaturesForRequest(request, bucketConfig);
            } catch (ServiceNotAvailableException e) {
                failSafe(environment.scheduler(), true, request.observable(), e);
                return;
            }

            //don't send timed out requests to server
            if(!request.isActive()) {
                return;
            }
        }

        locator(request).locateAndDispatch(request, nodes, config, environment, responseBuffer);
    }
135684
@Override
	public void serviceRequest(final Request request) {
		// Get the expected session token
		UIContext uic = UIContextHolder.getCurrent();
		String expected = uic.getEnvironment().getSessionToken();

		// Session token should already be set
		if (expected == null) {
			LOG.error("Session token should already be set on the session before AJAX request. Can be due to the session timing out.");
			handleError();
		}

		// Get the session token from the request
		String got = request.getParameter(Environment.SESSION_TOKEN_VARIABLE);

		// Check tokens match (both must be provided)
		if (Util.equals(expected, got)) {
			// Process Service Request
			getBackingComponent().serviceRequest(request);
		} else { // Invalid token
			LOG.error("Wrong session token detected for AJAX request. Expected token [" + expected
					+ "] but got token [" + got + "].");
			handleError();
		}
	}
853030
@Override
	public void serviceRequest(final Request request) {
		// Get the expected session token
		UIContext uic = UIContextHolder.getCurrent();
		String expected = uic.getEnvironment().getSessionToken();

		// Get the session token from the request
		String got = request.getParameter(Environment.SESSION_TOKEN_VARIABLE);

		// Check tokens match (Both null if new session)
		// or processing a GET and no token
		if (Util.equals(expected, got) || (got == null && "GET".equals(request.getMethod()))) {
			// Process request
			getBackingComponent().serviceRequest(request);
		} else {  // Invalid token
			String msg;
			if (expected == null && got != null) {
				msg = "Session for token [" + got + "] is no longer valid or timed out.";
			} else {
				msg = "Wrong session token detected for servlet request. Expected token [" + expected
						+ "] but got token [" + got + "].";
			}
			LOG.error(msg);
			String message = I18nUtilities.format(uic.getLocale(),
					InternalMessages.DEFAULT_SESSION_TOKEN_ERROR);
			throw new SystemException(message);
		}

	}
616701
public static void setDispatchedPage(ServletRequest request, String dispatchedPage) {
		if(logger.isLoggable(Level.FINE)) logger.log(
			Level.FINE,
			"request={0}, dispatchedPage={1}",
			new Object[] {
				request,
				dispatchedPage
			}
		);
		request.setAttribute(DISPATCHED_PAGE_REQUEST_ATTRIBUTE, dispatchedPage);
	}
282077
private void dispatchRequest(final HttpServerExchange exchange, final ServletRequestContext servletRequestContext, final ServletChain servletChain, final DispatcherType dispatcherType) throws Exception {
        HttpHandler next=null;
        try{
            //lets get access of superclass private fields using reflection:
            Field nextField = ServletInitialHandler.class.getDeclaredField("next");
            nextField.setAccessible(true);
            next = (HttpHandler)nextField.get(this);
            nextField.setAccessible(false);
        }catch(NoSuchFieldException | IllegalAccessException e){
            throw new ServletException(e);
        }

        servletRequestContext.setDispatcherType(dispatcherType);
        servletRequestContext.setCurrentServlet(servletChain);
        if (dispatcherType == DispatcherType.REQUEST || dispatcherType == DispatcherType.ASYNC) {
            super.handleFirstRequest(exchange, servletChain, servletRequestContext, servletRequestContext.getServletRequest(), servletRequestContext.getServletResponse());
        } else {
            next.handleRequest(exchange);
        }
    }
1081374
protected void doRequest(javax.servlet.sip.SipServletRequest req) throws javax.servlet.ServletException, java.io.IOException{
    	String m = req.getMethod();
		if ("INVITE".equals(m))
			doInvite(req);
		else if ("ACK".equals(m))
			doAck(req);
		else if ("OPTIONS".equals(m))
			doOptions(req);
		else if ("BYE".equals(m))
			doBye(req);
		else if ("CANCEL".equals(m))
			doCancel(req);
		else if ("REGISTER".equals(m))
			doRegister(req);
		else if ("SUBSCRIBE".equals(m))
			doSubscribe(req);
		else if ("NOTIFY".equals(m))
			doNotify(req);
		else if ("MESSAGE".equals(m))
			doMessage(req);
		else if ("INFO".equals(m))
			doInfo(req);
		else if ("REFER".equals(m))
			doRefer(req);
		else if ("PUBLISH".equals(m))
			doPublish(req);
		else if ("UPDATE".equals(m))
			doUpdate(req);
		else if ("PRACK".equals(m))
			doPrack(req);
		else if (req.isInitial())
			notHandled(req);
    }
1126270
public SipServletRequest getLinkedSipServletRequest(SipServletRequest req) {
        if (req == null) {
            throw new NullPointerException("the argument is null");
        }
        return linkedRequestMap.get(req);
    }
10773
static void preHandleMultipartRequest(HttpServletRequest request)
        throws ServletException
    {
        MultipartRequestHandler multipartHandler = getCachedMultipartHandler(request);
        
        if (multipartHandler == null)
        {
            multipartHandler = getMultipartHandler(request);
            
            if (multipartHandler != null)
            {
                //
                // Run the request through the handler, and cache the handler in the outer request.
                //
                multipartHandler.handleRequest(request);
                HttpServletRequest outerRequest = ScopedServletUtils.getOuterRequest(request);
                outerRequest.setAttribute(PREHANDLED_MULTIPART_REQUEST_ATTR, multipartHandler);
            }
        }
    }
511158
public void setRequest(ServletRequest request) {
        if (request != null) {
            if (logger.isDebugEnabled()) {
                logger.debug(String.format("set request: %s", request));
            }
            this.threadLocalRequests.set((HttpServletRequest) request);
        } else {
            //if null, remove from threadLocalRequests
            // @see WindowTask#run 's finally
            if (logger.isDebugEnabled()) {
                HttpServletRequest tmpRequest = this.threadLocalRequests.get();
                logger.debug(String.format("remove request: %s", tmpRequest));
            }
            this.threadLocalRequests.remove();
        }
    }
731433
public void setRequest(HttpServletRequest request) {
		WaybackRequest wbRequest = new WaybackRequest();
		wbRequest.extractHttpRequestInfo(request);
		this.wbRequest = wbRequest;
	}
511291
@Override
	public void serviceRequest(final Request request) {

		// Get trigger id
		String triggerId = request.getParameter(WServlet.AJAX_TRIGGER_PARAM_NAME);
		if (triggerId == null) {
			throw new SystemException("No AJAX trigger id to on request");
		}

		// Find the Component for this trigger
		ComponentWithContext trigger = WebUtilities.getComponentById(triggerId,
				true);
		if (trigger == null) {
			throw new SystemException("No component found for AJAX trigger " + triggerId + ".");
		}
		WComponent triggerComponent = trigger.getComponent();

		// Check for an internal AJAX request (if client has flagged it as internal)
		boolean internal = request.getParameter(WServlet.AJAX_TRIGGER_INTERNAL_PARAM_NAME) != null;

		AjaxOperation ajaxOperation = null;
		if (internal) {
			if (!(triggerComponent instanceof AjaxInternalTrigger)) {
				throw new SystemException("AJAX trigger [" + triggerId + "] does not support internal actions.");
			}
			// Create internal operation
			ajaxOperation = new AjaxOperation(triggerId);
		} else {
			// Check for a registered AJAX operation
			ajaxOperation = AjaxHelper.getAjaxOperation(triggerId);

			// Override registered operation if it is a GET and trigger supports Internal AJAX
			// TODO This is only required until all components start using the Internal param flag
			if (ajaxOperation != null && "GET".equals(request.getMethod()) && triggerComponent instanceof AjaxInternalTrigger) {
				// Create internal operation
				ajaxOperation = new AjaxOperation(triggerId);
			}
		}

		// If no operation registered, check if the trigger supports internal AJAX then assume it is an Internal Action
		if (ajaxOperation == null && trigger.getComponent() instanceof AjaxInternalTrigger) {
			// Create internal operation
			ajaxOperation = new AjaxOperation(triggerId);
		}

		// No Valid operation
		if (ajaxOperation == null) {
			throw new SystemException("No AJAX operation has been registered for trigger " + triggerId + ".");
		}

		// Set current operation
		AjaxHelper.setCurrentOperationDetails(ajaxOperation, trigger);

		// Process Service Request
		super.serviceRequest(request);
	}