// Set an appropriate CORS header if requested and if allowed
 private void setCorsHeader(HttpServletRequest pReq, HttpServletResponse pResp) {
   String origin = requestHandler.extractCorsOrigin(pReq.getHeader("Origin"));
   if (origin != null) {
     pResp.setHeader("Access-Control-Allow-Origin", origin);
     pResp.setHeader("Access-Control-Allow-Credentials", "true");
   }
 }
 private void sendResponse(HttpServletResponse pResp, String pContentType, String pJsonTxt)
     throws IOException {
   setContentType(pResp, pContentType);
   pResp.setStatus(200);
   setNoCacheHeaders(pResp);
   PrintWriter writer = pResp.getWriter();
   writer.write(pJsonTxt);
 }
 private void setContentType(HttpServletResponse pResp, String pContentType) {
   boolean encodingDone = false;
   try {
     pResp.setCharacterEncoding("utf-8");
     pResp.setContentType(pContentType);
     encodingDone = true;
   } catch (NoSuchMethodError error) {
     /* Servlet 2.3 */
   } catch (UnsupportedOperationException error) {
     /* Equinox HTTP Service */
   }
   if (!encodingDone) {
     // For a Servlet 2.3 container or an Equinox HTTP Service, set the charset by hand
     pResp.setContentType(pContentType + "; charset=utf-8");
   }
 }
 /**
  * OPTION requests are treated as CORS preflight requests
  *
  * @param req the original request
  * @param resp the response the answer are written to
  */
 @Override
 protected void doOptions(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
   Map<String, String> responseHeaders =
       requestHandler.handleCorsPreflightRequest(
           req.getHeader("Origin"), req.getHeader("Access-Control-Request-Headers"));
   for (Map.Entry<String, String> entry : responseHeaders.entrySet()) {
     resp.setHeader(entry.getKey(), entry.getValue());
   }
 }
  private void setNoCacheHeaders(HttpServletResponse pResp) {
    pResp.setHeader("Cache-Control", "no-cache");
    pResp.setHeader("Pragma", "no-cache");
    // Check for a date header and set it accordingly to the recommendations of
    // RFC-2616 (http://tools.ietf.org/html/rfc2616#section-14.21)
    //
    //   "To mark a response as "already expired," an origin server sends an
    //    Expires date that is equal to the Date header value. (See the rules
    //  for expiration calculations in section 13.2.4.)"
    //
    // See also #71

    long now = System.currentTimeMillis();
    pResp.setDateHeader("Date", now);
    // 1h  in the past since it seems, that some servlet set the date header on their
    // own so that it cannot be guaranteed that these headers are really equals.
    // It happened on Tomcat that Date: was finally set *before* Expires: in the final
    // answers some times which seems to be an implementation peculiarity from Tomcat
    pResp.setDateHeader("Expires", now - 3600000);
  }