Sso status response entity.

@param request the request
@return the response entity
162800
@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity ssoStatus(final HttpServletRequest request) {
        val tgtId = this.ticketGrantingTicketCookieGenerator.retrieveCookieValue(request);
        if (StringUtils.isNotBlank(tgtId)) {
            val auth = this.ticketRegistrySupport.getAuthenticationFrom(tgtId);
            if (auth != null) {
                val ticketState = this.ticketRegistrySupport.getTicketState(tgtId);
                val body = CollectionUtils.wrap("principal", auth.getPrincipal().getId(),
                    "authenticationDate", auth.getAuthenticationDate(),
                    "ticketGrantingTicketCreationTime", ticketState.getCreationTime(),
                    "ticketGrantingTicketPreviousTimeUsed", ticketState.getPreviousTimeUsed(),
                    "ticketGrantingTicketLastTimeUsed", ticketState.getLastTimeUsed());
                return ResponseEntity.ok(body);
            }
        }
        return ResponseEntity.badRequest().build();
    }
1337058
public EnableDomainResponse enableDomain(EnableDomainRequest request) {
        checkNotNull(request, "The parameter request should NOT be null.");
        InternalRequest internalRequest = createRequest(request, HttpMethodName.POST, DOMAIN, request.getDomain());
        internalRequest.addParameter("enable", "");
        return invokeHttpClient(internalRequest, EnableDomainResponse.class);
    }
1006538
protected Response getResponse(HttpEntity entity, RequestBuilder req) {
        CloseableHttpClient client = getClient();
        initHeaders(req);
        req.setEntity(entity);
        CloseableHttpResponse resp = null;
        Response response = null;
        try {
            final HttpUriRequest uriRequest = req.build();
            resp = client.execute(uriRequest);
            response = new Response(resp);
            response.setMethod(Methods.POST.getMethod());
            response.setRequestLine(uriRequest.getRequestLine().toString());
        } catch (Exception e) {
            // TODO: log the error
            e.printStackTrace();
        } finally {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return response;
    }
592739
public GetStatUvResponse getStatUv(GetStatUvRequest request) {
        InternalRequest internalRequest = this.createRequest(request, HttpMethodName.GET, STAT, "uv");
        
        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, GetStatUvResponse.class);
    }
1332819
protected byte[] getBinaryRequestPayload(SignableRequest<?> request) {
        if (SdkHttpUtils.usePayloadForQueryParameters(request)) {
            String encodedParameters = SdkHttpUtils.encodeParameters(request);
            if (encodedParameters == null)
                return new byte[0];

            return encodedParameters.getBytes(UTF8);
        }

        return getBinaryRequestPayloadWithoutQueryParams(request);
    }
212027
public Credential getSingleSignOn(HttpRequest request,
                                      HttpResponse response)
    {
        if (_ssoRealm!=null)
            return _ssoRealm.getSingleSignOn(request,response);
        return null;
    }
636164
public ListDomainStatisticsResponse listDomainStatistics(ListDomainStatisticsRequest request) {
        checkNotNull(request, "The parameter request should NOT be null.");

        checkStringNotEmpty(request.getStartTime(), "startTime should NOT be empty");

        InternalRequest internalRequest = createRequest(HttpMethodName.GET, request,
                STATISTICS, LIVE_DOMAIN, "list");
        internalRequest.addParameter("startTime", request.getStartTime());
        if (request.getEndTime() != null) {
            internalRequest.addParameter("endTime", request.getEndTime());
        }
        if (request.getKeyword() != null) {
            internalRequest.addParameter("keyword", request.getKeyword());
        }
        if (request.getKeywordType() != null) {
            internalRequest.addParameter("keywordType", request.getKeywordType());
        }
        if (request.getOrderBy() != null) {
            internalRequest.addParameter("orderBy", request.getOrderBy());
        }
        return invokeHttpClient(internalRequest, ListDomainStatisticsResponse.class);
    }
1019164
public Response makeRequest(final Request request) {

        HttpMethod method = request.getMethod();
        RequestBuilder builder = RequestBuilder.create(method.toString())
            .setUri(request.constructURL().toString())
            .setVersion(HttpVersion.HTTP_1_1)
            .setCharset(StandardCharsets.UTF_8);

        if (request.requiresAuthentication()) {
            builder.addHeader(HttpHeaders.AUTHORIZATION, request.getAuthString());
        }

        if (method == HttpMethod.POST) {
            builder.addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");

            for (Map.Entry<String, List<String>> entry : request.getPostParams().entrySet()) {
                for (String value : entry.getValue()) {
                    builder.addParameter(entry.getKey(), value);
                }
            }
        }

        HttpResponse response = null;

        try {
            response = client.execute(builder.build());
            HttpEntity entity = response.getEntity();
            return new Response(
                // Consume the entire HTTP response before returning the stream
                entity == null ? null : new BufferedHttpEntity(entity).getContent(),
                response.getStatusLine().getStatusCode()
            );
        } catch (IOException e) {
            throw new ApiException(e.getMessage(), e);
        } finally {

            // Ensure this response is properly closed
            HttpClientUtils.closeQuietly(response);

        }

    }
