Determine whether a response should be given in JSON or XML format based on the incoming HttpServletRequest's
<code>"_format"</code> parameter and <code>"Accept:"</code> HTTP header.
974570
public static ResponseEncoding determineResponseEncodingWithDefault(RequestDetails theReq) {
		ResponseEncoding retVal = determineResponseEncodingNoDefault(theReq, theReq.getServer().getDefaultResponseEncoding());
		if (retVal == null) {
			retVal = new ResponseEncoding(theReq.getServer().getFhirContext(), theReq.getServer().getDefaultResponseEncoding(), null);
		}
		return retVal;
	}
818309
public static void checkCharset(String accepts) throws IOException {
        if (accepts == null) {
            // ie7 does not send this header
            return;
        }
        // I've seen both "utf-8" and "UTF-8" -> test case-insensitive
        if (contains(accepts.toLowerCase(), Engine.ENCODING)) {
            return;
        }
        if (contains(accepts, "*")) {
            return;
        }
        throw new IOException(Engine.ENCODING + " encoding is not accepted: " + accepts);
    }
75714
@RequestMapping(method = RequestMethod.POST)
    protected final void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if (isLegal(request)) {
            String result = processRequest(request);
            //设置正确的 content-type 以防止中文乱码
            response.setContentType("text/xml;charset=UTF-8");
            PrintWriter writer = response.getWriter();
            writer.write(result);
            writer.close();
        }
    }
715898
private ContentType getAcceptType() {
        // If the format header is present, it overrides the ACCEPT header.
        String format = m_variableMap.get("format");
        if (format != null) {
            return new ContentType(format);
        }
        String acceptParts = m_request.getHeader(HttpDefs.ACCEPT);
        if (!Utils.isEmpty(acceptParts)) {
	        for (String acceptPart : acceptParts.split(",")) {
	            ContentType acceptType = new ContentType(acceptPart);
	            if (acceptType.isJSON() || acceptType.isXML() || acceptType.isPlainText()) {
	                return acceptType;
	            }
	        }
        }
        return getContentType();
    }
92604
public static HttpServletResponse getEncodingResponse(
            HttpServletResponse response, String charset) {
        response.setCharacterEncoding(charset);
        response.setContentType("text/html;charset=" + charset);
        return response;
    }
529962
@Nullable
    @SuppressWarnings("FloatingPointEquality")
    private static HttpEncodingType determineEncoding(String acceptEncoding) {
        float starQ = -1.0f;
        float gzipQ = -1.0f;
        float deflateQ = -1.0f;
        for (String encoding : acceptEncoding.split(",")) {
            float q = 1.0f;
            final int equalsPos = encoding.indexOf('=');
            if (equalsPos != -1) {
                try {
                    q = Float.parseFloat(encoding.substring(equalsPos + 1));
                } catch (NumberFormatException e) {
                    // Ignore encoding
                    q = 0.0f;
                }
            }
            if (encoding.contains("*")) {
                starQ = q;
            } else if (encoding.contains("gzip") && q > gzipQ) {
                gzipQ = q;
            } else if (encoding.contains("deflate") && q > deflateQ) {
                deflateQ = q;
            }
        }
        if (gzipQ > 0.0f || deflateQ > 0.0f) {
            if (gzipQ >= deflateQ) {
                return HttpEncodingType.GZIP;
            } else {
                return HttpEncodingType.DEFLATE;
            }
        }
        if (starQ > 0.0f) {
            if (gzipQ == -1.0f) {
                return HttpEncodingType.GZIP;
            }
            if (deflateQ == -1.0f) {
                return HttpEncodingType.DEFLATE;
            }
        }
        return null;
    }
44091
public HttpClientResponseBuilder doReturnXML(String response, Charset charset) {
        return responseBuilder.doReturnXML(response, charset);
    }
733468
@Override
    public void doGet(HttpServletRequest request,
            HttpServletResponse response)
            throws IOException, ServletException {
        super.doGet(request, response);
        //jsonp is specified when response is expected to go to javascript function.
        String jsonp = request.getParameter(HTTPClientInterface.JSONP);
        AuthenticationResult authResult = null;
        String target = request.getPathInfo();
        if (target == null) target = "/";
        try {
            response.setContentType(HTTPAdminListener.JSON_CONTENT_TYPE);
            if (!HTTPClientInterface.validateJSONP(jsonp, (Request )request, response)) {
                return;
            }
            response.setStatus(HttpServletResponse.SC_OK);
            authResult = authenticate(request);
            if (!authResult.isAuthenticated()) {
                response.getWriter().print(buildClientResponse(jsonp, ClientResponse.UNEXPECTED_FAILURE, authResult.m_message));
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return;
            }

            if (!target.equals("/")) {
                response.getWriter().print(buildClientResponse(jsonp, ClientResponse.UNEXPECTED_FAILURE, "Resource not found"));
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return;
            }
            if (jsonp != null) {
                response.getWriter().write(jsonp + "(");
            }
            m_mapper.writeValue(response.getWriter(), new Profile(authResult.m_user, authResult.m_perms));
            if (jsonp != null) {
                response.getWriter().write(")");
            }
        } catch (Exception ex) {
            rateLimitedLogWarn("Not servicing url: %s Details: ", target, ex.getMessage());
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().print(buildClientResponse(null, ClientResponse.UNEXPECTED_FAILURE, Throwables.getStackTraceAsString(ex)));
        }
    }
