/* (non-Javadoc)
@see org.apereo.portal.portlet.rendering.IPortletExecutionManager#isPortletHeaderRenderRequested(org.apereo.portal.portlet.om.IPortletWindowId, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
181634
@Override
    public boolean isPortletRenderHeaderRequested(
            IPortletWindowId portletWindowId,
            HttpServletRequest request,
            HttpServletResponse response) {
        final Map<IPortletWindowId, IPortletRenderExecutionWorker> portletRenderingMap =
                this.getPortletHeaderRenderingMap(request);
        final IPortletRenderExecutionWorker tracker = portletRenderingMap.get(portletWindowId);

        return tracker != null;
    }
666842
private boolean _isRedirectTrueOnThisRequest(FacesContext facesContext)
    {
        ExternalContext externalContext = facesContext.getExternalContext();
        Map<String, Object> requestMap = externalContext.getRequestMap();
        Boolean redirect = (Boolean) requestMap.get(FLASH_REDIRECT);
        
        return Boolean.TRUE.equals(redirect);
    }
644626
private boolean checkRequestHeaders(HeaderMap headers) {
        // :method pseudo-header must be present always exactly one time;
        // HTTP2 request MUST NOT contain 'connection' header
        if (headers.count(METHOD) != 1 || headers.contains(Headers.CONNECTION)) {
            return false;
        }

        // if CONNECT type is used, then we expect :method and :authority to be present only;
        // :scheme and :path must not be present
        if (headers.get(METHOD).contains(Methods.CONNECT_STRING)) {
            if (headers.contains(SCHEME) || headers.contains(PATH) || headers.count(AUTHORITY) != 1) {
                return false;
            }
        // For other HTTP methods we expect that :scheme, :method, and :path pseudo-headers are
        // present exactly one time.
        } else if (headers.count(SCHEME) != 1 || headers.count(PATH) != 1) {
            return false;
        }

        // HTTP2 request MAY contain TE header but if so, then only with 'trailers' value.
        if (headers.contains(Headers.TE)) {
            for (String value : headers.get(Headers.TE)) {
                if (!value.equals("trailers")) {
                    return false;
                }
            }
        }

        return true;
    }
1338074
protected IPortletWindowId parsePortletWindowIdSuffix(
            HttpServletRequest request,
            final String prefix,
            final Set<String> additionalPortletIds,
            final String name) {
        // See if the parameter name has an additional separator
        final int windowIdStartIdx = name.indexOf(SEPARATOR, prefix.length());
        if (windowIdStartIdx < (prefix.length() + SEPARATOR.length()) - 1) {
            return null;
        }

        // Extract the windowId string and see if it was listed as an additional windowId
        final String portletWindowIdStr = name.substring(windowIdStartIdx + SEPARATOR.length());
        if (additionalPortletIds.contains(portletWindowIdStr)) {
            try {
                return this.portletWindowRegistry.getPortletWindowId(request, portletWindowIdStr);
            } catch (IllegalArgumentException e) {
                this.logger.warn(
                        "Failed to parse portlet window id: "
                                + portletWindowIdStr
                                + " null will be returned",
                        e);
            }
        }

        return null;
    }
192910
protected String verifyPortletWindowId(
            HttpServletRequest request, IPortletWindowId portletWindowId) {
        final IUserInstance userInstance = this.userInstanceManager.getUserInstance(request);
        final IUserPreferencesManager preferencesManager = userInstance.getPreferencesManager();
        final IUserLayoutManager userLayoutManager = preferencesManager.getUserLayoutManager();

        final IPortletWindow portletWindow =
                this.portletWindowRegistry.getPortletWindow(request, portletWindowId);
        final IPortletWindowId delegationParentWindowId = portletWindow.getDelegationParentId();
        if (delegationParentWindowId != null) {
            return verifyPortletWindowId(request, delegationParentWindowId);
        }

        final IPortletEntity portletEntity = portletWindow.getPortletEntity();
        final String channelSubscribeId = portletEntity.getLayoutNodeId();
        final IUserLayoutNodeDescription node = userLayoutManager.getNode(channelSubscribeId);
        if (node == null) {
            throw new IllegalArgumentException(
                    "No layout node exists for id "
                            + channelSubscribeId
                            + " of window "
                            + portletWindowId);
        }

        return node.getId();
    }
1268174
@SuppressWarnings("deprecation")
    @Override
    public boolean isRequestedSessionIdFromUrl() {
        try {
            collaborator.preInvoke(componentMetaData);
            return request.isRequestedSessionIdFromUrl();
        } finally {
            collaborator.postInvoke();
        }
    }
656151
private boolean isHeaderinSuppressedHeadersList(String headername)
    {
        if (WCCustomProperties.CHECK_REQUEST_OBJECT_IN_USE){
            checkRequestObjectInUse();
        }

        boolean suppressHeader = false;
        if(headername != null){
            Iterator itList = suppressheadersList.iterator();
            while (itList.hasNext() && !(suppressHeader)) {
                String s = (String) itList.next();
                if (headername.startsWith(s)) {    	
                    suppressHeader = true;
                    if (TraceComponent.isAnyTracingEnabled() && logger.isLoggable (Level.FINE))   
                        logger.logp(Level.FINE, CLASS_NAME, "isHeaderinSuppressedHeadersList", " suppressHeadersInRequest is set and headername --> "+ headername +" begins with --> " + s);
                }
            }
        }
        return suppressHeader;
    }
727835
public void setOnHeadViewBindViewHolderListener(FamiliarRecyclerView.OnHeadViewBindViewHolderListener onHeadViewBindViewHolderListener) {
        if (null != mWrapFamiliarRecyclerViewAdapter) {
            mWrapFamiliarRecyclerViewAdapter.setOnHeadViewBindViewHolderListener(onHeadViewBindViewHolderListener);
        } else {
            mTempOnHeadViewBindViewHolderListener = onHeadViewBindViewHolderListener;
        }
    }
1322694
@Override
    public void doPortletServeResource(
            IPortletWindowId portletWindowId,
            HttpServletRequest request,
            HttpServletResponse response) {
        final long timeout = getPortletResourceTimeout(portletWindowId, request);

        final IPortletExecutionWorker<Long> resourceWorker =
                this.portletWorkerFactory.createResourceWorker(request, response, portletWindowId);
        resourceWorker.submit();

        try {
            resourceWorker.get(timeout);
        } catch (Exception e) {
            // Log the exception but not this thread's stacktrace. The portlet worker has already
            // logged its stack trace
            this.logger.error(
                    "resource worker {} failed with exception {}", resourceWorker, e.toString());
            // render generic serveResource error
            try {
                if (!response.isCommitted()) {
                    response.sendError(
                            HttpServletResponse.SC_SERVICE_UNAVAILABLE, "resource unavailable");
                }
            } catch (IOException e1) {
                logger.error(
                        "caught IOException trying to send error response for failed resource worker",
                        e);
            }
        }

        // If the worker is still running add it to the hung-workers queue
        if (!resourceWorker.isComplete()) {
            cancelWorker(request, resourceWorker);
        }
    }
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);
		}
	}
1284223
@Override
  public final synchronized void onHttpRequest(final ParsedHttpRequest parsedHttpRequest,
                                               final HttpServletResponse response)
      throws IOException, ServletException {
    LOG.log(Level.INFO, "HttpServeShellCmdHandler in webserver onHttpRequest is called: {0}",
        parsedHttpRequest.getRequestUri());
    final String queryStr = parsedHttpRequest.getQueryString();

    if (parsedHttpRequest.getTargetEntity().equalsIgnoreCase("Evaluators")) {
      final byte[] b = HttpShellJobDriver.CODEC.encode(queryStr);
      LOG.log(Level.INFO, "HttpServeShellCmdHandler call HelloDriver onCommand(): {0}", queryStr);
      messageHandler.get().onNext(b);

      notify();

      final long endTime = System.currentTimeMillis() + WAIT_TIMEOUT;
      while (cmdOutput == null) {
        final long waitTime = endTime - System.currentTimeMillis();
        if (waitTime <= 0) {
          break;
        }

        try {
          wait(WAIT_TIME);
        } catch (final InterruptedException e) {
          LOG.log(Level.WARNING, "HttpServeShellCmdHandler onHttpRequest InterruptedException: {0}", e);
        }
      }
      if (cmdOutput != null) {
        response.getOutputStream().write(cmdOutput.getBytes(StandardCharsets.UTF_8));
        cmdOutput = null;
      }
    } else if (parsedHttpRequest.getTargetEntity().equalsIgnoreCase("Driver")) {
      final String commandOutput = CommandUtils.runCommand(queryStr);
      response.getOutputStream().write(commandOutput.getBytes(StandardCharsets.UTF_8));
    }
  }
234150
protected boolean isThresholdNotificationRequired()
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(tc, "isThresholdNotificationRequired");

        boolean result = false;

        if (_isEventNotificationEnabled ||
            (mp.getCustomProperties().getOutputLinkThresholdEventsToLog() && destinationHandler.isLink()) ||
            (mp.getCustomProperties().getOutputDestinationThresholdEventsToLog() && !destinationHandler.isLink()))
            result = true;

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "isThresholdNotificationRequired", new Boolean(result));

        return result;
    }
1223954
@Override
    public void render(
            Map<String, ?> model, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        final IPortletWindowId portletWindowId =
                (IPortletWindowId) model.get(DELEGATE_PORTLET_WINDOW_ID);
        final DelegationRequest delegationRequest = (DelegationRequest) model.get(DELEGATE_REQUEST);

        final PortletRequest portletRequest =
                (PortletRequest) request.getAttribute(Constants.PORTLET_REQUEST);
        final PortletResponse portletResponse =
                (PortletResponse) request.getAttribute(Constants.PORTLET_RESPONSE);

        final PortletDelegationDispatcher requestDispatcher =
                portletDelegationLocator.getRequestDispatcher(portletRequest, portletWindowId);
        if (requestDispatcher == null) {
            throw new IllegalArgumentException(
                    "No PortletDelegationDispatcher exists for portlet window id: "
                            + portletWindowId);
        }
        this.logger.debug(
                "Found delegation dispatcher for portlet window id {} - {}",
                portletWindowId,
                requestDispatcher);

        final DelegationResponse delegationResponse;
        final String phase = (String) request.getAttribute(PortletRequest.LIFECYCLE_PHASE);
        if (PortletRequest.RENDER_PHASE.equals(phase)) {
            final PortletOutputHandler portletOutputHandler =
                    (PortletOutputHandler) model.get(DELEGATE_RENDER_OUTPUT_HANDLER);
            if (portletOutputHandler != null) {
                this.logger.debug(
                        "Delegating RenderRequest with custom Writer and {}", delegationRequest);
                delegationResponse =
                        requestDispatcher.doRender(
                                (RenderRequest) portletRequest,
                                (RenderResponse) portletResponse,
                                delegationRequest,
                                portletOutputHandler);
            } else {
                this.logger.debug(
                        "Delegating RenderRequest with default Writer and {}", delegationRequest);
                delegationResponse =
                        requestDispatcher.doRender(
                                (RenderRequest) portletRequest,
                                (RenderResponse) portletResponse,
                                delegationRequest);
            }
        } else if (PortletRequest.RESOURCE_PHASE.equals(phase)) {
            this.logger.debug("Delegating ResourceRequest and {}", delegationRequest);
            delegationResponse =
                    requestDispatcher.doServeResource(
                            (ResourceRequest) portletRequest,
                            (ResourceResponse) portletResponse,
                            delegationRequest);
        } else {
            throw new UnsupportedOperationException(
                    "Portlet lifecycle phase "
                            + phase
                            + " is not supported by the delegation view");
        }

        this.logger.debug("{}", delegationResponse);
    }
1160947
@Override
    public boolean enableImmediateResponseRead() {
        if (headersSent()) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Request hdrs already sent, too late for immediate read");
            }
            return false;
        }
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "Immediate response read requested: " + getVC());
        }
        this.bImmediateRead = true;
        return true;
    }
438029
@Override
	protected void processRequest(String requestedPath, HttpServletRequest request, HttpServletResponse response,
			BundleHashcodeType bundleHashcodeType) throws IOException {

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

		// 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 {

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

		// Returns the real file path
		String filePath = getRealFilePath(requestedPath, bundleHashcodeType);

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

				// Set the content type
				response.setContentType(getContentType(requestedPath, request));
				writeContent(filePath, request, response);

			} else {
				if (!responseHeaderWritten) {
					LOGGER.error("Unable to load the image for the request URI : " + request.getRequestURI());
					response.sendError(HttpServletResponse.SC_NOT_FOUND);
				}
			}
		} catch (EOFException eofex) {
			LOGGER.info("Browser cut off response", eofex);
		} catch (ResourceNotFoundException e) {
			LOGGER.info("Unable to write resource " + request.getRequestURI(), e);
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
		} catch (IOException ex) {
			LOGGER.error("Unable to write resource " + request.getRequestURI(), ex);
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
		}

		if (LOGGER.isDebugEnabled())
			LOGGER.debug("request succesfully attended");
	}
484638
public static boolean isInternalRequest(HttpServletRequest request){
		//
		if(Boolean.parseBoolean(request.getHeader(WebConstants.HEADER_INTERNAL_REQUEST))){
			return true;
		}

		boolean isInner = IpUtils.isInnerIp(request.getServerName());
		String forwardHost = request.getHeader(WebConstants.HEADER_FORWARDED_HOST);
		//来源于网关
		if(StringUtils.isNotBlank(forwardHost)){
			isInner = IpUtils.isInnerIp(StringUtils.split(forwardHost, ":")[0]);
		}else{			
			if(!isInner){
				isInner = IpUtils.isInnerIp(IpUtils.getinvokerIpAddr(request));
			}
		}
		return isInner;
	}
1060949
private ResponseEntity<?> handleRequestInternal(HttpMethod method, HttpEntity<?> requestEntity) {
        HttpMessage request = endpointConfiguration.getMessageConverter().convertInbound(requestEntity, endpointConfiguration, null);

        HttpServletRequest servletRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        UrlPathHelper pathHelper = new UrlPathHelper();

        Enumeration allHeaders = servletRequest.getHeaderNames();
        for (String headerName : CollectionUtils.toArray(allHeaders, new String[] {})) {
            if (request.getHeader(headerName) == null) {
                String headerValue = servletRequest.getHeader(headerName);
                request.header(headerName, headerValue != null ? headerValue : "");
            }
        }

        if (endpointConfiguration.isHandleCookies()) {
            request.setCookies(servletRequest.getCookies());
        }

        if (endpointConfiguration.isHandleAttributeHeaders()) {
            Enumeration<String> attributeNames = servletRequest.getAttributeNames();
            while (attributeNames.hasMoreElements()) {
                String attributeName = attributeNames.nextElement();
                Object attribute = servletRequest.getAttribute(attributeName);
                request.setHeader(attributeName, attribute);
            }
        }

        request.path(pathHelper.getRequestUri(servletRequest))
                .uri(pathHelper.getRequestUri(servletRequest))
                .contextPath(pathHelper.getContextPath(servletRequest))
                .queryParams(Optional.ofNullable(pathHelper.getOriginatingQueryString(servletRequest))
                                    .map(queryString -> queryString.replaceAll("&", ","))
                                    .orElse(""))
                .version(servletRequest.getProtocol())
                .method(method);

        Message response = endpointAdapter.handleMessage(request);

        ResponseEntity<?> responseEntity;
        if (response == null) {
            responseEntity = new ResponseEntity<>(HttpStatus.valueOf(endpointConfiguration.getDefaultStatusCode()));
        } else {
            HttpMessage httpResponse;
            if (response instanceof HttpMessage) {
                httpResponse = (HttpMessage) response;
            } else {
                httpResponse = new HttpMessage(response);
            }

            if (httpResponse.getStatusCode() == null) {
                httpResponse.status(HttpStatus.valueOf(endpointConfiguration.getDefaultStatusCode()));
            }

            responseEntity = (ResponseEntity<?>) endpointConfiguration.getMessageConverter().convertOutbound(httpResponse, endpointConfiguration, null);

            if (endpointConfiguration.isHandleCookies() && httpResponse.getCookies() != null) {
                HttpServletResponse servletResponse = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
                for (Cookie cookie : httpResponse.getCookies()) {
                    servletResponse.addCookie(cookie);
                }
            }
        }
        responseCache.add(responseEntity);
        
        return responseEntity;
    }