Get an instance of a DataGridStateFactory given a {@link ServletRequest}.

@param request the current {@link ServletRequest}
@return an instance of the factory
552046
public static final DataGridStateFactory getInstance(ServletRequest request) {
        Object obj = request.getAttribute(KEY);
        if(obj != null) {
            assert obj instanceof DataGridStateFactory;
            return (DataGridStateFactory)obj;
        }
        else {
            DataGridStateFactory factory = new DataGridStateFactory(request);
            request.setAttribute(KEY, factory);
            return factory;
        }
    }
590233
public void doTag() {
        JspContext jspContext = getJspContext();
        DataGridStateFactory factory = DataGridStateFactory.getInstance(jspContext);
        assert factory != null;

        DataGridState state = null;
        if(_config != null)
            state = factory.getDataGridState(_name, _config);
        else
            state = factory.getDataGridState(_name);

        jspContext.setAttribute(_var, state);
    }
261456
public static GlobalApp getGlobalApp(ServletRequest request) {
        assert request instanceof HttpServletRequest;
        GlobalApp ga = PageFlowUtils.getGlobalApp((HttpServletRequest)request);
        if(ga == null) {
            String message = "There is no current GlobalApp!";
            LOGGER.error(message);
            throw new RuntimeException(message);
        }
        return ga;
    }
975470
static GraphNode getServiceNode(HttpServletRequest request) {
        final IRI serviceUri = new IRI(getFullRequestUrl(request));
        final Graph resultGraph = new SimpleGraph();
        return new GraphNode(serviceUri, resultGraph);
    }
112905
public CreateClusterResponse createCluster(CreateClusterRequest request) {
        checkNotNull(request, "request should not be null.");
        checkStringNotEmpty(request.getImageType(), "The imageType should not be null or empty string.");
        checkStringNotEmpty(request.getImageVersion(), "The imageVersion should not be null or empty string.");
        checkNotNull(request.getInstanceGroups(), "The instanceGroups should not be null.");

        StringWriter writer = new StringWriter();
        try {
            JsonGenerator jsonGenerator = JsonUtils.jsonGeneratorOf(writer);
            jsonGenerator.writeStartObject();
            jsonGenerator.writeStringField("imageType", request.getImageType());
            jsonGenerator.writeStringField("imageVersion", request.getImageVersion());
            jsonGenerator.writeArrayFieldStart("instanceGroups");
            for (InstanceGroupConfig instanceGroup : request.getInstanceGroups()) {
                jsonGenerator.writeStartObject();
                if (instanceGroup.getName() != null) {
                    jsonGenerator.writeStringField("name", instanceGroup.getName());
                }
                jsonGenerator.writeStringField("type", instanceGroup.getType());
                jsonGenerator.writeStringField("instanceType", instanceGroup.getInstanceType());
                jsonGenerator.writeNumberField("instanceCount", instanceGroup.getInstanceCount());
                jsonGenerator.writeEndObject();
            }
            jsonGenerator.writeEndArray();
            if (request.getName() != null) {
                jsonGenerator.writeStringField("name", request.getName());
            }
            if (request.getLogUri() != null) {
                jsonGenerator.writeStringField("logUri", request.getLogUri());
            }
            jsonGenerator.writeBooleanField("autoTerminate", request.getAutoTerminate());

            if (request.getApplications() != null) {
                jsonGenerator.writeArrayFieldStart("applications");
                for (ApplicationConfig application : request.getApplications()) {
                    jsonGenerator.writeStartObject();
                    jsonGenerator.writeStringField("name", application.getName());
                    jsonGenerator.writeStringField("version", application.getVersion());
                    if (application.getProperties() != null) {
                        jsonGenerator.writeObjectFieldStart("properties");
                        for (Map.Entry<String, Object> entry : application.getProperties().entrySet()) {
                            jsonGenerator.writeObjectField(entry.getKey(), entry.getValue());
                        }
                        jsonGenerator.writeEndObject();
                    }
                    jsonGenerator.writeEndObject();
                }
                jsonGenerator.writeEndArray();
            }

            if (request.getSteps() != null) {
                jsonGenerator.writeArrayFieldStart("steps");
                for (StepConfig step : request.getSteps()) {
                    jsonGenerator.writeStartObject();
                    if (step.getName() != null) {
                        jsonGenerator.writeStringField("name", step.getName());
                    }
                    jsonGenerator.writeStringField("type", step.getType());
                    jsonGenerator.writeStringField("actionOnFailure", step.getActionOnFailure());
                    jsonGenerator.writeObjectFieldStart("properties");
                    for (Map.Entry<String, String> entry : step.getProperties().entrySet()) {
                        jsonGenerator.writeStringField(entry.getKey(), entry.getValue());
                    }
                    jsonGenerator.writeEndObject();
                    jsonGenerator.writeEndObject();
                }
                jsonGenerator.writeEndArray();
            }

            jsonGenerator.writeEndObject();
            jsonGenerator.close();
        } catch (IOException e) {
            throw new BceClientException("Fail to generate json", e);
        }

        byte[] json = null;
        try {
            json = writer.toString().getBytes(DEFAULT_ENCODING);
        } catch (UnsupportedEncodingException e) {
            throw new BceClientException("Fail to get UTF-8 bytes", e);
        }

        InternalRequest internalRequest = this.createRequest(request, HttpMethodName.POST, CLUSTER);
        internalRequest.addHeader(Headers.CONTENT_LENGTH, String.valueOf(json.length));
        internalRequest.addHeader(Headers.CONTENT_TYPE, "application/json");
        internalRequest.setContent(RestartableInputStream.wrap(json));

        if (request.getClientToken() != null) {
            internalRequest.addParameter("clientToken", request.getClientToken());
        }

        return this.invokeHttpClient(internalRequest, CreateClusterResponse.class);
    }
