/**
   * Process the blog entries
   *
   * @param httpServletRequest Request
   * @param httpServletResponse Response
   * @param user {@link org.blojsom.blog.BlogUser} instance
   * @param context Context
   * @param entries Blog entries retrieved for the particular request
   * @return Modified set of blog entries
   * @throws BlojsomPluginException If there is an error processing the blog entries
   */
  public BlogEntry[] process(
      HttpServletRequest httpServletRequest,
      HttpServletResponse httpServletResponse,
      BlogUser user,
      Map context,
      BlogEntry[] entries)
      throws BlojsomPluginException {
    if (!authenticateUser(httpServletRequest, httpServletResponse, context, user)) {
      httpServletRequest.setAttribute(PAGE_PARAM, ADMIN_LOGIN_PAGE);

      return entries;
    }

    String username = getUsernameFromSession(httpServletRequest, user.getBlog());
    if (!checkPermission(user, null, username, FILE_UPLOAD_PERMISSION)) {
      httpServletRequest.setAttribute(PAGE_PARAM, ADMIN_ADMINISTRATION_PAGE);
      addOperationResultMessage(context, "You are not allowed to upload files");

      return entries;
    }

    File resourceDirectory =
        new File(
            _blojsomConfiguration.getInstallationDirectory()
                + _resourcesDirectory
                + user.getId()
                + "/");

    String action = BlojsomUtils.getRequestValue(ACTION_PARAM, httpServletRequest);
    if (BlojsomUtils.checkNullOrBlank(action)) {
      _logger.debug("User did not request edit action");

      httpServletRequest.setAttribute(PAGE_PARAM, ADMIN_ADMINISTRATION_PAGE);
    } else if (PAGE_ACTION.equals(action)) {
      _logger.debug("User requested file upload page");

      httpServletRequest.setAttribute(PAGE_PARAM, FILE_UPLOAD_PAGE);
    } else if (UPLOAD_FILE_ACTION.equals(action)) {
      _logger.debug("User requested file upload action");

      // Create a new disk file upload and set its parameters
      DiskFileUpload diskFileUpload = new DiskFileUpload();
      diskFileUpload.setRepositoryPath(_temporaryDirectory);
      diskFileUpload.setSizeThreshold(_maximumMemorySize);
      diskFileUpload.setSizeMax(_maximumUploadSize);

      try {
        List items = diskFileUpload.parseRequest(httpServletRequest);
        Iterator itemsIterator = items.iterator();
        while (itemsIterator.hasNext()) {
          FileItem item = (FileItem) itemsIterator.next();

          // Check for the file upload form item
          if (!item.isFormField()) {
            String itemNameWithoutPath = BlojsomUtils.getFilenameFromPath(item.getName());

            _logger.debug(
                "Found file item: " + itemNameWithoutPath + " of type: " + item.getContentType());

            // Is it one of the accepted file types?
            String fileType = item.getContentType();
            boolean isAcceptedFileType = _acceptedFileTypes.containsKey(fileType);

            String extension = BlojsomUtils.getFileExtension(itemNameWithoutPath);
            boolean isAcceptedFileExtension = true;
            for (int i = 0; i < _invalidFileExtensions.length; i++) {
              String invalidFileExtension = _invalidFileExtensions[i];
              if (itemNameWithoutPath.indexOf(invalidFileExtension) != -1) {
                isAcceptedFileExtension = false;
                break;
              }
            }

            // If so, upload the file to the resources directory
            if (isAcceptedFileType && isAcceptedFileExtension) {
              if (!resourceDirectory.exists()) {
                if (!resourceDirectory.mkdirs()) {
                  _logger.error(
                      "Unable to create resource directory for user: "******"Unable to create resource directory");
                  return entries;
                }
              }

              File resourceFile =
                  new File(
                      _blojsomConfiguration.getInstallationDirectory()
                          + _resourcesDirectory
                          + user.getId()
                          + "/"
                          + itemNameWithoutPath);
              try {
                item.write(resourceFile);
              } catch (Exception e) {
                _logger.error(e);
                addOperationResultMessage(
                    context, "Unknown error in file upload: " + e.getMessage());
              }

              String resourceURL =
                  user.getBlog().getBlogBaseURL()
                      + _blojsomConfiguration.getResourceDirectory()
                      + user.getId()
                      + "/"
                      + item.getName();

              _logger.debug("Successfully uploaded resource file: " + resourceFile.toString());
              addOperationResultMessage(
                  context,
                  "Successfully upload resource file: "
                      + item.getName()
                      + ". <p></p>Here is a link to <a href=\""
                      + resourceURL
                      + "\">"
                      + item.getName()
                      + "</a>. Right-click and copy the link to the resource to use in a blog entry.");
            } else {
              if (!isAcceptedFileExtension) {
                _logger.error("Upload file does not have an accepted extension: " + extension);
                addOperationResultMessage(
                    context, "Upload file does not have an accepted extension: " + extension);
              } else {
                _logger.error(
                    "Upload file is not an accepted type: "
                        + item.getName()
                        + " of type: "
                        + item.getContentType());
                addOperationResultMessage(
                    context,
                    "Upload file is not an accepted type: "
                        + item.getName()
                        + " of type: "
                        + item.getContentType());
              }
            }
          }
        }
      } catch (FileUploadException e) {
        _logger.error(e);
        addOperationResultMessage(context, "Unknown error in file upload: " + e.getMessage());
      }

      httpServletRequest.setAttribute(PAGE_PARAM, FILE_UPLOAD_PAGE);
    } else if (DELETE_UPLOAD_FILES.equals(action)) {
      String[] filesToDelete = httpServletRequest.getParameterValues(FILE_TO_DELETE);
      if (filesToDelete != null && filesToDelete.length > 0) {
        File deletedFile;
        for (int i = 0; i < filesToDelete.length; i++) {
          String fileToDelete = filesToDelete[i];
          deletedFile = new File(resourceDirectory, fileToDelete);
          if (!deletedFile.delete()) {
            _logger.debug("Unable to delete resource file: " + deletedFile.toString());
          }
        }

        addOperationResultMessage(
            context, "Deleted " + filesToDelete.length + " file(s) from resources directory");
      }

      httpServletRequest.setAttribute(PAGE_PARAM, FILE_UPLOAD_PAGE);
    }

    // Create a list of files in the user's resource directory
    Map resourceFilesMap = null;
    if (resourceDirectory.exists()) {
      File[] resourceFiles = resourceDirectory.listFiles();

      if (resourceFiles != null) {
        resourceFilesMap = new HashMap(resourceFiles.length);
        for (int i = 0; i < resourceFiles.length; i++) {
          File resourceFile = resourceFiles[i];
          resourceFilesMap.put(resourceFile.getName(), resourceFile.getName());
        }
      }
    } else {
      resourceFilesMap = new HashMap();
    }

    resourceFilesMap = new TreeMap(resourceFilesMap);
    context.put(PLUGIN_ADMIN_FILE_UPLOAD_FILES, resourceFilesMap);

    return entries;
  }
  /**
   * Process the blog entries
   *
   * @param httpServletRequest Request
   * @param httpServletResponse Response
   * @param user {@link org.blojsom.blog.BlogUser} instance
   * @param context Context
   * @param entries Blog entries retrieved for the particular request
   * @return Modified set of blog entries
   * @throws org.blojsom.plugin.BlojsomPluginException If there is an error processing the blog
   *     entries
   */
  public BlogEntry[] process(
      HttpServletRequest httpServletRequest,
      HttpServletResponse httpServletResponse,
      BlogUser user,
      Map context,
      BlogEntry[] entries)
      throws BlojsomPluginException {
    if (!authenticateUser(httpServletRequest, httpServletResponse, context, user)) {
      httpServletRequest.setAttribute(PAGE_PARAM, ADMIN_LOGIN_PAGE);

      return entries;
    }

    // Check to see the requesting user is an administrator
    if (!_administrators.containsKey(user.getId())) {
      _logger.debug("User: "******" is not a valid administrator");

      httpServletRequest.setAttribute(PAGE_PARAM, ADMIN_ADMINISTRATION_PAGE);
      return entries;
    }

    context.put(
        BLOJSOM_PLUGIN_EDIT_BLOG_USERS_MAP,
        Collections.unmodifiableMap(_blojsomConfiguration.getBlogUsers()));
    String action = BlojsomUtils.getRequestValue(ACTION_PARAM, httpServletRequest);
    if (BlojsomUtils.checkNullOrBlank(action)) {
      _logger.debug("User did not request edit action");
      httpServletRequest.setAttribute(PAGE_PARAM, ADMIN_ADMINISTRATION_PAGE);
    } else if (PAGE_ACTION.equals(action)) {
      _logger.debug("User requested edit blog users page");

      httpServletRequest.setAttribute(PAGE_PARAM, EDIT_BLOG_USERS_PAGE);
    } else if (DELETE_BLOG_USER_ACTION.equals(action)) {
      _logger.debug("User requested delete blog user action");

      String blogUserID = BlojsomUtils.getRequestValue(BLOG_USER_ID, httpServletRequest);
      if (BlojsomUtils.checkNullOrBlank(blogUserID)) {
        httpServletRequest.setAttribute(PAGE_PARAM, EDIT_BLOG_USERS_PAGE);
        return entries;
      } else {
        _logger.debug("Deleting user: "******"/");
        if (!BlojsomUtils.deleteDirectory(blogConfigurationDirectory)) {
          _logger.error(
              "Unable to remove blog configuration directory: "
                  + blogConfigurationDirectory.toString());
          addOperationResultMessage(
              context, "Unable to remove blog configuration for user: "******"Removed blog configuration directory: " + blogConfigurationDirectory.toString());
        }

        File blogDirectory = new File(_blogHomeBaseDirectory + blogUserID + "/");
        if (!BlojsomUtils.deleteDirectory(blogDirectory)) {
          _logger.error("Unable to remove blog directory for user: "******"Unable to remove blog directory for user: "******"Removed blog directory: " + blogDirectory.toString());
        }

        File blogResourcesDirectory =
            new File(
                _blojsomConfiguration.getInstallationDirectory()
                    + _blojsomConfiguration.getResourceDirectory()
                    + blogUserID
                    + "/");
        if (!BlojsomUtils.deleteDirectory(blogResourcesDirectory)) {
          _logger.error(
              "Unable to remove blog resource directory: " + blogResourcesDirectory.toString());
          addOperationResultMessage(
              context, "Unable to remove resources directory for user: "******"Removed blog resource directory: " + blogResourcesDirectory.toString());
        }

        writeBlojsomConfiguration();
        _logger.debug("Wrote new blojsom configuration after deleting user: "******"Deleted user: "******"User requested add blog user action");

      Map blogUsers = _blojsomConfiguration.getBlogUsers();
      String blogUserID = BlojsomUtils.getRequestValue(BLOG_USER_ID, httpServletRequest);

      if (BlojsomUtils.checkNullOrBlank(blogUserID)) { // Check that we got a blog user ID
        addOperationResultMessage(context, "No blog ID specified for adding a blog");
        httpServletRequest.setAttribute(PAGE_PARAM, EDIT_BLOG_USERS_PAGE);

        return entries;
      } else if (blogUsers.containsKey(blogUserID)) { // Check that the user does not already exist
        _logger.debug("User: "******" already exists");
        addOperationResultMessage(context, "Blog ID: " + blogUserID + " already exists");
        httpServletRequest.setAttribute(PAGE_PARAM, EDIT_BLOG_USERS_PAGE);

        return entries;
      } else { // Begin the process of adding a new user
        _logger.debug("Adding new user id: " + blogUserID);

        BlogUser blogUser = new BlogUser();
        blogUser.setId(blogUserID);

        File blogUserDirectory =
            new File(
                _blojsomConfiguration.getInstallationDirectory()
                    + _blojsomConfiguration.getBaseConfigurationDirectory()
                    + blogUserID);
        if (blogUserDirectory
            .exists()) { // Make sure that the blog user ID does not conflict with a directory
                         // underneath the installation directory
          _logger.debug("User directory already exists for blog user: "******"User directory already exists for blog ID: " + blogUserID);
          httpServletRequest.setAttribute(PAGE_PARAM, EDIT_BLOG_USERS_PAGE);

          return entries;
        } else { // Otherwise, check the authorization passwords match
          String blogUserPassword =
              BlojsomUtils.getRequestValue(BLOG_USER_PASSWORD, httpServletRequest);
          String blogUserPasswordCheck =
              BlojsomUtils.getRequestValue(BLOG_USER_PASSWORD_CHECK, httpServletRequest);
          String blogBaseURL = BlojsomUtils.getRequestValue(BLOG_BASE_URL_IP, httpServletRequest);
          String blogURL = BlojsomUtils.getRequestValue(BLOG_URL_IP, httpServletRequest);

          // Check for the blog and blog base URLs
          if (BlojsomUtils.checkNullOrBlank(blogURL)
              || BlojsomUtils.checkNullOrBlank(blogBaseURL)) {
            _logger.debug("No blog URL or base URL supplied");
            addOperationResultMessage(context, "No blog URL or base URL supplied");
            httpServletRequest.setAttribute(PAGE_PARAM, EDIT_BLOG_USERS_PAGE);

            return entries;
          } else {
            if (!blogURL.endsWith("/")) {
              blogURL += "/";
            }
            if (!blogBaseURL.endsWith("/")) {
              blogBaseURL += "/";
            }
          }

          // Check to see that the password and password check are equal
          if (!blogUserPassword.equals(blogUserPasswordCheck)) {
            _logger.debug("User password does not equal password check");
            addOperationResultMessage(context, "User password does not equal user password check");
            httpServletRequest.setAttribute(PAGE_PARAM, EDIT_BLOG_USERS_PAGE);

            return entries;
          } else { // And if they do, copy the bootstrap directory and initialize the user
            String bootstrap =
                _blojsomConfiguration.getInstallationDirectory()
                    + _blojsomConfiguration.getBaseConfigurationDirectory()
                    + _bootstrapDirectory
                    + "/";
            _logger.debug("Bootstrap directory: " + bootstrap);
            File bootstrapDirectory = new File(bootstrap);
            String userDirectory =
                _blojsomConfiguration.getInstallationDirectory()
                    + _blojsomConfiguration.getBaseConfigurationDirectory()
                    + blogUserID
                    + "/";
            _logger.debug("User directory: " + userDirectory);
            File newUserDirectory = new File(userDirectory);

            _logger.debug(
                "Copying bootstrap directory: "
                    + bootstrapDirectory.toString()
                    + " to target user directory: "
                    + newUserDirectory.toString());
            try {
              BlojsomUtils.copyDirectory(bootstrapDirectory, newUserDirectory);
            } catch (IOException e) {
              addOperationResultMessage(
                  context, "Unable to copy bootstrap directory. Check log files for error");
              httpServletRequest.setAttribute(PAGE_PARAM, EDIT_BLOG_USERS_PAGE);
              _logger.error(e);

              return entries;
            }

            try {
              // Configure blog
              Properties blogProperties =
                  BlojsomUtils.loadProperties(
                      _servletConfig,
                      _blojsomConfiguration.getBaseConfigurationDirectory()
                          + blogUserID
                          + '/'
                          + BLOG_DEFAULT_PROPERTIES);
              blogProperties.put(BLOG_HOME_IP, _blogHomeBaseDirectory + blogUserID);
              File blogHomeDirectory = new File(_blogHomeBaseDirectory + blogUserID);
              if (!blogHomeDirectory.mkdirs()) {
                _logger.error(
                    "Unable to create blog home directory: " + blogHomeDirectory.toString());
                addOperationResultMessage(
                    context, "Unable to create blog home directory for blog ID: " + blogUserID);
                httpServletRequest.setAttribute(PAGE_PARAM, EDIT_BLOG_USERS_PAGE);

                return entries;
              }
              blogProperties.put(BLOG_BASE_URL_IP, blogBaseURL);
              blogProperties.put(BLOG_URL_IP, blogURL);

              // Write out the blog configuration
              File blogConfigurationFile =
                  new File(
                      _blojsomConfiguration.getInstallationDirectory()
                          + _blojsomConfiguration.getBaseConfigurationDirectory()
                          + blogUserID
                          + '/'
                          + BLOG_DEFAULT_PROPERTIES);
              FileOutputStream fos = new FileOutputStream(blogConfigurationFile);
              blogProperties.store(fos, null);
              fos.close();
              _logger.debug(
                  "Wrote blog configuration information for new user: "******"Set authorization information for new user: "******"Wrote blog authorization information for new user: "******"Loaded flavor information for new user: "******"Added plugin chain: "
                          + plugin
                          + '='
                          + pluginProperties.getProperty(plugin)
                          + " for user: "******"Loaded plugin chain map for new user: "******"/");
            File bootstrapResourcesDirectory =
                new File(bootstrapDirectory, _blojsomConfiguration.getResourceDirectory());
            if (!blogResourcesDirectory.mkdirs()) {
              _logger.error(
                  "Unable to create blog resource directory: " + blogResourcesDirectory.toString());
            } else {
              _logger.debug("Added blog resource directory: " + blogResourcesDirectory.toString());
            }
            try {
              if (bootstrapResourcesDirectory.exists()) {
                BlojsomUtils.copyDirectory(bootstrapResourcesDirectory, blogResourcesDirectory);
              }

              // Cleanup the bootstrap resources directory
              File resourcesDirectoryToDelete =
                  new File(
                      _blojsomConfiguration.getInstallationDirectory()
                          + _blojsomConfiguration.getBaseConfigurationDirectory()
                          + blogUserID
                          + _blojsomConfiguration.getResourceDirectory());
              if (resourcesDirectoryToDelete.exists()) {
                BlojsomUtils.deleteDirectory(resourcesDirectoryToDelete);
              }
            } catch (IOException e) {
              _logger.error(e);
            }

            // Add the user to the global list of users
            _blojsomConfiguration.getBlogUsers().put(blogUserID, blogUser);
            writeBlojsomConfiguration();
            _logger.debug("Wrote new blojsom configuration after adding new user: "******"Added new blog: " + blogUserID);
          }
        }
      }
    }

    return entries;
  }
  /**
   * Process the blog entries
   *
   * @param httpServletRequest Request
   * @param httpServletResponse Response
   * @param user {@link BlogUser} instance
   * @param context Context
   * @param entries Blog entries retrieved for the particular request
   * @return Modified set of blog entries
   * @throws BlojsomPluginException If there is an error processing the blog entries
   */
  public BlogEntry[] process(
      HttpServletRequest httpServletRequest,
      HttpServletResponse httpServletResponse,
      BlogUser user,
      Map context,
      BlogEntry[] entries)
      throws BlojsomPluginException {
    if (!authenticateUser(httpServletRequest, httpServletResponse, context, user)) {
      httpServletRequest.setAttribute(PAGE_PARAM, ADMIN_LOGIN_PAGE);

      return entries;
    }

    Blog blog = user.getBlog();

    String action = BlojsomUtils.getRequestValue(ACTION_PARAM, httpServletRequest);
    if (BlojsomUtils.checkNullOrBlank(action)) {
      _logger.debug("User did not request edit action");
      httpServletRequest.setAttribute(PAGE_PARAM, ADMIN_ADMINISTRATION_PAGE);
    } else if (PAGE_ACTION.equals(action)) {
      _logger.debug("User requested edit categories page");
      httpServletRequest.setAttribute(PAGE_PARAM, EDIT_BLOG_CATEGORIES_PAGE);
    } else if (DELETE_BLOG_CATEGORY_ACTION.equals(action)) {
      _logger.debug("User request blog category delete action");
      String blogCategoryName =
          BlojsomUtils.getRequestValue(BLOG_CATEGORY_NAME, httpServletRequest);
      blogCategoryName = BlojsomUtils.normalize(blogCategoryName);

      File existingBlogCategory =
          new File(blog.getBlogHome() + "/" + BlojsomUtils.removeInitialSlash(blogCategoryName));
      if (!BlojsomUtils.deleteDirectory(existingBlogCategory)) {
        _logger.debug("Unable to delete blog category: " + existingBlogCategory.toString());
        addOperationResultMessage(context, "Unable to delete blog category: " + blogCategoryName);
      } else {
        _logger.debug("Deleted blog category: " + existingBlogCategory.toString());
        addOperationResultMessage(context, "Deleted blog category: " + blogCategoryName);
      }

      httpServletRequest.setAttribute(PAGE_PARAM, EDIT_BLOG_CATEGORIES_PAGE);
    } else if (EDIT_BLOG_CATEGORY_ACTION.equals(action)) {
      String blogCategoryName =
          BlojsomUtils.getRequestValue(BLOG_CATEGORY_NAME, httpServletRequest);
      blogCategoryName = BlojsomUtils.normalize(blogCategoryName);
      _logger.debug("Editing blog category: " + blogCategoryName);

      File existingBlogCategory =
          new File(blog.getBlogHome() + "/" + BlojsomUtils.removeInitialSlash(blogCategoryName));
      _logger.debug(
          "Retrieving blog properties from category directory: " + existingBlogCategory.toString());
      String[] propertiesExtensions = blog.getBlogPropertiesExtensions();
      File[] propertiesFiles =
          existingBlogCategory.listFiles(BlojsomUtils.getExtensionsFilter(propertiesExtensions));

      if (propertiesFiles != null && propertiesFiles.length > 0) {
        StringBuffer categoryPropertiesString = new StringBuffer();
        for (int i = 0; i < propertiesFiles.length; i++) {
          File propertiesFile = propertiesFiles[i];
          _logger.debug("Loading blog properties from file: " + propertiesFile.toString());
          BlojsomProperties categoryProperties = new BlojsomProperties();
          try {
            FileInputStream fis = new FileInputStream(propertiesFile);
            categoryProperties.load(fis);
            fis.close();

            Iterator keyIterator = categoryProperties.keySet().iterator();
            Object key;
            while (keyIterator.hasNext()) {
              key = keyIterator.next();
              categoryPropertiesString
                  .append(key.toString())
                  .append("=")
                  .append(categoryProperties.get(key))
                  .append("\r\n");
            }
          } catch (IOException e) {
            addOperationResultMessage(context, "Unable to load blog category: " + blogCategoryName);
            _logger.error(e);
          }
        }

        context.put(
            BLOJSOM_PLUGIN_EDIT_BLOG_CATEGORIES_CATEGORY_METADATA,
            categoryPropertiesString.toString());
      }

      context.put(BLOJSOM_PLUGIN_EDIT_BLOG_CATEGORIES_CATEGORY_NAME, blogCategoryName);
      httpServletRequest.setAttribute(PAGE_PARAM, EDIT_BLOG_CATEGORY_PAGE);
    } else if (ADD_BLOG_CATEGORY_ACTION.equals(action)
        || UPDATE_BLOG_CATEGORY_ACTION.equals(action)) {
      boolean isUpdatingCategory = UPDATE_BLOG_CATEGORY_ACTION.equals(action);

      String blogCategoryName =
          BlojsomUtils.getRequestValue(BLOG_CATEGORY_NAME, httpServletRequest);
      // Check for blank or null category
      if (BlojsomUtils.checkNullOrBlank(blogCategoryName)) {
        httpServletRequest.setAttribute(PAGE_PARAM, EDIT_BLOG_CATEGORIES_PAGE);
        addOperationResultMessage(context, "No blog category specified");
        return entries;
      }
      blogCategoryName = BlojsomUtils.normalize(blogCategoryName);

      if (!isUpdatingCategory) {
        _logger.debug("Adding blog category: " + blogCategoryName);
      } else {
        _logger.debug("Updating blog category: " + blogCategoryName);
      }

      String blogCategoryMetaData =
          BlojsomUtils.getRequestValue(BLOG_CATEGORY_META_DATA, httpServletRequest);
      if (blogCategoryMetaData == null) {
        blogCategoryMetaData = "";
      }

      if (!isUpdatingCategory) {
        _logger.debug("Adding blog category meta-data: " + blogCategoryMetaData);
      }

      // Separate the blog category meta-data into key/value pairs
      BufferedReader br = new BufferedReader(new StringReader(blogCategoryMetaData));
      String input;
      String[] splitInput;
      BlojsomProperties categoryMetaData = new BlojsomProperties(blog.getBlogFileEncoding());
      try {
        while ((input = br.readLine()) != null) {
          splitInput = input.split("=");
          if (splitInput.length == 2) {
            categoryMetaData.put(splitInput[0], splitInput[1]);
          }
        }
      } catch (IOException e) {
        addOperationResultMessage(context, "Unable to read category metadata from input");
        _logger.error(e);
      }

      File newBlogCategory =
          new File(blog.getBlogHome() + "/" + BlojsomUtils.removeInitialSlash(blogCategoryName));
      if (!isUpdatingCategory) {
        if (!newBlogCategory.mkdirs()) {
          _logger.error("Unable to add new blog category: " + blogCategoryName);
          addOperationResultMessage(
              context, "Unable to add new blog category: " + blogCategoryName);
          httpServletRequest.setAttribute(PAGE_PARAM, EDIT_BLOG_CATEGORIES_PAGE);

          return entries;
        } else {
          _logger.debug("Created blog directory: " + newBlogCategory.toString());
        }
      }

      File newBlogProperties = new File(newBlogCategory.getAbsolutePath() + "/blojsom.properties");
      try {
        FileOutputStream fos = new FileOutputStream(newBlogProperties);
        categoryMetaData.store(fos, null);
        fos.close();
        _logger.debug("Wrote blog properties to: " + newBlogProperties.toString());
      } catch (IOException e) {
        _logger.error(e);
      }

      if (!isUpdatingCategory) {
        _logger.debug("Successfully added new blog category: " + blogCategoryName);
        addOperationResultMessage(
            context, "Successfully added new blog category: " + blogCategoryName);
      } else {
        _logger.debug("Successfully updated blog category: " + blogCategoryName);
        addOperationResultMessage(
            context, "Successfully updated blog category: " + blogCategoryName);
      }

      httpServletRequest.setAttribute(PAGE_PARAM, ADMIN_ADMINISTRATION_PAGE);
    }

    return entries;
  }
  /**
   * Process the blog entries
   *
   * @param httpServletRequest Request
   * @param httpServletResponse Response
   * @param user {@link org.blojsom.blog.BlogUser} instance
   * @param context Context
   * @param entries Blog entries retrieved for the particular request
   * @return Modified set of blog entries
   * @throws BlojsomPluginException If there is an error processing the blog entries
   */
  public BlogEntry[] process(
      HttpServletRequest httpServletRequest,
      HttpServletResponse httpServletResponse,
      BlogUser user,
      Map context,
      BlogEntry[] entries)
      throws BlojsomPluginException {
    if (!authenticateUser(httpServletRequest, httpServletResponse, context, user)) {
      httpServletRequest.setAttribute(PAGE_PARAM, ADMIN_LOGIN_PAGE);

      return entries;
    }

    String username = getUsernameFromSession(httpServletRequest, user.getBlog());
    if (!checkPermission(user, null, username, EDIT_BLOG_ENTRIES_PERMISSION)) {
      httpServletRequest.setAttribute(PAGE_PARAM, ADMIN_ADMINISTRATION_PAGE);
      addOperationResultMessage(
          context,
          getAdminResource(
              FAILED_PERMISSION_EDIT_KEY,
              FAILED_PERMISSION_EDIT_KEY,
              user.getBlog().getBlogAdministrationLocale()));

      return entries;
    }

    String action = BlojsomUtils.getRequestValue(ACTION_PARAM, httpServletRequest);
    if (BlojsomUtils.checkNullOrBlank(action)) {
      _logger.debug("User did not request edit action");
      httpServletRequest.setAttribute(PAGE_PARAM, ADMIN_ADMINISTRATION_PAGE);
    } else if (PAGE_ACTION.equals(action)) {
      _logger.debug("User requested edit blog entries page");

      httpServletRequest.setAttribute(PAGE_PARAM, EDIT_BLOG_ENTRIES_PAGE);
    } else if (EDIT_BLOG_ENTRIES_ACTION.equals(action)) {
      _logger.debug("User requested edit blog entries list page");

      String blogCategoryName =
          BlojsomUtils.getRequestValue(BLOG_CATEGORY_NAME, httpServletRequest);
      blogCategoryName = BlojsomUtils.normalize(blogCategoryName);

      BlogCategory category;
      category = _fetcher.newBlogCategory();
      category.setCategory(blogCategoryName);
      category.setCategoryURL(
          user.getBlog().getBlogURL() + BlojsomUtils.removeInitialSlash(blogCategoryName));

      Map fetchMap = new HashMap();
      fetchMap.put(BlojsomFetcher.FETCHER_CATEGORY, category);
      fetchMap.put(BlojsomFetcher.FETCHER_NUM_POSTS_INTEGER, new Integer(-1));
      try {
        entries = _fetcher.fetchEntries(fetchMap, user);
        if (entries != null) {
          _logger.debug(
              "Retrieved " + entries.length + " entries from category: " + blogCategoryName);
          Arrays.sort(entries, BlojsomUtils.FILE_TIME_COMPARATOR);
        } else {
          _logger.debug("No entries found in category: " + blogCategoryName);
        }
      } catch (BlojsomFetcherException e) {
        _logger.error(e);
        entries = new BlogEntry[0];
      }

      context.put(BLOJSOM_PLUGIN_EDIT_BLOG_ENTRIES_CATEGORY, blogCategoryName);
      context.put(BLOJSOM_PLUGIN_EDIT_BLOG_ENTRIES_LIST, entries);
      httpServletRequest.setAttribute(PAGE_PARAM, EDIT_BLOG_ENTRIES_LIST_PAGE);
    } else if (EDIT_BLOG_ENTRY_ACTION.equals(action)) {
      _logger.debug("User requested edit blog entry action");

      String blogCategoryName =
          BlojsomUtils.getRequestValue(BLOG_CATEGORY_NAME, httpServletRequest);
      blogCategoryName = BlojsomUtils.normalize(blogCategoryName);
      String blogEntryId = BlojsomUtils.getRequestValue(BLOG_ENTRY_ID, httpServletRequest);
      _logger.debug("Blog entry id: " + blogEntryId);

      try {
        BlogEntry entry = BlojsomUtils.fetchEntry(_fetcher, user, blogCategoryName, blogEntryId);
        context.put(BLOJSOM_PLUGIN_EDIT_BLOG_ENTRIES_ENTRY, entry);

        _blojsomConfiguration
            .getEventBroadcaster()
            .processEvent(
                new ProcessBlogEntryEvent(
                    this,
                    new Date(),
                    entry,
                    user,
                    httpServletRequest,
                    httpServletResponse,
                    context));
      } catch (BlojsomFetcherException e) {
        _logger.error(e);
        addOperationResultMessage(
            context,
            formatAdminResource(
                FAILED_RETRIEVE_BLOG_ENTRY_KEY,
                FAILED_RETRIEVE_BLOG_ENTRY_KEY,
                user.getBlog().getBlogAdministrationLocale(),
                new Object[] {blogEntryId}));
        entries = new BlogEntry[0];
      }

      context.put(
          BLOJSOM_PLUGIN_EDIT_BLOG_ENTRIES_CATEGORY, BlojsomUtils.addSlashes(blogCategoryName));
      httpServletRequest.setAttribute(PAGE_PARAM, EDIT_BLOG_ENTRY_PAGE);
    } else if (UPDATE_BLOG_ENTRY_ACTION.equals(action)) {
      _logger.debug("User requested update blog entry action");

      Blog blog = user.getBlog();
      String blogCategoryName =
          BlojsomUtils.getRequestValue(BLOG_CATEGORY_NAME, httpServletRequest);
      blogCategoryName = BlojsomUtils.normalize(blogCategoryName);
      String updatedBlogCategoryName =
          BlojsomUtils.getRequestValue(UPDATED_BLOG_CATEGORY_NAME, httpServletRequest);
      updatedBlogCategoryName = BlojsomUtils.normalize(updatedBlogCategoryName);
      String blogEntryId = BlojsomUtils.getRequestValue(BLOG_ENTRY_ID, httpServletRequest);
      String blogEntryDescription =
          BlojsomUtils.getRequestValue(BLOG_ENTRY_DESCRIPTION, httpServletRequest);
      String blogEntryTitle = BlojsomUtils.getRequestValue(BLOG_ENTRY_TITLE, httpServletRequest);
      if (BlojsomUtils.checkNullOrBlank(blogEntryTitle)) {
        blogEntryDescription = BlojsomUtils.LINE_SEPARATOR + blogEntryDescription;
      }
      String allowComments =
          BlojsomUtils.getRequestValue(BLOG_METADATA_COMMENTS_DISABLED, httpServletRequest);
      String allowTrackbacks =
          BlojsomUtils.getRequestValue(BLOG_METADATA_TRACKBACKS_DISABLED, httpServletRequest);
      String blogTrackbackURLs =
          BlojsomUtils.getRequestValue(BLOG_TRACKBACK_URLS, httpServletRequest);
      String pingBlogURLS = BlojsomUtils.getRequestValue(PING_BLOG_URLS, httpServletRequest);
      String sendPingbacks =
          BlojsomUtils.getRequestValue(
              PingbackPlugin.PINGBACK_PLUGIN_METADATA_SEND_PINGBACKS, httpServletRequest);

      _logger.debug("Blog entry id: " + blogEntryId);

      try {
        BlogEntry entryToUpdate =
            BlojsomUtils.fetchEntry(_fetcher, user, blogCategoryName, blogEntryId);
        entryToUpdate.setTitle(blogEntryTitle);
        entryToUpdate.setDescription(blogEntryDescription);

        boolean movingCategory = !blogCategoryName.equals(updatedBlogCategoryName);

        Map entryMetaData = entryToUpdate.getMetaData();
        if (entryMetaData == null) {
          entryMetaData = new HashMap();
        }

        if (!BlojsomUtils.checkNullOrBlank(allowComments)) {
          entryMetaData.put(BLOG_METADATA_COMMENTS_DISABLED, "y");
        } else {
          entryMetaData.remove(BLOG_METADATA_COMMENTS_DISABLED);
        }

        if (!BlojsomUtils.checkNullOrBlank(allowTrackbacks)) {
          entryMetaData.put(BLOG_METADATA_TRACKBACKS_DISABLED, "y");
        } else {
          entryMetaData.remove(BLOG_METADATA_TRACKBACKS_DISABLED);
        }

        if (BlojsomUtils.checkNullOrBlank(pingBlogURLS)) {
          entryMetaData.put(WeblogsPingPlugin.NO_PING_WEBLOGS_METADATA, "true");
        } else {
          entryMetaData.remove(WeblogsPingPlugin.NO_PING_WEBLOGS_METADATA);
        }

        if (!BlojsomUtils.checkNullOrBlank(sendPingbacks)) {
          entryMetaData.put(PingbackPlugin.PINGBACK_PLUGIN_METADATA_SEND_PINGBACKS, "true");
        } else {
          entryMetaData.remove(PingbackPlugin.PINGBACK_PLUGIN_METADATA_SEND_PINGBACKS);
        }

        String entryPublishDateTime = httpServletRequest.getParameter(BLOG_ENTRY_PUBLISH_DATETIME);
        if (!BlojsomUtils.checkNullOrBlank(entryPublishDateTime)) {
          SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
          try {
            Date publishDateTime = simpleDateFormat.parse(entryPublishDateTime);
            _logger.debug("Publishing blog entry at: " + publishDateTime.toString());
            entryMetaData.put(
                BlojsomMetaDataConstants.BLOG_ENTRY_METADATA_TIMESTAMP,
                Long.toString(publishDateTime.getTime()));
          } catch (ParseException e) {
            _logger.error(e);
          }
        }

        entryToUpdate.setMetaData(entryMetaData);

        _blojsomConfiguration
            .getEventBroadcaster()
            .processEvent(
                new ProcessBlogEntryEvent(
                    this,
                    new Date(),
                    entryToUpdate,
                    user,
                    httpServletRequest,
                    httpServletResponse,
                    context));

        if (movingCategory) {
          _logger.debug("Moving entry from " + blogCategoryName + " to " + updatedBlogCategoryName);
          BlogEntry movedEntry = _fetcher.newBlogEntry();

          BlogCategory category;
          category = _fetcher.newBlogCategory();
          category.setCategory(updatedBlogCategoryName);
          category.setCategoryURL(
              user.getBlog().getBlogURL()
                  + BlojsomUtils.removeInitialSlash(updatedBlogCategoryName));

          movedEntry.setTitle(blogEntryTitle);
          movedEntry.setCategory(updatedBlogCategoryName);
          movedEntry.setDescription(blogEntryDescription);
          movedEntry.setBlogCategory(category);
          movedEntry.setMetaData(entryMetaData);

          movedEntry.setComments(entryToUpdate.getComments());
          movedEntry.setTrackbacks(entryToUpdate.getTrackbacks());
          movedEntry.setPingbacks(entryToUpdate.getPingbacks());

          movedEntry.save(user);

          _logger.debug("Moving " + entryToUpdate.getNumComments() + " comments");
          List comments = entryToUpdate.getComments();
          for (int i = 0; i < comments.size(); i++) {
            BlogComment blogComment = (BlogComment) comments.get(i);
            try {
              BlogComment movedComment = _fetcher.newBlogComment();
              movedComment.setAuthor(blogComment.getAuthor());
              movedComment.setAuthorEmail(blogComment.getAuthorEmail());
              movedComment.setAuthorURL(blogComment.getAuthorURL());
              movedComment.setBlogEntry(movedEntry);
              movedComment.setComment(blogComment.getComment());
              movedComment.setMetaData(blogComment.getMetaData());
              movedComment.setId(blogComment.getId());
              movedComment.setCommentDateLong(blogComment.getCommentDateLong());

              movedComment.save(user);
              blogComment.delete(user);
            } catch (BlojsomException e) {
              _logger.error(e);
            }
          }

          _logger.debug("Moving " + entryToUpdate.getNumTrackbacks() + " trackbacks");
          List trackbacks = entryToUpdate.getTrackbacks();
          for (int i = 0; i < trackbacks.size(); i++) {
            Trackback trackback = (Trackback) trackbacks.get(i);
            try {
              Trackback movedTrackback = _fetcher.newTrackback();
              movedTrackback.setBlogEntry(movedEntry);
              movedTrackback.setBlogName(trackback.getBlogName());
              movedTrackback.setExcerpt(trackback.getExcerpt());
              movedTrackback.setId(trackback.getId());
              movedTrackback.setMetaData(trackback.getMetaData());
              movedTrackback.setTitle(trackback.getTitle());
              movedTrackback.setUrl(trackback.getUrl());
              movedTrackback.setTrackbackDateLong(trackback.getTrackbackDateLong());

              movedTrackback.save(user);
              trackback.delete(user);
            } catch (BlojsomException e) {
              _logger.error(e);
            }
          }

          _logger.debug("Moving " + entryToUpdate.getNumPingbacks() + " pingbacks");
          List pingbacks = entryToUpdate.getPingbacks();
          for (int i = 0; i < pingbacks.size(); i++) {
            Pingback pingback = (Pingback) pingbacks.get(i);
            try {
              Pingback movedPingback = _fetcher.newPingback();
              movedPingback.setBlogEntry(movedEntry);
              movedPingback.setBlogName(pingback.getBlogName());
              movedPingback.setExcerpt(pingback.getExcerpt());
              movedPingback.setId(pingback.getId());
              movedPingback.setMetaData(pingback.getMetaData());
              movedPingback.setTitle(pingback.getTitle());
              movedPingback.setUrl(pingback.getUrl());
              movedPingback.setTrackbackDateLong(pingback.getTrackbackDateLong());

              movedPingback.save(user);
              pingback.delete(user);
            } catch (BlojsomException e) {
              _logger.error(e);
            }
          }

          movedEntry.load(user);
          entryToUpdate.delete(user);
          entryToUpdate = movedEntry;
        } else {
          entryToUpdate.save(user);
        }

        entryToUpdate.load(user);

        _logger.debug("Updated blog entry: " + entryToUpdate.getLink());

        StringBuffer entryLink = new StringBuffer();
        entryLink
            .append("<a href=\"")
            .append(user.getBlog().getBlogURL())
            .append(BlojsomUtils.removeInitialSlash(entryToUpdate.getCategory()))
            .append("?")
            .append(PERMALINK_PARAM)
            .append("=")
            .append(entryToUpdate.getPermalink())
            .append("\">")
            .append(entryToUpdate.getTitle())
            .append("</a>");
        addOperationResultMessage(
            context,
            formatAdminResource(
                UPDATED_BLOG_ENTRY_KEY,
                UPDATED_BLOG_ENTRY_KEY,
                user.getBlog().getBlogAdministrationLocale(),
                new Object[] {entryLink.toString()}));

        UpdatedBlogEntryEvent updateEvent =
            new UpdatedBlogEntryEvent(this, new Date(), entryToUpdate, user);
        _blojsomConfiguration.getEventBroadcaster().broadcastEvent(updateEvent);

        // Send trackback pings
        if (!BlojsomUtils.checkNullOrBlank(blogTrackbackURLs)) {
          sendTrackbackPings(blog, entryToUpdate, blogTrackbackURLs);
        }

        httpServletRequest.setAttribute(PAGE_PARAM, EDIT_BLOG_ENTRY_PAGE);
        context.put(BLOJSOM_PLUGIN_EDIT_BLOG_ENTRIES_ENTRY, entryToUpdate);

        if (movingCategory) {
          blogCategoryName = updatedBlogCategoryName;
        }
        blogCategoryName = BlojsomUtils.addSlashes(blogCategoryName);
        context.put(BLOJSOM_PLUGIN_EDIT_BLOG_ENTRIES_CATEGORY, blogCategoryName);
      } catch (BlojsomFetcherException e) {
        _logger.error(e);
        addOperationResultMessage(
            context,
            formatAdminResource(
                FAILED_RETRIEVE_BLOG_ENTRY_KEY,
                FAILED_RETRIEVE_BLOG_ENTRY_KEY,
                user.getBlog().getBlogAdministrationLocale(),
                new Object[] {blogEntryId}));
        httpServletRequest.setAttribute(PAGE_PARAM, EDIT_BLOG_ENTRIES_PAGE);
        entries = new BlogEntry[0];
      } catch (BlojsomException e) {
        _logger.error(e);
        addOperationResultMessage(
            context,
            formatAdminResource(
                FAILED_RETRIEVE_BLOG_ENTRY_KEY,
                FAILED_RETRIEVE_BLOG_ENTRY_KEY,
                user.getBlog().getBlogAdministrationLocale(),
                new Object[] {blogEntryId}));
        entries = new BlogEntry[0];
        httpServletRequest.setAttribute(PAGE_PARAM, EDIT_BLOG_ENTRIES_PAGE);
      }
    } else if (DELETE_BLOG_ENTRY_ACTION.equals(action)) {
      _logger.debug("User requested delete blog entry action");

      String blogCategoryName =
          BlojsomUtils.getRequestValue(BLOG_CATEGORY_NAME, httpServletRequest);
      blogCategoryName = BlojsomUtils.normalize(blogCategoryName);
      String blogEntryId = BlojsomUtils.getRequestValue(BLOG_ENTRY_ID, httpServletRequest);
      _logger.debug("Blog entry id: " + blogEntryId);

      try {
        BlogEntry entryToDelete =
            BlojsomUtils.fetchEntry(_fetcher, user, blogCategoryName, blogEntryId);
        String title = entryToDelete.getTitle();
        entryToDelete.delete(user);
        addOperationResultMessage(
            context,
            formatAdminResource(
                DELETED_BLOG_ENTRY_KEY,
                DELETED_BLOG_ENTRY_KEY,
                user.getBlog().getBlogAdministrationLocale(),
                new Object[] {title}));
        DeletedBlogEntryEvent deleteEvent =
            new DeletedBlogEntryEvent(this, new Date(), entryToDelete, user);
        _blojsomConfiguration.getEventBroadcaster().broadcastEvent(deleteEvent);
      } catch (BlojsomFetcherException e) {
        _logger.error(e);
        addOperationResultMessage(
            context,
            formatAdminResource(
                FAILED_DELETE_BLOG_ENTRY_KEY,
                FAILED_DELETE_BLOG_ENTRY_KEY,
                user.getBlog().getBlogAdministrationLocale(),
                new Object[] {blogEntryId}));
        entries = new BlogEntry[0];
      } catch (BlojsomException e) {
        _logger.error(e);
        addOperationResultMessage(
            context,
            formatAdminResource(
                FAILED_DELETE_BLOG_ENTRY_KEY,
                FAILED_DELETE_BLOG_ENTRY_KEY,
                user.getBlog().getBlogAdministrationLocale(),
                new Object[] {blogEntryId}));
        entries = new BlogEntry[0];
      }

      httpServletRequest.setAttribute(PAGE_PARAM, EDIT_BLOG_ENTRIES_PAGE);
    } else if (NEW_BLOG_ENTRY_ACTION.equals(action)) {
      _logger.debug("User requested new blog entry action");

      String blogCategoryName =
          BlojsomUtils.getRequestValue(BLOG_CATEGORY_NAME, httpServletRequest);
      blogCategoryName = BlojsomUtils.normalize(blogCategoryName);

      _blojsomConfiguration
          .getEventBroadcaster()
          .processEvent(
              new ProcessBlogEntryEvent(
                  this, new Date(), null, user, httpServletRequest, httpServletResponse, context));

      context.put(BLOJSOM_PLUGIN_EDIT_BLOG_ENTRIES_CATEGORY, blogCategoryName);
      httpServletRequest.setAttribute(PAGE_PARAM, ADD_BLOG_ENTRY_PAGE);
    } else if (ADD_BLOG_ENTRY_ACTION.equals(action)) {
      _logger.debug("User requested add blog entry action");
      Blog blog = user.getBlog();

      String blogCategoryName =
          BlojsomUtils.getRequestValue(BLOG_CATEGORY_NAME, httpServletRequest);
      blogCategoryName = BlojsomUtils.normalize(blogCategoryName);
      if (!blogCategoryName.endsWith("/")) {
        blogCategoryName += "/";
      }
      String blogEntryDescription =
          BlojsomUtils.getRequestValue(BLOG_ENTRY_DESCRIPTION, httpServletRequest);
      String blogEntryTitle = BlojsomUtils.getRequestValue(BLOG_ENTRY_TITLE, httpServletRequest);

      if (BlojsomUtils.checkNullOrBlank(blogEntryTitle)
          && BlojsomUtils.checkNullOrBlank(blogEntryDescription)) {
        httpServletRequest.setAttribute(PAGE_PARAM, ADD_BLOG_ENTRY_PAGE);
        _blojsomConfiguration
            .getEventBroadcaster()
            .processEvent(
                new ProcessBlogEntryEvent(
                    this,
                    new Date(),
                    null,
                    user,
                    httpServletRequest,
                    httpServletResponse,
                    context));

        addOperationResultMessage(
            context,
            getAdminResource(
                BLANK_ENTRY_KEY, BLANK_ENTRY_KEY, user.getBlog().getBlogAdministrationLocale()));

        return entries;
      }

      if (BlojsomUtils.checkNullOrBlank(blogEntryTitle)) {
        blogEntryDescription = BlojsomUtils.LINE_SEPARATOR + blogEntryDescription;
      }
      String allowComments =
          BlojsomUtils.getRequestValue(BLOG_METADATA_COMMENTS_DISABLED, httpServletRequest);
      String allowTrackbacks =
          BlojsomUtils.getRequestValue(BLOG_METADATA_TRACKBACKS_DISABLED, httpServletRequest);
      String blogTrackbackURLs =
          BlojsomUtils.getRequestValue(BLOG_TRACKBACK_URLS, httpServletRequest);
      String proposedBlogFilename =
          BlojsomUtils.getRequestValue(BLOG_ENTRY_PROPOSED_NAME, httpServletRequest);
      String pingBlogURLS = BlojsomUtils.getRequestValue(PING_BLOG_URLS, httpServletRequest);
      String sendPingbacks =
          BlojsomUtils.getRequestValue(
              PingbackPlugin.PINGBACK_PLUGIN_METADATA_SEND_PINGBACKS, httpServletRequest);

      BlogCategory category;
      category = _fetcher.newBlogCategory();
      category.setCategory(blogCategoryName);
      category.setCategoryURL(
          user.getBlog().getBlogURL() + BlojsomUtils.removeInitialSlash(blogCategoryName));

      BlogEntry entry;
      entry = _fetcher.newBlogEntry();
      entry.setTitle(blogEntryTitle);
      entry.setCategory(blogCategoryName);
      entry.setDescription(blogEntryDescription);
      entry.setBlogCategory(category);

      Map entryMetaData = new HashMap();
      username =
          (String)
              httpServletRequest
                  .getSession()
                  .getAttribute(
                      user.getBlog().getBlogAdminURL() + "_" + BLOJSOM_ADMIN_PLUGIN_USERNAME_KEY);
      entryMetaData.put(BlojsomMetaDataConstants.BLOG_ENTRY_METADATA_AUTHOR, username);

      String entryPublishDateTime = httpServletRequest.getParameter(BLOG_ENTRY_PUBLISH_DATETIME);
      if (!BlojsomUtils.checkNullOrBlank(entryPublishDateTime)) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
        try {
          Date publishDateTime = simpleDateFormat.parse(entryPublishDateTime);
          _logger.debug("Publishing blog entry at: " + publishDateTime.toString());
          entryMetaData.put(
              BlojsomMetaDataConstants.BLOG_ENTRY_METADATA_TIMESTAMP,
              Long.toString(publishDateTime.getTime()));
        } catch (ParseException e) {
          _logger.error(e);
          entryMetaData.put(
              BlojsomMetaDataConstants.BLOG_ENTRY_METADATA_TIMESTAMP,
              Long.toString(new Date().getTime()));
        }
      } else {
        entryMetaData.put(
            BlojsomMetaDataConstants.BLOG_ENTRY_METADATA_TIMESTAMP,
            Long.toString(new Date().getTime()));
      }

      if (!BlojsomUtils.checkNullOrBlank(allowComments)) {
        entryMetaData.put(BLOG_METADATA_COMMENTS_DISABLED, "y");
      }

      if (!BlojsomUtils.checkNullOrBlank(allowTrackbacks)) {
        entryMetaData.put(BLOG_METADATA_TRACKBACKS_DISABLED, "y");
      }

      if (BlojsomUtils.checkNullOrBlank(pingBlogURLS)) {
        entryMetaData.put(WeblogsPingPlugin.NO_PING_WEBLOGS_METADATA, "true");
      }

      if (!BlojsomUtils.checkNullOrBlank(sendPingbacks)) {
        entryMetaData.put(PingbackPlugin.PINGBACK_PLUGIN_METADATA_SEND_PINGBACKS, "true");
      }

      entry.setMetaData(entryMetaData);

      try {
        _blojsomConfiguration
            .getEventBroadcaster()
            .processEvent(
                new ProcessBlogEntryEvent(
                    this,
                    new Date(),
                    entry,
                    user,
                    httpServletRequest,
                    httpServletResponse,
                    context));

        entry.save(user);
        entry.load(user);

        StringBuffer entryLink = new StringBuffer();
        entry.setLink(
            user.getBlog().getBlogURL()
                + BlojsomUtils.removeInitialSlash(entry.getCategory())
                + "?"
                + PERMALINK_PARAM
                + "="
                + entry.getPermalink());
        entryLink
            .append("<a href=\"")
            .append(entry.getLink())
            .append("\">")
            .append(entry.getTitle())
            .append("</a>");
        addOperationResultMessage(
            context,
            formatAdminResource(
                ADDED_BLOG_ENTRY_KEY,
                ADDED_BLOG_ENTRY_KEY,
                user.getBlog().getBlogAdministrationLocale(),
                new Object[] {entryLink.toString()}));

        AddBlogEntryEvent addEvent = new AddBlogEntryEvent(this, new Date(), entry, user);
        _blojsomConfiguration.getEventBroadcaster().broadcastEvent(addEvent);
      } catch (BlojsomException e) {
        _logger.error(e);
        addOperationResultMessage(
            context,
            formatAdminResource(
                FAILED_ADD_BLOG_ENTRY_KEY,
                FAILED_ADD_BLOG_ENTRY_KEY,
                user.getBlog().getBlogAdministrationLocale(),
                new Object[] {blogCategoryName}));
      }

      // Send trackback pings
      if (!BlojsomUtils.checkNullOrBlank(blogTrackbackURLs)) {
        sendTrackbackPings(blog, entry, blogTrackbackURLs);
      }

      httpServletRequest.setAttribute(PAGE_PARAM, EDIT_BLOG_ENTRY_ACTION);
      context.put(BLOJSOM_PLUGIN_EDIT_BLOG_ENTRIES_ENTRY, entry);
      context.put(BLOJSOM_PLUGIN_EDIT_BLOG_ENTRIES_CATEGORY, blogCategoryName);
    } else if (DELETE_BLOG_COMMENTS.equals(action)) {
      _logger.debug("User requested delete blog comments action");

      String blogCategoryName =
          BlojsomUtils.getRequestValue(BLOG_CATEGORY_NAME, httpServletRequest);
      blogCategoryName = BlojsomUtils.normalize(blogCategoryName);
      String blogEntryId = BlojsomUtils.getRequestValue(BLOG_ENTRY_ID, httpServletRequest);
      try {
        blogEntryId = URLDecoder.decode(blogEntryId, UTF8);
      } catch (UnsupportedEncodingException e) {
        _logger.error(e);
      }
      _logger.debug("Blog entry id: " + blogEntryId);

      BlogCategory category;
      category = _fetcher.newBlogCategory();
      category.setCategory(blogCategoryName);
      category.setCategoryURL(
          user.getBlog().getBlogURL() + BlojsomUtils.removeInitialSlash(blogCategoryName));

      Map fetchMap = new HashMap();
      fetchMap.put(BlojsomFetcher.FETCHER_CATEGORY, category);
      fetchMap.put(BlojsomFetcher.FETCHER_PERMALINK, blogEntryId);
      try {
        entries = _fetcher.fetchEntries(fetchMap, user);
        if (entries != null) {
          _logger.debug(
              "Retrieved " + entries.length + " entries from category: " + blogCategoryName);
          BlogEntry entryToUpdate = entries[0];

          String[] blogCommentIDs = httpServletRequest.getParameterValues(BLOG_COMMENT_ID);
          if (blogCommentIDs != null && blogCommentIDs.length > 0) {
            for (int i = 0; i < blogCommentIDs.length; i++) {
              String blogCommentID = blogCommentIDs[i];
              BlogComment[] blogComments = entryToUpdate.getCommentsAsArray();
              for (int j = 0; j < blogComments.length; j++) {
                BlogComment blogComment = blogComments[j];
                if (blogComment.getId().equals(blogCommentID)) {
                  try {
                    blogComment.delete(user);

                    _blojsomConfiguration
                        .getEventBroadcaster()
                        .broadcastEvent(
                            new CommentDeletedEvent(this, new Date(), blogComment, user));
                  } catch (BlojsomException e) {
                    _logger.error(e);
                  }
                }
              }
            }

            addOperationResultMessage(
                context,
                formatAdminResource(
                    DELETED_COMMENTS_KEY,
                    DELETED_COMMENTS_KEY,
                    user.getBlog().getBlogAdministrationLocale(),
                    new Object[] {new Integer(blogCommentIDs.length)}));

            entries = _fetcher.fetchEntries(fetchMap, user);
            entryToUpdate = entries[0];
          }

          context.put(BLOJSOM_PLUGIN_EDIT_BLOG_ENTRIES_ENTRY, entryToUpdate);
          context.put(BLOJSOM_PLUGIN_EDIT_BLOG_ENTRIES_CATEGORY, blogCategoryName);
        }
      } catch (BlojsomFetcherException e) {
        _logger.error(e);
      }

      httpServletRequest.setAttribute(PAGE_PARAM, EDIT_BLOG_ENTRY_PAGE);
    } else if (APPROVE_BLOG_COMMENTS.equals(action)) {
      _logger.debug("User requested approve blog comments action");

      String blogCategoryName =
          BlojsomUtils.getRequestValue(BLOG_CATEGORY_NAME, httpServletRequest);
      blogCategoryName = BlojsomUtils.normalize(blogCategoryName);
      String blogEntryId = BlojsomUtils.getRequestValue(BLOG_ENTRY_ID, httpServletRequest);
      try {
        blogEntryId = URLDecoder.decode(blogEntryId, UTF8);
      } catch (UnsupportedEncodingException e) {
        _logger.error(e);
      }
      _logger.debug("Blog entry id: " + blogEntryId);

      BlogCategory category;
      category = _fetcher.newBlogCategory();
      category.setCategory(blogCategoryName);
      category.setCategoryURL(
          user.getBlog().getBlogURL() + BlojsomUtils.removeInitialSlash(blogCategoryName));

      Map fetchMap = new HashMap();
      fetchMap.put(BlojsomFetcher.FETCHER_CATEGORY, category);
      fetchMap.put(BlojsomFetcher.FETCHER_PERMALINK, blogEntryId);
      try {
        entries = _fetcher.fetchEntries(fetchMap, user);
        if (entries != null) {
          _logger.debug(
              "Retrieved " + entries.length + " entries from category: " + blogCategoryName);
          BlogEntry entryToUpdate = entries[0];

          String[] blogCommentIDs = httpServletRequest.getParameterValues(BLOG_COMMENT_ID);
          if (blogCommentIDs != null && blogCommentIDs.length > 0) {
            for (int i = 0; i < blogCommentIDs.length; i++) {
              String blogCommentID = blogCommentIDs[i];
              BlogComment[] blogComments = entryToUpdate.getCommentsAsArray();

              for (int j = 0; j < blogComments.length; j++) {
                BlogComment blogComment = blogComments[j];
                if (blogComment.getId().equals(blogCommentID)) {
                  Map blogCommentMetaData = blogComment.getMetaData();

                  blogCommentMetaData.put(
                      CommentModerationPlugin.BLOJSOM_COMMENT_MODERATION_PLUGIN_APPROVED, "true");
                  try {
                    blogComment.save(user);

                    _blojsomConfiguration
                        .getEventBroadcaster()
                        .broadcastEvent(
                            new CommentApprovedEvent(this, new Date(), blogComment, user));
                  } catch (BlojsomException e) {
                    _logger.error(e);
                  }
                }
              }
            }

            addOperationResultMessage(
                context,
                formatAdminResource(
                    APPROVED_COMMENTS_KEY,
                    APPROVED_COMMENTS_KEY,
                    user.getBlog().getBlogAdministrationLocale(),
                    new Object[] {new Integer(blogCommentIDs.length)}));

            entries = _fetcher.fetchEntries(fetchMap, user);
            entryToUpdate = entries[0];
          }

          context.put(BLOJSOM_PLUGIN_EDIT_BLOG_ENTRIES_ENTRY, entryToUpdate);
          context.put(BLOJSOM_PLUGIN_EDIT_BLOG_ENTRIES_CATEGORY, blogCategoryName);
        }
      } catch (BlojsomFetcherException e) {
        _logger.error(e);
      }

      httpServletRequest.setAttribute(PAGE_PARAM, EDIT_BLOG_ENTRY_PAGE);
    } else if (DELETE_BLOG_TRACKBACKS.equals(action)) {
      _logger.debug("User requested delete blog trackbacks action");

      String blogCategoryName =
          BlojsomUtils.getRequestValue(BLOG_CATEGORY_NAME, httpServletRequest);
      blogCategoryName = BlojsomUtils.normalize(blogCategoryName);
      String blogEntryId = BlojsomUtils.getRequestValue(BLOG_ENTRY_ID, httpServletRequest);
      try {
        blogEntryId = URLDecoder.decode(blogEntryId, UTF8);
      } catch (UnsupportedEncodingException e) {
        _logger.error(e);
      }
      _logger.debug("Blog entry id: " + blogEntryId);

      BlogCategory category;
      category = _fetcher.newBlogCategory();
      category.setCategory(blogCategoryName);
      category.setCategoryURL(
          user.getBlog().getBlogURL() + BlojsomUtils.removeInitialSlash(blogCategoryName));

      Map fetchMap = new HashMap();
      fetchMap.put(BlojsomFetcher.FETCHER_CATEGORY, category);
      fetchMap.put(BlojsomFetcher.FETCHER_PERMALINK, blogEntryId);
      try {
        entries = _fetcher.fetchEntries(fetchMap, user);
        if (entries != null) {
          _logger.debug(
              "Retrieved " + entries.length + " entries from category: " + blogCategoryName);
          BlogEntry entryToUpdate = entries[0];

          String[] blogTrackbackIDs = httpServletRequest.getParameterValues(BLOG_TRACKBACK_ID);
          if (blogTrackbackIDs != null && blogTrackbackIDs.length > 0) {
            for (int i = 0; i < blogTrackbackIDs.length; i++) {
              String blogTrackbackID = blogTrackbackIDs[i];
              Trackback[] trackbacks = entryToUpdate.getTrackbacksAsArray();

              for (int j = 0; j < trackbacks.length; j++) {
                Trackback trackback = trackbacks[j];
                if (trackback.getId().equals(blogTrackbackID)) {
                  try {
                    trackback.delete(user);

                    _blojsomConfiguration
                        .getEventBroadcaster()
                        .broadcastEvent(
                            new TrackbackDeletedEvent(this, new Date(), trackback, user));
                  } catch (BlojsomException e) {
                    _logger.error(e);
                  }
                }
              }
            }

            addOperationResultMessage(
                context,
                formatAdminResource(
                    DELETED_TRACKBACKS_KEY,
                    DELETED_TRACKBACKS_KEY,
                    user.getBlog().getBlogAdministrationLocale(),
                    new Object[] {new Integer(blogTrackbackIDs.length)}));

            entries = _fetcher.fetchEntries(fetchMap, user);
            entryToUpdate = entries[0];
          }

          context.put(BLOJSOM_PLUGIN_EDIT_BLOG_ENTRIES_ENTRY, entryToUpdate);
          context.put(BLOJSOM_PLUGIN_EDIT_BLOG_ENTRIES_CATEGORY, blogCategoryName);
        }
      } catch (BlojsomFetcherException e) {
        _logger.error(e);
      }

      httpServletRequest.setAttribute(PAGE_PARAM, EDIT_BLOG_ENTRY_PAGE);

    } else if (APPROVE_BLOG_TRACKBACKS.equals(action)) {
      _logger.debug("User requested approve blog trackbacks action");

      String blogCategoryName =
          BlojsomUtils.getRequestValue(BLOG_CATEGORY_NAME, httpServletRequest);
      blogCategoryName = BlojsomUtils.normalize(blogCategoryName);
      String blogEntryId = BlojsomUtils.getRequestValue(BLOG_ENTRY_ID, httpServletRequest);
      try {
        blogEntryId = URLDecoder.decode(blogEntryId, UTF8);
      } catch (UnsupportedEncodingException e) {
        _logger.error(e);
      }
      _logger.debug("Blog entry id: " + blogEntryId);

      BlogCategory category;
      category = _fetcher.newBlogCategory();
      category.setCategory(blogCategoryName);
      category.setCategoryURL(
          user.getBlog().getBlogURL() + BlojsomUtils.removeInitialSlash(blogCategoryName));

      Map fetchMap = new HashMap();
      fetchMap.put(BlojsomFetcher.FETCHER_CATEGORY, category);
      fetchMap.put(BlojsomFetcher.FETCHER_PERMALINK, blogEntryId);
      try {
        entries = _fetcher.fetchEntries(fetchMap, user);
        if (entries != null) {
          _logger.debug(
              "Retrieved " + entries.length + " entries from category: " + blogCategoryName);
          BlogEntry entryToUpdate = entries[0];

          String[] blogTrackbackIDs = httpServletRequest.getParameterValues(BLOG_TRACKBACK_ID);
          if (blogTrackbackIDs != null && blogTrackbackIDs.length > 0) {
            for (int i = 0; i < blogTrackbackIDs.length; i++) {
              String blogTrackbackID = blogTrackbackIDs[i];
              Trackback[] trackbacks = entryToUpdate.getTrackbacksAsArray();

              for (int j = 0; j < trackbacks.length; j++) {
                Trackback trackback = trackbacks[j];
                if (trackback.getId().equals(blogTrackbackID)) {
                  Map blogTrackbackMetaData = trackback.getMetaData();

                  blogTrackbackMetaData.put(
                      TrackbackModerationPlugin.BLOJSOM_TRACKBACK_MODERATION_PLUGIN_APPROVED,
                      "true");
                  try {
                    trackback.save(user);

                    _blojsomConfiguration
                        .getEventBroadcaster()
                        .broadcastEvent(
                            new TrackbackApprovedEvent(this, new Date(), trackback, user));
                  } catch (BlojsomException e) {
                    _logger.error(e);
                  }
                }
              }
            }

            addOperationResultMessage(
                context,
                formatAdminResource(
                    APPROVED_TRACKBACKS_KEY,
                    APPROVED_TRACKBACKS_KEY,
                    user.getBlog().getBlogAdministrationLocale(),
                    new Object[] {new Integer(blogTrackbackIDs.length)}));

            entries = _fetcher.fetchEntries(fetchMap, user);
            entryToUpdate = entries[0];
          }

          context.put(BLOJSOM_PLUGIN_EDIT_BLOG_ENTRIES_ENTRY, entryToUpdate);
          context.put(BLOJSOM_PLUGIN_EDIT_BLOG_ENTRIES_CATEGORY, blogCategoryName);
        }
      } catch (BlojsomFetcherException e) {
        _logger.error(e);
      }

      httpServletRequest.setAttribute(PAGE_PARAM, EDIT_BLOG_ENTRY_PAGE);
    }

    return entries;
  }