public RepositoryFile(
      final String fileName,
      final RepositoryFile parent,
      final byte[] data,
      final long lastModified) {
    this();
    this.fileId = UUIDUtil.getUUIDAsString();

    this.fileName = fileName;
    if (parent != null) {
      parent.addChildFile(this);
    }
    setParent(parent);
    setData(data);
    setLastModified(lastModified);
    directory = data == null;
  }
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    try {
      // Retrieving the file upload defaults from pentaho.xml
      String relativePath =
          PentahoSystem.getSystemSetting(
              "file-upload-defaults/relative-path",
              String.valueOf(DEFAULT_RELATIVE_UPLOAD_FILE_PATH)); // $NON-NLS-1$
      String maxFileLimit =
          PentahoSystem.getSystemSetting(
              "file-upload-defaults/max-file-limit", String.valueOf(MAX_FILE_SIZE)); // $NON-NLS-1$
      String maxFolderLimit =
          PentahoSystem.getSystemSetting(
              "file-upload-defaults/max-folder-limit",
              String.valueOf(MAX_FOLDER_SIZE)); // $NON-NLS-1$

      response.setContentType("text/plain");
      FileItem uploadItem = getFileItem(request);
      if (uploadItem == null) {
        response
            .getWriter()
            .write(
                Messages.getInstance()
                    .getErrorString("UploadFileServlet.ERROR_0001_NO_FILE_TO_UPLOAD"));
        return;
      }
      if (Long.parseLong(maxFileLimit) < uploadItem.getSize()) {
        response
            .getWriter()
            .write(
                Messages.getInstance().getErrorString("UploadFileServlet.ERROR_0003_FILE_TOO_BIG"));
        return;
      }

      String path = PentahoSystem.getApplicationContext().getSolutionPath(relativePath);

      File pathDir = new File(path);
      // create the path if it doesn't exist yet
      if (!pathDir.exists()) {
        pathDir.mkdirs();
      }

      if (uploadItem.getSize() + getFolderSize(pathDir) > Long.parseLong(maxFolderLimit)) {
        response
            .getWriter()
            .write(
                Messages.getInstance()
                    .getErrorString("UploadFileServlet.ERROR_0004_FOLDER_SIZE_LIMIT_REACHED"));
        return;
      }
      byte[] fileContents = uploadItem.get();
      UUID id = UUIDUtil.getUUID();
      String filename = id.toString() + CSV_EXT;

      if (doesFileExists(new File(path + filename))) {
        response
            .getWriter()
            .write(
                Messages.getInstance()
                    .getErrorString("UploadFileServlet.ERROR_0002_FILE_ALREADY_EXIST"));
        return;
      }
      FileOutputStream outputStream = new FileOutputStream(path + filename);
      outputStream.write(fileContents);
      outputStream.flush();
      outputStream.close();
      response.getWriter().write(new String(filename));
    } catch (Exception e) {
      response
          .getWriter()
          .write(
              Messages.getInstance()
                  .getErrorString(
                      "UploadFileServlet.ERROR_0005_UNKNOWN_ERROR", e.getLocalizedMessage()));
    }
  }
  public void createReportContent(
      final OutputStream outputStream,
      final Serializable fileId,
      final String path,
      final boolean forceDefaultOutputTarget)
      throws Exception {
    final long start = System.currentTimeMillis();
    final Map<String, Object> inputs = contentGenerator.createInputs();

    AuditHelper.audit(
        userSession.getId(),
        userSession.getName(),
        path,
        contentGenerator.getObjectName(),
        getClass().getName(),
        MessageTypes.INSTANCE_START,
        contentGenerator.getInstanceId(),
        "",
        0,
        contentGenerator); //$NON-NLS-1$

    String result = MessageTypes.INSTANCE_END;
    StagingHandler reportStagingHandler = null;
    try {
      final Object rawSessionId = inputs.get(ParameterXmlContentHandler.SYS_PARAM_SESSION_ID);
      if ((rawSessionId instanceof String) == false || "".equals(rawSessionId)) {
        inputs.put(ParameterXmlContentHandler.SYS_PARAM_SESSION_ID, UUIDUtil.getUUIDAsString());
      }

      // produce rendered report
      final SimpleReportingComponent reportComponent = new SimpleReportingComponent();
      reportComponent.setReportFileId(fileId);
      reportComponent.setPaginateOutput(true);
      reportComponent.setForceDefaultOutputTarget(forceDefaultOutputTarget);
      reportComponent.setDefaultOutputTarget(HtmlTableModule.TABLE_HTML_PAGE_EXPORT_TYPE);
      if (path.endsWith(".prpti")) {
        reportComponent.setForceUnlockPreferredOutput(true);
      }
      reportComponent.setInputs(inputs);

      final MasterReport report = reportComponent.getReport();
      final StagingMode stagingMode = getStagingMode(inputs, report);
      reportStagingHandler = new StagingHandler(outputStream, stagingMode, this.userSession);

      if (reportStagingHandler.isFullyBuffered()) {
        // it is safe to disable the buffered writing for the report now that we have a
        // extra buffering in place.
        report.getReportConfiguration().setConfigProperty(FORCED_BUFFERED_WRITING, "false");
      }

      reportComponent.setOutputStream(reportStagingHandler.getStagingOutputStream());

      // the requested mime type can be null, in that case the report-component will resolve the
      // desired
      // type from the output-target.
      // Hoever, the report-component will inspect the inputs independently from the mimetype here.

      final IUnifiedRepository repository =
          PentahoSystem.get(IUnifiedRepository.class, userSession);
      final RepositoryFile file = repository.getFileById(fileId);

      // add all inputs (request parameters) to report component
      final String mimeType = reportComponent.getMimeType();

      // If we haven't set an accepted page, -1 will be the default, which will give us a report
      // with no pages. This default is used so that when we do our parameter interaction with the
      // engine we can spend as little time as possible rendering unused pages, making it no pages.
      // We are going to intentionally reset the accepted page to the first page, 0, at this point,
      // if the accepted page is -1.
      final String outputTarget = reportComponent.getComputedOutputTarget();
      if (HtmlTableModule.TABLE_HTML_PAGE_EXPORT_TYPE.equals(outputTarget)
          && reportComponent.getAcceptedPage() < 0) {
        reportComponent.setAcceptedPage(0);
      }

      if (logger.isDebugEnabled()) {
        logger.debug(
            Messages.getInstance()
                .getString(
                    "ReportPlugin.logStartGenerateContent",
                    mimeType, //$NON-NLS-1$
                    outputTarget,
                    String.valueOf(reportComponent.getAcceptedPage())));
      }

      HttpServletResponse response = null;
      boolean streamToBrowser = false;
      final IParameterProvider pathProviders = contentGenerator.getParameterProviders().get("path");
      if (pathProviders != null) {
        final Object httpResponse = pathProviders.getParameter("httpresponse");
        if (httpResponse
            instanceof HttpServletResponse) { // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
          response = (HttpServletResponse) httpResponse; // $NON-NLS-1$ //$NON-NLS-2$
          if (reportStagingHandler.getStagingMode() == StagingMode.THRU) {
            // Direct back - check output stream...
            final OutputStream respOutputStream = response.getOutputStream();
            if (respOutputStream == outputStream) {
              //
              // Massive assumption here -
              // Assume the container returns the same object on successive calls to
              // response.getOutputStream()
              streamToBrowser = true;
            }
          }
        }
      }

      final String extension = MimeHelper.getExtension(mimeType);
      String filename = file.getName();
      if (filename.lastIndexOf(".") != -1) { // $NON-NLS-1$
        filename = filename.substring(0, filename.lastIndexOf(".")); // $NON-NLS-1$
      }
      String disposition =
          "inline; filename*=UTF-8''"
              + RepositoryPathEncoder.encode(
                  RepositoryPathEncoder.encodeRepositoryPath(filename + extension));

      final boolean validates = reportComponent.validate();
      if (!validates) {
        sendErrorResponse(response, outputStream, reportStagingHandler);
      } else {
        if (response != null) {
          // Send headers before we begin execution
          response.setHeader("Content-Disposition", disposition);
          response.setHeader("Content-Description", file.getName()); // $NON-NLS-1$
          response.setHeader("Cache-Control", "private, max-age=0, must-revalidate");
        }
        if (reportComponent.execute()) {
          if (response != null) {
            if (reportStagingHandler.canSendHeaders()) {
              response.setHeader("Content-Disposition", disposition);
              response.setHeader("Content-Description", file.getName()); // $NON-NLS-1$
              response.setHeader("Cache-Control", "private, max-age=0, must-revalidate");
              response.setContentLength(reportStagingHandler.getWrittenByteCount());
            }
          }
          if (logger.isDebugEnabled()) {
            logger.debug(
                Messages.getInstance()
                    .getString(
                        "ReportPlugin.logEndGenerateContent",
                        String.valueOf(reportStagingHandler.getWrittenByteCount()))); // $NON-NLS-1$
          }
          reportStagingHandler.complete(); // will copy bytes to final destination...

        } else { // failed execution
          sendErrorResponse(response, outputStream, reportStagingHandler);
        }
      }
    } catch (Exception ex) {
      result = MessageTypes.INSTANCE_FAILED;
      throw ex;
    } finally {
      if (reportStagingHandler != null) {
        reportStagingHandler.close();
      }
      final long end = System.currentTimeMillis();
      AuditHelper.audit(
          userSession.getId(),
          userSession.getName(),
          path,
          contentGenerator.getObjectName(),
          getClass().getName(),
          result,
          contentGenerator.getInstanceId(),
          "",
          ((float) (end - start) / 1000),
          contentGenerator); //$NON-NLS-1$
    }
  }
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    try {

      String relativePath =
          PentahoSystem.getSystemSetting(
              "file-upload-defaults/relative-path",
              String.valueOf(DEFAULT_RELATIVE_UPLOAD_FILE_PATH)); // $NON-NLS-1$
      String maxFileLimit =
          PentahoSystem.getSystemSetting(
              "file-upload-defaults/max-file-limit",
              String.valueOf(MAX_FILE_SIZE)); // $NON-NLS-1$
      String maxFolderLimit =
          PentahoSystem.getSystemSetting(
              "file-upload-defaults/max-folder-limit",
              String.valueOf(MAX_FOLDER_SIZE)); // $NON-NLS-1$
      IPentahoSession session = PentahoHttpSessionHelper.getPentahoSession(request);

      response.setContentType("text/plain"); // $NON-NLS-1$

      FileItem uploadItem = getFileItem(request);
      if (uploadItem == null) {
        String error =
            Messages.getErrorString(
                "UploadFileDebugServlet.ERROR_0001_NO_FILE_TO_UPLOAD"); //$NON-NLS-1$
        response.getWriter().write(error);
        return;
      }
      if (Long.parseLong(maxFileLimit) < uploadItem.getSize()) {
        String error =
            Messages.getErrorString(
                "UploadFileDebugServlet.ERROR_0003_FILE_TOO_BIG"); //$NON-NLS-1$
        response.getWriter().write(error);
        return;
      }

      String path = PentahoSystem.getApplicationContext().getSolutionPath(relativePath);
      File pathDir = new File(path);
      // create the path if it doesn't exist yet
      if (!pathDir.exists()) {
        pathDir.mkdirs();
      }

      if (uploadItem.getSize() + getFolderSize(new File(path)) > Long.parseLong(maxFolderLimit)) {
        String error =
            Messages.getErrorString(
                "UploadFileDebugServlet.ERROR_0004_FOLDER_SIZE_LIMIT_REACHED"); //$NON-NLS-1$
        response.getWriter().write(error);
        return;
      }

      String filename = request.getParameter("file_name"); // $NON-NLS-1$
      if (StringUtils.isEmpty(filename)) {
        filename = UUIDUtil.getUUID().toString();
      }

      String temporary = request.getParameter("mark_temporary"); // $NON-NLS-1$
      boolean isTemporary = false;
      if (temporary != null) {
        isTemporary = Boolean.valueOf(temporary);
      }

      File file;
      if (isTemporary) {
        file =
            PentahoSystem.getApplicationContext()
                .createTempFile(session, "", ".tmp", true); // $NON-NLS-1$
      } else {
        file = new File(path + File.separatorChar + filename);
      }

      FileOutputStream outputStream = new FileOutputStream(file);
      byte[] fileContents = uploadItem.get();
      outputStream.write(fileContents);
      outputStream.flush();
      outputStream.close();

      response.getWriter().write(file.getName());
    } catch (Exception e) {
      String error =
          Messages.getErrorString(
              "UploadFileDebugServlet.ERROR_0005_UNKNOWN_ERROR",
              e.getLocalizedMessage()); // $NON-NLS-1$
      response.getWriter().write(error);
    }
  }