428190
public GetStatTopRefererResponse getStatTopReferer(GetStatTopRefererRequest request) {
        InternalRequest internalRequest = this.createRequest(request, HttpMethodName.GET, STAT, "topn", "referer");
        
        if (request.getStartTime() != null) {
            internalRequest.addParameter("startTime", DateUtils.formatAlternateIso8601Date(request.getStartTime()));
        }
        
        if (request.getEndTime() != null) {
            internalRequest.addParameter("endTime", DateUtils.formatAlternateIso8601Date(request.getEndTime()));
        }
        
        if (request.getDomain() != null) {
            internalRequest.addParameter("domain", request.getDomain());
        }
        
        if (request.getPeriod() != null) {
            internalRequest.addParameter("period", String.valueOf(request.getPeriod()));
        }
        
        return this.invokeHttpClient(internalRequest, GetStatTopRefererResponse.class);
    }
939283
public CmsTemplateContextInfo getContextInfoBean(CmsObject cms, HttpServletRequest request) {

        CmsTemplateContextInfo result = new CmsTemplateContextInfo();
        CmsTemplateContext context = (CmsTemplateContext)request.getAttribute(ATTR_TEMPLATE_CONTEXT);
        if (context != null) {
            result.setCurrentContext(context.getKey());

            I_CmsTemplateContextProvider provider = context.getProvider();
            Locale locale = OpenCms.getWorkplaceManager().getWorkplaceLocale(cms);
            CmsXmlContentProperty settingDefinition = createTemplateContextsPropertyDefinition(provider, locale);
            result.setSettingDefinition(settingDefinition);
            String cookieName = context.getProvider().getOverrideCookieName();
            if (cookieName != null) {
                String cookieValue = CmsRequestUtil.getCookieValue(request.getCookies(), cookieName);
                result.setSelectedContext(cookieValue);
            }
            result.setCookieName(cookieName);
            Map<String, String> niceNames = new LinkedHashMap<String, String>();
            for (Map.Entry<String, CmsTemplateContext> entry : provider.getAllContexts().entrySet()) {
                CmsTemplateContext otherContext = entry.getValue();
                String niceName = otherContext.getLocalizedName(locale);
                niceNames.put(otherContext.getKey(), niceName);
                for (CmsClientVariant variant : otherContext.getClientVariants().values()) {
                    CmsClientVariantInfo info = new CmsClientVariantInfo(
                        variant.getName(),
                        variant.getNiceName(locale),
                        variant.getScreenWidth(),
                        variant.getScreenHeight(),
                        variant.getParameters());
                    result.setClientVariant(otherContext.getKey(), variant.getName(), info);
                }
            }
            result.setContextLabels(niceNames);
            result.setContextProvider(provider.getClass().getName());
        }
        Map<String, CmsDefaultSet<String>> allowedContextMap = safeGetAllowedContextMap();
        result.setAllowedContexts(allowedContextMap);
        return result;
    }
