List of usage examples for org.apache.commons.io FileUtils moveFile
public static void moveFile(File srcFile, File destFile) throws IOException
From source file:com.dycody.android.idealnote.utils.StorageHelper.java
/** * Creates a fiile to be used as attachment. *//*from w ww .j av a 2 s .co m*/ public static Attachment createAttachmentFromUri(Context mContext, Uri uri, boolean moveSource) { String name = FileHelper.getNameFromUri(mContext, uri); String extension = FileHelper.getFileExtension(FileHelper.getNameFromUri(mContext, uri)) .toLowerCase(Locale.getDefault()); File f; if (moveSource) { f = createNewAttachmentFile(mContext, extension); try { FileUtils.moveFile(new File(uri.getPath()), f); } catch (IOException e) { Log.e(Constants.TAG, "Can't move file " + uri.getPath()); } } else { f = StorageHelper.createExternalStoragePrivateFile(mContext, uri, extension); } Attachment mAttachment = null; if (f != null) { mAttachment = new Attachment(Uri.fromFile(f), StorageHelper.getMimeTypeInternal(mContext, uri)); mAttachment.setName(name); mAttachment.setSize(f.length()); } return mAttachment; }
From source file:edu.ucsb.eucalyptus.storage.fs.FileSystemStorageManager.java
public void deleteObjectRollback(String[] backup, String bucket, String object) throws IOException { if (backup == null || backup[0] == null || bucket == null || object == null) return;// w w w .j a va 2 s . c o m File oldObjectFile = new File(rootDirectory + FILE_SEPARATOR + bucket + FILE_SEPARATOR + object); File backupFile = new File(backup[0]); if (backupFile.exists()) { if (oldObjectFile.exists()) { FileUtils.forceDelete(oldObjectFile); } FileUtils.moveFile(backupFile, oldObjectFile); } }
From source file:com.linkedin.pinot.controller.api.resources.LLCSegmentCompletionHandlers.java
@Nullable private String uploadSegment(FormDataMultiPart multiPart, String instanceId, String segmentName, boolean isSplitCommit) { try {/*from w w w . j a va 2 s . co m*/ Map<String, List<FormDataBodyPart>> map = multiPart.getFields(); if (!PinotSegmentUploadRestletResource.validateMultiPart(map, segmentName)) { return null; } String name = map.keySet().iterator().next(); FormDataBodyPart bodyPart = map.get(name).get(0); FileUploadPathProvider provider = new FileUploadPathProvider(_controllerConf); File tmpFile = new File(provider.getFileUploadTmpDir(), name + "." + UUID.randomUUID().toString()); tmpFile.deleteOnExit(); try (InputStream inputStream = bodyPart.getValueAs(InputStream.class); OutputStream outputStream = new FileOutputStream(tmpFile)) { IOUtils.copyLarge(inputStream, outputStream); } LLCSegmentName llcSegmentName = new LLCSegmentName(segmentName); final String rawTableName = llcSegmentName.getTableName(); final File tableDir = new File(provider.getBaseDataDir(), rawTableName); File segmentFile; if (isSplitCommit) { String uniqueSegmentFileName = SegmentCompletionUtils.generateSegmentFileName(segmentName); segmentFile = new File(tableDir, uniqueSegmentFileName); } else { segmentFile = new File(tableDir, segmentName); } if (isSplitCommit) { FileUtils.moveFile(tmpFile, segmentFile); } else { // Multiple threads can reach this point at the same time, if the following scenario happens // The server that was asked to commit did so very slowly (due to network speeds). Meanwhile the FSM in // SegmentCompletionManager timed out, and allowed another server to commit, which did so very quickly (somehow // the network speeds changed). The second server made it through the FSM and reached this point. // The synchronization below takes care that exactly one file gets moved in place. // There are still corner conditions that are not handled correctly. For example, // 1. What if the offset of the faster server was different? // 2. We know that only the faster server will get to complete the COMMIT call successfully. But it is possible // that the race to this statement is won by the slower server, and so the real segment that is in there is that // of the slower server. // In order to overcome controller restarts after the segment is renamed, but before it is committed, we DO need to // check for existing segment file and remove it. So, the block cannot be removed altogether. // For now, we live with these corner cases. Once we have split-commit enabled and working, this code will no longer // be used. synchronized (SegmentCompletionManager.getInstance()) { if (segmentFile.exists()) { LOGGER.warn("Segment file {} exists. Replacing with upload from {}", segmentFile.getAbsolutePath(), instanceId); FileUtils.deleteQuietly(segmentFile); } FileUtils.moveFile(tmpFile, segmentFile); } } LOGGER.info("Moved file {} to {}", tmpFile.getAbsolutePath(), segmentFile.getAbsolutePath()); return new URI(SCHEME + segmentFile.getAbsolutePath(), /* boolean escaped */ false).toString(); } catch (InvalidControllerConfigException e) { LOGGER.error("Invalid controller config exception from instance {} for segment {}", instanceId, segmentName, e); return null; } catch (IOException e) { LOGGER.error("File upload exception from instance {} for segment {}", instanceId, segmentName, e); return null; } finally { multiPart.cleanup(); } }
From source file:com.door43.translationstudio.core.TargetTranslationMigrator.java
/** * major restructuring of the manifest to provide better support for future front/back matter, drafts, rendering, * and resolves issues between desktop and android platforms. * @param path/*from w w w .j a va 2 s. co m*/ * @return */ private static File v4(File path) throws Exception { File manifestFile = new File(path, MANIFEST_FILE); JSONObject manifest = new JSONObject(FileUtils.readFileToString(manifestFile)); // type { String typeId = "text"; if (manifest.has("project")) { try { JSONObject projectJson = manifest.getJSONObject("project"); typeId = projectJson.getString("type"); projectJson.remove("type"); manifest.put("project", projectJson); } catch (JSONException e) { e.printStackTrace(); } } JSONObject typeJson = new JSONObject(); TranslationType translationType = TranslationType.get(typeId); typeJson.put("id", typeId); if (translationType != null) { typeJson.put("name", translationType.getName()); } else { typeJson.put("name", ""); } manifest.put("type", typeJson); } // update project // NOTE: this was actually in v3 but we missed it so we need to catch it here if (manifest.has("project_id")) { String projectId = manifest.getString("project_id"); manifest.remove("project_id"); JSONObject projectJson = new JSONObject(); projectJson.put("id", projectId); projectJson.put("name", projectId.toUpperCase()); // we don't know the full name at this point manifest.put("project", projectJson); } // update resource if (manifest.getJSONObject("type").getString("id").equals("text")) { if (manifest.has("resource_id")) { String resourceId = manifest.getString("resource_id"); manifest.remove("resource_id"); JSONObject resourceJson = new JSONObject(); // TRICKY: supported resource id's (or now types) are "reg", "obs", "ulb", and "udb". if (resourceId.equals("ulb")) { resourceJson.put("name", "Unlocked Literal Bible"); } else if (resourceId.equals("udb")) { resourceJson.put("name", "Unlocked Dynamic Bible"); } else if (resourceId.equals("obs")) { resourceJson.put("name", "Open Bible Stories"); } else { // everything else changes to "reg" resourceId = "reg"; resourceJson.put("name", "Regular"); } resourceJson.put("id", resourceId); manifest.put("resource", resourceJson); } else if (!manifest.has("resource")) { // add missing resource JSONObject resourceJson = new JSONObject(); JSONObject projectJson = manifest.getJSONObject("project"); JSONObject typeJson = manifest.getJSONObject("type"); if (typeJson.getString("id").equals("text")) { String resourceId = projectJson.getString("id"); if (resourceId.equals("obs")) { resourceJson.put("id", "obs"); resourceJson.put("name", "Open Bible Stories"); } else { // everything else changes to reg resourceJson.put("id", "reg"); resourceJson.put("name", "Regular"); } manifest.put("resource", resourceJson); } } } else { // non-text translation types do not have resources manifest.remove("resource_id"); manifest.remove("resource"); } // update source translations if (manifest.has("source_translations")) { JSONObject oldSourceTranslationsJson = manifest.getJSONObject("source_translations"); manifest.remove("source_translations"); JSONArray newSourceTranslationsJson = new JSONArray(); Iterator<String> keys = oldSourceTranslationsJson.keys(); while (keys.hasNext()) { try { String key = keys.next(); JSONObject oldObj = oldSourceTranslationsJson.getJSONObject(key); JSONObject sourceTranslation = new JSONObject(); String[] parts = key.split("-", 2); if (parts.length == 2) { String languageResourceId = parts[1]; String[] pieces = languageResourceId.split("-"); if (pieces.length > 0) { String resId = pieces[pieces.length - 1]; sourceTranslation.put("resource_id", resId); sourceTranslation.put("language_id", languageResourceId.substring(0, languageResourceId.length() - resId.length() - 1)); sourceTranslation.put("checking_level", oldObj.getString("checking_level")); sourceTranslation.put("date_modified", oldObj.getInt("date_modified")); sourceTranslation.put("version", oldObj.getString("version")); newSourceTranslationsJson.put(sourceTranslation); } } } catch (Exception e) { // don't fail migration just because a source translation was invalid e.printStackTrace(); } } manifest.put("source_translations", newSourceTranslationsJson); } // update parent draft if (manifest.has("parent_draft_resource_id")) { JSONObject draftStatus = new JSONObject(); draftStatus.put("resource_id", manifest.getString("parent_draft_resource_id")); draftStatus.put("checking_entity", ""); draftStatus.put("checking_level", ""); draftStatus.put("comments", "The parent draft is unknown"); draftStatus.put("contributors", ""); draftStatus.put("publish_date", ""); draftStatus.put("source_text", ""); draftStatus.put("source_text_version", ""); draftStatus.put("version", ""); manifest.put("parent_draft", draftStatus); manifest.remove("parent_draft_resource_id"); } // update finished chunks if (manifest.has("finished_frames")) { JSONArray finishedFrames = manifest.getJSONArray("finished_frames"); manifest.remove("finished_frames"); manifest.put("finished_chunks", finishedFrames); } // remove finished titles if (manifest.has("finished_titles")) { JSONArray finishedChunks = manifest.getJSONArray("finished_chunks"); JSONArray finishedTitles = manifest.getJSONArray("finished_titles"); manifest.remove("finished_titles"); for (int i = 0; i < finishedTitles.length(); i++) { String chapterId = finishedTitles.getString(i); finishedChunks.put(chapterId + "-title"); } manifest.put("finished_chunks", finishedChunks); } // remove finished references if (manifest.has("finished_references")) { JSONArray finishedChunks = manifest.getJSONArray("finished_chunks"); JSONArray finishedReferences = manifest.getJSONArray("finished_references"); manifest.remove("finished_references"); for (int i = 0; i < finishedReferences.length(); i++) { String chapterId = finishedReferences.getString(i); finishedChunks.put(chapterId + "-reference"); } manifest.put("finished_chunks", finishedChunks); } // remove project components // NOTE: this was never quite official, just in android if (manifest.has("finished_project_components")) { JSONArray finishedChunks = manifest.getJSONArray("finished_chunks"); JSONArray finishedProjectComponents = manifest.getJSONArray("finished_project_components"); manifest.remove("finished_project_components"); for (int i = 0; i < finishedProjectComponents.length(); i++) { String component = finishedProjectComponents.getString(i); finishedChunks.put("00-" + component); } manifest.put("finished_chunks", finishedChunks); } // add format if (!Manifest.valueExists(manifest, "format") || manifest.getString("format").equals("usx") || manifest.getString("format").equals("default")) { String typeId = manifest.getJSONObject("type").getString("id"); String projectId = manifest.getJSONObject("project").getString("id"); if (!typeId.equals("text") || projectId.equals("obs")) { manifest.put("format", "markdown"); } else { manifest.put("format", "usfm"); } } // update where project title is saved. File oldProjectTitle = new File(path, "title.txt"); File newProjectTitle = new File(path, "00/title.txt"); if (oldProjectTitle.exists()) { newProjectTitle.getParentFile().mkdirs(); FileUtils.moveFile(oldProjectTitle, newProjectTitle); } // update package version manifest.put("package_version", 5); FileUtils.write(manifestFile, manifest.toString(2)); // migrate usx to usfm String format = manifest.getString("format"); // TRICKY: we just added the new format field, anything marked as usfm may have residual usx and needs to be migrated if (format.equals("usfm")) { File[] chapterDirs = path.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.isDirectory() && !pathname.getName().equals(".git"); } }); for (File cDir : chapterDirs) { File[] chunkFiles = cDir.listFiles(); for (File chunkFile : chunkFiles) { try { String usx = FileUtils.readFileToString(chunkFile); String usfm = USXtoUSFMConverter.doConversion(usx).toString(); FileUtils.writeStringToFile(chunkFile, usfm); } catch (IOException e) { // this conversion may have failed but don't stop the rest of the migration e.printStackTrace(); } } } } return path; }
From source file:com.silverpeas.util.FileUtil.java
/** * Moves the specified source file to the specified destination. If the destination exists, it is * then replaced by the source; if the destination is a directory, then it is deleted with all of * its contain.//ww w . j a v a2 s. c om * * @param source the file to move. * @param destination the destination file of the move. * @throws IOException if the source or the destination is invalid or if an error occurs while * moving the file. */ public static void moveFile(File source, File destination) throws IOException { if (destination.exists()) { FileUtils.forceDelete(destination); } FileUtils.moveFile(source, destination); }
From source file:aurelienribon.gdxsetupui.ProjectSetup.java
private void move(File base, String path1, String path2) throws IOException { if (path1.equals(path2)) return;//from w w w . j a v a 2 s. c o m File file1 = new File(base, FilenameUtils.normalize(path1)); File file2 = new File(base, FilenameUtils.normalize(path2)); FileUtils.deleteQuietly(file2); if (file1.isDirectory()) FileUtils.moveDirectory(file1, file2); else FileUtils.moveFile(file1, file2); }
From source file:jeplus.RadianceWinTools.java
/** * Call DaySim gen_dc to run the simulation * @param config Radiance Configuration/* ww w. j a va 2 s. c o m*/ * @param WorkDir The working directory where the input files are stored and the output files to be generated * @param model * @param in * @param out * @param err * @param process * @return the result code represents the state of execution steps. >=0 means successful */ public static int runGen_DC(RadianceConfig config, String WorkDir, String model, String in, String out, String err, ProcessWrapper process) { int ExitValue = -99; // Manipulate header file HashMap<String, String> props = new HashMap<>(); // props.put("project_name", ""); props.put("project_directory", "./"); props.put("bin_directory", config.getResolvedDaySimBinDir()); props.put("tmp_directory", "./"); props.put("Template_File", config.getResolvedDaySimBinDir() + "../template/"); props.put("sensor_file", in); try { FileUtils.moveFile(new File(WorkDir + File.separator + model), new File(WorkDir + File.separator + model + ".ori")); } catch (IOException ex) { logger.error("Error renaming header file to " + WorkDir + File.separator + model + ".ori", ex); } DaySimModel.updateHeaderFile(WorkDir + File.separator + model + ".ori", WorkDir + File.separator + model, props); // Run command try { StringBuilder buf = new StringBuilder(config.getResolvedDaySimBinDir()); buf.append(File.separator).append("gen_dc"); List<String> command = new ArrayList<>(); command.add(buf.toString()); command.add(model); ProcessBuilder builder = new ProcessBuilder(command); builder.directory(new File(WorkDir)); builder.environment().put("RAYPATH", "." + File.pathSeparator + config.getResolvedDaySimLibDir()); builder.redirectOutput(new File(WorkDir + File.separator + out)); if (err == null || out.equals(err)) { builder.redirectErrorStream(true); } else { builder.redirectError(new File(WorkDir + File.separator + err)); } if (in != null) { builder.redirectInput(new File(WorkDir + File.separator + in)); } Process proc = builder.start(); if (process != null) { process.setWrappedProc(proc); } ExitValue = proc.waitFor(); } catch (IOException | InterruptedException ex) { logger.error("Error occoured when executing DaySim gen_dc", ex); } // Return Radiance exit value return ExitValue; }
From source file:com.ning.metrics.serialization.writer.DiskSpoolEventWriter.java
private File renameFile(final File srcFile, final File destDir) { final File destinationOutputFile = new File(destDir, srcFile.getName()); try {/*from w ww .ja va 2 s .c o m*/ FileUtils.moveFile(srcFile, destinationOutputFile); log.debug("Moved [{}] to [{}]", srcFile, destDir); } catch (IOException e) { log.warn(String.format("Error renaming spool file %s to %s: %s", srcFile, destinationOutputFile, e)); } return destinationOutputFile; }
From source file:it.feio.android.omninotes.utils.StorageManager.java
/** * @param mContext// w ww . j a va 2 s . c o m * @param uri * @return */ public static Attachment createAttachmentFromUri(Context mContext, Uri uri, boolean moveSource) { String name = FileHelper.getNameFromUri(mContext, uri); String extension = FileHelper.getFileExtension(FileHelper.getNameFromUri(mContext, uri)) .toLowerCase(Locale.getDefault()); File f = null; if (moveSource) { f = createNewAttachmentFile(mContext, extension); try { FileUtils.moveFile(new File(uri.getPath()), f); } catch (IOException e) { Log.e(Constants.TAG, "Can't move file " + uri.getPath()); } } else { f = StorageManager.createExternalStoragePrivateFile(mContext, uri, extension); } Attachment mAttachment = null; if (f != null) { mAttachment = new Attachment(Uri.fromFile(f), StorageManager.getMimeTypeInternal(mContext, uri)); mAttachment.setName(name); mAttachment.setSize(f.length()); } return mAttachment; }
From source file:de.pksoftware.springstrap.fs.service.LocalFileSystemService.java
@Override public void moveFile(ItemVisibility visibility, FileSystemBucket bucket, IFileSystemPath src, IFileSystemPath dest) throws NoSuchFileException, NotAFileException, FSIOException { File srcFile = getItem(visibility, bucket, src); if (!srcFile.exists()) { throw new NoSuchFileException(bucket, src); }/* w ww.j a va 2 s. com*/ if (srcFile.isDirectory()) { throw new NotAFileException(bucket, src); } File destFile = getItem(visibility, bucket, dest); if (destFile.exists() && destFile.isDirectory()) { throw new NotAFileException(bucket, dest); } try { FileUtils.moveFile(srcFile, destFile); } catch (IOException e) { logger.error("Could not move file from {} to {}", srcFile, destFile); throw new FSIOException(bucket, src, "moveFile", e); } }