Example #1
0
  @Override
  public void doRender(Invocation inv) throws Exception {
    if (StringUtils.isEmpty(text)) {
      return;
    }

    if (logger.isDebugEnabled()) {
      logger.debug("trying to render text:" + text);
    }

    HttpServletResponse response = inv.getResponse();
    String oldEncoding = response.getCharacterEncoding();
    if (StringUtils.isBlank(oldEncoding) || oldEncoding.startsWith("ISO-")) {
      String encoding = inv.getRequest().getCharacterEncoding();
      Assert.isTrue(encoding != null);
      response.setCharacterEncoding(encoding);
      if (logger.isDebugEnabled()) {
        logger.debug(
            "set response.characterEncoding by default:" + response.getCharacterEncoding());
      }
    }

    if (response.getContentType() == null) {
      response.setContentType("text/html");
      if (logger.isDebugEnabled()) {
        logger.debug("set response content-type by default: " + response.getContentType());
      }
    }
    sendResponse(response, text);
  }
Example #2
0
 /* 避免中文乱码 */
 private void setContentType(HttpServletResponse res) {
   String contentType = res.getContentType();
   if (Strings.isNullOrEmpty(contentType)) {
     contentType = "text/html; charset=UTF-8";
   }
   final String iso = "iso-8859-1";
   if (!contentType.toLowerCase().contains("charset")) {
     String encoding = res.getCharacterEncoding();
     if (Strings.isNullOrEmpty(encoding) || encoding.toLowerCase().equals(iso)) {
       encoding = "UTF-8";
     }
     contentType += "; charset=" + encoding;
     res.setContentType(contentType);
   } else {
     int pos = contentType.toLowerCase().lastIndexOf(iso);
     if (pos > 0) {
       String mime = contentType.substring(0, pos) + "UTF-8";
       int start = pos + iso.length() + 1;
       if (start < contentType.length()) {
         mime += contentType.substring(start);
       }
       res.setContentType(mime);
     }
   }
 }
  private void setContentType(
      HttpServletResponse response,
      String contentType,
      String encoding,
      boolean contentTypeIsDefault) {

    if (response.getContentType() == null || !contentTypeIsDefault)
      response.setContentType(GrailsWebUtil.getContentType(contentType, encoding));
  }
Example #4
0
  public static boolean isImageResponse(HttpServletResponse response) {

    String responseType = response.getContentType();

    if (responseType != null && responseType.startsWith(AccessConstants.IMAGE_CONTENT_TYPE)) {
      return true;
    } else {
      return false;
    }
  }
Example #5
0
  public void render(HttpServletRequest req, HttpServletResponse resp, Object obj)
      throws IOException {

    if (resp.getContentType() == null)
      if (jsonp) resp.setContentType(JSONP_CT);
      else resp.setContentType(CT);
    Writer writer = resp.getWriter();
    if (jsonp) writer.write(req.getParameter(jsonpParam == null ? "callback" : jsonpParam) + "(");
    Mvcs.write(resp, writer, null == obj ? data : obj, format.clone());
    if (jsonp) writer.write(");");
  }
