Example usage for org.apache.commons.io FileUtils moveDirectory

List of usage examples for org.apache.commons.io FileUtils moveDirectory

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils moveDirectory.

Prototype

public static void moveDirectory(File srcDir, File destDir) throws IOException 

Source Link

Document

Moves a directory.

Usage

From source file:com.mirth.connect.plugins.datapruner.DataPruner.java

private void archiveAndGetIdsToPrune(Map<String, Object> params, String channelId,
        Calendar messageDateThreshold, String archiveFolder, PruneIds messageIds, PruneIds contentMessageIds)
        throws Throwable {
    String tempChannelFolder = archiveFolder + "/." + channelId;
    String finalChannelFolder = archiveFolder + "/" + channelId;

    try {//from ww  w. ja v  a 2 s .c  o m
        MessageWriterOptions messageWriterOptions = SerializationUtils.clone(archiverOptions);
        messageWriterOptions.setBaseFolder(System.getProperty("user.dir"));

        if (messageWriterOptions.getArchiveFormat() == null) {
            messageWriterOptions.setRootFolder(tempChannelFolder);
        } else {
            messageWriterOptions.setRootFolder(archiveFolder);
            messageWriterOptions.setArchiveFileName(channelId);
        }

        logger.debug("Running archiver, channel: " + channelId + ", root folder: "
                + messageWriterOptions.getRootFolder() + ", archive format: "
                + messageWriterOptions.getArchiveFormat() + ", archive filename: "
                + messageWriterOptions.getArchiveFileName() + ", file pattern: "
                + messageWriterOptions.getFilePattern());
        numExported = 0;
        status.setArchiving(true);
        MessageWriter archiver = MessageWriterFactory.getInstance().getMessageWriter(messageWriterOptions,
                ConfigurationController.getInstance().getEncryptor());

        AttachmentSource attachmentSource = null;
        if (messageWriterOptions.includeAttachments()) {
            attachmentSource = new AttachmentSource() {
                @Override
                public List<Attachment> getMessageAttachments(Message message) throws ClientException {
                    return MessageController.getInstance().getMessageAttachment(message.getChannelId(),
                            message.getMessageId());
                }
            };
        }
        long minMessageId = 0;
        try {
            List<Map<String, Object>> maps;
            do {
                ThreadUtils.checkInterruptedStatus();
                SqlSession session = SqlConfig.getSqlSessionManager().openSession(true);

                try {
                    params.put("minMessageId", minMessageId);
                    maps = session.selectList("Message.getMessagesToPrune", params);
                } finally {
                    session.close();
                }

                List<Long> archiveMessageIds = new ArrayList<Long>();
                Iterator<Map<String, Object>> iterator = maps.iterator();
                while (iterator.hasNext()) {
                    Map<String, Object> map = iterator.next();

                    long receivedDate = ((Calendar) map.get("mm_received_date")).getTimeInMillis();
                    long id = (Long) map.get("id");

                    if (messageDateThreshold != null && receivedDate < messageDateThreshold.getTimeInMillis()) {
                        messageIds.add(id);
                    } else {
                        contentMessageIds.add(id);
                    }

                    minMessageId = id + 1;
                    archiveMessageIds.add(id);

                    if (archiveMessageIds.size() == archiverBlockSize || !iterator.hasNext()) {
                        ThreadUtils.checkInterruptedStatus();
                        DonkeyDao dao = getDaoFactory().getDao();
                        try {
                            List<Message> messages = dao.getMessages(channelId, archiveMessageIds);

                            for (Message message : messages) {
                                if (attachmentSource != null) {
                                    List<Attachment> attachments = attachmentSource
                                            .getMessageAttachments(message);

                                    if (CollectionUtils.isNotEmpty(attachments)) {
                                        message.setAttachments(attachments);
                                    }
                                }

                                if (archiver.write(message)) {
                                    numExported++;
                                }
                            }

                            archiveMessageIds.clear();
                        } finally {
                            dao.close();
                        }
                    }
                }
            } while (maps != null && maps.size() == ID_RETRIEVE_LIMIT);

            archiver.finishWrite();
        } finally {
            archiver.close();
        }

        if (messageWriterOptions.getArchiveFormat() == null && new File(tempChannelFolder).isDirectory()) {
            try {
                FileUtils.moveDirectory(new File(tempChannelFolder), new File(finalChannelFolder));
            } catch (IOException e) {
                logger.error("Failed to move " + tempChannelFolder + " to " + finalChannelFolder, e);
            }
        }
    } catch (Throwable t) {
        FileUtils.deleteQuietly(new File(tempChannelFolder));
        FileUtils.deleteQuietly(new File(finalChannelFolder));
        throw t;
    } finally {
        status.setArchiving(false);
    }
}

From source file:com.silverpeas.silvercrawler.control.SilverCrawlerSessionController.java

public void renameFolder(String folderName, String newName)
        throws SilverCrawlerFolderRenameException, IOException {
    // looks for weird characters in new file name (security)
    if (containsWeirdCharacters(newName)) {
        throw new SilverCrawlerFolderRenameException("SilverCrawlerSessionController.renameFolder",
                SilverpeasException.ERROR, getString("silverCrawler.nameIncorrect"));
    }//from ww w . java2 s  .  c  o m

    // Get Full Path
    File after = FileUtils.getFile(getFullPath(newName));
    if (after.exists()) {
        throw new SilverCrawlerFolderRenameException("SilverCrawlerSessionController.renameFolder",
                SilverpeasException.ERROR, getString("silverCrawler.folderNameAlreadyExists"));
    }

    // Rename file
    File before = FileUtils.getFile(getFullPath(folderName));
    if (before.isDirectory()) {
        FileUtils.moveDirectory(before, after);
    } else {
        FileUtils.moveFile(before, after);
    }
}

