/**
   * Read lines of a text file into a String, optionally ignoring comments.
   *
   * @param listFile the File to read from.
   * @param withcomments If <code>false</code> ignore lines starting with '#'.
   * @return String representation of the file content.
   */
  public static String getListString(final File listFile, final boolean withcomments) {
    final StringBuilder temp = new StringBuilder(300);

    BufferedReader br = null;
    try {
      br = new BufferedReader(new InputStreamReader(new FileInputStream(listFile)));
      temp.ensureCapacity((int) listFile.length());

      // Read the List
      String line = "";
      while ((line = br.readLine()) != null) {
        if (line.isEmpty()) {
          continue;
        }
        if (line.charAt(0) != '#' || withcomments) {
          // temp += line + serverCore.CRLF_STRING;
          temp.append(line).append(CR).append(LF);
        }
      }
      br.close();
    } catch (final IOException e) {
    } finally {
      if (br != null) {
        try {
          br.close();
        } catch (final Exception e) {
        }
      }
    }

    return new String(temp);
  }
Example #2
1
  /**
   * Escape编码(Unicode)
   *
   * @param content
   * @return 编码后的字符串
   */
  public static String escape(String content) {
    if (StrUtil.isBlank(content)) {
      return content;
    }

    int i;
    char j;
    StringBuilder tmp = new StringBuilder();
    tmp.ensureCapacity(content.length() * 6);

    for (i = 0; i < content.length(); i++) {

      j = content.charAt(i);

      if (Character.isDigit(j) || Character.isLowerCase(j) || Character.isUpperCase(j))
        tmp.append(j);
      else if (j < 256) {
        tmp.append("%");
        if (j < 16) tmp.append("0");
        tmp.append(Integer.toString(j, 16));
      } else {
        tmp.append("%u");
        tmp.append(Integer.toString(j, 16));
      }
    }
    return tmp.toString();
  }
  private void sendResults(
      HashMap<String, List<String>> results,
      String reportEmail,
      String subject,
      String logPath,
      String fileName) {
    StringBuilder message = new StringBuilder(1024);
    message.ensureCapacity(256);

    List<String> messages = ((List<String>) results.get("errors"));
    if ((messages != null) && (0 < messages.size())) {
      message.append("\nError Found:\n\n");
      Logger.info(ContentImporterThread.class, "\nError Found:\n");

      for (String tempMsg : messages) {
        message.append(tempMsg + "\n");
        Logger.info(ContentImporterThread.class, tempMsg);
      }
    }

    messages = ((List<String>) results.get("warnings"));
    if ((messages != null) && (0 < messages.size())) {
      message.append("\nWarnings Found:\n\n");
      Logger.info(ContentImporterThread.class, "\nWarnings Found:\n");

      for (String tempMsg : messages) {
        message.append(tempMsg + "\n");
        Logger.info(ContentImporterThread.class, tempMsg);
      }
    }

    messages = ((List<String>) results.get("results"));
    if ((messages != null) && (0 < messages.size())) {
      message.append("\nResults:\n\n");
      Logger.info(ContentImporterThread.class, "\nResults:\n");

      for (String tempMsg : messages) {
        message.append(tempMsg + "\n");
        Logger.info(ContentImporterThread.class, tempMsg);
      }
    }

    Company company = PublicCompanyFactory.getDefaultCompany();

    contentImporterLogger(logPath, fileName, message.toString());
    if (UtilMethods.isSet(reportEmail)) {
      Mailer m = new Mailer();
      m.setToEmail(reportEmail);
      m.setFromEmail(company.getEmailAddress());
      m.setCc(null);
      m.setBcc(null);
      m.setSubject(subject);
      m.setTextBody(message.toString());

      if (!m.sendMessage()) {
        Logger.info(ContentImporterThread.class, "Email couldn't be sent.");
      }
    }
  }
