public void processAction(PortletConfig config, ActionRequest req, ActionResponse res)
      throws Exception {

    try {
      String cmd = ParamUtil.getString(req, Constants.CMD);

      if (!cmd.equals(Constants.UPDATE)) {
        return;
      }

      String content = ParamUtil.getString(req, "content");

      if (Validator.isNull(content)) {
        throw new AnnouncementsContentException();
      }

      String portletResource = ParamUtil.getString(req, "portletResource");

      String languageId = LanguageUtil.getLanguageId(req);

      PortletPreferences prefs =
          PortletPreferencesFactoryUtil.getPortletSetup(req, portletResource, false, false);

      LocalizationUtil.setPrefsValue(prefs, "content", languageId, content);

      prefs.store();

      SessionMessages.add(req, config.getPortletName() + ".doConfigure");
    } catch (AnnouncementsContentException ace) {
      SessionErrors.add(req, ace.getClass().getName());
    }
  }
  public void processAction(PortletConfig config, ActionRequest req, ActionResponse res)
      throws Exception {

    String cmd = ParamUtil.getString(req, Constants.CMD);

    String portletResource = ParamUtil.getString(req, "portletResource");

    PortletPreferences prefs =
        PortletPreferencesFactoryUtil.getPortletSetup(req, portletResource, true, true);

    if (cmd.equals("remove-footer-article")) {
      removeFooterArticle(req, prefs);
    } else if (cmd.equals("remove-header-article")) {
      removeHeaderArticle(req, prefs);
    } else if (cmd.equals("set-footer-article")) {
      setFooterArticle(req, prefs);
    } else if (cmd.equals("set-header-article")) {
      setHeaderArticle(req, prefs);
    } else if (cmd.equals(Constants.UPDATE)) {
      updateConfiguration(req, prefs);
    }

    if (SessionErrors.isEmpty(req)) {
      try {
        prefs.store();
      } catch (ValidatorException ve) {
        SessionErrors.add(req, ValidatorException.class.getName(), ve);

        return;
      }

      SessionMessages.add(req, config.getPortletName() + ".doConfigure");
    }
  }
  @SuppressWarnings("deprecation")
  private Structure _loadStructure(ActionForm form, ActionRequest req, ActionResponse res)
      throws ActionException, DotDataException {

    User user = _getUser(req);
    Structure structure = new Structure();
    String inodeString = req.getParameter("inode");
    if (InodeUtils.isSet(inodeString)) {
      /*
       * long inode = Long.parseLong(inodeString); if (inode != 0) {
       * structure = StructureFactory.getStructureByInode(inode); }
       */

      if (InodeUtils.isSet(inodeString)) {
        structure = StructureFactory.getStructureByInode(inodeString);
      }
    }
    req.setAttribute(WebKeys.Structure.STRUCTURE, structure);

    boolean searchable = false;

    List<Field> fields = structure.getFields();
    for (Field f : fields) {
      if (f.isIndexed()) {
        searchable = true;
        break;
      }
    }

    if (!searchable && InodeUtils.isSet(structure.getInode())) {
      String message = "warning.structure.notsearchable";
      SessionMessages.add(req, "message", message);
    }

    if (structure.isFixed()) {
      String message = "warning.object.isfixed";
      SessionMessages.add(req, "message", message);
    }

    // Checking permissions
    _checkUserPermissions(structure, user, PermissionAPI.PERMISSION_READ);

    return structure;
  }
  private void _deleteScheduler(
      ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form, User user)
      throws Exception {
    ContentImporterForm contentImporterForm = (ContentImporterForm) form;

    if (UtilMethods.isSet(contentImporterForm.getJobGroup()))
      QuartzUtils.removeJob(contentImporterForm.getJobName(), contentImporterForm.getJobGroup());
    else QuartzUtils.removeJob(req.getParameter("name"), req.getParameter("group"));

    SessionMessages.add(req, "message", "message.Scheduler.delete");
  }
  private void _checkWritePermissions(Structure structure, User user, HttpServletRequest httpReq)
      throws Exception {
    try {
      _checkUserPermissions(structure, user, PERMISSION_PUBLISH);

    } catch (Exception ae) {
      if (ae.getMessage().equals(WebKeys.USER_PERMISSIONS_EXCEPTION)) {
        SessionMessages.add(httpReq, "message", "message.insufficient.permissions.to.save");
      }
      throw ae;
    }
  }
