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);
      }
    }
  }
Esempio n. 2
0
  @Override
  public void processAction(
      ActionMapping mapping,
      ActionForm form,
      PortletConfig portletConfig,
      ActionRequest actionRequest,
      ActionResponse actionResponse)
      throws Exception {

    try {
      String csv = getUsersCSV(actionRequest, actionResponse);

      String fileName = "users.csv";
      byte[] bytes = csv.getBytes();

      HttpServletRequest request = PortalUtil.getHttpServletRequest(actionRequest);
      HttpServletResponse response = PortalUtil.getHttpServletResponse(actionResponse);

      ServletResponseUtil.sendFile(request, response, fileName, bytes, ContentTypes.TEXT_CSV_UTF8);

      setForward(actionRequest, ActionConstants.COMMON_NULL);
    } catch (Exception e) {
      SessionErrors.add(actionRequest, e.getClass());

      setForward(actionRequest, "portlet.users_admin.error");
    }
  }
  @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 sendResponse(
      ActionRequest actionRequest, ActionResponse actionResponse, String msg, boolean success)
      throws Exception {

    StringBundler sb = new StringBundler(7);

    sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
    sb.append("<response>");

    if (success) {
      sb.append("<error>0</error>");
    } else {
      sb.append("<error>1</error>");
      sb.append("<message>");
      sb.append(msg);
      sb.append("</message>");
    }

    sb.append("</response>");

    HttpServletRequest request = PortalUtil.getHttpServletRequest(actionRequest);
    HttpServletResponse response = PortalUtil.getHttpServletResponse(actionResponse);

    ServletResponseUtil.sendFile(
        request,
        response,
        null,
        sb.toString().getBytes(StringPool.UTF8),
        ContentTypes.TEXT_XML_UTF8);
  }
Esempio n. 5
0
  @Override
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    try {
      long groupId = ParamUtil.getLong(request, "groupId");
      String articleId = ParamUtil.getString(request, "articleId");

      String languageId = LanguageUtil.getLanguageId(request);

      JournalArticle article =
          JournalArticleServiceUtil.getLatestArticle(
              groupId, articleId, WorkflowConstants.STATUS_APPROVED);

      String fileName = "content.xml";
      byte[] bytes = article.getContentByLocale(languageId).getBytes();

      ServletResponseUtil.sendFile(request, response, fileName, bytes, ContentTypes.TEXT_XML_UTF8);

      return null;
    } catch (Exception e) {
      PortalUtil.sendError(e, request, response);

      return null;
    }
  }
  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);
      }
    }
  }
Esempio n. 8
0
  @Override
  public void serveResource(
      StrutsPortletAction originalStrutsPortletAction,
      PortletConfig portletConfig,
      ResourceRequest resourceRequest,
      ResourceResponse resourceResponse) {

    long entryId = ParamUtil.getLong(resourceRequest, "entryId");
    ThemeDisplay themeDisplay = (ThemeDisplay) resourceRequest.getAttribute(WebKeys.THEME_DISPLAY);

    BlogsEntry entry;
    try {
      entry = BlogsEntryServiceUtil.getEntry(entryId);
      StringBundler sb = new StringBundler();

      sb.append("<html>");

      sb.append("<head>");
      sb.append("<meta content=\"");
      sb.append(ContentTypes.TEXT_HTML_UTF8);
      sb.append("\" http-equiv=\"content-type\" />");
      sb.append("<base href=\"");
      sb.append(themeDisplay.getPortalURL());
      sb.append("\" />");
      sb.append("</head>");

      sb.append("<body>");
      sb.append(entry.getContent());
      sb.append("</body>");
      sb.append("</html>");

      InputStream is = new UnsyncByteArrayInputStream(sb.toString().getBytes(StringPool.UTF8));
      File destinationFile = null;

      destinationFile = DocumentConversionUtil.convert(entry.getEntryId() + "", is, "html", "pdf");
      OutputStream out = resourceResponse.getPortletOutputStream();
      InputStream in = new FileInputStream(destinationFile);
      HttpServletResponse httpRes = PortalUtil.getHttpServletResponse(resourceResponse);
      HttpServletRequest httpReq = PortalUtil.getHttpServletRequest(resourceRequest);
      String contentType = MimeTypesUtil.getContentType(destinationFile);
      ServletResponseUtil.sendFile(httpReq, httpRes, destinationFile.getName(), in, contentType);
      out.close();

    } catch (PortalException e) {
      System.out.println("PortalException : " + getClass().getName() + "\n" + e);
      // e.printStackTrace();
    } catch (SystemException e) {
      System.out.println("SystemException : " + getClass().getName() + "\n" + e);
      // e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
      System.out.println("UnsupportedEncodingException : " + getClass().getName() + "\n" + e);
      // e.printStackTrace();
    } catch (Exception e) {
      System.out.println("Exception : " + getClass().getName() + "\n" + e);
      // e.printStackTrace();
    }
  }
  @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;
    }
  }
  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();
  }
  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();
  }
  @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);
  }