Example #4
1
  public void display(String html, String charset) {

    if (html != null) {
      m_content.ensureCapacity(html.length());
    }

    m_content.setLength(0);
    m_content.append(html);
  }
  public static void main(String args[]) {
    StringBuilder sb = new StringBuilder("푸른 산빛을");
    sb.ensureCapacity(50);
    printStringBuilder(sb);

    sb.append(" 깨지고 적은 길을 걸어서 차마 떨치고 갔습니다.");
    printStringBuilder(sb);

    sb.insert(10, " 단풍나무 숲을 향하여 난");
    printStringBuilder(sb);

    sb.delete(10, 29);
    printStringBuilder(sb);
  }
  /**
   * Parses through an html daybreak file and extracts any found daybreak fragments
   *
   * @param daybreakFile
   * @return
   */
  public static List<DaybreakFragment> extractDaybreakFragments(DaybreakFile daybreakFile)
      throws IOException {
    Assert.isTrue(
        daybreakFile.getDaybreakDocType() != DaybreakDocType.PAGE_FILE,
        "This parser is not for page files");

    List<DaybreakFragment> daybreakFragments = new ArrayList<>();

    String fullText =
        FileUtils.readFileToString(daybreakFile.getFile(), "UTF-8").replaceAll("\\r?\\n", " ");

    Matcher rowMatcher = rowPattern.matcher(fullText);
    rowMatcher.find(); // Throw the first two rows away
    rowMatcher.find(); // They are just headers for the table
    while (rowMatcher.find()) { // Each row contains 1 bill
      String text =
          stripParts
              .matcher(rowMatcher.group(1)) // Match all non <br> and </td> tags
              .replaceAll("") // Remove them
              .replace("</td>", "\n") // convert </td> and <br> to newlines
              .replace("<br>", "\n")
              .replace("�", " ") // Replace all instances of � with space
          ;

      // Here we are going through each line and trimming excess whitespace
      String[] lines = text.split("\\n");
      String fragmentPrintNo = null;
      StringBuilder fragmentText = new StringBuilder();
      fragmentText.ensureCapacity(text.length());
      for (int i = 0; i < lines.length; i++) {
        if (i == 0) { // The first line should be the bill print number
          fragmentPrintNo = lines[i].trim();
        }
        fragmentText.append(lines[i].trim());
        fragmentText.append('\n');
      }

      // TODO: it is assumed that the daybreak only contains bills from the current session year
      // todo: perhaps there is another way of getting the session year?
      BillId fragmentBillId =
          new BillId(fragmentPrintNo, SessionYear.of(daybreakFile.getReportDate().getYear()));

      daybreakFragments.add(
          new DaybreakFragment(fragmentBillId, daybreakFile, fragmentText.toString()));
    }

    return daybreakFragments;
  }
  /**
   * This convenience wrapper function filters all real transformations that have to be undertaken
   * on the first string to transform the later into the second string. Both strings have to be
   * represented by a path that is yielded by the <code>levenshteinPath</code> method of an existing
   * <code>ComparedStrings</code> object.
   *
   * <p>All resulting transformations are represented by <code>String</code> objects that stand for
   * one step of the transformation. Any further transformation details described by the original
   * Levenshtein path are lost. Note that the number of transformations is strictly smaller than the
   * number of Levenshtein path nodes since <code>ACTION_START</code> and <code>ACTION_REMAIN</code>
   * nodes do not trigger a real transformation and are therefore filtered out.
   *
   * @param levenshteinPath The transformation path that alters one string into another
   * @param firstWord The first word that is represented by <code>levenshteinPath</code>
   * @param secondWord The second word that is represented by <code>levenshteinPath</code>
   * @return An array of strings that describes all transformation steps including in their order
   * @since jLevenshtein v0.2
   */
  public static String[] resultTransformation(
      Map<HashPoint, Integer> levenshteinPath, String firstWord, String secondWord) {

    StringBuilder sb = new StringBuilder(firstWord);
    char[] secondWordChars = secondWord.toCharArray();
    sb.ensureCapacity(secondWordChars.length);

    int firstWordIndexShifted = 0;
    List<String> transformations = new ArrayList<String>(levenshteinPath.size() - 1);
    transformations.add(firstWord);

    loop:
    for (Entry<HashPoint, Integer> entry :
        new TreeMap<HashPoint, Integer>(levenshteinPath).entrySet()) {

      switch (entry.getValue().intValue()) {
        case Levenshtein.ACTION_SUBSTITUTE:
          sb.setCharAt(
              entry.getKey().y - 1 + firstWordIndexShifted, secondWordChars[entry.getKey().x - 1]);
          break;

        case Levenshtein.ACTION_INSERT:
          sb.insert(
              entry.getKey().y + firstWordIndexShifted, secondWordChars[entry.getKey().x - 1]);
          firstWordIndexShifted++;
          break;

        case Levenshtein.ACTION_DELETE:
          sb.deleteCharAt(entry.getKey().y - 1 + firstWordIndexShifted);
          firstWordIndexShifted--;
          break;

        case Levenshtein.ACTION_SWAP:
          sb.setCharAt(
              entry.getKey().y - 1 + firstWordIndexShifted, secondWordChars[entry.getKey().x - 1]);
          sb.setCharAt(
              entry.getKey().y - 2 + firstWordIndexShifted, secondWordChars[entry.getKey().x - 2]);
          break;

        default:
          continue loop;
      }

      transformations.add(sb.toString());
    }

    return transformations.toArray(new String[0]);
  }
  /**
   * Merge a list of values together and, if needed, restrict the number output and include a
   * "...and N others." to the end.
   *
   * @param sb, the {@link StringBuilder} to which the new list of values should be appended.
   * @param vals, the list of values to be merged.
   * @param maxNumToPrint, the maximum number of elements to be printed.
   * @param numToPrintIfOverMax, the number of elements to print if the input has more than <code>
   *     maxNumToPrint</code> elements. The rest of the elements will be printed as "...and N
   *     others."
   * @param separator, the String to delimit the items in the output.
   */
  public static void mergeListTogetherWithLimitedSize(
      final StringBuilder sb,
      final Collection<String> vals,
      final int maxNumToPrint,
      final int numToPrintIfOverMax,
      final String separator) {

    int numToPrint = vals.size();
    String extraText = "";
    if (numToPrint > maxNumToPrint) {
      numToPrint = numToPrintIfOverMax;
      extraText = separator + "...and " + (vals.size() - numToPrint) + " others.";
    }

    sb.ensureCapacity(sb.length() + numToPrint * 30 + 1 + extraText.length());
    int numPrinted = 0;
    for (final Iterator<String> iter = vals.iterator(); numPrinted < numToPrint; numPrinted++) {
      if (numPrinted > 0) sb.append(separator);

      sb.append(iter.next());
    }
    sb.append(extraText);
  }
  private String convertValueToMessage(int value) {
    String format = mIndicatorFormatter != null ? mIndicatorFormatter : DEFAULT_FORMATTER;
    // We're trying to re-use the Formatter here to avoid too much memory allocations
    // But I'm not completey sure if it's doing anything good... :(
    // Previously, this condition was wrong so the Formatter was always re-created
    // But as I fixed the condition, the formatter started outputting trash characters from previous
    // calls, so I mark the StringBuilder as empty before calling format again.

    // Anyways, I see the memory usage still go up on every call to this method
    // and I have no clue on how to fix that... damn Strings...
    if (mFormatter == null || !mFormatter.locale().equals(Locale.getDefault())) {
      int bufferSize = format.length() + String.valueOf(mMax).length();
      if (mFormatBuilder == null) {
        mFormatBuilder = new StringBuilder(bufferSize);
      } else {
        mFormatBuilder.ensureCapacity(bufferSize);
      }
      mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());
    } else {
      mFormatBuilder.setLength(0);
    }
    return mFormatter.format(format, value).toString();
  }
  /**
   * Enregistre un message dans la base
   *
   * @param m
   */
  public void createNewMessage(MlMessage m) {
    int idCompte = m.getIdCompte();
    int idDossierStockage = m.getIdDossier();
    String uidMessage = m.getUIDMessage();
    String expediteur = encodeHTMLforBase(m.getExpediteur());
    List<String> listeDestinataire = m.getDestinataire();
    List<String> listCopy = m.getDestinataireCopy();
    List<String> listCachee = m.getDestinataireCache();

    File fileToBlobDestinataires = createBlobFileFromlist(listeDestinataire, "destinataire");
    File fileToBlobDestCopy = createBlobFileFromlist(listCopy, "dest_copy");
    File fileToBlobDestHide = createBlobFileFromlist(listCachee, "hide_dest");

    String sujet = encodeHTMLforBase(m.getSujet());
    String contenu = m.getContenu();
    File fileToBlobContenu = createFileForBlob(contenu, "contenu");

    String dateReception = RecupDate.getTimeStamp(m.getDateReception());

    int tailleStringBuilder =
        uidMessage.length()
            + expediteur.length()
            /* + destinataires.length() */ + sujet.length()
            + 500;
    // on construit la requette
    StringBuilder requette = new StringBuilder(tailleStringBuilder);
    requette.ensureCapacity(tailleStringBuilder);
    requette.append("INSERT INTO " + EnTable.MAIL_RECU.getNomTable()); //
    requette.append("("); //
    requette.append(EnStructMailRecu.ID_COMPTE.getNomChamp() + ","); //
    requette.append(EnStructMailRecu.ID_DOSSIER.getNomChamp() + ","); //
    requette.append(EnStructMailRecu.UID.getNomChamp() + ","); //
    requette.append(EnStructMailRecu.EXPEDITEUR.getNomChamp() + ","); //
    requette.append(EnStructMailRecu.DEST.getNomChamp() + ","); //
    requette.append(EnStructMailRecu.DEST_COPY.getNomChamp() + ","); //
    requette.append(EnStructMailRecu.DEST_CACHE.getNomChamp() + ","); //
    requette.append(EnStructMailRecu.SUJET.getNomChamp() + ","); //
    requette.append(EnStructMailRecu.CONTENU.getNomChamp() + ","); //
    requette.append(EnStructMailRecu.DATE_RECEPTION.getNomChamp() + ","); //
    requette.append(EnStructMailRecu.STATUT.getNomChamp() + ")"); //
    requette.append("VALUES ("); //
    requette.append(idCompte + ","); //
    requette.append(idDossierStockage + ",'"); //
    requette.append(uidMessage + "','"); //
    requette.append(expediteur + "',"); //
    requette.append("?,"); // lstDest
    requette.append("?,"); // lstDestCC
    requette.append("?,'"); // lstDestBCC
    requette.append(sujet + "',");
    requette.append("?,'"); // c'est pour le contenu qui sera stocké dans un
    // blob
    requette.append(dateReception + "',"); //
    if (m.isLu()) {
      requette.append("'T')");
    } else {
      requette.append("'F')");
    }

    // le status de lecture du message (F= nonlu,T=lu)

    // on l'execute

    boolean succes =
        requeteFact.executeRequeteWithBlob(
            requette.toString(),
            fileToBlobContenu,
            fileToBlobDestinataires,
            fileToBlobDestCopy,
            fileToBlobDestHide);
    if (succes) {

      // on recupere le nouvel id du message que l'on vient d'enregistrer
      String getMaxId =
          "SELECT max ("
              + EnStructMailRecu.ID_MESSAGE.getNomChamp()
              + ") FROM "
              + EnTable.MAIL_RECU.getNomTable();
      String maxId = requeteFact.get1Champ(getMaxId);
      // ("l'id de message que l'on vient d'enregistrer est: "
      // + maxId);

      // lst.add();

      // updateStatusLecture(lst, false);

      JTreeFactory treeFact = new JTreeFactory();
      MlListeMessageGrille lst = new MlListeMessageGrille();
      lst.add(new MlMessageGrille(Integer.parseInt(maxId)));
      treeFact.majUnreadCount(lst);

      verifEtSuppressionBlob(new File(m.getCheminPhysique()));
      verifEtSuppressionBlob(fileToBlobContenu);
      verifEtSuppressionBlob(fileToBlobDestinataires);
      verifEtSuppressionBlob(fileToBlobDestCopy);
      verifEtSuppressionBlob(fileToBlobDestHide);

      // on insere le contenu en base
      // si des pieces jointe sont presente, on enregistre leur chemin en
      // base avec l'id du message
      for (File f1 : m.getListePieceJointe()) {
        if (requeteFact.enregistrePieceJointe(maxId, f1)) {
          f1.delete();
        }
      }
    }
  }
