protected void writeImage(Image image, HttpServletRequest request, HttpServletResponse response) {

    if (image == null) {
      return;
    }

    String contentType = null;

    String type = image.getType();

    if (!type.equals(ImageConstants.TYPE_NOT_AVAILABLE)) {
      contentType = MimeTypesUtil.getContentType("A." + type);

      response.setContentType(contentType);
    }

    String fileName = ParamUtil.getString(request, "fileName");

    try {
      byte[] bytes = getImageBytes(request, image);

      if (Validator.isNotNull(fileName)) {
        ServletResponseUtil.sendFile(request, response, fileName, bytes, contentType);
      } else {
        ServletResponseUtil.write(response, bytes);
      }
    } catch (Exception e) {
      if (_log.isWarnEnabled()) {
        _log.warn(e, e);
      }
    }
  }
  @Override
  public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse) {

    try {
      ThemeDisplay themeDisplay =
          (ThemeDisplay) resourceRequest.getAttribute(WebKeys.THEME_DISPLAY);

      if (!MentionsUtil.isMentionsEnabled(themeDisplay.getSiteGroupId())) {

        return;
      }

      HttpServletRequest request = PortalUtil.getHttpServletRequest(resourceRequest);

      JSONArray jsonArray = getJSONArray(request);

      HttpServletResponse response = PortalUtil.getHttpServletResponse(resourceResponse);

      response.setContentType(ContentTypes.APPLICATION_JSON);

      ServletResponseUtil.write(response, jsonArray.toString());
    } catch (Exception e) {
      _log.error(e, e);
    }

    return;
  }
  protected void remoteProcessAction(ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

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

    OAuthRequest oAuthRequest = new OAuthRequest(Verb.POST, getServerPortletURL());

    setRequestParameters(actionRequest, actionResponse, oAuthRequest);

    addOAuthParameter(oAuthRequest, "p_p_lifecycle", "1");
    addOAuthParameter(oAuthRequest, "p_p_state", WindowState.NORMAL.toString());

    Response response = getResponse(themeDisplay.getUser(), oAuthRequest);

    if (response.getCode() == HttpServletResponse.SC_FOUND) {
      String redirectLocation = response.getHeader(HttpHeaders.LOCATION);

      actionResponse.sendRedirect(redirectLocation);
    } else {
      HttpServletResponse httpServletResponse = PortalUtil.getHttpServletResponse(actionResponse);

      httpServletResponse.setContentType(response.getHeader(HttpHeaders.CONTENT_TYPE));

      ServletResponseUtil.write(httpServletResponse, response.getStream());
    }
  }
  @Override
  protected void processFilter(
      HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
      throws Exception {

    Object parsedContent = getDynamicContent(request, response, filterChain);

    if (parsedContent == null) {
      processFilter(DynamicCSSFilter.class, request, response, filterChain);
    } else {
      if (parsedContent instanceof File) {
        ServletResponseUtil.write(response, (File) parsedContent);
      } else if (parsedContent instanceof String) {
        ServletResponseUtil.write(response, (String) parsedContent);
      }
    }
  }
  @Override
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    // PLACEHOLDER 01
    // PLACEHOLDER 02
    // PLACEHOLDER 03
    // PLACEHOLDER 04
    // PLACEHOLDER 05

    if (_isValidRequest(request)) {
      String cmd = ParamUtil.getString(request, Constants.CMD);

      String clusterNodeId = ParamUtil.getString(request, "clusterNodeId");

      if (cmd.equals("licenseProperties")) {
        String licenseProperties = _getLicenseProperties(clusterNodeId);

        response.setContentType(ContentTypes.TEXT_JAVASCRIPT);

        ServletResponseUtil.write(response, licenseProperties);

        return null;
      } else if (cmd.equals("serverInfo")) {
        String serverInfo = _getServerInfo(clusterNodeId);

        response.setContentType(ContentTypes.TEXT_JAVASCRIPT);

        ServletResponseUtil.write(response, serverInfo);

        return null;
      }

      return mapping.findForward("portal.license");
    } else {
      response.sendRedirect(PortalUtil.getPathContext() + "/c/portal/layout");

      return null;
    }
  }
  protected static void writeJSON(
      PortletRequest portletRequest, ActionResponse actionResponse, Object json)
      throws IOException {

    HttpServletResponse response = PortalUtil.getHttpServletResponse(actionResponse);

    response.setContentType(ContentTypes.APPLICATION_JSON);

    ServletResponseUtil.write(response, json.toString());

    response.flushBuffer();
  }
  public static void writeJSON(
      PortletRequest portletRequest, PortletResponse portletResponse, Object json)
      throws IOException {

    HttpServletResponse response = PortalUtil.getHttpServletResponse(portletResponse);

    response.setContentType(_getContentType(portletRequest));

    ServletResponseUtil.write(response, json.toString());

    response.flushBuffer();
  }
  @Override
  protected void processFilter(
      HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
      throws Exception {

    ByteBufferServletResponse byteBufferResponse = new ByteBufferServletResponse(response);

    processFilter(ETagFilter.class, request, byteBufferResponse, filterChain);

    if (!ETagUtil.processETag(request, response, byteBufferResponse)) {
      ServletResponseUtil.write(response, byteBufferResponse.getByteBuffer());
    }
  }
  protected void sendFile(
      HttpServletResponse response, User user, long groupId, long folderId, String title)
      throws Exception {

    FileEntry fileEntry = DLAppServiceUtil.getFileEntry(groupId, folderId, title);

    String contentType = fileEntry.getMimeType();

    response.setContentType(contentType);

    InputStream inputStream = fileEntry.getContentStream();

    ServletResponseUtil.write(response, inputStream);
  }
  protected void testDatabase(HttpServletRequest request, HttpServletResponse response)
      throws Exception {

    JSONObject jsonObject = JSONFactoryUtil.createJSONObject();

    try {
      SetupWizardUtil.testDatabase(request);

      jsonObject.put("success", true);

      putMessage(request, jsonObject, "database-connection-was-established-sucessfully");
    } catch (ClassNotFoundException cnfe) {
      putMessage(
          request, jsonObject, "database-driver-x-is-not-present", cnfe.getLocalizedMessage());
    } catch (SQLException sqle) {
      putMessage(request, jsonObject, "database-connection-could-not-be-established");
    }

    response.setContentType(ContentTypes.APPLICATION_JSON);
    response.setHeader(HttpHeaders.CACHE_CONTROL, HttpHeaders.CACHE_CONTROL_NO_CACHE_VALUE);

    ServletResponseUtil.write(response, jsonObject.toString());
  }
  @Override
  protected void doServeResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse)
      throws Exception {

    HttpServletResponse httpServletResponse = PortalUtil.getHttpServletResponse(resourceResponse);

    HttpServletRequest httpServletRequest = PortalUtil.getHttpServletRequest(resourceRequest);

    DDMFormField ddmFormField = getDDMFormField(httpServletRequest);

    DDMFormFieldRenderer ddmFormFieldRenderer =
        _ddmFormFieldRendererRegistry.getDDMFormFieldRenderer(ddmFormField.getType());

    DDMFormFieldRenderingContext ddmFormFieldRenderingContext =
        createDDMFormFieldRenderingContext(httpServletRequest, httpServletResponse);

    String ddmFormFieldHTML =
        ddmFormFieldRenderer.render(ddmFormField, ddmFormFieldRenderingContext);

    httpServletResponse.setContentType(ContentTypes.TEXT_HTML);

    ServletResponseUtil.write(httpServletResponse, ddmFormFieldHTML);
  }
  @Override
  protected void processFilter(
      HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
      throws Exception {

    request.setAttribute(SKIP_FILTER, Boolean.TRUE);

    if (_log.isDebugEnabled()) {
      String completeURL = HttpUtil.getCompleteURL(request);

      _log.debug("Fragmenting " + completeURL);
    }

    BufferCacheServletResponse bufferCacheServletResponse =
        new BufferCacheServletResponse(response);

    processFilter(FragmentFilter.class, request, bufferCacheServletResponse, filterChain);

    String content = bufferCacheServletResponse.getString();

    content = getContent(request, content);

    ServletResponseUtil.write(response, content);
  }
  @Override
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    if (!PropsValues.PORTLET_URL_GENERATE_BY_PATH_ENABLED) {
      response.sendError(HttpServletResponse.SC_FORBIDDEN);

      return null;
    }

    try {
      String portletURL = getPortletURL(request);

      ServletResponseUtil.write(response, portletURL);
    } catch (Exception e) {
      PortalUtil.sendError(e, request, response);
    }

    return null;
  }
  protected void vtiBinWebsAsmx(HttpServletRequest request, HttpServletResponse response)
      throws Exception {

    StringBundler sb = new StringBundler(12);

    String url = "http://" + request.getLocalAddr() + ":" + request.getServerPort() + "/sharepoint";

    sb.append("<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"");
    sb.append("http://schemas.xmlsoap.org/soap/envelope/\">");
    sb.append("<SOAP-ENV:Header/>");
    sb.append("<SOAP-ENV:Body>");
    sb.append("<WebUrlFromPageUrlResponse xmlns=\"");
    sb.append("http://schemas.microsoft.com/sharepoint/soap/\">");
    sb.append("<WebUrlFromPageUrlResult>");
    sb.append(url);
    sb.append("</WebUrlFromPageUrlResult>");
    sb.append("</WebUrlFromPageUrlResponse>");
    sb.append("</SOAP-ENV:Body>");
    sb.append("</SOAP-ENV:Envelope>");

    response.setContentType(ContentTypes.TEXT_XML_UTF8);

    ServletResponseUtil.write(response, sb.toString());
  }
  protected void sendFile(
      HttpServletRequest request, HttpServletResponse response, User user, String[] pathArray)
      throws Exception {

    // Retrieve file details

    FileEntry fileEntry = getFileEntry(pathArray);

    if (fileEntry == null) {
      throw new NoSuchFileEntryException();
    }

    String version = ParamUtil.getString(request, "version");

    if (Validator.isNull(version)) {
      if (Validator.isNotNull(fileEntry.getVersion())) {
        version = fileEntry.getVersion();
      }
    }

    String tempFileId = DLUtil.getTempFileId(fileEntry.getFileEntryId(), version);

    FileVersion fileVersion = fileEntry.getFileVersion(version);

    String fileName = fileVersion.getTitle();

    String extension = fileVersion.getExtension();

    if (Validator.isNotNull(extension) && !fileName.endsWith(StringPool.PERIOD + extension)) {

      fileName += StringPool.PERIOD + extension;
    }

    // Handle requested conversion

    boolean converted = false;

    String targetExtension = ParamUtil.getString(request, "targetExtension");
    int imageThumbnail = ParamUtil.getInteger(request, "imageThumbnail");
    int documentThumbnail = ParamUtil.getInteger(request, "documentThumbnail");
    int previewFileIndex = ParamUtil.getInteger(request, "previewFileIndex");
    boolean audioPreview = ParamUtil.getBoolean(request, "audioPreview");
    boolean imagePreview = ParamUtil.getBoolean(request, "imagePreview");
    boolean videoPreview = ParamUtil.getBoolean(request, "videoPreview");
    int videoThumbnail = ParamUtil.getInteger(request, "videoThumbnail");

    InputStream inputStream = null;
    long contentLength = 0;

    if ((imageThumbnail > 0) && (imageThumbnail <= 3)) {
      fileName =
          FileUtil.stripExtension(fileName)
              .concat(StringPool.PERIOD)
              .concat(ImageProcessorUtil.getThumbnailType(fileVersion));

      int thumbnailIndex = imageThumbnail - 1;

      inputStream = ImageProcessorUtil.getThumbnailAsStream(fileVersion, thumbnailIndex);
      contentLength = ImageProcessorUtil.getThumbnailFileSize(fileVersion, thumbnailIndex);

      converted = true;
    } else if ((documentThumbnail > 0) && (documentThumbnail <= 3)) {
      fileName =
          FileUtil.stripExtension(fileName)
              .concat(StringPool.PERIOD)
              .concat(PDFProcessor.THUMBNAIL_TYPE);

      int thumbnailIndex = documentThumbnail - 1;

      inputStream = PDFProcessorUtil.getThumbnailAsStream(fileVersion, thumbnailIndex);
      contentLength = PDFProcessorUtil.getThumbnailFileSize(fileVersion, thumbnailIndex);

      converted = true;
    } else if (previewFileIndex > 0) {
      fileName =
          FileUtil.stripExtension(fileName)
              .concat(StringPool.PERIOD)
              .concat(PDFProcessor.PREVIEW_TYPE);
      inputStream = PDFProcessorUtil.getPreviewAsStream(fileVersion, previewFileIndex);
      contentLength = PDFProcessorUtil.getPreviewFileSize(fileVersion, previewFileIndex);

      converted = true;
    } else if (audioPreview || videoPreview) {
      String type = ParamUtil.getString(request, "type");

      fileName = FileUtil.stripExtension(fileName).concat(StringPool.PERIOD).concat(type);

      if (audioPreview) {
        inputStream = AudioProcessorUtil.getPreviewAsStream(fileVersion, type);
        contentLength = AudioProcessorUtil.getPreviewFileSize(fileVersion, type);
      } else {
        inputStream = VideoProcessorUtil.getPreviewAsStream(fileVersion, type);
        contentLength = VideoProcessorUtil.getPreviewFileSize(fileVersion, type);
      }

      converted = true;
    } else if (imagePreview) {
      String type = ImageProcessorUtil.getPreviewType(fileVersion);

      fileName = FileUtil.stripExtension(fileName).concat(StringPool.PERIOD).concat(type);

      inputStream = ImageProcessorUtil.getPreviewAsStream(fileVersion);

      contentLength = ImageProcessorUtil.getPreviewFileSize(fileVersion);

      converted = true;
    } else if ((videoThumbnail > 0) && (videoThumbnail <= 3)) {
      fileName =
          FileUtil.stripExtension(fileName)
              .concat(StringPool.PERIOD)
              .concat(VideoProcessor.THUMBNAIL_TYPE);

      int thumbnailIndex = videoThumbnail - 1;

      inputStream = VideoProcessorUtil.getThumbnailAsStream(fileVersion, thumbnailIndex);
      contentLength = VideoProcessorUtil.getThumbnailFileSize(fileVersion, thumbnailIndex);

      converted = true;
    } else {
      inputStream = fileVersion.getContentStream(true);
      contentLength = fileVersion.getSize();

      if (Validator.isNotNull(targetExtension)) {
        File convertedFile =
            DocumentConversionUtil.convert(tempFileId, inputStream, extension, targetExtension);

        if (convertedFile != null) {
          fileName =
              FileUtil.stripExtension(fileName).concat(StringPool.PERIOD).concat(targetExtension);
          inputStream = new FileInputStream(convertedFile);
          contentLength = convertedFile.length();

          converted = true;
        }
      }
    }

    // Determine proper content type

    String contentType = null;

    if (converted) {
      contentType = MimeTypesUtil.getContentType(fileName);
    } else {
      contentType = fileVersion.getMimeType();
    }

    // Support range HTTP header

    response.setHeader(HttpHeaders.ACCEPT_RANGES, HttpHeaders.ACCEPT_RANGES_BYTES_VALUE);

    List<Range> ranges = null;

    try {
      ranges = ServletResponseUtil.getRanges(request, response, contentLength);
    } catch (IOException ioe) {
      if (_log.isErrorEnabled()) {
        _log.error(ioe);
      }

      response.setHeader(HttpHeaders.CONTENT_RANGE, "bytes */" + contentLength);

      response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);

      return;
    }

    if ((ranges == null) || ranges.isEmpty()) {
      ServletResponseUtil.sendFile(
          request, response, fileName, inputStream, contentLength, contentType);
    } else {
      if (_log.isDebugEnabled()) {
        _log.debug("Request has range header " + request.getHeader(HttpHeaders.RANGE));
      }

      ServletResponseUtil.write(
          request, response, fileName, ranges, inputStream, contentLength, contentType);
    }
  }
  protected int doProcess(WebDAVRequest webDAVRequest) throws Exception {
    WebDAVStorage storage = webDAVRequest.getWebDAVStorage();

    if (!storage.isSupportsClassTwo()) {
      return HttpServletResponse.SC_METHOD_NOT_ALLOWED;
    }

    HttpServletRequest request = webDAVRequest.getHttpServletRequest();
    HttpServletResponse response = webDAVRequest.getHttpServletResponse();

    Lock lock = null;
    Status status = null;

    String lockUuid = webDAVRequest.getLockUuid();
    long timeout = WebDAVUtil.getTimeout(request);

    if (Validator.isNull(lockUuid)) {

      // Create new lock

      String owner = null;
      String xml = new String(FileUtil.getBytes(request.getInputStream()));

      if (Validator.isNotNull(xml)) {
        if (_log.isDebugEnabled()) {
          _log.debug("Request XML\n" + XMLFormatter.toString(xml));
        }

        Document document = SAXReaderUtil.read(xml);

        Element rootElement = document.getRootElement();

        boolean exclusive = false;

        Element lockscopeElement = rootElement.element("lockscope");

        for (Element element : lockscopeElement.elements()) {
          String name = GetterUtil.getString(element.getName());

          if (name.equals("exclusive")) {
            exclusive = true;
          }
        }

        if (!exclusive) {
          return HttpServletResponse.SC_BAD_REQUEST;
        }

        Element ownerElement = rootElement.element("owner");

        owner = ownerElement.getTextTrim();

        if (Validator.isNull(owner)) {
          List<Element> hrefElements = ownerElement.elements("href");

          for (Element hrefElement : hrefElements) {
            owner = "<D:href>" + hrefElement.getTextTrim() + "</D:href>";
          }
        }
      } else {
        _log.error("Empty request XML");

        return HttpServletResponse.SC_PRECONDITION_FAILED;
      }

      status = storage.lockResource(webDAVRequest, owner, timeout);

      lock = (Lock) status.getObject();
    } else {
      try {

        // Refresh existing lock

        lock = storage.refreshResourceLock(webDAVRequest, lockUuid, timeout);

        status = new Status(HttpServletResponse.SC_OK);
      } catch (WebDAVException wde) {
        if (wde.getCause() instanceof NoSuchLockException) {
          return HttpServletResponse.SC_PRECONDITION_FAILED;
        } else {
          throw wde;
        }
      }
    }

    // Return lock details

    if (lock == null) {
      return status.getCode();
    }

    long depth = WebDAVUtil.getDepth(request);

    String xml = getResponseXML(lock, depth);

    if (_log.isDebugEnabled()) {
      _log.debug("Response XML\n" + xml);
    }

    String lockToken = "<" + WebDAVUtil.TOKEN_PREFIX + lock.getUuid() + ">";

    response.setContentType(ContentTypes.TEXT_XML_UTF8);
    response.setHeader("Lock-Token", lockToken);
    response.setStatus(status.getCode());

    if (_log.isDebugEnabled()) {
      _log.debug("Returning lock token " + lockToken);
    }

    try {
      ServletResponseUtil.write(response, xml);
    } catch (Exception e) {
      if (_log.isWarnEnabled()) {
        _log.warn(e);
      }
    }

    return status.getCode();
  }