From source file:com.mediaworx.intellij.opencmsplugin.listeners.OpenCmsModuleFileChangeListener.java

/**
 * Moves meta data xml files for a moved resource
 * @param oldOcmsModule the source OpenCms module
 * @param newOcmsModule the target OpenCms module
 * @param oldVfsPath the VFS path before the move
 * @param newVfsPath the VFS path after the move
 * @param isDirectory <code>true</code> if the resource is a folder, <code>false</code> otherwise
 */// ww  w . jav a2  s .  c  om
private void handleMetaDataForMovedResources(OpenCmsModule oldOcmsModule, OpenCmsModule newOcmsModule,
        String oldVfsPath, String newVfsPath, boolean isDirectory) {
    String oldMetaDataFilePath = getMetaDataFilePath(oldOcmsModule, oldVfsPath, isDirectory);
    String newMetaDataFilePath = getMetaDataFilePath(newOcmsModule, newVfsPath, isDirectory);
    try {
        console.info("Move meta data file from " + oldMetaDataFilePath + " to " + newMetaDataFilePath);
        File oldMetaDataFile = new File(oldMetaDataFilePath);
        File newMetaDataFile = new File(newMetaDataFilePath);
        FileUtils.moveFile(oldMetaDataFile, newMetaDataFile);
        File oldParentFile = oldMetaDataFile.getParentFile();
        File newParentFile = newMetaDataFile.getParentFile();
        refreshFiles.add(oldParentFile);
        if (!FileUtil.filesEqual(oldParentFile, newParentFile)) {
            refreshFiles.add(newParentFile);
        }
    } catch (IOException e) {
        LOG.warn("Exception while moving " + oldMetaDataFilePath + " to " + newMetaDataFilePath, e);
    }
    if (isDirectory) {
        String oldMetaFolderPath = getMetaDataFilePathWithoutSuffix(oldOcmsModule, oldVfsPath);
        String newMetaFolderPath = getMetaDataFilePathWithoutSuffix(newOcmsModule, newVfsPath);
        try {
            console.info("Move meta data folder from " + oldMetaFolderPath + " to " + newMetaFolderPath);
            File oldMetaFolder = new File(oldMetaFolderPath);
            File newMetaFolder = new File(newMetaFolderPath);
            FileUtils.moveDirectory(oldMetaFolder, newMetaFolder);
            File oldParentFolder = oldMetaFolder.getParentFile();
            File newParentFolder = newMetaFolder.getParentFile();
            refreshFiles.add(oldParentFolder);
            if (!FileUtil.filesEqual(oldParentFolder, newParentFolder)) {
                refreshFiles.add(newParentFolder);
            }
        } catch (IOException e) {
            LOG.warn("Exception while moving " + oldMetaFolderPath + " to " + newMetaFolderPath, e);
        }
    }
}

From source file:com.fluidops.iwb.tools.RepositoryTool.java

/**
 * Rebuilds the repository by performing the following steps:
 * /*from  www .  j  av a 2s. c o  m*/
 * 1) Open the original repository from dbModelFolder
 * 2) Open a fresh target repository at dbModelFolder.tmp using nativeStoreIndices
 * 3) Copy the content from source repository to target repository (optionally applying a {@link FilterIteration})
 * 4) Move original repository to dbModelFolder.bak
 * 5) Move fresh target repository to dbModelFolder
 * 
 * In case of an error during a physical I/O operation (i.e. moving the original folder, deleting
 * the temporary repository) an IOException is thrown. The original repository remains
 * untouched, the target repository may have created files in dbModelFolder.tmp (which
 * need to be deleted manually)
 * 
 * @param dbModelFolder
 * @param targetFolder
 * @param nativeStoreIndicesSource the native store indices to be used for the source, e.g. "spoc"
 * @param nativeStoreIndicesTarget the native store indices to be used for the target, e.g. "spoc,psoc"
 * @param filterFactory the factory to create a {@link FilterIteration} (can be used to filter 
 *              statements during copying). May be <code>null</<code>
 * @throws IllegalStateException if the repository could not be repaired
 * @throws IOException
 */
private static void rebuildRepository(File dbModelFolder, File targetFolder, String nativeStoreIndicesSource,
        String nativeStoreIndicesTarget, FilterIterationFactory filterFactory) throws IOException {

    resetIndexConfiguration(dbModelFolder);
    File targetRepoTmpFolder = new File(dbModelFolder.getParentFile(), dbModelFolder.getName() + ".tmp");
    Repository sourceRepo = null;
    RepositoryConnection conn = null;

    try {

        sourceRepo = getRepository(dbModelFolder, nativeStoreIndicesSource);
        sourceRepo.initialize();
        conn = sourceRepo.getConnection();
        long sizeOld = conn.size();
        print("Original repository size: " + sizeOld);

        if (targetRepoTmpFolder.exists()) {
            throw new IOException("Temporary folder for repository from incomplete recovery exists at: "
                    + targetRepoTmpFolder.getPath() + ": Remove it manually.");
        }

        Repository targetRepo = null;
        RepositoryConnection targetConn = null;
        try {
            targetRepo = getRepository(targetRepoTmpFolder, nativeStoreIndicesTarget);
            targetRepo.initialize();
            targetConn = targetRepo.getConnection();
            print("Copying contents of repository to new store ...");
            print("(Note: Depending on the triple store size this might take several minutes)");
            copyRepositoryContent(conn, targetConn, filterFactory);
            long sizeNew = targetConn.size();
            print("New repository size: " + sizeNew);
            if (filterFactory == null && sizeOld != sizeNew)
                print("WARNING: repository size of old and new repository differ, please validate manually.");
        } finally {
            ReadWriteDataManagerImpl.closeQuietly(targetConn);
            ReadWriteDataManagerImpl.shutdownQuietly(targetRepo);
        }

    } catch (Exception e) {
        print("Error while rebuilding repository: " + e.getMessage());
        print("The original repository is still in place at " + dbModelFolder.getPath()
                + ". Temporary files need to be removed manually from " + targetRepoTmpFolder.getPath());
        throw new IllegalStateException("Error while rebuilding repository: " + e.getMessage());
    } finally {
        ReadWriteDataManagerImpl.closeQuietly(conn);
        ReadWriteDataManagerImpl.shutdownQuietly(sourceRepo);
        resetIndexConfiguration(dbModelFolder);
    }

    // Success: change the locations of the new and backup repository
    // 1) if targetFolder and dbModelFolder are the same, backup original repository to %dbModelFolder.bak%
    // 2) move new repository to %targetFolder%

    if (targetFolder.equals(dbModelFolder)) {
        File dbModelFolderBak = new File(dbModelFolder.getParentFile(), dbModelFolder.getName() + ".bak");
        FileUtils.moveDirectory(dbModelFolder, dbModelFolderBak);
        print("Note: the backup of the original repository is available at " + dbModelFolderBak.getPath());
    }
    FileUtils.moveDirectory(targetRepoTmpFolder, targetFolder);

    print("Repository successfully rebuild to " + targetFolder.getPath());

}

