/**
   * Method "replace".
   *
   * @return true if ok
   */
  public boolean replace(String migrationTaskName) {
    IFolder librariesFolder = ResourceManager.getLibrariesFolder();
    IFile definitionFile = librariesFolder.getFile(TALENDDEFINITIONFILENAME);

    if (definitionFile.exists()) {
      File file = new File(definitionFile.getLocationURI());
      try {
        String content = FileUtils.readFileToString(file, EMFUtil.ENCODING);
        for (String oldString : old2new.keySet()) {
          String newString = old2new.get(oldString);
          if (log.isInfoEnabled()) {
            log.info(
                DefaultMessagesImpl.getString(
                    "TalendDefinitionFileUpdate_MigLog",
                    migrationTaskName,
                    oldString,
                    newString)); //$NON-NLS-1$
          }
          content = StringUtils.replace(content, oldString, newString);
        }
        FileUtils.writeStringToFile(file, content, EMFUtil.ENCODING);
      } catch (IOException e) {
        log.error(e.getMessage(), e);
        return false;
      }
    }

    return true;
  }
  /**
   * DOC xqliu Comment method "doImport".
   *
   * @param resourceType
   * @param importObject
   * @param skip
   * @param rename
   * @param importItemName
   * @return
   */
  public static List<ReturnCode> doImport(
      EResourceConstant resourceType,
      ImportObject importObject,
      boolean skip,
      boolean rename,
      String importItemName) {
    assert resourceType != null;

    IFolder restoreFolder = ResourceManager.getOneFolder(resourceType);

    switch (resourceType) {
      case PATTERN_REGEX:
        return importToStucture(
            importObject, restoreFolder, ExpressionType.REGEXP, skip, rename, importItemName);
      case PATTERN_SQL:
        return importToStucture(
            importObject, restoreFolder, ExpressionType.SQL_LIKE, skip, rename, importItemName);
      case USER_DEFINED_INDICATORS:
        return importIndicatorToStucture(importObject, restoreFolder, skip, rename, importItemName);
      case RULES_PARSER:
        return importParserRuleToStucture(
            importObject, restoreFolder, skip, rename, importItemName);
      default:
        return null;
    }
  }
  /*
   * (non-Javadoc)
   *
   * @see org.talend.dataprofiler.core.migration.AWorkspaceTask#valid()
   */
  @Override
  public boolean valid() {
    // There handle a special case, the Thresholds is different in TOP and TDQ in 3.2.2(r33000)
    ProductVersion vesion = WorkspaceVersionHelper.getVesion();
    ProductVersion version322 = new ProductVersion(3, 2, 2);
    if (VersionComparator.isEqual(vesion, version322)
        && ResourceManager.getReportsFolder().exists()) {
      return false;
    }

    return super.valid();
  }
  @Override
  protected Item createFileItemByDuplicateFile(
      IFile newFile, String fileExtension, String newName) {

    IPath makeRelativeTo =
        newFile
            .getFullPath()
            .removeFirstSegments(1)
            .removeLastSegments(1)
            .makeRelativeTo(ResourceManager.getJRXMLFolder().getFullPath().removeFirstSegments(1));
    return createJrxml(makeRelativeTo, newName, WorkspaceUtils.ifileToFile(file), fileExtension);
  }
 /**
  * DOC msjian Comment method "extractFolder".
  *
  * @param oldItem
  * @param oldModelElement
  * @return
  */
 @Override
 protected IFolder extractFolder(Item oldItem, ModelElement oldObject) {
   boolean inCurrentMainProject = ProjectManager.getInstance().isInCurrentMainProject(oldItem);
   if (inCurrentMainProject) {
     Resource resource = oldItem.eResource();
     IPath path = new Path(resource.getURI().toPlatformString(false));
     IFile oldFile = ResourcesPlugin.getWorkspace().getRoot().getFile(path);
     return (IFolder) oldFile.getParent();
   } else {
     // for the reference project node, we get its folder in current project.
     return ResourceManager.getOneFolder(EResourceConstant.JRXML_TEMPLATE);
   }
 }
 private boolean isSystemIndicator(RepositoryNode node) {
   switch (node.getType()) {
     case TDQ_REPOSITORY_ELEMENT:
     case REPOSITORY_ELEMENT:
       if (node.getObject() != null) {
         Item item = node.getObject().getProperty().getItem();
         IFolder folder = WorkbenchUtils.getFolder(node);
         return item instanceof TDQIndicatorDefinitionItem
             && ResourceService.isSubFolder(ResourceManager.getSystemIndicatorFolder(), folder);
       }
     default:
   }
   return false;
 }
 /**
  * DOC xqliu Comment method "importFromExchange".
  *
  * @param componet
  * @return
  */
 public static void importFromExchange(IEcosComponent componet) throws Exception {
   File file = new File(componet.getInstalledLocation());
   File copiedFile =
       new File(
           System.getProperty("java.io.tmpdir")
               + File.separator
               + new Path(componet.getInstalledLocation()).lastSegment()); // $NON-NLS-1$
   FileUtils.copyFile(file, copiedFile); // copy the downloaded file out of the workspace
   Wizard wizard = new ImportFromExchangeWizard(copiedFile.getAbsolutePath());
   WizardDialog dialog = new WizardDialog(null, wizard);
   if (WizardDialog.OK == dialog.open()) {
     ResourceManager.getLibrariesFolder().refreshLocal(IResource.DEPTH_INFINITE, null);
   }
 }
  /**
   * Method "indexOf".
   *
   * @return the index of the first occurrence of the character in the character sequence
   *     represented by this object, or <code>-1</code> if the character does not occur.
   */
  public int indexOf(String str) {
    IFolder librariesFolder = ResourceManager.getLibrariesFolder();
    IFile definitionFile = librariesFolder.getFile(TALENDDEFINITIONFILENAME);

    if (definitionFile.exists()) {
      File file = new File(definitionFile.getLocationURI());
      try {
        String content = FileUtils.readFileToString(file, EMFUtil.ENCODING);
        return content.indexOf(str);
      } catch (IOException e) {
        log.error(e.getMessage(), e);
        return -1;
      }
    }
    return -1;
  }
  /**
   * DOC xqliu Comment method "importToStucture".
   *
   * @param importObject
   * @param selectionFolder
   * @param type
   * @param skip
   * @param rename
   * @param importItemName
   * @return
   */
  public static List<ReturnCode> importToStucture(
      ImportObject importObject,
      IFolder selectionFolder,
      ExpressionType type,
      boolean skip,
      boolean rename,
      String importItemName) {

    List<ReturnCode> importEvent = new ArrayList<ReturnCode>();

    // MOD qiongli 2012-12-20 TDQ-5899(issue 2),should get all patterns from Pattern folder.
    Set<String> names =
        PatternUtilities.getNestFolderPatternNames(
            new HashSet<String>(), ResourceManager.getPatternFolder());

    File importFile = importObject.getObjFile();

    String fileExtName = getFileExtName(importFile);

    if ("csv".equalsIgnoreCase(fileExtName)) { // $NON-NLS-1$
      try {
        CsvReader reader = new CsvReader(new FileReader(importFile), CURRENT_SEPARATOR);
        reader.setEscapeMode(CsvReader.ESCAPE_MODE_DOUBLED);
        reader.setTextQualifier(TEXT_QUAL);
        reader.setUseTextQualifier(USE_TEXT_QUAL);

        reader.readHeaders();
        while (reader.readRecord()) {

          String name = reader.get(PatternToExcelEnum.Label.getLiteral());

          if (names.contains(name)) {
            if (skip) {
              importEvent.add(
                  new ReturnCode(
                      DefaultMessagesImpl.getString("ImportFactory.patternInported", name),
                      false)); //$NON-NLS-1$
              continue;
            }
            if (rename) {
              name = name + "(" + new Date() + ")"; // $NON-NLS-1$ //$NON-NLS-2$
            }
          }

          PatternParameters patternParameters = new ImportFactory().new PatternParameters();
          patternParameters.name = name;
          patternParameters.auther = reader.get(PatternToExcelEnum.Author.getLiteral());
          patternParameters.description = reader.get(PatternToExcelEnum.Description.getLiteral());
          patternParameters.purpose = reader.get(PatternToExcelEnum.Purpose.getLiteral());
          patternParameters.relativePath = reader.get(PatternToExcelEnum.RelativePath.getLiteral());

          for (PatternLanguageType languagetype : PatternLanguageType.values()) {
            String cellStr = reader.get(languagetype.getExcelEnum().getLiteral());
            if (cellStr != null && !cellStr.equals("")) { // $NON-NLS-1$
              patternParameters.regex.put(languagetype.getLiteral(), cellStr);
            }
          }

          try {
            TypedReturnCode<Object> create =
                createAndStorePattern(patternParameters, selectionFolder, type);
            if (create.isOk()) {
              names.add(name);

              importEvent.add(
                  new ReturnCode(
                      DefaultMessagesImpl.getString(
                          "ImportFactory.importPattern",
                          name, //$NON-NLS-1$
                          selectionFolder.getProjectRelativePath().toString()),
                      true));
            } else {
              throw new TalendInternalPersistenceException(create.getMessage());
            }

          } catch (Exception e) {
            importEvent.add(
                new ReturnCode(
                    DefaultMessagesImpl.getString("ImportFactory.SaveFailed", name),
                    false)); //$NON-NLS-1$
          }
        }
        reader.close();
      } catch (Exception e) {
        log.error(e, e);
        importEvent.add(
            new ReturnCode(
                DefaultMessagesImpl.getString("ImportFactory.importFailed"), false)); // $NON-NLS-1$
      }
    }

    if ("xls".equalsIgnoreCase(fileExtName)) { // $NON-NLS-1$
      Map<Integer, PatternLanguageType> expressionMap = new HashMap<Integer, PatternLanguageType>();
      try {
        WorkbookSettings settings = new WorkbookSettings();
        settings.setEncoding("UTF-8"); // $NON-NLS-1$
        Workbook rwb = Workbook.getWorkbook(importFile, settings);
        Sheet[] sheets = rwb.getSheets();
        for (Sheet sheet : sheets) {
          Cell[] headerRow = sheet.getRow(0);

          for (Cell cell : headerRow) {
            for (PatternLanguageType languageType : PatternLanguageType.values()) {
              if (cell.getContents().equals(languageType.getExcelEnum().getLiteral())) {
                expressionMap.put(cell.getColumn(), languageType);
              }
            }
          }

          for (int i = 1; i < sheet.getRows(); i++) {
            Cell[] row = sheet.getRow(i);
            Cell cell = row[0];
            if (CellType.LABEL.equals(cell.getType())) {
              String contents = cell.getContents();
              if (names.contains(contents)) {
                if (skip) {
                  importEvent.add(
                      new ReturnCode(
                          DefaultMessagesImpl.getString(
                              "ImportFactory.patternInported", //$NON-NLS-1$
                              contents),
                          false));
                  continue;
                }
                if (rename) {
                  contents = contents + "(" + new Date() + ")"; // $NON-NLS-1$ //$NON-NLS-2$
                }
              }

              PatternParameters patternParameters = new ImportFactory().new PatternParameters();

              patternParameters.name = contents;
              patternParameters.auther = row[6].getContents();
              patternParameters.description = row[2].getContents();
              patternParameters.purpose = row[1].getContents();
              patternParameters.status = DevelopmentStatus.DRAFT.getLiteral();

              for (int columnIndex : expressionMap.keySet()) {
                String rowContent = row[columnIndex].getContents();
                if (!rowContent.equals("")) { // $NON-NLS-1$
                  patternParameters.regex.put(
                      expressionMap.get(columnIndex).getLiteral(), rowContent);
                }
              }

              try {
                TypedReturnCode<Object> create =
                    createAndStorePattern(patternParameters, selectionFolder, type);
                if (create.isOk()) {
                  names.add(contents);

                  importEvent.add(
                      new ReturnCode(
                          DefaultMessagesImpl.getString(
                              "ImportFactory.importPattern",
                              ((TDQItem) create.getObject())
                                  .getProperty()
                                  .getDisplayName(), //$NON-NLS-1$
                              selectionFolder.getProjectRelativePath().toString()),
                          true));
                } else {
                  throw new TalendInternalPersistenceException(create.getMessage());
                }

              } catch (Exception e) {
                importEvent.add(
                    new ReturnCode(
                        DefaultMessagesImpl.getString("ImportFactory.SaveFailed", contents),
                        false)); //$NON-NLS-1$
              }
            }
          }
        }

        rwb.close();
      } catch (BiffException e) {
        log.error(e, e);
        importEvent.add(
            new ReturnCode(
                DefaultMessagesImpl.getString("ImportFactory.importFailed"), false)); // $NON-NLS-1$
      } catch (IOException e) {
        log.error(e, e);
        importEvent.add(
            new ReturnCode(
                DefaultMessagesImpl.getString("ImportFactory.importFailed"), false)); // $NON-NLS-1$
      }
    }

    importObject.copyJarFiles();

    // ADD xqliu 2012-04-27 TDQ-5149
    checkImportEvent(importItemName, importEvent);
    // ~ TDQ-5149
    return importEvent;
  }