1219824
public SessionAffinityContext analyzeRequest(ServletRequest request) {
        // create local variable - JIT performance improvement
        final boolean isTraceOn = com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled();
        if (isTraceOn && LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINE)) {
            LoggingUtil.SESSION_LOGGER_CORE.entering(methodClassName, methodNames[ANALYZE_REQUEST]);
        }

        String sessionID = null;
        boolean reqFromCookie = false;
        boolean reqFromURL = false;
        boolean reqFromSSL = false;
        boolean reqFromClient = false;
        SessionAffinityContext sessionAffinityContext = null;
        List allSessionIds = null;

        // tries to get the sac from SSL (if applicable)
        if (_smc.useSSLId()) {
            String sessionId = getActualSSLSessionId(request);
            sessionAffinityContext = analyzeSSLRequest(request, sessionId);
        }
        // we found a sessionAffinityContext for SSL ... return
        if (sessionAffinityContext != null) {
            if (isTraceOn && LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINE)) {
                LoggingUtil.SESSION_LOGGER_CORE.exiting(methodClassName, methodNames[ANALYZE_REQUEST], "Affinity Context found from SSL");
            }
            return sessionAffinityContext;
        }

        // try a non-SSL request
        if (_smc.getEnableCookies()) {
            // allSessionIds =
            // ((IExtendedRequest)request).getAllCookieValues(_smc.getSessionCookieName());
            byte[] byteSessId = ((IExtendedRequest) request).getCookieValueAsBytes(_smc.getSessionCookieName());
            if (byteSessId != null) {
                allSessionIds = new ArrayList(1);
                allSessionIds.add(0, new String(byteSessId));
                if (isTraceOn && LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINE)) {
                    LoggingUtil.SESSION_LOGGER_CORE.logp(Level.FINE, methodClassName, methodNames[ANALYZE_REQUEST], "Found session id(s) in cookie");
                }
                reqFromCookie = true;
            } else { // 105740: Good message when cookies doesn't contain the sessionID
                if (isTraceOn&&LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINE)) {
                    LoggingUtil.SESSION_LOGGER_CORE.logp(Level.FINE, methodClassName, methodNames[ANALYZE_REQUEST], "No session id(s) found in cookie");
                }
            }


            /*
             * allSessionIds =
             * ((IExtendedRequest)request).getAllCookieValues(_smc.getSessionCookieName
             * ());
             * if ((allSessionIds != null) && (!allSessionIds.isEmpty())) {
             * if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&LoggingUtil.
             * SESSION_LOGGER_CORE.isLoggable(Level.FINE)) {
             * LoggingUtil.SESSION_LOGGER_CORE.logp(Level.FINE, methodClassName,
             * methodNames[ANALYZE_REQUEST], "Found session id(s) in cookie");
             * }
             * reqFromCookie = true;
             * }
             */
        }

        if ((!reqFromCookie) && (_smc.getEnableUrlRewriting())) {
            sessionID = getRequestedSessionIdFromURL(request);
            if (sessionID != null) {
                reqFromURL = true;
                allSessionIds = new ArrayList(1);
                allSessionIds.add(0, sessionID);
            }
            if (isTraceOn && LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINE)) {
                LoggingUtil.SESSION_LOGGER_CORE.logp(Level.FINE, methodClassName, methodNames[ANALYZE_REQUEST], "Found session id in URL: " + sessionID);
            }
        } 
        
        
        // Maybe a cookie was sent using the wrong means - ok it should be treated as
        // invalid but should be returned from ServletRequest.getRequestedSessionId()
        if (!reqFromCookie && !reqFromURL) {            
            if (_smc.getEnableCookies()) {
                // If cookies were enable now look in the URL
                sessionID = getRequestedSessionIdFromURL(request,true);
                if (sessionID != null) {
                    if (isTraceOn && LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINE)) {
                        LoggingUtil.SESSION_LOGGER_CORE.logp(Level.FINE, methodClassName, methodNames[ANALYZE_REQUEST], "Found client session id in URL: " + sessionID);
                    }
                    reqFromClient = true;
                    allSessionIds = new ArrayList(1);
                    allSessionIds.add(0, sessionID);
                }              
            } else {               
                byte[] byteSessId = ((IExtendedRequest) request).getCookieValueAsBytes(_smc.getSessionCookieName());
                if (byteSessId != null) {
                    allSessionIds = new ArrayList(1);
                    allSessionIds.add(0, new String(byteSessId));
                    if (isTraceOn && LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINE)) {
                        LoggingUtil.SESSION_LOGGER_CORE.logp(Level.FINE, methodClassName, methodNames[ANALYZE_REQUEST], "Found client session id(s) in cookie");
                    }
                    reqFromClient = true;
                } else { // 105740: Good message when cookies doesn't contain the sessionID
                    if (isTraceOn&&LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINE)) {
                        LoggingUtil.SESSION_LOGGER_CORE.logp(Level.FINE, methodClassName, methodNames[ANALYZE_REQUEST], "No session id(s) found in cookie");
                    }
                }
            }    
        }
        
        if (isTraceOn && LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINE)) {
            LoggingUtil.SESSION_LOGGER_CORE.logp(Level.FINE, methodClassName, methodNames[ANALYZE_REQUEST], "allSessionIds size = " + (allSessionIds == null ? "0" : allSessionIds.size()));
        }

        sessionAffinityContext = new SessionAffinityContext(allSessionIds, reqFromCookie, reqFromURL, reqFromSSL,reqFromClient);
        setNextId(sessionAffinityContext);

        // Since we didn't have a sac, but we have session id string...we've been
        // remotely dispatched
        // We need to set the version, id, and clones from the request string into
        // the response fields
        // of our sac.
        String idFromRequest = ((IExtendedRequest) request).getUpdatedSessionId();
        if (idFromRequest != null) { // if yes, modify newly created sac with that data
            setResponseData(idFromRequest, sessionAffinityContext);
        }
        if (isTraceOn && LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINE)) {
            LoggingUtil.SESSION_LOGGER_CORE.exiting(methodClassName, methodNames[ANALYZE_REQUEST]);
        }
        return sessionAffinityContext;
    }