From source file:com.hp.application.automation.tools.results.RunResultRecorder.java

/**
 * Copy Summary Html reports created by LoadRunner
 *
 * @param reportFolder//from  w  ww . j  a  va2 s.  c o m
 * @param testFolderPath
 * @param artifactsDir
 * @param reportNames
 * @param testResult
 * @throws IOException
 * @throws InterruptedException
 */
@SuppressWarnings("squid:S134")
private void createHtmlReport(FilePath reportFolder, String testFolderPath, File artifactsDir,
        List<String> reportNames, TestResult testResult) throws IOException, InterruptedException {
    String archiveTestResultMode = _resultsPublisherModel.getArchiveTestResultsMode();
    boolean createReport = archiveTestResultMode
            .equals(ResultsPublisherModel.CreateHtmlReportResults.getValue());

    if (createReport) {
        File testFolderPathFile = new File(testFolderPath);
        FilePath srcDirectoryFilePath = new FilePath(reportFolder, HTML_REPORT_FOLDER);
        if (srcDirectoryFilePath.exists()) {
            FilePath srcFilePath = new FilePath(srcDirectoryFilePath, IE_REPORT_FOLDER);
            if (srcFilePath.exists()) {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                srcFilePath.zip(baos);
                File reportDirectory = new File(artifactsDir.getParent(), PERFORMANCE_REPORT_FOLDER);
                if (!reportDirectory.exists()) {
                    reportDirectory.mkdir();
                }
                ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
                FilePath reportDirectoryFilePath = new FilePath(reportDirectory);
                FilePath tmpZipFile = new FilePath(reportDirectoryFilePath, "tmp.zip");
                tmpZipFile.copyFrom(bais);
                bais.close();
                baos.close();
                tmpZipFile.unzip(reportDirectoryFilePath);
                String newFolderName = org.apache.commons.io.FilenameUtils
                        .getName(testFolderPathFile.getPath());
                FileUtils.moveDirectory(new File(reportDirectory, IE_REPORT_FOLDER),
                        new File(reportDirectory, newFolderName));
                tmpZipFile.delete();
                outputReportFiles(reportNames, reportDirectory, testResult, false);
            }
        }
    }
}

From source file:ddf.test.itests.platform.TestConfiguration.java

private void restoreBackup(Path copy, Path original) throws IOException {
    if (Files.exists(copy) && Files.isDirectory(copy)) {
        FileUtils.deleteQuietly(original.toFile());
        FileUtils.moveDirectory(copy.toFile(), original.toFile());
    } else if (Files.exists(copy) && !Files.isDirectory(copy)) {
        FileUtils.deleteQuietly(original.toFile());
        FileUtils.moveFile(copy.toFile(), original.toFile());
    }// w  ww  .  j  ava2 s . c  o  m
}

From source file:com.microfocus.application.automation.tools.results.RunResultRecorder.java

/**
 * Copy Summary Html reports created by LoadRunner
 *
 * @param reportFolder/*from w  ww. ja va 2s .  c om*/
 * @param testFolderPath
 * @param artifactsDir
 * @param reportNames
 * @param testResult
 * @throws IOException
 * @throws InterruptedException
 */
@SuppressWarnings("squid:S134")
private void createHtmlReport(FilePath reportFolder, String testFolderPath, File artifactsDir,
        List<String> reportNames, TestResult testResult) throws IOException, InterruptedException {
    String archiveTestResultMode = _resultsPublisherModel.getArchiveTestResultsMode();
    boolean createReport = archiveTestResultMode
            .equals(ResultsPublisherModel.CreateHtmlReportResults.getValue());

    if (createReport) {
        File testFolderPathFile = new File(testFolderPath);
        FilePath srcDirectoryFilePath = new FilePath(reportFolder, HTML_REPORT_FOLDER);
        if (srcDirectoryFilePath.exists()) {
            FilePath srcFilePath = new FilePath(srcDirectoryFilePath, IE_REPORT_FOLDER);
            if (srcFilePath.exists()) {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                srcFilePath.zip(baos);
                File reportDirectory = new File(artifactsDir.getParent(), PERFORMANCE_REPORT_FOLDER);
                if (!reportDirectory.exists()) {
                    reportDirectory.mkdir();
                }
                ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
                FilePath reportDirectoryFilePath = new FilePath(reportDirectory);
                FilePath tmpZipFile = new FilePath(reportDirectoryFilePath, "tmp.zip");
                tmpZipFile.copyFrom(bais);
                bais.close();
                baos.close();
                tmpZipFile.unzip(reportDirectoryFilePath);
                String newFolderName = org.apache.commons.io.FilenameUtils
                        .getName(testFolderPathFile.getPath());
                FileUtils.moveDirectory(new File(reportDirectory, IE_REPORT_FOLDER),
                        new File(reportDirectory, newFolderName));
                tmpZipFile.delete();
                outputReportFiles(reportNames, reportDirectory, testResult, "Performance Report",
                        HTML_REPORT_FOLDER);
            }
        }
    }
}