Example #6
0
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");

    // Get the absolute path of the image ServletContext sc = getServletContext();
    String path = uploadsFolder;
    String filename = request.getParameter("file");
    String size = request.getParameter("size");

    if (size == null) {
      size = "original";
    } else {
      if (size.equals("small")) {
        size = "thumbs";
      } else if (size.equals("medium")) {
        size = "normal";
      }
    }

    String mimeType = getServletContext().getMimeType(filename);

    path = path + filename;
    if (path.contains("/Photos/")) {
      path = path.replaceAll("/Photos/", "/Photos/" + size + "/");
    }

    filename = filename.substring(filename.lastIndexOf("/") + 1);
    // Set content size
    File file = new File(path);
    if (!file.exists()) {
      file = new File(uploadsFolder + "empty_photo.jpg");
      response.setContentType("image/jpeg");
    } else {
      if (response.getContentType() == null) {
        response.setContentType(mimeType + ";charset=UTF-8");
        response.setHeader("Content-disposition", "inline; filename=\"" + filename + "\"");
      }
    }

    response.setContentLength((int) file.length());
    // Open the file and output streams
    FileInputStream in = new FileInputStream(file);
    OutputStream out = response.getOutputStream();

    // Copy the contents of the file to the output stream
    byte[] buf = new byte[1024];
    int count = 0;
    while ((count = in.read(buf)) >= 0) {
      out.write(buf, 0, count);
    }
    in.close();
    out.close();
  }
  protected PageInfo buildPage(
      HttpServletRequest request, HttpServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    // Invoke the next entity in the chain
    SerializableByteArrayOutputStream out = new SerializableByteArrayOutputStream();
    GenericResponseWrapper wrapper = new GenericResponseWrapper(response, out);
    Map<String, Serializable> cacheableRequestAttributes = new HashMap<String, Serializable>();

    // TODO: split the special include handling out into a separate method
    HttpServletResponse originalResponse = null;
    boolean isInclude = WebUtils.isIncludeRequest(request);
    if (isInclude) {
      originalResponse = WrappedResponseHolder.getWrappedResponse();
      WrappedResponseHolder.setWrappedResponse(wrapper);
    }
    try {
      List<String> attributesBefore = toList(request.getAttributeNames());
      chain.doFilter(request, wrapper);
      List<String> attributesAfter = toList(request.getAttributeNames());
      attributesAfter.removeAll(attributesBefore);
      for (String attrName : attributesAfter) {
        Object value = request.getAttribute(attrName);
        if (value instanceof Serializable) {
          cacheableRequestAttributes.put(attrName, (Serializable) value);
        }
      }
    } finally {
      if (isInclude) {
        WrappedResponseHolder.setWrappedResponse(originalResponse);
      }
    }
    wrapper.flush();

    long timeToLiveSeconds =
        Integer
            .MAX_VALUE; // TODO
                        // cacheManager.getEhcache(context.cacheName).cacheConfiguration.timeToLiveSeconds;

    String contentType = wrapper.getContentType();
    if (!StringUtils.hasLength(contentType)) {
      contentType = response.getContentType();
    }

    return new PageInfo(
        wrapper.getStatus(),
        contentType,
        out.toByteArray(),
        false,
        timeToLiveSeconds,
        wrapper.getAllHeaders(),
        wrapper.getCookies(),
        cacheableRequestAttributes);
  }
  /**
   * Delegate TRACE requests to {@link #processRequest}, if desired.
   *
   * <p>Applies HttpServlet's standard TRACE processing otherwise.
   *
   * @see #doService
   */
  @Override
  protected void doTrace(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    if (this.dispatchTraceRequest) {
      processRequest(request, response);
      if ("message/http".equals(response.getContentType())) {
        // Proper TRACE response coming from a handler - we're done.
        return;
      }
    }
    super.doTrace(request, response);
  }
 private void sendFallback(Integer size, HttpServletResponse response) throws IOException {
   if (response.getContentType() == null) {
     response.setContentType(StringUtil.getMimeType("png"));
   }
   InputStream in = null;
   try {
     in = getClass().getResourceAsStream("default_cover.png");
     BufferedImage image = ImageIO.read(in);
     if (size != null) {
       image = scale(image, size, size);
     }
     ImageIO.write(image, "png", response.getOutputStream());
   } finally {
     IOUtils.closeQuietly(in);
   }
 }
  public void serveResource(
      HttpServletRequest request, HttpServletResponse response, Portlet portlet)
      throws PortletContainerException {

    try {
      _doServeResource(request, response, portlet);

      String contentType = response.getContentType();

      if (contentType.equals(ContentTypes.TEXT_HTML)
          || contentType.equals(ContentTypes.TEXT_HTML_UTF8)) {

        AUIUtil.outputScriptData(request, response.getWriter());
      }
    } catch (Exception e) {
      throw new PortletContainerException(e);
    }
  }
Example #11
0
  /** JaggeryMethod responsible of writing to the output stream */
  public static void print(Context cx, Scriptable thisObj, Object[] args, Function funObj)
      throws ScriptException {
    if (!isWebSocket) {
      JaggeryContext jaggeryContext = CommonManager.getJaggeryContext();

      // If the script itself havent set the content type we set the default content type to be
      // text/html
      HttpServletResponse servletResponse =
          (HttpServletResponse) jaggeryContext.getProperty(SERVLET_RESPONSE);
      if (servletResponse.getContentType() == null) {
        servletResponse.setContentType(DEFAULT_CONTENT_TYPE);
      }

      if (servletResponse.getCharacterEncoding() == null) {
        servletResponse.setCharacterEncoding(DEFAULT_CHAR_ENCODING);
      }

      CommonManager.print(cx, thisObj, args, funObj);
    }
  }
 @Override
 public String getContentType() {
   return wrap.getContentType();
 }
 public String getContentType() {
   return response.getContentType();
 }