129916
public static AuthenticationResult authenticationResultFromRequest(final HttpServletRequest request)
  {
    final AuthenticationResult authenticationResult = (AuthenticationResult) request.getAttribute(
        AuthConfig.DRUID_AUTHENTICATION_RESULT
    );

    if (authenticationResult == null) {
      throw new ISE("Null authentication result");
    }

    return authenticationResult;
  }
1041913
public static String getRequestURI(final HttpServletRequest request) {
		return (String) request.getSession(true).getAttribute(STORE_URI_KEY);
	}
1210932
@SuppressWarnings("unchecked")
	@Override
	public <T extends Resource> T request(final HttpRequestBase request) {
		try {
			HttpResponse response = execute(client, request);
			Resource resource = toPage(request, response);
			return (T)resource;
		} catch (Exception e) {
			throw MechanizeExceptionFactory.newException(e);
		}
	}
600163
@SuppressWarnings("unused")
	public static <T> String getRequestPayload(Request<T> request) {
		Class<?> referenceClazz = request.getClass();
		List<Field> fields = ClassUtil.getAnnotatedFields(referenceClazz, Body.class);
		List<String> objects = new LinkedList<String>();
		for (Field field : fields) {
			Body body = field.getAnnotation(Body.class);

			String asString = ClassUtil.getValueOf(field, request, referenceClazz, String.class);
			return (asString != null ? asString : "");
			// what if there are more bodies?!
		}
		return EMPTY;
	}
