/*
(non-Javadoc)

@see
org.jdiameter.api.cxdx.ServerCxDxSessionListener#doServerAssignmentRequest(
org.jdiameter.api.cxdx.ServerCxDxSession, org.jdiameter.api.cxdx.events.JServerAssignmentRequest)
354103
@Override
  public void doServerAssignmentRequest(ServerCxDxSession appSession, JServerAssignmentRequest request)
      throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
    logger.info("Diameter Cx/Dx Session Factory :: doServerAssignmentRequest :: appSession[{}], Request[{}]", appSession, request);
  }
719939
@Override
	public void serviceRequest(final Request request) {
		// Get trigger id
		triggerId = request.getParameter(WServlet.AJAX_TRIGGER_PARAM_NAME);
		if (triggerId == null) {
			throw new SystemException("No AJAX trigger id to check step count");
		}

		// Get trigger and its context
		ComponentWithContext trigger = AjaxHelper.getCurrentTriggerAndContext();
		if (trigger == null) {
			throw new IllegalStateException(
					"No component/context available for AJAX trigger " + triggerId + ".");
		}

		// Get expected step count
		UIContext uic = UIContextHolder.getCurrent();
		int expected = uic.getEnvironment().getStep();

		// Step should already be set on the session
		if (expected == 0) {
			throw new SystemException(
					"Step count should already be set on the session before AJAX request.");
		}

		// Get step count on the request
		int got = StepCountUtil.getRequestStep(request);

		// Check we are on the current step
		if (expected == got) {
			// Process Service Request
			getBackingComponent().serviceRequest(request);
		} else { // Invalid step
			LOG.warn("AJAX: Wrong step detected. Expected step " + expected + " but got step " + got);
			// "GET" Ajax requests are just ignored and return an error code
			if ("GET".equals(request.getMethod())) {
				LOG.warn("Error code will be sent in the response for AJAX GET Request.");
				handleErrorCode();
				// Make sure the render phase is not processed
				throw new ActionEscape();
			} else if (StepCountUtil.isErrorRedirect()) { // Redirect to error page
				LOG.warn("User will be redirected to an error page.");
				redirectUrl = StepCountUtil.getErrorUrl();
			} else {  // Warp to the future by refreshing the page
				LOG.warn("Warp the user back to the future by refreshing the page.");
				handleWarpToTheFuture(uic);
				redirectUrl = buildApplicationUrl(uic);
			}
		}
	}
910441
protected void sendConfigureRequest(Connection connection, MemberState member, ConfigureRequest request) {
    logger.trace("{} - Sending {} to {}", context.getCluster().member().address(), request, member.getMember().serverAddress());
    connection.<ConfigureRequest, ConfigureResponse>sendAndReceive(request).whenComplete((response, error) -> {
      context.checkThread();

      // Complete the configure to the member.
      member.completeConfigure();

      if (open) {
        if (error == null) {
          logger.trace("{} - Received {} from {}", context.getCluster().member().address(), response, member.getMember().serverAddress());
          handleConfigureResponse(member, request, response);
        } else {
          logger.warn("{} - Failed to configure {}", context.getCluster().member().address(), member.getMember().serverAddress());
          handleConfigureResponseFailure(member, request, error);
        }
      }
    });
  }
1174881
@Override
	public void serviceRequest(final Request request) {
		// Get expected step count
		UIContext uic = UIContextHolder.getCurrent();
		int expected = uic.getEnvironment().getStep();

		// Step should already be set on the session
		if (expected == 0) {
			throw new SystemException(
					"Step count should already be set on the session before content request.");
		}

		// Get step count on the request
		int got = StepCountUtil.getRequestStep(request);

		// Check tokens match (both must be provided)
		if (expected == got) {
			// Process Service Request
			getBackingComponent().serviceRequest(request);
		} else if (!StepCountUtil.isStepOnRequest(request) && StepCountUtil.isCachedContentRequest(request)) {  // cached content (no step on request)
			// Process Service Request
			getBackingComponent().serviceRequest(request);
		} else {  // Invalid token
			// Set an error code
			LOG.warn(
					"Wrong step detected for content request. Expected step [" + expected + "] but got step [" + got
					+ "].");
			handleError();
		}

	}
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();
        }
    }
199046
public void init(HttpServletRequest request) {
		resetTimers();
		
		if (request != null) {
			String p = request.getPathInfo();
			final int pathLength = (p == null ? 0 : p.length());
			
			final StringBuffer urlSb = request.getRequestURL();
			String simpleUrl = urlSb.toString(); // without qs
			
			String qs = request.getQueryString();
			if (qs != null) urlSb.append("?").append(qs);
			final String fullUrl = urlSb.toString();
			contextUrl.set(fullUrl);
		
			requestCookies.remove();
			responseCookies.remove();
			
			StringBuilder cookiesDump = new StringBuilder();
			Map<String, Cookie> cookiez = requestCookies.get();
			for (javax.servlet.http.Cookie c : Check.ifNull(request.getCookies(), new javax.servlet.http.Cookie[0])) {
				cookiez.put(c.getName(), new BasicClientCookie(c.getName(), c.getValue()));
				cookiesDump.append(c.toString()).append(";");
			}
	
			String xForwardedFor = request.getHeader(HEADER_X_FORWARDED_FOR);
			clientIp.set(xForwardedFor != null ? xForwardedFor : request.getRemoteAddr());
			
			String xForwardedUrl = request.getHeader(HEADER_X_FORWARDED_URL);
			if (xForwardedUrl != null) {
				int i = xForwardedUrl.lastIndexOf("?");
				simpleUrl = (i == -1 ? xForwardedUrl : xForwardedUrl.substring(0, i));
			}
			
			try {
				simpleUrl = URLDecoder.decode(simpleUrl, "UTF-8"); // convert "%xx" stuff before working with lengths
			} catch (UnsupportedEncodingException e) {
				log.error(e.toString());
			}
			contextPath.set(simpleUrl.substring(0, simpleUrl.length() - pathLength));

			if (verbose) log.info(">>> Time 0 [" + fullUrl + "]. cookies from client: " + cookiesDump.toString());
		}
		
		initialized.set(true);
	}
895310
protected void initBinder(final HttpServletRequest request, final ServletRequestDataBinder binder) {
        if (serviceValidateConfigurationContext.isRenewEnabled()) {
            binder.setRequiredFields(CasProtocolConstants.PARAMETER_RENEW);
        }
    }
928472
@Override
	public void handleRequest(final Request request) {
		if (!isInitialised()) {
			getOrCreateComponentModel().delegate = new SafetyContainerDelegate(UIContextHolder.
					getCurrent());
			setInitialised(true);
		}

		try {
			UIContext delegate = getComponentModel().delegate;
			UIContextHolder.pushContext(delegate);

			try {
				for (int i = 0; i < shim.getChildCount(); i++) {
					shim.getChildAt(i).serviceRequest(request);
				}

				delegate.doInvokeLaters();
			} finally {
				UIContextHolder.popContext();
			}
		} catch (final ActionEscape e) {
			// We don't want to catch ActionEscapes (e.g. ForwardExceptions)
			throw e;
		} catch (final Exception e) {
			if (isAjaxOrTargetedRequest(request)) {
				throw new SystemException(e.getMessage(), e);
			} else {
				setAttribute(ERROR_KEY, e);
			}
		}
	}
63437
public static void serverReceived(NettyHttpRequest request) {
        try {
            SofaRequest sofaRequest = new SofaRequest();

            HttpHeaders headers = request.getHttpHeaders();
            String rpcTraceContext = headers.getHeaderString(RemotingConstants.NEW_RPC_TRACE_NAME);
            if (StringUtils.isNotBlank(rpcTraceContext)) {
                // 新格式
                sofaRequest.addRequestProp(RemotingConstants.NEW_RPC_TRACE_NAME, rpcTraceContext);
            } else {
                String traceIdKey = headers.getHeaderString(RemotingConstants.HTTP_HEADER_TRACE_ID_KEY);
                String rpcIdKey = headers.getHeaderString(RemotingConstants.HTTP_HEADER_RPC_ID_KEY);
                if (StringUtils.isEmpty(rpcIdKey)) {
                    rpcIdKey = request.getUri().getQueryParameters().getFirst(RemotingConstants.RPC_ID_KEY);
                }
                if (StringUtils.isEmpty(traceIdKey)) {
                    traceIdKey = request.getUri().getQueryParameters().getFirst(RemotingConstants.TRACE_ID_KEY);
                }

                if (StringUtils.isNotEmpty(traceIdKey) && StringUtils.isNotEmpty(rpcIdKey)) {
                    Map<String, String> map = new HashMap<String, String>();
                    map.put(RemotingConstants.TRACE_ID_KEY, traceIdKey);
                    map.put(RemotingConstants.RPC_ID_KEY, rpcIdKey);
                    String penAttrs = headers.getHeaderString(RemotingConstants.PEN_ATTRS_KEY);
                    map.put(RemotingConstants.PEN_ATTRS_KEY, penAttrs);
                    sofaRequest.addRequestProp(RemotingConstants.RPC_TRACE_NAME, map);
                }
            }
            Tracers.serverReceived(sofaRequest);
        } catch (Throwable t) {
            if (LOGGER.isWarnEnabled()) {
                LOGGER.warn("the process of rest tracer server receive occur error ", t);
            }
        }
    }
254444
@Override
    public void setupRequest ( CommonServerMessageBlock request ) {

        if ( ! ( request instanceof ServerMessageBlock ) ) {
            return;
        }

        ServerMessageBlock req = (ServerMessageBlock) request;

        req.addFlags2(this.negotiatedFlags2);
        req.setUseUnicode(req.isForceUnicode() || this.useUnicode);
        if ( req.isUseUnicode() ) {
            req.addFlags2(SmbConstants.FLAGS2_UNICODE);
        }

        if ( req instanceof SmbComTransaction ) {
            ( (SmbComTransaction) req ).setMaxBufferSize(this.snd_buf_size);
        }
    }
1213450
@Override
	public void handleRequest(final Request request) {
		if (!isDisabled()) {
			final SelectToggleModel model = getComponentModel();
			String requestParam = request.getParameter(getId());

			final State newValue;
			if ("all".equals(requestParam)) {
				newValue = State.ALL;
			} else if ("none".equals(requestParam)) {
				newValue = State.NONE;
			} else if ("some".equals(requestParam)) {
				newValue = State.SOME;
			} else {
				newValue = model.state;
			}

			if (!newValue.equals(model.state)) {
				setState(newValue);
			}
			if (!model.clientSide && model.target != null && !State.SOME.equals(newValue)) {
				// We need to change the selections *after* all components
				// Have updated themselves from the request, as they may change
				// their values when their handleRequest methods are called.
				invokeLater(new Runnable() {
					@Override
					public void run() {
						setSelections(model.target, State.ALL.equals(newValue));
					}
				});
			}
		}
	}
576510
@Override
    public RequestCtx handleRequest(HttpServletRequest request,
                                    HttpServletResponse response)
            throws IOException, ServletException {
        if (logger.isDebugEnabled()) {
            logger.debug("{}/handleRequest!", this.getClass().getName());
        }

        String dsState = request.getParameter("dsState");

        RequestCtx req = null;
        Map<URI, AttributeValue> actions = new HashMap<URI, AttributeValue>();
        Map<URI, AttributeValue> resAttr;
        try {
            String[] parts = getPathParts(request);
            resAttr = ResourceAttributes.getResources(parts);
            if (dsState != null && !dsState.isEmpty()) {
                resAttr.put(Constants.DATASTREAM.NEW_STATE.getURI(),
                            new StringAttribute(dsState));
            }

            actions
                    .put(Constants.ACTION.ID.getURI(),
                         Constants.ACTION.SET_DATASTREAM_STATE
                                 .getStringAttribute());
            actions.put(Constants.ACTION.API.getURI(),
                        Constants.ACTION.APIM.getStringAttribute());

            // modifying the FeSL policy datastream requires policy management permissions
            String dsID = parts[3];
            if (dsID != null && dsID.equals(FedoraPolicyStore.FESL_POLICY_DATASTREAM)) {
                actions.put(Constants.ACTION.ID.getURI(),
                            Constants.ACTION.MANAGE_POLICIES.getStringAttribute());
            }


            req =
                    getContextHandler().buildRequest(getSubjects(request),
                                                     actions,
                                                     resAttr,
                                                     getEnvironment(request));

            LogUtil.statLog(request.getRemoteUser(),
                            Constants.ACTION.SET_DATASTREAM_STATE.uri,
                            parts[1],
                            dsID);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ServletException(e.getMessage(), e);
        }

        return req;
    }
1070631
@Override
  public void sendRegistrationTerminationRequest(JRegistrationTerminationRequest request)
      throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
    send(Event.Type.SEND_MESSAGE, request, null);
  }
1135967
public void handleServerNotificationRegistration(RESTRequest request, int clientID, ServerNotificationRegistration serverNotificationRegistration,
                                                     JSONConverter converter) {
        //Get the client area
        ClientNotificationArea clientArea = getInboxIfAvailable(clientID, converter);

        if (serverNotificationRegistration.operation == Operation.RemoveAll) {
            //Unregister with our client area (will also unregister with the MBeanServer)
            clientArea.removeServerNotificationListener(request, serverNotificationRegistration, true, converter, false);

        } else {
            if (serverNotificationRegistration.operation == Operation.Add) {
                //Register with our client area (will also register with the MBeanServer)
                clientArea.addServerNotificationListener(request, serverNotificationRegistration, converter);

                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Added server-side notification");
                }

            } else {
                //Unregister with our client area (will also unregister with the MBeanServer)
                clientArea.removeServerNotificationListener(request, serverNotificationRegistration, false, converter, false);
            }
        }
    }
1233012
@Override
  public Answer processRequest(IRequest request, IRealm matchedRealm) {
    try {
      Answer ans = request.createAnswer(RESULT_REDIRECT_INDICATION);
      AvpSet set = ans.getAvps();
      String[] destHosts = matchedRealm.getPeerNames();
      for (String host:destHosts) {
        set.addAvp(Avp.REDIRECT_HOST, host, false);
      }

      IAgentConfiguration agentConfiguration = matchedRealm.getAgentConfiguration();
      //default
      int rhuValue = RHU_REALM_AND_APPLICATION;
      if (agentConfiguration != null) {
        Properties p = agentConfiguration.getProperties();
        try {
          rhuValue = Integer.parseInt(p.getProperty(RHU_PROPERTY, "" + rhuValue));
        }
        catch (Exception e) {
          if (logger.isWarnEnabled()) {
            logger.warn("Failed to parse configuration value. ", e);
          }
        }
      }

      set.addAvp(Avp.REDIRECT_HOST_USAGE, rhuValue);
      ans.setError(true);
      super.container.sendMessage((IMessage) ans);
    }
    catch (Exception e) {
      if (logger.isDebugEnabled()) {
        logger.debug("Failure when trying to send Answer", e);
      }
      Answer ans = request.createAnswer(RESULT_INVALID_AVP_VALUE);
      // now lets do the magic.
      if (e instanceof AvpDataException && ((AvpDataException) e).getAvp() != null) {
        // lets add failed if its present
        AvpSet failedAvp = ans.getAvps().addGroupedAvp(Avp.FAILED_AVP);
        failedAvp.addAvp(((AvpDataException) e).getAvp());
      }
      try {
        container.sendMessage((IMessage) ans);
      }
      catch (RouteException re) {
        if (logger.isDebugEnabled()) {
          logger.debug("Failure when trying to send failure answer", re);
        }
      }
      catch (AvpDataException ade) {
        if (logger.isDebugEnabled()) {
          logger.debug("Failure when trying to send failure answer", ade);
        }
      }
      catch (IllegalDiameterStateException idse) {
        if (logger.isDebugEnabled()) {
          logger.debug("Failure when trying to send failure answer", idse);
        }
      }
      catch (IOException ioe) {
        if (logger.isDebugEnabled()) {
          logger.debug("Failure when trying to send failure answer", ioe);
        }
      }
    }
    return null;
  }
378651
@Override
    public ClientResponse doHandle(ClientRequest request) {
        if (request == null) {
            throw new IllegalArgumentException("Request should not be null");
        }

        URI originalURI = request.getURI();
        request.setURI(locationManager.getRedirectedURI(originalURI));

        ClientResponse response = getNext().handle(request);
        while (response.getClientResponseStatus() == ClientResponse.Status.MOVED_PERMANENTLY) {
            try {
                locationManager.setRedirectedURI(response.getHeaders()
                        .getFirst("Location"));
            } catch (NullPointerException e) {
                throw new ClientHandlerException(
                        "HTTP Redirect did not include Location header");
            } catch (URISyntaxException e) {
                throw new ClientHandlerException(
                        "HTTP Redirect location is not a valid URI");
            }

            request.setURI(locationManager.getRedirectedURI(originalURI));
            response = getNext().handle(request);
        }
        return response;
    }
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);
	}