Example #11
0
  /**
   * Formats the log of executed commands into a string usable for logging purposes.
   *
   * <p>Examples:
   *
   * <ul>
   *   <li>TestCommand[SUCCESS][1ms]
   *   <li>TestCommand[SUCCESS][1ms], TestCommand[SUCCESS, RESPONSE_FROM_CACHE][1ms]x4
   *   <li>TestCommand[TIMEOUT][1ms]
   *   <li>TestCommand[FAILURE][1ms]
   *   <li>TestCommand[THREAD_POOL_REJECTED][1ms]
   *   <li>TestCommand[THREAD_POOL_REJECTED, FALLBACK_SUCCESS][1ms]
   *   <li>TestCommand[EMIT, SUCCESS][1ms]
   *   <li>TestCommand[EMITx5, SUCCESS][1ms]
   *   <li>TestCommand[EMITx5, FAILURE, FALLBACK_EMITx6, FALLBACK_FAILURE][100ms]
   *   <li>TestCommand[FAILURE, FALLBACK_SUCCESS][1ms], TestCommand[FAILURE, FALLBACK_SUCCESS,
   *       RESPONSE_FROM_CACHE][1ms]x4
   *   <li>GetData[SUCCESS][1ms], PutData[SUCCESS][1ms], GetValues[SUCCESS][1ms], GetValues[SUCCESS,
   *       RESPONSE_FROM_CACHE][1ms], TestCommand[FAILURE, FALLBACK_FAILURE][1ms],
   *       TestCommand[FAILURE, FALLBACK_FAILURE, RESPONSE_FROM_CACHE][1ms]
   * </ul>
   *
   * <p>If a command has a multiplier such as <code>x4</code>, that means this command was executed
   * 4 times with the same events. The time in milliseconds is the sum of the 4 executions.
   *
   * <p>For example, <code>TestCommand[SUCCESS][15ms]x4</code> represents TestCommand being executed
   * 4 times and the sum of those 4 executions was 15ms. These 4 each executed the run() method
   * since <code>RESPONSE_FROM_CACHE</code> was not present as an event.
   *
   * <p>If an EMIT or FALLBACK_EMIT has a multiplier such as <code>x5</code>, that means a <code>
   * HystrixObservableCommand</code> was used and it emitted that number of <code>OnNext</code>s.
   *
   * <p>For example, <code>TestCommand[EMITx5, FAILURE, FALLBACK_EMITx6, FALLBACK_FAILURE][100ms]
   * </code> represents TestCommand executing observably, emitted 5 <code>OnNext</code>s, then an
   * <code>OnError</code>. This command also has an Observable fallback, and it emits 6 <code>OnNext
   * </code>s, then an <code>OnCompleted</code>.
   *
   * @return String request log or "Unknown" if unable to instead of throwing an exception.
   */
  public String getExecutedCommandsAsString() {
    try {
      LinkedHashMap<String, Integer> aggregatedCommandsExecuted =
          new LinkedHashMap<String, Integer>();
      Map<String, Integer> aggregatedCommandExecutionTime = new HashMap<String, Integer>();

      StringBuilder builder = new StringBuilder();
      int estimatedLength = 0;
      for (HystrixInvokableInfo<?> command : allExecutedCommands) {
        builder.setLength(0);
        builder.append(command.getCommandKey().name());

        List<HystrixEventType> events =
            new ArrayList<HystrixEventType>(command.getExecutionEvents());
        if (events.size() > 0) {
          Collections.sort(events);
          // replicate functionality of Arrays.toString(events.toArray()) to append directly to
          // existing StringBuilder
          builder.append("[");
          for (HystrixEventType event : events) {
            switch (event) {
              case EMIT:
                int numEmissions = command.getNumberEmissions();
                if (numEmissions > 1) {
                  builder.append(event).append("x").append(numEmissions).append(", ");
                } else {
                  builder.append(event).append(", ");
                }
                break;
              case FALLBACK_EMIT:
                int numFallbackEmissions = command.getNumberFallbackEmissions();
                if (numFallbackEmissions > 1) {
                  builder.append(event).append("x").append(numFallbackEmissions).append(", ");
                } else {
                  builder.append(event).append(", ");
                }
                break;
              default:
                builder.append(event).append(", ");
            }
          }
          builder.setCharAt(builder.length() - 2, ']');
          builder.setLength(builder.length() - 1);
        } else {
          builder.append("[Executed]");
        }

        String display = builder.toString();
        estimatedLength +=
            display.length()
                + 12; // add 12 chars to display length for appending totalExecutionTime and count
                      // below
        Integer counter = aggregatedCommandsExecuted.get(display);
        if (counter != null) {
          aggregatedCommandsExecuted.put(display, counter + 1);
        } else {
          // add it
          aggregatedCommandsExecuted.put(display, 1);
        }

        int executionTime = command.getExecutionTimeInMilliseconds();
        if (executionTime < 0) {
          // do this so we don't create negative values or subtract values
          executionTime = 0;
        }
        counter = aggregatedCommandExecutionTime.get(display);
        if (counter != null && executionTime > 0) {
          // add to the existing executionTime (sum of executionTimes for duplicate command
          // displayNames)
          aggregatedCommandExecutionTime.put(
              display, aggregatedCommandExecutionTime.get(display) + executionTime);
        } else {
          // add it
          aggregatedCommandExecutionTime.put(display, executionTime);
        }
      }

      builder.setLength(0);
      builder.ensureCapacity(estimatedLength);
      for (String displayString : aggregatedCommandsExecuted.keySet()) {
        if (builder.length() > 0) {
          builder.append(", ");
        }
        builder.append(displayString);

        int totalExecutionTime = aggregatedCommandExecutionTime.get(displayString);
        builder.append("[").append(totalExecutionTime).append("ms]");

        int count = aggregatedCommandsExecuted.get(displayString);
        if (count > 1) {
          builder.append("x").append(count);
        }
      }
      return builder.toString();
    } catch (Exception e) {
      logger.error("Failed to create HystrixRequestLog response header string.", e);
      // don't let this cause the entire app to fail so just return "Unknown"
      return "Unknown";
    }
  }