From source file:com.aurel.track.dbase.HandleHome.java

/**
 * We reorganized the directory structure from 5.0.1 to 5.0.2
 *///from  w w  w .j a  v  a2  s  .  c om
private static void moveWordTemplates() {

    File sourceDir = new File(HandleHome.getTrackplus_Home() + File.separator + "wordTemplates");
    File targetDir = new File(HandleHome.getTrackplus_Home() + File.separator + WORD_TEMPLATES_DIR);

    try {
        if (sourceDir.exists() && !targetDir.exists()) {
            FileUtils.moveDirectory(sourceDir, targetDir);
        }
    } catch (IOException e) {
        LOGGER.error(e.getMessage());
        ;
    }
}

From source file:com.splout.db.dnode.DNodeHandler.java

/**
 * Runs a deploy action. Downloads file and warm up the data.
 * Interruptible./* w w  w .  j a  v  a  2  s .  co m*/
 */
private void runDeployAction(Fetcher.Reporter reporter, DeployAction action, long version)
        throws IOException, URISyntaxException, DNodeException, InterruptedException {

    log.info("Running deployAction[" + action + "] for version[" + version + "].");
    // 1- Call the fetcher for fetching
    File fetchedContent = fetcher.fetch(action.getDataURI(), reporter);
    // If we reach this point then the fetch has been OK
    // 2- Create the local folder were to move the fetched data
    File dbFolder = getLocalStorageFolder(action.getTablespace(), action.getPartition(), version);
    if (dbFolder.exists()) { // If the new folder where we want to deploy
        // already exists means it is
        // somehow
        // stalled from a previous failed deploy - it is ok to delete it
        FileUtils.deleteDirectory(dbFolder);
    }
    // 3- Perform a "mv" for finally making the data available
    FileUtils.moveDirectory(fetchedContent, dbFolder);

    // 4- Check if interrupted. In this case, we remove the folder before returning
    if (Thread.interrupted()) {
        try {
            FileUtils.deleteDirectory(dbFolder);
        } catch (IOException e) {
            log.warn("Not possible to remove " + dbFolder + " when trying to cancel de deployment.");
        }
        throw new InterruptedException();
    }

    // 5- Store metadata about the partition
    writePartitionMetadata(action, version);

    // 6- Preemptively load the Manager in case initialization is slow
    // Managers might warm up for a while (e.g. loading data into memory)
    loadManagerInEHCache(action.getTablespace(), action.getVersion(), action.getPartition(), dbFolder,
            action.getMetadata());
    log.info("Finished deployAction[" + action + "] for version[" + version + "].");
}

From source file:com.twinsoft.convertigo.eclipse.wizards.new_project.NewProjectWizard.java