907155
@Override
	public void serviceRequest(final Request request) {
		// Get window id off the request
		windowId = request.getParameter(WWindow.WWINDOW_REQUEST_PARAM_KEY);

		if (windowId == null) {
			super.serviceRequest(request);
		} else {
			// Get the window component
			ComponentWithContext target = WebUtilities.getComponentById(windowId, true);
			if (target == null) {
				throw new SystemException("No window component for id " + windowId);
			}

			// Setup the Environment on the context
			UIContext uic = UIContextHolder.getCurrentPrimaryUIContext();
			Environment originalEnvironment = uic.getEnvironment();
			uic.setEnvironment(new EnvironmentDelegate(originalEnvironment, windowId, target));

			if (attachWindow) {
				attachUI(target.getComponent());
			}
			UIContextHolder.pushContext(target.getContext());
			try {
				super.serviceRequest(request);
			} finally {
				uic.setEnvironment(originalEnvironment);
				UIContextHolder.popContext();
			}
		}
	}
1201703
public static ServletRequest getContextRequest()
    {
        ServiceContext context = (ServiceContext) _localContext.get();

        if (context != null)
            return context._request;
        else
            return null;
    }
340667
private CompletableFuture<PrimaryBackupServiceContext> getService(PrimitiveRequest request) {
    return services.computeIfAbsent(request.primitive().name(), n -> {
      PrimitiveType primitiveType = primitiveTypes.getPrimitiveType(request.primitive().type());
      PrimaryBackupServiceContext service = new PrimaryBackupServiceContext(
          serverName,
          PrimitiveId.from(request.primitive().name()),
          primitiveType,
          request.primitive(),
          threadContextFactory.createContext(),
          clusterMembershipService,
          memberGroupService,
          protocol,
          primaryElection);

      OrderedFuture<PrimaryBackupServiceContext> newOrderFuture = new OrderedFuture<>();
      service.open().whenComplete((v, e) -> {
        if (e != null) {
          newOrderFuture.completeExceptionally(e);
        } else {
          newOrderFuture.complete(service);
        }
      });
      return newOrderFuture;
    });
  }
640515
public GetSessionResponse getSession(GetSessionRequest request) {
        checkNotNull(request, "The parameter request should NOT be null.");
        checkStringNotEmpty(request.getSessionId(), "The parameter sessionId should NOT be null or empty string.");
        InternalRequest internalRequest = createRequest(HttpMethodName.GET, request, LIVE_SESSION,
                request.getSessionId());
        return invokeHttpClient(internalRequest, GetSessionResponse.class);
    }
877872
@Override
	public void serviceRequest(final Request request) {

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

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

		// Match (first time, both are zero)
		// or no Step count and processing a GET
		if (expected == got || (!StepCountUtil.isStepOnRequest(request) && "GET".equals(request.
				getMethod()))) {
			// Process Service Request
			getBackingComponent().serviceRequest(request);
		} else { // Invalid step
			LOG.warn(
					"SERVER: Wrong step detected. Expected step " + expected + " but got step " + got);

			// Redirect to error page
			if (StepCountUtil.isErrorRedirect()) {
				String url = StepCountUtil.getErrorUrl();
				LOG.warn("User will be redirected to an error page. URL: " + url);
				try {
					getResponse().sendRedirect(url);
				} catch (IOException e) {
					LOG.warn("Error trying to redirect for wrong step indicator.");
				}

				// Make sure the render phase is not processed
				throw new ActionEscape();
			} else {  // Warp to the future
				// Call handle step error
				WComponent application = getUI();
				if (application instanceof WApplication) {
					LOG.warn("The handleStepError method will be called on WApplication.");
					((WApplication) application).handleStepError();
				}

				LOG.warn("The render phase will warp the user back to the future.");
			}
		}
	}