List of usage examples for org.apache.commons.io FileUtils moveFile
public static void moveFile(File srcFile, File destFile) throws IOException
From source file:de.mendelson.comm.as2.server.AS2ServerProcessing.java
private void processUploadRequestFile(IoSession session, UploadRequestFile request) { UploadResponseFile response = new UploadResponseFile(request); try {/*www .j a va 2 s . com*/ String uploadHash = request.getUploadHash(); File tempFile = new File(this.uploadMap.get(uploadHash)); File targetFile = new File(request.getTargetFilename()); FileUtils.deleteQuietly(targetFile); FileUtils.moveFile(tempFile, targetFile); synchronized (this.uploadMap) { this.uploadMap.remove(uploadHash); } } catch (IOException e) { response.setException(e); } session.write(response); }
From source file:com.digitalgeneralists.assurance.UnitTestUtils.java
public void buildDeletedItemsStructure(ComparisonResult result) throws IOException { if (result.getSourceDeletedItemLocation(MergeEngine.getApplicationDeletedItemsLocation()).exists()) { FileUtils.deleteQuietly(// w w w . j a va 2 s . com result.getSourceDeletedItemLocation(MergeEngine.getApplicationDeletedItemsLocation())); } FileUtils.moveFile(result.getSource().getFile(), result.getSourceDeletedItemLocation(MergeEngine.getApplicationDeletedItemsLocation())); if (result.getTargetDeletedItemLocation(MergeEngine.getApplicationDeletedItemsLocation()).exists()) { FileUtils.deleteQuietly( result.getTargetDeletedItemLocation(MergeEngine.getApplicationDeletedItemsLocation())); } FileUtils.moveFile(result.getTarget().getFile(), result.getTargetDeletedItemLocation(MergeEngine.getApplicationDeletedItemsLocation())); }
From source file:it.drwolf.ridire.session.async.Mapper.java
private String createPoSTagResource(File plainTextFile, EntityManager entityManager, String encoding) throws InterruptedException, IOException { // this is needed because TreeTagger doesn't handle spaces inside // filenames correctly File tmpFile = File.createTempFile("treetagger", null); FileUtils.copyFile(plainTextFile, tmpFile); String treeTaggerBin = entityManager .find(CommandParameter.class, CommandParameter.TREETAGGER_EXECUTABLE_KEY).getCommandValue(); // if (encoding.equalsIgnoreCase("UTF-8") // || encoding.equalsIgnoreCase("UTF8")) { // treeTaggerBin = entityManager.find(CommandParameter.class, // CommandParameter.TREETAGGER_EXECUTABLE_UTF8_KEY) // .getCommandValue(); // }/*from w w w . j a v a 2 s.co m*/ this.ridireReTagger.setTreetaggerBin(treeTaggerBin); String tmpPoSFile = this.ridireReTagger.retagFile(tmpFile); File newPosFile = new File(plainTextFile.getAbsolutePath() + ".pos"); if (tmpPoSFile != null) { if (newPosFile.exists()) { FileUtils.deleteQuietly(newPosFile); } FileUtils.moveFile(new File(tmpPoSFile), newPosFile); return newPosFile.getAbsolutePath(); } return null; // CommandLine commandLine = CommandLine.parse(treeTaggerBin); // commandLine.addArgument(tmpFile.getPath()); // DefaultExecutor executor = new DefaultExecutor(); // executor.setExitValue(0); // ExecuteWatchdog watchdog = new ExecuteWatchdog( // Mapper.TREETAGGER_TIMEOUT); // executor.setWatchdog(watchdog); // ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); // ExecuteStreamHandler executeStreamHandler = new // PumpStreamHandler(baos, // null, null); // executor.setStreamHandler(executeStreamHandler); // int exitValue = executor.execute(commandLine); // FileUtils.deleteQuietly(tmpFile); // if (exitValue == 0) { // File posTagFile = new File(plainTextFile.getPath() + ".pos"); // FileUtils.writeByteArrayToFile(posTagFile, baos.toByteArray()); // return posTagFile.getCanonicalPath(); // } // return null; }
From source file:de.mendelson.comm.as2.server.AS2ServerProcessing.java
private void processUploadRequestKeystore(IoSession session, UploadRequestKeystore request) { UploadResponseKeystore response = new UploadResponseKeystore(request); try {/*from w w w.j a v a 2s . c om*/ String uploadHash = request.getUploadHash(); File tempFile = null; synchronized (this.uploadMap) { tempFile = new File(this.uploadMap.get(uploadHash)); } File targetFile = new File(request.getTargetFilename()); FileUtils.deleteQuietly(targetFile); FileUtils.moveFile(tempFile, targetFile); synchronized (this.uploadMap) { this.uploadMap.remove(uploadHash); } } catch (IOException e) { response.setException(e); } session.write(response); try { this.certificateManager.rereadKeystoreCertificates(); } catch (Exception e) { //nop } }
From source file:com.daphne.es.showcase.excel.service.ExcelDataService.java
/** * workbook/* w ww . ja v a 2s . co m*/ * 1?vbs ? * 2?c#?? * ? ????office 2007 ? * @param user * @param contextRootPath * @param searchable */ @Async public void exportExcel2003WithOneSheetPerWorkBook(final User user, final String contextRootPath, final Searchable searchable) { int workbookCount = 0; List<String> workbookFileNames = new ArrayList<String>(); int perSheetRows = 60000; //?sheet 6w? int totalRows = 0; String extension = "xls"; int pageSize = 1000; Long maxId = 0L; BufferedOutputStream out = null; try { long beginTime = System.currentTimeMillis(); while (true) { workbookCount++; String fileName = generateFilename(user, contextRootPath, workbookCount, extension); workbookFileNames.add(fileName); File file = new File(fileName); HSSFWorkbook wb = new HSSFWorkbook(); Sheet sheet = wb.createSheet(); Row headerRow = sheet.createRow(0); Cell idHeaderCell = headerRow.createCell(0); idHeaderCell.setCellValue("?"); Cell contentHeaderCell = headerRow.createCell(1); contentHeaderCell.setCellValue(""); totalRows = 1; Page<ExcelData> page = null; do { searchable.setPage(0, pageSize); // if (!searchable.containsSearchKey("id_in")) { searchable.addSearchFilter("id", SearchOperator.gt, maxId); } page = findAll(searchable); for (ExcelData data : page.getContent()) { Row row = sheet.createRow(totalRows); Cell idCell = row.createCell(0); idCell.setCellValue(data.getId()); Cell contentCell = row.createCell(1); contentCell.setCellValue(data.getContent()); maxId = Math.max(maxId, data.getId()); totalRows++; } //clear entity manager RepositoryHelper.clear(); } while (page.hasNext() && totalRows <= perSheetRows); out = new BufferedOutputStream(new FileOutputStream(file)); wb.write(out); IOUtils.closeQuietly(out); if (!page.hasNext()) { break; } } String fileName = workbookFileNames.get(0); if (workbookCount > 1 || needCompress(new File(fileName))) { fileName = fileName.substring(0, fileName.lastIndexOf("_")) + ".zip"; // compressAndDeleteOriginal(fileName, workbookFileNames.toArray(new String[0])); } else { String newFileName = fileName.substring(0, fileName.lastIndexOf("_")) + "." + extension; FileUtils.moveFile(new File(fileName), new File(newFileName)); fileName = newFileName; } long endTime = System.currentTimeMillis(); Map<String, Object> context = Maps.newHashMap(); context.put("seconds", (endTime - beginTime) / 1000); context.put("url", fileName.replace(contextRootPath, "")); notificationApi.notify(user.getId(), "excelExportSuccess", context); } catch (Exception e) { e.printStackTrace(); // IOUtils.closeQuietly(out); log.error("excel export error", e); Map<String, Object> context = Maps.newHashMap(); context.put("error", e.getMessage()); notificationApi.notify(user.getId(), "excelExportError", context); } }
From source file:com.luna.showcase.excel.service.ExcelDataService.java
/** * workbook//from ww w. j a v a2 s . c o m * 1?vbs ? * 2?c#?? * ? ????office 2007 ? * @param user * @param contextRootPath * @param searchable */ @Async public void exportExcel2003WithOneSheetPerWorkBook(final User user, final String contextRootPath, final Searchable searchable) { int workbookCount = 0; List<String> workbookFileNames = new ArrayList<String>(); int perSheetRows = 60000; //?sheet 6w? int totalRows = 0; String extension = "xls"; int pageSize = 1000; Long maxId = 0L; BufferedOutputStream out = null; try { long beginTime = System.currentTimeMillis(); while (true) { workbookCount++; String fileName = generateFilename(user, contextRootPath, workbookCount, extension); workbookFileNames.add(fileName); File file = new File(fileName); HSSFWorkbook wb = new HSSFWorkbook(); Sheet sheet = wb.createSheet(); Row headerRow = sheet.createRow(0); Cell idHeaderCell = headerRow.createCell(0); idHeaderCell.setCellValue("?"); Cell contentHeaderCell = headerRow.createCell(1); contentHeaderCell.setCellValue(""); totalRows = 1; Page<ExcelData> page = null; do { searchable.setPage(0, pageSize); // if (!searchable.containsSearchKey("id_in")) { searchable.addSearchFilter("id", SearchOperator.gt, maxId); } page = findAll(searchable); for (ExcelData data : page.getContent()) { Row row = sheet.createRow(totalRows); Cell idCell = row.createCell(0); idCell.setCellValue(data.getId()); Cell contentCell = row.createCell(1); contentCell.setCellValue(data.getContent()); maxId = Math.max(maxId, data.getId()); totalRows++; } //clear entity manager RepositoryHelper.clear(); } while (page.hasNextPage() && totalRows <= perSheetRows); out = new BufferedOutputStream(new FileOutputStream(file)); wb.write(out); IOUtils.closeQuietly(out); if (!page.hasNextPage()) { break; } } String fileName = workbookFileNames.get(0); if (workbookCount > 1 || needCompress(new File(fileName))) { fileName = fileName.substring(0, fileName.lastIndexOf("_")) + ".zip"; // compressAndDeleteOriginal(fileName, workbookFileNames.toArray(new String[0])); } else { String newFileName = fileName.substring(0, fileName.lastIndexOf("_")) + "." + extension; FileUtils.moveFile(new File(fileName), new File(newFileName)); fileName = newFileName; } long endTime = System.currentTimeMillis(); Map<String, Object> context = Maps.newHashMap(); context.put("seconds", (endTime - beginTime) / 1000); context.put("url", fileName.replace(contextRootPath, "")); notificationApi.notify(user.getId(), "excelExportSuccess", context); } catch (Exception e) { e.printStackTrace(); // IOUtils.closeQuietly(out); log.error("excel export error", e); Map<String, Object> context = Maps.newHashMap(); context.put("error", e.getMessage()); notificationApi.notify(user.getId(), "excelExportError", context); } }
From source file:com.taobao.android.APatchTool.java
/** * ?patch//from w w w.java 2s . c o m * * @param outPatchFile * @param projectArtifactId */ public void doPatch(File outPatchFile, String projectArtifactId) throws Exception { isApatch = true; if (mappingMap.get(replaceAnnotation) != null) { MethodReplaceAnnotation.ANNOTATION = mappingMap.get(replaceAnnotation); } File patchTmpDir = new File(outPatchFile.getParentFile(), "apatch-tmp"); patchTmpDir.mkdirs(); File adiffFile = new File(outPatchFile.getParentFile(), "apatch-diff.txt"); File adiffJsonFile = new File(outPatchFile.getParentFile(), "apatch-diff.json"); FileUtils.deleteQuietly(adiffFile); adiffFile.createNewFile(); // apk File unzipFolder = unzipApk(patchTmpDir); final File newApkUnzipFolder = new File(unzipFolder, NEW_APK_UNZIP_NAME); final File baseApkUnzipFolder = new File(unzipFolder, BASE_APK_UNZIP_NAME); // ?bundletpatch List<File> aPatches = createBundleAPatch(newApkUnzipFolder, baseApkUnzipFolder, patchTmpDir, andfixMainBundleName, adiffFile, adiffJsonFile); // ?bundletpatch // bundlesoawb? Collection<File> soFiles = FileUtils.listFiles(newApkUnzipFolder, new String[] { "so" }, true); if (splitDiffBundle != null) { for (Pair<BundleBO, BundleBO> bundle : splitDiffBundle) { List<File> aPatchFiles = processBundleFiles(bundle.getSecond().getBundleFile(), bundle.getFirst().getBundleFile(), patchTmpDir, adiffFile, adiffJsonFile); if (null != aPatchFiles) { for (File aPatchFile : aPatchFiles) { if (null != aPatchFile && aPatchFile.exists()) { aPatches.add(aPatchFile); } } } } } for (File soFile : soFiles) { String relativePath = PathUtils.toRelative(newApkUnzipFolder, soFile.getAbsolutePath()); if (null != notIncludeFiles && pathMatcher.match(notIncludeFiles, relativePath)) { continue; } File baseSoFile = new File(baseApkUnzipFolder, relativePath); if (PatchUtils.isBundleFile(soFile)) { // bundle List<File> aPatchFiles = processBundleFiles(soFile, baseSoFile, patchTmpDir, adiffFile, adiffJsonFile); if (null != aPatchFiles) { for (File aPatchFile : aPatchFiles) { if (null != aPatchFile && aPatchFile.exists()) { aPatches.add(aPatchFile); } } } } } if (aPatches.size() <= 0) { throw new Exception("No apatch files! No classes modify!"); } // ?aPatch // 4. ?apatch File[] aPatchFiles = new File[aPatches.size()]; aPatchFiles = aPatches.toArray(aPatchFiles); File mergePatchFile = null; if (null != aPatchFiles && aPatchFiles.length > 1) { MergePatch mergePatch = new MergePatch(aPatchFiles, projectArtifactId, patchTmpDir); mergePatchFile = mergePatch.doMerge(); } else if (null != aPatchFiles && aPatchFiles.length == 1) { mergePatchFile = aPatchFiles[0]; } if (null != mergePatchFile && mergePatchFile.exists()) { FileUtils.moveFile(mergePatchFile, outPatchFile); } FileUtils.deleteDirectory(unzipFolder); FileUtils.deleteDirectory(patchTmpDir); }
From source file:it.geosolutions.geobatch.flow.event.consumer.file.FileBasedEventConsumer.java
/*************************************************************************** * Main Thread cycle./*from w ww . j av a2s . c om*/ * * <LI>Create needed dirs</LI> <LI>Optionally backup files</LI> <LI>Move * files into a job-specific working dir</LI> <LI>Run the actions</LI> */ public Queue<FileSystemEvent> call() throws Exception { this.canceled = false; boolean jobResultSuccessful = false; Throwable exceptionOccurred = null; getListenerForwarder().setTask("Configuring"); getListenerForwarder().started(); try { // create live working dir getListenerForwarder().progressing(10, "Managing events"); // // Management of current working directory // // if we work on the input directory, we do not move around // anything, unless we want to // perform a backup if (configuration.isPerformBackup() || !configuration.isPreserveInput()) { if (!flowInstanceTempDir.exists() && !flowInstanceTempDir.mkdirs()) { throw new IllegalStateException("Could not create consumer backup directory!"); } } // set the consumer running context // don't know how this running context will be used in a FileBased* hiererchy, anyway let's force the use of proper methods. setRunningContext("DONT_USE_AS_FILEPATH_" + flowInstanceTempDir.getAbsolutePath()); // create backup dir. Creation is deferred until first usage getListenerForwarder().progressing(20, "Creating backup dir"); final File backupDirectory = new File(flowInstanceTempDir, "backup"); if (configuration.isPerformBackup()) { if (!backupDirectory.exists() && !backupDirectory.mkdirs()) { throw new IllegalStateException("Could not create consumer backup directory!"); } } // // Cycling on all the input events // Queue<FileSystemEvent> fileEventList = new LinkedList<FileSystemEvent>(); int numProcessedFiles = 0; for (FileSystemEvent event : this.eventsQueue) { if (LOGGER.isInfoEnabled()) { LOGGER.info( "[" + Thread.currentThread().getName() + "]: new element retrieved from the MailBox."); } // get info for the input file event final File sourceDataFile = event.getSource(); final String fileBareName; if ((sourceDataFile != null) && sourceDataFile.exists()) { fileBareName = FilenameUtils.getName(sourceDataFile.toString()); getListenerForwarder().progressing(30 + (10f / this.eventsQueue.size() * numProcessedFiles++), "Preprocessing event " + fileBareName); // // copy input file/dir to current working directory // if (IOUtils.acquireLock(this, sourceDataFile)) { // // Backing up inputs? // if (this.configuration.isPerformBackup()) { // Backing up files and delete sources. getListenerForwarder().progressing( 30 + (10f / this.eventsQueue.size() * numProcessedFiles++), "Creating backup files"); // In case we do not work on the input as is, we // move it to our // current working directory final File destDataFile = new File(backupDirectory, fileBareName); if (sourceDataFile.isDirectory()) { FileUtils.copyDirectory(sourceDataFile, destDataFile); } else { FileUtils.copyFile(sourceDataFile, destDataFile); } } // // Working on input events directly without moving to // working dir? // if (!configuration.isPreserveInput()) { // In case we do not work on the input as is, we // move it to our current working directory final File destDataFile = new File(flowInstanceTempDir, fileBareName); if (sourceDataFile.isDirectory()) { FileUtils.moveDirectory(sourceDataFile, destDataFile); } else { FileUtils.moveFile(sourceDataFile, destDataFile); } // adjust event sources since we moved the files // locally fileEventList.offer(new FileSystemEvent(destDataFile, event.getEventType())); } else { // we are going to work directly on the input files fileEventList.offer(event); } if (LOGGER.isInfoEnabled()) { LOGGER.info( "[" + Thread.currentThread().getName() + "]: accepted file " + sourceDataFile); } } else { if (LOGGER.isErrorEnabled()) { LOGGER.error(new StringBuilder("[").append(Thread.currentThread().getName()) .append("]: could not lock file ").append(sourceDataFile).toString()); } /* * TODO: lock not acquired: what else? */ } } // event.getSource()!=null && sourceDataFile.exists() else { /* * event.getSource()==null || !sourceDataFile.exists() this * could be an empty file representing a POLLING event */ fileEventList.offer(event); } } // // // TODO if no further processing is necessary or can be // done due to some error, set eventConsumerStatus to Finished or // Failure. (etj: ???) // // if (LOGGER.isInfoEnabled()) { LOGGER.info("[" + Thread.currentThread().getName() + "]: new element processed."); } // // Finally, run the Actions on the files getListenerForwarder().progressing(50, "Running actions"); try { // apply actions into the actual context (currentRunDirectory) fileEventList = this.applyActions(fileEventList); this.setStatus(EventConsumerStatus.COMPLETED); jobResultSuccessful = true; } catch (ActionException ae) { this.setStatus(EventConsumerStatus.FAILED); throw ae; } return fileEventList; } catch (ActionException e) { String msg = "[" + Thread.currentThread().getName() + "] Error during " + e.getType().getSimpleName() + " execution: " + e.getLocalizedMessage(); if (LOGGER.isDebugEnabled()) { LOGGER.error(msg, e); } else { LOGGER.error(msg); } this.setStatus(EventConsumerStatus.FAILED); exceptionOccurred = e; } catch (IOException e) { if (LOGGER.isErrorEnabled()) { LOGGER.error("[" + Thread.currentThread().getName() + "] could not move file " + " due to the following IO error: " + e.getLocalizedMessage(), e); } this.setStatus(EventConsumerStatus.FAILED); exceptionOccurred = e; } catch (InterruptedException e) { if (LOGGER.isErrorEnabled()) { LOGGER.error("[" + Thread.currentThread().getName() + "] could not move file " + " due to an InterruptedException: " + e.getLocalizedMessage(), e); } this.setStatus(EventConsumerStatus.FAILED); exceptionOccurred = e; } catch (RuntimeException e) { exceptionOccurred = e; throw e; } finally { getListenerForwarder().progressing(100, "Completed"); if (LOGGER.isInfoEnabled()) { LOGGER.info(Thread.currentThread().getName() + " DONE!"); } // this.dispose(); if (jobResultSuccessful && (exceptionOccurred == null)) { getListenerForwarder().completed(); } else { getListenerForwarder().failed(exceptionOccurred); } } return null; }
From source file:jp.primecloud.auto.process.puppet.PuppetNodeProcess.java
protected void restoreManifest(Long instanceNo) { Instance instance = instanceDao.read(instanceNo); File manifestFile = new File(manifestDir, instance.getFqdn() + ".base.pp"); // ?/*from w ww. j a v a 2 s .c o m*/ File backupDir = new File(manifestDir, "backup"); File backupFile = new File(backupDir, manifestFile.getName()); if (!backupFile.exists()) { return; } try { if (manifestFile.exists()) { FileUtils.forceDelete(manifestFile); } FileUtils.moveFile(backupFile, manifestFile); } catch (IOException e) { // ? log.warn(e.getMessage()); } }
From source file:com.greenpepper.maven.plugin.SpecificationRunnerMojo.java
private void prepareProjectIndex(Repository repository) throws IOException { File storage = new File(reportsDirectory, "index.json"); ProjectsIndex projectsIndex = new ProjectsIndex(storage); try {//from w ww. j ava 2 s . c om projectsIndex.load(); } catch (IOException e) { getLog().warn(format("index.json is corrupted. Start a new one. Cause: %s", e.getMessage())); FileUtils.moveFile(storage, new File(reportsDirectory, "index.json.orig")); } ProjectsIndex.ProjectInfo projectInfo = projectsIndex.getNameToInfo().get(repository.getName()); if (projectInfo == null) { projectInfo = new ProjectsIndex.ProjectInfo(); projectInfo.projectName = repository.getProjectName(); projectInfo.repoName = repository.getName(); projectInfo.repoId = getRepositoryMetaName(repository); projectInfo.systemUnderTest = repository.getSystemUnderTest(); projectInfo.startDate = ProjectsIndex.ProjectInfo.SIMPLE_DATE_FORMAT.format(new Date()); projectsIndex.getNameToInfo().put(repository.getName(), projectInfo); } else { projectInfo.startDate = ProjectsIndex.ProjectInfo.SIMPLE_DATE_FORMAT.format(new Date()); } projectsIndex.dump(); }