private Project createFromBlankProject(IProgressMonitor monitor) throws Exception {
    Project project = null;// w ww . j a va2s. com
    String projectArchivePath = "";
    String newProjectName = projectName;
    String oldProjectName = "";

    switch (templateId) {
    case TEMPLATE_SQL_CONNECTOR:
        projectArchivePath = Engine.TEMPLATES_PATH + "/project/" + SQL_TEMPLATE_PROJECT_FILE_NAME;
        oldProjectName = SQL_TEMPLATE_PROJECT_FILE_NAME.substring(0,
                SQL_TEMPLATE_PROJECT_FILE_NAME.indexOf(".car"));
        break;
    case TEMPLATE_SAP_CONNECTOR:
        projectArchivePath = Engine.TEMPLATES_PATH + "/project/" + SAP_TEMPLATE_PROJECT_FILE_NAME;
        oldProjectName = SAP_TEMPLATE_PROJECT_FILE_NAME.substring(0,
                SAP_TEMPLATE_PROJECT_FILE_NAME.indexOf(".car"));
        break;
    case TEMPLATE_SEQUENCE_CONNECTOR:
        projectArchivePath = Engine.TEMPLATES_PATH + "/project/" + SEQUENCE_TEMPLATE_PROJECT_FILE_NAME;
        oldProjectName = SEQUENCE_TEMPLATE_PROJECT_FILE_NAME.substring(0,
                SEQUENCE_TEMPLATE_PROJECT_FILE_NAME.indexOf(".car"));
        break;
    case TEMPLATE_EAI_HTML_WEB_SITE:
        projectArchivePath = Engine.TEMPLATES_PATH + "/project/" + WEB_INTEGRATION_TEMPLATE_PROJECT_FILE_NAME;
        oldProjectName = WEB_INTEGRATION_TEMPLATE_PROJECT_FILE_NAME.substring(0,
                WEB_INTEGRATION_TEMPLATE_PROJECT_FILE_NAME.indexOf(".car"));
        break;
    case TEMPLATE_EAI_HTTP:
        projectArchivePath = Engine.TEMPLATES_PATH + "/project/" + HTTP_INTEGRATION_TEMPLATE_PROJECT_FILE_NAME;
        oldProjectName = HTTP_INTEGRATION_TEMPLATE_PROJECT_FILE_NAME.substring(0,
                HTTP_INTEGRATION_TEMPLATE_PROJECT_FILE_NAME.indexOf(".car"));
        break;
    case TEMPLATE_WEB_HTML_BULL_DKU_7107:
        projectArchivePath = Engine.TEMPLATES_PATH + "/project/" + DKU_PUBLISHER_TEMPLATE_PROJECT_FILE_NAME;
        oldProjectName = DKU_PUBLISHER_TEMPLATE_PROJECT_FILE_NAME.substring(0,
                DKU_PUBLISHER_TEMPLATE_PROJECT_FILE_NAME.indexOf(".car"));
        break;
    case TEMPLATE_WEB_HTML_IBM_3270:
    case TEMPLATE_WEB_HTML_IBM_5250:
        projectArchivePath = Engine.TEMPLATES_PATH + "/project/" + JAVELIN_PUBLISHER_TEMPLATE_PROJECT_FILE_NAME;
        oldProjectName = JAVELIN_PUBLISHER_TEMPLATE_PROJECT_FILE_NAME.substring(0,
                JAVELIN_PUBLISHER_TEMPLATE_PROJECT_FILE_NAME.indexOf(".car"));
        break;
    case TEMPLATE_EAI_BULL_DKU_7107:
    case TEMPLATE_EAI_IBM_3270:
    case TEMPLATE_EAI_IBM_5250:
    case TEMPLATE_EAI_UNIX_VT220:
        projectArchivePath = Engine.TEMPLATES_PATH + "/project/"
                + JAVELIN_INTEGRATION_TEMPLATE_PROJECT_FILE_NAME;
        oldProjectName = JAVELIN_INTEGRATION_TEMPLATE_PROJECT_FILE_NAME.substring(0,
                JAVELIN_INTEGRATION_TEMPLATE_PROJECT_FILE_NAME.indexOf(".car"));
        break;
    case TEMPLATE_EAI_CICS_COMMEAREA:
        projectArchivePath = Engine.TEMPLATES_PATH + "/project/" + CICS_INTEGRATION_TEMPLATE_PROJECT_FILE_NAME;
        oldProjectName = CICS_INTEGRATION_TEMPLATE_PROJECT_FILE_NAME.substring(0,
                CICS_INTEGRATION_TEMPLATE_PROJECT_FILE_NAME.indexOf(".car"));
        break;
    case TEMPLATE_WEB_SERVICE_REST_REFERENCE:
    case TEMPLATE_WEB_SERVICE_SWAGGER_REFERENCE:
    case TEMPLATE_WEB_SERVICE_SOAP_REFERENCE:
        projectArchivePath = Engine.TEMPLATES_PATH + "/project/" + HTTP_INTEGRATION_TEMPLATE_PROJECT_FILE_NAME;
        oldProjectName = HTTP_INTEGRATION_TEMPLATE_PROJECT_FILE_NAME.substring(0,
                HTTP_INTEGRATION_TEMPLATE_PROJECT_FILE_NAME.indexOf(".car"));
        break;
    case TEMPLATE_SITE_CLIPPER:
        projectArchivePath = Engine.TEMPLATES_PATH + "/project/" + SITE_CLIPPER_TEMPLATE_PROJECT_FILE_NAME;
        oldProjectName = SITE_CLIPPER_TEMPLATE_PROJECT_FILE_NAME.substring(0,
                SITE_CLIPPER_TEMPLATE_PROJECT_FILE_NAME.indexOf(".car"));
        break;
    case TEMPLATE_MOBILE_EMPTY_JQUERYMOBILE:
        projectArchivePath = Engine.TEMPLATES_PATH + "/project/"
                + JQUERYMOBILE_MOBILE_EMPTY_TEMPLATE_PROJECT_FILE_NAME;
        oldProjectName = JQUERYMOBILE_MOBILE_EMPTY_TEMPLATE_PROJECT_FILE_NAME.substring(0,
                JQUERYMOBILE_MOBILE_EMPTY_TEMPLATE_PROJECT_FILE_NAME.indexOf(".car"));
        break;
    default:
        return null;
    }

    String temporaryDir = new File(Engine.USER_WORKSPACE_PATH + "/temp").getCanonicalPath();
    String tempProjectDir = temporaryDir + "/" + oldProjectName;
    String newProjectDir = Engine.PROJECTS_PATH + "/" + newProjectName;

    try {
        try {
            File f = null;

            monitor.setTaskName("Creating new project");
            monitor.worked(1);
            try {
                // Check if project already exists
                if (Engine.theApp.databaseObjectsManager.existsProject(newProjectName))
                    throw new EngineException("Unable to create new project ! A project with the same name (\""
                            + newProjectName + "\") already exists.");

                // Create temporary directory if needed
                f = new File(temporaryDir);
                if (f.mkdir()) {
                    monitor.setTaskName("Temporary directory created: " + temporaryDir);
                    monitor.worked(1);
                }
            } catch (Exception e) {
                throw new EngineException("Unable to create the temporary directory \"" + temporaryDir + "\".",
                        e);
            }

            // Decompress Convertigo archive to temporary directory
            ZipUtils.expandZip(projectArchivePath, temporaryDir, oldProjectName);

            monitor.setTaskName("Project archive expanded to temporary directory");
            monitor.worked(1);

            // Rename temporary project directory
            f = new File(tempProjectDir);
            if (!f.renameTo(new File(newProjectDir))) {
                throw new ConvertigoException("Unable to rename the directory path \"" + tempProjectDir
                        + "\" to \"" + newProjectDir + "\"."
                        + "\n This directory already exists or is probably locked by another application.");
            }
        } catch (Exception e) {
            throw new EngineException(
                    "Unable to deploy the project from the file \"" + projectArchivePath + "\".", e);
        }

        String xmlFilePath = newProjectDir + "/" + oldProjectName + ".xml";
        String newXmlFilePath = newProjectDir + "/" + newProjectName + ".xml";
        File xmlFile = new File(xmlFilePath);

        // load xml content of file in dom
        Document dom = null;

        // cration du docBuilderFactory
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        docBuilderFactory.setIgnoringElementContentWhitespace(true);
        docBuilderFactory.setNamespaceAware(true);

        // cration du docBuilder
        DocumentBuilder docBuilder;
        try {
            docBuilder = docBuilderFactory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            throw new EngineException("Wrong parser configuration.", e);
        }

        // parsing du fichier
        try {
            dom = docBuilder.parse(xmlFile);
        } catch (SAXException e) {
            throw new EngineException("Wrong XML file structure.", e);
        } catch (IOException e) {
            throw new EngineException("Could not read source file.", e);
        }

        monitor.setTaskName("Xml file parsed");
        monitor.worked(1);

        // set values of elements to configure on the new project
        String newEmulatorTechnology = "";
        String emulatorTechnologyName = "";
        String newIbmTerminalType = "";
        switch (templateId) {
        case TEMPLATE_SEQUENCE_CONNECTOR:
        case TEMPLATE_EAI_HTML_WEB_SITE:
        case TEMPLATE_EAI_HTTP:
            break;
        case TEMPLATE_WEB_HTML_BULL_DKU_7107:
        case TEMPLATE_EAI_BULL_DKU_7107:
            newEmulatorTechnology = Session.DKU;
            emulatorTechnologyName = "BullDKU7107"; //$NON-NLS-1$
            break;
        case TEMPLATE_WEB_HTML_IBM_3270:
        case TEMPLATE_EAI_IBM_3270:
            newEmulatorTechnology = Session.SNA;
            newIbmTerminalType = "IBM-3279";
            emulatorTechnologyName = "IBM3270"; //$NON-NLS-1$
            break;
        case TEMPLATE_WEB_HTML_IBM_5250:
        case TEMPLATE_EAI_IBM_5250:
            newEmulatorTechnology = Session.AS400;
            newIbmTerminalType = "IBM-3179";
            emulatorTechnologyName = "IBM5250"; //$NON-NLS-1$
            break;
        case TEMPLATE_EAI_UNIX_VT220:
            newEmulatorTechnology = Session.VT;
            emulatorTechnologyName = "UnixVT220"; //$NON-NLS-1$
            break;
        default:
            break;
        }

        // rename project in .xml file for all projects
        Element projectElem = (Element) dom.getDocumentElement().getElementsByTagName("project").item(0);
        NodeList projectProperties = projectElem.getElementsByTagName("property");

        Element property = (Element) XMLUtils.findNodeByAttributeValue(projectProperties, "name", "name");
        ((Element) property.getElementsByTagName("java.lang.String").item(0)).removeAttribute("value");
        ((Element) property.getElementsByTagName("java.lang.String").item(0)).setAttribute("value",
                newProjectName);
        monitor.setTaskName("Project renamed");
        monitor.worked(1);

        // empty project version
        property = (Element) XMLUtils.findNodeByAttributeValue(projectProperties, "name", "version");
        ((Element) property.getElementsByTagName("java.lang.String").item(0)).removeAttribute("value");
        ((Element) property.getElementsByTagName("java.lang.String").item(0)).setAttribute("value", "");

        // rename connector in .xml file for all projects
        String oldConnectorName = "unknown";
        String newConnectorName = "NewConnector";
        // interactionHub project connector name is by default set to "void"
        switch (templateId) {
        case TEMPLATE_MOBILE_EMPTY_JQUERYMOBILE:
        case TEMPLATE_SEQUENCE_CONNECTOR:
            newConnectorName = "void";
            break;
        default:
            newConnectorName = (page2 == null) ? "NewConnector" : page2.getConnectorName();
            break;
        }
        Element connectorElem = (Element) dom.getDocumentElement().getElementsByTagName("connector").item(0);
        NodeList connectorProperties = connectorElem.getElementsByTagName("property");

        property = (Element) XMLUtils.findNodeByAttributeValue(connectorProperties, "name", "name");
        oldConnectorName = ((Element) property.getElementsByTagName("java.lang.String").item(0))
                .getAttribute("value");
        ((Element) property.getElementsByTagName("java.lang.String").item(0)).removeAttribute("value");
        ((Element) property.getElementsByTagName("java.lang.String").item(0)).setAttribute("value",
                newConnectorName);
        monitor.setTaskName("Connector renamed");
        monitor.worked(1);

        // configure connector properties
        switch (templateId) {
        case TEMPLATE_WEB_HTML_BULL_DKU_7107:
        case TEMPLATE_WEB_HTML_IBM_3270:
        case TEMPLATE_WEB_HTML_IBM_5250:
        case TEMPLATE_EAI_BULL_DKU_7107:
        case TEMPLATE_EAI_IBM_3270:
        case TEMPLATE_EAI_IBM_5250:
        case TEMPLATE_EAI_UNIX_VT220:
            // change emulator technology
            // and change service code
            property = (Element) XMLUtils.findNodeByAttributeValue(connectorProperties, "name", "serviceCode");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).removeAttribute("value");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).setAttribute("value",
                    page7.getServiceCode());
            monitor.setTaskName("Connector service code updated");
            monitor.worked(1);

            property = (Element) XMLUtils.findNodeByAttributeValue(connectorProperties, "name",
                    "emulatorTechnology");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).removeAttribute("value");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).setAttribute("value",
                    newEmulatorTechnology);
            monitor.setTaskName("Connector emulator technology updated");
            monitor.worked(1);

            property = (Element) XMLUtils.findNodeByAttributeValue(connectorProperties, "name",
                    "ibmTerminalType");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).removeAttribute("value");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).setAttribute("value",
                    newIbmTerminalType);
            monitor.setTaskName("Terminal type updated");
            monitor.worked(1);

            // rename emulatorTechnology criteria
            Element criteriaElem = (Element) dom.getDocumentElement().getElementsByTagName("criteria").item(0);
            NodeList criteriaProperties = criteriaElem.getElementsByTagName("property");

            property = (Element) XMLUtils.findNodeByAttributeValue(criteriaProperties, "name", "name");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).removeAttribute("value");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).setAttribute("value",
                    emulatorTechnologyName);
            monitor.setTaskName("Emulator technology criteria renamed");
            monitor.worked(1);
            break;
        case TEMPLATE_WEB_SERVICE_REST_REFERENCE:
        case TEMPLATE_EAI_HTML_WEB_SITE:
        case TEMPLATE_EAI_HTTP:
            // change connector server and port,
            // change https mode
            // and change proxy server and proxy port
            property = (Element) XMLUtils.findNodeByAttributeValue(connectorProperties, "name", "server");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).removeAttribute("value");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).setAttribute("value",
                    page6.getHttpServer());
            monitor.setTaskName("Connector server updated");
            monitor.worked(1);

            property = (Element) XMLUtils.findNodeByAttributeValue(connectorProperties, "name", "port");
            ((Element) property.getElementsByTagName("java.lang.Integer").item(0)).removeAttribute("value");
            ((Element) property.getElementsByTagName("java.lang.Integer").item(0)).setAttribute("value",
                    page6.getHttpPort());
            monitor.setTaskName("Connector port updated");
            monitor.worked(1);

            property = (Element) XMLUtils.findNodeByAttributeValue(connectorProperties, "name", "https");
            ((Element) property.getElementsByTagName("java.lang.Boolean").item(0)).removeAttribute("value");
            ((Element) property.getElementsByTagName("java.lang.Boolean").item(0)).setAttribute("value",
                    Boolean.toString(page6.isBSSL()));
            monitor.setTaskName("Connector https mode updated");
            monitor.worked(1);
            break;

        case TEMPLATE_EAI_CICS_COMMEAREA:
            property = (Element) XMLUtils.findNodeByAttributeValue(connectorProperties, "name",
                    "mainframeName");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).removeAttribute("value");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).setAttribute("value",
                    page5.getCtgName());
            monitor.setTaskName("Connector mainframe name updated");
            monitor.worked(1);

            property = (Element) XMLUtils.findNodeByAttributeValue(connectorProperties, "name", "server");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).removeAttribute("value");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).setAttribute("value",
                    page5.getCtgServer());
            monitor.setTaskName("Connector server updated");
            monitor.worked(1);

            property = (Element) XMLUtils.findNodeByAttributeValue(connectorProperties, "name", "port");
            ((Element) property.getElementsByTagName("java.lang.Integer").item(0)).removeAttribute("value");
            ((Element) property.getElementsByTagName("java.lang.Integer").item(0)).setAttribute("value",
                    page5.getCtgPort());
            monitor.setTaskName("Connector port updated");
            monitor.worked(1);
            break;

        case TEMPLATE_SQL_CONNECTOR:
            // change emulator technology
            // and change service code
            property = (Element) XMLUtils.findNodeByAttributeValue(connectorProperties, "name", "jdbcURL");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).setAttribute("value",
                    configureSQLConnectorPage.getJdbcURL());
            monitor.setTaskName("JDBC URL updated");
            monitor.worked(1);

            property = (Element) XMLUtils.findNodeByAttributeValue(connectorProperties, "name",
                    "jdbcDriverClassName");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).setAttribute("value",
                    configureSQLConnectorPage.getJdbcDriver());
            monitor.setTaskName("JDBC driver updated");
            monitor.worked(1);

            property = (Element) XMLUtils.findNodeByAttributeValue(connectorProperties, "name", "jdbcUserName");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).setAttribute("value",
                    configureSQLConnectorPage.getUsername());
            monitor.setTaskName("Username updated");
            monitor.worked(1);

            property = (Element) XMLUtils.findNodeByAttributeValue(connectorProperties, "name",
                    "jdbcUserPassword");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).setAttribute("value",
                    configureSQLConnectorPage.getPassword());
            monitor.setTaskName("Password updated");
            monitor.worked(1);

            break;

        case TEMPLATE_SAP_CONNECTOR:
            // change emulator technology
            // and change service code

            // Application Server Host
            property = (Element) XMLUtils.findNodeByAttributeValue(connectorProperties, "name", "ashost");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).setAttribute("value",
                    configureSAPConnectorPage.getAsHost());
            monitor.setTaskName("Application Server Host updated");
            monitor.worked(1);

            // System Number
            property = (Element) XMLUtils.findNodeByAttributeValue(connectorProperties, "name", "systemNumber");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).setAttribute("value",
                    configureSAPConnectorPage.getSystemNumber());
            monitor.setTaskName("System number updated");
            monitor.worked(1);

            // Client
            property = (Element) XMLUtils.findNodeByAttributeValue(connectorProperties, "name", "client");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).setAttribute("value",
                    configureSAPConnectorPage.getClient());
            monitor.setTaskName("Client updated");
            monitor.worked(1);

            // User
            property = (Element) XMLUtils.findNodeByAttributeValue(connectorProperties, "name", "user");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).setAttribute("value",
                    configureSAPConnectorPage.getUser());
            monitor.setTaskName("User updated");
            monitor.worked(1);

            // Password
            property = (Element) XMLUtils.findNodeByAttributeValue(connectorProperties, "name", "password");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).setAttribute("value",
                    configureSAPConnectorPage.getPassword());
            monitor.setTaskName("Password updated");
            monitor.worked(1);

            // Language
            property = (Element) XMLUtils.findNodeByAttributeValue(connectorProperties, "name", "language");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).setAttribute("value",
                    configureSAPConnectorPage.getLanguage());
            monitor.setTaskName("Language updated");
            monitor.worked(1);

            break;

        case TEMPLATE_SITE_CLIPPER:
            property = (Element) XMLUtils.findNodeByAttributeValue(connectorProperties, "name",
                    "trustAllServerCertificates");
            ((Element) property.getElementsByTagName("java.lang.Boolean").item(0)).removeAttribute("value");
            ((Element) property.getElementsByTagName("java.lang.Boolean").item(0)).setAttribute("value",
                    Boolean.toString(page11.isTrustAllServerCertificates()));
            monitor.setTaskName("Connector certificates policy updated");
            monitor.worked(1);
            break;

        default:
            break;
        }

        // Configure connector's default transaction properties
        Element transactionElem = (Element) dom.getDocumentElement().getElementsByTagName("transaction")
                .item(0);
        NodeList transactionProperties = transactionElem.getElementsByTagName("property");

        switch (templateId) {
        case TEMPLATE_SITE_CLIPPER:
            property = (Element) XMLUtils.findNodeByAttributeValue(transactionProperties, "name", "targetURL");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).removeAttribute("value");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).setAttribute("value",
                    page11.getTargetURL());
            monitor.setTaskName("Host url updated");
            monitor.worked(1);
            break;
        case TEMPLATE_SQL_CONNECTOR:
            property = (Element) XMLUtils.findNodeByAttributeValue(transactionProperties, "name", "sqlQuery");
            ((Element) property.getElementsByTagName("java.lang.String").item(0)).removeAttribute("value");
            monitor.setTaskName("SQL queries updated");
            monitor.worked(1);
            break;
        default:
            break;
        }

        // write the new .xml file
        // prepare the string source to write
        String doc = XMLUtils.prettyPrintDOM(dom);
        // create the output file
        File newXmlFile = new File(newXmlFilePath);
        if (!newXmlFile.createNewFile()) {
            throw new ConvertigoException("Unable to create the .xml file \"" + newProjectName + ".xml\".");
        }
        // write the file to the disk
        byte data[] = doc.getBytes();
        FileOutputStream fos = new FileOutputStream(newXmlFilePath);
        BufferedOutputStream dest = new BufferedOutputStream(fos, data.length);
        try {
            dest.write(data, 0, data.length);
        } finally {
            dest.flush();
            dest.close();
        }

        monitor.setTaskName("New xml file created and saved");
        monitor.worked(1);

        // delete the old .xml file
        if (!xmlFile.delete()) {
            throw new ConvertigoException("Unable to delete the .xml file \"" + oldProjectName + ".xml\".");
        }

        monitor.setTaskName("Old xml file deleted");
        monitor.worked(1);

        try {
            String xsdInternalPath = newProjectDir + "/" + Project.XSD_FOLDER_NAME + "/"
                    + Project.XSD_INTERNAL_FOLDER_NAME;
            File xsdInternalDir = new File(xsdInternalPath).getCanonicalFile();

            boolean needConnectorRename = !oldConnectorName.equals(newConnectorName);
            if (needConnectorRename) {
                File srcDir = new File(xsdInternalDir, oldConnectorName);
                File destDir = new File(xsdInternalDir, newConnectorName);

                if (oldConnectorName.equalsIgnoreCase(newConnectorName)) {
                    File destDirTmp = new File(xsdInternalDir, "tmp" + oldConnectorName).getCanonicalFile();
                    FileUtils.moveDirectory(srcDir, destDirTmp);
                    srcDir = destDirTmp;
                }
                FileUtils.moveDirectory(srcDir, destDir);
            }

            for (File connectorDir : xsdInternalDir.listFiles()) {
                if (connectorDir.isDirectory()) {
                    String connectorName = connectorDir.getName();
                    for (File transactionXsdFile : connectorDir.listFiles()) {
                        String xsdFilePath = transactionXsdFile.getCanonicalPath();
                        ProjectUtils.xsdRenameProject(xsdFilePath, oldProjectName, newProjectName);
                        if (needConnectorRename && connectorName.equals(newConnectorName)) {
                            ProjectUtils.xsdRenameConnector(xsdFilePath, oldConnectorName, newConnectorName);
                        }
                    }
                }
            }

            monitor.setTaskName("Schemas updated");
            monitor.worked(1);

        } catch (ConvertigoException e) {
            Engine.logDatabaseObjectManager.error("An error occured while updating transaction schemas", e);
        }

        String projectPath = newProjectDir + "/" + newProjectName;

        // Import the project from the new .xml file
        project = Engine.theApp.databaseObjectsManager.importProject(projectPath + ".xml");

        // In the case we want to predefine with the new project wizard a SQL query
        switch (templateId) {
        case TEMPLATE_SQL_CONNECTOR:
            try {
                SqlConnector connector = (SqlConnector) project.getDefaultConnector();
                SqlTransaction transaction = connector.getDefaultTransaction();

                String sqlQuery = transaction.getSqlQuery();
                transaction.setSqlQuery(sqlQuery);
                CarUtils.exportProject(project, projectPath + ".xml");
            } catch (Exception e) {
                Engine.logDatabaseObjectManager
                        .error("An error occured while initialize SQL project \"" + projectName + "\"", e);
            }
            break;
        }
        monitor.setTaskName("Project loaded");
        monitor.worked(1);

        monitor.setTaskName("Resources created");
        monitor.worked(1);
    } catch (Exception e) {
        // Delete everything
        try {
            Engine.logBeans.error(
                    "An error occured while creating project, everything will be deleted. Please see Studio logs for more informations.",
                    null);
            // TODO : see if we can delete oldProjectName : a real project
            // could exist with this oldProjectName ?
            // Engine.theApp.databaseObjectsManager.deleteProject(oldProjectName,
            // false, false);
            Engine.theApp.databaseObjectsManager.deleteProject(newProjectName, false, false);
            projectName = null; // avoid load of project in view
            project = null;
        } catch (Exception ex) {
        }

        throw new Exception("Unable to create project from template", e);
    }

    return project;
}