Example #6
0
  public void processAction(ActionRequest req, ActionResponse res)
      throws IOException, PortletException {

    try {
      String cmd = ParamUtil.getString(req, Constants.CMD);

      if (cmd.equals(Constants.SEND)) {
        String selectTo = req.getParameter("select_to");
        String to = req.getParameter("to");
        String subject = ParamUtil.getString(req, "subject");
        String message = ParamUtil.getString(req, "message");

        if (!Validator.isEmailAddress(selectTo) && !Validator.isEmailAddress(to)) {

          SessionErrors.add(req, "to_invalid");
        } else if (!Validator.isEmailAddress(to)) {
          to = selectTo;
        }

        if (SessionErrors.isEmpty(req)) {
          User user = PortalUtil.getUser(req);

          MailServiceUtil.sendEmail(
              new MailMessage(
                  new InternetAddress(user.getEmailAddress(), user.getFullName()),
                  new InternetAddress(to),
                  subject,
                  message));

          res.setRenderParameter("select_to", StringPool.BLANK);
          res.setRenderParameter("to", StringPool.BLANK);
          res.setRenderParameter("subject", StringPool.BLANK);
          res.setRenderParameter("message", StringPool.BLANK);

          SessionMessages.add(req, getPortletConfig().getPortletName() + ".send", to);
        } else {
          res.setRenderParameter("select_to", selectTo);
          res.setRenderParameter("to", to);
          res.setRenderParameter("subject", subject);
          res.setRenderParameter("message", message);
        }
      }
    } catch (Exception e) {
      throw new PortletException(e);
    }
  }
  private void _defaultStructure(ActionForm form, ActionRequest req, ActionResponse res) {
    try {

      Structure structure = (Structure) req.getAttribute(WebKeys.Structure.STRUCTURE);

      User user = _getUser(req);
      HttpServletRequest httpReq = ((ActionRequestImpl) req).getHttpServletRequest();
      _checkWritePermissions(structure, user, httpReq);

      StructureFactory.disableDefault();
      structure.setDefaultStructure(true);
      StructureFactory.saveStructure(structure);
      String message = "message.structure.defaultstructure";
      SessionMessages.add(req, "message", message);
    } catch (Exception ex) {
      Logger.debug(EditStructureAction.class, ex.toString());
    }
  }
  private void _deleteStructure(ActionForm form, ActionRequest req, ActionResponse res)
      throws Exception {

    try {
      Structure structure = (Structure) req.getAttribute(WebKeys.Structure.STRUCTURE);

      User user = _getUser(req);
      HttpServletRequest httpReq = ((ActionRequestImpl) req).getHttpServletRequest();

      // Checking permissions
      _checkDeletePermissions(structure, user, httpReq);

      // checking if there is containers using this structure
      List<Container> containers =
          APILocator.getContainerAPI().findContainersForStructure(structure.getInode());
      if (containers.size() > 0) {
        StringBuilder names = new StringBuilder();
        for (int i = 0; i < containers.size(); i++)
          names.append(containers.get(i).getFriendlyName()).append(", ");
        Logger.warn(
            EditStructureAction.class,
            "Structure "
                + structure.getName()
                + " can't be deleted because the following containers are using it: "
                + names);
        SessionMessages.add(req, "message", "message.structure.notdeletestructure.container");
        return;
      }

      if (!structure.isDefaultStructure()) {

        @SuppressWarnings("rawtypes")
        List fields = FieldFactory.getFieldsByStructure(structure.getInode());

        @SuppressWarnings("rawtypes")
        Iterator fieldsIter = fields.iterator();

        while (fieldsIter.hasNext()) {
          Field field = (Field) fieldsIter.next();
          FieldFactory.deleteField(field);
        }

        int limit = 200;
        int offset = 0;
        List<Contentlet> contentlets =
            conAPI.findByStructure(structure, user, false, limit, offset);
        int size = contentlets.size();
        while (size > 0) {
          conAPI.delete(contentlets, user, false);
          contentlets = conAPI.findByStructure(structure, user, false, limit, offset);
          size = contentlets.size();
        }

        if (structure.getStructureType() == Structure.STRUCTURE_TYPE_FORM) {

          @SuppressWarnings({"deprecation", "static-access"})
          Structure st =
              StructureCache.getStructureByName(fAPI.FORM_WIDGET_STRUCTURE_NAME_FIELD_NAME);

          if (UtilMethods.isSet(st) && UtilMethods.isSet(st.getInode())) {

            @SuppressWarnings({"deprecation", "static-access"})
            Field field = st.getField(fAPI.FORM_WIDGET_FORM_ID_FIELD_NAME);

            List<Contentlet> widgetresults =
                conAPI.search(
                    "+structureInode:"
                        + st.getInode()
                        + " +"
                        + field.getFieldContentlet()
                        + ":"
                        + structure.getInode(),
                    0,
                    0,
                    "",
                    user,
                    false);
            if (widgetresults.size() > 0) {
              conAPI.delete(widgetresults, user, false);
            }
          }
        }

        // http://jira.dotmarketing.net/browse/DOTCMS-6435
        if (structure.getStructureType() == Structure.STRUCTURE_TYPE_FILEASSET) {
          StructureFactory.updateFolderFileAssetReferences(structure);
        }

        List<Relationship> relationships = RelationshipFactory.getRelationshipsByParent(structure);
        for (Relationship rel : relationships) {
          RelationshipFactory.deleteRelationship(rel);
        }
        relationships = RelationshipFactory.getRelationshipsByChild(structure);
        for (Relationship rel : relationships) {
          RelationshipFactory.deleteRelationship(rel);
        }

        PermissionAPI perAPI = APILocator.getPermissionAPI();
        perAPI.removePermissions(structure);

        StructureFactory.deleteStructure(structure);

        // Removing the structure from cache
        FieldsCache.removeFields(structure);
        StructureCache.removeStructure(structure);
        StructureServices.removeStructureFile(structure);

        SessionMessages.add(req, "message", "message.structure.deletestructure");
      } else {
        SessionMessages.add(req, "message", "message.structure.notdeletestructure");
      }
    } catch (Exception ex) {
      Logger.debug(EditStructureAction.class, ex.toString());
      throw ex;
    }
  }
  private void _saveStructure(ActionForm form, ActionRequest req, ActionResponse res) {
    try {
      boolean newStructure = false;
      StructureForm structureForm = (StructureForm) form;
      Structure structure = (Structure) req.getAttribute(WebKeys.Structure.STRUCTURE);

      User user = _getUser(req);
      HttpServletRequest httpReq = ((ActionRequestImpl) req).getHttpServletRequest();

      if (!UtilMethods.isSet(structureForm.getHost())
          && (!UtilMethods.isSet(structureForm.getFolder())
              || structureForm.getFolder().equals("SYSTEM_FOLDER"))) {
        throw new DotDataException(LanguageUtil.get(user, "Host-or-folder-is-required"));
      }

      // Checking permissions
      _checkWritePermissions(structure, user, httpReq);

      // Check if another structure with the same name exist
      String auxStructureName = structureForm.getName();
      auxStructureName = (auxStructureName != null ? auxStructureName.trim() : "");

      @SuppressWarnings("deprecation")
      Structure auxStructure = StructureCache.getStructureByType(auxStructureName);

      if (InodeUtils.isSet(auxStructure.getInode())
          && !auxStructure.getInode().equalsIgnoreCase(structure.getInode())) {
        throw new DotDataException(
            LanguageUtil.get(user, "There-is-another-structure-with-the-same-name"));
      }

      Arrays.sort(reservedStructureNames);
      if (!InodeUtils.isSet(structureForm.getInode())
          && (Arrays.binarySearch(reservedStructureNames, auxStructureName) >= 0)) {
        throw new DotDataException("Invalid Reserved Structure Name : " + auxStructureName);
      }

      // Validate if is a new structure and if the name hasn't change
      if (!InodeUtils.isSet(structure.getInode())) {
        newStructure = true;
      } else {
        String structureName = structure.getName();
        String structureFormName = structureForm.getName();
        if (UtilMethods.isSet(structureName)
            && UtilMethods.isSet(structureFormName)
            && !structureName.equals(structureFormName)
            && !structure.isFixed()) {

          StructureCache.removeStructure(structure);
        }
      }

      // If the structure is fixed the name cannot be changed
      if (structure.isFixed()) {
        structureForm.setName(structure.getName());
      }

      // if I'm editing a structure the structureType couldn't not be
      // change
      if (UtilMethods.isSet(structure.getInode()) && InodeUtils.isSet(structure.getInode())) {
        // reset the structure type to it's original value
        structureForm.setStructureType(structure.getStructureType());
      }
      if (UtilMethods.isSet(structure.getVelocityVarName())) {
        structureForm.setVelocityVarName(structure.getVelocityVarName());
      }
      if (UtilMethods.isSet(structureForm.getHost())) {
        if (!structureForm.getHost().equals(Host.SYSTEM_HOST)
            && hostAPI.findSystemHost().getIdentifier().equals(structureForm.getHost())) {
          structureForm.setHost(Host.SYSTEM_HOST);
        }
        structureForm.setFolder("SYSTEM_FOLDER");
      } else if (UtilMethods.isSet(structureForm.getFolder())) {
        structureForm.setHost(folderAPI.find(structureForm.getFolder(), user, false).getHostId());
      }

      if (UtilMethods.isSet(structureForm.getHost())
          && (!UtilMethods.isSet(structureForm.getFolder())
              || structureForm.getFolder().equals("SYSTEM_FOLDER"))) {
        Host host = hostAPI.find(structureForm.getHost(), user, false);
        if (host != null) {
          if (structure.getStructureType() == Structure.STRUCTURE_TYPE_FORM) {
            if (!perAPI.doesUserHavePermissions(
                host,
                "PARENT:"
                    + PermissionAPI.PERMISSION_CAN_ADD_CHILDREN
                    + ", STRUCTURES:"
                    + PermissionAPI.PERMISSION_PUBLISH,
                user)) {
              throw new DotDataException(
                  LanguageUtil.get(
                      user, "User-does-not-have-add-children-permission-on-host-folder"));
            }
          } else {
            if (!perAPI.doesUserHavePermission(
                host, PermissionAPI.PERMISSION_CAN_ADD_CHILDREN, user)) {
              throw new DotDataException(
                  LanguageUtil.get(
                      user, "User-does-not-have-add-children-permission-on-host-folder"));
            }
          }
        }
      }

      if (UtilMethods.isSet(structureForm.getFolder())
          && !structureForm.getFolder().equals("SYSTEM_FOLDER")) {
        Folder folder = folderAPI.find(structureForm.getFolder(), user, false);
        if (folder != null) {
          if (structure.getStructureType() == Structure.STRUCTURE_TYPE_FORM) {
            if (!perAPI.doesUserHavePermissions(
                folder,
                "PARENT:"
                    + PermissionAPI.PERMISSION_CAN_ADD_CHILDREN
                    + ", STRUCTURES:"
                    + PermissionAPI.PERMISSION_PUBLISH,
                user)) {
              throw new DotDataException(
                  LanguageUtil.get(
                      user, "User-does-not-have-add-children-permission-on-host-folder"));
            }
          } else {
            if (!perAPI.doesUserHavePermission(
                folder, PermissionAPI.PERMISSION_CAN_ADD_CHILDREN, user)) {
              throw new DotDataException(
                  LanguageUtil.get(
                      user, "User-does-not-have-add-children-permission-on-host-folder"));
            }
          }
        }
      }

      BeanUtils.copyProperties(structure, structureForm);

      // if htmlpage doesn't exist page id should be an identifier. Should
      // be refactored once we get identifierAPI/HTMLPage API done
      String pageDetail = structureForm.getDetailPage();

      if (newStructure) {
        String structureVelocityName =
            VelocityUtil.convertToVelocityVariable(structure.getName(), true);
        List<String> velocityvarnames = StructureFactory.getAllVelocityVariablesNames();
        int found = 0;
        if (VelocityUtil.isNotAllowedVelocityVariableName(structureVelocityName)) {
          found++;
        }

        for (String velvar : velocityvarnames) {
          if (velvar != null) {
            if (structureVelocityName.equalsIgnoreCase(velvar)) {
              found++;
            } else if (velvar.toLowerCase().contains(structureVelocityName.toLowerCase())) {
              String number = velvar.substring(structureVelocityName.length());
              if (RegEX.contains(number, "^[0-9]+$")) {
                found++;
              }
            }
          }
        }
        if (found > 0) {
          structureVelocityName = structureVelocityName + Integer.toString(found);
        }
        structure.setVelocityVarName(structureVelocityName);
      }

      if (UtilMethods.isSet(pageDetail)) {
        structure.setDetailPage(pageDetail);
      }

      // Saving interval review properties
      if (structureForm.isReviewContent()) {
        structure.setReviewInterval(
            structureForm.getReviewIntervalNum() + structureForm.getReviewIntervalSelect());
      } else {
        structure.setReviewInterval(null);
        structure.setReviewerRole(null);
      }

      // If there is no default structure this would be
      Structure defaultStructure = StructureFactory.getDefaultStructure();
      if (!InodeUtils.isSet(defaultStructure.getInode())) {
        structure.setDefaultStructure(true);
      }
      if (newStructure) {
        structure.setFixed(false);
        structure.setOwner(user.getUserId());
      }
      // validate iit is a form structure set it as system by default
      if (structureForm.getStructureType() == Structure.STRUCTURE_TYPE_FORM) {
        structure.setSystem(true);
      }
      StructureFactory.saveStructure(structure);
      structureForm.setUrlMapPattern(structure.getUrlMapPattern());

      WorkflowScheme scheme = APILocator.getWorkflowAPI().findSchemeForStruct(structure);

      String schemeId = req.getParameter("workflowScheme");

      if (scheme != null && UtilMethods.isSet(schemeId) && !schemeId.equals(scheme.getId())) {
        scheme = APILocator.getWorkflowAPI().findScheme(schemeId);
        APILocator.getWorkflowAPI().saveSchemeForStruct(structure, scheme);
      }

      // if the structure is a widget we need to add the base fields.
      if (newStructure && structureForm.getStructureType() == Structure.STRUCTURE_TYPE_WIDGET) {
        wAPI.createBaseWidgetFields(structure);
      }

      // if the structure is a form we need to add the base fields.
      if (newStructure && structureForm.getStructureType() == Structure.STRUCTURE_TYPE_FORM) {
        fAPI.createBaseFormFields(structure);
      }

      // if the structure is a form we need to add the base fields.
      if (newStructure && structureForm.getStructureType() == Structure.STRUCTURE_TYPE_FILEASSET) {
        APILocator.getFileAssetAPI().createBaseFileAssetFields(structure);
      }
      if (!newStructure) {
        perAPI.resetPermissionReferences(structure);
      }

      // Saving the structure in cache
      StructureCache.removeStructure(structure);
      StructureCache.addStructure(structure);
      StructureServices.removeStructureFile(structure);

      String message = "message.structure.savestructure";
      if (structure.getStructureType() == 3) {
        message = "message.form.saveform";
      }
      SessionMessages.add(req, "message", message);
      AdminLogger.log(
          EditStructureAction.class,
          "_saveStructure",
          "Structure saved : " + structure.getName(),
          user);
    } catch (Exception ex) {
      Logger.error(this.getClass(), ex.toString());
      String message = ex.toString();
      SessionMessages.add(req, "error", message);
    }
  }
  public void processAction(
      ActionMapping mapping,
      ActionForm form,
      PortletConfig config,
      ActionRequest req,
      ActionResponse res)
      throws Exception {

    String cmd = req.getParameter(Constants.CMD);
    Logger.debug(this, "Inside EditContentImporterJobAction cmd=" + cmd);

    // get the user
    User user = _getUser(req);

    CronScheduledTask scheduler = null;

    try {
      Logger.debug(this, "I'm retrieving the schedule");
      scheduler = _retrieveScheduler(req, res, config, form);
    } catch (Exception ae) {
      _handleException(ae, req);
    }

    /*
     *  if we are saving,
     *
     */
    if ((cmd != null) && cmd.equals(Constants.ADD)) {
      try {

        ContentImporterForm contentImporterForm = (ContentImporterForm) form;
        boolean hasErrors = false;

        if (!UtilMethods.isSet(contentImporterForm.getJobName())) {
          SessionMessages.add(req, "error", "message.Scheduler.invalidJobName");
          hasErrors = true;
        } else if (!contentImporterForm.isEditMode() && (scheduler != null)) {
          SessionMessages.add(req, "error", "message.Scheduler.jobAlreadyExists");
          hasErrors = true;
        }

        SimpleDateFormat sdf = new SimpleDateFormat(WebKeys.DateFormats.DOTSCHEDULER_DATE2);

        if (contentImporterForm.isHaveCronExpression()) {
          if (!UtilMethods.isSet(contentImporterForm.getCronExpression())) {
            SessionMessages.add(req, "error", "message.Scheduler.cronexpressionNeeded");
            hasErrors = true;
          }
        }
        Date endDate = null;
        if (contentImporterForm.isHaveEndDate()) {
          try {
            endDate = sdf.parse(contentImporterForm.getEndDate());
          } catch (Exception e) {
          }
        }

        if ((endDate != null) && !hasErrors) {
          Date startDate = null;
          if (contentImporterForm.isHaveStartDate()) {
            try {
              startDate = sdf.parse(contentImporterForm.getStartDate());
            } catch (Exception e) {
            }
          }

          if (startDate == null) {
            SessionMessages.add(req, "error", "message.Scheduler.startDateNeeded");
            hasErrors = true;
          } else if (endDate.before(startDate)) {
            SessionMessages.add(req, "error", "message.Scheduler.endDateBeforeStartDate");
            hasErrors = true;
          } else if (endDate.before(new Date())) {
            SessionMessages.add(req, "error", "message.Scheduler.endDateBeforeActualDate");
            hasErrors = true;
          }
        }

        if (!UtilMethods.isSet(contentImporterForm.getStructure())) {
          SessionMessages.add(req, "error", "message.content.importer.structure.required");
          hasErrors = true;
        }

        if (!UtilMethods.isSet(contentImporterForm.getFilePath())) {
          SessionMessages.add(req, "error", "message.content.importer.file.path.required");
          hasErrors = true;
        }

        if ((contentImporterForm.getFields() != null)
            && (0 < contentImporterForm.getFields().length)) {
          boolean containsIdentifier = false;
          for (String key : contentImporterForm.getFields()) {
            if (key.equals("0")) {
              containsIdentifier = true;
              break;
            }
          }
        }

        if (Validator.validate(req, form, mapping) && !hasErrors) {
          Logger.debug(this, "I'm Saving the scheduler");
          if (_saveScheduler(req, res, config, form, user)) {
            scheduler = _retrieveScheduler(req, res, config, form);

            if (scheduler != null) {
              _populateForm(form, scheduler);
              contentImporterForm.setMap(scheduler.getProperties());
            }

            String redirect = req.getParameter("referrer");
            if (UtilMethods.isSet(redirect)) {
              redirect = URLDecoder.decode(redirect, "UTF-8") + "&group=" + scheduler.getJobGroup();
              _sendToReferral(req, res, redirect);
              return;
            }
          } else {
            SessionMessages.clear(req);
            SessionMessages.add(req, "error", "message.Scheduler.invalidJobSettings");
            contentImporterForm.setMap(getSchedulerProperties(req, contentImporterForm));
            loadEveryDayForm(form, req);
          }
        } else {
          contentImporterForm.setMap(getSchedulerProperties(req, contentImporterForm));
          loadEveryDayForm(form, req);
        }
      } catch (Exception ae) {
        if (!ae.getMessage().equals(WebKeys.UNIQUE_SCHEDULER_EXCEPTION)) {
          _handleException(ae, req);
        }
      }
    }

    /*
     * deleting the list, return to listing page
     *
     */
    else if ((cmd != null) && cmd.equals(Constants.DELETE)) {
      try {
        Logger.debug(this, "I'm deleting the scheduler");
        _deleteScheduler(req, res, config, form, user);

      } catch (Exception ae) {
        _handleException(ae, req);
      }

      String redirect = req.getParameter("referrer");
      if (UtilMethods.isSet(redirect)) {
        redirect = URLDecoder.decode(redirect, "UTF-8");
        _sendToReferral(req, res, redirect);
        return;
      }
    }

    /*
     * Copy copy props from the db to the form bean
     *
     */
    if ((cmd != null) && cmd.equals(Constants.EDIT)) {
      if (scheduler != null) {
        _populateForm(form, scheduler);
        ContentImporterForm contentImporterForm = (ContentImporterForm) form;

        contentImporterForm.setEditMode(true);
        if (!UtilMethods.isSet(scheduler.getCronExpression())) {
          SessionMessages.add(req, "message", "message.Scheduler.jobExpired");
        }
      }
    }

    /*
     * return to edit page
     *
     */
    setForward(req, "portlet.ext.plugins.content.importer.struts.edit_job");
  }
  private static boolean _saveScheduler(
      ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form, User user)
      throws Exception {
    boolean result = false;
    ContentImporterForm contentImporterForm = (ContentImporterForm) form;

    SimpleDateFormat sdf = new SimpleDateFormat(WebKeys.DateFormats.DOTSCHEDULER_DATE2);

    Date startDate = null;
    if (contentImporterForm.isHaveStartDate()) {
      try {
        startDate = sdf.parse(contentImporterForm.getStartDate());
      } catch (Exception e) {
      }
    }

    Date endDate = null;
    if (contentImporterForm.isHaveEndDate()) {
      try {
        endDate = sdf.parse(contentImporterForm.getEndDate());
      } catch (Exception e) {
      }
    }

    Map<String, Object> properties = new HashMap<String, Object>(10);

    properties.put("structure", "" + contentImporterForm.getStructure());

    if ((contentImporterForm.getFields() != null) && (0 < contentImporterForm.getFields().length)) {
      StringBuilder fields = new StringBuilder(64);
      fields.ensureCapacity(8);
      for (String field : contentImporterForm.getFields()) {
        if (0 < fields.length()) fields.append("," + field);
        else fields.append(field);
      }

      properties.put("fields", fields.toString());
    }

    if (UtilMethods.isSet(contentImporterForm.getFilePath()))
      properties.put("filePath", contentImporterForm.getFilePath());

    if (UtilMethods.isSet(contentImporterForm.getReportEmail()))
      properties.put("reportEmail", contentImporterForm.getReportEmail());

    if (UtilMethods.isSet(contentImporterForm.getCsvSeparatorDelimiter()))
      properties.put("csvSeparatorDelimiter", contentImporterForm.getCsvSeparatorDelimiter());

    if (UtilMethods.isSet(contentImporterForm.getCsvTextDelimiter()))
      properties.put("csvTextDelimiter", contentImporterForm.getCsvTextDelimiter());

    if (UtilMethods.isSet(contentImporterForm.getLanguage()))
      properties.put("language", Long.toString(contentImporterForm.getLanguage()));

    if (contentImporterForm.isPublishContent()) properties.put("publishContent", "true");
    else properties.put("publishContent", "false");

    if (contentImporterForm.isDeleteAllContent()) properties.put("deleteAllContent", "true");
    else properties.put("deleteAllContent", "false");

    if (contentImporterForm.isSaveWithoutVersions()) properties.put("saveWithoutVersions", "true");
    else properties.put("saveWithoutVersions", "false");

    properties.put("haveCronExpression", contentImporterForm.isHaveCronExpression());

    String cronSecondsField = "0";
    String cronMinutesField = "0";
    String cronHoursField = "*";
    String cronDaysOfMonthField = "*";
    String cronMonthsField = "*";
    String cronDaysOfWeekField = "?";
    String cronYearsField = "*";

    String cronExpression = "";

    if (contentImporterForm.isHaveCronExpression()) {
      cronExpression = contentImporterForm.getCronExpression();
    } else {
      if (contentImporterForm.isAtInfo()) {
        if (UtilMethods.isSet(req.getParameter("at")) && req.getParameter("at").equals("isTime")) {
          cronSecondsField = req.getParameter("atTimeSecond");
          cronMinutesField = req.getParameter("atTimeMinute");
          cronHoursField = req.getParameter("atTimeHour");
        }

        if (UtilMethods.isSet(req.getParameter("at"))
            && req.getParameter("at").equals("isBetween")) {
          cronHoursField =
              req.getParameter("betweenFromHour") + "-" + req.getParameter("betweenToHour");
        }
      }

      if (contentImporterForm.isEveryInfo()) {
        if (UtilMethods.isSet(req.getParameter("every"))
            && req.getParameter("every").equals("isDate")) {
          cronDaysOfMonthField = req.getParameter("everyDateDay");

          try {
            cronMonthsField = "" + (Integer.parseInt(req.getParameter("everyDateMonth")) + 1);
          } catch (Exception e) {
          }

          cronYearsField = req.getParameter("everyDateYear");
        }

        if (UtilMethods.isSet(req.getParameter("every"))
            && req.getParameter("every").equals("isDays")) {
          cronDaysOfMonthField = "?";

          String[] daysOfWeek = req.getParameterValues("everyDay");

          cronDaysOfWeekField = "";
          for (String day : daysOfWeek) {
            if (cronDaysOfWeekField.length() == 0) {
              cronDaysOfWeekField = day;
            } else {
              cronDaysOfWeekField = cronDaysOfWeekField + "," + day;
            }
          }
        }
      }

      if (UtilMethods.isSet(req.getParameter("eachInfo"))) {
        if (UtilMethods.isSet(req.getParameter("eachHours"))) {
          try {
            int eachHours = Integer.parseInt(req.getParameter("eachHours"));
            cronHoursField = cronHoursField + "/" + eachHours;
          } catch (Exception e) {
          }
        }

        if (UtilMethods.isSet(req.getParameter("eachMinutes"))) {
          try {
            int eachMinutes = Integer.parseInt(req.getParameter("eachMinutes"));
            cronMinutesField = cronMinutesField + "/" + eachMinutes;
          } catch (Exception e) {
          }
        }
      }

      cronExpression =
          cronSecondsField
              + " "
              + cronMinutesField
              + " "
              + cronHoursField
              + " "
              + cronDaysOfMonthField
              + " "
              + cronMonthsField
              + " "
              + cronDaysOfWeekField
              + " "
              + cronYearsField;
    }
    CronScheduledTask job = new CronScheduledTask();
    job.setJobName(contentImporterForm.getJobName());
    job.setJobGroup(contentImporterForm.getJobGroup());
    job.setJobDescription(contentImporterForm.getJobDescription());
    job.setJavaClassName("org.dotcms.plugins.contentImporter.quartz.ContentImporterThread");
    job.setProperties(properties);
    job.setStartDate(startDate);
    job.setEndDate(endDate);
    job.setCronExpression(cronExpression);

    try {
      QuartzUtils.scheduleTask(job);
    } catch (Exception e) {
      Logger.error(EditContentImporterJobAction.class, e.getMessage(), e);
      return false;
    }

    SessionMessages.add(req, "message", "message.Scheduler.saved");

    return true;
  }