Esempio n. 14
0
  @Override
  public ActionForward strutsExecute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    try {
      ServletResponseUtil.sendFile(
          request, response, null, getRSS(request), ContentTypes.TEXT_XML_UTF8);

      return null;
    } catch (Exception e) {
      PortalUtil.sendError(e, request, response);

      return null;
    }
  }
  @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);
  }
  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());
  }
Esempio n. 17
0
  @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 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();
  }
  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);
    }
  }
Esempio n. 22
0
  protected void getFile(
      long fileEntryId,
      long folderId,
      String name,
      String title,
      String version,
      long fileShortcutId,
      String uuid,
      long groupId,
      String targetExtension,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    if (name.startsWith("DLFE-")) {
      name = name.substring(5);
    }

    name = FileUtil.stripExtension(name);

    FileEntry fileEntry = null;

    if (Validator.isNotNull(uuid) && (groupId > 0)) {
      fileEntry = DLAppServiceUtil.getFileEntryByUuidAndGroupId(uuid, groupId);

      folderId = fileEntry.getFolderId();
    }

    if (fileEntryId > 0) {
      fileEntry = DLAppServiceUtil.getFileEntry(fileEntryId);
    } else if (fileShortcutId <= 0) {
      if (Validator.isNotNull(title)) {
        fileEntry = DLAppServiceUtil.getFileEntry(groupId, folderId, title);
      } else if (Validator.isNotNull(name)) {
        DLFileEntry dlFileEntry =
            DLFileEntryLocalServiceUtil.fetchFileEntryByName(groupId, folderId, name);

        if (dlFileEntry == null) {

          // LPS-30374

          List<DLFileEntry> dlFileEntries =
              DLFileEntryLocalServiceUtil.getFileEntries(folderId, name);

          if (!dlFileEntries.isEmpty()) {
            dlFileEntry = dlFileEntries.get(0);
          }
        }

        if (dlFileEntry != null) {
          ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);

          PermissionChecker permissionChecker = themeDisplay.getPermissionChecker();

          DLFileEntryPermission.check(permissionChecker, dlFileEntry, ActionKeys.VIEW);

          fileEntry = new LiferayFileEntry(dlFileEntry);
        }
      }
    } else {
      DLFileShortcut fileShortcut = DLAppServiceUtil.getFileShortcut(fileShortcutId);

      fileEntryId = fileShortcut.getToFileEntryId();

      fileEntry = DLAppServiceUtil.getFileEntry(fileEntryId);
    }

    if (Validator.isNull(version)) {
      if ((fileEntry != null) && Validator.isNotNull(fileEntry.getVersion())) {

        version = fileEntry.getVersion();
      } else {
        throw new NoSuchFileEntryException();
      }
    }

    FileVersion fileVersion = fileEntry.getFileVersion(version);

    InputStream is = fileVersion.getContentStream(true);
    String fileName = fileVersion.getTitle();
    long contentLength = fileVersion.getSize();
    String contentType = fileVersion.getMimeType();

    if (Validator.isNotNull(targetExtension)) {
      String id = DLUtil.getTempFileId(fileEntry.getFileEntryId(), version);

      String sourceExtension = fileVersion.getExtension();

      if (!fileName.endsWith(StringPool.PERIOD + sourceExtension)) {
        fileName += StringPool.PERIOD + sourceExtension;
      }

      File convertedFile = DocumentConversionUtil.convert(id, is, sourceExtension, targetExtension);

      if (convertedFile != null) {
        fileName =
            FileUtil.stripExtension(fileName).concat(StringPool.PERIOD).concat(targetExtension);
        is = new FileInputStream(convertedFile);
        contentLength = convertedFile.length();
        contentType = MimeTypesUtil.getContentType(fileName);
      }
    }

    ServletResponseUtil.sendFile(request, response, fileName, is, contentLength, contentType);
  }
  @Override
  public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {

    String servletPath = request.getServletPath();
    String pathInfo = URLDecoder.decode(request.getPathInfo(), StringPool.UTF8);

    String path = servletPath.concat(pathInfo);

    if (!isAllowedPath(path)) {
      response.setStatus(HttpServletResponse.SC_NOT_FOUND);

      return;
    }

    File file = new File(_tempDir, path);

    String canonicalPath = file.getCanonicalPath();

    if (!file.exists()
        || file.isDirectory()
        || !file.canRead()
        || file.isHidden()
        || !canonicalPath.startsWith(_tempDir.getCanonicalPath())) {

      response.setStatus(HttpServletResponse.SC_NOT_FOUND);

      return;
    }

    long lastModified = file.lastModified();

    if (lastModified > 0) {
      long ifModifiedSince = request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE);

      if ((ifModifiedSince > 0) && (ifModifiedSince == lastModified)) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);

        return;
      }
    }

    if (lastModified > 0) {
      response.setDateHeader(HttpHeaders.LAST_MODIFIED, lastModified);
    }

    String fileName = file.getName();

    // Determine proper content type

    String contentType = MimeTypesUtil.getContentType(fileName);

    // Send file

    if (isSupportsRangeHeader(contentType)) {
      sendFileWithRangeHeader(
          request, response, fileName, new FileInputStream(file), file.length(), contentType);
    } else {
      ServletResponseUtil.sendFile(
          request, response, fileName, new FileInputStream(file), file.length(), contentType);
    }
  }
  @Override
  public void processAction(
      ActionMapping mapping,
      ActionForm form,
      PortletConfig portletConfig,
      ActionRequest actionRequest,
      ActionResponse actionResponse)
      throws Exception {

    File file = null;

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

      long groupId = ParamUtil.getLong(actionRequest, "groupId");
      boolean privateLayout = ParamUtil.getBoolean(actionRequest, "privateLayout");
      long[] layoutIds = ParamUtil.getLongValues(actionRequest, "layoutIds");
      String fileName = ParamUtil.getString(actionRequest, "exportFileName");
      String range = ParamUtil.getString(actionRequest, "range");

      Date startDate = null;
      Date endDate = null;

      if (range.equals("dateRange")) {
        int startDateMonth = ParamUtil.getInteger(actionRequest, "startDateMonth");
        int startDateDay = ParamUtil.getInteger(actionRequest, "startDateDay");
        int startDateYear = ParamUtil.getInteger(actionRequest, "startDateYear");
        int startDateHour = ParamUtil.getInteger(actionRequest, "startDateHour");
        int startDateMinute = ParamUtil.getInteger(actionRequest, "startDateMinute");
        int startDateAmPm = ParamUtil.getInteger(actionRequest, "startDateAmPm");

        if (startDateAmPm == Calendar.PM) {
          startDateHour += 12;
        }

        startDate =
            PortalUtil.getDate(
                startDateMonth,
                startDateDay,
                startDateYear,
                startDateHour,
                startDateMinute,
                themeDisplay.getTimeZone(),
                new PortalException());

        int endDateMonth = ParamUtil.getInteger(actionRequest, "endDateMonth");
        int endDateDay = ParamUtil.getInteger(actionRequest, "endDateDay");
        int endDateYear = ParamUtil.getInteger(actionRequest, "endDateYear");
        int endDateHour = ParamUtil.getInteger(actionRequest, "endDateHour");
        int endDateMinute = ParamUtil.getInteger(actionRequest, "endDateMinute");
        int endDateAmPm = ParamUtil.getInteger(actionRequest, "endDateAmPm");

        if (endDateAmPm == Calendar.PM) {
          endDateHour += 12;
        }

        endDate =
            PortalUtil.getDate(
                endDateMonth,
                endDateDay,
                endDateYear,
                endDateHour,
                endDateMinute,
                themeDisplay.getTimeZone(),
                new PortalException());
      } else if (range.equals("fromLastPublishDate")) {
        LayoutSet layoutSet = LayoutSetLocalServiceUtil.getLayoutSet(groupId, privateLayout);

        UnicodeProperties settingsProperties = layoutSet.getSettingsProperties();

        long lastPublishDate =
            GetterUtil.getLong(settingsProperties.getProperty("last-publish-date"));

        if (lastPublishDate > 0) {
          Calendar cal = Calendar.getInstance(themeDisplay.getTimeZone(), themeDisplay.getLocale());

          endDate = cal.getTime();

          cal.setTimeInMillis(lastPublishDate);

          startDate = cal.getTime();
        }
      } else if (range.equals("last")) {
        int rangeLast = ParamUtil.getInteger(actionRequest, "last");

        Date now = new Date();

        startDate = new Date(now.getTime() - (rangeLast * Time.HOUR));

        endDate = now;
      }

      file =
          LayoutServiceUtil.exportLayoutsAsFile(
              groupId,
              privateLayout,
              layoutIds,
              actionRequest.getParameterMap(),
              startDate,
              endDate);

      HttpServletRequest request = PortalUtil.getHttpServletRequest(actionRequest);
      HttpServletResponse response = PortalUtil.getHttpServletResponse(actionResponse);

      ServletResponseUtil.sendFile(
          request, response, fileName, new FileInputStream(file), ContentTypes.APPLICATION_ZIP);

      setForward(actionRequest, ActionConstants.COMMON_NULL);
    } catch (Exception e) {
      _log.error(e, e);

      SessionErrors.add(actionRequest, e.getClass().getName());

      String pagesRedirect = ParamUtil.getString(actionRequest, "pagesRedirect");

      sendRedirect(actionRequest, actionResponse, pagesRedirect);
    } finally {
      FileUtil.delete(file);
    }
  }
  public static void sendFile(PortletRequest portletRequest, PortletResponse portletResponse)
      throws IOException {

    long groupId = ParamUtil.getLong(portletRequest, "groupId");
    String articleId = ParamUtil.getString(portletRequest, "articleId");

    String targetExtension = ParamUtil.getString(portletRequest, "targetExtension");

    PortletPreferences portletPreferences = portletRequest.getPreferences();

    String[] allowedExtensions = StringUtil.split(portletPreferences.getValue("extensions", null));

    String languageId = LanguageUtil.getLanguageId(portletRequest);
    PortletRequestModel portletRequestModel =
        new PortletRequestModel(portletRequest, portletResponse);
    ThemeDisplay themeDisplay = (ThemeDisplay) portletRequest.getAttribute(WebKeys.THEME_DISPLAY);
    HttpServletRequest request = PortalUtil.getHttpServletRequest(portletRequest);
    HttpServletResponse response = PortalUtil.getHttpServletResponse(portletResponse);

    JournalArticleDisplay articleDisplay =
        JournalContentUtil.getDisplay(
            groupId, articleId, null, "export", languageId, 1, portletRequestModel, themeDisplay);

    int pages = articleDisplay.getNumberOfPages();

    StringBundler sb = new StringBundler(pages + 12);

    sb.append("<html>");

    sb.append("<head>");
    sb.append("<meta content=\"");
    sb.append(ContentTypes.TEXT_HTML_UTF8);
    sb.append("\" http-equiv=\"content-type\" />");
    sb.append("<base href=\"");
    sb.append(themeDisplay.getPortalURL());
    sb.append("\" />");
    sb.append("</head>");

    sb.append("<body>");

    sb.append(articleDisplay.getContent());

    for (int i = 2; i <= pages; i++) {
      articleDisplay =
          JournalContentUtil.getDisplay(groupId, articleId, "export", languageId, i, themeDisplay);

      sb.append(articleDisplay.getContent());
    }

    sb.append("</body>");
    sb.append("</html>");

    InputStream is = new UnsyncByteArrayInputStream(sb.toString().getBytes(StringPool.UTF8));

    String title = articleDisplay.getTitle();
    String sourceExtension = "html";

    String fileName = title.concat(StringPool.PERIOD).concat(sourceExtension);

    String contentType = MimeTypesUtil.getContentType(fileName);

    if (Validator.isNull(targetExtension)
        || !ArrayUtil.contains(allowedExtensions, targetExtension)) {

      ServletResponseUtil.sendFile(request, response, fileName, is, contentType);

      return;
    }

    String id =
        DLUtil.getTempFileId(
            articleDisplay.getId(), String.valueOf(articleDisplay.getVersion()), languageId);

    File convertedFile = DocumentConversionUtil.convert(id, is, sourceExtension, targetExtension);

    if (convertedFile != null) {
      fileName = title.concat(StringPool.PERIOD).concat(targetExtension);

      is = new FileInputStream(convertedFile);
    }

    ServletResponseUtil.sendFile(request, response, fileName, is, contentType);
  }
  @Override
  public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse)
      throws IOException, PortletException {

    String resourceID = GetterUtil.getString(resourceRequest.getResourceID());

    HttpServletRequest request = PortalUtil.getHttpServletRequest(resourceRequest);

    HttpServletResponse response = PortalUtil.getHttpServletResponse(resourceResponse);

    if (resourceID.equals("compareVersions")) {
      ThemeDisplay themeDisplay =
          (ThemeDisplay) resourceRequest.getAttribute(WebKeys.THEME_DISPLAY);

      long groupId = ParamUtil.getLong(resourceRequest, "groupId");
      String articleId = ParamUtil.getString(resourceRequest, "articleId");
      double sourceVersion = ParamUtil.getDouble(resourceRequest, "filterSourceVersion");
      double targetVersion = ParamUtil.getDouble(resourceRequest, "filterTargetVersion");
      String languageId = ParamUtil.getString(resourceRequest, "languageId");

      String diffHtmlResults = null;

      try {
        diffHtmlResults =
            JournalUtil.diffHtml(
                groupId,
                articleId,
                sourceVersion,
                targetVersion,
                languageId,
                new PortletRequestModel(resourceRequest, resourceResponse),
                themeDisplay);
      } catch (CompareVersionsException cve) {
        resourceRequest.setAttribute(WebKeys.DIFF_VERSION, cve.getVersion());
      } catch (Exception e) {
        try {
          PortalUtil.sendError(e, request, response);
        } catch (ServletException se) {
        }
      }

      resourceRequest.setAttribute(WebKeys.DIFF_HTML_RESULTS, diffHtmlResults);

      PortletSession portletSession = resourceRequest.getPortletSession();

      PortletContext portletContext = portletSession.getPortletContext();

      PortletRequestDispatcher portletRequestDispatcher =
          portletContext.getRequestDispatcher(
              "/html/taglib/ui/diff_version_comparator/diff_html.jsp");

      portletRequestDispatcher.include(resourceRequest, resourceResponse);
    } else if (resourceID.equals("rss")) {
      try {
        byte[] xml = JournalRSSUtil.getRSS(resourceRequest, resourceResponse);

        ServletResponseUtil.sendFile(request, response, null, xml, ContentTypes.TEXT_XML_UTF8);
      } catch (Exception e) {
        try {
          PortalUtil.sendError(e, request, response);
        } catch (ServletException se) {
        }
      }
    } else {
      super.serveResource(resourceRequest, resourceResponse);
    }
  }