874453
private void checkSerialize(final HttpServletRequest request) {
    String reqpar = request.getParameter("serialize");

    if (reqpar == null) {
      return;
    }

    HttpSession sess = request.getSession(false);
    Enumeration en = sess.getAttributeNames();

    while (en.hasMoreElements()) {
      String attrname = (String)en.nextElement();
      ObjectOutputStream oo = null;

      info("Attempt to serialize attr " + attrname);
      Object o = sess.getAttribute(attrname);

      try {
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        oo = new ObjectOutputStream(bo);
        oo.writeObject(o);
        oo.flush();

        info("Serialized object " + attrname + " has size: " + bo.size());
      } catch (Throwable t) {
        t.printStackTrace();
      } finally {
        if (oo != null) {
          try {
            oo.close();
          } catch (Throwable t) {}
        }
      }
    }
  }
855061
def ensure_json_content_type(req, app):
    
    res = req.get_response(app, catch_exc_info=True)
    res.content_type = 'application/json; charset=utf-8'
    return res
31839
def select_header_accept(self, accepts):
        
        if not accepts:
            return

        accepts = [x.lower() for x in accepts]

        if 'application/json' in accepts:
            return 'application/json'
        else:
            return ', '.join(accepts)
1103402
public static HttpServletResponse getHttpServletResponse(final Response response)
	{
		final WebResponse webResponse = (WebResponse)response;
		final HttpServletResponse httpServletResponse = (HttpServletResponse)webResponse
			.getContainerResponse();
		return httpServletResponse;
	}
1106608
function (response, expectedResponseType) {
            if (expectedResponseType == "text") {
                if (!response.responseText && response.responseJSON != null) {
                    // convert JSON to text
                    if (ariaUtilsType.isString(response.responseJSON)) {
                        // this case is important for JSON-P services which return a simple string
                        // we simply use that string as text
                        // (could be useful to load templates through JSON-P, for example)
                        response.responseText = response.responseJSON;
                    } else {
                        // really convert the JSON structure to a string
                        response.responseText = ariaUtilsJson.convertToJsonString(response.responseJSON);
                    }
                }
            } else if (expectedResponseType == "json") {
                if (response.responseJSON == null && response.responseText != null) {
                    // convert text to JSON
                    var errorMsg = (require("../utils/String")).substitute(this.JSON_PARSING_ERROR, [response.url,
                            response.responseText]);
                    if (response.responseText === "") {
                        var undef;
                        response.responseJSON = undef;
                    } else {
                        response.responseJSON = ariaUtilsJson.load(response.responseText, this, errorMsg);
                    }
                }
            }

        }
1342824
protected boolean passConditionalHeaders(HttpServletRequest request, HttpServletResponse response, Resource resource) throws IOException
    {
        if (!request.getMethod().equals(HttpRequest.__HEAD) && request.getAttribute(Dispatcher.__INCLUDE_REQUEST_URI) == null)
        {
            // If we have meta data for the file
            // Try a direct match for most common requests. Avoids
            // parsing the date.
            ResourceCache.ResourceMetaData metaData = _httpContext.getResourceMetaData(resource);
            if (metaData != null)
            {
                String ifms = request.getHeader(HttpFields.__IfModifiedSince);
                String mdlm = metaData.getLastModified();
                if (ifms != null && mdlm != null && ifms.equals(mdlm))
                {
                    response.reset();
                    response.setStatus(HttpResponse.__304_Not_Modified);
                    response.flushBuffer();
                    return false;
                }
            }

            long date = 0;
            // Parse the if[un]modified dates and compare to resource

            if ((date = request.getDateHeader(HttpFields.__IfUnmodifiedSince)) > 0)
            {
                if (resource.lastModified() / 1000 > date / 1000)
                {
                    response.sendError(HttpResponse.__412_Precondition_Failed);
                    return false;
                }
            }

            if ((date = request.getDateHeader(HttpFields.__IfModifiedSince)) > 0)
            {
                if (resource.lastModified() / 1000 <= date / 1000)
                {
                    response.reset();
                    response.setStatus(HttpResponse.__304_Not_Modified);
                    response.flushBuffer();
                    return false;
                }
            }
        }
        return true;
    }
801409
public static void setHeader(HttpServletResponse response, String name, Object value) {
		if (value instanceof String) {
			response.setHeader(name, (String) value);
		} else if (Date.class.isAssignableFrom(value.getClass())) {
			response.setDateHeader(name, ((Date) value).getTime());
		} else if (value instanceof Integer || "int".equals(value.getClass().getSimpleName().toLowerCase())) {
			response.setIntHeader(name, (Integer) value);
		} else {
			response.setHeader(name, value.toString());
		}
	}
644894
def http_response(self, request):
        '''
        '''
        content_types = request.content_types
        if not content_types or self._content_type in content_types:
            response = request.response
            response.content_type = self._content_type
            response.encoding = self.charset
            response.content = self.to_bytes()
            return response
        else:
            raise HttpException(status=415, msg=request.content_types)
70538
def find_response_format(allowed_response_formats):
    
    # allowed formats default to [] before this
    if not allowed_response_formats:
        allowed_response_formats = [ResponseFormats.JSON]

    content_type = request.headers.get("Accept")
    if content_type is None:
        # Nothing specified, default to endpoint definition
        if allowed_response_formats:
            return allowed_response_formats[0]
        # Finally, default to JSON
        return ResponseFormats.JSON

    for response_format in ResponseFormats.prioritized():
        if response_format not in allowed_response_formats:
            continue
        if response_format.matches(content_type):
            return response_format

    # fallback for previous behavior
    return ResponseFormats.JSON