Example #14
0
 private boolean isJSONResponse(HttpServletResponse response) {
   String contentType = response.getContentType();
   return contentType != null
       && (contentType.indexOf("application/json") > -1 || contentType.indexOf("text/json") > -1);
 }
 @Override
 public synchronized String getContentType() {
   return actualResponse.getContentType();
 }
  // The tck uses only get & post requests
  protected void processTCKReq(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    LOGGER.entering(LOG_CLASS, "servlet entry");

    PortletRequest portletReq = (PortletRequest) request.getAttribute("javax.portlet.request");
    PortletResponse portletResp = (PortletResponse) request.getAttribute("javax.portlet.response");
    PortletConfig portletConfig = (PortletConfig) request.getAttribute("javax.portlet.config");
    long svtTid = Thread.currentThread().getId();
    long reqTid = (Long) portletReq.getAttribute(THREADID_ATTR);

    PrintWriter writer = ((MimeResponse) portletResp).getWriter();

    JSR286DispatcherReqRespTestCaseDetails tcd = new JSR286DispatcherReqRespTestCaseDetails();

    // Create result objects for the tests

    /* TestCase: V2DispatcherReqRespTests4_SPEC2_19_IncludeServletResourceResponse_containsHeader */
    /* Details: "In a target servlet of a include in the Resource phase,    */
    /* the method HttpServletResponse.containsHeader must return false"     */
    TestResult tr0 =
        tcd.getTestResultFailed(
            V2DISPATCHERREQRESPTESTS4_SPEC2_19_INCLUDESERVLETRESOURCERESPONSE_CONTAINSHEADER);
    try {
      boolean ok = response.containsHeader("Accept");
      tr0.setTcSuccess(ok == false);
    } catch (Exception e) {
      tr0.appendTcDetail(e.toString());
    }
    tr0.writeTo(writer);

    /* TestCase: V2DispatcherReqRespTests4_SPEC2_19_IncludeServletResourceResponse_encodeRedirectURL1 */
    /* Details: "In a target servlet of a include in the Resource phase,    */
    /* the method HttpServletResponse.encodeRedirectURL must return null"   */
    TestResult tr1 =
        tcd.getTestResultFailed(
            V2DISPATCHERREQRESPTESTS4_SPEC2_19_INCLUDESERVLETRESOURCERESPONSE_ENCODEREDIRECTURL1);
    try {
      String isval = response.encodeRedirectURL("http://www.cnn.com/");
      CompareUtils.stringsEqual(isval, null, tr1);
    } catch (Exception e) {
      tr1.appendTcDetail(e.toString());
    }
    tr1.writeTo(writer);

    /* TestCase: V2DispatcherReqRespTests4_SPEC2_19_IncludeServletResourceResponse_encodeRedirectUrl */
    /* Details: "In a target servlet of a include in the Resource phase,    */
    /* the method HttpServletResponse.encodeRedirectUrl must return null"   */
    TestResult tr2 =
        tcd.getTestResultFailed(
            V2DISPATCHERREQRESPTESTS4_SPEC2_19_INCLUDESERVLETRESOURCERESPONSE_ENCODEREDIRECTURL);
    try {
      String isval = response.encodeRedirectUrl("http://www.cnn.com/");
      CompareUtils.stringsEqual(isval, null, tr2);
    } catch (Exception e) {
      tr2.appendTcDetail(e.toString());
    }
    tr2.writeTo(writer);

    /* TestCase: V2DispatcherReqRespTests4_SPEC2_19_IncludeServletResourceResponse_encodeURL1 */
    /* Details: "In a target servlet of a include in the Resource phase,    */
    /* the method HttpServletResponse.encodeURL must provide the same       */
    /* functionality as ResourceResponse.encodeURL"                         */
    TestResult tr3 =
        tcd.getTestResultFailed(
            V2DISPATCHERREQRESPTESTS4_SPEC2_19_INCLUDESERVLETRESOURCERESPONSE_ENCODEURL1);
    try {
      String turl = "http://www.apache.org/";
      String hval = (String) response.encodeURL(turl);
      String pval = (String) portletResp.encodeURL(turl);
      CompareUtils.stringsEqual("HttpServletResponse", hval, "ResourceResponse", pval, tr3);
    } catch (Exception e) {
      tr3.appendTcDetail(e.toString());
    }
    tr3.writeTo(writer);

    /* TestCase: V2DispatcherReqRespTests4_SPEC2_19_IncludeServletResourceResponse_encodeUrl */
    /* Details: "In a target servlet of a include in the Resource phase,    */
    /* the method HttpServletResponse.encodeUrl must provide the same       */
    /* functionality as ResourceResponse.encodeURL"                         */
    TestResult tr4 =
        tcd.getTestResultFailed(
            V2DISPATCHERREQRESPTESTS4_SPEC2_19_INCLUDESERVLETRESOURCERESPONSE_ENCODEURL);
    try {
      String turl = "http://www.apache.org/";
      String hval = (String) response.encodeUrl(turl);
      String pval = (String) portletResp.encodeURL(turl);
      CompareUtils.stringsEqual("HttpServletResponse", hval, "ResourceResponse", pval, tr4);
    } catch (Exception e) {
      tr4.appendTcDetail(e.toString());
    }
    tr4.writeTo(writer);

    /* TestCase: V2DispatcherReqRespTests4_SPEC2_19_IncludeServletResourceResponse_getBufferSize */
    /* Details: "In a target servlet of a include in the Resource phase,    */
    /* the method HttpServletResponse.getBufferSize must provide the same   */
    /* functionality as ResourceResponse.getBufferSize"                     */
    TestResult tr5 =
        tcd.getTestResultFailed(
            V2DISPATCHERREQRESPTESTS4_SPEC2_19_INCLUDESERVLETRESOURCERESPONSE_GETBUFFERSIZE);
    try {
      int hval = response.getBufferSize();
      int pval = ((ResourceResponse) portletResp).getBufferSize();
      String str =
          "Value "
              + hval
              + " from "
              + "HttpServletResponse"
              + " does not equal value "
              + pval
              + " + ResourceResponse";
      if (hval != pval) {
        tr5.appendTcDetail(str);
      }
      tr5.setTcSuccess(hval == pval);
    } catch (Exception e) {
      tr5.appendTcDetail(e.toString());
    }
    tr5.writeTo(writer);

    /* TestCase: V2DispatcherReqRespTests4_SPEC2_19_IncludeServletResourceResponse_getCharacterEncoding */
    /* Details: "In a target servlet of a include in the Resource phase,    */
    /* the method HttpServletResponse.getCharacterEncoding must provide     */
    /* the same functionality as ResourceResponse.getCharacterEncoding"     */
    TestResult tr6 =
        tcd.getTestResultFailed(
            V2DISPATCHERREQRESPTESTS4_SPEC2_19_INCLUDESERVLETRESOURCERESPONSE_GETCHARACTERENCODING);
    try {
      String hval = response.getCharacterEncoding();
      String pval = ((ResourceResponse) portletResp).getCharacterEncoding();
      CompareUtils.stringsEqual("HttpServletResponse", hval, "ResourceResponse", pval, tr6);
    } catch (Exception e) {
      tr6.appendTcDetail(e.toString());
    }
    tr6.writeTo(writer);

    /* TestCase: V2DispatcherReqRespTests4_SPEC2_19_IncludeServletResourceResponse_getContentType */
    /* Details: "In a target servlet of a include in the Resource phase,    */
    /* the method HttpServletResponse.getContentType must provide the       */
    /* same functionality as ResourceResponse.getContentType"               */
    TestResult tr7 =
        tcd.getTestResultFailed(
            V2DISPATCHERREQRESPTESTS4_SPEC2_19_INCLUDESERVLETRESOURCERESPONSE_GETCONTENTTYPE);
    try {
      String hval = response.getContentType();
      String pval = ((ResourceResponse) portletResp).getContentType();
      CompareUtils.stringsEqual("HttpServletResponse", hval, "ResourceResponse", pval, tr7);
    } catch (Exception e) {
      tr7.appendTcDetail(e.toString());
    }
    tr7.writeTo(writer);

    /* TestCase: V2DispatcherReqRespTests4_SPEC2_19_IncludeServletResourceResponse_getLocale */
    /* Details: "In a target servlet of a include in the Resource phase,    */
    /* the method HttpServletResponse.getLocale must provide the same       */
    /* functionality as ResourceResponse.getLocale"                         */
    TestResult tr8 =
        tcd.getTestResultFailed(
            V2DISPATCHERREQRESPTESTS4_SPEC2_19_INCLUDESERVLETRESOURCERESPONSE_GETLOCALE);
    try {
      Locale hl = response.getLocale();
      Locale pl = ((MimeResponse) portletResp).getLocale();
      String hval = hl.getDisplayName();
      String pval = pl.getDisplayName();
      CompareUtils.stringsEqual("HttpServletResponse", hval, "ResourceResponse", pval, tr8);
    } catch (Exception e) {
      tr8.appendTcDetail(e.toString());
    }
    tr8.writeTo(writer);

    /* TestCase: V2DispatcherReqRespTests4_SPEC2_19_IncludeServletResourceResponse_isCommitted */
    /* Details: "In a target servlet of a include in the Resource phase,    */
    /* the method HttpServletResponse.isCommitted must provide the same     */
    /* functionality as ResourceResponse.isCommitted"                       */
    TestResult tr9 =
        tcd.getTestResultFailed(
            V2DISPATCHERREQRESPTESTS4_SPEC2_19_INCLUDESERVLETRESOURCERESPONSE_ISCOMMITTED);
    try {
      boolean hval = response.isCommitted();
      boolean pval = ((ResourceResponse) portletResp).isCommitted();
      String str =
          "Value "
              + hval
              + " from "
              + "HttpServletResponse"
              + " does not equal value "
              + pval
              + " + ResourceResponse";
      if (hval != pval) {
        tr9.appendTcDetail(str);
      }
      tr9.setTcSuccess(hval == pval);
    } catch (Exception e) {
      tr9.appendTcDetail(e.toString());
    }
    tr9.writeTo(writer);
  }
 private void detectContentTypeFromPage(Content page, HttpServletResponse response) {
   String contentType = page.getProperty("meta.http-equiv.Content-Type");
   if (contentType != null && "text/html".equals(response.getContentType())) {
     response.setContentType(contentType);
   }
 }
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    HeaderCacheServletResponse headerCacheServletResponse = null;

    if (response instanceof HeaderCacheServletResponse) {
      headerCacheServletResponse = (HeaderCacheServletResponse) response;
    } else {
      headerCacheServletResponse = new HeaderCacheServletResponse(response);
    }

    ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);

    Layout layout = themeDisplay.getLayout();

    Boolean layoutDefault = (Boolean) request.getAttribute(WebKeys.LAYOUT_DEFAULT);

    if ((layoutDefault != null) && (layoutDefault.booleanValue())) {
      Layout requestedLayout = (Layout) request.getAttribute(WebKeys.REQUESTED_LAYOUT);

      if (requestedLayout != null) {
        String redirectParam = "redirect";

        if (Validator.isNotNull(PropsValues.AUTH_LOGIN_PORTLET_NAME)) {
          redirectParam =
              PortalUtil.getPortletNamespace(PropsValues.AUTH_LOGIN_PORTLET_NAME) + redirectParam;
        }

        String authLoginURL = null;

        if (PrefsPropsUtil.getBoolean(
            themeDisplay.getCompanyId(),
            PropsKeys.CAS_AUTH_ENABLED,
            PropsValues.CAS_AUTH_ENABLED)) {

          authLoginURL = themeDisplay.getURLSignIn();
        }

        if (Validator.isNull(authLoginURL)) {
          authLoginURL = PortalUtil.getCommunityLoginURL(themeDisplay);
        }

        if (Validator.isNull(authLoginURL)) {
          authLoginURL = PropsValues.AUTH_LOGIN_URL;
        }

        if (Validator.isNull(authLoginURL)) {
          PortletURL loginURL = LoginUtil.getLoginURL(request, themeDisplay.getPlid());

          authLoginURL = loginURL.toString();
        }

        String currentURL = PortalUtil.getCurrentURL(request);

        authLoginURL = HttpUtil.setParameter(authLoginURL, redirectParam, currentURL);

        if (_log.isDebugEnabled()) {
          _log.debug("Redirect requested layout to " + authLoginURL);
        }

        headerCacheServletResponse.sendRedirect(authLoginURL);
      } else {
        String redirect = PortalUtil.getLayoutURL(layout, themeDisplay);

        if (_log.isDebugEnabled()) {
          _log.debug("Redirect default layout to " + redirect);
        }

        headerCacheServletResponse.sendRedirect(redirect);
      }

      return null;
    }

    long plid = ParamUtil.getLong(request, "p_l_id");

    if (_log.isDebugEnabled()) {
      _log.debug("p_l_id is " + plid);
    }

    if (plid > 0) {
      ActionForward actionForward =
          processLayout(mapping, request, headerCacheServletResponse, plid);

      String contentType = response.getContentType();

      CacheResponseUtil.setHeaders(response, headerCacheServletResponse.getHeaders());

      if (contentType != null) {
        response.setContentType(contentType);
      }

      return actionForward;
    } else {
      try {
        forwardLayout(request);

        return mapping.findForward(ActionConstants.COMMON_FORWARD_JSP);
      } catch (Exception e) {
        PortalUtil.sendError(e, request, headerCacheServletResponse);

        CacheResponseUtil.setHeaders(response, headerCacheServletResponse.getHeaders());

        return null;
      }
    }
  }
  /**
   * Don't know if this check is correct...
   *
   * @param response
   * @return
   */
  private boolean needsUtf8Encoding(HttpServletResponse response) {
    String contentType = response.getContentType();

    return contentType != null ? contentType.endsWith("/json") : false;
  }
  /**
   * This method renders the given request URI using the Sling request processing and stores the
   * result at the request's location relative to the cache root folder. The request is processed in
   * the context of the given user's session.
   *
   * @param uri The request URI including selectors and extensions
   * @param configCacheRoot The cache root folder
   * @param admin The admin session used to store the result in the cache
   * @param session The user's session
   * @return <code>true</code> if the cache was updated
   */
  protected boolean renderResource(
      String uri, String configCacheRoot, Session admin, Session session)
      throws RepositoryException, ServletException, IOException {
    String cachePath = configCacheRoot + getTargetPath(uri);

    ResourceResolver resolver = null;
    try {
      resolver = createResolver(session.getUserID());

      // render resource
      ByteArrayOutputStream out = new ByteArrayOutputStream();
      HttpServletRequest request = createRequest(uri);
      HttpServletResponse response = requestResponseFactory.createResponse(out);

      slingServlet.processRequest(request, response, resolver);
      response.getWriter().flush();

      // compare md5 checksum with cache
      String md5 = requestResponseFactory.getMD5(response);
      String md5Path = cachePath + "/" + JcrConstants.JCR_CONTENT + "/" + MD5_HASH_PROPERTY;

      if (!admin.propertyExists(md5Path) || !admin.getProperty(md5Path).getString().equals(md5)) {
        log.info("MD5 hash missing or not equal, updating content sync cache: {}", cachePath);

        JcrUtil.createPath(cachePath, "sling:Folder", "nt:file", admin, false);

        Node cacheContentNode =
            JcrUtil.createPath(cachePath + "/jcr:content", "nt:resource", admin);
        if (needsUtf8Encoding(response)) {
          cacheContentNode.setProperty(
              JcrConstants.JCR_DATA,
              admin
                  .getValueFactory()
                  .createBinary(
                      IOUtils.toInputStream(out.toString(response.getCharacterEncoding()))));
        } else {
          cacheContentNode.setProperty(
              JcrConstants.JCR_DATA,
              admin.getValueFactory().createBinary(new ByteArrayInputStream(out.toByteArray())));
        }
        cacheContentNode.setProperty(JcrConstants.JCR_LASTMODIFIED, Calendar.getInstance());
        if (response.getContentType() != null) {
          cacheContentNode.setProperty(JcrConstants.JCR_MIMETYPE, response.getContentType());
        }
        if (response.getCharacterEncoding() != null) {
          cacheContentNode.setProperty(JcrConstants.JCR_ENCODING, response.getCharacterEncoding());
        }

        cacheContentNode.addMixin(NT_MD5_HASH);
        cacheContentNode.setProperty(MD5_HASH_PROPERTY, md5);

        admin.save();

        return true;
      } else {
        log.info("Skipping update of content sync cache: {}", uri);

        return false;
      }
    } catch (LoginException e) {
      log.error("Creating resource resolver for resource rendering failed: ", e);
      return false;
    } finally {
      if (resolver != null) {
        resolver.close();
      }

      if (admin.hasPendingChanges()) {
        admin.refresh(false);
      }
    }
  }