61028
@RequestMapping(value = "/userSession", method = RequestMethod.GET)
    @ResponseBody
    public JsonObject<?> session(HttpServletRequest request) {
        JsonObject<?> ret = JsonObject.create();
        String cookieValueUsername = CookieUtils.getCookieValue(request,
                UserWebConstant.CookieKey.USERNAME.getValue());
        String cookieValuePwd = CookieUtils.getCookieValue(request,
                UserWebConstant.CookieKey.PWDMD5.getValue());
        if (LoginValidator.isValid(cookieValueUsername, cookieValuePwd)) {
            LOG.info("Already logon with username=" + cookieValueUsername);
            ret.addData("id", UserWebConstant.USERMAP.get(cookieValueUsername).getUserId());
            ret.addData("name", cookieValueUsername);
            return ret;
        } else {
            ret.setStatus(GlobalResponseStatusMsg.NOT_LOGIN.getCode());
            ret.addStatusInfo(GlobalResponseStatusMsg.NOT_LOGIN.getMessage().getMessage());
        }

        return ret;
    }
284878
protected Response executeRequest(Request request)
    {
        try
        {
            com.squareup.okhttp.Request httpRequest = buildHttpRequest(request);

            if(logger.isInfoEnabled())
                logger.info("Sending request: {} {}",httpRequest.method(),httpRequest.urlString());

            if(logger.isDebugEnabled() && request.getRequestMethod().isBodyRequest())
            {
                Buffer buffer = new Buffer();
                httpRequest.body().writeTo(buffer);
                if(maxLoggedBodySize == -1 || buffer.size() <= maxLoggedBodySize )
                    logger.debug("Request body: {}", buffer.readUtf8());
                else
                    logger.debug("Request body not captured: too large. ");
            }

            if(logger.isTraceEnabled())
                logger.trace("Request headers: {}",httpRequest.headers().toString());

            Response response = client.newCall(httpRequest).execute();

            if(response.code() == HttpURLConnection.HTTP_UNAUTHORIZED && authorizationFactory != null
                    && authorizationFactory.retryOnAuthenticationError())
            {
                if(authorizationFactory instanceof ResettableAuthorizationFactory)
                    ((ResettableAuthorizationFactory) authorizationFactory).reset();

                response = client.newCall(httpRequest).execute();
            }

            logger.info("Response code: {}",response.code());

            if(logger.isTraceEnabled())
                logger.trace("Response headers: {}",response.headers().toString());

            if(logger.isDebugEnabled())
            {
                ByteArrayOutputStream copy = new ByteArrayOutputStream();
                copy(response.body().byteStream(),copy);
                response = response.newBuilder().body(ResponseBody.create(response.body().contentType(),copy.toByteArray())).build();

                if(maxLoggedBodySize == -1 || copy.size() <= maxLoggedBodySize)
                    logger.debug("Response body: {}",copy.toString());
                else
                    logger.debug("Response body not captured: too large.");
            }
            if (response.code() >= HttpURLConnection.HTTP_BAD_REQUEST)
            {
                throw readException(response);
            }

            return response;
        }
        catch (IOException e)
        {
            throw new ClientConnectionException("Error calling service.",e);
        }

    }
441388
public EngineResult engineResult(HttpRequestBase request) {
        EngineResult engineResult = new EngineResult();
        try {
            HttpResponse response = httpClient.execute(request);
            if (response != null) {
                engineResult.responseCode = response.getStatusLine().getStatusCode();
                HttpEntity responseEntity = response.getEntity();
                long contentLength = responseEntity.getContentLength();
                if (contentLength < 0) {
                    contentLength = 0;
                }
                ByteArrayOutputStream bOut = new ByteArrayOutputStream((int) contentLength);
                InputStream in = responseEntity.getContent();
                int read;
                byte[] tmpBuf = new byte[8192];
                while ((read = in.read(tmpBuf)) != -1) {
                    bOut.write(tmpBuf, 0, read);
                }
                in.close();
                bOut.close();
                engineResult.response = bOut.toByteArray();
                switch (engineResult.responseCode) {
                case 200:
                    engineResult.parse(xmlValidator);
                    in = new ByteArrayInputStream(engineResult.response);
                    engineResult.engine = Engine.unmarshall(in);
                    in.close();
                    engineResult.status = ResultStatus.OK;
                    break;
                case 404:
                    engineResult.status = ResultStatus.NOT_FOUND;
                    break;
                case 500:
                    engineResult.status = ResultStatus.INTERNAL_ERROR;
                    break;
                default:
                    engineResult.status = ResultStatus.NO_RESPONSE;
                    break;
                }
            } else {
                engineResult.status = ResultStatus.NO_RESPONSE;
            }
        } catch (NoHttpResponseException e) {
            engineResult.status = ResultStatus.OFFLINE;
            engineResult.t = e;
        } catch (ClientProtocolException e) {
            engineResult.status = ResultStatus.RESPONSE_EXCEPTION;
            engineResult.t = e;
        } catch (IOException e) {
            engineResult.status = ResultStatus.RESPONSE_EXCEPTION;
            engineResult.t = e;
        } catch (JAXBException e) {
            engineResult.status = ResultStatus.JAXB_EXCEPTION;
            engineResult.t = e;
        } catch (XMLStreamException e) {
            engineResult.status = ResultStatus.XML_EXCEPTION;
            engineResult.t = e;
        }
        return engineResult;
    }