Example #12
0
 /**
  * Escapes a string appropriately to be a valid in JSON. Valid JSON strings are defined in RFC
  * 4627, Section 2.5.
  *
  * @param s The string to escape, which is assumed to be in .
  * @param buf The buffer into which to write the escaped string.
  */
 static void escapeJson(final String s, final StringBuilder buf) {
   final int length = s.length();
   int extra = 0;
   // First count how many extra chars we'll need, if any.
   for (int i = 0; i < length; i++) {
     final char c = s.charAt(i);
     switch (c) {
       case '"':
       case '\\':
       case '\b':
       case '\f':
       case '\n':
       case '\r':
       case '\t':
         extra++;
         continue;
     }
     if (c < 0x001F) {
       extra += 4;
     }
   }
   if (extra == 0) {
     buf.append(s); // Nothing to escape.
     return;
   }
   buf.ensureCapacity(buf.length() + length + extra);
   for (int i = 0; i < length; i++) {
     final char c = s.charAt(i);
     switch (c) {
       case '"':
         buf.append('\\').append('"');
         continue;
       case '\\':
         buf.append('\\').append('\\');
         continue;
       case '\b':
         buf.append('\\').append('b');
         continue;
       case '\f':
         buf.append('\\').append('f');
         continue;
       case '\n':
         buf.append('\\').append('n');
         continue;
       case '\r':
         buf.append('\\').append('r');
         continue;
       case '\t':
         buf.append('\\').append('t');
         continue;
     }
     if (c < 0x001F) {
       buf.append('\\')
           .append('u')
           .append('0')
           .append('0')
           .append((char) Const.HEX[(c >>> 4) & 0x0F])
           .append((char) Const.HEX[c & 0x0F]);
     } else {
       buf.append(c);
     }
   }
 }
  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;
  }