Example #21
0
  /**
   * Executes the {@link HttpMethod} passed in and sends the proxy response back to the client via
   * the given {@link HttpServletResponse}.
   *
   * @param httpMethodProxyRequest An object representing the proxy request to be made
   * @param httpServletResponse An object by which we can send the proxied response back to the
   *     client
   * @throws IOException Can be thrown by the {@link HttpClient}.executeMethod
   * @throws ServletException Can be thrown to indicate that another error has occurred
   */
  private void executeProxyRequest(
      HttpMethod httpMethodProxyRequest,
      HttpServletRequest httpServletRequest,
      HttpServletResponse httpServletResponse)
      throws IOException, ServletException {
    // Create a default HttpClient
    HttpClient httpClient;
    httpClient = createClientWithLogin();
    httpMethodProxyRequest.setFollowRedirects(false);

    // Execute the request
    int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest);
    //        String response = httpMethodProxyRequest.getResponseBodyAsString();

    // Check if the proxy response is a redirect
    // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect
    // Hooray for open source software
    if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */
        && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) {
      String stringStatusCode = Integer.toString(intProxyResponseCode);
      String stringLocation = httpMethodProxyRequest.getResponseHeader(HEADER_LOCATION).getValue();
      if (stringLocation == null) {
        throw new ServletException(
            "Received status code: "
                + stringStatusCode
                + " but no "
                + HEADER_LOCATION
                + " header was found in the response");
      }
      // Modify the redirect to go to this proxy servlet rather that the proxied host
      String stringMyHostName = httpServletRequest.getServerName();
      if (httpServletRequest.getServerPort() != 80) {
        stringMyHostName += ":" + httpServletRequest.getServerPort();
      }
      stringMyHostName += httpServletRequest.getContextPath();
      if (followRedirects) {
        httpServletResponse.sendRedirect(
            stringLocation.replace(getProxyHostAndPort() + proxyPath, stringMyHostName));
        return;
      }
    } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) {
      // 304 needs special handling. See:
      // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
      // We get a 304 whenever passed an 'If-Modified-Since'
      // header and the data on disk has not changed; server
      // responds w/ a 304 saying I'm not going to send the
      // body because the file has not changed.
      httpServletResponse.setIntHeader(HEADER_CONTENT_LENGTH, 0);
      httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
      return;
    }

    // Pass the response code back to the client
    httpServletResponse.setStatus(intProxyResponseCode);

    // Pass response headers back to the client
    Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders();
    for (Header header : headerArrayResponse) {
      if (header.getName().equals("Transfer-Encoding") && header.getValue().equals("chunked")
          || header.getName().equals("Content-Encoding") && header.getValue().equals("gzip")) {
        // proxy servlet does not support chunked encoding
      } else {
        httpServletResponse.setHeader(header.getName(), header.getValue());
      }
    }

    List<Header> responseHeaders = Arrays.asList(headerArrayResponse);

    // FIXME We should handle both String and bytes response in the same way:
    String response = null;
    byte[] bodyBytes = null;

    if (isBodyParameterGzipped(responseHeaders)) {
      LOGGER.trace("GZipped: true");
      if (!followRedirects && intProxyResponseCode == HttpServletResponse.SC_MOVED_TEMPORARILY) {
        response = httpMethodProxyRequest.getResponseHeader(HEADER_LOCATION).getValue();
        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        intProxyResponseCode = HttpServletResponse.SC_OK;
        httpServletResponse.setHeader(HEADER_LOCATION, response);
        httpServletResponse.setContentLength(response.length());
      } else {
        bodyBytes = ungzip(httpMethodProxyRequest.getResponseBody());
        httpServletResponse.setContentLength(bodyBytes.length);
      }
    }

    if (httpServletResponse.getContentType() != null
        && httpServletResponse.getContentType().contains("text")) {
      LOGGER.trace("Received status code: {} Response: {}", intProxyResponseCode, response);
    } else {
      LOGGER.trace("Received status code: {} [Response is not textual]", intProxyResponseCode);
    }

    // Send the content to the client
    if (response != null) {
      httpServletResponse.getWriter().write(response);
    } else if (bodyBytes != null) {
      httpServletResponse.getOutputStream().write(bodyBytes);
    } else {
      IOUtils.copy(
          httpMethodProxyRequest.getResponseBodyAsStream(), httpServletResponse.getOutputStream());
    }
  }