1239712
public static String getHttpServletRequestUserAgent(final HttpServletRequest request) {
        if (request != null) {
            return request.getHeader(USER_AGENT_HEADER);
        }
        return null;
    }
988877
protected void sendClientResponse(PendingOpsRequest request) {
        byte statusCode = ClientResponse.SUCCESS;
        String statusString = null;
        /*
         * It is possible not to receive a table response if a feature is not enabled
         */
        // All of the null/empty table handling/detecting/generation sucks.  Just making it
        // work for now, not making it pretty. --izzy
        VoltTable responseTables[] = request.aggregateTables;
        if (responseTables == null || responseTables.length == 0) {
            responseTables = new VoltTable[0];
            statusCode = ClientResponse.GRACEFUL_FAILURE;
            statusString =
                "Requested info \"" + request.subselector +
                "\" is not yet available or not supported in the current configuration.";
        }

        ClientResponseImpl response =
            new ClientResponseImpl(statusCode, ClientResponse.UNINITIALIZED_APP_STATUS_CODE, null,
                    responseTables, statusString);
        response.setClientHandle(request.clientData);
        ByteBuffer buf = ByteBuffer.allocate(response.getSerializedSize() + 4);
        buf.putInt(buf.capacity() - 4);
        response.flattenToBuffer(buf).flip();
        request.c.writeStream().enqueue(buf);
    }
495459
public function getEntity(Request $request)
    {
        $response = $this->send($request);
        $entity_class = $request->getEntityClass();
        return $entity_class::fromResponse($response);
    }
162779
public GetDomainStatisticsResponse getDomainStatistics(GetDomainStatisticsRequest request) {
        checkNotNull(request, "The parameter request should NOT be null.");

        checkStringNotEmpty(request.getDomain(), "Domain should NOT be empty.");
        InternalRequest internalRequest = createRequest(HttpMethodName.GET, request, STATISTICS,
                LIVE_DOMAIN, request.getDomain());
        if (request.getStartDate() != null) {
            internalRequest.addParameter("startDate", request.getStartDate());
        }
        if (request.getEndDate() != null) {
            internalRequest.addParameter("endDate", request.getEndDate());
        }
        if (request.getAggregate() != null) {
            internalRequest.addParameter("aggregate", request.getAggregate().toString());
        }
        return invokeHttpClient(internalRequest, GetDomainStatisticsResponse.class);
    }
292387
protected String getEntityIdFromRequest(final RequestContext requestContext) {
        val request = WebUtils.getHttpServletRequestFromExternalWebflowContext(requestContext);
        return request.getParameter(this.entityIdParameterName);
    }
779258
@VisibleForTesting
	static String doExtractResponse(int statusCode, HttpEntity entity) {
		String message = null;

		if (entity != null) {
			try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
				entity.writeTo(baos);
				message = baos.toString("UTF-8");
			}
			catch (IOException ex) {
				throw new SystemException(ex);
			}
		}

		//if the response is in the 400 range, use IllegalArgumentException, which currently translates to a 400 error
		if (statusCode>= HttpStatus.SC_BAD_REQUEST && statusCode < HttpStatus.SC_INTERNAL_SERVER_ERROR) {
			throw new IllegalArgumentException("Status code: " + statusCode + " .  Error occurred. " +  message);
		}
		//everything else that's not in the 200 range, use SystemException, which translates to a 500 error.
		if ((statusCode < HttpStatus.SC_OK) || (statusCode >= HttpStatus.SC_MULTIPLE_CHOICES)) {
			throw new SystemException("Status code: " + statusCode + " .  Error occurred. " +  message);
		} else {
			return message;
		}
	}